diff --git a/AGENTS.md b/AGENTS.md index 19a77f0..436d3f1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,6 +1,6 @@ # InviteCodeKt Agent 指引 -InviteCodeKt 是跨 Minecraft 版本的邀請與推薦獎勵插件。修改領域行為前,先閱讀 `CONTEXT.md`、`docs/adr/` 下相關 ADR,以及授權該工作的 GitHub issue。 +InviteCodeKt repository 開發的產品名稱是 InviteCode,它是跨 Minecraft 版本的邀請與推薦獎勵插件。修改領域行為前,先閱讀 `CONTEXT.md`、`docs/adr/` 下相關 ADR,以及授權該工作的 GitHub issue。 平台無關行為放在 `invitecode-core`。新版 Paper 或 Spigot API reference 放在 `invitecode-platform-modern`,不得引入 NMS。除非已接受的新 ADR 明確改變決策,否則必須保留既有的 storage、privacy、reward delivery 與 Java 8 相容性邊界。 diff --git a/CHANGELOG.md b/CHANGELOG.md index bcc1881..6045be5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,5 +11,10 @@ - Java 8 bytecode 驗證與初始 CI workflow。 - 最小 Bukkit 插件 metadata 與設定範例。 - SQLite persistence adapter、明確 schema migration、原子 Claim/Reward Delivery、可稽核且具復原流程的 Reward 狀態歷史,以及跨重啟 repository contract tests。 +- Claim 防濫用使用獨立 HMAC-SHA-256 密鑰與 30 天到期網路雜湊,支援 `ALLOW`/`WARN`/`DENY`,不保存或記錄原始 IP 與雜湊。 - 可設定的 Qualification Policy、內建與外部 condition provider、短路求值、不可逆 qualification,以及 Qualification Fact 的 SQLite transaction。 - Qualification 與 Inviter milestone 獎勵規劃、穩定冪等鍵、先保存後執行的 Reward Action 狀態流程、離線補發邊界、失敗復原與 Vault Economy adapter。 +- Bukkit runtime 狀態、版本化 YAML 與語系 snapshot、明確 SQLite migration/maintenance mode,以及不阻塞 server main thread 的單一背景 executor。 +- 全新 SQLite 安裝會在首次啟動自動建立 schema 與防濫用密鑰;既有資料庫升級仍使用明確 migration。 +- 玩家 Invite Code、Claim Confirmation、私密聊天輸入、status/stats、登入日 Qualification 與 Pending Reward 補發流程。 +- 可稽核的 Invitation、Eligibility、Reward、Code Rotation 與 Storage 管理指令,以及唯讀 doctor 與原子 reload。 diff --git a/README.md b/README.md index 384d054..871619d 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ -# InviteCodeKt +# InviteCode -InviteCodeKt 是從零重寫的 Kotlin Minecraft 邀請與推薦獎勵插件。目標是以單一可安裝 JAR 支援 Spigot 與 Paper 1.8.8 到最新已測試版本,並透過隔離的 adapter 載入新版能力。 +InviteCode 是從零重寫的 Kotlin Minecraft 邀請與推薦獎勵插件;`InviteCodeKt` 是 repository 名稱,`Kt` 只表示實作使用 Kotlin。目標是以單一可安裝 JAR 支援 Spigot 與 Paper 1.8.8 到最新已測試版本,並透過隔離的 adapter 載入新版能力。 > [!IMPORTANT] -> 這個 repository 目前是 `0.1.0-SNAPSHOT`。平台無關的 Invitation 核心狀態機、Invite Code lifecycle、SQLite adapter、Qualification Policy 與可復原的 Reward Delivery 已實作;Minecraft 平台工作流程尚未完成串接。 +> 這個 repository 目前是 `0.1.0-SNAPSHOT`。舊版相容的 Bukkit 指令、聊天輸入、SQLite lifecycle、Qualification 與可復原 Reward Delivery 已完成串接;新版原生 Dialog 與跨版本真實伺服器矩陣仍由後續 Issue 驗收。 ## 專案目標 @@ -42,7 +42,7 @@ mise exec java@local-8 -- .\gradlew.bat clean check shadowJar 可安裝的骨架 JAR 會輸出至: ```text -invitecode-plugin/build/libs/InviteCodeKt-0.1.0-SNAPSHOT.jar +invitecode-plugin/build/libs/InviteCode-0.1.0-SNAPSHOT.jar ``` 所有本機 Java、Gradle 建置與測試指令都必須透過 `mise exec` 執行。Gradle Wrapper 仍由 repository 管理。建置流程會驗證目前 production class 使用 Java 8 bytecode。未來的新版 adapter 只有在 class 維持隔離,並驗證舊版 JVM 不會載入時,才可使用新版 bytecode。 @@ -60,7 +60,9 @@ invitecode-plugin/build/libs/InviteCodeKt-0.1.0-SNAPSHOT.jar - 所有 SQLite 入口都要求 `BlockingOperationGuard`;Minecraft adapter 必須用它拒絕 server main thread,並在專用 executor 呼叫同步 storage interface。 - storage 錯誤會拒絕當次操作,不會自動切換成 memory、JSON 或其他 backend。 -目前 SQLite persistence 已有暫存資料庫 contract tests;插件啟動、設定載入與 executor 串接會在 Bukkit 工作流程 Issue 完成。 +SQLite persistence 具備暫存資料庫 contract tests,插件只在專用 executor 執行 blocking I/O。全新安裝會自動建立 SQLite schema 與所需密鑰;既有資料庫的 schema 更新仍須使用明確的 `admin storage migrate`。完整操作方式請參閱 [`docs/operations/bukkit-workflow.md`](./docs/operations/bukkit-workflow.md)。 + +Claim 防濫用只保存由 `anti-abuse.key` 產生、具期限的 HMAC-SHA-256 網路雜湊,不保存原始 IP;預設保留 30 天,並可設定相符時 `ALLOW`、`WARN` 或 `DENY`。密鑰由全新 SQLite 首次初始化建立,需隨 SQLite 備份且不得提交版本控制。 ## Qualification Policy @@ -68,13 +70,13 @@ invitecode-plugin/build/libs/InviteCodeKt-0.1.0-SNAPSHOT.jar 內建 provider 涵蓋遊玩時間、Claim 後經過時間、不同登入日數、管理員核准、permission 與 Placeholder 比較。Permission 與 Placeholder 值由平台 adapter 注入,核心不直接依賴 Bukkit 或 PlaceholderAPI。Qualification 通過時,Qualified Invitation 與造成通過的 facts 透過 storage transaction 原子保存;一般 reevaluation 不會反轉既有 qualification。 -設定格式、condition 參數與外部 provider 契約請參閱 [`docs/configuration/qualifications.md`](./docs/configuration/qualifications.md)。實際讀取 `qualifications.yml`、收集 Bukkit/Placeholder 值及 executor 排程會在 Bukkit 工作流程 Issue 串接。 +設定格式、condition 參數與外部 provider 契約請參閱 [`docs/configuration/qualifications.md`](./docs/configuration/qualifications.md)。Bukkit workflow 會收集遊玩時間、不同登入日、Permission 與 PlaceholderAPI 值,並定期重新評估;外部插件可由 Bukkit ServicesManager 取得 `InviteCodeApi`。 ## Reward Delivery Qualification Reward 與 Inviter Milestone Reward 會先以穩定冪等鍵保存完整 Delivery/Action,再執行訊息、Console 指令、玩家指令或 Vault 經濟獎勵。玩家離線或 Vault integration 暫時不可用時維持 `PENDING`;外部結果無法判定時轉為 `UNCERTAIN`,只允許具稽核資訊的管理操作決定重試或視為已交付。 -設定格式、placeholder、離線補發及失敗復原流程請參閱 [`docs/configuration/rewards.md`](./docs/configuration/rewards.md)。實際讀取 `rewards.yml`、登入補發、啟動復原與管理指令會在 Bukkit 工作流程 Issue 串接。 +設定格式、placeholder、離線補發及失敗復原流程請參閱 [`docs/configuration/rewards.md`](./docs/configuration/rewards.md)。Bukkit workflow 已串接玩家登入補發、啟動復原、Vault Economy 與具 actor/reason 的人工處理指令。 ## 分支 diff --git a/SECURITY.md b/SECURITY.md index 9a9fd4a..8bfed35 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -1,6 +1,6 @@ # 安全政策 -InviteCodeKt 尚未發布穩定版本。 +InviteCode 尚未發布穩定版本。 疑似漏洞請私下回報 repository owner。請勿在公開 issue 中附上資料庫憑證、原始 IP 位址、IP hash、玩家資料匯出內容或可利用漏洞的細節。 diff --git a/docs/adr/0001-single-cross-version-plugin-jar.md b/docs/adr/0001-single-cross-version-plugin-jar.md index 3d126e9..1195961 100644 --- a/docs/adr/0001-single-cross-version-plugin-jar.md +++ b/docs/adr/0001-single-cross-version-plugin-jar.md @@ -1,3 +1,5 @@ # 發布單一跨版本插件 JAR -InviteCodeKt 以一個可安裝 JAR 支援 Spigot 與 Paper 1.8.8 到最新已測試版本。平台無關與舊版程式碼以 Java 8 為目標且不使用 NMS;新版伺服器 API reference 放在隔離的 capability adapter,避免舊版 JVM 載入不相容的 class。這個決策讓安裝方式保持簡單,同時接受必須維護具代表性真實伺服器相容性矩陣的成本。 +InviteCode 以一個可安裝 JAR 支援 Spigot 與 Paper 1.8.8 到最新已測試版本。平台無關與舊版程式碼以 Java 8 為目標且不使用 NMS;新版伺服器 API reference 放在隔離的 capability adapter,避免舊版 JVM 載入不相容的 class。這個決策讓安裝方式保持簡單,同時接受必須維護具代表性真實伺服器相容性矩陣的成本。 + +`plugin.yml` 宣告 `api-version: '1.13'`,使 1.13 以上伺服器不以 legacy plugin 模式載入;1.8–1.12 的舊版 Bukkit loader 會忽略當時尚未定義的欄位。跨版本更名的 Bukkit enum 不得直接連結單一版本的欄位,必須由 compatibility boundary 以名稱解析。 diff --git a/docs/adr/0003-explicit-storage-migration.md b/docs/adr/0003-explicit-storage-migration.md index 9d38be8..c4afdb3 100644 --- a/docs/adr/0003-explicit-storage-migration.md +++ b/docs/adr/0003-explicit-storage-migration.md @@ -1,3 +1,5 @@ -# 只能透過明確遷移流程切換 Storage +# 全新 Storage 自動初始化,既有資料只透過明確遷移流程變更 -SQLite 與 MySQL 是 production backend;JSON 僅用於小型安裝環境與資料交換。變更 backend 設定時,不得在一般啟動或 reload 過程自動遷移資料。切換時必須執行明確的 preflight、migration、verification 與 cutover 流程;失敗時保留來源資料,避免在未察覺的情況下產生兩份各自寫入的資料。 +SQLite 與 MySQL 是 production backend;JSON 僅用於小型安裝環境與資料交換。選定 backend 尚未存在任何資料時,插件會在首次啟動自動建立該 backend 所需的 schema、metadata 與本機 secret,讓全新安裝可直接使用。自動初始化失敗時只清理由該次嘗試建立、尚未承載使用者資料的檔案,並進入可診斷的安全失敗狀態。 + +既有 backend 的 schema 升級、backend 切換與資料搬移不得在一般啟動或 reload 過程自動執行。這些操作必須使用明確的 preflight、migration、verification 與 cutover 流程;失敗時保留來源資料,避免在未察覺的情況下改寫資料或產生兩份各自寫入的資料。檔案或連線存在即視為既有 backend,不因內容異常而退回全新初始化。 diff --git a/docs/agents/domain.md b/docs/agents/domain.md index 1453ebf..ac8a337 100644 --- a/docs/agents/domain.md +++ b/docs/agents/domain.md @@ -1,6 +1,6 @@ # 領域文件 -InviteCodeKt 是單一 domain context 的 repository。 +InviteCodeKt 是開發 InviteCode 產品的單一 domain context repository。 修改領域行為前: diff --git a/docs/configuration/qualifications.md b/docs/configuration/qualifications.md index a871540..22ddbf6 100644 --- a/docs/configuration/qualifications.md +++ b/docs/configuration/qualifications.md @@ -49,6 +49,8 @@ Permission、Placeholder 或外部 provider 不存在時,condition 預設產 外部插件透過 `InviteCodeApi.registerQualificationConditionProvider` 註冊 `QualificationConditionProvider`。`type` 不分大小寫且同一時間只能有一個 provider;停用插件時必須關閉回傳的 `QualificationProviderRegistration`。外部插件可透過 `requestQualificationEvaluation` 要求重新評估指定 Invitation。 +Bukkit 插件可由 `Bukkit.getServicesManager().load(InviteCodeApi.class)` 取得執行中的 API。API 查詢與重新評估回傳 `CompletionStage`,不得在 server main thread 阻塞等待結果;插件停用或 SQLite 不可用時會以 exceptional completion 回報。 + Provider 的 `evaluate` 必須快速、不可阻塞,並依傳入 context 與唯讀參數回傳 `SATISFIED`、`UNSATISFIED` 或 `UNKNOWN`。需要 Bukkit 主執行緒的資料應先由平台工作流程建立快照,再交給 qualification executor;provider 不得自行執行資料庫或網路 I/O。 ## 保存與重新評估 diff --git a/docs/configuration/rewards.md b/docs/configuration/rewards.md index f137dd5..836d3d5 100644 --- a/docs/configuration/rewards.md +++ b/docs/configuration/rewards.md @@ -67,6 +67,6 @@ Action 執行流程如下: ## 執行緒邊界 -`RewardDeliveryProcessor` 會呼叫同步 storage interface,必須在專用 storage executor 執行,不可在 Minecraft server main thread 執行。Bukkit environment 只把需要 Bukkit API 的在線狀態、訊息、指令與 Vault 操作切回 server main thread。 +`AsyncRewardDeliveryWorkflow` 會把同步 storage transition 排入專用 executor,將在線狀態、訊息、指令與 Vault 外部效果以 continuation 切回 server main thread,再回到 executor 保存結果。任何背景執行緒都不會同步等待 server main thread。 -目前核心規劃、狀態處理、SQLite persistence 與 Bukkit/Vault adapter 已具備;實際載入 `rewards.yml`、玩家上線補發、啟動復原及管理指令會由 Bukkit 工作流程 Issue 串接。 +目前核心規劃、狀態處理、SQLite persistence、Bukkit/Vault adapter、`rewards.yml` 載入、玩家上線補發、啟動復原及管理指令均已串接。 diff --git a/docs/operations/bukkit-workflow.md b/docs/operations/bukkit-workflow.md new file mode 100644 index 0000000..57bc5ae --- /dev/null +++ b/docs/operations/bukkit-workflow.md @@ -0,0 +1,88 @@ +# Bukkit 操作與維護 + +本文件說明 InviteCode 在 Spigot/Paper 上的玩家流程、管理指令、SQLite 初始化、維護模式與人工驗收方式。Issue #10 使用 SQLite;選擇 `MYSQL` 或 `JSON` 會明確拒絕啟動,不會自動退回其他儲存方式。 + +## 首次啟動 + +插件的 Bukkit 名稱與資料夾均為 `InviteCode`。JAR 內的預設 YAML 集中在 `config/`,首次啟動時會輸出至 `plugins/InviteCode/`,不在資料夾中另外建立 `config/` 層級。設定選擇 SQLite 且資料庫檔案尚不存在時,第一次啟動會自動建立最新 schema 與 32-byte 的 `anti-abuse.key`,接著直接進入可用狀態,不要求管理員執行初始化指令。 + +`anti-abuse.key` 是 32 bytes 的隨機二進位 IP 防濫用 HMAC 密鑰,不是 ANSI、UTF-8 或其他文字編碼的文字檔;用文字編輯器開啟時顯示亂碼是正常現象,不得手動編輯。它必須像資料庫一樣備份並限制檔案讀取權限;不得提交 Git、貼到 Issue 或輸出至 log。後續啟動只讀取既有密鑰,不會自行取代。既有資料庫缺少密鑰、密鑰內容無效或 schema 版本不符時,插件會進入維護模式,不會把它當成全新安裝或自動升級。修復密鑰或執行明確 migration 後必須重啟;密鑰變更後,啟動時會清除由其他密鑰產生、已無法比較的舊雜湊。 + +`/invitecode admin storage migrate SQLITE ` 保留給既有 SQLite schema 升級與人工復原。`doctor` 不會建立資料庫或執行 migration。 + +維護模式只允許 `help`、`admin doctor` 與 `admin storage migrate`。設定錯誤須修正檔案並重新啟動;正常模式可用 `/invitecode reload` 驗證所有 YAML 後原子替換設定快照。`/invitecode admin reload` 保留為相容路徑。 + +## 玩家指令 + +Console 可使用 `/invitecode`、`/invitecode help` 與管理指令。需要玩家身分與狀態的 `code`、`claim`、`confirm`、`cancel`、`status` 與 `stats` 會明確回覆只限玩家使用。 + +Tab 建議會依發送者身分、權限與當前參數位置篩選。已完成的指令、不明路徑、Invite Code、UUID、reason 與超出語法長度的位置會回傳空集合,不會退回顯示所有線上玩家。 + +| 指令 | 權限 | 行為 | +| --- | --- | --- | +| `/invitecode help` | `invitecode.command.basic` | 顯示基本操作。 | +| `/invitecode code` | `invitecode.command.code` | 建立或顯示自己的 Invite Code;建立後即成為 Inviter。 | +| `/invitecode claim ` | `invitecode.command.claim` | 驗證有效 Invite Code,顯示限時確認,不會直接建立 Invitation。 | +| `/invitecode claim` | `invitecode.command.claim` | `CHAT`/`AUTO` 時私密擷取下一則聊天;`COMMAND_ONLY` 顯示完整用法。 | +| `/invitecode confirm` | `invitecode.command.claim` | 在確認期限內原子建立 Invitation。 | +| `/invitecode cancel` | `invitecode.command.claim` | 取消目前輸入或確認。 | +| `/invitecode status` | `invitecode.command.status` | 顯示 Claim Eligibility、Invitation 狀態與待補發 Reward 數。 | +| `/invitecode stats` | `invitecode.command.stats` | 顯示等待資格與已達資格的邀請數。 | + +聊天輸入會先取消公開聊天,再送入背景流程;原始訊息不會寫入 log。輸入、確認、逾時、成功、取消、登出或停用插件後,短期 Session 都會失效。玩家一旦建立 Invite Code、已有 Invitation,或超過 Claim Window,就不能使用他人的 Invite Code。 + +玩家登入時,插件會以 `anti-abuse.key` 對正規化網路位址執行 HMAC-SHA-256,SQLite 只保存雜湊、密鑰識別碼與觀察/到期時間,絕不保存原始 IP。`anti-abuse.ip-hash-retention` 預設為 30 天;到期資料會在玩家登入時清除。邀請人與受邀人有尚未到期的相同雜湊時,`matching-ip-action` 的行為如下: + +| 值 | 行為 | +| --- | --- | +| `ALLOW` | 不執行相符檢查,正常處理 Claim。 | +| `WARN` | 建立 Invitation,通知玩家並在 log 記錄雙方 UUID;不記錄 IP 或雜湊。 | +| `DENY` | 不建立 Invitation,通知玩家並在 log 記錄雙方 UUID;不記錄 IP 或雜湊。 | + +`HEX_COLOR` 會產生六碼十六進位 Invite Code,並以該 RGB 值最接近的舊版聊天色顯示。`CROCKFORD_BASE32` 目前使用固定八碼。新版原生 Dialog 屬於 Issue #11;本流程保留 command 與 chat fallback。 + +## 管理指令 + +所有修改指令最後都要提供非空白 `reason`。玩家參照接受完整 UUID 或唯一的已知名稱;未知或重複名稱會拒絕操作。 + +```text +/invitecode admin inspect player <玩家> +/invitecode admin inspect invitation +/invitecode admin inspect reward +/invitecode admin invitation unlink +/invitecode admin invitation transfer <新 Inviter> +/invitecode admin invitation force-qualify +/invitecode admin eligibility reset <玩家> +/invitecode admin reward retry +/invitecode admin reward mark-delivered +/invitecode admin code rotate <玩家> +/invitecode admin storage migrate SQLITE +/invitecode reload +/invitecode admin doctor +``` + +`/invitecode admin reload` 仍可使用,但說明與 Tab 建議以較直接的 `/invitecode reload` 為主。 + +Invitation、Eligibility、Code Rotation 與 Storage Migration 會留下 actor、reason 與 Audit Record;Reward 的人工決定會留下 Reward transition。`retry` 與 `mark-delivered` 只接受 `UNCERTAIN` Action。Force Qualification 會在同一 SQLite transaction 保存 Qualification、Audit Record 與完整 Reward plans。 + +## Qualification 與 Reward 復原 + +玩家登入、Claim 成功及每分鐘在線檢查會更新名稱、登入日與遊玩時間,然後重新評估仍為 `CLAIMED` 的 Invitation。第一次達成資格時,Qualified Invitation、Qualification Facts 與 Reward Delivery/Action 會原子保存。 + +玩家登入會補發自己的 `PENDING` Reward。玩家離線或 Vault Economy 不可用時維持 `PENDING`。插件啟動會先把上次中斷於 `PROCESSING` 的 Action 轉成 `UNCERTAIN`;這類外部結果不得自動重試,必須由管理員檢查後決定。 + +背景 executor 執行 SQLite 與 Qualification/Reward orchestration;Bukkit、聊天、指令、訊息與 Vault 操作只在 server main thread 執行。停用時會停止接受新工作並有界等待,不會讓背景執行緒同步等待主執行緒。 + +## 人工驗收 + +1. 在全新測試伺服器安裝 JAR,確認首次啟動自動建立 SQLite 與 `anti-abuse.key`,並直接進入可用狀態。 +2. 重啟伺服器,確認既有 SQLite 與 `anti-abuse.key` 直接開啟,且 schema 不會再次變更。舊 schema 拒絕自動升級的行為由合成資料庫自動化測試覆蓋;目前沒有既有使用者資料,因此不列為人工驗收要求。 +3. 讓玩家 A 建立 Invite Code;確認 A 不能再 Claim。玩家 B 分別以 command 與聊天輸入,確認聊天未公開、必須再執行 `confirm` 才建立 Invitation。 +4. 驗證自邀、錯碼、輪替後舊碼、逾時、重複 Claim 與過期 Claim Window 均被拒絕。 +5. 讓兩名測試玩家從同一網路登入,分別驗證 `DENY` 拒絕、`WARN` 允許並提示、`ALLOW` 直接允許;確認資料庫與 log 均沒有原始 IP,log 也沒有網路雜湊。 +6. 達成 Qualification 條件,確認 Invitation、Facts 與 Reward plans 出現;離線收件者重新登入後收到 Pending Reward。 +7. 在測試用 Reward 外部效果期間強制停止伺服器,重啟後確認 Action 為 `UNCERTAIN`,再驗證兩個人工處理指令與 transition history。 +8. 修改一份 YAML 為無效值後執行 reload,確認舊 snapshot 仍有效;恢復後再 reload。修改 `storage.yml` 時確認提示重新啟動/明確 cutover,而不熱切換。 +9. 以一般玩家、無權限管理員、Console 分別驗證權限與玩家專用限制;切換 `zh_TW`/`en_US`,確認語系 fallback 與缺鍵紀錄。 + +跨 Minecraft 版本的真實伺服器矩陣由 Issue #12 執行。 diff --git a/docs/spec/invitecode-1.0.md b/docs/spec/invitecode-1.0.md index be811b6..37b4f7a 100644 --- a/docs/spec/invitecode-1.0.md +++ b/docs/spec/invitecode-1.0.md @@ -1,15 +1,15 @@ -# InviteCodeKt 1.0 設計規格 +# InviteCode 1.0 設計規格 ## 產品邊界 -InviteCodeKt 在一名 Inviter 與一名 Invitee 之間建立一筆持久的 Invitation,依可設定的 policy 判定該 Invitation 是否符合資格,並交付可稽核的獎勵。這是新的產品線:舊版原始碼、設定與 `playerData.json` 只作為參考,不提供相容層或 importer。 +InviteCode 在一名 Inviter 與一名 Invitee 之間建立一筆持久的 Invitation,依可設定的 policy 判定該 Invitation 是否符合資格,並交付可稽核的獎勵。這是新的產品線:舊版原始碼、設定與 `playerData.json` 只作為參考,不提供相容層或 importer。 ## Invitation 生命週期 - 每位玩家都擁有自動產生的 Invite Code,但只有另一名玩家 Claim 該邀請碼後,擁有者才成為 Inviter。 - 一名 Invitee 最多只能有一名 Inviter;一名 Inviter 可以有多名 Invitee。 - 玩家只有在沒有 Invitation、尚未成為 Inviter,且仍在 Claim Window 內時才可 Claim。 -- First Seen At 是 InviteCodeKt 首次觀察到該玩家的時間;Claim Window 預設為 24 小時。 +- First Seen At 是 InviteCode 首次觀察到該玩家的時間;Claim Window 預設為 24 小時。 - Claim 必須經過 30 秒內完成的確認,確認畫面顯示目前的 Inviter 名稱與邀請碼。 - Claimed Invitation 只能成為 Qualified Invitation 一次;Qualification 為永久狀態。 - 一般玩家不能撤銷 Invitation。可稽核的管理操作支援 Unlink、Eligibility Reset、未 qualified Invitation 的 Transfer,以及 Force Qualification。 @@ -46,7 +46,9 @@ InviteCodeKt 在一名 Inviter 與一名 Invitee 之間建立一筆持久的 Inv - SQLite 與 MySQL 是 production backend;MySQL 必須在多個 plugin instance 同時操作時仍維持正確性。 - JSON 用於小型安裝環境、測試與有版本的資料交換。 +- 全新 backend 在首次啟動時自動建立 schema、metadata 與所需 secret,不要求管理員先執行初始化指令。 - 切換 backend 時必須執行明確的 migration,包含 preflight、暫停寫入、verification 與 cutover。 +- 已存在 backend 的 schema 升級不得在一般啟動時自動執行。 - Storage 發生錯誤時採拒絕操作的安全失敗模式;插件不得退回 memory 或其他 backend。 - IP 防濫用機制保存 keyed hash 30 天,不保存原始位址。 - Anonymization 移除名稱、IP hash 與顯示資料,同時保留歷史一致性。 @@ -76,4 +78,4 @@ InviteCodeKt 在一名 Inviter 與一名 Invitee 之間建立一筆持久的 Inv - 原生 permission grant Reward Action - NMS integration - Metrics 或自動更新 -- 啟動時自動執行 storage migration +- 啟動時自動升級既有 storage schema 或搬移 backend 資料 diff --git a/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/ClaimConfirmation.kt b/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/ClaimConfirmation.kt index 1bb5654..8f51945 100644 --- a/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/ClaimConfirmation.kt +++ b/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/ClaimConfirmation.kt @@ -31,7 +31,7 @@ class ClaimConfirmation private constructor( val inviterName: String, val inviteCode: InviteCode, val presentedAt: Instant, - private val expiresAt: Instant, + val expiresAt: Instant, ) { fun confirm(confirmingPlayerId: UUID, confirmedAt: Instant): ConfirmedClaim { if (confirmingPlayerId != inviteeId) { diff --git a/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/InvitationAdministration.kt b/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/InvitationAdministration.kt index b3a335a..fd01710 100644 --- a/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/InvitationAdministration.kt +++ b/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/InvitationAdministration.kt @@ -21,6 +21,8 @@ enum class InvitationAuditAction { TRANSFERRED, FORCE_QUALIFIED, ELIGIBILITY_RESET, + CODE_ROTATED, + STORAGE_MIGRATED, } data class AuditRecord( @@ -104,6 +106,10 @@ data class AuditedInvitationTransition( InvitationAuditAction.ELIGIBILITY_RESET -> throw IllegalArgumentException( "Eligibility Reset cannot audit an Invitation transition.", ) + InvitationAuditAction.CODE_ROTATED, + InvitationAuditAction.STORAGE_MIGRATED -> throw IllegalArgumentException( + "${auditRecord.action} cannot audit an Invitation transition.", + ) } } } diff --git a/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/InvitationClaimService.kt b/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/InvitationClaimService.kt index 1552d51..96c3018 100644 --- a/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/InvitationClaimService.kt +++ b/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/InvitationClaimService.kt @@ -15,25 +15,49 @@ interface InvitationTransactions { } interface InvitationTransaction { + fun activeInviter(inviteCode: InviteCode): UUID? + fun claimState(playerId: UUID): PlayerClaimState + fun hasMatchingNetworkHash(firstPlayerId: UUID, secondPlayerId: UUID, evaluatedAt: java.time.Instant): Boolean + fun add(invitation: Invitation) } sealed class InvitationClaimResult { - data class Claimed(val invitation: Invitation) : InvitationClaimResult() + data class Claimed( + val invitation: Invitation, + val matchingNetworkHash: Boolean = false, + ) : InvitationClaimResult() data class Rejected(val eligibility: ClaimEligibility) : InvitationClaimResult() + + data class InviteCodeUnavailable(val inviteCode: InviteCode) : InvitationClaimResult() + + data class MatchingNetworkDenied( + val inviterId: UUID, + val inviteeId: UUID, + ) : InvitationClaimResult() +} + +enum class MatchingNetworkAction { + ALLOW, + WARN, + DENY, } class InvitationClaimService( private val transactions: InvitationTransactions, private val eligibilityPolicy: ClaimEligibilityPolicy, private val invitationIdGenerator: () -> UUID, + private val matchingNetworkAction: MatchingNetworkAction = MatchingNetworkAction.ALLOW, ) { fun claim(confirmedClaim: ConfirmedClaim): InvitationClaimResult = transactions.atomically( playerIds = setOf(confirmedClaim.inviterId, confirmedClaim.inviteeId), ) { transaction -> + if (transaction.activeInviter(confirmedClaim.inviteCode) != confirmedClaim.inviterId) { + return@atomically InvitationClaimResult.InviteCodeUnavailable(confirmedClaim.inviteCode) + } val eligibility = eligibilityPolicy.evaluate( state = transaction.claimState(confirmedClaim.inviteeId), evaluatedAt = confirmedClaim.confirmedAt, @@ -41,6 +65,18 @@ class InvitationClaimService( if (!eligibility.eligible) { return@atomically InvitationClaimResult.Rejected(eligibility) } + val matchingNetworkHash = matchingNetworkAction != MatchingNetworkAction.ALLOW && + transaction.hasMatchingNetworkHash( + confirmedClaim.inviterId, + confirmedClaim.inviteeId, + confirmedClaim.confirmedAt, + ) + if (matchingNetworkHash && matchingNetworkAction == MatchingNetworkAction.DENY) { + return@atomically InvitationClaimResult.MatchingNetworkDenied( + confirmedClaim.inviterId, + confirmedClaim.inviteeId, + ) + } val invitation = Invitation( id = invitationIdGenerator(), @@ -50,6 +86,9 @@ class InvitationClaimService( claimedAt = confirmedClaim.confirmedAt, ) transaction.add(invitation) - InvitationClaimResult.Claimed(invitation) + InvitationClaimResult.Claimed( + invitation, + matchingNetworkHash && matchingNetworkAction == MatchingNetworkAction.WARN, + ) } } 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 761a8d5..f264cb5 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 @@ -32,7 +32,7 @@ class InviteCode private constructor(val normalized: String) { return InviteCode(normalized) } - /** Restores a canonical value previously accepted and stored by InviteCodeKt. */ + /** Restores a canonical value previously accepted and stored by InviteCode. */ fun fromNormalized(normalized: String): InviteCode { require(normalized.isNotBlank() && normalized == normalized.trim()) { "Stored Invite Code must be a non-blank canonical value." 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 index 4a1d8c6..17ceb32 100644 --- 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 @@ -33,6 +33,28 @@ class ColorInviteCodeGenerator( } } +class CrockfordInviteCodeGenerator( + private val length: Int = 8, + private val randomBytes: RandomBytes = SecureRandomBytes(), +) : InviteCodeGenerator { + init { + require(length in 4..32) { "Crockford Base32 Invite Code length must be between 4 and 32." } + } + + override fun generate(): InviteCode { + val bytes = ByteArray(length) + randomBytes.nextBytes(bytes) + val value = buildString(length) { + bytes.forEach { byte -> append(ALPHABET[(byte.toInt() and 0xFF) % ALPHABET.length]) } + } + return InviteCode.parse(value, InviteCodeFormats.crockfordBase32(length)) + } + + private companion object { + const val ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ" + } +} + private class SecureRandomBytes( private val secureRandom: SecureRandom = SecureRandom(), ) : RandomBytes { 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 8937f81..acfa4d2 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 @@ -47,6 +47,8 @@ interface InviteCodeTransaction { previous: RetiredInviteCode, current: ActiveInviteCode, ) + + fun saveAuditRecord(record: AuditRecord) } class InviteCodeCollisionException( @@ -80,7 +82,23 @@ class InviteCodeLifecycleService( inviterId: UUID, rotatedAt: Instant, ): InviteCodeRotation = retryCollisions { - tryRotate(inviterId, rotatedAt) + tryRotate(inviterId, rotatedAt, null) + } + + fun rotate( + inviterId: UUID, + rotatedAt: Instant, + auditRecord: AuditRecord, + ): InviteCodeRotation { + require( + auditRecord.action == InvitationAuditAction.CODE_ROTATED && + auditRecord.playerId == inviterId && + auditRecord.invitationId == null && + auditRecord.occurredAt == rotatedAt, + ) { "Invite Code rotation audit must identify the Inviter and rotation time." } + return retryCollisions { + tryRotate(inviterId, rotatedAt, auditRecord) + } } private fun tryAssign( @@ -104,6 +122,7 @@ class InviteCodeLifecycleService( private fun tryRotate( inviterId: UUID, rotatedAt: Instant, + auditRecord: AuditRecord?, ): CollisionAttempt = registry.atomically { transaction -> val existing = transaction.activeCode(inviterId) ?: throw ActiveInviteCodeNotFoundException(inviterId) @@ -124,6 +143,7 @@ class InviteCodeLifecycleService( activatedAt = rotatedAt, ) transaction.replace(previous, current) + auditRecord?.let(transaction::saveAuditRecord) CollisionAttempt.Success(InviteCodeRotation(previous, current)) } diff --git a/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/PlayerReferenceResolver.kt b/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/PlayerReferenceResolver.kt new file mode 100644 index 0000000..87f0b8f --- /dev/null +++ b/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/PlayerReferenceResolver.kt @@ -0,0 +1,39 @@ +package io.github.command1264.invitecode.core + +import java.util.UUID + +sealed class PlayerReferenceResolution { + data class Found(val player: StoredPlayer) : PlayerReferenceResolution() + + object Unknown : PlayerReferenceResolution() + + data class Ambiguous(val players: List) : PlayerReferenceResolution() { + init { + require(players.size >= 2) { "An ambiguous player reference requires at least two matches." } + } + } +} + +class PlayerReferenceResolver( + private val players: PlayerLookup, +) { + fun resolve(reference: String): PlayerReferenceResolution { + require(reference.isNotBlank()) { "Player reference must not be blank." } + val playerId = try { + UUID.fromString(reference) + } catch (_: IllegalArgumentException) { + null + } + if (playerId != null) { + return players.player(playerId)?.let(PlayerReferenceResolution::Found) + ?: PlayerReferenceResolution.Unknown + } + + val matches = players.playersByLastKnownName(reference) + return when (matches.size) { + 0 -> PlayerReferenceResolution.Unknown + 1 -> PlayerReferenceResolution.Found(matches.single()) + else -> PlayerReferenceResolution.Ambiguous(matches) + } + } +} diff --git a/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/QualificationEvaluator.kt b/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/QualificationEvaluator.kt index 36441b8..477479e 100644 --- a/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/QualificationEvaluator.kt +++ b/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/QualificationEvaluator.kt @@ -11,6 +11,7 @@ import java.util.concurrent.ConcurrentHashMap class QualificationProviderRegistry( providers: Iterable = emptyList(), + private val fallback: QualificationProviderRegistry? = null, ) { private val providersByType = ConcurrentHashMap() @@ -35,10 +36,13 @@ class QualificationProviderRegistry( context: QualificationConditionContext, ): QualificationConditionOutcome { val provider = providersByType[normalizeType(condition.type)] - ?: return when (condition.onUnavailable) { + if (provider == null) { + fallback?.let { return it.evaluate(condition, context) } + return when (condition.onUnavailable) { MissingQualificationProviderOutcome.UNKNOWN -> QualificationConditionOutcome.UNKNOWN MissingQualificationProviderOutcome.UNSATISFIED -> QualificationConditionOutcome.UNSATISFIED } + } return try { provider.evaluate(context, condition.parameters) } catch (error: Exception) { diff --git a/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/QualificationRewardService.kt b/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/QualificationRewardService.kt new file mode 100644 index 0000000..1cc7d7a --- /dev/null +++ b/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/QualificationRewardService.kt @@ -0,0 +1,86 @@ +package io.github.command1264.invitecode.core + +import io.github.command1264.invitecode.api.InvitationStatus +import io.github.command1264.invitecode.api.QualificationConditionContext +import java.util.UUID + +data class QualificationRewardResult( + val qualification: QualificationServiceResult, + val rewardPlans: List, +) + +class QualificationRewardService( + private val records: QualificationRewardRecords, + private val evaluator: QualificationEvaluator, +) { + fun reevaluate( + invitationId: UUID, + policy: QualificationPolicy, + context: QualificationConditionContext, + rewards: RewardConfiguration, + ): QualificationRewardResult { + val invitation = requireNotNull(records.invitation(invitationId)) { + "Invitation $invitationId does not exist." + } + return when (invitation.status) { + InvitationStatus.QUALIFIED -> result( + QualificationEvaluationStatus.ALREADY_QUALIFIED, + invitation, + ) + InvitationStatus.UNLINKED -> result( + QualificationEvaluationStatus.NOT_APPLICABLE, + invitation, + ) + InvitationStatus.CLAIMED -> evaluateClaimed(invitation, policy, context, rewards) + } + } + + private fun evaluateClaimed( + invitation: Invitation, + policy: QualificationPolicy, + context: QualificationConditionContext, + rewards: RewardConfiguration, + ): QualificationRewardResult { + val evaluation = evaluator.evaluate(invitation, policy, context) + if (!evaluation.qualified) { + records.saveQualificationFacts(evaluation.facts) + return QualificationRewardResult( + QualificationServiceResult( + QualificationEvaluationStatus.NOT_QUALIFIED, + evaluation.invitation, + evaluation.facts, + ), + emptyList(), + ) + } + val qualified = evaluation.invitation + val qualifiedCount = records.qualifiedInvitationCount(qualified.inviterId) + 1 + val achievedAt = requireNotNull(qualified.qualifiedAt) + val qualificationPlans = rewards.qualificationRewards.toSortedMap().values.map { definition -> + RewardDeliveryPlanner.planQualification(definition, qualified) + } + val milestonePlans = rewards.milestoneRewards.toSortedMap().values + .filter { it.qualifiedInvitations == qualifiedCount } + .map { definition -> + RewardDeliveryPlanner.planMilestone(definition, qualified.inviterId, achievedAt) + } + val plans = qualificationPlans + milestonePlans + records.saveQualifiedInvitationWithRewards(qualified, evaluation.facts, plans) + return QualificationRewardResult( + QualificationServiceResult( + QualificationEvaluationStatus.QUALIFIED, + qualified, + evaluation.facts, + ), + plans, + ) + } + + private fun result( + status: QualificationEvaluationStatus, + invitation: Invitation, + ) = QualificationRewardResult( + QualificationServiceResult(status, invitation, emptyList()), + emptyList(), + ) +} 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 new file mode 100644 index 0000000..f7ae601 --- /dev/null +++ b/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/StorageConfiguration.kt @@ -0,0 +1,164 @@ +package io.github.command1264.invitecode.core + +import java.time.Duration +import java.util.Locale + +enum class StorageBackendType { + SQLITE, + MYSQL, + JSON, +} + +data class SqliteConfiguration(val file: String) { + init { + require(file.isNotBlank()) { "SQLite file must not be blank." } + require(!file.startsWith('/') && !WINDOWS_ABSOLUTE.matches(file)) { + "SQLite file must be relative to the plugin data directory." + } + val segments = file.replace('\\', '/').split('/') + require(segments.none { it.isBlank() || it == "." || it == ".." }) { + "SQLite file must not contain empty, current-directory, or parent-directory segments." + } + } + + companion object { + private val WINDOWS_ABSOLUTE = Regex("^[A-Za-z]:.*") + } +} + +data class MysqlConfiguration( + val host: String, + val port: Int, + val database: String, + val username: String, + val passwordReference: String, + val connectionTimeout: Duration, +) { + init { + require(host.isNotBlank()) { "MySQL host must not be blank." } + require(port in 1..65535) { "MySQL port must be between 1 and 65535." } + require(database.isNotBlank()) { "MySQL database must not be blank." } + require(username.isNotBlank()) { "MySQL username must not be blank." } + require(passwordReference.isNotBlank()) { "MySQL password reference must not be blank." } + require(!connectionTimeout.isZero && !connectionTimeout.isNegative) { + "MySQL connection timeout must be greater than zero." + } + } +} + +data class StorageConfiguration( + val version: Int, + val backend: StorageBackendType, + val sqlite: SqliteConfiguration, + val mysql: MysqlConfiguration, +) { + fun requireSupportedBackend(): StorageConfiguration { + if (backend != StorageBackendType.SQLITE) { + 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.", +) + +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()}." + } + val version = value.requiredInteger("config-version", "Storage configuration") + require(version == CURRENT_VERSION) { + "Storage config-version $version is unsupported; expected $CURRENT_VERSION." + } + val sqlite = value.requiredMap("sqlite", "Storage configuration") + require(sqlite.keys == setOf("file")) { "sqlite must contain only file." } + val mysql = value.requiredMap("mysql", "Storage configuration") + require(mysql.keys == MYSQL_KEYS) { + "mysql must contain only ${MYSQL_KEYS.sorted().joinToString()}." + } + return StorageConfiguration( + version = version, + backend = value.requiredEnum("backend", "Storage configuration"), + sqlite = SqliteConfiguration(sqlite.requiredString("file", "sqlite")), + mysql = MysqlConfiguration( + host = mysql.requiredString("host", "mysql"), + port = mysql.requiredInteger("port", "mysql"), + database = mysql.requiredString("database", "mysql"), + username = mysql.requiredString("username", "mysql"), + passwordReference = mysql.requiredString("password", "mysql"), + connectionTimeout = parsePositiveDuration( + mysql.requiredString("connection-timeout", "mysql"), + "mysql.connection-timeout", + ), + ), + ) + } + + private fun parsePositiveDuration(raw: String, location: String): Duration { + val duration = SHORT_DURATION.matchEntire(raw)?.let { match -> + val amount = match.groupValues[1].toLongOrNull() + ?: throw IllegalArgumentException("$location duration is outside the supported range.") + when (match.groupValues[2]) { + "ms" -> Duration.ofMillis(amount) + "s" -> Duration.ofSeconds(amount) + "m" -> Duration.ofMinutes(amount) + "h" -> Duration.ofHours(amount) + "d" -> Duration.ofDays(amount) + else -> error("Unreachable duration unit") + } + } ?: try { + Duration.parse(raw) + } catch (error: Exception) { + throw IllegalArgumentException("$location must be a duration such as 5s or PT5S.", error) + } + require(!duration.isZero && !duration.isNegative) { "$location must be greater than zero." } + return duration + } + + private fun Map.requiredMap(name: String, location: String): Map { + val value = this[name] + require(value is Map<*, *> && value.keys.all { it is String }) { + "$location requires map $name with string keys." + } + @Suppress("UNCHECKED_CAST") + return value as Map + } + + private fun Map.requiredString(name: String, location: String): String { + val value = this[name] + require(value is String && value.isNotBlank()) { "$location requires non-blank string $name." } + return value + } + + private fun Map.requiredInteger(name: String, location: String): Int = + (this[name] as? Number)?.toString()?.toIntOrNull() + ?: throw IllegalArgumentException("$location requires integer $name.") + + private inline fun > Map.requiredEnum( + name: String, + location: String, + ): T { + val raw = requiredString(name, location) + return try { + enumValueOf(raw.uppercase(Locale.ROOT)) + } catch (error: IllegalArgumentException) { + throw IllegalArgumentException("$location has unsupported $name '$raw'.", error) + } + } + + private val ROOT_KEYS = setOf("config-version", "backend", "sqlite", "mysql") + private val MYSQL_KEYS = setOf( + "host", + "port", + "database", + "username", + "password", + "connection-timeout", + ) + private val SHORT_DURATION = Regex("^(\\d+)(ms|s|m|h|d)$") +} diff --git a/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/StorageRecords.kt b/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/StorageRecords.kt index 9f9ebf4..d44f10e 100644 --- a/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/StorageRecords.kt +++ b/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/StorageRecords.kt @@ -1,6 +1,7 @@ package io.github.command1264.invitecode.core import java.time.Instant +import java.time.LocalDate import java.util.UUID data class StoredPlayer( @@ -15,6 +16,24 @@ data class StoredPlayer( } } +data class PlayerNetworkHash( + val playerId: UUID, + val keyId: String, + val hash: String, + val observedAt: Instant, + val expiresAt: Instant, +) { + init { + require(HASH_PATTERN.matches(keyId)) { "Network hash key ID must be a lowercase SHA-256 hex digest." } + require(HASH_PATTERN.matches(hash)) { "Player network hash must be a lowercase SHA-256 hex digest." } + require(expiresAt.isAfter(observedAt)) { "Player network hash expiry must be after observation." } + } + + companion object { + private val HASH_PATTERN = Regex("[0-9a-f]{64}") + } +} + enum class QualificationFactOutcome { SATISFIED, UNSATISFIED, @@ -112,6 +131,30 @@ data class StoredRewardDeliveryTransition( } } +data class InviterInvitationStats( + val claimed: Int, + val qualified: Int, +) { + init { + require(claimed >= 0) { "Claimed Invitation count must not be negative." } + require(qualified >= 0) { "Qualified Invitation count must not be negative." } + } +} + +data class RewardBacklogCounts( + val pending: Int, + val processing: Int, + val uncertain: Int, +) { + init { + require(pending >= 0) { "Pending Reward Action count must not be negative." } + require(processing >= 0) { "Processing Reward Action count must not be negative." } + require(uncertain >= 0) { "Uncertain Reward Action count must not be negative." } + } +} + +const val MAX_AUDIT_HISTORY_LIMIT: Int = 100 + /** * 持久化領域狀態的同步介面。SQL adapter 會執行 blocking I/O,呼叫端必須將操作排程至 * server main thread 以外的專用 executor。 @@ -148,15 +191,74 @@ interface RewardRecords { fun rewardDelivery(deliveryId: UUID): StoredRewardDelivery? } +interface QualificationRewardRecords : QualificationRecords, RewardRecords { + /** Persists the first successful Qualification and every resulting Reward plan in one transaction. */ + fun saveQualifiedInvitationWithRewards( + invitation: Invitation, + facts: List, + rewardPlans: List, + ) +} + +interface PlayerLookup { + fun player(playerId: UUID): StoredPlayer? + + /** + * Returns at most two case-insensitive exact matches. Two results are sufficient to reject an + * ambiguous player reference; callers must not assume a last known name is unique. + */ + fun playersByLastKnownName(lastKnownName: String): List +} + +interface InviteCodeQueries { + fun claimState(playerId: UUID): PlayerClaimState + + /** Returns the matching Invite Code only while it is active. */ + fun activeInviteCode(inviteCode: InviteCode): ActiveInviteCode? + + /** Returns every eligibility generation, newest Claim first with Invitation ID as the tie-breaker. */ + fun invitationsByInvitee(inviteeId: UUID): List + + /** Returns all Invitations currently attributed to the Inviter, newest first with ID as the tie-breaker. */ + fun invitationsByInviter(inviterId: UUID): List + + /** Counts current CLAIMED and QUALIFIED states separately; UNLINKED Invitations are excluded. */ + fun inviterInvitationStats(inviterId: UUID): InviterInvitationStats + + /** Returns facts in recording order, with fact ID as the tie-breaker. */ + fun qualificationFacts(invitationId: UUID): List + + /** Returns newest records first, with Audit Record ID as the tie-breaker. */ + fun auditHistoryByInvitation(invitationId: UUID, limit: Int): List + + /** Returns newest records first, with Audit Record ID as the tie-breaker. */ + fun auditHistoryByPlayer(playerId: UUID, limit: Int): List + + /** Returns newest deliveries first, with Reward Delivery ID as the tie-breaker. */ + fun rewardDeliveries(invitationId: UUID): List + + /** Counts global Reward Actions that still need delivery or operator attention. */ + fun rewardBacklogCounts(): RewardBacklogCounts +} + interface InviteCodeStorage : InvitationTransactions, InviteCodeRegistry, - QualificationRecords, - RewardRecords, + QualificationRewardRecords, + PlayerLookup, + InviteCodeQueries, AutoCloseable { fun savePlayer(player: StoredPlayer) - fun player(playerId: UUID): StoredPlayer? + fun recordLoginDay(playerId: UUID, loginDate: LocalDate) + + fun loginDays(playerId: UUID): Int + + fun recordNetworkHash(record: PlayerNetworkHash) + + fun purgeExpiredNetworkHashes(expiredAt: Instant): Int + + fun purgeNetworkHashesWithDifferentKey(keyId: String): Int fun activeInviteCode(inviterId: UUID): ActiveInviteCode? @@ -178,5 +280,10 @@ interface InviteCodeStorage : fun saveAuditedInvitationTransition(transition: AuditedInvitationTransition) + fun saveForcedQualificationWithRewards( + transition: AuditedInvitationTransition, + rewardPlans: List, + ) + fun saveAuditedClaimStateTransition(transition: AuditedClaimStateTransition) } 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 index 0579948..f267cfe 100644 --- 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 @@ -5,6 +5,15 @@ import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test class ColorInviteCodeGeneratorTest { + @Test + fun `crockford generator uses configured length and alphabet`() { + val generator = CrockfordInviteCodeGenerator(8) { destination -> + byteArrayOf(0, 1, 10, 17, 24, 31, 32, 255.toByte()).copyInto(destination) + } + + assertEquals("01AHRZ0Z", generator.generate().displayValue()) + } + @Test fun `generator turns three random bytes into an uppercase color invite code`() { val generator = ColorInviteCodeGenerator( diff --git a/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/InvitationClaimServiceTest.kt b/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/InvitationClaimServiceTest.kt index 4ee95b3..87fbc43 100644 --- a/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/InvitationClaimServiceTest.kt +++ b/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/InvitationClaimServiceTest.kt @@ -41,6 +41,64 @@ class InvitationClaimServiceTest { assertEquals(inviteeId, claimed.invitation.inviteeId) } + @Test + fun `confirmation cannot claim after Invite Code rotates`() { + val transactions = InMemoryInvitationTransactions( + firstSeenAtByPlayer = mapOf(inviteeId to firstSeenAt, inviterId to firstSeenAt), + ) + val service = InvitationClaimService( + transactions = transactions, + eligibilityPolicy = ClaimEligibilityPolicy(Duration.ofHours(24)), + invitationIdGenerator = { invitationId }, + ) + val confirmation = confirmedClaim(inviteeId, inviterId) + transactions.activeCodes[confirmation.inviteCode] = inviterId + transactions.activeCodes.clear() + + val result = service.claim(confirmation) + + assertInstanceOf(InvitationClaimResult.InviteCodeUnavailable::class.java, result) + } + + @Test + fun `matching retained network hash can deny a claim`() { + val transactions = InMemoryInvitationTransactions( + firstSeenAtByPlayer = mapOf(inviteeId to firstSeenAt, inviterId to firstSeenAt), + matchingNetworkPlayers = setOf(inviteeId, inviterId), + ) + val service = InvitationClaimService( + transactions, + ClaimEligibilityPolicy(Duration.ofHours(24)), + { invitationId }, + MatchingNetworkAction.DENY, + ) + + val result = service.claim(confirmedClaim(inviteeId, inviterId)) + + assertInstanceOf(InvitationClaimResult.MatchingNetworkDenied::class.java, result) + } + + @Test + fun `matching retained network hash can warn while allowing a claim`() { + val transactions = InMemoryInvitationTransactions( + firstSeenAtByPlayer = mapOf(inviteeId to firstSeenAt, inviterId to firstSeenAt), + matchingNetworkPlayers = setOf(inviteeId, inviterId), + ) + val service = InvitationClaimService( + transactions, + ClaimEligibilityPolicy(Duration.ofHours(24)), + { invitationId }, + MatchingNetworkAction.WARN, + ) + + val result = assertInstanceOf( + InvitationClaimResult.Claimed::class.java, + service.claim(confirmedClaim(inviteeId, inviterId)), + ) + + assertEquals(true, result.matchingNetworkHash) + } + @Test fun `one inviter can receive invitations from multiple invitees`() { val secondInviteeId = UUID.fromString("00000000-0000-0000-0000-000000000003") @@ -124,16 +182,22 @@ class InvitationClaimServiceTest { private fun confirmedClaim(inviteeId: UUID, inviterId: UUID) = ConfirmedClaim( inviteeId = inviteeId, inviterId = inviterId, - inviteCode = InviteCode.parse("A25981"), + inviteCode = InviteCode.parse(inviterId.toString().takeLast(6)), confirmedAt = firstSeenAt.plusSeconds(60), ) } private class InMemoryInvitationTransactions( private val firstSeenAtByPlayer: Map, + private val matchingNetworkPlayers: Set = emptySet(), ) : InvitationTransactions { private val locks = ConcurrentHashMap() private val invitations = CopyOnWriteArrayList() + val activeCodes = ConcurrentHashMap().apply { + firstSeenAtByPlayer.keys.forEach { playerId -> + put(InviteCode.parse(playerId.toString().takeLast(6)), playerId) + } + } override fun atomically( playerIds: Set, @@ -145,6 +209,8 @@ private class InMemoryInvitationTransactions( acquired.forEach(ReentrantLock::lock) try { return operation(object : InvitationTransaction { + override fun activeInviter(inviteCode: InviteCode): UUID? = activeCodes[inviteCode] + override fun claimState(playerId: UUID): PlayerClaimState = PlayerClaimState( playerId = playerId, firstSeenAt = requireNotNull(firstSeenAtByPlayer[playerId]), @@ -152,6 +218,12 @@ private class InMemoryInvitationTransactions( hasInvitation = invitations.any { it.inviteeId == playerId }, ) + override fun hasMatchingNetworkHash( + firstPlayerId: UUID, + secondPlayerId: UUID, + evaluatedAt: Instant, + ): Boolean = firstPlayerId in matchingNetworkPlayers && secondPlayerId in matchingNetworkPlayers + override fun add(invitation: Invitation) { invitations += invitation } 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 ee65320..afd0882 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 @@ -160,6 +160,7 @@ private class InMemoryInviteCodeRegistry( 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 } + private val auditRecords = mutableListOf() override fun atomically(operation: (InviteCodeTransaction) -> T): T = synchronized(this) { operation(object : InviteCodeTransaction { @@ -187,6 +188,10 @@ private class InMemoryInviteCodeRegistry( activeInviterByCode[current.code] = current.inviterId reservedCodes += current.code } + + override fun saveAuditRecord(record: AuditRecord) { + auditRecords += record + } }) } diff --git a/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/PlayerReferenceResolverTest.kt b/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/PlayerReferenceResolverTest.kt new file mode 100644 index 0000000..915e810 --- /dev/null +++ b/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/PlayerReferenceResolverTest.kt @@ -0,0 +1,53 @@ +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.util.UUID + +class PlayerReferenceResolverTest { + private val first = StoredPlayer( + UUID.fromString("00000000-0000-0000-0000-000000000001"), + Instant.EPOCH, + "SameName", + ) + private val second = StoredPlayer( + UUID.fromString("00000000-0000-0000-0000-000000000002"), + Instant.EPOCH, + "samename", + ) + private val lookup = object : PlayerLookup { + override fun player(playerId: UUID): StoredPlayer? = + listOf(first, second).singleOrNull { it.id == playerId } + + override fun playersByLastKnownName(lastKnownName: String): List = + listOf(first, second).filter { it.lastKnownName.equals(lastKnownName, ignoreCase = true) } + } + private val resolver = PlayerReferenceResolver(lookup) + + @Test + fun `UUID is resolved before treating the reference as a player name`() { + assertEquals(PlayerReferenceResolution.Found(first), resolver.resolve(first.id.toString())) + assertEquals(PlayerReferenceResolution.Unknown, resolver.resolve(UUID.randomUUID().toString())) + } + + @Test + fun `unique player name resolves case insensitively`() { + val unique = first.copy(lastKnownName = "OnlyOne") + val resolver = PlayerReferenceResolver(object : PlayerLookup { + override fun player(playerId: UUID): StoredPlayer? = null + override fun playersByLastKnownName(lastKnownName: String): List = listOf(unique) + }) + + assertEquals(PlayerReferenceResolution.Found(unique), resolver.resolve("onlyone")) + } + + @Test + fun `unknown and ambiguous player names remain distinct`() { + assertEquals(PlayerReferenceResolution.Unknown, resolver.resolve("Nobody")) + assertEquals( + PlayerReferenceResolution.Ambiguous(listOf(first, second)), + resolver.resolve("SAMENAME"), + ) + } +} diff --git a/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/QualificationEvaluatorTest.kt b/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/QualificationEvaluatorTest.kt index ee0affe..abaeef5 100644 --- a/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/QualificationEvaluatorTest.kt +++ b/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/QualificationEvaluatorTest.kt @@ -81,6 +81,28 @@ class QualificationEvaluatorTest { registry.register(provider("custom") { QualificationConditionOutcome.UNSATISFIED }) } + @Test + fun `local built-ins take precedence and unknown types fall back to external providers`() { + val external = QualificationProviderRegistry( + listOf(provider("CUSTOM") { QualificationConditionOutcome.SATISFIED }), + ) + val local = QualificationProviderRegistry( + listOf(provider("LOCAL") { QualificationConditionOutcome.SATISFIED }), + fallback = external, + ) + val policy = policy( + group(condition("local", "LOCAL"), condition("external", "CUSTOM")), + ) + + val result = QualificationEvaluator(local).evaluate(claimedInvitation(), policy, context()) + + assertTrue(result.qualified) + assertEquals( + listOf(QualificationFactOutcome.SATISFIED, QualificationFactOutcome.SATISFIED), + result.facts.map { it.outcome }, + ) + } + private fun provider( type: String, result: () -> QualificationConditionOutcome, diff --git a/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/QualificationRewardServiceTest.kt b/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/QualificationRewardServiceTest.kt new file mode 100644 index 0000000..a2c6fd3 --- /dev/null +++ b/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/QualificationRewardServiceTest.kt @@ -0,0 +1,100 @@ +package io.github.command1264.invitecode.core + +import io.github.command1264.invitecode.api.InvitationStatus +import io.github.command1264.invitecode.api.QualificationConditionContext +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import java.time.Duration +import java.time.Instant +import java.util.UUID + +class QualificationRewardServiceTest { + @Test + fun `first successful qualification saves reward plans in the same persistence call`() { + val invitation = Invitation( + UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), + InvitationStatus.CLAIMED, Instant.EPOCH, + ) + val records = QualificationRewardRecordsFake(invitation) + val service = QualificationRewardService( + records, + QualificationEvaluator(QualificationProviderRegistry(BuiltInQualificationProviders.create())), + ) + val policy = QualificationPolicyParser.parse( + "new-player", + mapOf( + "any-of" to listOf( + mapOf("all-of" to listOf(mapOf("type" to "PLAY_TIME", "at-least" to "30m"))), + ), + ), + ) + val rewards = RewardConfigurationParser.parse( + mapOf( + "config-version" to 1, + "qualification-rewards" to mapOf( + "default" to mapOf( + "inviter" to listOf(mapOf("type" to "MESSAGE", "message" to "invite.done")), + "invitee" to emptyList(), + ), + ), + "milestone-rewards" to emptyMap(), + ), + ) + + val result = service.reevaluate( + invitation.id, + policy, + QualificationConditionContext( + invitation.id, + invitation.inviterId, + invitation.inviteeId, + invitation.claimedAt, + Instant.EPOCH.plusSeconds(1), + playTime = Duration.ofMinutes(30), + ), + rewards, + ) + + assertEquals(QualificationEvaluationStatus.QUALIFIED, result.qualification.status) + assertEquals(1, result.rewardPlans.size) + assertTrue(records.atomicQualificationSaved) + assertEquals(InvitationStatus.QUALIFIED, records.current.status) + } +} + +private class QualificationRewardRecordsFake( + var current: Invitation, +) : QualificationRewardRecords { + var atomicQualificationSaved = false + + override fun invitation(invitationId: UUID): Invitation? = current.takeIf { it.id == invitationId } + override fun qualifiedInvitationCount(inviterId: UUID) = 0 + override fun saveQualificationFacts(facts: List) = Unit + override fun saveQualifiedInvitation(invitation: Invitation, facts: List) = + error("Qualification and Reward plans must be persisted together") + + override fun saveQualifiedInvitationWithRewards( + invitation: Invitation, + facts: List, + rewardPlans: List, + ) { + atomicQualificationSaved = true + current = invitation + } + + override fun saveRewardAction(action: StoredRewardAction) = unsupported() + override fun rewardAction(actionId: UUID): StoredRewardAction? = unsupported() + override fun rewardActions(deliveryId: UUID): List = unsupported() + override fun pendingRewardActions(recipientId: UUID): List = unsupported() + override fun recoverInterruptedRewardActions(recoveredAt: Instant): Int = unsupported() + override fun resolveUncertainRewardAction( + actionId: UUID, + resolution: UncertainRewardActionResolution, + context: RewardAdministrationContext, + ): StoredRewardAction = unsupported() + override fun saveRewardDelivery(delivery: StoredRewardDelivery, actions: List) = unsupported() + override fun rewardDelivery(deliveryId: UUID): StoredRewardDelivery? = unsupported() + + private fun unsupported(): Nothing = error("Not used by this test") +} 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 new file mode 100644 index 0000000..8230784 --- /dev/null +++ b/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/StorageConfigurationTest.kt @@ -0,0 +1,49 @@ +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 +import java.time.Duration + +class StorageConfigurationTest { + @Test + fun `parses SQLite while retaining restart-only MySQL settings`() { + val configuration = StorageConfigurationParser.parse(validConfiguration()) + + assertEquals(StorageBackendType.SQLITE, configuration.backend) + assertEquals("invitecode.db", configuration.sqlite.file) + assertEquals(3306, configuration.mysql.port) + assertEquals(Duration.ofSeconds(5), configuration.mysql.connectionTimeout) + assertEquals("${'$'}{INVITECODE_DB_PASSWORD}", configuration.mysql.passwordReference) + } + + @Test + fun `rejects unsafe SQLite paths`() { + val sqlite = mapOf("file" to "../outside.db") + val value = validConfiguration().toMutableMap().apply { put("sqlite", sqlite) } + + assertThrows { StorageConfigurationParser.parse(value) } + } + + @Test + fun `marks unfinished backends unsupported`() { + assertThrows { + StorageConfigurationParser.parse(validConfiguration().toMutableMap().apply { put("backend", "MYSQL") }) + .requireSupportedBackend() + } + } + + private fun validConfiguration(): Map = mapOf( + "config-version" to 1, + "backend" to "SQLITE", + "sqlite" to mapOf("file" to "invitecode.db"), + "mysql" to mapOf( + "host" to "localhost", + "port" to 3306, + "database" to "invitecode", + "username" to "invitecode", + "password" to "${'$'}{INVITECODE_DB_PASSWORD}", + "connection-timeout" to "5s", + ), + ) +} diff --git a/invitecode-platform-bukkit/src/main/kotlin/io/github/command1264/invitecode/platform/bukkit/AsyncOperationExecutor.kt b/invitecode-platform-bukkit/src/main/kotlin/io/github/command1264/invitecode/platform/bukkit/AsyncOperationExecutor.kt new file mode 100644 index 0000000..25230cb --- /dev/null +++ b/invitecode-platform-bukkit/src/main/kotlin/io/github/command1264/invitecode/platform/bukkit/AsyncOperationExecutor.kt @@ -0,0 +1,61 @@ +package io.github.command1264.invitecode.platform.bukkit + +import java.time.Duration +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicBoolean + +interface BackgroundOperationExecutor { + fun submit( + operation: () -> T, + onSuccess: (T) -> Unit, + onFailure: (Throwable) -> Unit, + ): Boolean +} + +class AsyncOperationExecutor( + threadName: String, + private val dispatchMain: (() -> Unit) -> Unit, +) : BackgroundOperationExecutor, AutoCloseable { + private val accepting = AtomicBoolean(true) + private val executor = Executors.newSingleThreadExecutor { operation -> + Thread(operation, threadName).apply { isDaemon = true } + } + + val acceptingOperations: Boolean + get() = accepting.get() + + override fun submit( + operation: () -> T, + onSuccess: (T) -> Unit, + onFailure: (Throwable) -> Unit, + ): Boolean { + if (!accepting.get()) return false + return try { + executor.execute { + val result = runCatching(operation) + if (accepting.get()) { + dispatchMain { + if (!accepting.get()) return@dispatchMain + result.fold(onSuccess, onFailure) + } + } + } + true + } catch (_: java.util.concurrent.RejectedExecutionException) { + false + } + } + + fun close(timeout: Duration): Boolean { + require(!timeout.isNegative) { "Executor shutdown timeout must not be negative." } + if (accepting.getAndSet(false)) executor.shutdown() + val terminated = executor.awaitTermination(timeout.toMillis(), TimeUnit.MILLISECONDS) + if (!terminated) executor.shutdownNow() + return terminated + } + + override fun close() { + close(Duration.ofSeconds(5)) + } +} diff --git a/invitecode-platform-bukkit/src/main/kotlin/io/github/command1264/invitecode/platform/bukkit/AsyncRewardDeliveryWorkflow.kt b/invitecode-platform-bukkit/src/main/kotlin/io/github/command1264/invitecode/platform/bukkit/AsyncRewardDeliveryWorkflow.kt new file mode 100644 index 0000000..cdf841f --- /dev/null +++ b/invitecode-platform-bukkit/src/main/kotlin/io/github/command1264/invitecode/platform/bukkit/AsyncRewardDeliveryWorkflow.kt @@ -0,0 +1,177 @@ +package io.github.command1264.invitecode.platform.bukkit + +import io.github.command1264.invitecode.core.RewardActionExecutionContext +import io.github.command1264.invitecode.core.RewardActionExecutionResult +import io.github.command1264.invitecode.core.RewardActionExecutor +import io.github.command1264.invitecode.core.RewardActionProcessingResult +import io.github.command1264.invitecode.core.RewardActionProcessingStatus +import io.github.command1264.invitecode.core.RewardActionReadiness +import io.github.command1264.invitecode.core.RewardActionStatus +import io.github.command1264.invitecode.core.RewardDeliveryCoordinator +import io.github.command1264.invitecode.core.StoredRewardAction +import java.time.Instant +import java.util.UUID +import java.util.concurrent.RejectedExecutionException + +interface RewardActionStateStore { + fun action(actionId: UUID): StoredRewardAction? + fun begin(actionId: UUID, occurredAt: Instant): StoredRewardAction + fun delivered(actionId: UUID, occurredAt: Instant): StoredRewardAction + fun failed(actionId: UUID, reason: String, occurredAt: Instant): StoredRewardAction + fun deferred(actionId: UUID, occurredAt: Instant): StoredRewardAction + fun uncertain(actionId: UUID, reason: String, occurredAt: Instant): StoredRewardAction +} + +class CoordinatorRewardActionStateStore( + private val coordinator: RewardDeliveryCoordinator, +) : RewardActionStateStore { + override fun action(actionId: UUID) = coordinator.action(actionId) + override fun begin(actionId: UUID, occurredAt: Instant) = coordinator.begin(actionId, occurredAt) + override fun delivered(actionId: UUID, occurredAt: Instant) = coordinator.delivered(actionId, occurredAt) + override fun failed(actionId: UUID, reason: String, occurredAt: Instant) = + coordinator.failed(actionId, reason, occurredAt) + override fun deferred(actionId: UUID, occurredAt: Instant) = coordinator.deferred(actionId, occurredAt) + override fun uncertain(actionId: UUID, reason: String, occurredAt: Instant) = + coordinator.uncertain(actionId, reason, occurredAt) +} + +class AsyncRewardDeliveryWorkflow( + private val operations: BackgroundOperationExecutor, + private val store: RewardActionStateStore, + private val executor: RewardActionExecutor, + private val now: () -> Instant = Instant::now, +) { + fun process( + requested: StoredRewardAction, + context: RewardActionExecutionContext, + onComplete: (RewardActionProcessingResult) -> Unit, + onFailure: (Throwable) -> Unit = {}, + ): Boolean { + require(requested.recipientId == context.recipientId) { + "Reward Action recipient does not match execution context." + } + return operations.submit( + operation = { requireAction(requested.id) }, + onSuccess = { current -> inspectReadiness(current, context, onComplete, onFailure) }, + onFailure = onFailure, + ) + } + + private fun inspectReadiness( + current: StoredRewardAction, + context: RewardActionExecutionContext, + onComplete: (RewardActionProcessingResult) -> Unit, + onFailure: (Throwable) -> Unit, + ) { + existingResult(current)?.let { + onComplete(it) + return + } + val readiness = try { + executor.readiness(current, context) + } catch (error: Exception) { + onFailure(error) + return + } + if (readiness != RewardActionReadiness.READY) { + onComplete( + RewardActionProcessingResult(RewardActionProcessingStatus.DEFERRED, current, readiness), + ) + return + } + submitNested( + operation = { + val latest = requireAction(current.id) + existingResult(latest)?.let(BeginOutcome::Existing) + ?: BeginOutcome.Begun(store.begin(latest.id, now())) + }, + onSuccess = { outcome -> + when (outcome) { + is BeginOutcome.Existing -> onComplete(outcome.result) + is BeginOutcome.Begun -> executeExternal(outcome.action, context, onComplete, onFailure) + } + }, + onFailure = onFailure, + ) + } + + private fun executeExternal( + processing: StoredRewardAction, + context: RewardActionExecutionContext, + onComplete: (RewardActionProcessingResult) -> Unit, + onFailure: (Throwable) -> Unit, + ) { + val external = try { + ExternalOutcome.Result(executor.execute(processing, context)) + } catch (error: Exception) { + ExternalOutcome.Unknown(error.javaClass.simpleName) + } + submitNested( + operation = { persist(processing.id, external) }, + onSuccess = onComplete, + onFailure = onFailure, + ) + } + + private fun persist(actionId: UUID, outcome: ExternalOutcome): RewardActionProcessingResult = when (outcome) { + is ExternalOutcome.Unknown -> result( + RewardActionProcessingStatus.UNCERTAIN, + store.uncertain( + actionId, + "External Reward Action execution threw ${outcome.errorType}; result is unknown.", + now(), + ), + ) + is ExternalOutcome.Result -> when (val execution = outcome.value) { + RewardActionExecutionResult.Delivered -> result( + RewardActionProcessingStatus.DELIVERED, + store.delivered(actionId, now()), + ) + is RewardActionExecutionResult.Deferred -> RewardActionProcessingResult( + RewardActionProcessingStatus.DEFERRED, + store.deferred(actionId, now()), + execution.readiness, + ) + is RewardActionExecutionResult.Failed -> result( + RewardActionProcessingStatus.FAILED, + store.failed(actionId, execution.reason, now()), + ) + } + } + + private fun existingResult(action: StoredRewardAction): RewardActionProcessingResult? = when (action.status) { + RewardActionStatus.PENDING -> null + RewardActionStatus.PROCESSING -> result(RewardActionProcessingStatus.ALREADY_PROCESSING, action) + RewardActionStatus.DELIVERED, + RewardActionStatus.FAILED, + RewardActionStatus.UNCERTAIN, + RewardActionStatus.EXPIRED -> result(RewardActionProcessingStatus.ALREADY_TERMINAL, action) + } + + private fun requireAction(actionId: UUID): StoredRewardAction = requireNotNull(store.action(actionId)) { + "Reward Action $actionId does not exist." + } + + private fun submitNested( + operation: () -> T, + onSuccess: (T) -> Unit, + onFailure: (Throwable) -> Unit, + ) { + if (!operations.submit(operation, onSuccess, onFailure)) { + onFailure(RejectedExecutionException("Reward workflow executor is stopping.")) + } + } + + private fun result(status: RewardActionProcessingStatus, action: StoredRewardAction) = + RewardActionProcessingResult(status, action) + + private sealed class BeginOutcome { + data class Begun(val action: StoredRewardAction) : BeginOutcome() + data class Existing(val result: RewardActionProcessingResult) : BeginOutcome() + } + + private sealed class ExternalOutcome { + data class Result(val value: RewardActionExecutionResult) : ExternalOutcome() + data class Unknown(val errorType: String) : ExternalOutcome() + } +} diff --git a/invitecode-platform-bukkit/src/main/kotlin/io/github/command1264/invitecode/platform/bukkit/BukkitPluginConfiguration.kt b/invitecode-platform-bukkit/src/main/kotlin/io/github/command1264/invitecode/platform/bukkit/BukkitPluginConfiguration.kt new file mode 100644 index 0000000..2af92db --- /dev/null +++ b/invitecode-platform-bukkit/src/main/kotlin/io/github/command1264/invitecode/platform/bukkit/BukkitPluginConfiguration.kt @@ -0,0 +1,214 @@ +package io.github.command1264.invitecode.platform.bukkit + +import io.github.command1264.invitecode.core.ColorInviteCodeGenerator +import io.github.command1264.invitecode.core.CrockfordInviteCodeGenerator +import io.github.command1264.invitecode.core.InviteCodeFormat +import io.github.command1264.invitecode.core.InviteCodeFormats +import io.github.command1264.invitecode.core.InviteCodeGenerator +import io.github.command1264.invitecode.core.MatchingNetworkAction +import java.time.Duration +import java.time.ZoneId +import java.util.Locale + +enum class InviteCodeRuntimeFormat { + HEX_COLOR, + CROCKFORD_BASE32, +} + +fun InviteCodeRuntimeFormat.parser(): InviteCodeFormat = when (this) { + InviteCodeRuntimeFormat.HEX_COLOR -> InviteCodeFormats.colorHex + InviteCodeRuntimeFormat.CROCKFORD_BASE32 -> InviteCodeFormats.crockfordBase32(8) +} + +fun InviteCodeRuntimeFormat.generator(): InviteCodeGenerator = when (this) { + InviteCodeRuntimeFormat.HEX_COLOR -> ColorInviteCodeGenerator() + InviteCodeRuntimeFormat.CROCKFORD_BASE32 -> CrockfordInviteCodeGenerator() +} + +enum class ExistingPlayerPolicy { + START_WINDOW, + EXPIRED, +} + +data class LanguageConfiguration( + val defaultLocale: String, + val useClientLocale: Boolean, +) + +data class InviteCodeConfiguration( + val format: InviteCodeRuntimeFormat, + val customCodesEnabled: Boolean, +) + +data class ClaimWorkflowConfiguration( + val window: Duration, + val inputMode: InputMode, + val confirmationTimeout: Duration, + val chatInputTimeout: Duration, + val existingPlayerPolicy: ExistingPlayerPolicy, +) + +data class AntiAbuseConfiguration( + val matchingIpAction: MatchingNetworkAction, + val ipHashRetention: Duration, +) + +data class BukkitPluginConfiguration( + val version: Int, + val language: LanguageConfiguration, + val inviteCode: InviteCodeConfiguration, + val claim: ClaimWorkflowConfiguration, + val antiAbuse: AntiAbuseConfiguration, + val timeZone: ZoneId, +) + +object BukkitPluginConfigurationParser { + const val CURRENT_VERSION = 1 + + fun parse(value: Map): BukkitPluginConfiguration { + require(value.keys == ROOT_KEYS) { + "General configuration must contain only ${ROOT_KEYS.sorted().joinToString()} ." + } + val version = value.requiredInteger("config-version", "General configuration") + require(version == CURRENT_VERSION) { + "General config-version $version is unsupported; expected $CURRENT_VERSION." + } + val language = value.requiredMap("language", "General configuration") + requireKeys(language, LANGUAGE_KEYS, "language") + val inviteCode = value.requiredMap("invite-code", "General configuration") + requireKeys(inviteCode, INVITE_CODE_KEYS, "invite-code") + val claim = value.requiredMap("claim", "General configuration") + requireKeys(claim, CLAIM_KEYS, "claim") + val antiAbuse = value.requiredMap("anti-abuse", "General configuration") + requireKeys(antiAbuse, ANTI_ABUSE_KEYS, "anti-abuse") + + val inputMode = claim.requiredEnum("input-mode", "claim") + require(inputMode != InputMode.DIALOG) { + "DIALOG input is owned by the modern adapter; use AUTO, CHAT, or COMMAND_ONLY here." + } + return BukkitPluginConfiguration( + version = version, + language = LanguageConfiguration( + normalizeLocale(language.requiredString("default", "language")), + language.requiredBoolean("use-client-locale", "language"), + ), + inviteCode = InviteCodeConfiguration( + inviteCode.requiredEnum("format", "invite-code"), + inviteCode.requiredBoolean("custom-codes-enabled", "invite-code"), + ), + claim = ClaimWorkflowConfiguration( + parsePositiveDuration(claim.requiredString("window", "claim"), "claim.window"), + inputMode, + parsePositiveDuration( + claim.requiredString("confirmation-timeout", "claim"), + "claim.confirmation-timeout", + ), + parsePositiveDuration( + claim.requiredString("chat-input-timeout", "claim"), + "claim.chat-input-timeout", + ), + claim.requiredEnum("existing-player-policy", "claim"), + ), + antiAbuse = AntiAbuseConfiguration( + antiAbuse.requiredEnum("matching-ip-action", "anti-abuse"), + parsePositiveDuration( + antiAbuse.requiredString("ip-hash-retention", "anti-abuse"), + "anti-abuse.ip-hash-retention", + ), + ), + timeZone = try { + ZoneId.of(value.requiredString("time-zone", "General configuration")) + } catch (error: Exception) { + throw IllegalArgumentException("General configuration time-zone is invalid.", error) + }, + ) + } + + private fun parsePositiveDuration(raw: String, location: String): Duration { + val duration = SHORT_DURATION.matchEntire(raw)?.let { match -> + val amount = match.groupValues[1].toLongOrNull() + ?: throw IllegalArgumentException("$location duration is outside the supported range.") + when (match.groupValues[2]) { + "ms" -> Duration.ofMillis(amount) + "s" -> Duration.ofSeconds(amount) + "m" -> Duration.ofMinutes(amount) + "h" -> Duration.ofHours(amount) + "d" -> Duration.ofDays(amount) + else -> error("Unreachable duration unit") + } + } ?: try { + Duration.parse(raw) + } catch (error: Exception) { + throw IllegalArgumentException("$location must be a duration such as 30s, 24h, or PT30S.", error) + } + require(!duration.isZero && !duration.isNegative) { "$location must be greater than zero." } + return duration + } + + private fun normalizeLocale(raw: String): String { + val match = LOCALE.matchEntire(raw) + ?: throw IllegalArgumentException("Locale '$raw' must use language_COUNTRY format.") + return match.groupValues[1].lowercase(Locale.ROOT) + "_" + + match.groupValues[2].uppercase(Locale.ROOT) + } + + private fun requireKeys(value: Map, keys: Set, location: String) { + require(value.keys == keys) { "$location must contain only ${keys.sorted().joinToString()} ." } + } + + private fun Map.requiredMap(name: String, location: String): Map { + val value = this[name] + require(value is Map<*, *> && value.keys.all { it is String }) { + "$location requires map $name with string keys." + } + @Suppress("UNCHECKED_CAST") + return value as Map + } + + private fun Map.requiredString(name: String, location: String): String { + val value = this[name] + require(value is String && value.isNotBlank()) { "$location requires non-blank string $name." } + return value + } + + private fun Map.requiredBoolean(name: String, location: String): Boolean = + this[name] as? Boolean + ?: throw IllegalArgumentException("$location requires boolean $name.") + + private fun Map.requiredInteger(name: String, location: String): Int = + (this[name] as? Number)?.toString()?.toIntOrNull() + ?: throw IllegalArgumentException("$location requires integer $name.") + + private inline fun > Map.requiredEnum( + name: String, + location: String, + ): T { + val raw = requiredString(name, location) + return try { + enumValueOf(raw.uppercase(Locale.ROOT)) + } catch (error: IllegalArgumentException) { + throw IllegalArgumentException("$location has unsupported $name '$raw'.", error) + } + } + + private val ROOT_KEYS = setOf( + "config-version", + "language", + "invite-code", + "claim", + "anti-abuse", + "time-zone", + ) + private val LANGUAGE_KEYS = setOf("default", "use-client-locale") + private val INVITE_CODE_KEYS = setOf("format", "custom-codes-enabled") + private val CLAIM_KEYS = setOf( + "window", + "input-mode", + "confirmation-timeout", + "chat-input-timeout", + "existing-player-policy", + ) + private val ANTI_ABUSE_KEYS = setOf("matching-ip-action", "ip-hash-retention") + private val SHORT_DURATION = Regex("^(\\d+)(ms|s|m|h|d)$") + private val LOCALE = Regex("^([A-Za-z]{2,3})[_-]([A-Za-z]{2})$") +} diff --git a/invitecode-platform-bukkit/src/main/kotlin/io/github/command1264/invitecode/platform/bukkit/BukkitRewardExecutionEnvironment.kt b/invitecode-platform-bukkit/src/main/kotlin/io/github/command1264/invitecode/platform/bukkit/BukkitRewardExecutionEnvironment.kt index 9525e4b..cf3bdb8 100644 --- a/invitecode-platform-bukkit/src/main/kotlin/io/github/command1264/invitecode/platform/bukkit/BukkitRewardExecutionEnvironment.kt +++ b/invitecode-platform-bukkit/src/main/kotlin/io/github/command1264/invitecode/platform/bukkit/BukkitRewardExecutionEnvironment.kt @@ -4,11 +4,8 @@ import io.github.command1264.invitecode.core.OnlineRewardActionResult import io.github.command1264.invitecode.core.RewardExecutionEnvironment import org.bukkit.Bukkit import org.bukkit.Server -import org.bukkit.plugin.Plugin import java.math.BigDecimal import java.util.UUID -import java.util.concurrent.Callable -import java.util.concurrent.ExecutionException fun interface RewardMessageResolver { fun resolve(playerId: UUID, localeKey: String): String @@ -18,60 +15,55 @@ fun interface EconomyRewardGateway { fun deposit(playerId: UUID, amount: BigDecimal): Boolean } -class BukkitMainThreadExecutor( - private val server: Server, - private val plugin: Plugin, -) { - fun call(operation: () -> T): T { - if (Bukkit.isPrimaryThread()) return operation() - return try { - server.scheduler.callSyncMethod(plugin, Callable(operation)).get() - } catch (error: InterruptedException) { - Thread.currentThread().interrupt() - throw IllegalStateException("Interrupted while waiting for a Bukkit main-thread Reward operation.", error) - } catch (error: ExecutionException) { - val cause = error.cause ?: error - if (cause is RuntimeException) throw cause - throw IllegalStateException("Bukkit main-thread Reward operation failed.", cause) - } - } -} - class BukkitRewardExecutionEnvironment( private val server: Server, - private val mainThread: BukkitMainThreadExecutor, private val messages: RewardMessageResolver, private val economy: EconomyRewardGateway? = null, + private val isPrimaryThread: () -> Boolean = Bukkit::isPrimaryThread, ) : RewardExecutionEnvironment { - override fun isOnline(playerId: UUID): Boolean = mainThread.call { - server.getPlayer(playerId)?.isOnline == true + override fun isOnline(playerId: UUID): Boolean { + requireMainThread() + return server.getPlayer(playerId)?.isOnline == true } - override fun dispatchConsole(command: String): Boolean = mainThread.call { - server.dispatchCommand(server.consoleSender, command) + override fun dispatchConsole(command: String): Boolean { + requireMainThread() + return server.dispatchCommand(server.consoleSender, command) } - override fun dispatchPlayer(playerId: UUID, command: String): OnlineRewardActionResult = mainThread.call { + override fun dispatchPlayer(playerId: UUID, command: String): OnlineRewardActionResult { + requireMainThread() val player = server.getPlayer(playerId) - ?: return@call OnlineRewardActionResult.RECIPIENT_OFFLINE - if (player.performCommand(command)) { + ?: return OnlineRewardActionResult.RECIPIENT_OFFLINE + return if (player.performCommand(command)) { OnlineRewardActionResult.ACCEPTED } else { OnlineRewardActionResult.REJECTED } } - override fun sendMessage(playerId: UUID, localeKey: String): OnlineRewardActionResult = mainThread.call { + override fun sendMessage(playerId: UUID, localeKey: String): OnlineRewardActionResult { + requireMainThread() val player = server.getPlayer(playerId) - ?: return@call OnlineRewardActionResult.RECIPIENT_OFFLINE + ?: return OnlineRewardActionResult.RECIPIENT_OFFLINE player.sendMessage(messages.resolve(playerId, localeKey)) - OnlineRewardActionResult.ACCEPTED + return OnlineRewardActionResult.ACCEPTED } - override fun economyAvailable(): Boolean = economy != null + override fun economyAvailable(): Boolean { + requireMainThread() + return economy != null + } - override fun deposit(playerId: UUID, amount: BigDecimal): Boolean = mainThread.call { - requireNotNull(economy) { "Vault economy integration is unavailable." } + override fun deposit(playerId: UUID, amount: BigDecimal): Boolean { + requireMainThread() + return requireNotNull(economy) { "Vault economy integration is unavailable." } .deposit(playerId, amount) } + + private fun requireMainThread() { + check(isPrimaryThread()) { + "Bukkit Reward operations must be called on the server main thread by AsyncRewardDeliveryWorkflow." + } + } } diff --git a/invitecode-platform-bukkit/src/main/kotlin/io/github/command1264/invitecode/platform/bukkit/ClaimInteractionSessions.kt b/invitecode-platform-bukkit/src/main/kotlin/io/github/command1264/invitecode/platform/bukkit/ClaimInteractionSessions.kt new file mode 100644 index 0000000..09e2321 --- /dev/null +++ b/invitecode-platform-bukkit/src/main/kotlin/io/github/command1264/invitecode/platform/bukkit/ClaimInteractionSessions.kt @@ -0,0 +1,82 @@ +package io.github.command1264.invitecode.platform.bukkit + +import io.github.command1264.invitecode.core.ClaimConfirmation +import java.time.Duration +import java.time.Instant +import java.util.UUID + +class ClaimInteractionSessions( + private val now: () -> Instant = Instant::now, +) { + private val sessions = mutableMapOf() + + @Synchronized + fun startChatInput(playerId: UUID, timeout: Duration) { + require(!timeout.isZero && !timeout.isNegative) { "Chat input timeout must be greater than zero." } + sessions[playerId] = Session.ChatInput(now().plus(timeout)) + } + + @Synchronized + fun startConfirmation(confirmation: ClaimConfirmation) { + sessions[confirmation.inviteeId] = Session.Confirmation(confirmation) + } + + @Synchronized + fun hasChatInput(playerId: UUID): Boolean { + val session = sessions[playerId] as? Session.ChatInput ?: return false + if (now().isAfter(session.expiresAt)) { + sessions.remove(playerId) + return false + } + return true + } + + @Synchronized + fun consumeChatInput(playerId: UUID, message: String): String? { + val session = sessions[playerId] as? Session.ChatInput ?: return null + sessions.remove(playerId) + if (now().isAfter(session.expiresAt)) return null + return message.trim() + } + + @Synchronized + fun consumeConfirmation(playerId: UUID): ClaimConfirmation? { + val session = sessions[playerId] as? Session.Confirmation ?: return null + sessions.remove(playerId) + if (now().isAfter(session.value.expiresAt)) return null + return session.value + } + + @Synchronized + fun cancel(playerId: UUID): Boolean = sessions.remove(playerId) != null + + @Synchronized + fun expireChatInput(playerId: UUID): Boolean { + val session = sessions[playerId] as? Session.ChatInput ?: return false + if (!now().isAfter(session.expiresAt)) return false + sessions.remove(playerId) + return true + } + + @Synchronized + fun expireConfirmation(playerId: UUID): Boolean { + val session = sessions[playerId] as? Session.Confirmation ?: return false + if (!now().isAfter(session.value.expiresAt)) return false + sessions.remove(playerId) + return true + } + + fun disconnect(playerId: UUID) { + cancel(playerId) + } + + @Synchronized + fun clear() { + sessions.clear() + } + + private sealed class Session { + data class ChatInput(val expiresAt: Instant) : Session() + data class Confirmation(val value: ClaimConfirmation) : Session() + } +} diff --git a/invitecode-platform-bukkit/src/main/kotlin/io/github/command1264/invitecode/platform/bukkit/InviteCodeCommandParser.kt b/invitecode-platform-bukkit/src/main/kotlin/io/github/command1264/invitecode/platform/bukkit/InviteCodeCommandParser.kt new file mode 100644 index 0000000..2ddd090 --- /dev/null +++ b/invitecode-platform-bukkit/src/main/kotlin/io/github/command1264/invitecode/platform/bukkit/InviteCodeCommandParser.kt @@ -0,0 +1,206 @@ +package io.github.command1264.invitecode.platform.bukkit + +import java.util.Locale + +enum class InviteCodeCommandId { + HELP, + CODE, + CLAIM, + CONFIRM, + CANCEL, + STATUS, + STATS, + ADMIN_INSPECT_PLAYER, + ADMIN_INSPECT_INVITATION, + ADMIN_INSPECT_REWARD, + ADMIN_INVITATION_UNLINK, + ADMIN_INVITATION_TRANSFER, + ADMIN_INVITATION_FORCE_QUALIFY, + ADMIN_ELIGIBILITY_RESET, + ADMIN_REWARD_RETRY, + ADMIN_REWARD_MARK_DELIVERED, + ADMIN_CODE_ROTATE, + ADMIN_STORAGE_MIGRATE, + ADMIN_RELOAD, + ADMIN_DOCTOR, +} + +sealed interface InviteCodeCommandParseResult + +data class ParsedInviteCodeCommand( + val id: InviteCodeCommandId, + val permission: String, + val playerOnly: Boolean, + val allowedDuringMaintenance: Boolean, + val operands: List = emptyList(), + val reason: String? = null, +) : InviteCodeCommandParseResult + +data class InvalidInviteCodeCommand(val messageKey: String) : InviteCodeCommandParseResult + +object InviteCodeCommandParser { + fun parse(rawArguments: List): InviteCodeCommandParseResult { + if (rawArguments.any { it.isBlank() }) return invalid() + val arguments = rawArguments.map { it.lowercase(Locale.ROOT) } + if (arguments.isEmpty() || arguments == listOf("help")) { + return command( + InviteCodeCommandId.HELP, + "invitecode.command.basic", + playerOnly = false, + maintenance = true, + ) + } + return when (arguments.first()) { + "code" -> exact(rawArguments, 1, InviteCodeCommandId.CODE, "invitecode.command.code") + "claim" -> claim(rawArguments) + "confirm" -> exact(rawArguments, 1, InviteCodeCommandId.CONFIRM, "invitecode.command.claim") + "cancel" -> exact(rawArguments, 1, InviteCodeCommandId.CANCEL, "invitecode.command.claim") + "status" -> exact(rawArguments, 1, InviteCodeCommandId.STATUS, "invitecode.command.status") + "stats" -> exact(rawArguments, 1, InviteCodeCommandId.STATS, "invitecode.command.stats") + "reload" -> exact( + rawArguments, + 1, + InviteCodeCommandId.ADMIN_RELOAD, + "invitecode.admin.reload", + playerOnly = false, + ) + "admin" -> parseAdmin(rawArguments, arguments) + else -> invalid() + } + } + + private fun claim(arguments: List): InviteCodeCommandParseResult { + if (arguments.size !in 1..2) return invalid() + return command( + InviteCodeCommandId.CLAIM, + "invitecode.command.claim", + operands = arguments.drop(1), + ) + } + + private fun parseAdmin( + raw: List, + normalized: List, + ): InviteCodeCommandParseResult { + if (normalized.size < 2) return invalid() + return when (normalized[1]) { + "inspect" -> parseInspect(raw, normalized) + "invitation" -> parseInvitationMutation(raw, normalized) + "eligibility" -> reasoned( + raw, normalized, listOf("admin", "eligibility", "reset"), 1, + InviteCodeCommandId.ADMIN_ELIGIBILITY_RESET, "invitecode.admin.eligibility", + ) + "reward" -> parseRewardMutation(raw, normalized) + "code" -> reasoned( + raw, normalized, listOf("admin", "code", "rotate"), 1, + InviteCodeCommandId.ADMIN_CODE_ROTATE, "invitecode.admin.code", + ) + "storage" -> reasoned( + raw, normalized, listOf("admin", "storage", "migrate"), 1, + InviteCodeCommandId.ADMIN_STORAGE_MIGRATE, "invitecode.admin.storage", maintenance = true, + ) + "reload" -> exact( + raw, 2, InviteCodeCommandId.ADMIN_RELOAD, "invitecode.admin.reload", + playerOnly = false, + ) + "doctor" -> exact( + raw, 2, InviteCodeCommandId.ADMIN_DOCTOR, "invitecode.admin.doctor", + playerOnly = false, maintenance = true, + ) + else -> invalid() + } + } + + private fun parseInspect(raw: List, normalized: List): InviteCodeCommandParseResult { + if (raw.size != 4) return invalid() + val id = when (normalized[2]) { + "player" -> InviteCodeCommandId.ADMIN_INSPECT_PLAYER + "invitation" -> InviteCodeCommandId.ADMIN_INSPECT_INVITATION + "reward" -> InviteCodeCommandId.ADMIN_INSPECT_REWARD + else -> return invalid() + } + return command(id, "invitecode.admin.inspect", playerOnly = false, operands = listOf(raw[3])) + } + + private fun parseInvitationMutation( + raw: List, + normalized: List, + ): InviteCodeCommandParseResult = when (normalized.getOrNull(2)) { + "unlink" -> reasoned( + raw, normalized, listOf("admin", "invitation", "unlink"), 1, + InviteCodeCommandId.ADMIN_INVITATION_UNLINK, "invitecode.admin.invitation", + ) + "transfer" -> reasoned( + raw, normalized, listOf("admin", "invitation", "transfer"), 2, + InviteCodeCommandId.ADMIN_INVITATION_TRANSFER, "invitecode.admin.invitation", + ) + "force-qualify" -> reasoned( + raw, normalized, listOf("admin", "invitation", "force-qualify"), 2, + InviteCodeCommandId.ADMIN_INVITATION_FORCE_QUALIFY, "invitecode.admin.qualification", + ) + else -> invalid() + } + + private fun parseRewardMutation( + raw: List, + normalized: List, + ): InviteCodeCommandParseResult = when (normalized.getOrNull(2)) { + "retry" -> reasoned( + raw, normalized, listOf("admin", "reward", "retry"), 1, + InviteCodeCommandId.ADMIN_REWARD_RETRY, "invitecode.admin.reward", + ) + "mark-delivered" -> reasoned( + raw, normalized, listOf("admin", "reward", "mark-delivered"), 1, + InviteCodeCommandId.ADMIN_REWARD_MARK_DELIVERED, "invitecode.admin.reward", + ) + else -> invalid() + } + + private fun reasoned( + raw: List, + normalized: List, + prefix: List, + operandCount: Int, + id: InviteCodeCommandId, + permission: String, + maintenance: Boolean = false, + ): InviteCodeCommandParseResult { + if (normalized.take(prefix.size) != prefix) return invalid() + val reasonStart = prefix.size + operandCount + if (raw.size <= reasonStart) return InvalidInviteCodeCommand("command.reason-required") + val reason = raw.drop(reasonStart).joinToString(" ").trim() + if (reason.isBlank()) return InvalidInviteCodeCommand("command.reason-required") + return command( + id, + permission, + playerOnly = false, + maintenance = maintenance, + operands = raw.subList(prefix.size, reasonStart), + reason = reason, + ) + } + + private fun exact( + arguments: List, + size: Int, + id: InviteCodeCommandId, + permission: String, + playerOnly: Boolean = true, + maintenance: Boolean = false, + ): InviteCodeCommandParseResult = if (arguments.size == size) { + command(id, permission, playerOnly, maintenance) + } else { + invalid() + } + + private fun command( + id: InviteCodeCommandId, + permission: String, + playerOnly: Boolean = true, + maintenance: Boolean = false, + operands: List = emptyList(), + reason: String? = null, + ) = ParsedInviteCodeCommand(id, permission, playerOnly, maintenance, operands, reason) + + private fun invalid() = InvalidInviteCodeCommand("command.usage") +} diff --git a/invitecode-platform-bukkit/src/main/kotlin/io/github/command1264/invitecode/platform/bukkit/InviteCodeTabCompletion.kt b/invitecode-platform-bukkit/src/main/kotlin/io/github/command1264/invitecode/platform/bukkit/InviteCodeTabCompletion.kt new file mode 100644 index 0000000..b48bbb2 --- /dev/null +++ b/invitecode-platform-bukkit/src/main/kotlin/io/github/command1264/invitecode/platform/bukkit/InviteCodeTabCompletion.kt @@ -0,0 +1,123 @@ +package io.github.command1264.invitecode.platform.bukkit + +import java.util.Locale + +object InviteCodeTabCompletion { + fun complete( + arguments: List, + player: Boolean, + hasPermission: (String) -> Boolean, + onlinePlayerNames: Collection, + ): List { + if (arguments.isEmpty()) return emptyList() + val path = arguments.dropLast(1).map { it.lowercase(Locale.ROOT) } + val prefix = arguments.last() + val candidates = if ( + path.size == 4 && path.take(3) == listOf("admin", "invitation", "transfer") + ) { + permitted(hasPermission, "invitecode.admin.invitation", onlinePlayerNames) + } else when (path) { + emptyList() -> rootCandidates(player, hasPermission) + listOf("admin") -> adminCandidates(hasPermission) + listOf("admin", "inspect") -> permitted( + hasPermission, + "invitecode.admin.inspect", + "player", + "invitation", + "reward", + ) + listOf("admin", "invitation") -> invitationCandidates(hasPermission) + listOf("admin", "eligibility") -> permitted( + hasPermission, + "invitecode.admin.eligibility", + "reset", + ) + listOf("admin", "reward") -> permitted( + hasPermission, + "invitecode.admin.reward", + "retry", + "mark-delivered", + ) + listOf("admin", "code") -> permitted( + hasPermission, + "invitecode.admin.code", + "rotate", + ) + listOf("admin", "storage") -> permitted( + hasPermission, + "invitecode.admin.storage", + "migrate", + ) + listOf("admin", "inspect", "player") -> + permitted(hasPermission, "invitecode.admin.inspect", onlinePlayerNames) + listOf("admin", "eligibility", "reset") -> + permitted(hasPermission, "invitecode.admin.eligibility", onlinePlayerNames) + listOf("admin", "code", "rotate") -> + permitted(hasPermission, "invitecode.admin.code", onlinePlayerNames) + listOf("admin", "storage", "migrate") -> + permitted(hasPermission, "invitecode.admin.storage", listOf("SQLITE")) + else -> emptyList() + } + return candidates + .asSequence() + .filter { it.startsWith(prefix, ignoreCase = true) } + .distinct() + .sortedWith(String.CASE_INSENSITIVE_ORDER) + .toList() + } + + private fun rootCandidates( + player: Boolean, + hasPermission: (String) -> Boolean, + ): List = buildList { + if (hasPermission("invitecode.command.basic")) add("help") + if (player && hasPermission("invitecode.command.code")) add("code") + if (player && hasPermission("invitecode.command.claim")) addAll(listOf("claim", "confirm", "cancel")) + if (player && hasPermission("invitecode.command.status")) add("status") + if (player && hasPermission("invitecode.command.stats")) add("stats") + if (hasPermission("invitecode.admin.reload")) add("reload") + if (ADMIN_PERMISSIONS.any(hasPermission)) add("admin") + } + + private fun adminCandidates(hasPermission: (String) -> Boolean): List = buildList { + if (hasPermission("invitecode.admin.inspect")) add("inspect") + if (hasPermission("invitecode.admin.invitation") || hasPermission("invitecode.admin.qualification")) { + add("invitation") + } + if (hasPermission("invitecode.admin.eligibility")) add("eligibility") + if (hasPermission("invitecode.admin.reward")) add("reward") + if (hasPermission("invitecode.admin.code")) add("code") + if (hasPermission("invitecode.admin.storage")) add("storage") + if (hasPermission("invitecode.admin.reload")) add("reload") + if (hasPermission("invitecode.admin.doctor")) add("doctor") + } + + private fun invitationCandidates(hasPermission: (String) -> Boolean): List = buildList { + if (hasPermission("invitecode.admin.invitation")) addAll(listOf("unlink", "transfer")) + if (hasPermission("invitecode.admin.qualification")) add("force-qualify") + } + + private fun permitted( + hasPermission: (String) -> Boolean, + permission: String, + vararg candidates: String, + ): List = if (hasPermission(permission)) candidates.toList() else emptyList() + + private fun permitted( + hasPermission: (String) -> Boolean, + permission: String, + candidates: Collection, + ): Collection = if (hasPermission(permission)) candidates else emptyList() + + private val ADMIN_PERMISSIONS = listOf( + "invitecode.admin.inspect", + "invitecode.admin.invitation", + "invitecode.admin.eligibility", + "invitecode.admin.qualification", + "invitecode.admin.reward", + "invitecode.admin.code", + "invitecode.admin.storage", + "invitecode.admin.reload", + "invitecode.admin.doctor", + ) +} diff --git a/invitecode-platform-bukkit/src/main/kotlin/io/github/command1264/invitecode/platform/bukkit/LocalizedMessages.kt b/invitecode-platform-bukkit/src/main/kotlin/io/github/command1264/invitecode/platform/bukkit/LocalizedMessages.kt new file mode 100644 index 0000000..3371969 --- /dev/null +++ b/invitecode-platform-bukkit/src/main/kotlin/io/github/command1264/invitecode/platform/bukkit/LocalizedMessages.kt @@ -0,0 +1,48 @@ +package io.github.command1264.invitecode.platform.bukkit + +import java.util.Locale + +class LocalizedMessages( + private val defaultLocale: String, + private val useClientLocale: Boolean, + catalogs: Map>, + private val onMissingKey: (String) -> Unit = {}, +) { + private val catalogs = catalogs.mapKeys { normalizeLocale(it.key) } + + init { + require(this.catalogs.containsKey(normalizeLocale(defaultLocale))) { + "Default locale $defaultLocale does not have a message catalog." + } + } + + fun resolve(clientLocale: String?, key: String): String { + require(key.isNotBlank()) { "Message key must not be blank." } + val preferred = if (useClientLocale && clientLocale != null) { + catalogs[normalizeLocale(clientLocale)] + } else { + null + } + preferred?.get(key)?.let { return it } + catalogs.getValue(normalizeLocale(defaultLocale))[key]?.let { return it } + onMissingKey(key) + return "[missing: $key]" + } + + fun resolve(clientLocale: String?, key: String, variables: Map): String { + require(variables.keys.all(VARIABLE_NAME::matches)) { "Message variable names must use lowercase snake_case." } + return variables.entries.fold(resolve(clientLocale, key)) { message, (name, value) -> + message.replace("{$name}", value) + } + } + + private fun normalizeLocale(raw: String): String { + val parts = raw.replace('-', '_').split('_', limit = 2) + if (parts.size != 2) return raw + return parts[0].lowercase(Locale.ROOT) + "_" + parts[1].uppercase(Locale.ROOT) + } + + private companion object { + val VARIABLE_NAME = Regex("[a-z][a-z0-9_]*") + } +} diff --git a/invitecode-platform-bukkit/src/main/kotlin/io/github/command1264/invitecode/platform/bukkit/NetworkAddressHasher.kt b/invitecode-platform-bukkit/src/main/kotlin/io/github/command1264/invitecode/platform/bukkit/NetworkAddressHasher.kt new file mode 100644 index 0000000..520961e --- /dev/null +++ b/invitecode-platform-bukkit/src/main/kotlin/io/github/command1264/invitecode/platform/bukkit/NetworkAddressHasher.kt @@ -0,0 +1,105 @@ +package io.github.command1264.invitecode.platform.bukkit + +import java.nio.file.FileAlreadyExistsException +import java.nio.file.Files +import java.nio.file.Path +import java.nio.file.StandardOpenOption +import java.nio.file.attribute.PosixFilePermission +import java.security.SecureRandom +import java.security.MessageDigest +import java.util.concurrent.atomic.AtomicBoolean +import javax.crypto.Mac +import javax.crypto.spec.SecretKeySpec + +class NetworkAddressHasher private constructor( + secret: ByteArray, +) : AutoCloseable { + private val key = secret.copyOf() + private val closed = AtomicBoolean(false) + val keyId: String = MessageDigest.getInstance("SHA-256") + .digest(key) + .joinToString("") { byte -> "%02x".format(byte.toInt() and 0xff) } + + init { + require(key.size == SECRET_SIZE) { "Network hash secret must contain exactly $SECRET_SIZE bytes." } + } + + fun hash(addressBytes: ByteArray): String { + check(!closed.get()) { "Network address hasher is closed." } + require(addressBytes.size == IPV4_SIZE || addressBytes.size == IPV6_SIZE) { + "Network address must be a 4-byte IPv4 or 16-byte IPv6 address." + } + val normalized = normalize(addressBytes) + return try { + val mac = Mac.getInstance(ALGORITHM) + mac.init(SecretKeySpec(key, ALGORITHM)) + mac.doFinal(normalized).joinToString("") { byte -> "%02x".format(byte.toInt() and 0xff) } + } finally { + normalized.fill(0) + } + } + + override fun close() { + if (closed.compareAndSet(false, true)) key.fill(0) + } + + companion object { + private const val ALGORITHM = "HmacSHA256" + private const val SECRET_SIZE = 32 + private const val IPV4_SIZE = 4 + private const val IPV6_SIZE = 16 + + fun loadExisting(path: Path): NetworkAddressHasher { + require(Files.isRegularFile(path)) { + "Network hash secret ${path.toAbsolutePath()} is missing; run the explicit storage migration." + } + val bytes = Files.readAllBytes(path) + require(bytes.size == SECRET_SIZE) { + "Network hash secret ${path.toAbsolutePath()} must contain exactly $SECRET_SIZE bytes." + } + return try { + NetworkAddressHasher(bytes) + } finally { + bytes.fill(0) + } + } + + fun loadOrCreate(path: Path, random: SecureRandom = SecureRandom()): NetworkAddressHasher { + if (Files.exists(path)) return loadExisting(path) + path.toAbsolutePath().parent?.let(Files::createDirectories) + val bytes = ByteArray(SECRET_SIZE).also(random::nextBytes) + try { + try { + Files.write(path, bytes, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE) + restrictPosixPermissions(path) + } catch (_: FileAlreadyExistsException) { + return loadExisting(path) + } + return NetworkAddressHasher(bytes) + } finally { + bytes.fill(0) + } + } + + private fun normalize(addressBytes: ByteArray): ByteArray { + val ipv4MappedPrefix = byteArrayOf(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1) + return if ( + addressBytes.size == IPV6_SIZE && + addressBytes.copyOfRange(0, ipv4MappedPrefix.size).contentEquals(ipv4MappedPrefix) + ) { + addressBytes.copyOfRange(ipv4MappedPrefix.size, IPV6_SIZE) + } else { + addressBytes.copyOf() + } + } + + private fun restrictPosixPermissions(path: Path) { + runCatching { + Files.setPosixFilePermissions( + path, + setOf(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE), + ) + } + } + } +} diff --git a/invitecode-platform-bukkit/src/main/kotlin/io/github/command1264/invitecode/platform/bukkit/PluginRuntimeState.kt b/invitecode-platform-bukkit/src/main/kotlin/io/github/command1264/invitecode/platform/bukkit/PluginRuntimeState.kt new file mode 100644 index 0000000..bc81cce --- /dev/null +++ b/invitecode-platform-bukkit/src/main/kotlin/io/github/command1264/invitecode/platform/bukkit/PluginRuntimeState.kt @@ -0,0 +1,91 @@ +package io.github.command1264.invitecode.platform.bukkit + +import java.util.concurrent.atomic.AtomicLong +import java.util.concurrent.atomic.AtomicReference + +enum class RuntimePhase { + STARTING, + ACTIVE, + MAINTENANCE, + STOPPING, + STOPPED, +} + +class PluginRuntimeState { + private val currentPhase = AtomicReference(RuntimePhase.STARTING) + private val currentMaintenanceReason = AtomicReference(null) + + val phase: RuntimePhase + get() = currentPhase.get() + + val maintenanceReason: String? + get() = currentMaintenanceReason.get() + + fun activate() { + transition(setOf(RuntimePhase.STARTING, RuntimePhase.MAINTENANCE), RuntimePhase.ACTIVE) + currentMaintenanceReason.set(null) + } + + fun enterMaintenance(reason: String) { + require(reason.isNotBlank()) { "Maintenance reason must not be blank." } + while (true) { + val existing = currentPhase.get() + check(existing in setOf(RuntimePhase.STARTING, RuntimePhase.ACTIVE, RuntimePhase.MAINTENANCE)) { + "Cannot enter maintenance from $existing." + } + if (currentPhase.compareAndSet(existing, RuntimePhase.MAINTENANCE)) { + currentMaintenanceReason.set(reason) + return + } + } + } + + fun beginStopping() { + while (true) { + val existing = currentPhase.get() + if (existing == RuntimePhase.STOPPING) return + check(existing != RuntimePhase.STOPPED) { "Runtime has already stopped." } + if (currentPhase.compareAndSet(existing, RuntimePhase.STOPPING)) return + } + } + + fun finishStopping() { + transition(setOf(RuntimePhase.STOPPING), RuntimePhase.STOPPED) + currentMaintenanceReason.set(null) + } + + fun acceptsGameplayCommands(): Boolean = phase == RuntimePhase.ACTIVE + + private fun transition(allowed: Set, target: RuntimePhase) { + while (true) { + val existing = currentPhase.get() + check(existing in allowed) { "Cannot transition runtime from $existing to $target." } + if (currentPhase.compareAndSet(existing, target)) return + } + } +} + +data class RuntimeSnapshot( + val generation: Long, + val value: T, +) + +class AtomicRuntimeSnapshot private constructor(initialSnapshot: RuntimeSnapshot?) { + constructor(initialValue: T) : this(RuntimeSnapshot(0, initialValue)) + constructor() : this(null) + + private val generation = AtomicLong(initialSnapshot?.generation ?: -1) + private val snapshot = AtomicReference(initialSnapshot) + + fun current(): RuntimeSnapshot = requireNotNull(snapshot.get()) { + "Runtime snapshot has not been installed." + } + + fun currentOrNull(): RuntimeSnapshot? = snapshot.get() + + fun replace(candidate: T): RuntimeSnapshot { + val replacement = RuntimeSnapshot(generation.incrementAndGet(), candidate) + snapshot.set(replacement) + return replacement + } +} 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 new file mode 100644 index 0000000..a872827 --- /dev/null +++ b/invitecode-platform-bukkit/src/main/kotlin/io/github/command1264/invitecode/platform/bukkit/RuntimeConfigurationAssembler.kt @@ -0,0 +1,133 @@ +package io.github.command1264.invitecode.platform.bukkit + +import io.github.command1264.invitecode.core.QualificationConfiguration +import io.github.command1264.invitecode.core.QualificationConfigurationParser +import io.github.command1264.invitecode.core.RewardActionType +import io.github.command1264.invitecode.core.RewardConfiguration +import io.github.command1264.invitecode.core.RewardConfigurationParser +import io.github.command1264.invitecode.core.StorageConfiguration +import io.github.command1264.invitecode.core.StorageConfigurationParser + +data class InviteCodeRuntimeConfiguration( + val general: BukkitPluginConfiguration, + val storage: StorageConfiguration, + val qualifications: QualificationConfiguration, + val rewards: RewardConfiguration, + val messages: LocalizedMessages, + val availableLocales: Set, +) + +data class RuntimeReloadCandidate( + val configuration: InviteCodeRuntimeConfiguration, + val storageRestartRequired: Boolean, +) + +object RuntimeConfigurationReload { + fun reconcile( + current: InviteCodeRuntimeConfiguration, + candidate: InviteCodeRuntimeConfiguration, + ): RuntimeReloadCandidate { + val storageChanged = current.storage != candidate.storage + return RuntimeReloadCandidate( + if (storageChanged) candidate.copy(storage = current.storage) else candidate, + storageChanged, + ) + } +} + +object RuntimeConfigurationAssembler { + fun parse( + general: Map, + storage: Map, + qualifications: Map, + rewards: Map, + messageCatalogs: Map>, + onMissingMessage: (String) -> Unit = {}, + ): InviteCodeRuntimeConfiguration { + val parsedGeneral = BukkitPluginConfigurationParser.parse(general) + val parsedStorage = StorageConfigurationParser.parse(storage).requireSupportedBackend() + val parsedQualifications = QualificationConfigurationParser.parse(qualifications) + val parsedRewards = RewardConfigurationParser.parse(rewards) + require(messageCatalogs.isNotEmpty()) { "At least one message catalog is required." } + val parsedCatalogs = messageCatalogs.mapValues { (locale, document) -> + MessageCatalogParser.parse(locale, document) + } + val defaultCatalog = parsedCatalogs[parsedGeneral.language.defaultLocale] + ?: throw IllegalArgumentException( + "Default locale ${parsedGeneral.language.defaultLocale} does not have a message catalog.", + ) + val rewardMessageKeys = buildList { + parsedRewards.qualificationRewards.values.forEach { reward -> + addAll(reward.inviterActions.filter { it.type == RewardActionType.MESSAGE }.map { it.payload }) + addAll(reward.inviteeActions.filter { it.type == RewardActionType.MESSAGE }.map { it.payload }) + } + parsedRewards.milestoneRewards.values.forEach { reward -> + addAll(reward.inviterActions.filter { it.type == RewardActionType.MESSAGE }.map { it.payload }) + } + }.toSet() + val missingRewardMessages = rewardMessageKeys - defaultCatalog.keys + require(missingRewardMessages.isEmpty()) { + "Default locale is missing Reward message keys: ${missingRewardMessages.sorted().joinToString()}." + } + return InviteCodeRuntimeConfiguration( + general = parsedGeneral, + storage = parsedStorage, + qualifications = parsedQualifications, + rewards = parsedRewards, + messages = LocalizedMessages( + parsedGeneral.language.defaultLocale, + parsedGeneral.language.useClientLocale, + parsedCatalogs, + onMissingMessage, + ), + availableLocales = parsedCatalogs.keys, + ) + } +} + +object MessageCatalogParser { + const val CURRENT_VERSION = 1 + + fun parse(locale: String, document: Map): Map { + require(locale.isNotBlank()) { "Message catalog locale must not be blank." } + val version = (document["messages-version"] as? Number)?.toString()?.toIntOrNull() + ?: throw IllegalArgumentException("Message catalog $locale requires integer messages-version.") + require(version == CURRENT_VERSION) { + "Message catalog $locale version $version is unsupported; expected $CURRENT_VERSION." + } + require(document.keys.any { it != "messages-version" }) { + "Message catalog $locale must contain at least one message." + } + val messages = linkedMapOf() + document.filterKeys { it != "messages-version" }.forEach { (key, value) -> + flatten(locale, key, value, messages) + } + return messages + } + + private fun flatten( + locale: String, + key: String, + value: Any?, + destination: MutableMap, + ) { + require(key.isNotBlank()) { "Message catalog $locale contains a blank key." } + when (value) { + is String -> { + require(value.isNotBlank()) { "Message catalog $locale key $key must not be blank." } + destination[key] = value + } + is Map<*, *> -> { + require(value.isNotEmpty() && value.keys.all { it is String }) { + "Message catalog $locale key $key must be a non-empty map with string keys." + } + value.forEach { (childKey, childValue) -> + flatten(locale, "$key.${childKey as String}", childValue, destination) + } + } + else -> throw IllegalArgumentException( + "Message catalog $locale key $key must be a string or nested map.", + ) + } + } +} diff --git a/invitecode-platform-bukkit/src/test/kotlin/io/github/command1264/invitecode/platform/bukkit/AsyncOperationExecutorTest.kt b/invitecode-platform-bukkit/src/test/kotlin/io/github/command1264/invitecode/platform/bukkit/AsyncOperationExecutorTest.kt new file mode 100644 index 0000000..12785fe --- /dev/null +++ b/invitecode-platform-bukkit/src/test/kotlin/io/github/command1264/invitecode/platform/bukkit/AsyncOperationExecutorTest.kt @@ -0,0 +1,63 @@ +package io.github.command1264.invitecode.platform.bukkit + +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 java.time.Duration +import java.util.concurrent.CountDownLatch +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.TimeUnit + +class AsyncOperationExecutorTest { + @Test + fun `runs blocking work off caller and returns result through main dispatcher`() { + val callbacks = CopyOnWriteArrayList<() -> Unit>() + val completed = CountDownLatch(1) + val caller = Thread.currentThread().name + var worker = caller + var result: String? = null + AsyncOperationExecutor("invitecode-test", callbacks::add).use { executor -> + assertTrue(executor.submit( + operation = { + worker = Thread.currentThread().name + "ok" + }, + onSuccess = { result = it; completed.countDown() }, + onFailure = { throw AssertionError(it) }, + )) + waitForCallbacks(callbacks) + callbacks.removeAt(0).invoke() + assertTrue(completed.await(1, TimeUnit.SECONDS)) + } + + assertTrue(worker.startsWith("invitecode-test")) + assertTrue(worker != caller) + assertEquals("ok", result) + } + + @Test + fun `close rejects new work and suppresses late callback`() { + val callbacks = CopyOnWriteArrayList<() -> Unit>() + val release = CountDownLatch(1) + val executor = AsyncOperationExecutor("invitecode-test", callbacks::add) + assertTrue(executor.submit( + operation = { release.await(); "late" }, + onSuccess = { throw AssertionError("late callback must be suppressed") }, + onFailure = { }, + )) + + release.countDown() + assertTrue(executor.close(Duration.ofSeconds(1))) + assertFalse(executor.submit({ "rejected" }, {}, {})) + callbacks.forEach { it.invoke() } + } + + private fun waitForCallbacks(callbacks: List<() -> Unit>) { + repeat(100) { + if (callbacks.isNotEmpty()) return + Thread.sleep(5) + } + throw AssertionError("Timed out waiting for callback") + } +} diff --git a/invitecode-platform-bukkit/src/test/kotlin/io/github/command1264/invitecode/platform/bukkit/AsyncRewardDeliveryWorkflowTest.kt b/invitecode-platform-bukkit/src/test/kotlin/io/github/command1264/invitecode/platform/bukkit/AsyncRewardDeliveryWorkflowTest.kt new file mode 100644 index 0000000..885a2e8 --- /dev/null +++ b/invitecode-platform-bukkit/src/test/kotlin/io/github/command1264/invitecode/platform/bukkit/AsyncRewardDeliveryWorkflowTest.kt @@ -0,0 +1,165 @@ +package io.github.command1264.invitecode.platform.bukkit + +import io.github.command1264.invitecode.core.RewardActionExecutionContext +import io.github.command1264.invitecode.core.RewardActionExecutionResult +import io.github.command1264.invitecode.core.RewardActionExecutor +import io.github.command1264.invitecode.core.RewardActionProcessingStatus +import io.github.command1264.invitecode.core.RewardActionReadiness +import io.github.command1264.invitecode.core.RewardActionStatus +import io.github.command1264.invitecode.core.StoredRewardAction +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 java.time.Instant +import java.util.UUID + +class AsyncRewardDeliveryWorkflowTest { + @Test + fun `persists processing before executing external effect`() { + val store = InMemoryRewardActionStateStore(action()) + var executed = false + val workflow = AsyncRewardDeliveryWorkflow( + ImmediateOperations, + store, + object : RewardActionExecutor { + override fun readiness( + action: StoredRewardAction, + context: RewardActionExecutionContext, + ) = RewardActionReadiness.READY + + override fun execute( + action: StoredRewardAction, + context: RewardActionExecutionContext, + ): RewardActionExecutionResult { + assertEquals(RewardActionStatus.PROCESSING, store.current.status) + executed = true + return RewardActionExecutionResult.Delivered + } + }, + ) + var status: RewardActionProcessingStatus? = null + + assertTrue( + workflow.process(store.current, context(store.current), onComplete = { status = it.status }), + ) + + assertTrue(executed) + assertEquals(RewardActionStatus.DELIVERED, store.current.status) + assertEquals(RewardActionProcessingStatus.DELIVERED, status) + } + + @Test + fun `offline recipient stays pending without external effect`() { + val store = InMemoryRewardActionStateStore(action()) + var executed = false + val workflow = AsyncRewardDeliveryWorkflow( + ImmediateOperations, + store, + object : RewardActionExecutor { + override fun readiness( + action: StoredRewardAction, + context: RewardActionExecutionContext, + ) = RewardActionReadiness.RECIPIENT_OFFLINE + + override fun execute( + action: StoredRewardAction, + context: RewardActionExecutionContext, + ): RewardActionExecutionResult { + executed = true + return RewardActionExecutionResult.Delivered + } + }, + ) + var status: RewardActionProcessingStatus? = null + + workflow.process(store.current, context(store.current), onComplete = { status = it.status }) + + assertFalse(executed) + assertEquals(RewardActionStatus.PENDING, store.current.status) + assertEquals(RewardActionProcessingStatus.DEFERRED, status) + } + + @Test + fun `unknown external result becomes uncertain`() { + val store = InMemoryRewardActionStateStore(action()) + val workflow = AsyncRewardDeliveryWorkflow( + ImmediateOperations, + store, + object : RewardActionExecutor { + override fun readiness( + action: StoredRewardAction, + context: RewardActionExecutionContext, + ) = RewardActionReadiness.READY + + override fun execute( + action: StoredRewardAction, + context: RewardActionExecutionContext, + ): RewardActionExecutionResult = throw IllegalStateException("unknown result") + }, + ) + var status: RewardActionProcessingStatus? = null + + workflow.process(store.current, context(store.current), onComplete = { status = it.status }) + + assertEquals(RewardActionStatus.UNCERTAIN, store.current.status) + assertEquals(RewardActionProcessingStatus.UNCERTAIN, status) + } + + private fun action(): StoredRewardAction { + val now = Instant.parse("2026-01-01T00:00:00Z") + return StoredRewardAction( + id = UUID.randomUUID(), + rewardDeliveryId = UUID.randomUUID(), + invitationId = UUID.randomUUID(), + recipientId = UUID.randomUUID(), + position = 0, + type = "MESSAGE", + payload = "invite.completed", + status = RewardActionStatus.PENDING, + idempotencyKey = "test-action", + createdAt = now, + updatedAt = now, + ) + } + + private fun context(action: StoredRewardAction) = RewardActionExecutionContext( + recipientId = action.recipientId, + recipientName = "Player", + inviterId = null, + inviterName = null, + inviteeId = null, + inviteeName = null, + ) +} + +private object ImmediateOperations : BackgroundOperationExecutor { + override fun submit( + operation: () -> T, + onSuccess: (T) -> Unit, + onFailure: (Throwable) -> Unit, + ): Boolean { + runCatching(operation).fold(onSuccess, onFailure) + return true + } +} + +private class InMemoryRewardActionStateStore(initial: StoredRewardAction) : RewardActionStateStore { + var current = initial + private set + + override fun action(actionId: UUID): StoredRewardAction? = current.takeIf { it.id == actionId } + + override fun begin(actionId: UUID, occurredAt: Instant) = transition(RewardActionStatus.PROCESSING, occurredAt) + override fun delivered(actionId: UUID, occurredAt: Instant) = transition(RewardActionStatus.DELIVERED, occurredAt) + override fun failed(actionId: UUID, reason: String, occurredAt: Instant) = + transition(RewardActionStatus.FAILED, occurredAt, reason) + override fun deferred(actionId: UUID, occurredAt: Instant) = transition(RewardActionStatus.PENDING, occurredAt) + override fun uncertain(actionId: UUID, reason: String, occurredAt: Instant) = + transition(RewardActionStatus.UNCERTAIN, occurredAt, reason) + + private fun transition(status: RewardActionStatus, occurredAt: Instant, error: String? = null): StoredRewardAction { + current = current.copy(status = status, updatedAt = occurredAt, lastError = error) + return current + } +} diff --git a/invitecode-platform-bukkit/src/test/kotlin/io/github/command1264/invitecode/platform/bukkit/BukkitPluginConfigurationTest.kt b/invitecode-platform-bukkit/src/test/kotlin/io/github/command1264/invitecode/platform/bukkit/BukkitPluginConfigurationTest.kt new file mode 100644 index 0000000..28c0d6f --- /dev/null +++ b/invitecode-platform-bukkit/src/test/kotlin/io/github/command1264/invitecode/platform/bukkit/BukkitPluginConfigurationTest.kt @@ -0,0 +1,69 @@ +package io.github.command1264.invitecode.platform.bukkit + +import io.github.command1264.invitecode.core.MatchingNetworkAction +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 java.time.Duration +import java.time.ZoneId + +class BukkitPluginConfigurationTest { + @Test + fun `parses the versioned general configuration`() { + val configuration = BukkitPluginConfigurationParser.parse(validConfiguration()) + + assertEquals("zh_TW", configuration.language.defaultLocale) + assertTrue(configuration.language.useClientLocale) + assertEquals(InputMode.AUTO, configuration.claim.inputMode) + assertEquals(Duration.ofHours(24), configuration.claim.window) + assertEquals(Duration.ofSeconds(30), configuration.claim.confirmationTimeout) + assertEquals(Duration.ofSeconds(60), configuration.claim.chatInputTimeout) + assertEquals(ZoneId.of("Asia/Taipei"), configuration.timeZone) + assertFalse(configuration.inviteCode.customCodesEnabled) + assertEquals(MatchingNetworkAction.DENY, configuration.antiAbuse.matchingIpAction) + } + + @Test + fun `rejects unknown fields and unsupported versions`() { + val unknown = validConfiguration().toMutableMap().apply { put("surprise", true) } + assertThrows { BukkitPluginConfigurationParser.parse(unknown) } + + val unsupported = validConfiguration().toMutableMap().apply { put("config-version", 2) } + assertThrows { BukkitPluginConfigurationParser.parse(unsupported) } + } + + @Test + fun `rejects Dialog mode until the modern adapter owns it`() { + val claim = (validConfiguration().getValue("claim") as Map).toMutableMap() + claim["input-mode"] = "DIALOG" + val root = validConfiguration().toMutableMap().apply { put("claim", claim) } + + assertThrows { BukkitPluginConfigurationParser.parse(root) } + } + + private fun validConfiguration(): Map = mapOf( + "config-version" to 1, + "language" to mapOf( + "default" to "zh_TW", + "use-client-locale" to true, + ), + "invite-code" to mapOf( + "format" to "HEX_COLOR", + "custom-codes-enabled" to false, + ), + "claim" to mapOf( + "window" to "24h", + "input-mode" to "AUTO", + "confirmation-timeout" to "30s", + "chat-input-timeout" to "60s", + "existing-player-policy" to "START_WINDOW", + ), + "anti-abuse" to mapOf( + "matching-ip-action" to "DENY", + "ip-hash-retention" to "30d", + ), + "time-zone" to "Asia/Taipei", + ) +} diff --git a/invitecode-platform-bukkit/src/test/kotlin/io/github/command1264/invitecode/platform/bukkit/ClaimInteractionSessionsTest.kt b/invitecode-platform-bukkit/src/test/kotlin/io/github/command1264/invitecode/platform/bukkit/ClaimInteractionSessionsTest.kt new file mode 100644 index 0000000..2e228b7 --- /dev/null +++ b/invitecode-platform-bukkit/src/test/kotlin/io/github/command1264/invitecode/platform/bukkit/ClaimInteractionSessionsTest.kt @@ -0,0 +1,100 @@ +package io.github.command1264.invitecode.platform.bukkit + +import io.github.command1264.invitecode.core.ClaimConfirmation +import io.github.command1264.invitecode.core.InviteCode +import io.github.command1264.invitecode.core.InviteCodeFormats +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import java.time.Duration +import java.time.Instant +import java.util.UUID + +class ClaimInteractionSessionsTest { + @Test + fun `chat input does not consume an active confirmation`() { + val now = Instant.parse("2026-01-01T00:00:00Z") + val playerId = UUID.randomUUID() + val confirmation = ClaimConfirmation.present( + playerId, + UUID.randomUUID(), + "Inviter", + InviteCode.parse("ABCDEF", InviteCodeFormats.colorHex), + now, + Duration.ofSeconds(30), + ) + val sessions = ClaimInteractionSessions { now } + sessions.startConfirmation(confirmation) + + assertEquals(null, sessions.consumeChatInput(playerId, "not a code")) + assertEquals(confirmation, sessions.consumeConfirmation(playerId)) + } + + @Test + fun `expired chat input is removed exactly once`() { + var now = Instant.parse("2026-01-01T00:00:00Z") + val playerId = UUID.randomUUID() + val sessions = ClaimInteractionSessions { now } + sessions.startChatInput(playerId, Duration.ofSeconds(1)) + + assertFalse(sessions.expireChatInput(playerId)) + now = now.plusSeconds(2) + assertTrue(sessions.expireChatInput(playerId)) + assertFalse(sessions.expireChatInput(playerId)) + } + + @Test + fun `chat input is private one shot and expires`() { + var now = Instant.EPOCH + val sessions = ClaimInteractionSessions { now } + + sessions.startChatInput(playerId, Duration.ofSeconds(60)) + assertTrue(sessions.hasChatInput(playerId)) + assertEquals("a1b2c3", sessions.consumeChatInput(playerId, " a1b2c3 ")) + assertNull(sessions.consumeChatInput(playerId, "second")) + + sessions.startChatInput(playerId, Duration.ofSeconds(60)) + now = now.plusSeconds(61) + assertNull(sessions.consumeChatInput(playerId, "expired")) + assertFalse(sessions.hasChatInput(playerId)) + } + + @Test + fun `confirmation replaces input and is consumed once`() { + val sessions = ClaimInteractionSessions { Instant.EPOCH } + sessions.startChatInput(playerId, Duration.ofSeconds(60)) + val confirmation = ClaimConfirmation.present( + inviteeId = playerId, + inviterId = inviterId, + inviterName = "Inviter", + inviteCode = InviteCode.parse("A1B2C3"), + presentedAt = Instant.EPOCH, + validity = Duration.ofSeconds(30), + ) + + sessions.startConfirmation(confirmation) + + assertFalse(sessions.hasChatInput(playerId)) + assertEquals(confirmation, sessions.consumeConfirmation(playerId)) + assertNull(sessions.consumeConfirmation(playerId)) + } + + @Test + fun `cancel and disconnect clear every session`() { + val sessions = ClaimInteractionSessions { Instant.EPOCH } + sessions.startChatInput(playerId, Duration.ofSeconds(60)) + assertTrue(sessions.cancel(playerId)) + assertFalse(sessions.cancel(playerId)) + + sessions.startChatInput(playerId, Duration.ofSeconds(60)) + sessions.disconnect(playerId) + assertFalse(sessions.hasChatInput(playerId)) + } + + companion object { + private val playerId = UUID.fromString("00000000-0000-0000-0000-000000000001") + private val inviterId = UUID.fromString("00000000-0000-0000-0000-000000000002") + } +} diff --git a/invitecode-platform-bukkit/src/test/kotlin/io/github/command1264/invitecode/platform/bukkit/InviteCodeCommandParserTest.kt b/invitecode-platform-bukkit/src/test/kotlin/io/github/command1264/invitecode/platform/bukkit/InviteCodeCommandParserTest.kt new file mode 100644 index 0000000..706debb --- /dev/null +++ b/invitecode-platform-bukkit/src/test/kotlin/io/github/command1264/invitecode/platform/bukkit/InviteCodeCommandParserTest.kt @@ -0,0 +1,134 @@ +package io.github.command1264.invitecode.platform.bukkit + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertInstanceOf +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test + +class InviteCodeCommandParserTest { + @Test + fun `player command routes expose permissions and operands`() { + val claim = assertInstanceOf( + ParsedInviteCodeCommand::class.java, + InviteCodeCommandParser.parse(listOf("claim", "A1B2C3")), + ) + + assertEquals(InviteCodeCommandId.CLAIM, claim.id) + assertEquals("invitecode.command.claim", claim.permission) + assertEquals(listOf("A1B2C3"), claim.operands) + assertTrue(claim.playerOnly) + assertFalse(claim.allowedDuringMaintenance) + } + + @Test + fun `help doctor and storage migration are available in maintenance`() { + listOf( + emptyList(), + listOf("help"), + listOf("admin", "doctor"), + listOf("admin", "storage", "migrate", "SQLITE", "initial setup"), + ).forEach { arguments -> + val parsed = assertInstanceOf( + ParsedInviteCodeCommand::class.java, + InviteCodeCommandParser.parse(arguments), + ) + assertTrue(parsed.allowedDuringMaintenance) + } + } + + @Test + fun `reload has a direct console-safe route`() { + val parsed = assertInstanceOf( + ParsedInviteCodeCommand::class.java, + InviteCodeCommandParser.parse(listOf("reload")), + ) + + assertEquals(InviteCodeCommandId.ADMIN_RELOAD, parsed.id) + assertEquals("invitecode.admin.reload", parsed.permission) + assertFalse(parsed.playerOnly) + assertFalse(parsed.allowedDuringMaintenance) + } + + @Test + fun `help and administrative commands can be used by console`() { + val commands = listOf( + emptyList(), + listOf("help"), + listOf("reload"), + listOf("admin", "doctor"), + listOf("admin", "reload"), + listOf("admin", "inspect", "player", "Alex"), + ) + + commands.forEach { arguments -> + val parsed = assertInstanceOf( + ParsedInviteCodeCommand::class.java, + InviteCodeCommandParser.parse(arguments), + ) + assertFalse(parsed.playerOnly) + } + } + + @Test + fun `admin mutation requires a non blank reason`() { + val missing = InviteCodeCommandParser.parse( + listOf("admin", "invitation", "unlink", "invitation-id"), + ) + assertInstanceOf(InvalidInviteCodeCommand::class.java, missing) + + val parsed = assertInstanceOf( + ParsedInviteCodeCommand::class.java, + InviteCodeCommandParser.parse( + listOf("admin", "invitation", "unlink", "invitation-id", "duplicate", "account"), + ), + ) + assertEquals(InviteCodeCommandId.ADMIN_INVITATION_UNLINK, parsed.id) + assertEquals(listOf("invitation-id"), parsed.operands) + assertEquals("duplicate account", parsed.reason) + } + + @Test + fun `unknown and surplus arguments are rejected`() { + assertInstanceOf( + InvalidInviteCodeCommand::class.java, + InviteCodeCommandParser.parse(listOf("status", "extra")), + ) + assertInstanceOf( + InvalidInviteCodeCommand::class.java, + InviteCodeCommandParser.parse(listOf("unknown")), + ) + } + + @Test + fun `all administrative routes are recognized`() { + val routes = mapOf( + listOf("admin", "inspect", "player", "Alex") to InviteCodeCommandId.ADMIN_INSPECT_PLAYER, + listOf("admin", "inspect", "invitation", UUID) to InviteCodeCommandId.ADMIN_INSPECT_INVITATION, + listOf("admin", "inspect", "reward", UUID) to InviteCodeCommandId.ADMIN_INSPECT_REWARD, + listOf("admin", "invitation", "transfer", UUID, "Alex", "reason") to + InviteCodeCommandId.ADMIN_INVITATION_TRANSFER, + listOf("admin", "invitation", "force-qualify", UUID, "new-player", "reason") to + InviteCodeCommandId.ADMIN_INVITATION_FORCE_QUALIFY, + listOf("admin", "eligibility", "reset", "Alex", "reason") to + InviteCodeCommandId.ADMIN_ELIGIBILITY_RESET, + listOf("admin", "reward", "retry", UUID, "reason") to InviteCodeCommandId.ADMIN_REWARD_RETRY, + listOf("admin", "reward", "mark-delivered", UUID, "reason") to + InviteCodeCommandId.ADMIN_REWARD_MARK_DELIVERED, + listOf("admin", "code", "rotate", "Alex", "reason") to InviteCodeCommandId.ADMIN_CODE_ROTATE, + listOf("admin", "reload") to InviteCodeCommandId.ADMIN_RELOAD, + ) + + routes.forEach { (arguments, expected) -> + val parsed = assertInstanceOf( + ParsedInviteCodeCommand::class.java, + InviteCodeCommandParser.parse(arguments), + ) + assertEquals(expected, parsed.id) + } + } + + private companion object { + const val UUID = "00000000-0000-0000-0000-000000000001" + } +} diff --git a/invitecode-platform-bukkit/src/test/kotlin/io/github/command1264/invitecode/platform/bukkit/InviteCodeTabCompletionTest.kt b/invitecode-platform-bukkit/src/test/kotlin/io/github/command1264/invitecode/platform/bukkit/InviteCodeTabCompletionTest.kt new file mode 100644 index 0000000..e1a0ef3 --- /dev/null +++ b/invitecode-platform-bukkit/src/test/kotlin/io/github/command1264/invitecode/platform/bukkit/InviteCodeTabCompletionTest.kt @@ -0,0 +1,97 @@ +package io.github.command1264.invitecode.platform.bukkit + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test + +class InviteCodeTabCompletionTest { + private val allowAll: (String) -> Boolean = { true } + private val onlinePlayers = listOf("Alex", "Steve") + + @Test + fun `player and console receive only applicable root commands`() { + assertEquals( + listOf("admin", "cancel", "claim", "code", "confirm", "help", "reload", "stats", "status"), + complete(listOf(""), player = true), + ) + assertEquals(listOf("admin", "help", "reload"), complete(listOf(""), player = false)) + assertEquals(listOf("stats", "status"), complete(listOf("st"), player = true)) + } + + @Test + fun `administrative trees and player operands complete at exact positions`() { + assertEquals( + listOf("code", "doctor", "eligibility", "inspect", "invitation", "reload", "reward", "storage"), + complete(listOf("admin", ""), player = false), + ) + assertEquals( + listOf("invitation", "player", "reward"), + complete(listOf("admin", "inspect", ""), player = false), + ) + assertEquals( + onlinePlayers, + complete(listOf("admin", "inspect", "player", ""), player = false), + ) + assertEquals( + listOf("Steve"), + complete(listOf("admin", "invitation", "transfer", "invitation-id", "St"), player = false), + ) + assertEquals( + listOf("SQLITE"), + complete(listOf("admin", "storage", "migrate", "s"), player = false), + ) + } + + @Test + fun `finished unknown and excess arguments never fall back to player names`() { + listOf( + listOf("status", ""), + listOf("stats", "anything"), + listOf("help", ""), + listOf("reload", ""), + listOf("unknown", ""), + listOf("admin", "doctor", ""), + listOf("admin", "inspect", "player", "Alex", ""), + listOf("admin", "invitation", "transfer", "invitation-id", "Alex", "reason", "extra"), + listOf("one", "two", "three", "four", "five", "six", "seven"), + ).forEach { arguments -> + assertEquals(emptyList(), complete(arguments, player = true), arguments.toString()) + } + } + + @Test + fun `permissions hide unavailable branches`() { + val onlyHelp: (String) -> Boolean = { it == "invitecode.command.basic" } + + assertEquals( + listOf("help"), + InviteCodeTabCompletion.complete(listOf(""), true, onlyHelp, onlinePlayers), + ) + assertEquals( + emptyList(), + InviteCodeTabCompletion.complete(listOf("admin", ""), false, onlyHelp, onlinePlayers), + ) + + val onlyQualification: (String) -> Boolean = { it == "invitecode.admin.qualification" } + assertEquals( + listOf("force-qualify"), + InviteCodeTabCompletion.complete( + listOf("admin", "invitation", ""), + false, + onlyQualification, + onlinePlayers, + ), + ) + assertEquals( + emptyList(), + InviteCodeTabCompletion.complete( + listOf("admin", "inspect", "player", ""), + false, + onlyQualification, + onlinePlayers, + ), + ) + } + + private fun complete(arguments: List, player: Boolean): List = + InviteCodeTabCompletion.complete(arguments, player, allowAll, onlinePlayers) +} diff --git a/invitecode-platform-bukkit/src/test/kotlin/io/github/command1264/invitecode/platform/bukkit/LocalizedMessagesTest.kt b/invitecode-platform-bukkit/src/test/kotlin/io/github/command1264/invitecode/platform/bukkit/LocalizedMessagesTest.kt new file mode 100644 index 0000000..57d3c9f --- /dev/null +++ b/invitecode-platform-bukkit/src/test/kotlin/io/github/command1264/invitecode/platform/bukkit/LocalizedMessagesTest.kt @@ -0,0 +1,53 @@ +package io.github.command1264.invitecode.platform.bukkit + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test + +class LocalizedMessagesTest { + @Test + fun `replaces named variables after locale fallback`() { + val messages = LocalizedMessages( + defaultLocale = "zh_TW", + useClientLocale = true, + catalogs = mapOf("zh_TW" to mapOf("claim.ready" to "邀請人:{inviter}")), + ) + + assertEquals( + "邀請人:Alex", + messages.resolve("ja_JP", "claim.ready", mapOf("inviter" to "Alex")), + ) + } + + @Test + fun `uses client locale then default locale then visible missing key`() { + val missing = mutableListOf() + val messages = LocalizedMessages( + defaultLocale = "zh_TW", + useClientLocale = true, + catalogs = mapOf( + "zh_TW" to mapOf("claim.ok" to "完成", "default.only" to "預設"), + "en_US" to mapOf("claim.ok" to "Done"), + ), + onMissingKey = missing::add, + ) + + assertEquals("Done", messages.resolve("en_us", "claim.ok")) + assertEquals("預設", messages.resolve("en_US", "default.only")) + assertEquals("[missing: unknown.key]", messages.resolve("en_US", "unknown.key")) + assertEquals(listOf("unknown.key"), missing) + } + + @Test + fun `ignores client locale when disabled`() { + val messages = LocalizedMessages( + defaultLocale = "zh_TW", + useClientLocale = false, + catalogs = mapOf( + "zh_TW" to mapOf("claim.ok" to "完成"), + "en_US" to mapOf("claim.ok" to "Done"), + ), + ) + + assertEquals("完成", messages.resolve("en_US", "claim.ok")) + } +} diff --git a/invitecode-platform-bukkit/src/test/kotlin/io/github/command1264/invitecode/platform/bukkit/NetworkAddressHasherTest.kt b/invitecode-platform-bukkit/src/test/kotlin/io/github/command1264/invitecode/platform/bukkit/NetworkAddressHasherTest.kt new file mode 100644 index 0000000..2a655f0 --- /dev/null +++ b/invitecode-platform-bukkit/src/test/kotlin/io/github/command1264/invitecode/platform/bukkit/NetworkAddressHasherTest.kt @@ -0,0 +1,38 @@ +package io.github.command1264.invitecode.platform.bukkit + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertNotEquals +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import java.nio.file.Files +import java.nio.file.Path + +class NetworkAddressHasherTest { + @TempDir + lateinit var temporaryDirectory: Path + + @Test + fun `generated secret remains stable across reload without exposing the address`() { + val path = temporaryDirectory.resolve("anti-abuse.key") + val address = byteArrayOf(192.toByte(), 0, 2, 10) + val first = NetworkAddressHasher.loadOrCreate(path).use { it.keyId to it.hash(address) } + val second = NetworkAddressHasher.loadExisting(path).use { it.keyId to it.hash(address) } + + assertEquals(first, second) + assertEquals(64, first.first.length) + assertEquals(64, first.second.length) + assertEquals(32, Files.size(path)) + assertNotEquals(address.toList(), Files.readAllBytes(path).toList()) + } + + @Test + fun `IPv4 and IPv4-mapped IPv6 addresses have the same digest`() { + val hasher = NetworkAddressHasher.loadOrCreate(temporaryDirectory.resolve("anti-abuse.key")) + val ipv4 = byteArrayOf(203.toByte(), 0, 113, 7) + val mapped = byteArrayOf(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1) + ipv4 + + hasher.use { + assertEquals(it.hash(ipv4), it.hash(mapped)) + } + } +} diff --git a/invitecode-platform-bukkit/src/test/kotlin/io/github/command1264/invitecode/platform/bukkit/PluginRuntimeStateTest.kt b/invitecode-platform-bukkit/src/test/kotlin/io/github/command1264/invitecode/platform/bukkit/PluginRuntimeStateTest.kt new file mode 100644 index 0000000..0b0f05d --- /dev/null +++ b/invitecode-platform-bukkit/src/test/kotlin/io/github/command1264/invitecode/platform/bukkit/PluginRuntimeStateTest.kt @@ -0,0 +1,58 @@ +package io.github.command1264.invitecode.platform.bukkit + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test + +class PluginRuntimeStateTest { + @Test + fun `startup can become active and then stop`() { + val runtime = PluginRuntimeState() + + runtime.activate() + assertEquals(RuntimePhase.ACTIVE, runtime.phase) + assertTrue(runtime.acceptsGameplayCommands()) + + runtime.beginStopping() + assertEquals(RuntimePhase.STOPPING, runtime.phase) + assertFalse(runtime.acceptsGameplayCommands()) + + runtime.finishStopping() + assertEquals(RuntimePhase.STOPPED, runtime.phase) + } + + @Test + fun `startup failure enters maintenance and can recover`() { + val runtime = PluginRuntimeState() + + runtime.enterMaintenance("storage unavailable") + assertEquals(RuntimePhase.MAINTENANCE, runtime.phase) + assertEquals("storage unavailable", runtime.maintenanceReason) + assertFalse(runtime.acceptsGameplayCommands()) + + runtime.activate() + assertEquals(RuntimePhase.ACTIVE, runtime.phase) + assertEquals(null, runtime.maintenanceReason) + } + + @Test + fun `stopped runtime cannot become active again`() { + val runtime = PluginRuntimeState() + runtime.beginStopping() + runtime.finishStopping() + + assertThrows(IllegalStateException::class.java) { runtime.activate() } + } + + @Test + fun `configuration snapshots swap as one generation`() { + val snapshots = AtomicRuntimeSnapshot("first") + + val updated = snapshots.replace("second") + + assertEquals(1, updated.generation) + assertEquals("second", snapshots.current().value) + } +} 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 new file mode 100644 index 0000000..dac6ff5 --- /dev/null +++ b/invitecode-platform-bukkit/src/test/kotlin/io/github/command1264/invitecode/platform/bukkit/RuntimeConfigurationAssemblerTest.kt @@ -0,0 +1,136 @@ +package io.github.command1264.invitecode.platform.bukkit + +import io.github.command1264.invitecode.core.StorageBackendType +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Test + +class RuntimeConfigurationAssemblerTest { + @Test + fun `parses all configuration documents into one snapshot`() { + val configuration = RuntimeConfigurationAssembler.parse( + general = general(), + storage = storage(), + qualifications = qualifications(), + rewards = rewards(), + messageCatalogs = mapOf( + "zh_TW" to catalog("邀請成功"), + "en_US" to catalog("Invitation completed"), + ), + ) + + assertEquals(StorageBackendType.SQLITE, configuration.storage.backend) + assertEquals("邀請成功", configuration.messages.resolve("ja_JP", "invite.completed")) + assertEquals("Invitation completed", configuration.messages.resolve("en_US", "invite.completed")) + } + + @Test + fun `invalid replacement does not change installed snapshot`() { + val snapshots = AtomicRuntimeSnapshot( + RuntimeConfigurationAssembler.parse( + general(), storage(), qualifications(), rewards(), mapOf("zh_TW" to catalog("舊訊息")), + ), + ) + + assertThrows(IllegalArgumentException::class.java) { + val invalid = RuntimeConfigurationAssembler.parse( + general(), storage(), qualifications(), rewards(), + mapOf("zh_TW" to mapOf("messages-version" to 2, "invite" to mapOf("completed" to "新訊息"))), + ) + snapshots.replace(invalid) + } + + assertEquals(0, snapshots.current().generation) + assertEquals("舊訊息", snapshots.current().value.messages.resolve(null, "invite.completed")) + } + + @Test + fun `unsupported configured backend fails before snapshot installation`() { + val mysql = storage().toMutableMap().apply { this["backend"] = "MYSQL" } + + assertThrows(IllegalStateException::class.java) { + RuntimeConfigurationAssembler.parse( + general(), mysql, qualifications(), rewards(), mapOf("zh_TW" to catalog("訊息")), + ) + } + } + + @Test + fun `reload applies non storage changes while deferring storage cutover`() { + val current = RuntimeConfigurationAssembler.parse( + general(), storage(), qualifications(), rewards(), mapOf("zh_TW" to catalog("舊訊息")), + ) + val changedStorage = storage().toMutableMap().apply { + this["sqlite"] = mapOf("file" to "replacement.db") + } + val candidate = RuntimeConfigurationAssembler.parse( + general(), changedStorage, qualifications(), rewards(), mapOf("zh_TW" to catalog("新訊息")), + ) + + val reload = RuntimeConfigurationReload.reconcile(current, candidate) + + assertEquals(true, reload.storageRestartRequired) + assertEquals("invitecode.db", reload.configuration.storage.sqlite.file) + assertEquals("新訊息", reload.configuration.messages.resolve(null, "invite.completed")) + } + + private fun general(): Map = mapOf( + "config-version" to 1, + "language" to mapOf("default" to "zh_TW", "use-client-locale" to true), + "invite-code" to mapOf("format" to "HEX_COLOR", "custom-codes-enabled" to false), + "claim" to mapOf( + "window" to "24h", + "input-mode" to "AUTO", + "confirmation-timeout" to "30s", + "chat-input-timeout" to "60s", + "existing-player-policy" to "START_WINDOW", + ), + "anti-abuse" to mapOf("matching-ip-action" to "DENY", "ip-hash-retention" to "30d"), + "time-zone" to "Asia/Taipei", + ) + + private fun storage(): Map = mapOf( + "config-version" to 1, + "backend" to "SQLITE", + "sqlite" to mapOf("file" to "invitecode.db"), + "mysql" to mapOf( + "host" to "localhost", + "port" to 3306, + "database" to "invitecode", + "username" to "invitecode", + "password" to "env:INVITECODE_DB_PASSWORD", + "connection-timeout" to "5s", + ), + ) + + private fun qualifications(): Map = mapOf( + "config-version" to 1, + "policies" to mapOf( + "new-player" to mapOf( + "any-of" to listOf( + mapOf( + "all-of" to listOf( + mapOf("type" to "PLAY_TIME", "at-least" to "30m"), + ), + ), + ), + ), + ), + ) + + private fun rewards(): Map = mapOf( + "config-version" to 1, + "qualification-rewards" to mapOf( + "default" to mapOf( + "inviter" to listOf(mapOf("type" to "MESSAGE", "message" to "invite.completed")), + "invitee" to emptyList(), + ), + ), + "milestone-rewards" to emptyMap(), + ) + + private fun catalog(message: String): Map = mapOf( + "messages-version" to 1, + "invite" to mapOf("completed" to message), + ) +} diff --git a/invitecode-plugin/build.gradle.kts b/invitecode-plugin/build.gradle.kts index 6dc0912..28d64ca 100644 --- a/invitecode-plugin/build.gradle.kts +++ b/invitecode-plugin/build.gradle.kts @@ -5,6 +5,9 @@ import org.gradle.api.provider.ListProperty import org.gradle.api.tasks.Input import org.gradle.api.tasks.InputFile import org.gradle.api.tasks.TaskAction +import org.gradle.api.tasks.testing.Test +import java.nio.ByteBuffer +import java.nio.charset.StandardCharsets import java.util.zip.ZipFile plugins { @@ -18,6 +21,9 @@ abstract class VerifyPluginJar : DefaultTask() { @get:Input abstract val requiredEntries: ListProperty + @get:Input + abstract val forbiddenEntries: ListProperty + @TaskAction fun verify() { val archive = archiveFile.get().asFile @@ -29,28 +35,56 @@ abstract class VerifyPluginJar : DefaultTask() { } } + forbiddenEntries.get().forEach { entry -> + check(zip.getEntry(entry) == null) { + "${archive.name} contains obsolete root entry $entry" + } + } + + val pluginYml = zip.getInputStream(requireNotNull(zip.getEntry("plugin.yml"))).use { input -> + Charsets.UTF_8.newDecoder().decode(ByteBuffer.wrap(input.readBytes())).toString() + } + check(pluginYml.all { it.code <= 0x7f }) { + "plugin.yml must contain ASCII text only" + } + check(pluginYml.lineSequence().any { it.trim() == "name: InviteCode" }) { + "plugin.yml must declare the product name InviteCode" + } + check(pluginYml.lineSequence().any { it.trim() == "api-version: '1.13'" }) { + "plugin.yml must declare the oldest supported modern API version" + } + val entries = zip.entries() while (entries.hasMoreElements()) { val entry = entries.nextElement() if (!entry.name.endsWith(".class")) continue zip.getInputStream(entry).use { input -> - val header = ByteArray(8) - check(input.read(header) == header.size) { + val bytes = input.readBytes() + check(bytes.size >= 8) { "Unable to read class header for ${entry.name}" } - val major = ((header[6].toInt() and 0xff) shl 8) or - (header[7].toInt() and 0xff) + val major = ((bytes[6].toInt() and 0xff) shl 8) or + (bytes[7].toInt() and 0xff) check(major <= 52) { "${entry.name} targets class-file major $major; Java 8 requires 52 or lower" } + if (!entry.name.startsWith( + "io/github/command1264/invitecode/plugin/VaultEconomyRewardGateway", + ) + ) { + val constants = String(bytes, StandardCharsets.ISO_8859_1) + check(!constants.contains("net/milkbowl/vault/")) { + "${entry.name} links the optional Vault API outside its isolated adapter" + } + } } } } } } -description = "Installable InviteCodeKt Bukkit plugin." +description = "Installable InviteCode Bukkit plugin." dependencies { implementation(project(":invitecode-api")) @@ -61,11 +95,13 @@ dependencies { implementation(project(":invitecode-platform-modern")) compileOnly("org.spigotmc:spigot-api:1.8.8-R0.1-SNAPSHOT") compileOnly("com.github.MilkBowl:VaultAPI:1.7") + testImplementation("org.spigotmc:spigot-api:1.8.8-R0.1-SNAPSHOT") } val pluginVersion = version.toString() tasks.processResources { + filteringCharset = "UTF-8" inputs.property("version", pluginVersion) filesMatching("plugin.yml") { expand(mapOf("version" to pluginVersion)) @@ -74,12 +110,19 @@ tasks.processResources { val shadowJar = tasks.named("shadowJar") { inputs.property("java8CompatibilityLayout", "v1") - archiveBaseName.set("InviteCodeKt") + archiveBaseName.set("InviteCode") archiveClassifier.set("") exclude("module-info.class", "META-INF/versions/**") mergeServiceFiles() } +tasks.withType().configureEach { + dependsOn(shadowJar) + doFirst { + systemProperty("invitecode.shadowJar", shadowJar.get().archiveFile.get().asFile.absolutePath) + } +} + tasks.build { dependsOn(shadowJar) } @@ -90,17 +133,27 @@ val verifyPluginJar by tasks.registering(VerifyPluginJar::class) { requiredEntries.set( listOf( "plugin.yml", + "config/config.yml", + "config/storage.yml", + "config/qualifications.yml", + "config/rewards.yml", + "config/messages/zh_TW.yml", + "config/messages/en_US.yml", + "io/github/command1264/invitecode/plugin/InviteCodePlugin.class", + "org/sqlite/JDBC.class", + "org/sqlite/native/Linux/x86_64/libsqlitejdbc.so", + "org/sqlite/native/Windows/x86_64/sqlitejdbc.dll", + "META-INF/services/java.sql.Driver", + ), + ) + forbiddenEntries.set( + listOf( "config.yml", "storage.yml", "qualifications.yml", "rewards.yml", "messages/zh_TW.yml", "messages/en_US.yml", - "io/github/command1264/invitecode/plugin/InviteCodePlugin.class", - "org/sqlite/JDBC.class", - "org/sqlite/native/Linux/x86_64/libsqlitejdbc.so", - "org/sqlite/native/Windows/x86_64/sqlitejdbc.dll", - "META-INF/services/java.sql.Driver", ), ) } diff --git a/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/AdminWorkflowController.kt b/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/AdminWorkflowController.kt new file mode 100644 index 0000000..b07f135 --- /dev/null +++ b/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/AdminWorkflowController.kt @@ -0,0 +1,283 @@ +package io.github.command1264.invitecode.plugin + +import io.github.command1264.invitecode.core.AuditRecord +import io.github.command1264.invitecode.core.InvitationAdministrationContext +import io.github.command1264.invitecode.core.InvitationAuditAction +import io.github.command1264.invitecode.core.InviteCodeLifecycleService +import io.github.command1264.invitecode.core.InviteCodeStorage +import io.github.command1264.invitecode.core.PlayerReferenceResolution +import io.github.command1264.invitecode.core.PlayerReferenceResolver +import io.github.command1264.invitecode.core.RewardAdministrationContext +import io.github.command1264.invitecode.core.RewardDeliveryPlan +import io.github.command1264.invitecode.core.RewardDeliveryPlanner +import io.github.command1264.invitecode.core.UncertainRewardActionResolution +import io.github.command1264.invitecode.platform.bukkit.AsyncOperationExecutor +import io.github.command1264.invitecode.platform.bukkit.AtomicRuntimeSnapshot +import io.github.command1264.invitecode.platform.bukkit.InviteCodeCommandId +import io.github.command1264.invitecode.platform.bukkit.InviteCodeRuntimeConfiguration +import io.github.command1264.invitecode.platform.bukkit.generator +import io.github.command1264.invitecode.platform.bukkit.ParsedInviteCodeCommand +import org.bukkit.command.CommandSender +import org.bukkit.entity.Player +import org.bukkit.plugin.Plugin +import java.time.Instant +import java.util.UUID +import java.util.concurrent.atomic.AtomicReference +import java.util.logging.Level + +class AdminWorkflowController( + private val plugin: Plugin, + private val configuration: AtomicRuntimeSnapshot, + private val storage: AtomicReference, + private val operations: AsyncOperationExecutor, + private val refreshPlayer: (UUID) -> Unit, + private val now: () -> Instant = Instant::now, +) { + fun handle(sender: CommandSender, request: ParsedInviteCodeCommand): Boolean { + val actor = sender.name + val reason = request.reason + return when (request.id) { + InviteCodeCommandId.ADMIN_INSPECT_PLAYER -> inspectPlayer(sender, request.operands.single()) + InviteCodeCommandId.ADMIN_INSPECT_INVITATION -> inspectInvitation(sender, request.operands.single()) + InviteCodeCommandId.ADMIN_INSPECT_REWARD -> inspectReward(sender, request.operands.single()) + InviteCodeCommandId.ADMIN_INVITATION_UNLINK -> mutate(sender) { store -> + val invitation = requireInvitation(store, request.operands.single()) + store.saveAuditedInvitationTransition(invitation.adminUnlink(context(actor, reason))) + AdminMessage("admin.invitation-unlinked", mapOf("invitation" to invitation.id.toString())) + } + InviteCodeCommandId.ADMIN_INVITATION_TRANSFER -> mutate(sender) { store -> + val invitation = requireInvitation(store, request.operands[0]) + val inviter = resolvePlayer(store, request.operands[1]) + store.saveAuditedInvitationTransition(invitation.adminTransfer(inviter, context(actor, reason))) + AdminMessage( + "admin.invitation-transferred", + mapOf("invitation" to invitation.id.toString(), "inviter" to inviter.toString()), + ) + } + InviteCodeCommandId.ADMIN_INVITATION_FORCE_QUALIFY -> forceQualify(sender, request, actor) + InviteCodeCommandId.ADMIN_ELIGIBILITY_RESET -> mutate(sender) { store -> + val playerId = resolvePlayer(store, request.operands.single()) + val transition = store.claimState(playerId).adminResetEligibility(context(actor, reason)) + store.saveAuditedClaimStateTransition(transition) + AdminMessage("admin.eligibility-reset", mapOf("player" to playerId.toString())) + } + InviteCodeCommandId.ADMIN_REWARD_RETRY -> resolveReward( + sender, request, actor, UncertainRewardActionResolution.RETRY, + ) + InviteCodeCommandId.ADMIN_REWARD_MARK_DELIVERED -> resolveReward( + sender, request, actor, UncertainRewardActionResolution.MARK_DELIVERED, + ) + InviteCodeCommandId.ADMIN_CODE_ROTATE -> rotateCode(sender, request, actor) + else -> false + } + } + + private fun inspectPlayer(sender: CommandSender, reference: String): Boolean = query(sender) { store -> + val playerId = resolvePlayer(store, reference) + val state = store.claimState(playerId) + val code = store.activeInviteCode(playerId)?.code?.displayValue() ?: "NONE" + val stats = store.inviterInvitationStats(playerId) + listOf( + "Player=$playerId name=${store.player(playerId)?.lastKnownName ?: "UNKNOWN"}", + "firstSeen=${state.firstSeenAt} inviter=${state.isInviter} invitee=${state.hasInvitation} code=$code", + "claimed=${stats.claimed} qualified=${stats.qualified} audit=${store.auditHistoryByPlayer(playerId, 20).size}", + ) + } + + private fun inspectInvitation(sender: CommandSender, reference: String): Boolean = query(sender) { store -> + val id = parseUuid(reference, "Invitation ID") + val invitation = requireNotNull(store.invitation(id)) { "Invitation $id 不存在。" } + listOf( + "Invitation=${invitation.id} status=${invitation.status}", + "inviter=${invitation.inviterId} invitee=${invitation.inviteeId} claimedAt=${invitation.claimedAt}", + "facts=${store.qualificationFacts(id).size} rewards=${store.rewardDeliveries(id).size} " + + "audit=${store.auditHistoryByInvitation(id, 20).size}", + ) + } + + private fun inspectReward(sender: CommandSender, reference: String): Boolean = query(sender) { store -> + val id = parseUuid(reference, "Reward Action ID") + val action = requireNotNull(store.rewardAction(id)) { "Reward Action $id 不存在。" } + listOf( + "RewardAction=${action.id} delivery=${action.rewardDeliveryId} status=${action.status}", + "recipient=${action.recipientId} type=${action.type} updatedAt=${action.updatedAt}", + "lastError=${action.lastError ?: "NONE"} transitions=${store.rewardActionTransitions(id).size}", + ) + } + + private fun forceQualify( + sender: CommandSender, + request: ParsedInviteCodeCommand, + actor: String, + ): Boolean { + val runtime = configuration.current().value + return mutate(sender, onSuccess = { result -> + send(sender, result.message) + result.players.forEach(refreshPlayer) + }) { store -> + val invitation = requireInvitation(store, request.operands[0]) + val policy = requireNotNull(runtime.qualifications.policies[request.operands[1]]) { + "Qualification Policy ${request.operands[1]} 不存在。" + } + val transition = invitation.adminForceQualify( + now(), + policy.id, + policy.revision, + context(actor, request.reason), + ) + val plans = rewardPlans(store, transition.invitation, runtime) + store.saveForcedQualificationWithRewards(transition, plans) + MutationResult( + AdminMessage( + "admin.invitation-force-qualified", + mapOf( + "invitation" to invitation.id.toString(), + "rewards" to plans.size.toString(), + ), + ), + setOf(invitation.inviterId, invitation.inviteeId), + ) + } + } + + private fun rewardPlans( + store: InviteCodeStorage, + invitation: io.github.command1264.invitecode.core.Invitation, + runtime: InviteCodeRuntimeConfiguration, + ): List { + val qualification = runtime.rewards.qualificationRewards.toSortedMap().values.map { + RewardDeliveryPlanner.planQualification(it, invitation) + } + val count = store.qualifiedInvitationCount(invitation.inviterId) + 1 + val achievedAt = requireNotNull(invitation.qualifiedAt) + val milestones = runtime.rewards.milestoneRewards.toSortedMap().values + .filter { it.qualifiedInvitations == count } + .map { RewardDeliveryPlanner.planMilestone(it, invitation.inviterId, achievedAt) } + return qualification + milestones + } + + private fun resolveReward( + sender: CommandSender, + request: ParsedInviteCodeCommand, + actor: String, + resolution: UncertainRewardActionResolution, + ): Boolean = mutate( + sender, + onSuccess = { result -> + send(sender, result.message) + if (resolution == UncertainRewardActionResolution.RETRY) result.players.forEach(refreshPlayer) + }, + ) { store -> + val id = parseUuid(request.operands.single(), "Reward Action ID") + val result = store.resolveUncertainRewardAction( + id, + resolution, + RewardAdministrationContext(actor, requireNotNull(request.reason), now()), + ) + MutationResult( + AdminMessage( + "admin.reward-resolved", + mapOf("action" to id.toString(), "status" to result.status.name), + ), + setOf(result.recipientId), + ) + } + + private fun rotateCode( + sender: CommandSender, + request: ParsedInviteCodeCommand, + actor: String, + ): Boolean { + val runtime = configuration.current().value + return mutate(sender) { store -> + val playerId = resolvePlayer(store, request.operands.single()) + val generator = runtime.general.inviteCode.format.generator() + val rotatedAt = now() + val auditRecord = AuditRecord( + UUID.randomUUID(), + InvitationAuditAction.CODE_ROTATED, + actor, + requireNotNull(request.reason), + rotatedAt, + playerId = playerId, + ) + val rotation = InviteCodeLifecycleService(store, generator, 64) + .rotate(playerId, rotatedAt, auditRecord) + AdminMessage( + "admin.code-rotated", + mapOf( + "player" to playerId.toString(), + "previous" to rotation.previous.code.displayValue(), + "current" to rotation.current.code.displayValue(), + ), + ) + } + } + + private fun mutate( + sender: CommandSender, + onSuccess: (T) -> Unit = { + if (it is AdminMessage) send(sender, it) else sender.sendMessage(it.toString()) + }, + operation: (InviteCodeStorage) -> T, + ): Boolean = submit(sender, operation, onSuccess) + + private fun query(sender: CommandSender, operation: (InviteCodeStorage) -> List): Boolean = + submit(sender, operation) { lines -> lines.forEach(sender::sendMessage) } + + private fun submit( + sender: CommandSender, + operation: (InviteCodeStorage) -> T, + onSuccess: (T) -> Unit, + ): Boolean { + val accepted = operations.submit( + operation = { operation(requireNotNull(storage.get()) { "SQLite storage is unavailable." }) }, + onSuccess = onSuccess, + onFailure = { error -> + send(sender, AdminMessage("admin.error")) + plugin.logger.log(Level.WARNING, "InviteCode 管理操作失敗。", error) + }, + ) + if (!accepted) send(sender, AdminMessage("admin.stopping")) + return true + } + + private fun resolvePlayer(store: InviteCodeStorage, reference: String): UUID = + when (val result = PlayerReferenceResolver(store).resolve(reference)) { + is PlayerReferenceResolution.Found -> result.player.id + PlayerReferenceResolution.Unknown -> throw IllegalArgumentException("找不到玩家:$reference") + is PlayerReferenceResolution.Ambiguous -> throw IllegalArgumentException( + "玩家名稱 $reference 對應多筆資料,請改用 UUID。", + ) + } + + private fun requireInvitation(store: InviteCodeStorage, reference: String) = + parseUuid(reference, "Invitation ID").let { id -> + requireNotNull(store.invitation(id)) { "Invitation $id 不存在。" } + } + + private fun context(actor: String, reason: String?) = InvitationAdministrationContext( + UUID.randomUUID(), + actor, + requireNotNull(reason), + now(), + ) + + private fun parseUuid(value: String, label: String): UUID = try { + UUID.fromString(value) + } catch (error: IllegalArgumentException) { + throw IllegalArgumentException("$label 必須是有效 UUID。", error) + } + + private fun send(sender: CommandSender, message: AdminMessage) { + val locale = (sender as? Player)?.let(BukkitLocaleCompatibility::locale) + sender.sendMessage(configuration.current().value.messages.resolve(locale, message.key, message.variables)) + } + + private data class AdminMessage( + val key: String, + val variables: Map = emptyMap(), + ) + + private data class MutationResult(val message: AdminMessage, val players: Set) +} diff --git a/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/BukkitConfigurationLoader.kt b/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/BukkitConfigurationLoader.kt new file mode 100644 index 0000000..1d8dc29 --- /dev/null +++ b/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/BukkitConfigurationLoader.kt @@ -0,0 +1,67 @@ +package io.github.command1264.invitecode.plugin + +import io.github.command1264.invitecode.platform.bukkit.InviteCodeRuntimeConfiguration +import io.github.command1264.invitecode.platform.bukkit.RuntimeConfigurationAssembler +import org.bukkit.configuration.ConfigurationSection +import org.bukkit.configuration.file.YamlConfiguration +import java.nio.charset.StandardCharsets +import java.nio.file.Files +import java.nio.file.Path +import kotlin.io.path.nameWithoutExtension + +class BukkitConfigurationLoader( + private val dataDirectory: Path, + private val onMissingMessage: (String) -> Unit, +) { + fun load(): InviteCodeRuntimeConfiguration = RuntimeConfigurationAssembler.parse( + general = loadDocument(dataDirectory.resolve("config.yml")), + storage = loadDocument(dataDirectory.resolve("storage.yml")), + qualifications = loadDocument(dataDirectory.resolve("qualifications.yml")), + rewards = loadDocument(dataDirectory.resolve("rewards.yml")), + messageCatalogs = loadMessageCatalogs(), + onMissingMessage = onMissingMessage, + ) + + private fun loadMessageCatalogs(): Map> { + val messagesDirectory = dataDirectory.resolve("messages") + require(Files.isDirectory(messagesDirectory)) { + "Message catalog directory does not exist: ${messagesDirectory.toAbsolutePath()}." + } + Files.newDirectoryStream(messagesDirectory, "*.yml").use { files -> + return files.associate { file -> + file.nameWithoutExtension to restoreBooleanLikeMessageKeys(loadDocument(file)) + } + } + } + + private fun restoreBooleanLikeMessageKeys(document: Map): Map { + val values = document["value"] as? Map<*, *> ?: return document + if ("yes" in values || "no" in values || "true" !in values || "false" !in values) return document + + val restoredValues = values.entries.associate { (key, value) -> + when (key) { + "true" -> "yes" to value + "false" -> "no" to value + else -> key to value + } + } + return document + ("value" to restoredValues) + } + + private fun loadDocument(path: Path): Map { + require(Files.isRegularFile(path)) { "Configuration file does not exist: ${path.toAbsolutePath()}." } + val yaml = YamlConfiguration() + Files.newBufferedReader(path, StandardCharsets.UTF_8).use { reader -> yaml.load(reader) } + return yaml.getValues(false).mapValues { (_, value) -> normalize(value) } + } + + private fun normalize(value: Any?): Any? = when (value) { + is ConfigurationSection -> value.getValues(false).mapValues { (_, child) -> normalize(child) } + is Map<*, *> -> value.entries.associate { (key, child) -> + require(key is String) { "YAML configuration keys must be strings." } + key to normalize(child) + } + is List<*> -> value.map(::normalize) + else -> value + } +} diff --git a/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/BukkitInviteCodeApi.kt b/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/BukkitInviteCodeApi.kt new file mode 100644 index 0000000..047fba5 --- /dev/null +++ b/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/BukkitInviteCodeApi.kt @@ -0,0 +1,70 @@ +package io.github.command1264.invitecode.plugin + +import io.github.command1264.invitecode.api.ClaimEligibilitySnapshot +import io.github.command1264.invitecode.api.InvitationSnapshot +import io.github.command1264.invitecode.api.InviteCodeApi +import io.github.command1264.invitecode.api.QualificationConditionProvider +import io.github.command1264.invitecode.api.QualificationEvaluationSnapshot +import io.github.command1264.invitecode.api.QualificationProviderRegistration +import io.github.command1264.invitecode.core.ClaimEligibilityPolicy +import io.github.command1264.invitecode.core.InviteCodeStorage +import io.github.command1264.invitecode.core.QualificationProviderRegistry +import io.github.command1264.invitecode.platform.bukkit.AsyncOperationExecutor +import io.github.command1264.invitecode.platform.bukkit.AtomicRuntimeSnapshot +import io.github.command1264.invitecode.platform.bukkit.InviteCodeRuntimeConfiguration +import java.time.Instant +import java.util.UUID +import java.util.concurrent.CompletableFuture +import java.util.concurrent.CompletionStage +import java.util.concurrent.atomic.AtomicReference + +class BukkitInviteCodeApi( + private val configuration: AtomicRuntimeSnapshot, + private val storage: AtomicReference, + private val operations: AsyncOperationExecutor, + private val providers: QualificationProviderRegistry, + private val requestEvaluation: (UUID) -> CompletionStage, + private val now: () -> Instant = Instant::now, +) : InviteCodeApi { + override fun getClaimEligibility(playerId: UUID): CompletionStage = submit { + val evaluatedAt = now() + val store = requireNotNull(storage.get()) { "SQLite storage is unavailable." } + val eligibility = ClaimEligibilityPolicy(configuration.current().value.general.claim.window) + .evaluate(store.claimState(playerId), evaluatedAt) + ClaimEligibilitySnapshot( + playerId, + eligibility.eligible, + eligibility.reasons.map { it.name }.sorted(), + evaluatedAt, + ) + } + + override fun getInvitation(invitationId: UUID): CompletionStage = submit { + val store = requireNotNull(storage.get()) { "SQLite storage is unavailable." } + store.invitation(invitationId)?.let { invitation -> + InvitationSnapshot( + invitation.id, + invitation.inviterId, + invitation.inviteeId, + invitation.status, + invitation.claimedAt, + invitation.qualifiedAt, + ) + } + } + + override fun registerQualificationConditionProvider( + provider: QualificationConditionProvider, + ): QualificationProviderRegistration = providers.register(provider) + + override fun requestQualificationEvaluation( + invitationId: UUID, + ): CompletionStage = requestEvaluation(invitationId) + + private fun submit(operation: () -> T): CompletionStage { + val future = CompletableFuture() + val accepted = operations.submit(operation, future::complete, future::completeExceptionally) + if (!accepted) future.completeExceptionally(IllegalStateException("InviteCode is stopping.")) + return future + } +} diff --git a/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/BukkitInviteCodeTabCompleter.kt b/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/BukkitInviteCodeTabCompleter.kt new file mode 100644 index 0000000..fb66fc6 --- /dev/null +++ b/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/BukkitInviteCodeTabCompleter.kt @@ -0,0 +1,24 @@ +package io.github.command1264.invitecode.plugin + +import io.github.command1264.invitecode.platform.bukkit.InviteCodeTabCompletion +import org.bukkit.Server +import org.bukkit.command.Command +import org.bukkit.command.CommandSender +import org.bukkit.command.TabCompleter +import org.bukkit.entity.Player + +internal class BukkitInviteCodeTabCompleter( + private val server: Server, +) : TabCompleter { + override fun onTabComplete( + sender: CommandSender, + command: Command, + alias: String, + args: Array, + ): List = InviteCodeTabCompletion.complete( + arguments = args.toList(), + player = sender is Player, + hasPermission = sender::hasPermission, + onlinePlayerNames = server.onlinePlayers.map(Player::getName), + ) +} diff --git a/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/BukkitLocaleCompatibility.kt b/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/BukkitLocaleCompatibility.kt new file mode 100644 index 0000000..fc7c2e2 --- /dev/null +++ b/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/BukkitLocaleCompatibility.kt @@ -0,0 +1,23 @@ +package io.github.command1264.invitecode.plugin + +import org.bukkit.entity.Player + +internal object BukkitLocaleCompatibility { + fun locale(player: Player): String? = resolveLocale(player) { player.spigot() } + + internal fun resolveLocale( + directReceiver: Any, + legacyReceiver: () -> Any, + ): String? = readLocale(directReceiver) ?: readLocale(legacyReceiver()) + + private fun readLocale(receiver: Any): String? { + return try { + val method = receiver.javaClass.methods.firstOrNull { + it.name == "getLocale" && it.parameterTypes.isEmpty() && it.returnType == String::class.java + } ?: return null + (method.invoke(receiver) as? String)?.takeIf(String::isNotBlank) + } catch (_: ReflectiveOperationException) { + null + } + } +} diff --git a/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/BukkitStatisticCompatibility.kt b/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/BukkitStatisticCompatibility.kt new file mode 100644 index 0000000..cb0c466 --- /dev/null +++ b/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/BukkitStatisticCompatibility.kt @@ -0,0 +1,22 @@ +package io.github.command1264.invitecode.plugin + +import org.bukkit.Statistic +import org.bukkit.entity.Player + +internal object BukkitStatisticCompatibility { + private val playTimeStatistic: Statistic by lazy { + val name = resolvePlayTimeStatisticName(Statistic.values().map(Statistic::name)) + Statistic.valueOf(name) + } + + fun playTimeTicks(player: Player): Long = player.getStatistic(playTimeStatistic).toLong() + + internal fun resolvePlayTimeStatisticName(availableNames: Collection): String = when { + MODERN_PLAY_TIME_STATISTIC in availableNames -> MODERN_PLAY_TIME_STATISTIC + LEGACY_PLAY_TIME_STATISTIC in availableNames -> LEGACY_PLAY_TIME_STATISTIC + else -> error("This Bukkit version does not expose a supported play-time statistic.") + } + + private const val MODERN_PLAY_TIME_STATISTIC = "PLAY_ONE_MINUTE" + private const val LEGACY_PLAY_TIME_STATISTIC = "PLAY_ONE_TICK" +} diff --git a/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/BundledConfigurationInstaller.kt b/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/BundledConfigurationInstaller.kt new file mode 100644 index 0000000..0a30b22 --- /dev/null +++ b/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/BundledConfigurationInstaller.kt @@ -0,0 +1,34 @@ +package io.github.command1264.invitecode.plugin + +import java.io.InputStream +import java.nio.file.Files +import java.nio.file.Path + +internal class BundledConfigurationInstaller( + private val dataDirectory: Path, + private val openResource: (String) -> InputStream?, +) { + fun installMissing() { + RESOURCES.forEach { (resourcePath, outputPath) -> + val target = dataDirectory.resolve(outputPath) + if (Files.notExists(target)) { + Files.createDirectories(requireNotNull(target.parent)) + val resource = requireNotNull(openResource(resourcePath)) { + "Bundled resource does not exist: $resourcePath" + } + resource.use { Files.copy(it, target) } + } + } + } + + companion object { + private val RESOURCES = mapOf( + "config/config.yml" to "config.yml", + "config/storage.yml" to "storage.yml", + "config/qualifications.yml" to "qualifications.yml", + "config/rewards.yml" to "rewards.yml", + "config/messages/zh_TW.yml" to "messages/zh_TW.yml", + "config/messages/en_US.yml" to "messages/en_US.yml", + ) + } +} 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 6f1f3c5..1aa3181 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 @@ -1,26 +1,465 @@ package io.github.command1264.invitecode.plugin +import io.github.command1264.invitecode.core.InviteCodeStorage +import io.github.command1264.invitecode.core.AuditRecord +import io.github.command1264.invitecode.core.InvitationAuditAction +import io.github.command1264.invitecode.core.RewardDeliveryCoordinator +import io.github.command1264.invitecode.core.QualificationProviderRegistry +import io.github.command1264.invitecode.api.InviteCodeApi +import io.github.command1264.invitecode.platform.bukkit.AsyncOperationExecutor +import io.github.command1264.invitecode.platform.bukkit.AtomicRuntimeSnapshot +import io.github.command1264.invitecode.platform.bukkit.ClaimInteractionSessions +import io.github.command1264.invitecode.platform.bukkit.InvalidInviteCodeCommand +import io.github.command1264.invitecode.platform.bukkit.InviteCodeCommandId +import io.github.command1264.invitecode.platform.bukkit.InviteCodeCommandParser +import io.github.command1264.invitecode.platform.bukkit.InviteCodeRuntimeConfiguration +import io.github.command1264.invitecode.platform.bukkit.ParsedInviteCodeCommand +import io.github.command1264.invitecode.platform.bukkit.PluginRuntimeState +import io.github.command1264.invitecode.platform.bukkit.RuntimePhase +import io.github.command1264.invitecode.platform.bukkit.RuntimeConfigurationReload +import io.github.command1264.invitecode.platform.bukkit.NetworkAddressHasher +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 org.bukkit.Bukkit import org.bukkit.command.Command import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandSender +import org.bukkit.entity.Player import org.bukkit.plugin.java.JavaPlugin +import org.bukkit.plugin.ServicePriority +import org.bukkit.scheduler.BukkitTask +import java.time.Duration +import java.time.Instant +import java.util.concurrent.atomic.AtomicReference +import java.util.UUID +import java.util.logging.Level class InviteCodePlugin : JavaPlugin() { + private val runtime = PluginRuntimeState() + private val configuration = AtomicRuntimeSnapshot() + private val storage = AtomicReference() + private val networkHasher = AtomicReference() + private val sessions = ClaimInteractionSessions() + private var operations: AsyncOperationExecutor? = null + private var playerWorkflows: PlayerWorkflowController? = null + private var qualificationTask: BukkitTask? = null + override fun onEnable() { - saveDefaultConfig() - getCommand("invitecode")?.setExecutor(ScaffoldCommand()) - logger.info("InviteCodeKt ${description.version} 專案骨架已啟用;領域功能尚未實作。") + saveBundledResources() + val executor = AsyncOperationExecutor("InviteCode-storage") { operation -> + server.scheduler.runTask(this, Runnable(operation)) + } + operations = executor + val externalQualificationProviders = QualificationProviderRegistry() + val playerWorkflows = PlayerWorkflowController( + this, + configuration, + storage, + executor, + sessions, + externalQualificationProviders, + networkHasher, + economyGateway = { OptionalVaultIntegration.find(server, logger) }, + ) + this.playerWorkflows = playerWorkflows + server.servicesManager.register( + InviteCodeApi::class.java, + BukkitInviteCodeApi( + configuration, + storage, + executor, + externalQualificationProviders, + playerWorkflows::requestQualificationEvaluation, + ), + this, + ServicePriority.Normal, + ) + server.pluginManager.registerEvents(playerWorkflows, this) + val adminWorkflows = AdminWorkflowController( + this, + configuration, + storage, + executor, + refreshPlayer = { playerId -> + server.getPlayer(playerId)?.let(playerWorkflows::registerPlayer) + }, + ) + getCommand("invitecode")?.let { command -> + command.setExecutor( + RuntimeCommandExecutor( + runtime, + configuration, + reload = ::reload, + migrateStorage = ::migrateStorage, + playerWorkflow = playerWorkflows::handle, + adminWorkflow = adminWorkflows::handle, + doctor = ::doctor, + ), + ) + command.setTabCompleter(BukkitInviteCodeTabCompleter(server)) + } + qualificationTask = server.scheduler.runTaskTimer(this, Runnable { + if (runtime.phase == RuntimePhase.ACTIVE) { + server.onlinePlayers.forEach(playerWorkflows::registerPlayer) + } + }, 20L * 60L, 20L * 60L) + start(executor) + } + + override fun onDisable() { + runtime.beginStopping() + qualificationTask?.cancel() + qualificationTask = null + sessions.clear() + server.servicesManager.unregisterAll(this) + operations?.close(Duration.ofSeconds(2)) + operations = null + playerWorkflows = null + networkHasher.getAndSet(null)?.close() + storage.getAndSet(null)?.close() + runtime.finishStopping() + } + + private fun start(executor: AsyncOperationExecutor) { + val accepted = executor.submit( + operation = ::loadStartup, + onSuccess = { result -> + result.configuration?.let(configuration::replace) + if (result.storage != null) { + storage.set(result.storage) + networkHasher.set(requireNotNull(result.networkHasher)) + runtime.activate() + if (result.recoveredRewardActions > 0) { + logger.warning( + "已將 ${result.recoveredRewardActions} 筆中斷的 Reward Action 標記為 UNCERTAIN。", + ) + } + if (result.storageInitialized) { + logger.info("已自動完成首次 SQLite schema 與防濫用密鑰初始化。") + } + server.onlinePlayers.forEach { playerWorkflows?.registerPlayer(it) } + logger.info("InviteCode ${description.version} 已啟用。") + } else { + val message = result.error?.message ?: "未知的啟動錯誤。" + runtime.enterMaintenance(message) + logger.log(Level.SEVERE, "InviteCode 已進入維護模式:$message", result.error) + } + }, + onFailure = { error -> + runtime.enterMaintenance(error.message ?: "未知的啟動錯誤。") + logger.log(Level.SEVERE, "InviteCode 啟動失敗,已進入維護模式。", error) + }, + ) + if (!accepted) runtime.enterMaintenance("背景執行器未接受啟動工作。") + } + + private fun loadStartup(): StartupResult { + val candidate = try { + BukkitConfigurationLoader(dataFolder.toPath()) { key -> + logger.warning("找不到語系訊息:$key") + }.load() + } catch (error: Exception) { + return StartupResult(error = error) + } + var opened: InviteCodeStorage? = null + var hasher: NetworkAddressHasher? = null + return try { + val dataDirectory = dataFolder.toPath().normalize() + val database = dataDirectory.resolve(candidate.storage.sqlite.file).normalize() + require(database.startsWith(dataDirectory)) { "SQLite database path escapes the plugin data directory." } + val bootstrap = SqliteRuntimeBootstrap( + database, + dataDirectory.resolve(NETWORK_SECRET_FILE), + BlockingOperationGuard.rejectingServerMainThread(Bukkit::isPrimaryThread), + ).initializeOrOpen() + opened = bootstrap.storage + hasher = bootstrap.networkHasher + val recovered = RewardDeliveryCoordinator(opened).recoverInterrupted(Instant.now()) + StartupResult( + configuration = candidate, + storage = opened, + networkHasher = hasher, + storageInitialized = bootstrap.initialized, + recoveredRewardActions = recovered, + ) + } catch (error: Exception) { + hasher?.close() + opened?.close() + StartupResult(configuration = candidate, error = error) + } + } + + private fun reload(sender: CommandSender) { + val executor = operations + if (executor == null) { + sendLocalized(sender, "admin.reload-stopping") + return + } + val accepted = executor.submit( + operation = { + val candidate = BukkitConfigurationLoader(dataFolder.toPath()) { key -> + logger.warning("找不到語系訊息:$key") + }.load() + val current = configuration.current() + RuntimeConfigurationReload.reconcile(current.value, candidate) + }, + onSuccess = { result -> + configuration.replace(result.configuration) + sendLocalized(sender, "admin.reload-success") + if (result.storageRestartRequired) { + sendLocalized(sender, "admin.reload-storage-restart") + } + }, + onFailure = { error -> + sendLocalized(sender, "admin.reload-failed") + logger.log(Level.WARNING, "InviteCode reload 驗證失敗;仍使用原設定。", error) + }, + ) + if (!accepted) sendLocalized(sender, "admin.reload-stopping") + } + + private fun migrateStorage(sender: CommandSender, request: ParsedInviteCodeCommand) { + if (!request.operands.single().equals("SQLITE", ignoreCase = true)) { + sendLocalized(sender, "admin.storage-unsupported") + return + } + val candidate = configuration.currentOrNull()?.value + if (candidate == null) { + sendLocalized(sender, "admin.storage-config-unavailable") + return + } + val executor = operations + if (executor == null) { + sendLocalized(sender, "admin.storage-stopping") + return + } + val actor = sender.name + val reason = requireNotNull(request.reason) + val accepted = executor.submit( + operation = { + val dataDirectory = dataFolder.toPath().normalize() + val database = dataDirectory.resolve(candidate.storage.sqlite.file).normalize() + require(database.startsWith(dataDirectory)) { + "SQLite database path escapes the plugin data directory." + } + val guard = BlockingOperationGuard.rejectingServerMainThread(Bukkit::isPrimaryThread) + val version = SqliteSchemaMigrator(database, guard).migrate() + val opened = SqliteInviteCodeStorage.open(database, guard) + var newHasher: NetworkAddressHasher? = null + try { + val loadedHasher = networkHasher.get() + newHasher = if (loadedHasher == null) { + NetworkAddressHasher.loadOrCreate(dataDirectory.resolve(NETWORK_SECRET_FILE)) + } else { + null + } + val effectiveHasher = loadedHasher ?: requireNotNull(newHasher) + opened.purgeNetworkHashesWithDifferentKey(effectiveHasher.keyId) + opened.saveAuditRecord( + AuditRecord( + UUID.randomUUID(), + InvitationAuditAction.STORAGE_MIGRATED, + actor, + reason, + Instant.now(), + ), + ) + StorageMigrationResult(version, opened, newHasher) + } catch (error: Exception) { + newHasher?.close() + opened.close() + throw error + } + }, + onSuccess = { result -> + storage.getAndSet(result.storage)?.close() + result.networkHasher?.let { hasher -> + networkHasher.getAndSet(hasher)?.close() + } + if (runtime.phase == RuntimePhase.MAINTENANCE) runtime.activate() + server.onlinePlayers.forEach { playerWorkflows?.registerPlayer(it) } + logger.info("$actor 以理由「$reason」完成 SQLite schema migration 至版本 ${result.version}。") + sendLocalized(sender, "admin.storage-success", mapOf("version" to result.version.toString())) + }, + onFailure = { error -> + sendLocalized(sender, "admin.storage-failed") + logger.log(Level.SEVERE, "$actor 執行 SQLite schema migration 失敗;理由:$reason", error) + }, + ) + if (!accepted) sendLocalized(sender, "admin.storage-stopping") + } + + private fun doctor(sender: CommandSender) { + val generation = configuration.currentOrNull()?.generation?.toString() ?: "尚未載入" + val executor = operations + val store = storage.get() + val placeholder = server.pluginManager.getPlugin("PlaceholderAPI")?.isEnabled == true + val vault = OptionalVaultIntegration.find(server, logger) != null + sendLocalized( + sender, + "admin.doctor-runtime", + mapOf( + "phase" to runtime.phase.name, + "generation" to generation, + "executor" to if (executor?.acceptingOperations == true) "ACCEPTING" else "STOPPED", + ), + ) + sendLocalized( + sender, + "admin.doctor-integrations", + mapOf("placeholder" to placeholder.toString(), "vault" to vault.toString()), + ) + runtime.maintenanceReason?.let { + sendLocalized(sender, "admin.doctor-maintenance", mapOf("reason" to it)) + } + if (store == null || executor == null) { + sendLocalized(sender, "admin.doctor-storage-offline") + return + } + val accepted = executor.submit( + operation = { store.rewardBacklogCounts() }, + onSuccess = { backlog -> + sendLocalized( + sender, + "admin.doctor-storage", + mapOf( + "schema" to SqliteSchemaMigrator.currentVersion.toString(), + "pending" to backlog.pending.toString(), + "processing" to backlog.processing.toString(), + "uncertain" to backlog.uncertain.toString(), + ), + ) + }, + onFailure = { sendLocalized(sender, "admin.doctor-storage-failed") }, + ) + if (!accepted) sendLocalized(sender, "admin.doctor-executor-stopping") + } + + private fun sendLocalized( + sender: CommandSender, + key: String, + variables: Map = emptyMap(), + ) { + val messages = configuration.currentOrNull()?.value?.messages + if (messages == null) { + sender.sendMessage("InviteCode configuration is not loaded.") + return + } + val locale = (sender as? Player)?.let(BukkitLocaleCompatibility::locale) + sender.sendMessage(messages.resolve(locale, key, variables)) + } + + private fun saveBundledResources() { + BundledConfigurationInstaller(dataFolder.toPath(), ::getResource).installMissing() + } + + companion object { + private const val NETWORK_SECRET_FILE = "anti-abuse.key" } } -private class ScaffoldCommand : CommandExecutor { +private data class StartupResult( + val configuration: InviteCodeRuntimeConfiguration? = null, + val storage: InviteCodeStorage? = null, + val networkHasher: NetworkAddressHasher? = null, + val storageInitialized: Boolean = false, + val error: Throwable? = null, + val recoveredRewardActions: Int = 0, +) + +private data class StorageMigrationResult( + val version: Int, + val storage: InviteCodeStorage, + val networkHasher: NetworkAddressHasher?, +) + +private class RuntimeCommandExecutor( + private val runtime: PluginRuntimeState, + private val configuration: AtomicRuntimeSnapshot, + private val reload: (CommandSender) -> Unit, + private val migrateStorage: (CommandSender, ParsedInviteCodeCommand) -> Unit, + private val playerWorkflow: (Player, ParsedInviteCodeCommand) -> Boolean, + private val adminWorkflow: (CommandSender, ParsedInviteCodeCommand) -> Boolean, + private val doctor: (CommandSender) -> Unit, +) : CommandExecutor { override fun onCommand( sender: CommandSender, command: Command, label: String, args: Array, - ): Boolean { - sender.sendMessage("InviteCodeKt 已安裝;目前的專案骨架尚未實作玩家操作流程。") + ): Boolean = when (val parsed = InviteCodeCommandParser.parse(args.toList())) { + is InvalidInviteCodeCommand -> { + send(sender, "runtime.usage", mapOf("label" to label)) + true + } + is ParsedInviteCodeCommand -> execute(sender, label, parsed) + } + + private fun execute(sender: CommandSender, label: String, request: ParsedInviteCodeCommand): Boolean { + if (!sender.hasPermission(request.permission)) { + send(sender, "runtime.no-permission") + return true + } + if (request.playerOnly && sender !is Player) { + send(sender, "runtime.player-only") + return true + } + if (runtime.phase != RuntimePhase.ACTIVE && !request.allowedDuringMaintenance) { + send( + sender, + "runtime.unavailable", + mapOf("detail" to (runtime.maintenanceReason ?: runtime.phase.name)), + ) + return true + } + when (request.id) { + InviteCodeCommandId.HELP -> help(sender, label) + InviteCodeCommandId.ADMIN_RELOAD -> reload(sender) + InviteCodeCommandId.ADMIN_STORAGE_MIGRATE -> migrateStorage(sender, request) + InviteCodeCommandId.ADMIN_DOCTOR -> { + doctor(sender) + } + InviteCodeCommandId.CODE, + InviteCodeCommandId.CLAIM, + InviteCodeCommandId.CONFIRM, + InviteCodeCommandId.CANCEL, + InviteCodeCommandId.STATUS, + InviteCodeCommandId.STATS -> playerWorkflow(sender as Player, request) + else -> adminWorkflow(sender, request) + } return true } + + private fun send(sender: CommandSender, key: String, variables: Map = emptyMap()) { + val messages = configuration.currentOrNull()?.value?.messages + if (messages == null) { + sender.sendMessage("InviteCode configuration is not loaded.") + return + } + val locale = (sender as? Player)?.let(BukkitLocaleCompatibility::locale) + sender.sendMessage(messages.resolve(locale, key, variables)) + } + + private fun help(sender: CommandSender, label: String) { + send(sender, "runtime.help-header") + val routes = listOf( + Triple("invitecode.command.code", true, "/$label code"), + Triple("invitecode.command.claim", true, "/$label claim [code] | confirm | cancel"), + Triple("invitecode.command.status", true, "/$label status"), + Triple("invitecode.command.stats", true, "/$label stats"), + Triple("invitecode.admin.inspect", false, "/$label admin inspect player|invitation|reward ..."), + Triple("invitecode.admin.invitation", false, "/$label admin invitation unlink|transfer ..."), + Triple("invitecode.admin.qualification", false, "/$label admin invitation force-qualify ..."), + Triple("invitecode.admin.eligibility", false, "/$label admin eligibility reset ..."), + Triple("invitecode.admin.reward", false, "/$label admin reward retry|mark-delivered ..."), + Triple("invitecode.admin.code", false, "/$label admin code rotate ..."), + Triple("invitecode.admin.storage", false, "/$label admin storage migrate SQLITE "), + Triple("invitecode.admin.reload", false, "/$label reload"), + Triple("invitecode.admin.doctor", false, "/$label admin doctor"), + ) + routes.filter { (permission, playerOnly, _) -> + sender.hasPermission(permission) && (!playerOnly || sender is Player) + }.forEach { (_, _, usage) -> sender.sendMessage(usage) } + } } diff --git a/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/OptionalVaultIntegration.kt b/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/OptionalVaultIntegration.kt new file mode 100644 index 0000000..c436713 --- /dev/null +++ b/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/OptionalVaultIntegration.kt @@ -0,0 +1,26 @@ +package io.github.command1264.invitecode.plugin + +import io.github.command1264.invitecode.platform.bukkit.EconomyRewardGateway +import org.bukkit.Server +import java.util.logging.Level +import java.util.logging.Logger + +internal object OptionalVaultIntegration { + private const val ADAPTER_CLASS = + "io.github.command1264.invitecode.plugin.VaultEconomyRewardGateway" + + fun find(server: Server, logger: Logger): EconomyRewardGateway? { + if (!server.pluginManager.isPluginEnabled("Vault")) return null + + return try { + val adapter = Class.forName(ADAPTER_CLASS, true, OptionalVaultIntegration::class.java.classLoader) + adapter.getMethod("find", Server::class.java).invoke(null, server) as? EconomyRewardGateway + } catch (error: ReflectiveOperationException) { + logger.log(Level.WARNING, "Vault 已啟用,但 InviteCode 無法載入 Vault 經濟整合。", error) + null + } catch (error: LinkageError) { + logger.log(Level.WARNING, "Vault 已啟用,但 Vault API 或經濟服務不相容。", error) + null + } + } +} diff --git a/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/PlayerWorkflowController.kt b/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/PlayerWorkflowController.kt new file mode 100644 index 0000000..9146363 --- /dev/null +++ b/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/PlayerWorkflowController.kt @@ -0,0 +1,672 @@ +package io.github.command1264.invitecode.plugin + +import io.github.command1264.invitecode.api.InvitationStatus +import io.github.command1264.invitecode.api.QualificationEvaluationSnapshot +import io.github.command1264.invitecode.api.QualificationConditionContext +import io.github.command1264.invitecode.core.BuiltInQualificationProviders +import io.github.command1264.invitecode.core.ClaimConfirmation +import io.github.command1264.invitecode.core.ClaimEligibility +import io.github.command1264.invitecode.core.ClaimEligibilityPolicy +import io.github.command1264.invitecode.core.InvitationClaimResult +import io.github.command1264.invitecode.core.InvitationClaimService +import io.github.command1264.invitecode.core.InviteCode +import io.github.command1264.invitecode.core.InviteCodeLifecycleService +import io.github.command1264.invitecode.core.InviteCodeStorage +import io.github.command1264.invitecode.core.QualificationEvaluationStatus +import io.github.command1264.invitecode.core.QualificationEvaluator +import io.github.command1264.invitecode.core.QualificationProviderRegistry +import io.github.command1264.invitecode.core.QualificationRewardService +import io.github.command1264.invitecode.core.PermissionQualificationLookup +import io.github.command1264.invitecode.core.PlayerNetworkHash +import io.github.command1264.invitecode.core.PlaceholderQualificationLookup +import io.github.command1264.invitecode.core.RewardActionExecutionContext +import io.github.command1264.invitecode.core.RewardDeliveryCoordinator +import io.github.command1264.invitecode.core.StandardRewardActionExecutor +import io.github.command1264.invitecode.core.PlayerClaimState +import io.github.command1264.invitecode.core.StoredPlayer +import io.github.command1264.invitecode.core.StoredRewardAction +import io.github.command1264.invitecode.platform.bukkit.AsyncRewardDeliveryWorkflow +import io.github.command1264.invitecode.platform.bukkit.BukkitRewardExecutionEnvironment +import io.github.command1264.invitecode.platform.bukkit.CoordinatorRewardActionStateStore +import io.github.command1264.invitecode.platform.bukkit.EconomyRewardGateway +import io.github.command1264.invitecode.platform.bukkit.AsyncOperationExecutor +import io.github.command1264.invitecode.platform.bukkit.AtomicRuntimeSnapshot +import io.github.command1264.invitecode.platform.bukkit.ClaimInteractionSessions +import io.github.command1264.invitecode.platform.bukkit.InputMode +import io.github.command1264.invitecode.platform.bukkit.InviteCodeCommandId +import io.github.command1264.invitecode.platform.bukkit.InviteCodeRuntimeConfiguration +import io.github.command1264.invitecode.platform.bukkit.generator +import io.github.command1264.invitecode.platform.bukkit.parser +import io.github.command1264.invitecode.platform.bukkit.ParsedInviteCodeCommand +import io.github.command1264.invitecode.platform.bukkit.RewardMessageResolver +import io.github.command1264.invitecode.platform.bukkit.NetworkAddressHasher +import org.bukkit.ChatColor +import org.bukkit.OfflinePlayer +import org.bukkit.entity.Player +import org.bukkit.event.EventHandler +import org.bukkit.event.EventPriority +import org.bukkit.event.Listener +import org.bukkit.event.player.AsyncPlayerChatEvent +import org.bukkit.event.player.PlayerJoinEvent +import org.bukkit.event.player.PlayerQuitEvent +import org.bukkit.plugin.Plugin +import java.time.Instant +import java.time.Duration +import java.util.UUID +import java.util.concurrent.atomic.AtomicReference +import java.util.concurrent.CompletableFuture +import java.util.concurrent.CompletionStage +import java.util.logging.Level + +class PlayerWorkflowController( + private val plugin: Plugin, + private val configuration: AtomicRuntimeSnapshot, + private val storage: AtomicReference, + private val operations: AsyncOperationExecutor, + private val sessions: ClaimInteractionSessions, + private val externalQualificationProviders: QualificationProviderRegistry, + private val networkHasher: AtomicReference, + private val economyGateway: () -> EconomyRewardGateway? = { null }, + private val now: () -> Instant = Instant::now, +) : Listener { + fun requestQualificationEvaluation(invitationId: UUID): CompletionStage { + val future = CompletableFuture() + val accepted = operations.submit( + operation = { + val store = requireNotNull(storage.get()) { "SQLite storage is unavailable." } + requireNotNull(store.invitation(invitationId)) { "Invitation $invitationId does not exist." } + }, + onSuccess = { invitation -> + val player = plugin.server.getPlayer(invitation.inviteeId) + val runtime = configuration.current().value + val playTime = player?.let { + Duration.ofMillis(BukkitStatisticCompatibility.playTimeTicks(it) * 50L) + } + val inputs = player?.let { captureQualificationInputs(it, runtime) } + ?: QualificationInputs(emptyMap(), emptyMap()) + submitQualificationEvaluation(invitationId, playTime, runtime, inputs, future) + }, + onFailure = future::completeExceptionally, + ) + if (!accepted) future.completeExceptionally(IllegalStateException("InviteCode is stopping.")) + return future + } + + fun handle(player: Player, request: ParsedInviteCodeCommand): Boolean = when (request.id) { + InviteCodeCommandId.CODE -> showCode(player) + InviteCodeCommandId.CLAIM -> claim(player, request.operands.singleOrNull()) + InviteCodeCommandId.CONFIRM -> confirm(player) + InviteCodeCommandId.CANCEL -> cancel(player) + InviteCodeCommandId.STATUS -> status(player) + InviteCodeCommandId.STATS -> stats(player) + else -> false + }.let { true } + + @EventHandler(priority = EventPriority.MONITOR) + fun onJoin(event: PlayerJoinEvent) { + registerPlayer(event.player) + } + + fun registerPlayer(player: Player) { + if (storage.get() == null || configuration.currentOrNull() == null) return + val playerId = player.uniqueId + val playerName = player.name + val observedAt = now() + val snapshot = configuration.current() + val hasPlayedBefore = player.hasPlayedBefore() + val playTime = Duration.ofMillis(BukkitStatisticCompatibility.playTimeTicks(player) * 50L) + val externalInputs = captureQualificationInputs(player, snapshot.value) + val networkAddress = player.address?.address?.address?.copyOf() + submit( + playerId, + operation = { store -> + val existing = store.player(playerId) + val firstSeenAt = if ( + existing == null && hasPlayedBefore && + snapshot.value.general.claim.existingPlayerPolicy == + io.github.command1264.invitecode.platform.bukkit.ExistingPlayerPolicy.EXPIRED + ) { + observedAt.minus(snapshot.value.general.claim.window).minusNanos(1) + } else { + observedAt + } + store.savePlayer(existing?.copy(lastKnownName = playerName) ?: StoredPlayer(playerId, firstSeenAt, playerName)) + store.recordLoginDay( + playerId, + observedAt.atZone(snapshot.value.general.timeZone).toLocalDate(), + ) + store.purgeExpiredNetworkHashes(observedAt) + networkAddress?.let { address -> + try { + val hasher = requireNotNull(networkHasher.get()) { + "Network hash secret is unavailable." + } + val hash = hasher.hash(address) + store.recordNetworkHash( + PlayerNetworkHash( + playerId, + hasher.keyId, + hash, + observedAt, + observedAt.plus(snapshot.value.general.antiAbuse.ipHashRetention), + ), + ) + } finally { + address.fill(0) + } + } + evaluateQualificationsAndPendingRewards( + store, + playerId, + playerName, + playTime, + observedAt, + snapshot.value, + externalInputs, + ) + }, + onSuccess = ::deliverRewards, + ) + } + + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + fun onChat(event: AsyncPlayerChatEvent) { + val playerId = event.player.uniqueId + val code = sessions.consumeChatInput(playerId, event.message) ?: return + event.isCancelled = true + plugin.server.scheduler.runTask(plugin, Runnable { + plugin.server.getPlayer(playerId)?.let { beginClaim(it, code) } + }) + } + + @EventHandler + fun onQuit(event: PlayerQuitEvent) { + sessions.disconnect(event.player.uniqueId) + } + + private fun showCode(player: Player) { + val playerId = player.uniqueId + val snapshot = configuration.current() + val generator = snapshot.value.general.inviteCode.format.generator() + submit( + playerId, + operation = { store -> + InviteCodeLifecycleService(store, generator, 64).assign(playerId, now()) + }, + onSuccess = { code -> + send(playerId, "command.code.value", mapOf("code" to display(code.code))) + }, + ) + } + + private fun claim(player: Player, code: String?) { + val playerId = player.uniqueId + if (code != null) { + beginClaim(player, code) + return + } + val claim = configuration.current().value.general.claim + if (claim.inputMode == InputMode.COMMAND_ONLY) { + send(playerId, "command.claim.command-only") + return + } + sessions.startChatInput(playerId, claim.chatInputTimeout) + scheduleTimeout(claim.chatInputTimeout) { + if (sessions.expireChatInput(playerId)) send(playerId, "command.claim.chat-timeout") + } + send( + playerId, + "command.claim.chat-started", + mapOf("seconds" to claim.chatInputTimeout.seconds.toString()), + ) + } + + private fun beginClaim(player: Player, rawCode: String) { + val playerId = player.uniqueId + val snapshot = configuration.current() + submit( + playerId, + operation = { store -> prepareClaim(playerId, rawCode, snapshot.value, store) }, + onSuccess = { prepared -> + when (prepared) { + PreparedClaim.Invalid -> send(playerId, "command.claim.invalid-code") + PreparedClaim.Unavailable -> send(playerId, "command.claim.unavailable") + PreparedClaim.Self -> send(playerId, "command.claim.self") + is PreparedClaim.Ready -> { + sessions.startConfirmation(prepared.confirmation) + scheduleTimeout(snapshot.value.general.claim.confirmationTimeout) { + if (sessions.expireConfirmation(playerId)) { + send(playerId, "command.claim.confirmation-timeout") + } + } + send( + playerId, + "command.claim.confirmation", + mapOf( + "inviter" to prepared.confirmation.inviterName, + "code" to display(prepared.confirmation.inviteCode), + "seconds" to snapshot.value.general.claim.confirmationTimeout.seconds.toString(), + ), + ) + } + } + }, + ) + } + + private fun prepareClaim( + inviteeId: UUID, + rawCode: String, + runtime: InviteCodeRuntimeConfiguration, + store: InviteCodeStorage, + ): PreparedClaim { + val format = runtime.general.inviteCode.format.parser() + val code = try { + InviteCode.parse(rawCode, format) + } catch (_: IllegalArgumentException) { + return PreparedClaim.Invalid + } + val active = store.activeInviteCode(code) ?: return PreparedClaim.Unavailable + if (active.inviterId == inviteeId) return PreparedClaim.Self + val inviterName = store.player(active.inviterId)?.lastKnownName ?: active.inviterId.toString() + return PreparedClaim.Ready( + ClaimConfirmation.present( + inviteeId, + active.inviterId, + inviterName, + active.code, + now(), + runtime.general.claim.confirmationTimeout, + ), + ) + } + + private fun confirm(player: Player) { + val playerId = player.uniqueId + val confirmation = sessions.consumeConfirmation(playerId) + if (confirmation == null) { + send(playerId, "command.claim.no-confirmation") + return + } + val snapshot = configuration.current() + submit( + playerId, + operation = { store -> + val confirmed = confirmation.confirm(playerId, now()) + InvitationClaimService( + store, + ClaimEligibilityPolicy(snapshot.value.general.claim.window), + UUID::randomUUID, + snapshot.value.general.antiAbuse.matchingIpAction, + ).claim(confirmed) + }, + onSuccess = { result -> + when (result) { + is InvitationClaimResult.Claimed -> { + send(playerId, "command.claim.claimed") + if (result.matchingNetworkHash) { + send(playerId, "command.claim.matching-network-warning") + plugin.logger.warning( + "允許網路雜湊相符的 Claim:inviter=${result.invitation.inviterId}," + + "invitee=${result.invitation.inviteeId}。", + ) + } + plugin.server.getPlayer(playerId)?.let(::registerPlayer) + } + is InvitationClaimResult.MatchingNetworkDenied -> { + send(playerId, "command.claim.matching-network-denied") + plugin.logger.warning( + "拒絕網路雜湊相符的 Claim:inviter=${result.inviterId},invitee=${result.inviteeId}。", + ) + } + is InvitationClaimResult.InviteCodeUnavailable -> send( + playerId, + "command.claim.unavailable", + ) + is InvitationClaimResult.Rejected -> sendEligibility(playerId, result.eligibility) + } + }, + ) + } + + private fun cancel(player: Player) { + send( + player.uniqueId, + if (sessions.cancel(player.uniqueId)) "command.claim.cancelled" else "command.claim.nothing-to-cancel", + ) + } + + private fun status(player: Player) { + val playerId = player.uniqueId + val snapshot = configuration.current() + submit( + playerId, + operation = { store -> + val state = store.claimState(playerId) + PlayerStatus( + eligibility = ClaimEligibilityPolicy(snapshot.value.general.claim.window).evaluate(state, now()), + state = state, + invitationStatus = store.invitationsByInvitee(playerId).firstOrNull()?.status, + pendingRewards = store.pendingRewardActions(playerId).size, + ) + }, + onSuccess = { result -> + send( + playerId, + "command.status.summary", + mapOf( + "eligible" to resolve( + playerId, + if (result.eligibility.eligible) "value.yes" else "value.no", + ), + "invitation" to resolve( + playerId, + "value.invitation.${result.invitationStatus?.name?.lowercase() ?: "none"}", + ), + "pending_rewards" to result.pendingRewards.toString(), + ), + ) + if (!result.eligibility.eligible) sendEligibility(playerId, result.eligibility) + }, + ) + } + + private fun stats(player: Player) { + val playerId = player.uniqueId + submit( + playerId, + operation = { store -> store.inviterInvitationStats(playerId) }, + onSuccess = { result -> + send( + playerId, + "command.stats.summary", + mapOf("claimed" to result.claimed.toString(), "qualified" to result.qualified.toString()), + ) + }, + ) + } + + private fun sendEligibility(playerId: UUID, eligibility: ClaimEligibility) { + val reasons = eligibility.reasons.joinToString("、") { + resolve(playerId, "command.claim.reason.${it.name.lowercase()}") + } + send(playerId, "command.claim.ineligible", mapOf("reasons" to reasons)) + } + + private fun evaluateQualificationsAndPendingRewards( + store: InviteCodeStorage, + playerId: UUID, + playerName: String, + playTime: Duration, + evaluatedAt: Instant, + runtime: InviteCodeRuntimeConfiguration, + externalInputs: QualificationInputs, + ): List { + val evaluator = QualificationEvaluator( + QualificationProviderRegistry( + BuiltInQualificationProviders.create( + PermissionQualificationLookup { requestedPlayer, permission -> + externalInputs.permissions[permission].takeIf { requestedPlayer == playerId } + }, + PlaceholderQualificationLookup { requestedPlayer, placeholder -> + externalInputs.placeholders[placeholder].takeIf { requestedPlayer == playerId } + }, + ), + fallback = externalQualificationProviders, + ), + ) + val service = QualificationRewardService(store, evaluator) + store.invitationsByInvitee(playerId) + .filter { it.status == InvitationStatus.CLAIMED } + .forEach { invitation -> + for (policy in runtime.qualifications.policies.toSortedMap().values) { + val result = service.reevaluate( + invitation.id, + policy, + QualificationConditionContext( + invitationId = invitation.id, + inviterId = invitation.inviterId, + inviteeId = invitation.inviteeId, + claimedAt = invitation.claimedAt, + evaluatedAt = evaluatedAt, + playTime = playTime, + loginDays = store.loginDays(playerId), + ), + runtime.rewards, + ) + if (result.qualification.status == QualificationEvaluationStatus.QUALIFIED) break + } + } + return store.pendingRewardActions(playerId).map { action -> + val invitation = action.invitationId?.let(store::invitation) + val inviterId = invitation?.inviterId ?: action.recipientId.takeIf { action.invitationId == null } + PendingRewardTask( + action, + RewardActionExecutionContext( + recipientId = action.recipientId, + recipientName = playerName, + inviterId = inviterId, + inviterName = inviterId?.let { store.player(it)?.lastKnownName }, + inviteeId = invitation?.inviteeId, + inviteeName = invitation?.inviteeId?.let { store.player(it)?.lastKnownName }, + ), + ) + } + } + + private fun submitQualificationEvaluation( + invitationId: UUID, + playTime: Duration?, + runtime: InviteCodeRuntimeConfiguration, + externalInputs: QualificationInputs, + future: CompletableFuture, + ) { + val evaluatedAt = now() + val accepted = operations.submit( + operation = { + val store = requireNotNull(storage.get()) { "SQLite storage is unavailable." } + val invitation = requireNotNull(store.invitation(invitationId)) { + "Invitation $invitationId does not exist." + } + val evaluator = QualificationEvaluator( + QualificationProviderRegistry( + BuiltInQualificationProviders.create( + PermissionQualificationLookup { playerId, permission -> + externalInputs.permissions[permission] + .takeIf { playerId == invitation.inviteeId } + }, + PlaceholderQualificationLookup { playerId, placeholder -> + externalInputs.placeholders[placeholder] + .takeIf { playerId == invitation.inviteeId } + }, + ), + fallback = externalQualificationProviders, + ), + ) + var current = invitation + if (current.status == InvitationStatus.CLAIMED) { + val service = QualificationRewardService(store, evaluator) + for (policy in runtime.qualifications.policies.toSortedMap().values) { + val result = service.reevaluate( + current.id, + policy, + QualificationConditionContext( + current.id, + current.inviterId, + current.inviteeId, + current.claimedAt, + evaluatedAt, + playTime, + store.loginDays(current.inviteeId), + ), + runtime.rewards, + ) + current = result.qualification.invitation + if (current.status == InvitationStatus.QUALIFIED) break + } + } + val rewards = store.pendingRewardActions(current.inviteeId).map { action -> + PendingRewardTask( + action, + RewardActionExecutionContext( + action.recipientId, + store.player(action.recipientId)?.lastKnownName, + current.inviterId, + store.player(current.inviterId)?.lastKnownName, + current.inviteeId, + store.player(current.inviteeId)?.lastKnownName, + ), + ) + } + QualificationApiResult( + QualificationEvaluationSnapshot( + current.id, + current.status, + current.qualificationPolicyId, + current.qualificationRevision, + evaluatedAt, + ), + rewards, + ) + }, + onSuccess = { result -> + deliverRewards(result.pendingRewards) + future.complete(result.snapshot) + }, + onFailure = future::completeExceptionally, + ) + if (!accepted) future.completeExceptionally(IllegalStateException("InviteCode is stopping.")) + } + + private fun captureQualificationInputs( + player: Player, + runtime: InviteCodeRuntimeConfiguration, + ): QualificationInputs { + val conditions = runtime.qualifications.policies.values.flatMap { policy -> + policy.anyOf.flatMap { group -> group.allOf } + } + val permissions = conditions + .filter { it.type.equals("PERMISSION", ignoreCase = true) } + .mapNotNull { it.parameters["permission"] } + .distinct() + .associateWith(player::hasPermission) + val placeholders = conditions + .filter { it.type.equals("PLACEHOLDER", ignoreCase = true) } + .mapNotNull { it.parameters["placeholder"] } + .distinct() + .associateWith { placeholder -> resolvePlaceholder(player, placeholder) } + return QualificationInputs(permissions, placeholders) + } + + private fun resolvePlaceholder(player: Player, placeholder: String): String? { + if (plugin.server.pluginManager.getPlugin("PlaceholderAPI")?.isEnabled != true) return null + return try { + val type = Class.forName("me.clip.placeholderapi.PlaceholderAPI") + val method = type.getMethod("setPlaceholders", OfflinePlayer::class.java, String::class.java) + method.invoke(null, player, placeholder) as? String + } catch (error: ReflectiveOperationException) { + plugin.logger.log(Level.WARNING, "PlaceholderAPI 呼叫失敗,Qualification 將回報 UNKNOWN。", error) + null + } + } + + private fun deliverRewards(tasks: List) { + if (tasks.isEmpty()) return + val store = storage.get() ?: return + val messages = configuration.current().value.messages + val environment = BukkitRewardExecutionEnvironment( + plugin.server, + RewardMessageResolver { playerId, localeKey -> + val locale = plugin.server.getPlayer(playerId)?.let(BukkitLocaleCompatibility::locale) + messages.resolve(locale, localeKey) + }, + economyGateway(), + ) + val workflow = AsyncRewardDeliveryWorkflow( + operations, + CoordinatorRewardActionStateStore(RewardDeliveryCoordinator(store)), + StandardRewardActionExecutor(environment), + ) + tasks.forEach { task -> + val accepted = workflow.process( + task.action, + task.context, + onComplete = {}, + onFailure = { error -> + plugin.logger.log(Level.WARNING, "InviteCode Reward Action ${task.action.id} 處理失敗。", error) + }, + ) + if (!accepted) return + } + } + + private fun submit( + playerId: UUID, + operation: (InviteCodeStorage) -> T, + onSuccess: (T) -> Unit, + ) { + val accepted = operations.submit( + operation = { operation(requireNotNull(storage.get()) { "SQLite storage is unavailable." }) }, + onSuccess = onSuccess, + onFailure = { error -> + send(playerId, "command.error") + plugin.logger.log(Level.WARNING, "InviteCode 玩家操作失敗。", error) + }, + ) + if (!accepted) send(playerId, "command.stopping") + } + + private fun send(playerId: UUID, key: String, variables: Map = emptyMap()) { + val player = plugin.server.getPlayer(playerId) ?: return + val messages = configuration.currentOrNull()?.value?.messages + if (messages == null) { + player.sendMessage("InviteCode 設定尚未載入。") + return + } + player.sendMessage(messages.resolve(BukkitLocaleCompatibility.locale(player), key, variables)) + } + + private fun resolve(playerId: UUID, key: String): String { + val player = plugin.server.getPlayer(playerId) ?: return "[offline]" + return configuration.current().value.messages.resolve(BukkitLocaleCompatibility.locale(player), key) + } + + private fun display(code: InviteCode): String { + val legacy = code.color?.nearestLegacyColor() ?: return code.displayValue() + return "${ChatColor.COLOR_CHAR}${legacy.code}${code.displayValue()}${ChatColor.RESET}" + } + + private fun scheduleTimeout(duration: Duration, operation: () -> Unit) { + val ticks = ((duration.toMillis() + 49L) / 50L).coerceAtLeast(1L) + plugin.server.scheduler.runTaskLater(plugin, Runnable(operation), ticks) + } + + private sealed class PreparedClaim { + object Invalid : PreparedClaim() + object Unavailable : PreparedClaim() + object Self : PreparedClaim() + data class Ready(val confirmation: ClaimConfirmation) : PreparedClaim() + } + + private data class PlayerStatus( + val eligibility: ClaimEligibility, + val state: PlayerClaimState, + val invitationStatus: InvitationStatus?, + val pendingRewards: Int, + ) + + private data class PendingRewardTask( + val action: StoredRewardAction, + val context: RewardActionExecutionContext, + ) + + private data class QualificationInputs( + val permissions: Map, + val placeholders: Map, + ) + + private data class QualificationApiResult( + val snapshot: QualificationEvaluationSnapshot, + val pendingRewards: List, + ) +} diff --git a/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/SqliteRuntimeBootstrap.kt b/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/SqliteRuntimeBootstrap.kt new file mode 100644 index 0000000..b77c042 --- /dev/null +++ b/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/SqliteRuntimeBootstrap.kt @@ -0,0 +1,75 @@ +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.sql.BlockingOperationGuard +import io.github.command1264.invitecode.storage.sql.SqliteInviteCodeStorage +import io.github.command1264.invitecode.storage.sql.SqliteSchemaMigrator +import java.nio.file.Files +import java.nio.file.Path +import java.time.Instant +import java.util.UUID + +internal data class SqliteBootstrapResult( + val storage: SqliteInviteCodeStorage, + val networkHasher: NetworkAddressHasher, + val initialized: Boolean, +) + +internal class SqliteRuntimeBootstrap( + private val database: Path, + private val networkSecret: Path, + private val blockingOperationGuard: BlockingOperationGuard, + private val now: () -> Instant = Instant::now, +) { + fun initializeOrOpen(): SqliteBootstrapResult { + require(!Files.exists(database) || Files.isRegularFile(database)) { + "SQLite path ${database.toAbsolutePath()} exists but is not a regular file." + } + val initialize = !Files.exists(database) + val secretExisted = Files.isRegularFile(networkSecret) + var storage: SqliteInviteCodeStorage? = null + var hasher: NetworkAddressHasher? = null + try { + if (initialize) { + hasher = NetworkAddressHasher.loadOrCreate(networkSecret) + SqliteSchemaMigrator(database, blockingOperationGuard).migrate() + } else { + hasher = NetworkAddressHasher.loadExisting(networkSecret) + } + storage = SqliteInviteCodeStorage.open(database, blockingOperationGuard) + storage.purgeNetworkHashesWithDifferentKey(hasher.keyId) + if (initialize) { + storage.saveAuditRecord( + AuditRecord( + UUID.randomUUID(), + InvitationAuditAction.STORAGE_MIGRATED, + "system", + "automatic first initialization", + now(), + ), + ) + } + return SqliteBootstrapResult(storage, hasher, initialize) + } catch (error: Exception) { + storage?.close() + hasher?.close() + if (initialize) { + cleanupCreatedFile(database.resolveSibling("${database.fileName}-wal"), error) + cleanupCreatedFile(database.resolveSibling("${database.fileName}-shm"), error) + cleanupCreatedFile(database, error) + if (!secretExisted) cleanupCreatedFile(networkSecret, error) + } + throw error + } + } + + private fun cleanupCreatedFile(path: Path, original: Exception) { + try { + Files.deleteIfExists(path) + } catch (cleanupError: Exception) { + original.addSuppressed(cleanupError) + } + } +} diff --git a/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/VaultEconomyRewardGateway.kt b/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/VaultEconomyRewardGateway.kt index 9857dab..79eb7a2 100644 --- a/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/VaultEconomyRewardGateway.kt +++ b/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/VaultEconomyRewardGateway.kt @@ -17,6 +17,7 @@ class VaultEconomyRewardGateway private constructor( } companion object { + @JvmStatic fun find(server: Server): VaultEconomyRewardGateway? { if (!server.pluginManager.isPluginEnabled("Vault")) return null val provider = server.servicesManager.getRegistration(Economy::class.java)?.provider ?: return null diff --git a/invitecode-plugin/src/main/resources/config.yml b/invitecode-plugin/src/main/resources/config/config.yml similarity index 100% rename from invitecode-plugin/src/main/resources/config.yml rename to invitecode-plugin/src/main/resources/config/config.yml diff --git a/invitecode-plugin/src/main/resources/config/messages/en_US.yml b/invitecode-plugin/src/main/resources/config/messages/en_US.yml new file mode 100644 index 0000000..3e0f1a7 --- /dev/null +++ b/invitecode-plugin/src/main/resources/config/messages/en_US.yml @@ -0,0 +1,73 @@ +messages-version: 1 +runtime: + usage: "Invalid usage. Use /{label} help to see available commands." + no-permission: "You do not have permission to run this command." + player-only: "Only a player can run this command." + unavailable: "InviteCode cannot run this operation right now: {detail}" + help-header: "Available InviteCode commands:" +command: + code: + value: "Your Invite Code is {code}" + claim: + command-only: "Use /invitecode claim ." + chat-started: "Enter the Invite Code in chat within {seconds} seconds. It will not be published." + chat-timeout: "Invite Code chat input expired. Run /invitecode claim again." + invalid-code: "The Invite Code format is invalid. Check it and try again." + unavailable: "That Invite Code does not exist, was rotated, or is no longer active." + self: "You cannot use your own Invite Code." + confirmation: "Inviter: {inviter}; Invite Code: {code}. Use /invitecode confirm within {seconds} seconds, or /invitecode cancel." + confirmation-timeout: "The Claim Confirmation expired. Enter the Invite Code again." + no-confirmation: "There is no Claim to confirm, or it has expired." + claimed: "The Invitation has been created." + matching-network-warning: "You and the inviter recently used the same network. This Claim was allowed but may be reviewed by an administrator." + matching-network-denied: "You and the inviter recently used the same network, so this Claim was denied." + ineligible: "You cannot use an Invite Code right now. Reasons: {reasons}." + reason: + already_inviter: "you are already an Inviter" + already_invitee: "you already have an Invitation" + claim_window_expired: "the Claim Window has expired" + cancelled: "The current Invite Code input or confirmation was cancelled." + nothing-to-cancel: "There is no Invite Code input or confirmation to cancel." + status: + summary: "Invitation status: eligible={eligible}, Invitation={invitation}, pending Rewards={pending_rewards}." + stats: + summary: "Your Invitation stats: awaiting qualification={claimed}, qualified={qualified}." + error: "The operation failed. Check the server log or contact an administrator." + stopping: "InviteCode is stopping and cannot accept new operations." +value: + 'yes': "yes" + 'no': "no" + invitation: + none: "none" + claimed: "awaiting qualification" + qualified: "qualified" + unlinked: "unlinked" +admin: + invitation-unlinked: "Invitation {invitation} was unlinked." + invitation-transferred: "Invitation {invitation} was transferred to {inviter}." + invitation-force-qualified: "Invitation {invitation} was force-qualified and {rewards} Reward Deliveries were created." + eligibility-reset: "Claim Eligibility was reset for player {player}." + reward-resolved: "Reward Action {action} was resolved as {status}." + code-rotated: "Player {player}'s Invite Code was rotated from {previous} to {current}." + error: "The administrative operation failed. Check the server log." + stopping: "InviteCode is stopping and cannot accept administrative operations." + reload-stopping: "InviteCode is stopping and cannot reload configuration." + reload-success: "InviteCode validated and applied the complete configuration snapshot." + reload-storage-restart: "storage.yml changes were not applied. Complete an explicit cutover and restart." + reload-failed: "Configuration validation failed. The previous snapshot remains active; check the server log." + storage-unsupported: "This version can migrate only SQLITE storage." + storage-config-unavailable: "Configuration is not loaded, so the SQLite path is unavailable." + storage-stopping: "InviteCode is stopping and cannot run the migration." + storage-success: "SQLite schema migration completed at version {version}." + storage-failed: "SQLite schema migration failed. Check the server log." + doctor-runtime: "Runtime={phase}, configuration generation={generation}, executor={executor}." + doctor-integrations: "Integrations: PlaceholderAPI={placeholder}, Vault Economy={vault}." + 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-executor-stopping: "The executor is stopping and cannot query the Reward backlog." +invite: + qualified: + inviter: "Your invitation has qualified." + invitee: "You have qualified as an invitee." diff --git a/invitecode-plugin/src/main/resources/config/messages/zh_TW.yml b/invitecode-plugin/src/main/resources/config/messages/zh_TW.yml new file mode 100644 index 0000000..d47b86b --- /dev/null +++ b/invitecode-plugin/src/main/resources/config/messages/zh_TW.yml @@ -0,0 +1,73 @@ +messages-version: 1 +runtime: + usage: "用法錯誤。請使用 /{label} help 查看可用指令。" + no-permission: "你沒有執行此指令的權限。" + player-only: "此指令只能由玩家執行。" + unavailable: "InviteCode 目前無法執行此操作:{detail}" + help-header: "InviteCode 可用指令:" +command: + code: + value: "你的邀請碼是 {code}" + claim: + command-only: "請使用 /invitecode claim <邀請碼>。" + chat-started: "請在 {seconds} 秒內於聊天輸入邀請碼;內容不會公開。" + chat-timeout: "邀請碼聊天輸入已逾時,請重新執行 /invitecode claim。" + invalid-code: "邀請碼格式無效,請檢查後再試一次。" + unavailable: "此邀請碼不存在、已輪替或已失效。" + self: "你不能使用自己的邀請碼。" + confirmation: "邀請人為 {inviter},邀請碼為 {code}。請在 {seconds} 秒內使用 /invitecode confirm 確認,或使用 /invitecode cancel 取消。" + confirmation-timeout: "邀請確認已逾時,請重新輸入邀請碼。" + no-confirmation: "沒有可確認的邀請,或確認已逾時。" + claimed: "邀請關係已建立。" + matching-network-warning: "系統偵測到你與邀請人近期使用相同網路;本次登記已允許,但可能交由管理員檢查。" + matching-network-denied: "系統偵測到你與邀請人近期使用相同網路,因此拒絕本次登記。" + ineligible: "目前無法使用邀請碼,原因:{reasons}。" + reason: + already_inviter: "你已成為邀請人" + already_invitee: "你已有邀請關係" + claim_window_expired: "可登記期間已結束" + cancelled: "已取消目前的邀請碼輸入或確認。" + nothing-to-cancel: "目前沒有可取消的邀請碼輸入或確認。" + status: + summary: "邀請狀態:可使用邀請碼={eligible}、Invitation={invitation}、待補發獎勵={pending_rewards}。" + stats: + summary: "你的邀請統計:等待資格={claimed}、已達資格={qualified}。" + error: "操作失敗,請查看伺服器紀錄或聯絡管理員。" + stopping: "InviteCode 正在停止,暫時不接受新操作。" +value: + 'yes': "是" + 'no': "否" + invitation: + none: "無" + claimed: "等待資格" + qualified: "已達資格" + unlinked: "已解除連結" +admin: + invitation-unlinked: "Invitation {invitation} 已解除連結。" + invitation-transferred: "Invitation {invitation} 已轉移至 {inviter}。" + invitation-force-qualified: "Invitation {invitation} 已強制達成資格,並建立 {rewards} 筆 Reward Delivery。" + eligibility-reset: "玩家 {player} 的 Claim Eligibility 已重設。" + reward-resolved: "Reward Action {action} 已處理為 {status}。" + code-rotated: "玩家 {player} 的邀請碼已從 {previous} 輪替為 {current}。" + error: "管理操作失敗,請查看伺服器紀錄。" + stopping: "InviteCode 正在停止,無法接受管理操作。" + reload-stopping: "InviteCode 正在停止,無法重新載入設定。" + reload-success: "InviteCode 設定已完整驗證並套用。" + reload-storage-restart: "storage.yml 的變更尚未套用;請完成明確 cutover 並重新啟動。" + reload-failed: "設定驗證失敗,仍保留上一份有效設定;請查看伺服器紀錄。" + storage-unsupported: "目前版本只支援遷移 SQLITE 儲存。" + storage-config-unavailable: "設定尚未成功載入,無法判定 SQLite 位置。" + storage-stopping: "InviteCode 正在停止,無法執行 migration。" + storage-success: "SQLite schema migration 已完成,目前版本為 {version}。" + storage-failed: "SQLite schema migration 失敗,請查看伺服器紀錄。" + doctor-runtime: "Runtime={phase},設定世代={generation},executor={executor}。" + doctor-integrations: "Integration:PlaceholderAPI={placeholder},Vault Economy={vault}。" + 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-executor-stopping: "Executor 正在停止,無法完成 Reward backlog 查詢。" +invite: + qualified: + inviter: "你的邀請已達成資格。" + invitee: "你已達成邀請資格。" diff --git a/invitecode-plugin/src/main/resources/qualifications.yml b/invitecode-plugin/src/main/resources/config/qualifications.yml similarity index 100% rename from invitecode-plugin/src/main/resources/qualifications.yml rename to invitecode-plugin/src/main/resources/config/qualifications.yml diff --git a/invitecode-plugin/src/main/resources/rewards.yml b/invitecode-plugin/src/main/resources/config/rewards.yml similarity index 100% rename from invitecode-plugin/src/main/resources/rewards.yml rename to invitecode-plugin/src/main/resources/config/rewards.yml diff --git a/invitecode-plugin/src/main/resources/storage.yml b/invitecode-plugin/src/main/resources/config/storage.yml similarity index 100% rename from invitecode-plugin/src/main/resources/storage.yml rename to invitecode-plugin/src/main/resources/config/storage.yml diff --git a/invitecode-plugin/src/main/resources/messages/en_US.yml b/invitecode-plugin/src/main/resources/messages/en_US.yml deleted file mode 100644 index 3bb35d3..0000000 --- a/invitecode-plugin/src/main/resources/messages/en_US.yml +++ /dev/null @@ -1,5 +0,0 @@ -messages-version: 1 -invite: - qualified: - inviter: "Your invitation has qualified." - invitee: "You have qualified as an invitee." diff --git a/invitecode-plugin/src/main/resources/messages/zh_TW.yml b/invitecode-plugin/src/main/resources/messages/zh_TW.yml deleted file mode 100644 index 14eacaf..0000000 --- a/invitecode-plugin/src/main/resources/messages/zh_TW.yml +++ /dev/null @@ -1,5 +0,0 @@ -messages-version: 1 -invite: - qualified: - inviter: "你的邀請已達成資格。" - invitee: "你已達成邀請資格。" diff --git a/invitecode-plugin/src/main/resources/plugin.yml b/invitecode-plugin/src/main/resources/plugin.yml index 574998d..5869dfa 100644 --- a/invitecode-plugin/src/main/resources/plugin.yml +++ b/invitecode-plugin/src/main/resources/plugin.yml @@ -1,7 +1,8 @@ -name: InviteCodeKt +name: InviteCode version: "${version}" main: io.github.command1264.invitecode.plugin.InviteCodePlugin -description: 跨 Minecraft 版本的邀請與推薦獎勵插件。 +api-version: '1.13' +description: Cross-version invitation and referral rewards plugin. authors: [Command1264] website: https://github.com/Command1264/InviteCodeKt softdepend: [PlaceholderAPI, Vault] @@ -9,7 +10,7 @@ softdepend: [PlaceholderAPI, Vault] commands: invitecode: aliases: [ic] - description: InviteCodeKt 主要指令。 + description: Main InviteCode command. permission: invitecode.command.basic permissions: diff --git a/invitecode-plugin/src/test/kotlin/io/github/command1264/invitecode/plugin/BukkitCompatibilityTest.kt b/invitecode-plugin/src/test/kotlin/io/github/command1264/invitecode/plugin/BukkitCompatibilityTest.kt new file mode 100644 index 0000000..baac78c --- /dev/null +++ b/invitecode-plugin/src/test/kotlin/io/github/command1264/invitecode/plugin/BukkitCompatibilityTest.kt @@ -0,0 +1,38 @@ +package io.github.command1264.invitecode.plugin + +import org.bukkit.Statistic +import org.bukkit.plugin.PluginDescriptionFile +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test + +class BukkitCompatibilityTest { + @Test + fun `play-time statistic resolves on legacy and modern Bukkit names`() { + assertEquals( + "PLAY_ONE_MINUTE", + BukkitStatisticCompatibility.resolvePlayTimeStatisticName(listOf("PLAY_ONE_MINUTE")), + ) + assertEquals( + "PLAY_ONE_TICK", + BukkitStatisticCompatibility.resolvePlayTimeStatisticName(listOf("PLAY_ONE_TICK")), + ) + assertEquals( + "PLAY_ONE_TICK", + BukkitStatisticCompatibility.resolvePlayTimeStatisticName(Statistic.values().map(Statistic::name)), + ) + } + + @Test + fun `Spigot 1_8 loader accepts the modern api-version metadata`() { + val resource = requireNotNull(javaClass.getResourceAsStream("/plugin.yml")) + val text = resource.bufferedReader(Charsets.UTF_8).use { it.readText() } + assertTrue(text.lineSequence().any { it.trim() == "api-version: '1.13'" }) + + val description = javaClass.getResourceAsStream("/plugin.yml").use { input -> + PluginDescriptionFile(requireNotNull(input)) + } + + assertEquals("InviteCode", description.name) + } +} diff --git a/invitecode-plugin/src/test/kotlin/io/github/command1264/invitecode/plugin/BukkitConfigurationLoaderTest.kt b/invitecode-plugin/src/test/kotlin/io/github/command1264/invitecode/plugin/BukkitConfigurationLoaderTest.kt new file mode 100644 index 0000000..2885cdc --- /dev/null +++ b/invitecode-plugin/src/test/kotlin/io/github/command1264/invitecode/plugin/BukkitConfigurationLoaderTest.kt @@ -0,0 +1,48 @@ +package io.github.command1264.invitecode.plugin + +import org.junit.jupiter.api.Assertions.assertEquals +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 + +class BukkitConfigurationLoaderTest { + @TempDir + lateinit var dataDirectory: Path + + @Test + fun `bundled message catalogs preserve yes and no keys`() { + BundledConfigurationInstaller(dataDirectory) { resourcePath -> + javaClass.classLoader.getResourceAsStream(resourcePath) + }.installMissing() + + val configuration = BukkitConfigurationLoader(dataDirectory) {}.load() + + assertEquals("是", configuration.messages.resolve("zh_TW", "value.yes")) + assertEquals("否", configuration.messages.resolve("zh_TW", "value.no")) + assertEquals("yes", configuration.messages.resolve("en_US", "value.yes")) + assertEquals("no", configuration.messages.resolve("en_US", "value.no")) + } + + @Test + fun `catalogs generated with unquoted yaml boolean keys remain compatible`() { + BundledConfigurationInstaller(dataDirectory) { resourcePath -> + javaClass.classLoader.getResourceAsStream(resourcePath) + }.installMissing() + listOf("zh_TW", "en_US").forEach { locale -> + val path = dataDirectory.resolve("messages/$locale.yml") + val legacy = String(Files.readAllBytes(path), StandardCharsets.UTF_8) + .replace(" 'yes':", " yes:") + .replace(" 'no':", " no:") + Files.write(path, legacy.toByteArray(StandardCharsets.UTF_8)) + } + + val configuration = BukkitConfigurationLoader(dataDirectory) {}.load() + + assertEquals("是", configuration.messages.resolve("zh_TW", "value.yes")) + assertEquals("否", configuration.messages.resolve("zh_TW", "value.no")) + assertEquals("yes", configuration.messages.resolve("en_US", "value.yes")) + assertEquals("no", configuration.messages.resolve("en_US", "value.no")) + } +} diff --git a/invitecode-plugin/src/test/kotlin/io/github/command1264/invitecode/plugin/BukkitLocaleCompatibilityTest.kt b/invitecode-plugin/src/test/kotlin/io/github/command1264/invitecode/plugin/BukkitLocaleCompatibilityTest.kt new file mode 100644 index 0000000..d04eba6 --- /dev/null +++ b/invitecode-plugin/src/test/kotlin/io/github/command1264/invitecode/plugin/BukkitLocaleCompatibilityTest.kt @@ -0,0 +1,35 @@ +package io.github.command1264.invitecode.plugin + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Test + +class BukkitLocaleCompatibilityTest { + @Test + fun `uses modern player locale without touching the legacy receiver`() { + var legacyCalled = false + + val locale = BukkitLocaleCompatibility.resolveLocale(LocaleReceiver("zh_tw")) { + legacyCalled = true + LocaleReceiver("en_us") + } + + assertEquals("zh_tw", locale) + assertFalse(legacyCalled) + } + + @Test + fun `falls back to legacy Spigot locale`() { + val locale = BukkitLocaleCompatibility.resolveLocale(NoLocaleReceiver) { + LocaleReceiver("en_us") + } + + assertEquals("en_us", locale) + } +} + +class LocaleReceiver(private val locale: String) { + fun getLocale(): String = locale +} + +object NoLocaleReceiver diff --git a/invitecode-plugin/src/test/kotlin/io/github/command1264/invitecode/plugin/BundledConfigurationInstallerTest.kt b/invitecode-plugin/src/test/kotlin/io/github/command1264/invitecode/plugin/BundledConfigurationInstallerTest.kt new file mode 100644 index 0000000..005b207 --- /dev/null +++ b/invitecode-plugin/src/test/kotlin/io/github/command1264/invitecode/plugin/BundledConfigurationInstallerTest.kt @@ -0,0 +1,42 @@ +package io.github.command1264.invitecode.plugin + +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.io.TempDir +import java.io.ByteArrayInputStream +import java.nio.charset.StandardCharsets +import java.nio.file.Files +import java.nio.file.Path + +class BundledConfigurationInstallerTest { + @TempDir + lateinit var dataDirectory: Path + + @Test + fun `installs nested jar resources into the flat plugin data layout without overwriting settings`() { + Files.write(dataDirectory.resolve("config.yml"), "existing".toByteArray(StandardCharsets.UTF_8)) + val requested = mutableListOf() + val installer = BundledConfigurationInstaller(dataDirectory) { resourcePath -> + requested += resourcePath + ByteArrayInputStream(resourcePath.toByteArray(StandardCharsets.UTF_8)) + } + + installer.installMissing() + + assertEquals("existing", String(Files.readAllBytes(dataDirectory.resolve("config.yml")), StandardCharsets.UTF_8)) + assertEquals( + "config/storage.yml", + String(Files.readAllBytes(dataDirectory.resolve("storage.yml")), StandardCharsets.UTF_8), + ) + assertEquals( + "config/messages/zh_TW.yml", + String(Files.readAllBytes(dataDirectory.resolve("messages/zh_TW.yml")), StandardCharsets.UTF_8), + ) + assertFalse(Files.exists(dataDirectory.resolve("config/config.yml"))) + assertTrue("config/config.yml" !in requested) + assertTrue("config/storage.yml" in requested) + assertTrue("config/messages/en_US.yml" in requested) + } +} diff --git a/invitecode-plugin/src/test/kotlin/io/github/command1264/invitecode/plugin/ShadowJarRuntimeCompatibilityTest.kt b/invitecode-plugin/src/test/kotlin/io/github/command1264/invitecode/plugin/ShadowJarRuntimeCompatibilityTest.kt new file mode 100644 index 0000000..14dd7f7 --- /dev/null +++ b/invitecode-plugin/src/test/kotlin/io/github/command1264/invitecode/plugin/ShadowJarRuntimeCompatibilityTest.kt @@ -0,0 +1,52 @@ +package io.github.command1264.invitecode.plugin + +import org.junit.jupiter.api.Assertions.assertNotSame +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import java.net.URL +import java.net.URLClassLoader +import java.nio.file.Path +import java.nio.file.Paths +import java.sql.Connection + +class ShadowJarRuntimeCompatibilityTest { + @TempDir + lateinit var temporaryDirectory: Path + + @Test + fun `plugin uses its bundled SQLite driver when parent exposes the same package`() { + val archive = Paths.get(requireNotNull(System.getProperty("invitecode.shadowJar"))) + val parent = ClassLoader.getSystemClassLoader() + val parentDriverLoader = Class.forName("org.sqlite.JDBC", true, parent).classLoader + + PluginFirstClassLoader(archive.toUri().toURL(), parent).use { loader -> + val connections = loader.loadClass( + "io.github.command1264.invitecode.storage.sql.SqliteSchemaMigratorKt", + ) + val connection = connections.getMethod("connect", Path::class.java) + .invoke(null, temporaryDirectory.resolve("isolated.db")) as Connection + + connection.use { + assertTrue(it.isValid(1)) + assertNotSame(parentDriverLoader, it.javaClass.classLoader) + } + } + } + + private class PluginFirstClassLoader( + archive: URL, + parent: ClassLoader, + ) : URLClassLoader(arrayOf(archive), parent) { + override fun loadClass(name: String, resolve: Boolean): Class<*> { + if (!name.startsWith("io.github.command1264.invitecode.")) { + return super.loadClass(name, resolve) + } + synchronized(getClassLoadingLock(name)) { + val loaded = findLoadedClass(name) ?: findClass(name) + if (resolve) resolveClass(loaded) + return loaded + } + } + } +} diff --git a/invitecode-plugin/src/test/kotlin/io/github/command1264/invitecode/plugin/SqliteRuntimeBootstrapTest.kt b/invitecode-plugin/src/test/kotlin/io/github/command1264/invitecode/plugin/SqliteRuntimeBootstrapTest.kt new file mode 100644 index 0000000..a0a9841 --- /dev/null +++ b/invitecode-plugin/src/test/kotlin/io/github/command1264/invitecode/plugin/SqliteRuntimeBootstrapTest.kt @@ -0,0 +1,65 @@ +package io.github.command1264.invitecode.plugin + +import io.github.command1264.invitecode.platform.bukkit.NetworkAddressHasher +import io.github.command1264.invitecode.storage.sql.BlockingOperationGuard +import io.github.command1264.invitecode.storage.sql.SqliteSchemaMigrator +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 + +class SqliteRuntimeBootstrapTest { + @TempDir + lateinit var temporaryDirectory: Path + + @Test + fun `fresh installation creates SQLite schema and network secret automatically`() { + val database = temporaryDirectory.resolve("invitecode.db") + val secret = temporaryDirectory.resolve("anti-abuse.key") + + val result = SqliteRuntimeBootstrap(database, secret, BlockingOperationGuard { }).initializeOrOpen() + + result.storage.use { + result.networkHasher.use { + assertTrue(result.initialized) + assertTrue(Files.isRegularFile(database)) + assertEquals(32, Files.size(secret)) + } + } + } + + @Test + fun `existing database with a missing secret requires explicit recovery`() { + val database = temporaryDirectory.resolve("invitecode.db") + val secret = temporaryDirectory.resolve("anti-abuse.key") + SqliteSchemaMigrator(database, BlockingOperationGuard { }).migrate() + + assertThrows { + SqliteRuntimeBootstrap(database, secret, BlockingOperationGuard { }).initializeOrOpen() + } + + assertFalse(Files.exists(secret)) + } + + @Test + fun `existing older schema is never upgraded during ordinary startup`() { + val database = temporaryDirectory.resolve("invitecode.db") + val secret = temporaryDirectory.resolve("anti-abuse.key") + SqliteSchemaMigrator( + database, + BlockingOperationGuard { }, + SqliteSchemaMigrator.DEFAULT_MIGRATIONS.take(7), + ).migrate() + NetworkAddressHasher.loadOrCreate(secret).close() + + val error = assertThrows { + SqliteRuntimeBootstrap(database, secret, BlockingOperationGuard { }).initializeOrOpen() + } + + assertTrue(error.message!!.contains("run the explicit schema migration")) + } +} diff --git a/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqlStorageBackends.kt b/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqlStorageBackends.kt index 8d48536..eea7773 100644 --- a/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqlStorageBackends.kt +++ b/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqlStorageBackends.kt @@ -9,5 +9,5 @@ object SqliteStorageBackend : StorageBackendDescriptor { object MysqlStorageBackend : StorageBackendDescriptor { override val id: String = "mysql" - override val productionReady: Boolean = true + override val productionReady: Boolean = false } diff --git a/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqliteIdentityRecords.kt b/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqliteIdentityRecords.kt index b1fa173..53035ba 100644 --- a/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqliteIdentityRecords.kt +++ b/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqliteIdentityRecords.kt @@ -4,10 +4,12 @@ import io.github.command1264.invitecode.core.ActiveInviteCode import io.github.command1264.invitecode.core.AuditedClaimStateTransition import io.github.command1264.invitecode.core.InviteCode import io.github.command1264.invitecode.core.PlayerClaimState +import io.github.command1264.invitecode.core.PlayerNetworkHash import io.github.command1264.invitecode.core.RetiredInviteCode import io.github.command1264.invitecode.core.StoredPlayer import java.sql.Connection import java.time.Instant +import java.time.LocalDate import java.util.UUID internal object SqlitePlayerRecords { @@ -17,7 +19,7 @@ internal object SqlitePlayerRecords { INSERT INTO invitecode_players(player_id, first_seen_at, last_known_name) VALUES (?, ?, ?) ON CONFLICT(player_id) DO UPDATE SET - last_known_name = excluded.last_known_name + last_known_name = COALESCE(excluded.last_known_name, invitecode_players.last_known_name) """.trimIndent(), ).use { statement -> statement.setString(1, player.id.toString()) @@ -27,6 +29,52 @@ internal object SqlitePlayerRecords { } } + fun findByLastKnownName(connection: Connection, lastKnownName: String): List = + connection.prepareStatement( + """ + SELECT player_id, first_seen_at, last_known_name + FROM invitecode_players + WHERE last_known_name = ? COLLATE NOCASE + ORDER BY player_id + LIMIT 2 + """.trimIndent(), + ).use { statement -> + statement.setString(1, lastKnownName) + statement.executeQuery().use { result -> + buildList { + while (result.next()) { + add( + StoredPlayer( + id = UUID.fromString(result.getString("player_id")), + firstSeenAt = Instant.parse(result.getString("first_seen_at")), + lastKnownName = result.getString("last_known_name"), + ), + ) + } + } + } + } + + fun recordLoginDay(connection: Connection, playerId: UUID, loginDate: LocalDate) { + connection.prepareStatement( + "INSERT OR IGNORE INTO invitecode_player_login_days(player_id, login_date) VALUES (?, ?)", + ).use { statement -> + statement.setString(1, playerId.toString()) + statement.setString(2, loginDate.toString()) + statement.executeUpdate() + } + } + + fun loginDays(connection: Connection, playerId: UUID): Int = connection.prepareStatement( + "SELECT COUNT(*) FROM invitecode_player_login_days WHERE player_id = ?", + ).use { statement -> + statement.setString(1, playerId.toString()) + statement.executeQuery().use { result -> + result.next() + result.getInt(1) + } + } + fun find(connection: Connection, playerId: UUID): StoredPlayer? = connection.prepareStatement( "SELECT player_id, first_seen_at, last_known_name FROM invitecode_players WHERE player_id = ?", @@ -56,6 +104,9 @@ internal object SqlitePlayerRecords { """ SELECT EXISTS( + SELECT 1 FROM invitecode_codes + WHERE inviter_id = ? AND retired_at IS NULL + ) OR EXISTS( SELECT 1 FROM invitecode_invitations WHERE inviter_id = ? AND inviter_eligibility_generation = ? ) AS is_inviter, @@ -66,9 +117,10 @@ internal object SqlitePlayerRecords { """.trimIndent(), ).use { statement -> statement.setString(1, playerId.toString()) - statement.setInt(2, playerState.second) - statement.setString(3, playerId.toString()) - statement.setInt(4, playerState.second) + statement.setString(2, playerId.toString()) + statement.setInt(3, playerState.second) + statement.setString(4, playerId.toString()) + statement.setInt(5, playerState.second) statement.executeQuery().use { result -> result.next() result.getBoolean("is_inviter") to result.getBoolean("has_invitation") @@ -106,6 +158,67 @@ internal object SqlitePlayerRecords { } } +internal object SqliteNetworkHashRecords { + fun save(connection: Connection, record: PlayerNetworkHash) { + connection.prepareStatement( + """ + INSERT INTO invitecode_player_network_hashes(player_id, key_id, network_hash, observed_at, expires_at) + VALUES (?, ?, ?, ?, ?) + ON CONFLICT(player_id, key_id, network_hash) DO UPDATE SET + observed_at = excluded.observed_at, + expires_at = excluded.expires_at + """.trimIndent(), + ).use { statement -> + statement.setString(1, record.playerId.toString()) + statement.setString(2, record.keyId) + statement.setString(3, record.hash) + statement.setString(4, record.observedAt.toString()) + statement.setString(5, record.expiresAt.toString()) + statement.executeUpdate() + } + } + + fun purgeExpired(connection: Connection, expiredAt: Instant): Int = connection.prepareStatement( + "DELETE FROM invitecode_player_network_hashes WHERE expires_at <= ?", + ).use { statement -> + statement.setString(1, expiredAt.toString()) + statement.executeUpdate() + } + + fun purgeDifferentKey(connection: Connection, keyId: String): Int = connection.prepareStatement( + "DELETE FROM invitecode_player_network_hashes WHERE key_id <> ?", + ).use { statement -> + statement.setString(1, keyId) + statement.executeUpdate() + } + + fun matches( + connection: Connection, + firstPlayerId: UUID, + secondPlayerId: UUID, + evaluatedAt: Instant, + ): Boolean = connection.prepareStatement( + """ + SELECT 1 + FROM invitecode_player_network_hashes first_hash + INNER JOIN invitecode_player_network_hashes second_hash + ON second_hash.key_id = first_hash.key_id + AND second_hash.network_hash = first_hash.network_hash + WHERE first_hash.player_id = ? + AND second_hash.player_id = ? + AND first_hash.expires_at > ? + AND second_hash.expires_at > ? + LIMIT 1 + """.trimIndent(), + ).use { statement -> + statement.setString(1, firstPlayerId.toString()) + statement.setString(2, secondPlayerId.toString()) + statement.setString(3, evaluatedAt.toString()) + statement.setString(4, evaluatedAt.toString()) + statement.executeQuery().use { it.next() } + } +} + internal object SqliteInviteCodeRecords { fun findActive(connection: Connection, inviterId: UUID): ActiveInviteCode? = connection.prepareStatement( @@ -126,6 +239,25 @@ internal object SqliteInviteCodeRecords { } } + fun findActive(connection: Connection, inviteCode: InviteCode): ActiveInviteCode? = + connection.prepareStatement( + """ + SELECT code, inviter_id, activated_at + FROM invitecode_codes + WHERE code = ? AND retired_at IS NULL + """.trimIndent(), + ).use { statement -> + statement.setString(1, inviteCode.normalized) + statement.executeQuery().use { result -> + if (!result.next()) return@use null + ActiveInviteCode( + inviterId = UUID.fromString(result.getString("inviter_id")), + code = InviteCode.fromNormalized(result.getString("code")), + activatedAt = Instant.parse(result.getString("activated_at")), + ) + } + } + fun isReserved(connection: Connection, code: InviteCode): Boolean = connection.prepareStatement("SELECT 1 FROM invitecode_codes WHERE code = ?").use { statement -> statement.setString(1, code.normalized) diff --git a/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqliteInvitationRecords.kt b/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqliteInvitationRecords.kt index 024c797..a398b34 100644 --- a/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqliteInvitationRecords.kt +++ b/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqliteInvitationRecords.kt @@ -6,6 +6,8 @@ import io.github.command1264.invitecode.core.AuditedInvitationTransition import io.github.command1264.invitecode.core.Invitation import io.github.command1264.invitecode.core.InvitationAuditAction import io.github.command1264.invitecode.core.InvitationAuditDetails +import io.github.command1264.invitecode.core.InviterInvitationStats +import io.github.command1264.invitecode.core.MAX_AUDIT_HISTORY_LIMIT import io.github.command1264.invitecode.core.QualificationFact import io.github.command1264.invitecode.core.QualificationFactOutcome import java.sql.Connection @@ -117,16 +119,48 @@ internal object SqliteInvitationRecords { statement.setString(1, invitationId.toString()) statement.executeQuery().use { result -> if (!result.next()) return@use null - Invitation( - id = UUID.fromString(result.getString("invitation_id")), - inviterId = UUID.fromString(result.getString("inviter_id")), - inviteeId = UUID.fromString(result.getString("invitee_id")), - status = InvitationStatus.valueOf(result.getString("status")), - claimedAt = Instant.parse(result.getString("claimed_at")), - qualifiedAt = result.getString("qualified_at")?.let(Instant::parse), - qualificationPolicyId = result.getString("qualification_policy_id"), - qualificationRevision = result.getString("qualification_revision"), - ) + result.toInvitation() + } + } + + fun findByInvitee(connection: Connection, inviteeId: UUID): List = + findByPlayerColumn(connection, "invitee_id", inviteeId) + + fun findByInviter(connection: Connection, inviterId: UUID): List = + findByPlayerColumn(connection, "inviter_id", inviterId) + + private fun findByPlayerColumn(connection: Connection, column: String, playerId: UUID): List = + connection.prepareStatement( + """ + SELECT invitation_id, inviter_id, invitee_id, status, claimed_at, + qualified_at, qualification_policy_id, qualification_revision + FROM invitecode_invitations + WHERE $column = ? + ORDER BY claimed_at DESC, invitation_id DESC + """.trimIndent(), + ).use { statement -> + statement.setString(1, playerId.toString()) + statement.executeQuery().use { result -> + buildList { while (result.next()) add(result.toInvitation()) } + } + } + + fun statsForInviter(connection: Connection, inviterId: UUID): InviterInvitationStats = + connection.prepareStatement( + """ + SELECT + SUM(CASE WHEN status = ? THEN 1 ELSE 0 END) AS claimed_count, + SUM(CASE WHEN status = ? THEN 1 ELSE 0 END) AS qualified_count + FROM invitecode_invitations + WHERE inviter_id = ? + """.trimIndent(), + ).use { statement -> + statement.setString(1, InvitationStatus.CLAIMED.name) + statement.setString(2, InvitationStatus.QUALIFIED.name) + statement.setString(3, inviterId.toString()) + statement.executeQuery().use { result -> + check(result.next()) { "Inviter Invitation stats query returned no row." } + InviterInvitationStats(result.getInt("claimed_count"), result.getInt("qualified_count")) } } @@ -141,6 +175,17 @@ internal object SqliteInvitationRecords { result.getInt(1) } } + + private fun java.sql.ResultSet.toInvitation() = Invitation( + id = UUID.fromString(getString("invitation_id")), + inviterId = UUID.fromString(getString("inviter_id")), + inviteeId = UUID.fromString(getString("invitee_id")), + status = InvitationStatus.valueOf(getString("status")), + claimedAt = Instant.parse(getString("claimed_at")), + qualifiedAt = getString("qualified_at")?.let(Instant::parse), + qualificationPolicyId = getString("qualification_policy_id"), + qualificationRevision = getString("qualification_revision"), + ) } internal object SqliteQualificationRecords { @@ -191,6 +236,36 @@ internal object SqliteQualificationRecords { ) } } + + fun findByInvitation(connection: Connection, invitationId: UUID): List = + connection.prepareStatement( + """ + SELECT fact_id, invitation_id, policy_id, qualification_revision, + condition_id, outcome, recorded_at + FROM invitecode_qualification_facts + WHERE invitation_id = ? + ORDER BY recorded_at, fact_id + """.trimIndent(), + ).use { statement -> + statement.setString(1, invitationId.toString()) + statement.executeQuery().use { result -> + buildList { + while (result.next()) { + add( + QualificationFact( + id = UUID.fromString(result.getString("fact_id")), + invitationId = UUID.fromString(result.getString("invitation_id")), + policyId = result.getString("policy_id"), + qualificationRevision = result.getString("qualification_revision"), + conditionId = result.getString("condition_id"), + outcome = QualificationFactOutcome.valueOf(result.getString("outcome")), + recordedAt = Instant.parse(result.getString("recorded_at")), + ), + ) + } + } + } + } } internal object SqliteAuditRecords { @@ -226,24 +301,53 @@ internal object SqliteAuditRecords { statement.setString(1, recordId.toString()) statement.executeQuery().use { result -> if (!result.next()) return@use null - AuditRecord( - id = UUID.fromString(result.getString("audit_id")), - action = InvitationAuditAction.valueOf(result.getString("action")), - actor = result.getString("actor"), - reason = result.getString("reason"), - occurredAt = Instant.parse(result.getString("occurred_at")), - invitationId = result.getString("invitation_id")?.let(UUID::fromString), - playerId = result.getString("player_id")?.let(UUID::fromString), - details = AuditDetailsCodec.decode( - kind = result.getString("details_kind"), - previousInviterId = result.getString("previous_inviter_id"), - newInviterId = result.getString("new_inviter_id"), - qualificationPolicyId = result.getString("qualification_policy_id"), - qualificationRevision = result.getString("qualification_revision"), - ), - ) + result.toAuditRecord() + } + } + + fun findByInvitation(connection: Connection, invitationId: UUID, limit: Int): List = + findHistory(connection, "invitation_id", invitationId, limit) + + fun findByPlayer(connection: Connection, playerId: UUID, limit: Int): List = + findHistory(connection, "player_id", playerId, limit) + + private fun findHistory( + connection: Connection, + column: String, + targetId: UUID, + limit: Int, + ): List { + require(limit in 1..MAX_AUDIT_HISTORY_LIMIT) { + "Audit history limit must be between 1 and $MAX_AUDIT_HISTORY_LIMIT." + } + return connection.prepareStatement( + "SELECT * FROM invitecode_audit_records WHERE $column = ? " + + "ORDER BY occurred_at DESC, audit_id DESC LIMIT ?", + ).use { statement -> + statement.setString(1, targetId.toString()) + statement.setInt(2, limit) + statement.executeQuery().use { result -> + buildList { while (result.next()) add(result.toAuditRecord()) } } } + } + + private fun java.sql.ResultSet.toAuditRecord() = AuditRecord( + id = UUID.fromString(getString("audit_id")), + action = InvitationAuditAction.valueOf(getString("action")), + actor = getString("actor"), + reason = getString("reason"), + occurredAt = Instant.parse(getString("occurred_at")), + invitationId = getString("invitation_id")?.let(UUID::fromString), + playerId = getString("player_id")?.let(UUID::fromString), + details = AuditDetailsCodec.decode( + kind = getString("details_kind"), + previousInviterId = getString("previous_inviter_id"), + newInviterId = getString("new_inviter_id"), + qualificationPolicyId = getString("qualification_policy_id"), + qualificationRevision = getString("qualification_revision"), + ), + ) } private data class AuditDetailsColumns( diff --git a/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqliteInviteCodeStorage.kt b/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqliteInviteCodeStorage.kt index 0e79139..b62b66b 100644 --- a/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqliteInviteCodeStorage.kt +++ b/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqliteInviteCodeStorage.kt @@ -9,12 +9,16 @@ import io.github.command1264.invitecode.core.InviteCodeStorage import io.github.command1264.invitecode.core.InviteCodeTransaction import io.github.command1264.invitecode.core.Invitation import io.github.command1264.invitecode.core.InvitationTransaction +import io.github.command1264.invitecode.core.InviterInvitationStats import io.github.command1264.invitecode.core.PlayerClaimState +import io.github.command1264.invitecode.core.PlayerNetworkHash import io.github.command1264.invitecode.core.QualificationFact import io.github.command1264.invitecode.core.RetiredInviteCode import io.github.command1264.invitecode.core.RewardActionStatus import io.github.command1264.invitecode.core.RewardAdministrationContext +import io.github.command1264.invitecode.core.RewardBacklogCounts import io.github.command1264.invitecode.core.RewardDeliveryStatus +import io.github.command1264.invitecode.core.RewardDeliveryPlan import io.github.command1264.invitecode.core.StoredPlayer import io.github.command1264.invitecode.core.StoredRewardAction import io.github.command1264.invitecode.core.StoredRewardActionTransition @@ -22,6 +26,7 @@ import io.github.command1264.invitecode.core.StoredRewardDelivery import io.github.command1264.invitecode.core.StoredRewardDeliveryTransition import io.github.command1264.invitecode.core.UncertainRewardActionResolution import java.time.Instant +import java.time.LocalDate import java.nio.file.Path import java.sql.Connection import java.sql.SQLException @@ -39,14 +44,48 @@ class SqliteInviteCodeStorage private constructor( write { SqlitePlayerRecords.save(it, player) } } + override fun recordLoginDay(playerId: UUID, loginDate: LocalDate) { + write { SqlitePlayerRecords.recordLoginDay(it, playerId, loginDate) } + } + + override fun loginDays(playerId: UUID): Int = read { + SqlitePlayerRecords.loginDays(it, playerId) + } + + override fun recordNetworkHash(record: PlayerNetworkHash) { + write { SqliteNetworkHashRecords.save(it, record) } + } + + override fun purgeExpiredNetworkHashes(expiredAt: Instant): Int = write { + SqliteNetworkHashRecords.purgeExpired(it, expiredAt) + } + + override fun purgeNetworkHashesWithDifferentKey(keyId: String): Int { + require(Regex("[0-9a-f]{64}").matches(keyId)) { "Network hash key ID is invalid." } + return write { SqliteNetworkHashRecords.purgeDifferentKey(it, keyId) } + } + override fun player(playerId: UUID): StoredPlayer? = read { SqlitePlayerRecords.find(it, playerId) } + override fun playersByLastKnownName(lastKnownName: String): List { + require(lastKnownName.isNotBlank()) { "Last known player name must not be blank." } + return read { SqlitePlayerRecords.findByLastKnownName(it, lastKnownName) } + } + + override fun claimState(playerId: UUID): PlayerClaimState = read { + SqlitePlayerRecords.claimState(it, playerId) + } + override fun activeInviteCode(inviterId: UUID): ActiveInviteCode? = read { SqliteInviteCodeRecords.findActive(it, inviterId) } + override fun activeInviteCode(inviteCode: InviteCode): ActiveInviteCode? = read { + SqliteInviteCodeRecords.findActive(it, inviteCode) + } + override fun isInviteCodeReserved(code: InviteCode): Boolean = read { SqliteInviteCodeRecords.isReserved(it, code) } @@ -59,6 +98,18 @@ class SqliteInviteCodeStorage private constructor( SqliteInvitationRecords.find(it, invitationId) } + override fun invitationsByInvitee(inviteeId: UUID): List = read { + SqliteInvitationRecords.findByInvitee(it, inviteeId) + } + + override fun invitationsByInviter(inviterId: UUID): List = read { + SqliteInvitationRecords.findByInviter(it, inviterId) + } + + override fun inviterInvitationStats(inviterId: UUID): InviterInvitationStats = read { + SqliteInvitationRecords.statsForInviter(it, inviterId) + } + override fun saveQualifiedInvitation(invitation: Invitation, facts: List) { require(facts.isNotEmpty()) { "Qualification requires at least one persisted Qualification Fact." } require( @@ -74,6 +125,37 @@ class SqliteInviteCodeStorage private constructor( } } + override fun saveQualifiedInvitationWithRewards( + invitation: Invitation, + facts: List, + rewardPlans: List, + ) { + require(facts.isNotEmpty()) { "Qualification requires at least one persisted Qualification Fact." } + require( + facts.all { + it.invitationId == invitation.id && + it.policyId == invitation.qualificationPolicyId && + it.qualificationRevision == invitation.qualificationRevision + }, + ) { + "Every Qualification Fact must match Invitation ${invitation.id} and its policy revision." + } + require(rewardPlans.flatMap { it.actions }.all { it.status == RewardActionStatus.PENDING }) { + "New Reward Actions must start in PENDING state." + } + require(rewardPlans.all { it.delivery.status == RewardDeliveryStatus.PENDING }) { + "New Reward Deliveries must start in PENDING state." + } + write { connection -> + SqliteInvitationRecords.qualify(connection, invitation) + facts.forEach { SqliteQualificationRecords.save(connection, it) } + rewardPlans.forEach { plan -> + SqliteRewardRecords.saveDelivery(connection, plan.delivery) + plan.actions.forEach { SqliteRewardRecords.saveAction(connection, it) } + } + } + } + override fun saveQualificationFact(fact: QualificationFact) { write { SqliteQualificationRecords.save(it, fact) } } @@ -92,6 +174,10 @@ class SqliteInviteCodeStorage private constructor( SqliteQualificationRecords.find(it, factId) } + override fun qualificationFacts(invitationId: UUID): List = read { + SqliteQualificationRecords.findByInvitation(it, invitationId) + } + override fun saveRewardAction(action: StoredRewardAction) { write { connection -> requireNotNull(SqliteRewardRecords.findAction(connection, action.id)) { @@ -200,6 +286,14 @@ class SqliteInviteCodeStorage private constructor( SqliteRewardRecords.findDelivery(it, deliveryId) } + override fun rewardDeliveries(invitationId: UUID): List = read { + SqliteRewardRecords.findDeliveriesByInvitation(it, invitationId) + } + + override fun rewardBacklogCounts(): RewardBacklogCounts = read { + SqliteRewardRecords.backlogCounts(it) + } + override fun rewardDeliveryTransitions(deliveryId: UUID): List = read { SqliteRewardRecords.findDeliveryTransitions(it, deliveryId) } @@ -212,6 +306,14 @@ class SqliteInviteCodeStorage private constructor( SqliteAuditRecords.find(it, recordId) } + override fun auditHistoryByInvitation(invitationId: UUID, limit: Int): List = read { + SqliteAuditRecords.findByInvitation(it, invitationId, limit) + } + + override fun auditHistoryByPlayer(playerId: UUID, limit: Int): List = read { + SqliteAuditRecords.findByPlayer(it, playerId, limit) + } + override fun saveAuditedInvitationTransition(transition: AuditedInvitationTransition) { write { connection -> SqliteInvitationRecords.transition(connection, transition) @@ -219,6 +321,23 @@ class SqliteInviteCodeStorage private constructor( } } + override fun saveForcedQualificationWithRewards( + transition: AuditedInvitationTransition, + rewardPlans: List, + ) { + require(transition.auditRecord.action == io.github.command1264.invitecode.core.InvitationAuditAction.FORCE_QUALIFIED) { + "Forced Qualification persistence requires a FORCE_QUALIFIED audit transition." + } + write { connection -> + SqliteInvitationRecords.transition(connection, transition) + SqliteAuditRecords.save(connection, transition.auditRecord) + rewardPlans.forEach { plan -> + SqliteRewardRecords.saveDelivery(connection, plan.delivery) + plan.actions.forEach { SqliteRewardRecords.saveAction(connection, it) } + } + } + } + override fun saveAuditedClaimStateTransition(transition: AuditedClaimStateTransition) { write { connection -> SqlitePlayerRecords.resetEligibility(connection, transition) @@ -242,6 +361,10 @@ class SqliteInviteCodeStorage private constructor( SqliteInviteCodeRecords.retire(connection, previous) SqliteInviteCodeRecords.activate(connection, current) } + + override fun saveAuditRecord(record: AuditRecord) { + SqliteAuditRecords.save(connection, record) + } }) } @@ -251,9 +374,23 @@ class SqliteInviteCodeStorage private constructor( ): T = write { connection -> require(playerIds.isNotEmpty()) { "An Invitation transaction requires at least one player." } operation(object : InvitationTransaction { + override fun activeInviter(inviteCode: InviteCode): UUID? = + SqliteInviteCodeRecords.findActive(connection, inviteCode)?.inviterId + override fun claimState(playerId: UUID): PlayerClaimState = SqlitePlayerRecords.claimState(connection, playerId) + override fun hasMatchingNetworkHash( + firstPlayerId: UUID, + secondPlayerId: UUID, + evaluatedAt: Instant, + ): Boolean = SqliteNetworkHashRecords.matches( + connection, + firstPlayerId, + secondPlayerId, + evaluatedAt, + ) + override fun add(invitation: Invitation) { SqliteInvitationRecords.save(connection, invitation, updateExisting = false) } diff --git a/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqliteRewardRecords.kt b/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqliteRewardRecords.kt index ee6d4ec..199ef79 100644 --- a/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqliteRewardRecords.kt +++ b/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqliteRewardRecords.kt @@ -2,6 +2,7 @@ package io.github.command1264.invitecode.storage.sql import io.github.command1264.invitecode.core.RewardActionStatus import io.github.command1264.invitecode.core.RewardAdministrationContext +import io.github.command1264.invitecode.core.RewardBacklogCounts import io.github.command1264.invitecode.core.RewardDeliveryStatus import io.github.command1264.invitecode.core.StoredRewardAction import io.github.command1264.invitecode.core.StoredRewardActionTransition @@ -87,14 +88,43 @@ internal object SqliteRewardRecords { statement.setString(1, deliveryId.toString()) statement.executeQuery().use { result -> if (!result.next()) return@use null - StoredRewardDelivery( - id = UUID.fromString(result.getString("delivery_id")), - invitationId = result.getString("invitation_id")?.let(UUID::fromString), - rewardId = result.getString("reward_id"), - status = RewardDeliveryStatus.valueOf(result.getString("status")), - idempotencyKey = result.getString("idempotency_key"), - createdAt = Instant.parse(result.getString("created_at")), - updatedAt = Instant.parse(result.getString("updated_at")), + result.toRewardDelivery() + } + } + + fun findDeliveriesByInvitation(connection: Connection, invitationId: UUID): List = + connection.prepareStatement( + """ + SELECT * FROM invitecode_reward_deliveries + WHERE invitation_id = ? + ORDER BY created_at DESC, delivery_id DESC + """.trimIndent(), + ).use { statement -> + statement.setString(1, invitationId.toString()) + statement.executeQuery().use { result -> + buildList { while (result.next()) add(result.toRewardDelivery()) } + } + } + + fun backlogCounts(connection: Connection): RewardBacklogCounts = + connection.prepareStatement( + """ + SELECT + SUM(CASE WHEN status = ? THEN 1 ELSE 0 END) AS pending_count, + SUM(CASE WHEN status = ? THEN 1 ELSE 0 END) AS processing_count, + SUM(CASE WHEN status = ? THEN 1 ELSE 0 END) AS uncertain_count + FROM invitecode_reward_actions + """.trimIndent(), + ).use { statement -> + statement.setString(1, RewardActionStatus.PENDING.name) + statement.setString(2, RewardActionStatus.PROCESSING.name) + statement.setString(3, RewardActionStatus.UNCERTAIN.name) + statement.executeQuery().use { result -> + check(result.next()) { "Reward backlog count query returned no row." } + RewardBacklogCounts( + pending = result.getInt("pending_count"), + processing = result.getInt("processing_count"), + uncertain = result.getInt("uncertain_count"), ) } } @@ -309,4 +339,14 @@ internal object SqliteRewardRecords { updatedAt = Instant.parse(getString("updated_at")), lastError = getString("last_error"), ) + + private fun java.sql.ResultSet.toRewardDelivery() = StoredRewardDelivery( + id = UUID.fromString(getString("delivery_id")), + invitationId = getString("invitation_id")?.let(UUID::fromString), + rewardId = getString("reward_id"), + status = RewardDeliveryStatus.valueOf(getString("status")), + idempotencyKey = getString("idempotency_key"), + createdAt = Instant.parse(getString("created_at")), + updatedAt = Instant.parse(getString("updated_at")), + ) } diff --git a/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqliteSchemaMigrator.kt b/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqliteSchemaMigrator.kt index a9c8e3b..0bce13a 100644 --- a/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqliteSchemaMigrator.kt +++ b/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqliteSchemaMigrator.kt @@ -3,8 +3,11 @@ package io.github.command1264.invitecode.storage.sql import java.nio.file.Files import java.nio.file.Path import java.sql.Connection -import java.sql.DriverManager +import java.sql.Driver import java.sql.SQLException +import java.net.URL +import java.net.URLClassLoader +import java.util.Properties /** 在任何 SQLite I/O 前確認目前 thread 允許執行 blocking operation。 */ fun interface BlockingOperationGuard { @@ -76,7 +79,7 @@ class SqliteSchemaMigrator( if (current > ordered.size) { throw SqliteStorageException( "SQLite schema version $current is newer than supported version ${ordered.size}; " + - "upgrade InviteCodeKt before opening ${database.toAbsolutePath()}.", + "upgrade InviteCode before opening ${database.toAbsolutePath()}.", ) } ordered.filter { it.version > current }.forEach { migration -> @@ -312,6 +315,92 @@ class SqliteSchemaMigrator( """.trimIndent(), ), ), + SqliteSchemaMigration( + version = 6, + description = "Add Bukkit workflow query indexes", + statements = listOf( + """ + CREATE INDEX invitecode_query_players_by_name + ON invitecode_players(last_known_name COLLATE NOCASE, player_id) + WHERE last_known_name IS NOT NULL + """.trimIndent(), + """ + CREATE INDEX invitecode_query_codes_active_reverse + ON invitecode_codes(code, inviter_id) + WHERE retired_at IS NULL + """.trimIndent(), + """ + CREATE INDEX invitecode_query_invitations_by_invitee + ON invitecode_invitations(invitee_id, claimed_at DESC, invitation_id DESC) + """.trimIndent(), + """ + CREATE INDEX invitecode_query_invitations_by_inviter + ON invitecode_invitations(inviter_id, claimed_at DESC, invitation_id DESC, status) + """.trimIndent(), + """ + CREATE INDEX invitecode_query_qualification_facts + ON invitecode_qualification_facts(invitation_id, recorded_at, fact_id) + """.trimIndent(), + """ + CREATE INDEX invitecode_query_audit_by_invitation + ON invitecode_audit_records(invitation_id, occurred_at DESC, audit_id DESC) + WHERE invitation_id IS NOT NULL + """.trimIndent(), + """ + CREATE INDEX invitecode_query_audit_by_player + ON invitecode_audit_records(player_id, occurred_at DESC, audit_id DESC) + WHERE player_id IS NOT NULL + """.trimIndent(), + """ + CREATE INDEX invitecode_query_reward_deliveries_by_invitation + ON invitecode_reward_deliveries(invitation_id, created_at DESC, delivery_id DESC) + WHERE invitation_id IS NOT NULL + """.trimIndent(), + """ + CREATE INDEX invitecode_query_reward_actions_by_status + ON invitecode_reward_actions(status) + """.trimIndent(), + ), + ), + SqliteSchemaMigration( + version = 7, + description = "Persist unique player login days for Qualification", + statements = listOf( + """ + CREATE TABLE invitecode_player_login_days ( + player_id TEXT NOT NULL, + login_date TEXT NOT NULL, + PRIMARY KEY (player_id, login_date), + FOREIGN KEY (player_id) REFERENCES invitecode_players(player_id) + ) + """.trimIndent(), + ), + ), + SqliteSchemaMigration( + version = 8, + description = "Persist expiring keyed network hashes for Claim anti-abuse", + statements = listOf( + """ + CREATE TABLE invitecode_player_network_hashes ( + player_id TEXT NOT NULL, + key_id TEXT NOT NULL CHECK (length(key_id) = 64), + network_hash TEXT NOT NULL CHECK (length(network_hash) = 64), + observed_at TEXT NOT NULL, + expires_at TEXT NOT NULL, + PRIMARY KEY (player_id, key_id, network_hash), + FOREIGN KEY (player_id) REFERENCES invitecode_players(player_id) + ) + """.trimIndent(), + """ + CREATE INDEX invitecode_network_hash_expiry + ON invitecode_player_network_hashes(expires_at) + """.trimIndent(), + """ + CREATE INDEX invitecode_network_hash_match + ON invitecode_player_network_hashes(key_id, network_hash, player_id, expires_at) + """.trimIndent(), + ), + ), ) val currentVersion: Int @@ -319,8 +408,47 @@ class SqliteSchemaMigrator( } } -internal fun connect(database: Path): Connection = - DriverManager.getConnection("jdbc:sqlite:${database.toAbsolutePath()}") +private class BundledSqliteClassLoader( + location: URL, + parent: ClassLoader, +) : URLClassLoader(arrayOf(location), parent) { + override fun getResource(name: String): URL? = + if (name.startsWith("org/sqlite/")) findResource(name) ?: super.getResource(name) + else super.getResource(name) + + override fun loadClass(name: String, resolve: Boolean): Class<*> { + if (!name.startsWith("org.sqlite.")) return super.loadClass(name, resolve) + synchronized(getClassLoadingLock(name)) { + val loaded = findLoadedClass(name) ?: findClass(name) + if (resolve) resolveClass(loaded) + return loaded + } + } +} + +private val sqliteDriver: Driver by lazy(LazyThreadSafetyMode.SYNCHRONIZED) { + val owner = SqliteSchemaMigrator::class.java + val location = requireNotNull(owner.protectionDomain.codeSource?.location) { + "Unable to locate the InviteCode code source for the bundled SQLite driver." + } + try { + BundledSqliteClassLoader(location, owner.classLoader) + .loadClass("org.sqlite.JDBC") + .getDeclaredConstructor() + .newInstance() as Driver + } catch (missingBundledDriver: ClassNotFoundException) { + // Module tests run from class directories, where Gradle supplies SQLite on the parent classpath. + Class.forName("org.sqlite.JDBC", true, owner.classLoader) + .getDeclaredConstructor() + .newInstance() as Driver + } +} + +internal fun connect(database: Path): Connection { + val url = "jdbc:sqlite:${database.toAbsolutePath()}" + return sqliteDriver.connect(url, Properties()) + ?: throw SQLException("The bundled SQLite driver did not accept $url") +} internal fun readSchemaVersion(connection: Connection): Int = connection.createStatement().use { statement -> diff --git a/invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/SqliteInviteCodeStorageTest.kt b/invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/SqliteInviteCodeStorageTest.kt index cd3b495..df791bc 100644 --- a/invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/SqliteInviteCodeStorageTest.kt +++ b/invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/SqliteInviteCodeStorageTest.kt @@ -13,9 +13,12 @@ import io.github.command1264.invitecode.core.AuditRecord import io.github.command1264.invitecode.core.AuditedInvitationTransition import io.github.command1264.invitecode.core.InvitationAdministrationContext import io.github.command1264.invitecode.core.PlayerClaimState +import io.github.command1264.invitecode.core.PlayerNetworkHash +import io.github.command1264.invitecode.core.MatchingNetworkAction import io.github.command1264.invitecode.core.Invitation import io.github.command1264.invitecode.core.InvitationAuditAction import io.github.command1264.invitecode.core.InvitationAuditDetails +import io.github.command1264.invitecode.core.InviterInvitationStats import io.github.command1264.invitecode.core.QualificationFact import io.github.command1264.invitecode.core.QualificationFactOutcome import io.github.command1264.invitecode.core.RewardActionStatus @@ -23,6 +26,11 @@ import io.github.command1264.invitecode.core.StoredRewardAction import io.github.command1264.invitecode.core.StoredRewardDelivery import io.github.command1264.invitecode.core.RewardDeliveryStatus import io.github.command1264.invitecode.core.RewardAdministrationContext +import io.github.command1264.invitecode.core.RewardBacklogCounts +import io.github.command1264.invitecode.core.QualificationRewardDefinition +import io.github.command1264.invitecode.core.RewardActionDefinition +import io.github.command1264.invitecode.core.RewardActionType +import io.github.command1264.invitecode.core.RewardDeliveryPlanner import io.github.command1264.invitecode.core.UncertainRewardActionResolution import io.github.command1264.invitecode.api.InvitationStatus import org.junit.jupiter.api.Assertions.assertEquals @@ -38,6 +46,7 @@ import java.sql.Connection import java.sql.SQLException import java.sql.Statement import java.time.Instant +import java.time.LocalDate import java.time.Duration import java.util.UUID import java.util.concurrent.CountDownLatch @@ -87,6 +96,101 @@ class SqliteInviteCodeStorageTest { } } + @Test + fun `login days count unique calendar dates`() { + val database = temporaryDirectory.resolve("login-days.db") + val guard = BlockingOperationGuard { } + val player = StoredPlayer(UUID.randomUUID(), Instant.EPOCH, "Player") + SqliteSchemaMigrator(database, guard).migrate() + + SqliteInviteCodeStorage.open(database, guard).use { storage -> + storage.savePlayer(player) + storage.recordLoginDay(player.id, LocalDate.parse("2026-09-21")) + storage.recordLoginDay(player.id, LocalDate.parse("2026-09-21")) + storage.recordLoginDay(player.id, LocalDate.parse("2026-09-22")) + + assertEquals(2, storage.loginDays(player.id)) + } + } + + @Test + fun `assigning an Invite Code makes the player an Inviter immediately`() { + val database = temporaryDirectory.resolve("inviter-role.db") + val guard = BlockingOperationGuard { } + val player = StoredPlayer(UUID.randomUUID(), Instant.EPOCH, "Inviter") + SqliteSchemaMigrator(database, guard).migrate() + + SqliteInviteCodeStorage.open(database, guard).use { storage -> + storage.savePlayer(player) + InviteCodeLifecycleService(storage, InviteCodeGenerator { + InviteCode.parse("ABCDEF", InviteCodeFormats.colorHex) + }, 1).assign(player.id, Instant.EPOCH) + + assertEquals(true, storage.claimState(player.id).isInviter) + } + } + + @Test + fun `qualification and reward plans commit atomically`() { + val database = temporaryDirectory.resolve("qualification-rewards.db") + val guard = BlockingOperationGuard { } + val inviter = StoredPlayer(UUID.randomUUID(), Instant.EPOCH, "Inviter") + val invitee = StoredPlayer(UUID.randomUUID(), Instant.EPOCH, "Invitee") + val claimed = Invitation(UUID.randomUUID(), inviter.id, invitee.id, InvitationStatus.CLAIMED, Instant.EPOCH) + val qualified = claimed.qualify(Instant.EPOCH.plusSeconds(1), "new-player", "revision") + val fact = QualificationFact( + UUID.randomUUID(), claimed.id, "new-player", "revision", "play-time", + QualificationFactOutcome.SATISFIED, Instant.EPOCH.plusSeconds(1), + ) + val plan = RewardDeliveryPlanner.planQualification( + QualificationRewardDefinition( + "default", + listOf(RewardActionDefinition(RewardActionType.MESSAGE, "invite.qualified.inviter")), + emptyList(), + ), + qualified, + ) + SqliteSchemaMigrator(database, guard).migrate() + + SqliteInviteCodeStorage.open(database, guard).use { storage -> + storage.savePlayer(inviter) + storage.savePlayer(invitee) + storage.saveInvitation(claimed) + storage.saveQualifiedInvitationWithRewards(qualified, listOf(fact), listOf(plan)) + + assertEquals(InvitationStatus.QUALIFIED, storage.invitation(claimed.id)?.status) + assertEquals(listOf(fact), storage.qualificationFacts(claimed.id)) + assertEquals(plan.delivery, storage.rewardDelivery(plan.delivery.id)) + assertEquals(plan.actions, storage.rewardActions(plan.delivery.id)) + } + } + + @Test + fun `atomic qualification rejects facts from another policy revision`() { + val database = temporaryDirectory.resolve("qualification-fact-mismatch.db") + val guard = BlockingOperationGuard { } + val inviter = StoredPlayer(UUID.randomUUID(), Instant.EPOCH) + val invitee = StoredPlayer(UUID.randomUUID(), Instant.EPOCH) + val claimed = Invitation(UUID.randomUUID(), inviter.id, invitee.id, InvitationStatus.CLAIMED, Instant.EPOCH) + val qualified = claimed.qualify(Instant.EPOCH.plusSeconds(1), "policy", "revision") + val mismatched = QualificationFact( + UUID.randomUUID(), claimed.id, "other-policy", "revision", "condition", + QualificationFactOutcome.SATISFIED, Instant.EPOCH.plusSeconds(1), + ) + SqliteSchemaMigrator(database, guard).migrate() + + SqliteInviteCodeStorage.open(database, guard).use { storage -> + storage.savePlayer(inviter) + storage.savePlayer(invitee) + storage.saveInvitation(claimed) + + assertThrows { + storage.saveQualifiedInvitationWithRewards(qualified, listOf(mismatched), emptyList()) + } + assertEquals(InvitationStatus.CLAIMED, storage.invitation(claimed.id)?.status) + } + } + @Test fun `thread guard rejects migration before database IO begins`() { val database = temporaryDirectory.resolve("main-thread.db") @@ -295,6 +399,102 @@ class SqliteInviteCodeStorageTest { } } + @Test + fun `retained matching network hashes deny Claim and expired hashes are purged`() { + val database = temporaryDirectory.resolve("network-hashes.db") + val guard = BlockingOperationGuard { } + val inviterId = UUID.fromString("00000000-0000-0000-0000-000000000005") + val inviteeId = UUID.fromString("00000000-0000-0000-0000-000000000006") + val invitationId = UUID.fromString("10000000-0000-0000-0000-000000000006") + val observedAt = Instant.parse("2026-09-22T00:00:00Z") + val confirmedAt = observedAt.plusSeconds(60) + val expiresAt = observedAt.plus(Duration.ofDays(30)) + val code = InviteCode.parse("A25981", InviteCodeFormats.colorHex) + val hash = "a".repeat(64) + val keyId = "b".repeat(64) + SqliteSchemaMigrator(database, guard).migrate() + + SqliteInviteCodeStorage.open(database, guard).use { storage -> + storage.savePlayer(StoredPlayer(inviterId, observedAt, "Inviter")) + storage.savePlayer(StoredPlayer(inviteeId, observedAt, "Invitee")) + InviteCodeLifecycleService(storage, InviteCodeGenerator { code }, 1).assign(inviterId, observedAt) + storage.recordNetworkHash( + PlayerNetworkHash(inviterId, "c".repeat(64), "d".repeat(64), observedAt, expiresAt), + ) + assertEquals(1, storage.purgeNetworkHashesWithDifferentKey(keyId)) + storage.recordNetworkHash(PlayerNetworkHash(inviterId, keyId, hash, observedAt, expiresAt)) + storage.recordNetworkHash(PlayerNetworkHash(inviteeId, keyId, hash, observedAt, expiresAt)) + val confirmation = ClaimConfirmation.present( + inviteeId, + inviterId, + "Inviter", + code, + observedAt, + Duration.ofMinutes(2), + ).confirm(inviteeId, confirmedAt) + + val result = InvitationClaimService( + storage, + ClaimEligibilityPolicy(Duration.ofHours(24)), + { invitationId }, + MatchingNetworkAction.DENY, + ).claim(confirmation) + + assertEquals(true, result is InvitationClaimResult.MatchingNetworkDenied) + assertEquals(emptyList(), storage.invitationsByInvitee(inviteeId)) + assertEquals(2, storage.purgeExpiredNetworkHashes(expiresAt)) + val stillMatches = storage.atomically(setOf(inviterId, inviteeId)) { + it.hasMatchingNetworkHash(inviterId, inviteeId, expiresAt) + } + assertEquals(false, stillMatches) + } + } + + @Test + fun `audited code rotation rolls back when the audit record cannot be saved`() { + val database = temporaryDirectory.resolve("audited-rotation-rollback.db") + val offMainThread = BlockingOperationGuard { } + val inviterId = UUID.fromString("00000000-0000-0000-0000-000000000004") + val initial = InviteCode.parse("A25981", InviteCodeFormats.colorHex) + val replacement = InviteCode.parse("0B35E7", InviteCodeFormats.colorHex) + val rotatedAt = Instant.parse("2026-09-22T02:00:00Z") + val auditId = UUID.fromString("40000000-0000-0000-0000-000000000004") + SqliteSchemaMigrator(database, offMainThread).migrate() + SqliteInviteCodeStorage.open(database, offMainThread).use { storage -> + storage.savePlayer(StoredPlayer(inviterId, Instant.parse("2026-09-22T00:00:00Z"))) + InviteCodeLifecycleService(storage, InviteCodeGenerator { initial }, 1) + .assign(inviterId, Instant.parse("2026-09-22T01:00:00Z")) + storage.saveAuditRecord( + AuditRecord( + auditId, + InvitationAuditAction.CODE_ROTATED, + "operator", + "existing record", + rotatedAt, + playerId = inviterId, + ), + ) + + assertThrows { + InviteCodeLifecycleService(storage, InviteCodeGenerator { replacement }, 1).rotate( + inviterId, + rotatedAt, + AuditRecord( + auditId, + InvitationAuditAction.CODE_ROTATED, + "operator", + "rotate code", + rotatedAt, + playerId = inviterId, + ), + ) + } + + assertEquals(initial, storage.activeInviteCode(inviterId)!!.code) + assertEquals(false, storage.isInviteCodeReserved(replacement)) + } + } + @Test fun `concurrent claims persist exactly one invitation for an invitee`() { val database = temporaryDirectory.resolve("claims.db") @@ -309,6 +509,14 @@ class SqliteInviteCodeStorageTest { listOf(firstInviter, secondInviter, invitee).forEach { playerId -> storage.savePlayer(StoredPlayer(playerId, firstSeenAt)) } + val inviteCodes = mapOf( + firstInviter to InviteCode.parse("A25981", InviteCodeFormats.colorHex), + secondInviter to InviteCode.parse("0B35E7", InviteCodeFormats.colorHex), + ) + inviteCodes.forEach { (inviterId, inviteCode) -> + InviteCodeLifecycleService(storage, InviteCodeGenerator { inviteCode }, 1) + .assign(inviterId, firstSeenAt) + } val service = InvitationClaimService( transactions = storage, eligibilityPolicy = ClaimEligibilityPolicy(Duration.ofHours(24)), @@ -327,7 +535,7 @@ class SqliteInviteCodeStorageTest { inviteeId = invitee, inviterId = inviterId, inviterName = "Inviter", - inviteCode = InviteCode.parse("A25981"), + inviteCode = inviteCodes.getValue(inviterId), presentedAt = firstSeenAt.plusSeconds(30), validity = Duration.ofSeconds(30), ).confirm(invitee, firstSeenAt.plusSeconds(60)), @@ -634,6 +842,11 @@ class SqliteInviteCodeStorageTest { .adminResetEligibility(context) storage.saveAuditedClaimStateTransition(reset) + InviteCodeLifecycleService( + storage, + InviteCodeGenerator { InviteCode.parse("A25981", InviteCodeFormats.colorHex) }, + 1, + ).assign(newInviter, resetAt) assertEquals(resetAt, storage.player(invitee)!!.firstSeenAt) assertEquals(reset.auditRecord, storage.auditRecord(context.auditRecordId)) @@ -1101,4 +1314,202 @@ class SqliteInviteCodeStorageTest { delegate.close() } } + + @Test + fun `player lookup claim state and active Invite Code reverse lookup support workflows`() { + val database = temporaryDirectory.resolve("workflow-player-lookups.db") + val guard = BlockingOperationGuard { } + val first = StoredPlayer(UUID.fromString("00000000-0000-0000-0000-000000000201"), Instant.EPOCH, "SameName") + val second = StoredPlayer(UUID.fromString("00000000-0000-0000-0000-000000000202"), Instant.EPOCH, "samename") + val initial = InviteCode.parse("A25981", InviteCodeFormats.colorHex) + val replacement = InviteCode.parse("0B35E7", InviteCodeFormats.colorHex) + SqliteSchemaMigrator(database, guard).migrate() + + SqliteInviteCodeStorage.open(database, guard).use { storage -> + storage.savePlayer(first) + storage.savePlayer(second) + storage.savePlayer(first.copy(lastKnownName = null)) + assertEquals("SameName", storage.player(first.id)!!.lastKnownName) + assertEquals(listOf(first, second), storage.playersByLastKnownName("SAMENAME")) + assertEquals(PlayerClaimState(first.id, Instant.EPOCH, false, false), storage.claimState(first.id)) + + val lifecycle = InviteCodeLifecycleService(storage, InviteCodeGenerator { initial }, 1) + lifecycle.assign(first.id, Instant.EPOCH) + InviteCodeLifecycleService(storage, InviteCodeGenerator { replacement }, 1) + .rotate(first.id, Instant.EPOCH.plusSeconds(1)) + + assertNull(storage.activeInviteCode(initial)) + assertEquals(first.id, storage.activeInviteCode(replacement)!!.inviterId) + assertEquals( + first.id, + storage.atomically(setOf(first.id)) { it.activeInviter(replacement) }, + ) + } + } + + @Test + fun `Invitation queries cover every Invitee generation and current Inviter stats`() { + val database = temporaryDirectory.resolve("workflow-invitation-queries.db") + val guard = BlockingOperationGuard { } + val inviter = UUID.fromString("00000000-0000-0000-0000-000000000211") + val invitee = UUID.fromString("00000000-0000-0000-0000-000000000212") + val first = Invitation( + UUID.fromString("10000000-0000-0000-0000-000000000211"), inviter, invitee, + InvitationStatus.CLAIMED, Instant.EPOCH, + ) + val second = Invitation( + UUID.fromString("10000000-0000-0000-0000-000000000212"), inviter, invitee, + InvitationStatus.CLAIMED, Instant.EPOCH.plusSeconds(2), + ) + val fact = QualificationFact( + UUID.fromString("20000000-0000-0000-0000-000000000211"), second.id, + "default", "revision-1", "play-time", QualificationFactOutcome.SATISFIED, + Instant.EPOCH.plusSeconds(3), + ) + SqliteSchemaMigrator(database, guard).migrate() + + SqliteInviteCodeStorage.open(database, guard).use { storage -> + storage.savePlayer(StoredPlayer(inviter, Instant.EPOCH)) + storage.savePlayer(StoredPlayer(invitee, Instant.EPOCH)) + storage.saveInvitation(first) + storage.saveAuditedClaimStateTransition( + storage.claimState(invitee).adminResetEligibility( + InvitationAdministrationContext( + UUID.fromString("40000000-0000-0000-0000-000000000211"), + "console", "new generation", Instant.EPOCH.plusSeconds(1), + ), + ), + ) + storage.saveInvitation(second) + val qualified = second.qualify(Instant.EPOCH.plusSeconds(3), "default", "revision-1") + storage.saveQualifiedInvitation(qualified, listOf(fact)) + + assertEquals(listOf(qualified, first), storage.invitationsByInvitee(invitee)) + assertEquals(listOf(qualified, first), storage.invitationsByInviter(inviter)) + assertEquals(InviterInvitationStats(claimed = 1, qualified = 1), storage.inviterInvitationStats(inviter)) + assertEquals(listOf(fact), storage.qualificationFacts(second.id)) + } + } + + @Test + fun `Audit history validates limits and has deterministic newest-first ordering`() { + val database = temporaryDirectory.resolve("workflow-audit-history.db") + val guard = BlockingOperationGuard { } + val inviter = UUID.fromString("00000000-0000-0000-0000-000000000221") + val invitee = UUID.fromString("00000000-0000-0000-0000-000000000222") + val invitation = Invitation( + UUID.fromString("10000000-0000-0000-0000-000000000221"), inviter, invitee, + InvitationStatus.CLAIMED, Instant.EPOCH, + ) + val older = AuditRecord( + UUID.fromString("40000000-0000-0000-0000-000000000221"), InvitationAuditAction.UNLINKED, + "console", "older", Instant.EPOCH.plusSeconds(1), invitationId = invitation.id, + ) + val sameTimeLowerId = older.copy( + id = UUID.fromString("40000000-0000-0000-0000-000000000222"), reason = "lower", + occurredAt = Instant.EPOCH.plusSeconds(2), + ) + val sameTimeHigherId = sameTimeLowerId.copy( + id = UUID.fromString("40000000-0000-0000-0000-000000000223"), reason = "higher", + ) + val playerRecord = AuditRecord( + UUID.fromString("40000000-0000-0000-0000-000000000224"), InvitationAuditAction.ELIGIBILITY_RESET, + "console", "player", Instant.EPOCH.plusSeconds(3), playerId = invitee, + ) + SqliteSchemaMigrator(database, guard).migrate() + + SqliteInviteCodeStorage.open(database, guard).use { storage -> + storage.savePlayer(StoredPlayer(inviter, Instant.EPOCH)) + storage.savePlayer(StoredPlayer(invitee, Instant.EPOCH)) + storage.saveInvitation(invitation) + listOf(older, sameTimeLowerId, sameTimeHigherId, playerRecord).forEach(storage::saveAuditRecord) + + assertEquals(listOf(sameTimeHigherId, sameTimeLowerId), storage.auditHistoryByInvitation(invitation.id, 2)) + assertEquals(listOf(playerRecord), storage.auditHistoryByPlayer(invitee, 10)) + assertThrows { storage.auditHistoryByInvitation(invitation.id, 0) } + assertThrows { storage.auditHistoryByPlayer(invitee, 101) } + } + } + + @Test + fun `Reward queries expose Invitation deliveries and global Action backlog counts`() { + val database = temporaryDirectory.resolve("workflow-reward-queries.db") + val guard = BlockingOperationGuard { } + val inviter = UUID.fromString("00000000-0000-0000-0000-000000000231") + val invitee = UUID.fromString("00000000-0000-0000-0000-000000000232") + val invitation = Invitation( + UUID.fromString("10000000-0000-0000-0000-000000000231"), inviter, invitee, + InvitationStatus.CLAIMED, Instant.EPOCH, + ) + SqliteSchemaMigrator(database, guard).migrate() + + SqliteInviteCodeStorage.open(database, guard).use { storage -> + storage.savePlayer(StoredPlayer(inviter, Instant.EPOCH)) + storage.savePlayer(StoredPlayer(invitee, Instant.EPOCH)) + storage.saveInvitation(invitation) + val aggregates = (1..3).map { offset -> + val delivery = StoredRewardDelivery( + UUID(0x3100000000000000L, offset.toLong()), invitation.id, "reward-$offset", + RewardDeliveryStatus.PENDING, "delivery-$offset", Instant.EPOCH.plusSeconds(offset.toLong()), + Instant.EPOCH.plusSeconds(offset.toLong()), + ) + val action = StoredRewardAction( + UUID(0x3000000000000000L, offset.toLong()), delivery.id, invitation.id, inviter, 0, + "message", "reward-$offset", RewardActionStatus.PENDING, "action-$offset", + delivery.createdAt, delivery.updatedAt, + ) + storage.saveRewardDelivery(delivery, listOf(action)) + delivery to action + } + val processingAt = Instant.EPOCH.plusSeconds(10) + storage.saveRewardAction(aggregates[0].second.copy(status = RewardActionStatus.PROCESSING, updatedAt = processingAt)) + storage.recoverInterruptedRewardActions(processingAt.plusSeconds(1)) + storage.saveRewardAction(aggregates[1].second.copy(status = RewardActionStatus.PROCESSING, updatedAt = processingAt.plusSeconds(2))) + + assertEquals( + aggregates.map { it.first.id }.reversed(), + storage.rewardDeliveries(invitation.id).map { it.id }, + ) + assertEquals(RewardBacklogCounts(pending = 1, processing = 1, uncertain = 1), storage.rewardBacklogCounts()) + } + } + + @Test + fun `version five migrates through workflow schemas without making player names unique`() { + val database = temporaryDirectory.resolve("workflow-v5-to-v6.db") + val guard = BlockingOperationGuard { } + SqliteSchemaMigrator(database, guard, SqliteSchemaMigrator.DEFAULT_MIGRATIONS.take(5)).migrate() + + assertEquals(SqliteSchemaMigrator.currentVersion, SqliteSchemaMigrator(database, guard).migrate()) + connect(database).use { connection -> + val indexes = connection.prepareStatement( + "SELECT name FROM sqlite_master WHERE type = 'index' AND name LIKE 'invitecode_query_%' ORDER BY name", + ).use { statement -> + statement.executeQuery().use { result -> + buildList { while (result.next()) add(result.getString(1)) } + } + } + assertEquals( + listOf( + "invitecode_query_audit_by_invitation", + "invitecode_query_audit_by_player", + "invitecode_query_codes_active_reverse", + "invitecode_query_invitations_by_invitee", + "invitecode_query_invitations_by_inviter", + "invitecode_query_players_by_name", + "invitecode_query_qualification_facts", + "invitecode_query_reward_actions_by_status", + "invitecode_query_reward_deliveries_by_invitation", + ), + indexes, + ) + } + SqliteInviteCodeStorage.open(database, guard).use { storage -> + val first = StoredPlayer(UUID.fromString("00000000-0000-0000-0000-000000000241"), Instant.EPOCH, "Duplicate") + val second = StoredPlayer(UUID.fromString("00000000-0000-0000-0000-000000000242"), Instant.EPOCH, "duplicate") + storage.savePlayer(first) + storage.savePlayer(second) + assertEquals(listOf(first, second), storage.playersByLastKnownName("DUPLICATE")) + } + } }