Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
InviteCodeKt 是從零重寫的 Kotlin Minecraft 邀請與推薦獎勵插件。目標是以單一可安裝 JAR 支援 Spigot 與 Paper 1.8.8 到最新已測試版本,並透過隔離的 adapter 載入新版能力。

> [!IMPORTANT]
> 這個 repository 目前是 `0.1.0-SNAPSHOT`。平台無關的 Invitation 核心狀態機已實作;qualification、storage、reward 與 Minecraft 平台工作流程尚未完成串接。
> 這個 repository 目前是 `0.1.0-SNAPSHOT`。平台無關的 Invitation 核心狀態機,以及 Invite Code 的產生、驗證、顏色資訊與 rotation lifecycle 已實作;qualification、storage、reward 與 Minecraft 平台工作流程尚未完成串接。

## 專案目標

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,31 @@ class InviteCode private constructor(val normalized: String) {
val isColorInviteCode: Boolean
get() = COLOR_CODE.matches(normalized)

val color: InviteCodeColor?
get() = if (isColorInviteCode) {
InviteCodeColor.fromRgb(normalized.toInt(radix = 16))
} else {
null
}

fun displayValue(): String = normalized

override fun equals(other: Any?): Boolean =
this === other || (other is InviteCode && normalized == other.normalized)

override fun hashCode(): Int = normalized.hashCode()

override fun toString(): String = normalized

companion object {
private val SEPARATORS = Regex("[-\\s]")
private val VALID_CODE = Regex("[A-Z0-9]{4,32}")
private val COLOR_CODE = Regex("[0-9A-F]{6}")

fun parse(raw: String): InviteCode {
val normalized = raw.trim().uppercase().replace(SEPARATORS, "")
require(VALID_CODE.matches(normalized)) {
"Invite Code must contain 4 to 32 ASCII letters or digits."
}
fun parse(
raw: String,
format: InviteCodeFormat = InviteCodeFormats.alphanumeric,
): InviteCode {
val normalized = format.normalize(raw)
format.requireValid(normalized)
return InviteCode(normalized)
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package io.github.command1264.invitecode.core

data class InviteCodeColor(
val red: Int,
val green: Int,
val blue: Int,
) {
init {
require(red in 0..255 && green in 0..255 && blue in 0..255) {
"RGB channels must be between 0 and 255."
}
}

val rgb: Int = (red shl 16) or (green shl 8) or blue

fun nearestLegacyColor(): LegacyInviteCodeColor =
LegacyInviteCodeColor.entries.minByOrNull { legacy ->
squaredDistanceTo(legacy.color)
} ?: error("At least one legacy color must be defined.")

private fun squaredDistanceTo(other: InviteCodeColor): Int {
val redDelta = red - other.red
val greenDelta = green - other.green
val blueDelta = blue - other.blue
return redDelta * redDelta + greenDelta * greenDelta + blueDelta * blueDelta
}

companion object {
fun fromRgb(rgb: Int): InviteCodeColor {
require(rgb in 0x000000..0xFFFFFF) { "RGB value must be between 0x000000 and 0xFFFFFF." }
return InviteCodeColor(
red = rgb shr 16 and 0xFF,
green = rgb shr 8 and 0xFF,
blue = rgb and 0xFF,
)
}
}
}

enum class LegacyInviteCodeColor(
val code: Char,
val color: InviteCodeColor,
) {
BLACK('0', InviteCodeColor.fromRgb(0x000000)),
DARK_BLUE('1', InviteCodeColor.fromRgb(0x0000AA)),
DARK_GREEN('2', InviteCodeColor.fromRgb(0x00AA00)),
DARK_AQUA('3', InviteCodeColor.fromRgb(0x00AAAA)),
DARK_RED('4', InviteCodeColor.fromRgb(0xAA0000)),
DARK_PURPLE('5', InviteCodeColor.fromRgb(0xAA00AA)),
GOLD('6', InviteCodeColor.fromRgb(0xFFAA00)),
GRAY('7', InviteCodeColor.fromRgb(0xAAAAAA)),
DARK_GRAY('8', InviteCodeColor.fromRgb(0x555555)),
BLUE('9', InviteCodeColor.fromRgb(0x5555FF)),
GREEN('a', InviteCodeColor.fromRgb(0x55FF55)),
AQUA('b', InviteCodeColor.fromRgb(0x55FFFF)),
RED('c', InviteCodeColor.fromRgb(0xFF5555)),
LIGHT_PURPLE('d', InviteCodeColor.fromRgb(0xFF55FF)),
YELLOW('e', InviteCodeColor.fromRgb(0xFFFF55)),
WHITE('f', InviteCodeColor.fromRgb(0xFFFFFF)),
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package io.github.command1264.invitecode.core

interface InviteCodeFormat {
fun normalize(raw: String): String

fun requireValid(normalized: String)
}

object InviteCodeFormats {
private val separators = Regex("[-\\s]")

val alphanumeric: InviteCodeFormat = regexFormat(
pattern = Regex("[A-Z0-9]{4,32}"),
errorMessage = "Invite Code must contain 4 to 32 ASCII letters or digits.",
)

val colorHex: InviteCodeFormat = regexFormat(
pattern = Regex("[0-9A-F]{6}"),
errorMessage = "A Color Invite Code must contain exactly six hexadecimal characters.",
)

fun crockfordBase32(length: Int): InviteCodeFormat {
require(length in 4..32) { "Crockford Base32 length must be between 4 and 32 characters." }
val pattern = Regex("[0-9A-HJKMNP-TV-Z]{$length}")
return object : InviteCodeFormat {
override fun normalize(raw: String): String = commonNormalize(raw)
.replace('O', '0')
.replace('I', '1')
.replace('L', '1')

override fun requireValid(normalized: String) {
require(pattern.matches(normalized)) {
"A Crockford Base32 Invite Code must contain exactly $length valid characters."
}
}
}
}

fun custom(
pattern: Regex,
description: String,
): InviteCodeFormat {
require(description.isNotBlank()) { "Custom Invite Code description must not be blank." }
return regexFormat(
pattern = pattern,
errorMessage = "$description is invalid.",
)
}

private fun regexFormat(
pattern: Regex,
errorMessage: String,
): InviteCodeFormat = object : InviteCodeFormat {
override fun normalize(raw: String): String = commonNormalize(raw)

override fun requireValid(normalized: String) {
require(pattern.matches(normalized)) { errorMessage }
}
}

internal fun commonNormalize(raw: String): String =
raw.trim().uppercase().replace(separators, "")
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package io.github.command1264.invitecode.core

import java.security.SecureRandom

fun interface InviteCodeGenerator {
fun generate(): InviteCode
}

fun interface RandomBytes {
fun nextBytes(destination: ByteArray)
}

class ColorInviteCodeGenerator(
private val randomBytes: RandomBytes = SecureRandomBytes(),
) : InviteCodeGenerator {
override fun generate(): InviteCode {
val bytes = ByteArray(COLOR_BYTE_COUNT)
randomBytes.nextBytes(bytes)
val normalized = buildString(COLOR_CODE_LENGTH) {
bytes.forEach { byte ->
val unsigned = byte.toInt() and 0xFF
append(HEX_DIGITS[unsigned shr 4])
append(HEX_DIGITS[unsigned and 0x0F])
}
}
return InviteCode.parse(normalized, InviteCodeFormats.colorHex)
}

private companion object {
const val COLOR_BYTE_COUNT = 3
const val COLOR_CODE_LENGTH = 6
const val HEX_DIGITS = "0123456789ABCDEF"
}
}

private class SecureRandomBytes(
private val secureRandom: SecureRandom = SecureRandom(),
) : RandomBytes {
override fun nextBytes(destination: ByteArray) {
secureRandom.nextBytes(destination)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
package io.github.command1264.invitecode.core

import java.time.Instant
import java.util.UUID

data class ActiveInviteCode(
val inviterId: UUID,
val code: InviteCode,
val activatedAt: Instant,
)

data class RetiredInviteCode(
val inviterId: UUID,
val code: InviteCode,
val activatedAt: Instant,
val retiredAt: Instant,
) {
init {
require(!retiredAt.isBefore(activatedAt)) {
"An Invite Code cannot be retired before it was activated."
}
}
}

data class InviteCodeRotation(
val previous: RetiredInviteCode,
val current: ActiveInviteCode,
)

/**
* Runs Invite Code allocation operations atomically. Implementations must prevent two overlapping
* operations from activating the same normalized Invite Code, reusing a retired Invite Code, or
* activating more than one Invite Code for an Inviter.
*/
interface InviteCodeRegistry {
fun <T> atomically(operation: (InviteCodeTransaction) -> T): T
}

interface InviteCodeTransaction {
fun activeCode(inviterId: UUID): ActiveInviteCode?

fun isReserved(code: InviteCode): Boolean

fun activate(activeInviteCode: ActiveInviteCode)

fun replace(
previous: RetiredInviteCode,
current: ActiveInviteCode,
)
}

class InviteCodeCollisionException(
val attempts: Int,
) : IllegalStateException(
"Could not allocate a unique Invite Code after $attempts attempts; " +
"increase the Invite Code namespace or inspect the Invite Code registry.",
)

class ActiveInviteCodeNotFoundException(
inviterId: UUID,
) : IllegalStateException("Inviter $inviterId does not have an active Invite Code to rotate.")

class InviteCodeLifecycleService(
private val registry: InviteCodeRegistry,
private val generator: InviteCodeGenerator,
private val maxCollisionAttempts: Int,
) {
init {
require(maxCollisionAttempts > 0) { "Maximum collision attempts must be positive." }
}

fun assign(
inviterId: UUID,
activatedAt: Instant,
): ActiveInviteCode = retryCollisions {
tryAssign(inviterId, activatedAt)
}

fun rotate(
inviterId: UUID,
rotatedAt: Instant,
): InviteCodeRotation = retryCollisions {
tryRotate(inviterId, rotatedAt)
}

private fun tryAssign(
inviterId: UUID,
activatedAt: Instant,
): CollisionAttempt<ActiveInviteCode> = registry.atomically { transaction ->
transaction.activeCode(inviterId)?.let { existing ->
return@atomically CollisionAttempt.Success(existing)
}

val candidate = generator.generate()
if (transaction.isReserved(candidate)) {
return@atomically CollisionAttempt.Collision
}

val activeInviteCode = ActiveInviteCode(inviterId, candidate, activatedAt)
transaction.activate(activeInviteCode)
CollisionAttempt.Success(activeInviteCode)
}

private fun tryRotate(
inviterId: UUID,
rotatedAt: Instant,
): CollisionAttempt<InviteCodeRotation> = registry.atomically { transaction ->
val existing = transaction.activeCode(inviterId)
?: throw ActiveInviteCodeNotFoundException(inviterId)
val candidate = generator.generate()
if (transaction.isReserved(candidate)) {
return@atomically CollisionAttempt.Collision
}

val previous = RetiredInviteCode(
inviterId = existing.inviterId,
code = existing.code,
activatedAt = existing.activatedAt,
retiredAt = rotatedAt,
)
val current = ActiveInviteCode(
inviterId = inviterId,
code = candidate,
activatedAt = rotatedAt,
)
transaction.replace(previous, current)
CollisionAttempt.Success(InviteCodeRotation(previous, current))
}

private inline fun <T> retryCollisions(attempt: () -> CollisionAttempt<T>): T {
repeat(maxCollisionAttempts) {
when (val result = attempt()) {
is CollisionAttempt.Success -> return result.value
CollisionAttempt.Collision -> Unit
}
}
throw InviteCodeCollisionException(maxCollisionAttempts)
}
}

private sealed class CollisionAttempt<out T> {
data class Success<T>(val value: T) : CollisionAttempt<T>()

object Collision : CollisionAttempt<Nothing>()
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package io.github.command1264.invitecode.core

import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test

class ColorInviteCodeGeneratorTest {
@Test
fun `generator turns three random bytes into an uppercase color invite code`() {
val generator = ColorInviteCodeGenerator(
randomBytes = RandomBytes { destination ->
byteArrayOf(0x00, 0x0F, 0xFF.toByte()).copyInto(destination)
},
)

val code = generator.generate()

assertEquals("000FFF", code.normalized)
assertTrue(code.isColorInviteCode)
}
}
Loading
Loading