From adc194297b34c7ddc78b9697b7c9e4e29a20b6b1 Mon Sep 17 00:00:00 2001 From: Command1264 Date: Mon, 21 Sep 2026 18:07:36 +0800 Subject: [PATCH 1/3] feat: implement invite code lifecycle (#4) --- README.md | 2 +- .../command1264/invitecode/core/InviteCode.kt | 27 ++- .../invitecode/core/InviteCodeColor.kt | 60 +++++++ .../invitecode/core/InviteCodeFormat.kt | 63 +++++++ .../invitecode/core/InviteCodeGenerator.kt | 42 +++++ .../core/InviteCodeLifecycleService.kt | 152 ++++++++++++++++ .../core/ColorInviteCodeGeneratorTest.kt | 21 +++ .../invitecode/core/InviteCodeFormatTest.kt | 46 +++++ .../core/InviteCodeLifecycleServiceTest.kt | 167 ++++++++++++++++++ .../invitecode/core/InviteCodeTest.kt | 22 +++ 10 files changed, 594 insertions(+), 8 deletions(-) create mode 100644 invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/InviteCodeColor.kt create mode 100644 invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/InviteCodeFormat.kt create mode 100644 invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/InviteCodeGenerator.kt create mode 100644 invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/InviteCodeLifecycleService.kt create mode 100644 invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/ColorInviteCodeGeneratorTest.kt create mode 100644 invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/InviteCodeFormatTest.kt create mode 100644 invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/InviteCodeLifecycleServiceTest.kt diff --git a/README.md b/README.md index 8ef2999..ac1c974 100644 --- a/README.md +++ b/README.md @@ -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 平台工作流程尚未完成串接。 ## 專案目標 diff --git a/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/InviteCode.kt b/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/InviteCode.kt index 3d24d5f..ce106cb 100644 --- a/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/InviteCode.kt +++ b/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/InviteCode.kt @@ -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) } } diff --git a/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/InviteCodeColor.kt b/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/InviteCodeColor.kt new file mode 100644 index 0000000..d26b0c9 --- /dev/null +++ b/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/InviteCodeColor.kt @@ -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)), +} diff --git a/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/InviteCodeFormat.kt b/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/InviteCodeFormat.kt new file mode 100644 index 0000000..4770342 --- /dev/null +++ b/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/InviteCodeFormat.kt @@ -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, "") +} diff --git a/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/InviteCodeGenerator.kt b/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/InviteCodeGenerator.kt new file mode 100644 index 0000000..4a1d8c6 --- /dev/null +++ b/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/InviteCodeGenerator.kt @@ -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) + } +} diff --git a/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/InviteCodeLifecycleService.kt b/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/InviteCodeLifecycleService.kt new file mode 100644 index 0000000..5211a96 --- /dev/null +++ b/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/InviteCodeLifecycleService.kt @@ -0,0 +1,152 @@ +package io.github.command1264.invitecode.core + +import java.time.Instant +import java.util.UUID + +data class ActiveInviteCode( + val ownerId: UUID, + val code: InviteCode, + val activatedAt: Instant, +) + +data class RetiredInviteCode( + val ownerId: 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 code or more than one active code for an owner. + */ +interface InviteCodeRegistry { + fun atomically(operation: (InviteCodeTransaction) -> T): T +} + +interface InviteCodeTransaction { + fun activeCode(ownerId: UUID): ActiveInviteCode? + + fun activeOwner(code: InviteCode): UUID? + + 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 code space or inspect the active code registry.", +) + +class ActiveInviteCodeNotFoundException( + ownerId: UUID, +) : IllegalStateException("Player $ownerId 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( + ownerId: UUID, + activatedAt: Instant, + ): ActiveInviteCode { + repeat(maxCollisionAttempts) { + when (val attempt = tryAssign(ownerId, activatedAt)) { + is AssignmentAttempt.Assigned -> return attempt.activeInviteCode + AssignmentAttempt.Collision -> Unit + } + } + throw InviteCodeCollisionException(maxCollisionAttempts) + } + + fun rotate( + ownerId: UUID, + rotatedAt: Instant, + ): InviteCodeRotation { + repeat(maxCollisionAttempts) { + when (val attempt = tryRotate(ownerId, rotatedAt)) { + is RotationAttempt.Rotated -> return attempt.rotation + RotationAttempt.Collision -> Unit + } + } + throw InviteCodeCollisionException(maxCollisionAttempts) + } + + private fun tryAssign( + ownerId: UUID, + activatedAt: Instant, + ): AssignmentAttempt = registry.atomically { transaction -> + transaction.activeCode(ownerId)?.let { existing -> + return@atomically AssignmentAttempt.Assigned(existing) + } + + val candidate = generator.generate() + if (transaction.activeOwner(candidate) != null) { + return@atomically AssignmentAttempt.Collision + } + + val activeInviteCode = ActiveInviteCode(ownerId, candidate, activatedAt) + transaction.activate(activeInviteCode) + AssignmentAttempt.Assigned(activeInviteCode) + } + + private fun tryRotate( + ownerId: UUID, + rotatedAt: Instant, + ): RotationAttempt = registry.atomically { transaction -> + val existing = transaction.activeCode(ownerId) + ?: throw ActiveInviteCodeNotFoundException(ownerId) + val candidate = generator.generate() + if (candidate == existing.code || transaction.activeOwner(candidate) != null) { + return@atomically RotationAttempt.Collision + } + + val previous = RetiredInviteCode( + ownerId = existing.ownerId, + code = existing.code, + activatedAt = existing.activatedAt, + retiredAt = rotatedAt, + ) + val current = ActiveInviteCode( + ownerId = ownerId, + code = candidate, + activatedAt = rotatedAt, + ) + transaction.replace(previous, current) + RotationAttempt.Rotated(InviteCodeRotation(previous, current)) + } +} + +private sealed class AssignmentAttempt { + data class Assigned(val activeInviteCode: ActiveInviteCode) : AssignmentAttempt() + + object Collision : AssignmentAttempt() +} + +private sealed class RotationAttempt { + data class Rotated(val rotation: InviteCodeRotation) : RotationAttempt() + + object Collision : RotationAttempt() +} diff --git a/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/ColorInviteCodeGeneratorTest.kt b/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/ColorInviteCodeGeneratorTest.kt new file mode 100644 index 0000000..0579948 --- /dev/null +++ b/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/ColorInviteCodeGeneratorTest.kt @@ -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) + } +} diff --git a/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/InviteCodeFormatTest.kt b/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/InviteCodeFormatTest.kt new file mode 100644 index 0000000..739e09a --- /dev/null +++ b/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/InviteCodeFormatTest.kt @@ -0,0 +1,46 @@ +package io.github.command1264.invitecode.core + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertThrows + +class InviteCodeFormatTest { + @Test + fun `color format accepts exactly six hexadecimal characters`() { + assertEquals( + "A25981", + InviteCode.parse("a2-59-81", InviteCodeFormats.colorHex).normalized, + ) + + assertThrows { + InviteCode.parse("A2598", InviteCodeFormats.colorHex) + } + assertThrows { + InviteCode.parse("A2598G", InviteCodeFormats.colorHex) + } + } + + @Test + fun `Crockford Base32 format canonicalizes aliases and rejects excluded letters`() { + val format = InviteCodeFormats.crockfordBase32(length = 6) + + assertEquals("0111Z2", InviteCode.parse("o1-il-z2", format).normalized) + assertThrows { + InviteCode.parse("12U456", format) + } + } + + @Test + fun `custom format uses the shared normalization and validation contract`() { + val format = InviteCodeFormats.custom( + pattern = Regex("VIP[0-9]{4}"), + description = "VIP Invite Code", + ) + + assertEquals("VIP1234", InviteCode.parse(" vip-1234 ", format).normalized) + val error = assertThrows { + InviteCode.parse("MEMBER1234", format) + } + assertEquals("VIP Invite Code is invalid.", error.message) + } +} diff --git a/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/InviteCodeLifecycleServiceTest.kt b/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/InviteCodeLifecycleServiceTest.kt new file mode 100644 index 0000000..c27fd5d --- /dev/null +++ b/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/InviteCodeLifecycleServiceTest.kt @@ -0,0 +1,167 @@ +package io.github.command1264.invitecode.core + +import java.time.Instant +import java.util.ArrayDeque +import java.util.UUID +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertThrows + +class InviteCodeLifecycleServiceTest { + @Test + fun `assignment retries a collision and activates the next candidate`() { + val occupiedOwner = UUID.randomUUID() + val newOwner = UUID.randomUUID() + val occupiedCode = InviteCode.parse("AAAAAA", InviteCodeFormats.colorHex) + val availableCode = InviteCode.parse("BBBBBB", InviteCodeFormats.colorHex) + val registry = InMemoryInviteCodeRegistry( + ActiveInviteCode(occupiedOwner, occupiedCode, Instant.EPOCH), + ) + val service = InviteCodeLifecycleService( + registry = registry, + generator = SequenceInviteCodeGenerator(occupiedCode, availableCode), + maxCollisionAttempts = 3, + ) + + val assigned = service.assign(newOwner, Instant.parse("2026-09-21T02:00:00Z")) + + assertEquals(availableCode, assigned.code) + assertEquals(newOwner, registry.resolveActiveOwner(availableCode)) + assertEquals(occupiedOwner, registry.resolveActiveOwner(occupiedCode)) + } + + @Test + fun `rotation retires the old code and activates a new code for the same owner`() { + val ownerId = UUID.randomUUID() + val oldCode = InviteCode.parse("A25981", InviteCodeFormats.colorHex) + val newCode = InviteCode.parse("FFAA00", InviteCodeFormats.colorHex) + val activatedAt = Instant.parse("2026-09-01T00:00:00Z") + val rotatedAt = Instant.parse("2026-09-21T02:30:00Z") + val registry = InMemoryInviteCodeRegistry( + ActiveInviteCode(ownerId, oldCode, activatedAt), + ) + val service = InviteCodeLifecycleService( + registry = registry, + generator = SequenceInviteCodeGenerator(newCode), + maxCollisionAttempts = 3, + ) + + val rotation = service.rotate(ownerId, rotatedAt) + + assertEquals(oldCode, rotation.previous.code) + assertEquals(rotatedAt, rotation.previous.retiredAt) + assertEquals(newCode, rotation.current.code) + assertEquals(null, registry.resolveActiveOwner(oldCode)) + assertEquals(ownerId, registry.resolveActiveOwner(newCode)) + } + + @Test + fun `assignment returns the existing active code without generating another candidate`() { + val ownerId = UUID.randomUUID() + val existing = ActiveInviteCode( + ownerId = ownerId, + code = InviteCode.parse("A25981", InviteCodeFormats.colorHex), + activatedAt = Instant.EPOCH, + ) + val service = InviteCodeLifecycleService( + registry = InMemoryInviteCodeRegistry(existing), + generator = SequenceInviteCodeGenerator(), + maxCollisionAttempts = 3, + ) + + assertEquals(existing, service.assign(ownerId, Instant.parse("2026-09-21T03:00:00Z"))) + } + + @Test + fun `assignment reports an actionable error after the collision limit`() { + val occupiedCode = InviteCode.parse("AAAAAA", InviteCodeFormats.colorHex) + val registry = InMemoryInviteCodeRegistry( + ActiveInviteCode(UUID.randomUUID(), occupiedCode, Instant.EPOCH), + ) + val service = InviteCodeLifecycleService( + registry = registry, + generator = SequenceInviteCodeGenerator(occupiedCode, occupiedCode), + maxCollisionAttempts = 2, + ) + + val error = assertThrows { + service.assign(UUID.randomUUID(), Instant.parse("2026-09-21T03:00:00Z")) + } + + assertEquals(2, error.attempts) + assertEquals( + "Could not allocate a unique Invite Code after 2 attempts; " + + "increase the code space or inspect the active code registry.", + error.message, + ) + } + + @Test + fun `rotation retries candidates that are current or owned by another player`() { + val ownerId = UUID.randomUUID() + val otherOwnerId = UUID.randomUUID() + val currentCode = InviteCode.parse("AAAAAA", InviteCodeFormats.colorHex) + val occupiedCode = InviteCode.parse("BBBBBB", InviteCodeFormats.colorHex) + val replacementCode = InviteCode.parse("CCCCCC", InviteCodeFormats.colorHex) + val registry = InMemoryInviteCodeRegistry( + ActiveInviteCode(ownerId, currentCode, Instant.EPOCH), + ActiveInviteCode(otherOwnerId, occupiedCode, Instant.EPOCH), + ) + val service = InviteCodeLifecycleService( + registry = registry, + generator = SequenceInviteCodeGenerator(currentCode, occupiedCode, replacementCode), + maxCollisionAttempts = 3, + ) + + val rotation = service.rotate(ownerId, Instant.parse("2026-09-21T03:00:00Z")) + + assertEquals(replacementCode, rotation.current.code) + assertEquals(otherOwnerId, registry.resolveActiveOwner(occupiedCode)) + } +} + +private class SequenceInviteCodeGenerator( + vararg codes: InviteCode, +) : InviteCodeGenerator { + private val remaining = ArrayDeque(codes.toList()) + + override fun generate(): InviteCode = remaining.removeFirst() +} + +private class InMemoryInviteCodeRegistry( + vararg initialCodes: ActiveInviteCode, +) : InviteCodeRegistry { + private val byOwner = initialCodes.associateByTo(mutableMapOf()) { it.ownerId } + private val ownerByCode = initialCodes.associateTo(mutableMapOf()) { it.code to it.ownerId } + + override fun atomically(operation: (InviteCodeTransaction) -> T): T = synchronized(this) { + operation(object : InviteCodeTransaction { + override fun activeCode(ownerId: UUID): ActiveInviteCode? = byOwner[ownerId] + + override fun activeOwner(code: InviteCode): UUID? = ownerByCode[code] + + override fun activate(activeInviteCode: ActiveInviteCode) { + check(byOwner[activeInviteCode.ownerId] == null) + check(ownerByCode[activeInviteCode.code] == null) + byOwner[activeInviteCode.ownerId] = activeInviteCode + ownerByCode[activeInviteCode.code] = activeInviteCode.ownerId + } + + override fun replace( + previous: RetiredInviteCode, + current: ActiveInviteCode, + ) { + check(byOwner[previous.ownerId]?.code == previous.code) + check(ownerByCode[previous.code] == previous.ownerId) + check(ownerByCode[current.code] == null) + byOwner[current.ownerId] = current + ownerByCode.remove(previous.code) + ownerByCode[current.code] = current.ownerId + } + }) + } + + fun resolveActiveOwner(code: InviteCode): UUID? = synchronized(this) { + ownerByCode[code] + } +} diff --git a/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/InviteCodeTest.kt b/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/InviteCodeTest.kt index 5f9fe41..19bb635 100644 --- a/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/InviteCodeTest.kt +++ b/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/InviteCodeTest.kt @@ -1,6 +1,7 @@ package io.github.command1264.invitecode.core import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertNull import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows @@ -14,10 +15,31 @@ class InviteCodeTest { assertTrue(code.isColorInviteCode) } + @Test + fun `codes compare by their normalized representation`() { + assertEquals( + InviteCode.parse("a2-59-81"), + InviteCode.parse("A25981"), + ) + } + @Test fun `punctuation other than display separator is rejected`() { assertThrows { InviteCode.parse("ABC/123") } } + + @Test + fun `color invite code exposes RGB and nearest legacy color`() { + val color = InviteCode.parse("FEA901", InviteCodeFormats.colorHex).color + + requireNotNull(color) + assertEquals(254, color.red) + assertEquals(169, color.green) + assertEquals(1, color.blue) + assertEquals(0xFEA901, color.rgb) + assertEquals(LegacyInviteCodeColor.GOLD, color.nearestLegacyColor()) + assertNull(InviteCode.parse("VIP1234").color) + } } From 4d3bcb882a5dd40eb031e8ac1a4ca9d131fde078 Mon Sep 17 00:00:00 2001 From: Command1264 Date: Mon, 21 Sep 2026 18:13:52 +0800 Subject: [PATCH 2/3] fix: reserve retired invite codes (#4) --- .../core/InviteCodeLifecycleService.kt | 93 +++++++--------- .../core/InviteCodeLifecycleServiceTest.kt | 105 +++++++++++------- 2 files changed, 110 insertions(+), 88 deletions(-) diff --git a/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/InviteCodeLifecycleService.kt b/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/InviteCodeLifecycleService.kt index 5211a96..1a4cd34 100644 --- a/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/InviteCodeLifecycleService.kt +++ b/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/InviteCodeLifecycleService.kt @@ -4,13 +4,13 @@ import java.time.Instant import java.util.UUID data class ActiveInviteCode( - val ownerId: UUID, + val inviterId: UUID, val code: InviteCode, val activatedAt: Instant, ) data class RetiredInviteCode( - val ownerId: UUID, + val inviterId: UUID, val code: InviteCode, val activatedAt: Instant, val retiredAt: Instant, @@ -29,16 +29,17 @@ data class InviteCodeRotation( /** * Runs Invite Code allocation operations atomically. Implementations must prevent two overlapping - * operations from activating the same normalized code or more than one active code for an owner. + * operations from activating the same normalized code, reusing a retired code, or activating more + * than one code for an Inviter. */ interface InviteCodeRegistry { fun atomically(operation: (InviteCodeTransaction) -> T): T } interface InviteCodeTransaction { - fun activeCode(ownerId: UUID): ActiveInviteCode? + fun activeCode(inviterId: UUID): ActiveInviteCode? - fun activeOwner(code: InviteCode): UUID? + fun isReserved(code: InviteCode): Boolean fun activate(activeInviteCode: ActiveInviteCode) @@ -56,8 +57,8 @@ class InviteCodeCollisionException( ) class ActiveInviteCodeNotFoundException( - ownerId: UUID, -) : IllegalStateException("Player $ownerId does not have an active Invite Code to rotate.") + inviterId: UUID, +) : IllegalStateException("Inviter $inviterId does not have an active Invite Code to rotate.") class InviteCodeLifecycleService( private val registry: InviteCodeRegistry, @@ -69,84 +70,76 @@ class InviteCodeLifecycleService( } fun assign( - ownerId: UUID, + inviterId: UUID, activatedAt: Instant, - ): ActiveInviteCode { - repeat(maxCollisionAttempts) { - when (val attempt = tryAssign(ownerId, activatedAt)) { - is AssignmentAttempt.Assigned -> return attempt.activeInviteCode - AssignmentAttempt.Collision -> Unit - } - } - throw InviteCodeCollisionException(maxCollisionAttempts) + ): ActiveInviteCode = retryCollisions { + tryAssign(inviterId, activatedAt) } fun rotate( - ownerId: UUID, + inviterId: UUID, rotatedAt: Instant, - ): InviteCodeRotation { - repeat(maxCollisionAttempts) { - when (val attempt = tryRotate(ownerId, rotatedAt)) { - is RotationAttempt.Rotated -> return attempt.rotation - RotationAttempt.Collision -> Unit - } - } - throw InviteCodeCollisionException(maxCollisionAttempts) + ): InviteCodeRotation = retryCollisions { + tryRotate(inviterId, rotatedAt) } private fun tryAssign( - ownerId: UUID, + inviterId: UUID, activatedAt: Instant, - ): AssignmentAttempt = registry.atomically { transaction -> - transaction.activeCode(ownerId)?.let { existing -> - return@atomically AssignmentAttempt.Assigned(existing) + ): CollisionAttempt = registry.atomically { transaction -> + transaction.activeCode(inviterId)?.let { existing -> + return@atomically CollisionAttempt.Success(existing) } val candidate = generator.generate() - if (transaction.activeOwner(candidate) != null) { - return@atomically AssignmentAttempt.Collision + if (transaction.isReserved(candidate)) { + return@atomically CollisionAttempt.Collision } - val activeInviteCode = ActiveInviteCode(ownerId, candidate, activatedAt) + val activeInviteCode = ActiveInviteCode(inviterId, candidate, activatedAt) transaction.activate(activeInviteCode) - AssignmentAttempt.Assigned(activeInviteCode) + CollisionAttempt.Success(activeInviteCode) } private fun tryRotate( - ownerId: UUID, + inviterId: UUID, rotatedAt: Instant, - ): RotationAttempt = registry.atomically { transaction -> - val existing = transaction.activeCode(ownerId) - ?: throw ActiveInviteCodeNotFoundException(ownerId) + ): CollisionAttempt = registry.atomically { transaction -> + val existing = transaction.activeCode(inviterId) + ?: throw ActiveInviteCodeNotFoundException(inviterId) val candidate = generator.generate() - if (candidate == existing.code || transaction.activeOwner(candidate) != null) { - return@atomically RotationAttempt.Collision + if (transaction.isReserved(candidate)) { + return@atomically CollisionAttempt.Collision } val previous = RetiredInviteCode( - ownerId = existing.ownerId, + inviterId = existing.inviterId, code = existing.code, activatedAt = existing.activatedAt, retiredAt = rotatedAt, ) val current = ActiveInviteCode( - ownerId = ownerId, + inviterId = inviterId, code = candidate, activatedAt = rotatedAt, ) transaction.replace(previous, current) - RotationAttempt.Rotated(InviteCodeRotation(previous, current)) + CollisionAttempt.Success(InviteCodeRotation(previous, current)) } -} - -private sealed class AssignmentAttempt { - data class Assigned(val activeInviteCode: ActiveInviteCode) : AssignmentAttempt() - object Collision : AssignmentAttempt() + private inline fun retryCollisions(attempt: () -> CollisionAttempt): T { + repeat(maxCollisionAttempts) { + when (val result = attempt()) { + is CollisionAttempt.Success -> return result.value + CollisionAttempt.Collision -> Unit + } + } + throw InviteCodeCollisionException(maxCollisionAttempts) + } } -private sealed class RotationAttempt { - data class Rotated(val rotation: InviteCodeRotation) : RotationAttempt() +private sealed class CollisionAttempt { + data class Success(val value: T) : CollisionAttempt() - object Collision : RotationAttempt() + object Collision : CollisionAttempt() } diff --git a/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/InviteCodeLifecycleServiceTest.kt b/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/InviteCodeLifecycleServiceTest.kt index c27fd5d..5f8ac9b 100644 --- a/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/InviteCodeLifecycleServiceTest.kt +++ b/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/InviteCodeLifecycleServiceTest.kt @@ -10,12 +10,12 @@ import org.junit.jupiter.api.assertThrows class InviteCodeLifecycleServiceTest { @Test fun `assignment retries a collision and activates the next candidate`() { - val occupiedOwner = UUID.randomUUID() - val newOwner = UUID.randomUUID() + val occupiedInviterId = UUID.randomUUID() + val newInviterId = UUID.randomUUID() val occupiedCode = InviteCode.parse("AAAAAA", InviteCodeFormats.colorHex) val availableCode = InviteCode.parse("BBBBBB", InviteCodeFormats.colorHex) val registry = InMemoryInviteCodeRegistry( - ActiveInviteCode(occupiedOwner, occupiedCode, Instant.EPOCH), + ActiveInviteCode(occupiedInviterId, occupiedCode, Instant.EPOCH), ) val service = InviteCodeLifecycleService( registry = registry, @@ -23,22 +23,22 @@ class InviteCodeLifecycleServiceTest { maxCollisionAttempts = 3, ) - val assigned = service.assign(newOwner, Instant.parse("2026-09-21T02:00:00Z")) + val assigned = service.assign(newInviterId, Instant.parse("2026-09-21T02:00:00Z")) assertEquals(availableCode, assigned.code) - assertEquals(newOwner, registry.resolveActiveOwner(availableCode)) - assertEquals(occupiedOwner, registry.resolveActiveOwner(occupiedCode)) + assertEquals(newInviterId, registry.resolveActiveInviter(availableCode)) + assertEquals(occupiedInviterId, registry.resolveActiveInviter(occupiedCode)) } @Test - fun `rotation retires the old code and activates a new code for the same owner`() { - val ownerId = UUID.randomUUID() + fun `rotation retires the old code and activates a new code for the same inviter`() { + val inviterId = UUID.randomUUID() val oldCode = InviteCode.parse("A25981", InviteCodeFormats.colorHex) val newCode = InviteCode.parse("FFAA00", InviteCodeFormats.colorHex) val activatedAt = Instant.parse("2026-09-01T00:00:00Z") val rotatedAt = Instant.parse("2026-09-21T02:30:00Z") val registry = InMemoryInviteCodeRegistry( - ActiveInviteCode(ownerId, oldCode, activatedAt), + ActiveInviteCode(inviterId, oldCode, activatedAt), ) val service = InviteCodeLifecycleService( registry = registry, @@ -46,20 +46,20 @@ class InviteCodeLifecycleServiceTest { maxCollisionAttempts = 3, ) - val rotation = service.rotate(ownerId, rotatedAt) + val rotation = service.rotate(inviterId, rotatedAt) assertEquals(oldCode, rotation.previous.code) assertEquals(rotatedAt, rotation.previous.retiredAt) assertEquals(newCode, rotation.current.code) - assertEquals(null, registry.resolveActiveOwner(oldCode)) - assertEquals(ownerId, registry.resolveActiveOwner(newCode)) + assertEquals(null, registry.resolveActiveInviter(oldCode)) + assertEquals(inviterId, registry.resolveActiveInviter(newCode)) } @Test fun `assignment returns the existing active code without generating another candidate`() { - val ownerId = UUID.randomUUID() + val inviterId = UUID.randomUUID() val existing = ActiveInviteCode( - ownerId = ownerId, + inviterId = inviterId, code = InviteCode.parse("A25981", InviteCodeFormats.colorHex), activatedAt = Instant.EPOCH, ) @@ -69,7 +69,7 @@ class InviteCodeLifecycleServiceTest { maxCollisionAttempts = 3, ) - assertEquals(existing, service.assign(ownerId, Instant.parse("2026-09-21T03:00:00Z"))) + assertEquals(existing, service.assign(inviterId, Instant.parse("2026-09-21T03:00:00Z"))) } @Test @@ -97,15 +97,15 @@ class InviteCodeLifecycleServiceTest { } @Test - fun `rotation retries candidates that are current or owned by another player`() { - val ownerId = UUID.randomUUID() - val otherOwnerId = UUID.randomUUID() + fun `rotation retries current and reserved candidates`() { + val inviterId = UUID.randomUUID() + val otherInviterId = UUID.randomUUID() val currentCode = InviteCode.parse("AAAAAA", InviteCodeFormats.colorHex) val occupiedCode = InviteCode.parse("BBBBBB", InviteCodeFormats.colorHex) val replacementCode = InviteCode.parse("CCCCCC", InviteCodeFormats.colorHex) val registry = InMemoryInviteCodeRegistry( - ActiveInviteCode(ownerId, currentCode, Instant.EPOCH), - ActiveInviteCode(otherOwnerId, occupiedCode, Instant.EPOCH), + ActiveInviteCode(inviterId, currentCode, Instant.EPOCH), + ActiveInviteCode(otherInviterId, occupiedCode, Instant.EPOCH), ) val service = InviteCodeLifecycleService( registry = registry, @@ -113,10 +113,36 @@ class InviteCodeLifecycleServiceTest { maxCollisionAttempts = 3, ) - val rotation = service.rotate(ownerId, Instant.parse("2026-09-21T03:00:00Z")) + val rotation = service.rotate(inviterId, Instant.parse("2026-09-21T03:00:00Z")) assertEquals(replacementCode, rotation.current.code) - assertEquals(otherOwnerId, registry.resolveActiveOwner(occupiedCode)) + assertEquals(otherInviterId, registry.resolveActiveInviter(occupiedCode)) + } + + @Test + fun `retired code remains reserved and cannot be assigned to another inviter`() { + val originalInviterId = UUID.randomUUID() + val newInviterId = UUID.randomUUID() + val retiredCode = InviteCode.parse("AAAAAA", InviteCodeFormats.colorHex) + val rotatedCode = InviteCode.parse("BBBBBB", InviteCodeFormats.colorHex) + val newInviterCode = InviteCode.parse("CCCCCC", InviteCodeFormats.colorHex) + val registry = InMemoryInviteCodeRegistry( + ActiveInviteCode(originalInviterId, retiredCode, Instant.EPOCH), + ) + InviteCodeLifecycleService( + registry = registry, + generator = SequenceInviteCodeGenerator(rotatedCode), + maxCollisionAttempts = 2, + ).rotate(originalInviterId, Instant.parse("2026-09-21T03:00:00Z")) + + val assigned = InviteCodeLifecycleService( + registry = registry, + generator = SequenceInviteCodeGenerator(retiredCode, newInviterCode), + maxCollisionAttempts = 2, + ).assign(newInviterId, Instant.parse("2026-09-21T04:00:00Z")) + + assertEquals(newInviterCode, assigned.code) + assertEquals(null, registry.resolveActiveInviter(retiredCode)) } } @@ -131,37 +157,40 @@ private class SequenceInviteCodeGenerator( private class InMemoryInviteCodeRegistry( vararg initialCodes: ActiveInviteCode, ) : InviteCodeRegistry { - private val byOwner = initialCodes.associateByTo(mutableMapOf()) { it.ownerId } - private val ownerByCode = initialCodes.associateTo(mutableMapOf()) { it.code to it.ownerId } + private val byInviter = initialCodes.associateByTo(mutableMapOf()) { it.inviterId } + private val activeInviterByCode = initialCodes.associateTo(mutableMapOf()) { it.code to it.inviterId } + private val reservedCodes = initialCodes.mapTo(mutableSetOf()) { it.code } override fun atomically(operation: (InviteCodeTransaction) -> T): T = synchronized(this) { operation(object : InviteCodeTransaction { - override fun activeCode(ownerId: UUID): ActiveInviteCode? = byOwner[ownerId] + override fun activeCode(inviterId: UUID): ActiveInviteCode? = byInviter[inviterId] - override fun activeOwner(code: InviteCode): UUID? = ownerByCode[code] + override fun isReserved(code: InviteCode): Boolean = code in reservedCodes override fun activate(activeInviteCode: ActiveInviteCode) { - check(byOwner[activeInviteCode.ownerId] == null) - check(ownerByCode[activeInviteCode.code] == null) - byOwner[activeInviteCode.ownerId] = activeInviteCode - ownerByCode[activeInviteCode.code] = activeInviteCode.ownerId + check(byInviter[activeInviteCode.inviterId] == null) + check(activeInviteCode.code !in reservedCodes) + byInviter[activeInviteCode.inviterId] = activeInviteCode + activeInviterByCode[activeInviteCode.code] = activeInviteCode.inviterId + reservedCodes += activeInviteCode.code } override fun replace( previous: RetiredInviteCode, current: ActiveInviteCode, ) { - check(byOwner[previous.ownerId]?.code == previous.code) - check(ownerByCode[previous.code] == previous.ownerId) - check(ownerByCode[current.code] == null) - byOwner[current.ownerId] = current - ownerByCode.remove(previous.code) - ownerByCode[current.code] = current.ownerId + check(byInviter[previous.inviterId]?.code == previous.code) + check(activeInviterByCode[previous.code] == previous.inviterId) + check(current.code !in reservedCodes) + byInviter[current.inviterId] = current + activeInviterByCode.remove(previous.code) + activeInviterByCode[current.code] = current.inviterId + reservedCodes += current.code } }) } - fun resolveActiveOwner(code: InviteCode): UUID? = synchronized(this) { - ownerByCode[code] + fun resolveActiveInviter(code: InviteCode): UUID? = synchronized(this) { + activeInviterByCode[code] } } From 065d69107a0bd262541a1e1ea85472f016e47520 Mon Sep 17 00:00:00 2001 From: Command1264 Date: Mon, 21 Sep 2026 18:16:42 +0800 Subject: [PATCH 3/3] refactor: align invite code domain language (#4) --- .../invitecode/core/InviteCodeLifecycleService.kt | 6 +++--- .../invitecode/core/InviteCodeLifecycleServiceTest.kt | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/InviteCodeLifecycleService.kt b/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/InviteCodeLifecycleService.kt index 1a4cd34..8937f81 100644 --- a/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/InviteCodeLifecycleService.kt +++ b/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/InviteCodeLifecycleService.kt @@ -29,8 +29,8 @@ data class InviteCodeRotation( /** * Runs Invite Code allocation operations atomically. Implementations must prevent two overlapping - * operations from activating the same normalized code, reusing a retired code, or activating more - * than one code for an Inviter. + * 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 atomically(operation: (InviteCodeTransaction) -> T): T @@ -53,7 +53,7 @@ class InviteCodeCollisionException( val attempts: Int, ) : IllegalStateException( "Could not allocate a unique Invite Code after $attempts attempts; " + - "increase the code space or inspect the active code registry.", + "increase the Invite Code namespace or inspect the Invite Code registry.", ) class ActiveInviteCodeNotFoundException( diff --git a/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/InviteCodeLifecycleServiceTest.kt b/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/InviteCodeLifecycleServiceTest.kt index 5f8ac9b..ee65320 100644 --- a/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/InviteCodeLifecycleServiceTest.kt +++ b/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/InviteCodeLifecycleServiceTest.kt @@ -91,7 +91,7 @@ class InviteCodeLifecycleServiceTest { assertEquals(2, error.attempts) assertEquals( "Could not allocate a unique Invite Code after 2 attempts; " + - "increase the code space or inspect the active code registry.", + "increase the Invite Code namespace or inspect the Invite Code registry.", error.message, ) }