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..8937f81 --- /dev/null +++ b/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/InviteCodeLifecycleService.kt @@ -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 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 = 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 = 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 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 CollisionAttempt { + data class Success(val value: T) : CollisionAttempt() + + object Collision : CollisionAttempt() +} 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..ee65320 --- /dev/null +++ b/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/InviteCodeLifecycleServiceTest.kt @@ -0,0 +1,196 @@ +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 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(occupiedInviterId, occupiedCode, Instant.EPOCH), + ) + val service = InviteCodeLifecycleService( + registry = registry, + generator = SequenceInviteCodeGenerator(occupiedCode, availableCode), + maxCollisionAttempts = 3, + ) + + val assigned = service.assign(newInviterId, Instant.parse("2026-09-21T02:00:00Z")) + + assertEquals(availableCode, assigned.code) + 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 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(inviterId, oldCode, activatedAt), + ) + val service = InviteCodeLifecycleService( + registry = registry, + generator = SequenceInviteCodeGenerator(newCode), + maxCollisionAttempts = 3, + ) + + val rotation = service.rotate(inviterId, rotatedAt) + + assertEquals(oldCode, rotation.previous.code) + assertEquals(rotatedAt, rotation.previous.retiredAt) + assertEquals(newCode, rotation.current.code) + assertEquals(null, registry.resolveActiveInviter(oldCode)) + assertEquals(inviterId, registry.resolveActiveInviter(newCode)) + } + + @Test + fun `assignment returns the existing active code without generating another candidate`() { + val inviterId = UUID.randomUUID() + val existing = ActiveInviteCode( + inviterId = inviterId, + code = InviteCode.parse("A25981", InviteCodeFormats.colorHex), + activatedAt = Instant.EPOCH, + ) + val service = InviteCodeLifecycleService( + registry = InMemoryInviteCodeRegistry(existing), + generator = SequenceInviteCodeGenerator(), + maxCollisionAttempts = 3, + ) + + assertEquals(existing, service.assign(inviterId, 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 Invite Code namespace or inspect the Invite Code registry.", + error.message, + ) + } + + @Test + 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(inviterId, currentCode, Instant.EPOCH), + ActiveInviteCode(otherInviterId, occupiedCode, Instant.EPOCH), + ) + val service = InviteCodeLifecycleService( + registry = registry, + generator = SequenceInviteCodeGenerator(currentCode, occupiedCode, replacementCode), + maxCollisionAttempts = 3, + ) + + val rotation = service.rotate(inviterId, Instant.parse("2026-09-21T03:00:00Z")) + + assertEquals(replacementCode, rotation.current.code) + 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)) + } +} + +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 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(inviterId: UUID): ActiveInviteCode? = byInviter[inviterId] + + override fun isReserved(code: InviteCode): Boolean = code in reservedCodes + + override fun activate(activeInviteCode: ActiveInviteCode) { + 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(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 resolveActiveInviter(code: InviteCode): UUID? = synchronized(this) { + activeInviterByCode[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) + } }