diff --git a/README.md b/README.md index 1d021d7..667298c 100644 --- a/README.md +++ b/README.md @@ -2,9 +2,9 @@ InviteCode is a Kotlin invitation and referral rewards plugin for Spigot and Paper. `InviteCodeKt` is the repository name; the plugin and its data directory are named `InviteCode`. -The project is currently `0.1.0-SNAPSHOT`. It builds one Java 8 compatible plugin JAR and keeps newer Minecraft APIs behind isolated adapters. SQLite and MySQL 8.4 are implemented storage backends. The final player experience and cross-version server matrix still require release-stage acceptance. +The project is currently `0.1.0-SNAPSHOT`. It builds one Java 8 compatible plugin JAR and keeps newer Minecraft APIs behind isolated adapters. SQLite and MySQL 8.4 are production storage backends; JSON is available for small single-instance installations. The final player experience and cross-version server matrix still require release-stage acceptance. -The complete maintainer guide is in [繁體中文](docs/README.zh-TW.md) and is the primary maintained documentation. See also the [product specification](docs/spec/invitecode-1.0.md), [Bukkit operations](docs/operations/bukkit-workflow.md), and [MySQL setup](docs/operations/mysql-storage.md). These documents are maintained in Traditional Chinese. +The complete maintainer guide is in [繁體中文](docs/README.zh-TW.md) and is the primary maintained documentation. See also the [product specification](docs/spec/invitecode-1.0.md), [Bukkit operations](docs/operations/bukkit-workflow.md), [JSON setup](docs/operations/json-storage.md), and [MySQL setup](docs/operations/mysql-storage.md). These documents are maintained in Traditional Chinese. ## Build diff --git a/docs/README.zh-TW.md b/docs/README.zh-TW.md index 4bba184..33684a5 100644 --- a/docs/README.zh-TW.md +++ b/docs/README.zh-TW.md @@ -12,7 +12,7 @@ InviteCode 是從零重寫的 Kotlin Minecraft 邀請與推薦獎勵插件;`In - 透過 Invite Code 建立一筆永久的 Inviter 與 Invitee 關係。 - 將建立 Invitation 與達成獎勵資格分成不同階段。 - 支援可設定的 Qualification Policy 與可復原的 Reward Delivery。 -- 已實作 SQLite 與 MySQL 8.4;JSON 仍是後續規劃。 +- 已實作 SQLite 與 MySQL 8.4;JSON 可供小型單實例伺服器、測試與資料交換使用。 - 在不使用 NMS 的前提下維持 Java 8 執行環境相容性。 - 在有能力的新版伺服器使用原生 Dialog 輸入,其餘版本安全退回聊天或指令輸入。 @@ -68,6 +68,8 @@ SQLite persistence 具備暫存資料庫 contract tests,插件只在專用 exe MySQL 8.4 使用共用外部 HMAC 密鑰、連線池及具 checksum 與中斷復原檢查的 migration ledger。資料庫須先存在,全新的空白 database 會在插件啟動時自動建表;多個插件實例必須使用同一個密鑰。設定與復原方式請見 [`mysql-storage.md`](./operations/mysql-storage.md)。 +JSON 以版本化、可閱讀的資料快照作為持久化來源,沿用 SQLite 的交易約束處理操作;每次寫入都要更新整份檔案,因此僅適合小型單實例環境。設定、備份與錯誤復原方式見 [`json-storage.md`](./operations/json-storage.md)。 + Claim 防濫用只保存具期限的 HMAC-SHA-256 網路雜湊,不保存原始 IP;預設保留 30 天,並可設定相符時 `ALLOW`、`WARN` 或 `DENY`。SQLite 的 `anti-abuse.key` 由首次初始化建立,需隨 SQLite 備份且不得提交版本控制;MySQL 則使用所有實例共用的外部密鑰。 ## Qualification Policy diff --git a/docs/operations/bukkit-workflow.md b/docs/operations/bukkit-workflow.md index 7c6f5bd..21e7401 100644 --- a/docs/operations/bukkit-workflow.md +++ b/docs/operations/bukkit-workflow.md @@ -1,6 +1,6 @@ # Bukkit 操作與維護 -本文件說明 InviteCode 在 Spigot/Paper 上的玩家流程、管理指令、儲存初始化、維護模式與人工驗收方式。可選擇 `SQLITE` 或 `MYSQL`;`JSON` 尚未實作。MySQL 的設定與復原細節見 [`mysql-storage.md`](./mysql-storage.md)。 +本文件說明 InviteCode 在 Spigot/Paper 上的玩家流程、管理指令、儲存初始化、維護模式與人工驗收方式。可選擇 `SQLITE`、`MYSQL` 或小型單實例環境使用的 `JSON`。JSON 與 MySQL 的設定及復原細節分別見 [`json-storage.md`](./json-storage.md) 與 [`mysql-storage.md`](./mysql-storage.md)。 ## 首次啟動 diff --git a/docs/operations/json-storage.md b/docs/operations/json-storage.md new file mode 100644 index 0000000..4668218 --- /dev/null +++ b/docs/operations/json-storage.md @@ -0,0 +1,9 @@ +# JSON 儲存設定與復原 + +JSON backend 適合小型單一伺服器、測試與資料交換。將 `plugins/InviteCode/storage.yml` 的 `backend` 設為 `JSON`,可選擇在 `json.file` 指定 `plugins/InviteCode/` 下的相對 `.json` 路徑;未設定時預設為 `invitecode.json`。第一次啟動會自動建立 JSON 檔與二進位 `anti-abuse.key`,不需管理員執行初始化指令。 + +JSON 檔是唯一的持久化資料來源,內含 `format-version`、`schema-version` 與按資料表分組的記錄;執行時使用暫存 SQLite 工作檔沿用現有交易、唯一性及稽核約束。每次成功寫入都會重新輸出整份 JSON,以同資料夾暫存檔原子替換正式檔,並將替換前的快照保留為 `invitecode.json.previous`(實際名稱跟隨 `json.file`)。`.lock` sidecar 以作業系統檔案鎖阻止兩個程序同時開啟;程序異常結束後檔案可能留存,鎖會由作業系統釋放,不應僅因檔案存在而刪除它。 + +每次寫入的成本隨整體資料量成長,不能像 MySQL 一樣讓多個插件實例共用同一份資料,也不應用於高併發或大型伺服器。JSON 格式供檢視與交換,但手動更改記錄可能破壞領域約束。切換 backend 不會自動搬移資料。JSON 格式與內部 schema 版本不相符時會拒絕開啟;目前沒有既有 JSON 檔的線上升級指令。 + +若 JSON 損毀或版本不支援,插件會進入維護模式,保留原檔,**不會**把它當成空白資料重新初始化。先停止伺服器並備份正式 JSON、`.previous` 及 `anti-abuse.key`。檢查錯誤訊息與版本;若上一份快照有效,可在伺服器停機時由管理員將 `.previous` 複製回正式檔,再啟動驗證。這會失去上一份快照之後的變更。不要重新產生 `anti-abuse.key`:它是 HMAC 密鑰,應與 JSON 同時備份。若寫入或原子替換失敗,當次程序會停止後續寫入;修正磁碟問題後重啟並檢查最後一份有效快照。 diff --git a/docs/testing/evidence/2026-09-23-issue-7-json-smoke.md b/docs/testing/evidence/2026-09-23-issue-7-json-smoke.md new file mode 100644 index 0000000..0f74dae --- /dev/null +++ b/docs/testing/evidence/2026-09-23-issue-7-json-smoke.md @@ -0,0 +1,19 @@ +# Issue #7 JSON 儲存自動化 Smoke + +- 日期:2026-09-23 +- 受測 JAR SHA-256:`99CE69BE0A38679EDD914AC608C0B0ACC85FE5BCD6A88D80B44FCEF3238BDADA` +- 設定:`backend: JSON`,全新隔離 TestLab 實例;未安排真人玩家驗收 + +| Profile | 核心/Java | 首次啟動 | 停機後重啟 | +| --- | --- | --- | --- | +| `spigot-1.8.8` | Spigot 1.8.8/`local-8` | 自動建立 JSON 與 32-byte 密鑰,InviteCode `ACTIVE` | 直接讀回 JSON,Doctor 顯示 `JSON 儲存版本=1` | +| `spigot-latest` | Spigot 26.2/`local-25` | 自動建立 JSON 與 32-byte 密鑰,InviteCode `ACTIVE`;Doctor 顯示 Dialog=`SPIGOT` | 未執行,已由最低 Spigot 與最新 Paper 覆蓋重啟 | +| `paper-latest` | Paper 26.2 build 128/`local-25` | 自動建立 JSON 與 32-byte 密鑰,InviteCode `ACTIVE` | 直接讀回 JSON,Doctor 顯示 `JSON 儲存版本=1`、Dialog=`PAPER` | + +最低 Spigot 與最新 Paper 的 JSON 與 `anti-abuse.key` SHA-256 在重啟前後各自保持不變;三個實例的 `logs/latest.log` 可用嚴格 UTF-8 解碼,沒有 InviteCode 維護模式、`NoSuchMethodError` 或找不到 JDBC driver。伺服器均以 `stop` 正常關閉,51888/52620/62620 port 已釋放。Java 8 JAR 檢查與相關 Gradle 測試通過。共用儲存契約由 SQLite、MySQL、JSON 三種 backend 使用;本機未提供 MySQL 測試服務,相關 integration tests 依既有設定略過。 + +測試過程先後查出兩個只有在實際伺服器 ClassLoader 才會出現的問題:JSON 快照直接經 `DriverManager` 無法取得封裝的 SQLite driver,以及舊版 Spigot 的 Gson 蓋過插件需要的版本。最終 JAR 已改用 SQL 模組既有的 driver 載入方式,並將插件用 Gson 搬至私有 package;上表與雜湊結果均為修正後同一份 JAR 的結果。 + +`spigot-latest` 的最後一輪 smoke 有一個從 `127.0.0.1` 進入的 `Command1` 玩家連線約四秒,並非本次安排的測試步驟。此連線使該實例產生玩家資料;沒有以其行為判定玩家流程通過,也不把該實例的 JSON 雜湊用於重啟一致性比較。 + +最新 Paper 與 Spigot 啟動時另有 OSHI 在 Windows Perflib 讀取英文 counter 名稱失敗的錯誤,堆疊位於伺服器的 OSHI/JNA,未涉及 InviteCode;伺服器與插件仍正常啟動。真人操作、其他 Minecraft 版本與高負載效能不在本次 smoke 範圍,仍待後續驗收。 diff --git a/docs/testing/test-servers.md b/docs/testing/test-servers.md index 50f270a..c1d82ae 100644 --- a/docs/testing/test-servers.md +++ b/docs/testing/test-servers.md @@ -65,7 +65,7 @@ pwsh -NoProfile -File .\scripts\test-servers\start.ps1 -Profile paper-latest ## 每個 profile 的最低 smoke 1. 確認 InviteCode 啟用且沒有 linkage error、legacy material warning 或未處理 exception。 -2. 確認第一次啟動自動建立 SQLite 與 anti-abuse key,重新啟動後沿用既有資料。 +2. 確認所選 backend 首次啟動自動建立必要資料與 anti-abuse key(MySQL 使用外部密鑰),重新啟動後沿用既有資料。 3. 玩家與 Console 驗證 `/ic help`、`/ic reload`、Tab completion 與權限拒絕。 4. 玩家驗證 Invite Code 顯示、Claim、Confirmation、Status 與 Stats。 5. 驗證 `zh_TW`/`en_US`、UTF-8 與 client locale fallback。 diff --git a/invitecode-core/build.gradle.kts b/invitecode-core/build.gradle.kts index 231b7cf..386d34c 100644 --- a/invitecode-core/build.gradle.kts +++ b/invitecode-core/build.gradle.kts @@ -1,5 +1,11 @@ description = "Platform-independent InviteCode domain model." +plugins { + `java-test-fixtures` +} + dependencies { api(project(":invitecode-api")) + testFixturesImplementation(platform("org.junit:junit-bom:5.13.4")) + testFixturesImplementation("org.junit.jupiter:junit-jupiter") } diff --git a/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/StorageConfiguration.kt b/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/StorageConfiguration.kt index 51ed9c4..a714443 100644 --- a/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/StorageConfiguration.kt +++ b/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/StorageConfiguration.kt @@ -32,6 +32,20 @@ data class SqliteConfiguration(val file: String) { } } +data class JsonConfiguration(val file: String) { + init { + require(file.isNotBlank() && file.endsWith(".json", ignoreCase = true)) { + "JSON file must be a non-blank .json path." + } + require(!file.startsWith('/') && !Regex("^[A-Za-z]:.*").matches(file)) { + "JSON file must be relative to the plugin data directory." + } + require(file.replace('\\', '/').split('/').none { it.isBlank() || it == "." || it == ".." }) { + "JSON file must not contain empty, current-directory, or parent-directory segments." + } + } +} + data class MysqlConfiguration( val host: String, val port: Int, @@ -76,25 +90,15 @@ data class StorageConfiguration( val backend: StorageBackendType, val sqlite: SqliteConfiguration, val mysql: MysqlConfiguration, -) { - fun requireSupportedBackend(): StorageConfiguration { - if (backend == StorageBackendType.JSON) { - throw UnsupportedStorageBackendException(backend) - } - return this - } -} - -class UnsupportedStorageBackendException(backend: StorageBackendType) : IllegalStateException( - "Storage backend $backend is not implemented in this version; select SQLITE or install a version that supports it.", + val json: JsonConfiguration = JsonConfiguration("invitecode.json"), ) object StorageConfigurationParser { const val CURRENT_VERSION = 1 fun parse(value: Map): StorageConfiguration { - require(value.keys == ROOT_KEYS) { - "Storage configuration must contain only ${ROOT_KEYS.sorted().joinToString()}." + require(value.keys == ROOT_KEYS || value.keys == ROOT_KEYS + "json") { + "Storage configuration must contain ${ROOT_KEYS.sorted().joinToString()} and optional json." } val version = value.requiredInteger("config-version", "Storage configuration") require(version == CURRENT_VERSION) { @@ -106,6 +110,11 @@ object StorageConfigurationParser { require(mysql.keys == MYSQL_KEYS) { "mysql must contain only ${MYSQL_KEYS.sorted().joinToString()}." } + val json = if ("json" in value) { + val map = value.requiredMap("json", "Storage configuration") + require(map.keys == setOf("file")) { "json must contain only file." } + JsonConfiguration(map.requiredString("file", "json")) + } else JsonConfiguration("invitecode.json") return StorageConfiguration( version = version, backend = value.requiredEnum("backend", "Storage configuration"), @@ -123,6 +132,7 @@ object StorageConfigurationParser { ), tlsMode = mysql.requiredEnum("tls-mode", "mysql"), ), + json = json, ) } diff --git a/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/StorageConfigurationTest.kt b/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/StorageConfigurationTest.kt index c89a4d6..8b7eada 100644 --- a/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/StorageConfigurationTest.kt +++ b/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/StorageConfigurationTest.kt @@ -27,16 +27,25 @@ class StorageConfigurationTest { } @Test - fun `supports MySQL and rejects unfinished JSON`() { + fun `supports MySQL and JSON with a safe default path`() { assertEquals( StorageBackendType.MYSQL, StorageConfigurationParser.parse(validConfiguration().toMutableMap().apply { put("backend", "MYSQL") }) - .requireSupportedBackend().backend, + .backend, ) - assertThrows { - StorageConfigurationParser.parse(validConfiguration().toMutableMap().apply { put("backend", "JSON") }) - .requireSupportedBackend() + val json = StorageConfigurationParser.parse( + validConfiguration().toMutableMap().apply { put("backend", "JSON") }, + ) + assertEquals(StorageBackendType.JSON, json.backend) + assertEquals("invitecode.json", json.json.file) + } + + @Test + fun `JSON file rejects escaping paths`() { + val value = validConfiguration().toMutableMap().apply { + put("json", mapOf("file" to "../outside.json")) } + assertThrows { StorageConfigurationParser.parse(value) } } @Test diff --git a/invitecode-core/src/testFixtures/kotlin/io/github/command1264/invitecode/core/StorageContractTest.kt b/invitecode-core/src/testFixtures/kotlin/io/github/command1264/invitecode/core/StorageContractTest.kt new file mode 100644 index 0000000..c5d3af9 --- /dev/null +++ b/invitecode-core/src/testFixtures/kotlin/io/github/command1264/invitecode/core/StorageContractTest.kt @@ -0,0 +1,47 @@ +package io.github.command1264.invitecode.core + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test +import java.time.Instant +import java.time.LocalDate +import java.util.UUID + +abstract class StorageContractTest { + protected abstract fun withStorage(test: (InviteCodeStorage) -> Unit) + + @Test + fun `player identity and unique login days survive storage operations`() = withStorage { storage -> + val id = UUID.randomUUID() + val firstSeen = Instant.parse("2026-09-22T00:00:00Z") + storage.savePlayer(StoredPlayer(id, firstSeen, "Original")) + storage.savePlayer(StoredPlayer(id, firstSeen.plusSeconds(5), "Latest")) + storage.recordLoginDay(id, LocalDate.parse("2026-09-22")) + storage.recordLoginDay(id, LocalDate.parse("2026-09-22")) + assertEquals(StoredPlayer(id, firstSeen, "Latest"), storage.player(id)) + assertEquals(1, storage.loginDays(id)) + } + + @Test + fun `reward state and transition history are durable`() = withStorage { storage -> + val recipient = UUID.randomUUID() + val now = Instant.parse("2026-09-22T00:00:00Z") + val deliveryId = UUID.randomUUID() + val actionId = UUID.randomUUID() + storage.savePlayer(StoredPlayer(recipient, now)) + val delivery = StoredRewardDelivery( + deliveryId, null, "first-milestone", RewardDeliveryStatus.PENDING, + "milestone:$recipient:1:first-milestone", now, now, + ) + val action = StoredRewardAction( + actionId, deliveryId, null, recipient, 0, "MESSAGE", "hello", + RewardActionStatus.PENDING, "${delivery.idempotencyKey}:0", now, now, + ) + storage.saveRewardDelivery(delivery, listOf(action)) + assertEquals(delivery, storage.rewardDelivery(deliveryId)) + assertEquals(listOf(action), storage.rewardActions(deliveryId)) + storage.saveRewardAction(action.copy(status = RewardActionStatus.PROCESSING, updatedAt = now.plusSeconds(1))) + assertEquals(1, storage.recoverInterruptedRewardActions(now.plusSeconds(2))) + assertEquals(RewardActionStatus.UNCERTAIN, storage.rewardAction(actionId)?.status) + assertEquals(3, storage.rewardActionTransitions(actionId).size) + } +} diff --git a/invitecode-platform-bukkit/src/main/kotlin/io/github/command1264/invitecode/platform/bukkit/RuntimeConfigurationAssembler.kt b/invitecode-platform-bukkit/src/main/kotlin/io/github/command1264/invitecode/platform/bukkit/RuntimeConfigurationAssembler.kt index a872827..fcee404 100644 --- a/invitecode-platform-bukkit/src/main/kotlin/io/github/command1264/invitecode/platform/bukkit/RuntimeConfigurationAssembler.kt +++ b/invitecode-platform-bukkit/src/main/kotlin/io/github/command1264/invitecode/platform/bukkit/RuntimeConfigurationAssembler.kt @@ -45,7 +45,7 @@ object RuntimeConfigurationAssembler { onMissingMessage: (String) -> Unit = {}, ): InviteCodeRuntimeConfiguration { val parsedGeneral = BukkitPluginConfigurationParser.parse(general) - val parsedStorage = StorageConfigurationParser.parse(storage).requireSupportedBackend() + val parsedStorage = StorageConfigurationParser.parse(storage) val parsedQualifications = QualificationConfigurationParser.parse(qualifications) val parsedRewards = RewardConfigurationParser.parse(rewards) require(messageCatalogs.isNotEmpty()) { "At least one message catalog is required." } diff --git a/invitecode-platform-bukkit/src/test/kotlin/io/github/command1264/invitecode/platform/bukkit/RuntimeConfigurationAssemblerTest.kt b/invitecode-platform-bukkit/src/test/kotlin/io/github/command1264/invitecode/platform/bukkit/RuntimeConfigurationAssemblerTest.kt index 5e3be7e..6c18218 100644 --- a/invitecode-platform-bukkit/src/test/kotlin/io/github/command1264/invitecode/platform/bukkit/RuntimeConfigurationAssemblerTest.kt +++ b/invitecode-platform-bukkit/src/test/kotlin/io/github/command1264/invitecode/platform/bukkit/RuntimeConfigurationAssemblerTest.kt @@ -45,14 +45,13 @@ class RuntimeConfigurationAssemblerTest { } @Test - fun `unsupported configured backend fails before snapshot installation`() { + fun `JSON backend is accepted in the configuration snapshot`() { val json = storage().toMutableMap().apply { this["backend"] = "JSON" } - assertThrows(IllegalStateException::class.java) { - RuntimeConfigurationAssembler.parse( - general(), json, qualifications(), rewards(), mapOf("zh_TW" to catalog("訊息")), - ) - } + val configured = RuntimeConfigurationAssembler.parse( + general(), json, qualifications(), rewards(), mapOf("zh_TW" to catalog("訊息")), + ) + assertEquals(StorageBackendType.JSON, configured.storage.backend) } @Test diff --git a/invitecode-platform-modern/src/main/kotlin/io/github/command1264/invitecode/platform/modern/ReflectiveNativeDialogInput.kt b/invitecode-platform-modern/src/main/kotlin/io/github/command1264/invitecode/platform/modern/ReflectiveNativeDialogInput.kt index f6fc390..604fab5 100644 --- a/invitecode-platform-modern/src/main/kotlin/io/github/command1264/invitecode/platform/modern/ReflectiveNativeDialogInput.kt +++ b/invitecode-platform-modern/src/main/kotlin/io/github/command1264/invitecode/platform/modern/ReflectiveNativeDialogInput.kt @@ -347,8 +347,11 @@ private class SpigotDialogBackend private constructor( val button = load("net.md_5.bungee.api.dialog.action.ActionButton") val dialog = load("net.md_5.bungee.api.dialog.Dialog") val confirmation = load("net.md_5.bungee.api.dialog.ConfirmationDialog") - val jsonElement = load("com.google.gson.JsonElement") - val jsonObject = load("com.google.gson.JsonObject") + // Shadow 8.3 relocates matching string constants. Construct the server API name at + // runtime so this reflective adapter still uses the server's Gson classes. + val serverJsonPackage = listOf("com", "google", "gson").joinToString(".") + val jsonElement = load("$serverJsonPackage.JsonElement") + val jsonObject = load("$serverJsonPackage.JsonObject") SpigotDialogBackend( plugin = plugin, eventClass = event, diff --git a/invitecode-plugin/build.gradle.kts b/invitecode-plugin/build.gradle.kts index 5e8378b..fe7ffc2 100644 --- a/invitecode-plugin/build.gradle.kts +++ b/invitecode-plugin/build.gradle.kts @@ -121,6 +121,7 @@ val shadowJar = tasks.named("shadowJar") { archiveClassifier.set("") exclude("module-info.class", "META-INF/versions/**") mergeServiceFiles() + relocate("com.google.gson", "io.github.command1264.invitecode.libs.gson") } tasks.withType().configureEach { @@ -150,6 +151,8 @@ val verifyPluginJar by tasks.registering(VerifyPluginJar::class) { "org/sqlite/JDBC.class", "com/mysql/cj/jdbc/Driver.class", "com/zaxxer/hikari/HikariDataSource.class", + "io/github/command1264/invitecode/libs/gson/Gson.class", + "io/github/command1264/invitecode/storage/json/JsonInviteCodeStorage.class", "org/slf4j/impl/JDK14LoggerFactory.class", "mysql/V1__initial_schema.sql", "org/sqlite/native/Linux/x86_64/libsqlitejdbc.so", @@ -165,6 +168,7 @@ val verifyPluginJar by tasks.registering(VerifyPluginJar::class) { "rewards.yml", "messages/zh_TW.yml", "messages/en_US.yml", + "com/google/gson/Gson.class", ), ) } diff --git a/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/InviteCodePlugin.kt b/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/InviteCodePlugin.kt index c83d49c..e89a4fb 100644 --- a/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/InviteCodePlugin.kt +++ b/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/InviteCodePlugin.kt @@ -21,6 +21,7 @@ import io.github.command1264.invitecode.platform.bukkit.RuntimeConfigurationRelo import io.github.command1264.invitecode.platform.bukkit.NetworkAddressHasher import io.github.command1264.invitecode.platform.modern.ModernPlatformCapabilities import io.github.command1264.invitecode.platform.modern.ModernPlatformIntegration +import io.github.command1264.invitecode.storage.json.JsonInviteCodeStorage import io.github.command1264.invitecode.storage.sql.BlockingOperationGuard import io.github.command1264.invitecode.storage.sql.SqliteInviteCodeStorage import io.github.command1264.invitecode.storage.sql.SqliteSchemaMigrator @@ -148,7 +149,7 @@ class InviteCodePlugin : JavaPlugin() { ) } if (result.storageInitialized) { - logger.info("已自動完成首次 ${result.configuration?.storage?.backend} schema 與防濫用密鑰初始化。") + logger.info("已自動完成首次 ${result.configuration?.storage?.backend} 儲存與防濫用密鑰初始化。") } server.onlinePlayers.forEach { playerWorkflows?.registerPlayer(it) } logger.info("InviteCode ${description.version} 已啟用。") @@ -196,7 +197,17 @@ class InviteCodePlugin : JavaPlugin() { hasher = bootstrap.networkHasher bootstrap.initialized } - StorageBackendType.JSON -> error("JSON storage is not implemented.") + StorageBackendType.JSON -> { + val dataDirectory = dataFolder.toPath().normalize() + val file = dataDirectory.resolve(candidate.storage.json.file).normalize() + require(file.startsWith(dataDirectory)) { "JSON storage path escapes the plugin data directory." } + val bootstrap = JsonRuntimeBootstrap( + file, dataDirectory.resolve(NETWORK_SECRET_FILE), guard, + ).initializeOrOpen() + opened = bootstrap.storage + hasher = bootstrap.networkHasher + bootstrap.initialized + } } val recovered = RewardDeliveryCoordinator(opened).recoverInterrupted(Instant.now()) StartupResult( @@ -363,10 +374,11 @@ class InviteCodePlugin : JavaPlugin() { sender, "admin.doctor-storage", mapOf( + "backend" to configuration.current().value.storage.backend.name, "schema" to when (configuration.current().value.storage.backend) { StorageBackendType.SQLITE -> SqliteSchemaMigrator.currentVersion.toString() StorageBackendType.MYSQL -> MysqlSchemaMigrator.CURRENT_VERSION.toString() - StorageBackendType.JSON -> "N/A" + StorageBackendType.JSON -> JsonInviteCodeStorage.FORMAT_VERSION.toString() }, "pending" to backlog.pending.toString(), "processing" to backlog.processing.toString(), diff --git a/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/JsonRuntimeBootstrap.kt b/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/JsonRuntimeBootstrap.kt new file mode 100644 index 0000000..7f8a35c --- /dev/null +++ b/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/JsonRuntimeBootstrap.kt @@ -0,0 +1,61 @@ +package io.github.command1264.invitecode.plugin + +import io.github.command1264.invitecode.core.AuditRecord +import io.github.command1264.invitecode.core.InvitationAuditAction +import io.github.command1264.invitecode.platform.bukkit.NetworkAddressHasher +import io.github.command1264.invitecode.storage.json.JsonInviteCodeStorage +import io.github.command1264.invitecode.storage.sql.BlockingOperationGuard +import java.nio.file.Files +import java.nio.file.Path +import java.time.Instant +import java.util.UUID + +internal data class JsonBootstrapResult( + val storage: JsonInviteCodeStorage, + val networkHasher: NetworkAddressHasher, + val initialized: Boolean, +) + +internal class JsonRuntimeBootstrap( + private val file: Path, + private val networkSecret: Path, + private val guard: BlockingOperationGuard, + private val now: () -> Instant = Instant::now, +) { + fun initializeOrOpen(): JsonBootstrapResult { + require(!Files.exists(file) || Files.isRegularFile(file)) { + "JSON storage path ${file.toAbsolutePath()} exists but is not a regular file." + } + val initialize = !Files.exists(file) + val secretExisted = Files.isRegularFile(networkSecret) + var storage: JsonInviteCodeStorage? = null + var hasher: NetworkAddressHasher? = null + try { + // Acquire the JSON writer lock before touching the shared anti-abuse key. + storage = JsonInviteCodeStorage.open(file, guard) + hasher = if (initialize) NetworkAddressHasher.loadOrCreate(networkSecret) + else NetworkAddressHasher.loadExisting(networkSecret) + storage.purgeNetworkHashesWithDifferentKey(hasher.keyId) + if (initialize) { + storage.saveAuditRecord(AuditRecord( + UUID.randomUUID(), InvitationAuditAction.STORAGE_MIGRATED, + "system", "automatic first initialization", now(), + )) + } + return JsonBootstrapResult(storage, hasher, initialize) + } catch (error: Exception) { + val ownedStorage = storage != null + storage?.close() + hasher?.close() + if (initialize && ownedStorage) { + listOf(file, file.resolveSibling("${file.fileName}.previous")).forEach { created -> + try { Files.deleteIfExists(created) } catch (cleanup: Exception) { error.addSuppressed(cleanup) } + } + if (!secretExisted) { + try { Files.deleteIfExists(networkSecret) } catch (cleanup: Exception) { error.addSuppressed(cleanup) } + } + } + throw error + } + } +} diff --git a/invitecode-plugin/src/main/resources/config/messages/en_US.yml b/invitecode-plugin/src/main/resources/config/messages/en_US.yml index 82cfdf7..c34f6f4 100644 --- a/invitecode-plugin/src/main/resources/config/messages/en_US.yml +++ b/invitecode-plugin/src/main/resources/config/messages/en_US.yml @@ -68,9 +68,9 @@ admin: doctor-runtime: "Runtime={phase}, configuration generation={generation}, executor={executor}." doctor-integrations: "Integrations: PlaceholderAPI={placeholder}, Vault Economy={vault}, Dialog={dialog}, RGB={rgb}." doctor-maintenance: "Maintenance reason: {reason}" - doctor-storage-offline: "SQLite is offline. Doctor did not create or modify the database." - doctor-storage: "SQLite schema={schema}; Reward backlog: PENDING={pending}, PROCESSING={processing}, UNCERTAIN={uncertain}." - doctor-storage-failed: "The SQLite health check failed. Check the server log." + doctor-storage-offline: "Storage is offline. Doctor did not create or modify data." + doctor-storage: "{backend} storage version={schema}; Reward backlog: PENDING={pending}, PROCESSING={processing}, UNCERTAIN={uncertain}." + doctor-storage-failed: "The storage health check failed. Check the server log." doctor-executor-stopping: "The executor is stopping and cannot query the Reward backlog." invite: qualified: diff --git a/invitecode-plugin/src/main/resources/config/messages/zh_TW.yml b/invitecode-plugin/src/main/resources/config/messages/zh_TW.yml index 5f7668e..ea5afce 100644 --- a/invitecode-plugin/src/main/resources/config/messages/zh_TW.yml +++ b/invitecode-plugin/src/main/resources/config/messages/zh_TW.yml @@ -68,9 +68,9 @@ admin: doctor-runtime: "Runtime={phase},設定世代={generation},executor={executor}。" doctor-integrations: "Integration:PlaceholderAPI={placeholder},Vault Economy={vault},Dialog={dialog},RGB={rgb}。" doctor-maintenance: "維護原因:{reason}" - doctor-storage-offline: "SQLite=未連線;doctor 未建立或修改資料庫。" - doctor-storage: "SQLite schema={schema};Reward backlog:PENDING={pending},PROCESSING={processing},UNCERTAIN={uncertain}。" - doctor-storage-failed: "SQLite 健康檢查失敗,請查看伺服器紀錄。" + doctor-storage-offline: "儲存未連線;doctor 未建立或修改資料。" + doctor-storage: "{backend} 儲存版本={schema};Reward backlog:PENDING={pending},PROCESSING={processing},UNCERTAIN={uncertain}。" + doctor-storage-failed: "儲存健康檢查失敗,請查看伺服器紀錄。" doctor-executor-stopping: "Executor 正在停止,無法完成 Reward backlog 查詢。" invite: qualified: diff --git a/invitecode-plugin/src/main/resources/config/storage.yml b/invitecode-plugin/src/main/resources/config/storage.yml index c48e847..66890ad 100644 --- a/invitecode-plugin/src/main/resources/config/storage.yml +++ b/invitecode-plugin/src/main/resources/config/storage.yml @@ -4,6 +4,9 @@ backend: SQLITE sqlite: file: invitecode.db +json: + file: invitecode.json + mysql: host: localhost port: 3306 diff --git a/invitecode-plugin/src/test/kotlin/io/github/command1264/invitecode/plugin/JsonRuntimeBootstrapTest.kt b/invitecode-plugin/src/test/kotlin/io/github/command1264/invitecode/plugin/JsonRuntimeBootstrapTest.kt new file mode 100644 index 0000000..d9b6262 --- /dev/null +++ b/invitecode-plugin/src/test/kotlin/io/github/command1264/invitecode/plugin/JsonRuntimeBootstrapTest.kt @@ -0,0 +1,52 @@ +package io.github.command1264.invitecode.plugin + +import io.github.command1264.invitecode.core.StoredPlayer +import io.github.command1264.invitecode.storage.sql.BlockingOperationGuard +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertThrows +import org.junit.jupiter.api.io.TempDir +import java.nio.file.Files +import java.nio.file.Path +import java.time.Instant +import java.util.UUID + +class JsonRuntimeBootstrapTest { + @TempDir lateinit var directory: Path + private val guard = BlockingOperationGuard { } + + @Test + fun `fresh JSON installation creates data and secret and reopens existing player`() { + val file = directory.resolve("invitecode.json") + val secret = directory.resolve("anti-abuse.key") + val first = JsonRuntimeBootstrap(file, secret, guard).initializeOrOpen() + val player = StoredPlayer(UUID.randomUUID(), Instant.parse("2026-09-23T00:00:00Z")) + first.storage.use { it.savePlayer(player) } + first.networkHasher.close() + assertTrue(first.initialized) + assertTrue(Files.isRegularFile(file)) + assertEquals(32, Files.size(secret)) + + val second = JsonRuntimeBootstrap(file, secret, guard).initializeOrOpen() + second.storage.use { assertEquals(player, it.player(player.id)) } + second.networkHasher.close() + assertFalse(second.initialized) + } + + @Test + fun `existing JSON file without secret is preserved and rejected`() { + val file = directory.resolve("invitecode.json") + val secret = directory.resolve("anti-abuse.key") + val first = JsonRuntimeBootstrap(file, secret, guard).initializeOrOpen() + first.storage.close() + first.networkHasher.close() + Files.delete(secret) + val before = Files.readAllBytes(file) + + assertThrows { JsonRuntimeBootstrap(file, secret, guard).initializeOrOpen() } + assertTrue(before.contentEquals(Files.readAllBytes(file))) + assertFalse(Files.exists(secret)) + } +} diff --git a/invitecode-storage-json/build.gradle.kts b/invitecode-storage-json/build.gradle.kts index a254fb2..e2c402c 100644 --- a/invitecode-storage-json/build.gradle.kts +++ b/invitecode-storage-json/build.gradle.kts @@ -2,4 +2,7 @@ description = "Versioned JSON storage for small installations and interchange." dependencies { implementation(project(":invitecode-core")) + implementation(project(":invitecode-storage-sql")) + implementation("com.google.code.gson:gson:2.14.0") + testImplementation(testFixtures(project(":invitecode-core"))) } diff --git a/invitecode-storage-json/src/main/kotlin/io/github/command1264/invitecode/storage/json/JsonInviteCodeStorage.kt b/invitecode-storage-json/src/main/kotlin/io/github/command1264/invitecode/storage/json/JsonInviteCodeStorage.kt new file mode 100644 index 0000000..cc551d6 --- /dev/null +++ b/invitecode-storage-json/src/main/kotlin/io/github/command1264/invitecode/storage/json/JsonInviteCodeStorage.kt @@ -0,0 +1,320 @@ +package io.github.command1264.invitecode.storage.json + +import com.google.gson.JsonArray +import com.google.gson.JsonObject +import com.google.gson.JsonParser +import com.google.gson.GsonBuilder +import io.github.command1264.invitecode.core.* +import io.github.command1264.invitecode.storage.sql.BlockingOperationGuard +import io.github.command1264.invitecode.storage.sql.SqliteInviteCodeStorage +import io.github.command1264.invitecode.storage.sql.SqliteSchemaMigrator +import io.github.command1264.invitecode.storage.sql.SqliteSnapshotAccess +import java.nio.channels.FileChannel +import java.nio.channels.FileLock +import java.nio.charset.StandardCharsets +import java.nio.file.AtomicMoveNotSupportedException +import java.nio.file.Files +import java.nio.file.Path +import java.nio.file.StandardCopyOption.ATOMIC_MOVE +import java.nio.file.StandardCopyOption.REPLACE_EXISTING +import java.nio.file.StandardOpenOption.CREATE +import java.nio.file.StandardOpenOption.WRITE +import java.sql.Connection +import java.sql.Types +import java.time.Instant +import java.time.LocalDate +import java.util.UUID + +/** + * A readable JSON snapshot backed by the already validated SQLite transaction engine. The SQLite + * working file is temporary; only the JSON snapshot is durable. A failed snapshot stops all writes. + */ +class JsonInviteCodeStorage private constructor( + private val file: Path, + private val workingDirectory: Path, + private val database: Path, + private val guard: BlockingOperationGuard, + private val lockChannel: FileChannel, + private val fileLock: FileLock, + private val delegate: SqliteInviteCodeStorage, +) : InviteCodeStorage by delegate { + private var closed = false + private var failed = false + + private fun persist(operation: () -> T): T = synchronized(this) { + check(!closed && !failed) { "JSON storage is closed or a previous write failed; restart after inspecting ${file.toAbsolutePath()}." } + guard.checkAllowed() + val result = operation() + try { + val snapshot = exportSnapshot(database, guard) + writeSnapshot(file, snapshot) + } catch (error: Exception) { + failed = true + throw JsonStorageException( + "JSON snapshot write failed for ${file.toAbsolutePath()}; writes are stopped. " + + "Preserve the JSON file and its .previous copy, then restart after fixing the cause.", error, + ) + } + result + } + + override fun savePlayer(player: StoredPlayer) = persist { delegate.savePlayer(player) } + override fun recordLoginDay(playerId: UUID, loginDate: LocalDate) = + persist { delegate.recordLoginDay(playerId, loginDate) } + override fun recordNetworkHash(record: PlayerNetworkHash) = persist { delegate.recordNetworkHash(record) } + override fun purgeExpiredNetworkHashes(expiredAt: Instant): Int = + persist { delegate.purgeExpiredNetworkHashes(expiredAt) } + override fun purgeNetworkHashesWithDifferentKey(keyId: String): Int = + persist { delegate.purgeNetworkHashesWithDifferentKey(keyId) } + override fun saveInvitation(invitation: Invitation) = persist { delegate.saveInvitation(invitation) } + override fun saveQualifiedInvitation(invitation: Invitation, facts: List) = + persist { delegate.saveQualifiedInvitation(invitation, facts) } + override fun saveQualifiedInvitationWithRewards( + invitation: Invitation, facts: List, rewardPlans: List, + ) = persist { delegate.saveQualifiedInvitationWithRewards(invitation, facts, rewardPlans) } + override fun saveQualificationFact(fact: QualificationFact) = persist { delegate.saveQualificationFact(fact) } + override fun saveQualificationFacts(facts: List) = + persist { delegate.saveQualificationFacts(facts) } + override fun saveRewardAction(action: StoredRewardAction) = persist { delegate.saveRewardAction(action) } + override fun recoverInterruptedRewardActions(recoveredAt: Instant): Int = + persist { delegate.recoverInterruptedRewardActions(recoveredAt) } + override fun resolveUncertainRewardAction( + actionId: UUID, resolution: UncertainRewardActionResolution, context: RewardAdministrationContext, + ): StoredRewardAction = persist { delegate.resolveUncertainRewardAction(actionId, resolution, context) } + override fun saveRewardDelivery(delivery: StoredRewardDelivery, actions: List) = + persist { delegate.saveRewardDelivery(delivery, actions) } + override fun saveAuditRecord(record: AuditRecord) = persist { delegate.saveAuditRecord(record) } + override fun saveAuditedInvitationTransition(transition: AuditedInvitationTransition) = + persist { delegate.saveAuditedInvitationTransition(transition) } + override fun saveForcedQualificationWithRewards( + transition: AuditedInvitationTransition, rewardPlans: List, + ) = persist { delegate.saveForcedQualificationWithRewards(transition, rewardPlans) } + override fun saveAuditedClaimStateTransition(transition: AuditedClaimStateTransition) = + persist { delegate.saveAuditedClaimStateTransition(transition) } + override fun atomically(operation: (InviteCodeTransaction) -> T): T = + persist { delegate.atomically(operation) } + override fun atomically(playerIds: Set, operation: (InvitationTransaction) -> T): T = + persist { delegate.atomically(playerIds, operation) } + + override fun close() = synchronized(this) { + if (closed) return@synchronized + closed = true + delegate.close() + fileLock.release() + lockChannel.close() + Files.deleteIfExists(database) + Files.deleteIfExists(workingDirectory) + } + + companion object { + const val FORMAT_VERSION = 1 + + fun open(file: Path, guard: BlockingOperationGuard): JsonInviteCodeStorage { + guard.checkAllowed() + val target = file.toAbsolutePath().normalize() + Files.createDirectories(requireNotNull(target.parent)) + // The OS releases this advisory lock even after a crash; the sidecar may remain safely. + val lockChannel = FileChannel.open(target.resolveSibling("${target.fileName}.lock"), CREATE, WRITE) + val fileLock = try { + lockChannel.tryLock() + ?: throw JsonStorageException("JSON storage ${target} is already open by another process.") + } catch (error: Exception) { + lockChannel.close() + throw JsonStorageException("Cannot lock JSON storage ${target}; another instance may be using it.", error) + } + val workingDirectory = try { + Files.createTempDirectory("invitecode-json-") + } catch (error: Exception) { + fileLock.release() + lockChannel.close() + throw error + } + val database = workingDirectory.resolve("working.db") + try { + SqliteSchemaMigrator(database, guard).migrate() + if (Files.exists(target)) importSnapshot(target, database, guard) + val delegate = SqliteInviteCodeStorage.open(database, guard) + try { + if (!Files.exists(target)) writeSnapshot(target, exportSnapshot(database, guard)) + return JsonInviteCodeStorage( + target, workingDirectory, database, guard, lockChannel, fileLock, delegate, + ) + } catch (error: Exception) { + delegate.close() + throw error + } + } catch (error: Exception) { + fileLock.release() + lockChannel.close() + Files.deleteIfExists(database) + Files.deleteIfExists(workingDirectory) + throw error + } + } + + private fun schema(connection: Connection): Map>> { + val tables = sortedMapOf>>() + connection.createStatement().use { query -> + query.executeQuery( + "SELECT name FROM sqlite_master WHERE type='table' AND name LIKE 'invitecode_%' ORDER BY name", + ).use { result -> + while (result.next()) { + val table = result.getString(1) + require(Regex("invitecode_[a-z_]+").matches(table)) { "Invalid storage table name." } + val columns = mutableListOf>() + connection.createStatement().use { statement -> + statement.executeQuery("PRAGMA table_info($table)").use { metadata -> + while (metadata.next()) { + val name = metadata.getString("name") + val type = metadata.getString("type").uppercase() + require(Regex("[a-z_]+").matches(name)) { "Invalid storage column name." } + columns += name to if (type.contains("INT")) Types.BIGINT else Types.VARCHAR + } + } + } + tables[table] = columns + } + } + } + return tables + } + + private fun exportSnapshot(database: Path, guard: BlockingOperationGuard): JsonObject = + SqliteSnapshotAccess.withConnection(database, guard) { connection -> + val root = JsonObject() + root.addProperty("format-version", FORMAT_VERSION) + root.addProperty("schema-version", SqliteSchemaMigrator.currentVersion) + val tables = JsonObject() + schema(connection).forEach { (table, columns) -> + val rows = JsonArray() + connection.createStatement().use { query -> + query.executeQuery("SELECT * FROM $table ORDER BY rowid").use { result -> + while (result.next()) { + val row = JsonObject() + columns.forEachIndexed { index, (column, type) -> + val value = result.getObject(index + 1) + when { + value == null -> row.add(column, null) + type == Types.BIGINT -> row.addProperty(column, (value as Number).toLong()) + else -> row.addProperty(column, value.toString()) + } + } + rows.add(row) + } + } + } + tables.add(table, rows) + } + root.add("tables", tables) + root + } + + private fun importSnapshot(file: Path, database: Path, guard: BlockingOperationGuard) { + val root = try { + Files.newBufferedReader(file, StandardCharsets.UTF_8).use { JsonParser.parseReader(it).asJsonObject } + } catch (error: Exception) { + throw JsonStorageException( + "JSON storage ${file.toAbsolutePath()} is damaged. Preserve it and inspect ${file.fileName}.previous; " + + "no new database was created over it.", error, + ) + } + try { + val format = root.get("format-version")?.asString?.takeIf { it.matches(Regex("[0-9]+")) }?.toIntOrNull() + require(format == FORMAT_VERSION) { + "JSON format version $format is unsupported; expected $FORMAT_VERSION. Preserve the file and upgrade InviteCode." + } + val schemaVersion = root.get("schema-version")?.asString?.takeIf { it.matches(Regex("[0-9]+")) }?.toIntOrNull() + require(schemaVersion == SqliteSchemaMigrator.currentVersion) { + "JSON schema version $schemaVersion is unsupported; expected ${SqliteSchemaMigrator.currentVersion}. " + + "Preserve the file and run an explicit migration with a compatible InviteCode version." + } + require(root.keySet() == setOf("format-version", "schema-version", "tables")) { + "JSON storage has unknown or missing root fields." + } + SqliteSnapshotAccess.withConnection(database, guard) { connection -> + val expected = schema(connection) + val tables = root.getAsJsonObject("tables") + require(tables.keySet() == expected.keys) { "JSON storage table set does not match the current schema." } + connection.createStatement().use { it.execute("PRAGMA foreign_keys=OFF") } + connection.autoCommit = false + try { + expected.forEach { (table, columns) -> + connection.createStatement().use { it.executeUpdate("DELETE FROM $table") } + val names = columns.joinToString(",") { it.first } + val placeholders = columns.joinToString(",") { "?" } + connection.prepareStatement("INSERT INTO $table ($names) VALUES ($placeholders)").use { insert -> + tables.getAsJsonArray(table).forEach { element -> + val row = element.asJsonObject + require(row.keySet() == columns.map { it.first }.toSet()) { + "JSON storage row in $table has unknown or missing columns." + } + columns.forEachIndexed { index, (name, type) -> + val value = row.get(name) + when { + value.isJsonNull -> insert.setNull(index + 1, type) + type == Types.BIGINT -> { + val raw = value.asString + require(raw.matches(Regex("-?[0-9]+"))) { "Invalid integer in $table.$name." } + insert.setLong(index + 1, raw.toLong()) + } + else -> insert.setString(index + 1, value.asString) + } + } + insert.executeUpdate() + } + } + } + connection.createStatement().use { query -> + query.executeQuery("PRAGMA foreign_key_check").use { result -> + check(!result.next()) { "JSON storage violates a foreign key constraint." } + } + query.executeQuery("PRAGMA integrity_check").use { result -> + check(result.next() && result.getString(1) == "ok") { "JSON storage failed integrity check." } + } + } + connection.commit() + } catch (error: Exception) { + connection.rollback() + throw error + } + } + } catch (error: Exception) { + throw JsonStorageException( + "Cannot load JSON storage ${file.toAbsolutePath()}: ${error.message}. " + + "Preserve it and ${file.fileName}.previous; no existing JSON data was overwritten.", error, + ) + } + } + + private fun writeSnapshot(file: Path, root: JsonObject) { + val temporary = Files.createTempFile(requireNotNull(file.parent), ".${file.fileName}.", ".tmp") + try { + val bytes = (GsonBuilder().serializeNulls().setPrettyPrinting().create().toJson(root) + "\n") + .toByteArray(StandardCharsets.UTF_8) + FileChannel.open(temporary, WRITE).use { channel -> + val buffer = java.nio.ByteBuffer.wrap(bytes) + while (buffer.hasRemaining()) channel.write(buffer) + channel.force(true) + } + if (Files.exists(file)) { + val previous = file.resolveSibling("${file.fileName}.previous") + val pendingPrevious = Files.createTempFile(file.parent, ".${file.fileName}.", ".backup") + try { + Files.copy(file, pendingPrevious, REPLACE_EXISTING) + FileChannel.open(pendingPrevious, WRITE).use { it.force(true) } + Files.move(pendingPrevious, previous, ATOMIC_MOVE, REPLACE_EXISTING) + } finally { + Files.deleteIfExists(pendingPrevious) + } + } + Files.move(temporary, file, ATOMIC_MOVE, REPLACE_EXISTING) + } catch (error: AtomicMoveNotSupportedException) { + throw JsonStorageException("Filesystem does not support atomic JSON replacement for ${file.toAbsolutePath()}.", error) + } finally { + Files.deleteIfExists(temporary) + } + } + } +} + +class JsonStorageException(message: String, cause: Throwable? = null) : IllegalStateException(message, cause) diff --git a/invitecode-storage-json/src/test/kotlin/io/github/command1264/invitecode/storage/json/JsonInviteCodeStorageTest.kt b/invitecode-storage-json/src/test/kotlin/io/github/command1264/invitecode/storage/json/JsonInviteCodeStorageTest.kt new file mode 100644 index 0000000..e70dce0 --- /dev/null +++ b/invitecode-storage-json/src/test/kotlin/io/github/command1264/invitecode/storage/json/JsonInviteCodeStorageTest.kt @@ -0,0 +1,124 @@ +package io.github.command1264.invitecode.storage.json + +import io.github.command1264.invitecode.core.StoredPlayer +import io.github.command1264.invitecode.core.StoredRewardAction +import io.github.command1264.invitecode.core.StoredRewardDelivery +import io.github.command1264.invitecode.core.RewardActionStatus +import io.github.command1264.invitecode.core.RewardDeliveryStatus +import io.github.command1264.invitecode.storage.sql.BlockingOperationGuard +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import java.nio.charset.StandardCharsets +import java.nio.file.Files +import java.nio.file.Path +import java.nio.file.StandardCopyOption.REPLACE_EXISTING +import java.time.Instant +import java.util.UUID + +class JsonInviteCodeStorageTest { + @TempDir lateinit var directory: Path + private val guard = BlockingOperationGuard { } + + @Test + fun `player survives reopen and prior snapshot remains recoverable`() { + val file = directory.resolve("invitecode.json") + val first = StoredPlayer(UUID.randomUUID(), Instant.parse("2026-09-23T00:00:00Z"), "First") + val second = StoredPlayer(UUID.randomUUID(), first.firstSeenAt, "Second") + JsonInviteCodeStorage.open(file, guard).use { storage -> + storage.savePlayer(first) + storage.savePlayer(second) + } + JsonInviteCodeStorage.open(file, guard).use { storage -> + assertEquals(first, storage.player(first.id)) + assertEquals(second, storage.player(second.id)) + } + val previous = file.resolveSibling("invitecode.json.previous") + assertTrue(Files.exists(previous)) + val text = String(Files.readAllBytes(previous), StandardCharsets.UTF_8) + assertTrue(text.contains(first.id.toString())) + } + + @Test + fun `corrupt JSON is rejected without changing source`() { + val file = directory.resolve("invitecode.json") + Files.write(file, "{not-json".toByteArray(StandardCharsets.UTF_8)) + val before = Files.readAllBytes(file) + val error = assertThrows(JsonStorageException::class.java) { + JsonInviteCodeStorage.open(file, guard) + } + assertTrue(error.message!!.contains("damaged")) + assertTrue(before.contentEquals(Files.readAllBytes(file))) + } + + @Test + fun `unsupported format fails closed`() { + val file = directory.resolve("invitecode.json") + JsonInviteCodeStorage.open(file, guard).close() + val content = String(Files.readAllBytes(file), StandardCharsets.UTF_8) + .replace("\"format-version\": 1", "\"format-version\": 999") + Files.write(file, content.toByteArray(StandardCharsets.UTF_8)) + val error = assertThrows(JsonStorageException::class.java) { + JsonInviteCodeStorage.open(file, guard) + } + assertTrue(error.message!!.contains("unsupported")) + assertTrue(String(Files.readAllBytes(file), StandardCharsets.UTF_8).contains("999")) + } + + @Test + fun `second writer is rejected and first writer remains usable`() { + val file = directory.resolve("invitecode.json") + JsonInviteCodeStorage.open(file, guard).use { first -> + assertThrows(JsonStorageException::class.java) { JsonInviteCodeStorage.open(file, guard) } + val player = StoredPlayer(UUID.randomUUID(), Instant.parse("2026-09-23T00:00:00Z")) + first.savePlayer(player) + assertEquals(player, first.player(player.id)) + } + JsonInviteCodeStorage.open(file, guard).close() + } + + @Test + fun `operator can restore previous valid snapshot after corruption`() { + val file = directory.resolve("invitecode.json") + val first = StoredPlayer(UUID.randomUUID(), Instant.parse("2026-09-23T00:00:00Z")) + JsonInviteCodeStorage.open(file, guard).use { storage -> + storage.savePlayer(first) + storage.savePlayer(StoredPlayer(UUID.randomUUID(), first.firstSeenAt)) + } + Files.write(file, "broken".toByteArray(StandardCharsets.UTF_8)) + assertThrows(JsonStorageException::class.java) { JsonInviteCodeStorage.open(file, guard) } + Files.copy(file.resolveSibling("invitecode.json.previous"), file, REPLACE_EXISTING) + JsonInviteCodeStorage.open(file, guard).use { assertEquals(first, it.player(first.id)) } + } + + @Test + fun `reward delivery and transition survive reopen`() { + val file = directory.resolve("invitecode.json") + val now = Instant.parse("2026-09-23T00:00:00Z") + val recipient = UUID.randomUUID() + val delivery = StoredRewardDelivery( + UUID.randomUUID(), null, "welcome", RewardDeliveryStatus.PENDING, + "welcome:$recipient", now, now, + ) + val action = StoredRewardAction( + UUID.randomUUID(), delivery.id, null, recipient, 0, "MESSAGE", "welcome.message", + RewardActionStatus.PENDING, "${delivery.idempotencyKey}:0", now, now, + ) + JsonInviteCodeStorage.open(file, guard).use { storage -> + storage.savePlayer(StoredPlayer(recipient, now)) + storage.saveRewardDelivery(delivery, listOf(action)) + storage.saveRewardAction(action.copy(status = RewardActionStatus.PROCESSING, updatedAt = now.plusSeconds(1))) + } + JsonInviteCodeStorage.open(file, guard).use { storage -> + assertEquals(RewardActionStatus.PROCESSING, storage.rewardAction(action.id)?.status) + assertEquals(2, storage.rewardActionTransitions(action.id).size) + assertEquals(1, storage.recoverInterruptedRewardActions(now.plusSeconds(2))) + } + JsonInviteCodeStorage.open(file, guard).use { storage -> + assertEquals(RewardActionStatus.UNCERTAIN, storage.rewardAction(action.id)?.status) + assertEquals(3, storage.rewardActionTransitions(action.id).size) + } + } +} diff --git a/invitecode-storage-json/src/test/kotlin/io/github/command1264/invitecode/storage/json/JsonStorageContractTest.kt b/invitecode-storage-json/src/test/kotlin/io/github/command1264/invitecode/storage/json/JsonStorageContractTest.kt new file mode 100644 index 0000000..4e636f0 --- /dev/null +++ b/invitecode-storage-json/src/test/kotlin/io/github/command1264/invitecode/storage/json/JsonStorageContractTest.kt @@ -0,0 +1,17 @@ +package io.github.command1264.invitecode.storage.json + +import io.github.command1264.invitecode.core.InviteCodeStorage +import io.github.command1264.invitecode.core.StorageContractTest +import io.github.command1264.invitecode.storage.sql.BlockingOperationGuard +import org.junit.jupiter.api.io.TempDir +import java.nio.file.Path + +class JsonStorageContractTest : StorageContractTest() { + @TempDir lateinit var temporaryDirectory: Path + + override fun withStorage(test: (InviteCodeStorage) -> Unit) { + JsonInviteCodeStorage.open( + temporaryDirectory.resolve("contract.json"), BlockingOperationGuard { }, + ).use(test) + } +} diff --git a/invitecode-storage-sql/build.gradle.kts b/invitecode-storage-sql/build.gradle.kts index 93a8777..9b4a0a6 100644 --- a/invitecode-storage-sql/build.gradle.kts +++ b/invitecode-storage-sql/build.gradle.kts @@ -2,6 +2,7 @@ description = "Shared SQLite and MySQL storage contracts and migrations." dependencies { implementation(project(":invitecode-core")) + testImplementation(testFixtures(project(":invitecode-core"))) implementation("org.xerial:sqlite-jdbc:3.53.4.0") implementation("com.mysql:mysql-connector-j:26.7.0") implementation("com.zaxxer:HikariCP:4.0.3") diff --git a/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqliteSnapshotAccess.kt b/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqliteSnapshotAccess.kt new file mode 100644 index 0000000..0d7e431 --- /dev/null +++ b/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqliteSnapshotAccess.kt @@ -0,0 +1,16 @@ +package io.github.command1264.invitecode.storage.sql + +import java.nio.file.Path +import java.sql.Connection + +/** Uses the bundled driver loader, which also works under legacy Bukkit plugin class loaders. */ +object SqliteSnapshotAccess { + fun withConnection( + database: Path, + guard: BlockingOperationGuard, + operation: (Connection) -> T, + ): T { + guard.checkAllowed() + return connect(database).use(operation) + } +} diff --git a/invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/MysqlIntegrationTest.kt b/invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/MysqlIntegrationTest.kt index f5522e3..d5fe401 100644 --- a/invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/MysqlIntegrationTest.kt +++ b/invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/MysqlIntegrationTest.kt @@ -1,5 +1,7 @@ package io.github.command1264.invitecode.storage.sql +import io.github.command1264.invitecode.core.StorageContractTest + import com.zaxxer.hikari.HikariDataSource import io.github.command1264.invitecode.core.ClaimConfirmation import io.github.command1264.invitecode.core.ClaimEligibilityPolicy diff --git a/invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/StorageContractTest.kt b/invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/StorageContractTest.kt index b54b78c..63ccdf0 100644 --- a/invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/StorageContractTest.kt +++ b/invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/StorageContractTest.kt @@ -1,58 +1,9 @@ package io.github.command1264.invitecode.storage.sql import io.github.command1264.invitecode.core.InviteCodeStorage -import io.github.command1264.invitecode.core.StoredPlayer -import io.github.command1264.invitecode.core.StoredRewardAction -import io.github.command1264.invitecode.core.StoredRewardDelivery -import io.github.command1264.invitecode.core.RewardActionStatus -import io.github.command1264.invitecode.core.RewardDeliveryStatus -import org.junit.jupiter.api.Assertions.assertEquals -import org.junit.jupiter.api.Test +import io.github.command1264.invitecode.core.StorageContractTest import org.junit.jupiter.api.io.TempDir import java.nio.file.Path -import java.time.Instant -import java.time.LocalDate -import java.util.UUID - -abstract class StorageContractTest { - protected abstract fun withStorage(test: (InviteCodeStorage) -> Unit) - - @Test - fun `player identity and unique login days survive storage operations`() = withStorage { storage -> - val id = UUID.randomUUID() - val firstSeen = Instant.parse("2026-09-22T00:00:00Z") - storage.savePlayer(StoredPlayer(id, firstSeen, "Original")) - storage.savePlayer(StoredPlayer(id, firstSeen.plusSeconds(5), "Latest")) - storage.recordLoginDay(id, LocalDate.parse("2026-09-22")) - storage.recordLoginDay(id, LocalDate.parse("2026-09-22")) - assertEquals(StoredPlayer(id, firstSeen, "Latest"), storage.player(id)) - assertEquals(1, storage.loginDays(id)) - } - - @Test - fun `reward state and transition history are durable`() = withStorage { storage -> - val recipient = UUID.randomUUID() - val now = Instant.parse("2026-09-22T00:00:00Z") - val deliveryId = UUID.randomUUID() - val actionId = UUID.randomUUID() - storage.savePlayer(StoredPlayer(recipient, now)) - val delivery = StoredRewardDelivery( - deliveryId, null, "first-milestone", RewardDeliveryStatus.PENDING, - "milestone:$recipient:1:first-milestone", now, now, - ) - val action = StoredRewardAction( - actionId, deliveryId, null, recipient, 0, "MESSAGE", "hello", - RewardActionStatus.PENDING, "${delivery.idempotencyKey}:0", now, now, - ) - storage.saveRewardDelivery(delivery, listOf(action)) - assertEquals(delivery, storage.rewardDelivery(deliveryId)) - assertEquals(listOf(action), storage.rewardActions(deliveryId)) - storage.saveRewardAction(action.copy(status = RewardActionStatus.PROCESSING, updatedAt = now.plusSeconds(1))) - assertEquals(1, storage.recoverInterruptedRewardActions(now.plusSeconds(2))) - assertEquals(RewardActionStatus.UNCERTAIN, storage.rewardAction(actionId)?.status) - assertEquals(3, storage.rewardActionTransitions(actionId).size) - } -} class SqliteStorageContractTest : StorageContractTest() { @TempDir lateinit var temporaryDirectory: Path