diff --git a/README.md b/README.md index 376ee00..04e41ef 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ InviteCode is a Kotlin invitation and referral rewards plugin for Spigot and Pap The project is currently `0.1.0-SNAPSHOT`. It builds one Java 8 compatible plugin JAR and keeps newer Minecraft APIs behind isolated adapters. SQLite and MySQL 8.4 are production storage backends; JSON is available for small single-instance installations. Cross-version, storage recovery, and optional integration checks are recorded in the [integrated artifact retest](docs/testing/evidence/2026-10-02-issue-12-final-artifact-retest.md). Folia remains experimental; automated checks and player acceptance are tracked separately. -The complete maintainer guide is in [繁體中文](docs/README.zh-TW.md) and is the primary maintained documentation. See also the [product specification](docs/spec/invitecode-1.0.md), [Bukkit operations](docs/operations/bukkit-workflow.md), [JSON setup](docs/operations/json-storage.md), [MySQL setup](docs/operations/mysql-storage.md), and [offline anonymization](docs/operations/offline-anonymization.md). These documents are maintained in Traditional Chinese. +The complete maintainer guide is in [繁體中文](docs/README.zh-TW.md) and is the primary maintained documentation. See also the [product specification](docs/spec/invitecode-1.0.md), [Bukkit operations](docs/operations/bukkit-workflow.md), [JSON setup](docs/operations/json-storage.md), [MySQL setup](docs/operations/mysql-storage.md), [offline anonymization](docs/operations/offline-anonymization.md), and [cross-backend transfer](docs/operations/cross-backend-transfer.md). These documents are maintained in Traditional Chinese. ## Build diff --git a/docs/README.zh-TW.md b/docs/README.zh-TW.md index 75df212..75cac67 100644 --- a/docs/README.zh-TW.md +++ b/docs/README.zh-TW.md @@ -74,6 +74,8 @@ Claim 防濫用只保存具期限的 HMAC-SHA-256 網路雜湊,不保存原始 玩家資料匿名化須在所有實例停止後,透過獨立維護工具預覽、備份並執行;它保留歷史關係,但同一 Minecraft UUID 再登入會視為新玩家。SQLite schema 9、MySQL schema 2 及 JSON snapshot schema 9 的既有資料升級方式與完整驗證步驟見 [`offline-anonymization.md`](./operations/offline-anonymization.md)。 +SQLite、JSON 與 MySQL 之間的資料搬移須使用[離線跨 backend 搬移工具](./operations/cross-backend-transfer.md),先停寫、核對相同防濫用密鑰與空白目的地,完成備份、全表驗證後才切換 `storage.yml`;一般啟動與 reload 不會自動搬移資料。 + ## Qualification Policy `QualificationPolicy` 使用 OR group 包含 AND condition;每次解析都會依正規化內容產生不可變的 SHA-256 revision。`QualificationEvaluator` 對 condition 依序短路求值,provider 缺失或執行失敗時安全地產生 `UNKNOWN`/設定的 `UNSATISFIED`,不會因此讓 Invitation qualified。 diff --git a/docs/adr/0006-offline-cross-backend-transfer.md b/docs/adr/0006-offline-cross-backend-transfer.md new file mode 100644 index 0000000..cb02413 --- /dev/null +++ b/docs/adr/0006-offline-cross-backend-transfer.md @@ -0,0 +1,15 @@ +# 跨 backend 搬移採離線、驗證後發布 + +狀態:已接受(2026-09-28,Issue #26) + +SQLite、JSON、MySQL 的 schema 升級只處理原 backend;變更 `storage.yml` 不會搬走既有玩家、Invitation、Reward 或稽核資料。為避免兩端分歧,跨 backend 搬移只透過獨立 CLI 執行,來源與目的地的所有 InviteCode 實例須先停止,不在插件啟動、reload 或遊戲指令中隱式搬移。 + +三種 backend 的六個不同方向都使用相同的持久化業務表白名單。匯出包含玩家、碼、邀請、資格事實、Reward Delivery 與 Action、狀態轉換、稽核、登入日期、網路 hash 及已匿名化舊碼的保留 hash;schema 與 migration ledger 由目的 backend 自行建立,不從來源複製。MySQL generated columns 由目的資料庫重建。匯入前須檢查來源版本、目的地完全空白及兩端防濫用密鑰識別碼相同;不提供自動重算網路 hash 或舊碼保留 hash 的密鑰輪替。來源始終保留,不因目的地驗證成功而刪除。 + +SQLite 目的地先在同資料夾建立暫存資料庫;JSON 目的地先建立暫存 SQLite 工作資料庫及暫存快照。全表資料、外鍵與關鍵唯一性檢查成功,並確認來源未變後,才以同目錄的硬連結建立正式檔;若目的檔已存在,建立會失敗而不覆寫,檔案系統不支援硬連結時安全失敗。MySQL 目的地必須是空白 database;搬移先建立 `invitecode_transfer_guard`,再初始化 schema、匯入及驗證。插件啟動與搬移會以同一把 database 級 advisory lock 序列化,偵測 guard 即拒絕啟用。MySQL DDL 無法交易回滾;失敗或中斷後目的 database 須保留供檢查,不能當成空白重試,須用備份或全新 database 重新開始。完成驗證才移除 guard。 + +CLI 要求操作者確認停寫,並在正式搬移前提供來源備份。SQLite/JSON 由工具建立並核對 SHA-256;MySQL 要求已建立的一致性 dump,工具只能確認檔案存在且非空,實際可還原性由操作者驗證。MySQL 還需專用帳號與 database,預檢拒絕同 database 的其他可見連線;其他帳號的不可見工作階段及檢查後新連入者仍須由維運流程停機保證。目的地完成後,由管理員單獨更新 `storage.yml`,確認只啟動指向目的地的一組實例。來源與備份保留作為回復基線;切回來源前先停止目的地寫入,評估切換後新增資料,不自動雙向同步。 + +真人遊戲內驗收依 Issue #12 延後;隔離資料庫測試不得連到正式資料庫。 + +來源匯出完成前也須通過唯讀完整性預檢;不可只依目的地外鍵在正式匯入時拒絕。SQLite 使用 `integrity_check` 與 `foreign_key_check`,包含曾停用 CHECK/外鍵後留下的違規資料;MySQL 依目前 schema 的外鍵 metadata 對業務表查找孤立紀錄,因重新啟用 `FOREIGN_KEY_CHECKS` 不會回頭驗證既有資料。SQL 識別符僅允許業務表與欄位白名單,不輸出玩家紀錄。匯出快照同時核對格式、欄位型別、nullability 及密鑰;預檢失敗不得建立備份或發布目的地。 diff --git a/docs/operations/cross-backend-transfer.md b/docs/operations/cross-backend-transfer.md new file mode 100644 index 0000000..231ad9f --- /dev/null +++ b/docs/operations/cross-backend-transfer.md @@ -0,0 +1,50 @@ +# 離線跨 backend 資料搬移 + +本工具支援 SQLite、JSON、MySQL 之間六個不同方向。它搬移完整 InviteCode 持久化資料,驗證後才發布目的地,不改寫來源,也不修改 `storage.yml`。`--stopped` 是操作者對停機狀態的確認;CLI 無法證明所有使用其他 MySQL 帳號的寫入者都已停止。 + +## 執行順序 + +1. 停止**所有**使用來源與目的 backend 的 InviteCode 實例及其他維護程序。MySQL 需專用 database 與帳號;目的 database 必須完全空白。SQLite/JSON 目的檔必須不存在。確認沒有 SQLite `-wal`/`-shm` 留存;不要直接刪除仍可能含有資料的檔案。 +2. 確認來源版本為 SQLite schema 9、JSON snapshot schema 9 或 MySQL schema 2。舊版本先依既有離線 schema 升級流程升級。事先準備**相同的 32-byte anti-abuse 密鑰**:SQLite/JSON 的 `--from-secret-file`、`--to-secret-file` 指向已存在的二進位密鑰檔;MySQL 的 Base64 密鑰從 `--mysql-secret-env` 指定的環境變數取得。不要重新產生密鑰;否則 IP hash 與已匿名化邀請碼的保留值會失效。 +3. 備份原始設定及密鑰。若來源是 MySQL,另以一致性方式完成可還原的 database dump;`--backup` 指向該 dump。若來源是 SQLite/JSON,`--backup` 指向尚不存在的檔案,工具在正式搬移時複製並核對 SHA-256。MySQL dump 的內容與可還原性須由管理員自行確認,工具只檢查非空。 +4. 先執行不加 `--apply` 的預檢,確認來源完整性、每張表的資料筆數、版本、目的地空白及密鑰一致;再加 `--apply --backup <路徑>` 正式執行。SQLite 預檢包含 CHECK/外鍵與檔案完整性,MySQL 包含既有孤立紀錄檢查;曾停用外鍵檢查的來源不會只因重新啟用外鍵而視為完整。若回報 `Source integrity check failed` 或 `Source foreign-key integrity check failed`,保持停機,先在經驗證的備份上調查或還原缺失資料;工具不會自動修補或刪除來源。過程中不得重啟任何實例。CLI 回報成功後,檢查目的地資料、Reward 未完成狀態、舊碼保留值及稽核,再把 `plugins/InviteCode/storage.yml` 只改為目的 backend,啟動一組伺服器並做唯讀 `doctor` 檢查。 + +以下範例的 `$JAR` 應為已驗證的 InviteCode JAR;所有路徑、主機、database 及環境變數名稱均須換成實際值。MySQL 密碼與密鑰不得放在指令參數、log 或 Git。 + +### SQLite → JSON + +```powershell +$entry = 'io.github.command1264.invitecode.plugin.OfflineStorageTransferMain' +$options = @('--from-backend','sqlite','--from-file',$SQLITE,'--from-secret-file',$SOURCE_KEY, + '--to-backend','json','--to-file',$JSON,'--to-secret-file',$DEST_KEY,'--stopped') +mise exec -- java -cp $JAR $entry @options +mise exec -- java -cp $JAR $entry @options --apply --backup $SOURCE_BACKUP +``` + +反向或 SQLite/JSON 之間其他方向只需交換 `--from-backend`/`--to-backend` 與各自的檔案及密鑰路徑。 + +### 涉及 MySQL + +MySQL database 必須事先建立但不含表格,並由專用帳號存取。TLS 預設 `VERIFY_IDENTITY`;隔離測試可明確改為 `--mysql-tls REQUIRED`。若 MySQL 是來源,`--backup` 必須是既有的非空 dump;若 MySQL 是目的地,來源的檔案備份由工具建立。 + +```powershell +$entry = 'io.github.command1264.invitecode.plugin.OfflineStorageTransferMain' +$mysql = @('--mysql-host',$HOSTNAME,'--mysql-port',$PORT,'--mysql-database',$DATABASE, + '--mysql-username',$USERNAME,'--mysql-password-env','INVITECODE_MYSQL_PASSWORD', + '--mysql-secret-env','INVITECODE_NETWORK_SECRET') +$options = @('--from-backend','json','--from-file',$JSON,'--from-secret-file',$SOURCE_KEY, + '--to-backend','mysql','--stopped') + $mysql +mise exec -- java -cp $JAR $entry @options +mise exec -- java -cp $JAR $entry @options --apply --backup $SOURCE_BACKUP +``` + +MySQL → SQLite/JSON 時,將 MySQL 設為 `--from-backend mysql`,目的地提供 `--to-file` 與 `--to-secret-file`,並把 `--backup` 指向已建立的 MySQL dump。兩端若都在同一台伺服器,仍須停止所有指向來源 database 的插件實例。 + +## 中斷與回復 + +- 預檢失敗或目的地已存在:保留來源,不覆寫目的地。核對錯誤、密鑰與設定後,使用新的空白目的地重試。 +- SQLite/JSON 匯入失敗:正式目的檔不會在匯入成功前發布。發布需要目的地所在檔案系統支援同目錄硬連結;不支援時安全失敗,請改用支援的檔案系統。暫存檔可能在程序崩潰後留存;先檢查後再以新目的路徑重試。來源與備份保留。 +- MySQL 初始化或匯入中斷:目的 database 保留 `invitecode_transfer_guard`,插件會拒絕啟用。不要手工刪除 guard 來繞過檢查;先保留事故證據,使用全新空白 database 重試,或從經驗證的備份還原後再處理。MySQL DDL 不能靠交易回滾清除。 +- 若切換設定後需要回復來源,先停止目的地所有寫入者;目的地啟用後新增的資料不會自動回流,須先人工核對差異。不得同時讓來源與目的地接受新 Claim 或獎勵交付。 + +真人遊戲內操作驗收依 Issue #12 延後。隔離測試與 dump 不得使用正式玩家資料。 diff --git a/docs/operations/json-storage.md b/docs/operations/json-storage.md index cf29433..f2d5439 100644 --- a/docs/operations/json-storage.md +++ b/docs/operations/json-storage.md @@ -4,6 +4,6 @@ JSON backend 適合小型單一伺服器、測試與資料交換。將 `plugins/ JSON 檔是唯一的持久化資料來源,內含 `format-version`、`schema-version` 與按資料表分組的記錄;執行時使用暫存 SQLite 工作檔沿用現有交易、唯一性及稽核約束。每次成功寫入都會重新輸出整份 JSON,以同資料夾暫存檔原子替換正式檔,並將替換前的快照保留為 `invitecode.json.previous`(實際名稱跟隨 `json.file`)。`.lock` sidecar 以作業系統檔案鎖阻止兩個程序同時開啟;程序異常結束後檔案可能留存,鎖會由作業系統釋放,不應僅因檔案存在而刪除它。 -每次寫入的成本隨整體資料量成長,不能像 MySQL 一樣讓多個插件實例共用同一份資料,也不應用於高併發或大型伺服器。JSON 格式供檢視與交換,但手動更改記錄可能破壞領域約束。切換 backend 不會自動搬移資料。JSON 格式與內部 schema 版本不相符時會拒絕開啟;schema 8 升至 9 須使用[離線維護工具](./offline-anonymization.md),沒有線上升級指令。 +每次寫入的成本隨整體資料量成長,不能像 MySQL 一樣讓多個插件實例共用同一份資料,也不應用於高併發或大型伺服器。JSON 格式供檢視與交換,但手動更改記錄可能破壞領域約束。切換 backend 須使用[離線跨 backend 搬移工具](./cross-backend-transfer.md),不會自動搬移資料。JSON 格式與內部 schema 版本不相符時會拒絕開啟;schema 8 升至 9 須使用[離線維護工具](./offline-anonymization.md),沒有線上升級指令。 若 JSON 損毀或版本不支援,插件會進入維護模式,保留原檔,**不會**把它當成空白資料重新初始化。先停止伺服器並備份正式 JSON、`.previous` 及 `anti-abuse.key`。檢查錯誤訊息與版本;若上一份快照有效,可在伺服器停機時由管理員將 `.previous` 複製回正式檔,再啟動驗證。這會失去上一份快照之後的變更。不要重新產生 `anti-abuse.key`:它是 HMAC 密鑰,應與 JSON 同時備份。若寫入或原子替換失敗,當次程序會停止後續寫入;修正磁碟問題後重啟並檢查最後一份有效快照。 diff --git a/docs/operations/mysql-storage.md b/docs/operations/mysql-storage.md index afcf2d6..36349e2 100644 --- a/docs/operations/mysql-storage.md +++ b/docs/operations/mysql-storage.md @@ -1,6 +1,6 @@ # MySQL 8.4 儲存設定與復原 -InviteCode 的 MySQL backend 目前以 MySQL 8.4 LTS 為正式驗證目標。MariaDB 尚未列入相容性承諾。插件會在已存在、完全空白的 database 首次啟動時自行建立 schema;database 本身與專用帳號須先由管理員建立。本功能不搬移 SQLite 資料,也不會在 reload 時切換 backend。 +InviteCode 的 MySQL backend 目前以 MySQL 8.4 LTS 為正式驗證目標。MariaDB 尚未列入相容性承諾。插件會在已存在、完全空白的 database 首次啟動時自行建立 schema;database 本身與專用帳號須先由管理員建立。跨 backend 資料搬移須使用[離線工具](./cross-backend-transfer.md),不會在 reload 時切換 backend。 ## 準備 database 與設定 @@ -42,7 +42,7 @@ $env:INVITECODE_NETWORK_SECRET = [Convert]::ToBase64String( 新 database 首次啟動時,插件會取得 MySQL advisory lock,寫入含 checksum 的 migration ledger,依序建立表並逐一檢查欄位、索引、外鍵與儲存引擎。MySQL DDL 無法像 SQLite 一樣完整交易回滾;若在建表途中中斷,ledger 會維持 `APPLYING`。下次啟動只在既有表通過結構檢查時建立剩餘的表;結構不同時進入維護模式,保留資料供人工檢查。完成後 ledger 為 `APPLIED`,後續啟動只檢查版本與結構。 -既有 schema 的版本更新須先備份、暫停所有使用同一 database 的插件實例,再執行 `/invitecode admin storage migrate MYSQL `;schema 1 升至 2 也可使用[離線維護工具](./offline-anonymization.md)與既有 dump。`doctor` 僅讀取健康狀態,不執行 migration。只有資料庫已建立而 schema 為全新的情況才會在一般啟動時自動建表;選擇不同 backend 並不搬移既有資料。不要在兩個 backend 同時收集正式玩家資料後直接改回設定。 +既有 schema 的版本更新須先備份、暫停所有使用同一 database 的插件實例,再執行 `/invitecode admin storage migrate MYSQL `;schema 1 升至 2 也可使用[離線維護工具](./offline-anonymization.md)與既有 dump。`doctor` 僅讀取健康狀態,不執行 migration。只有資料庫已建立而 schema 為全新的情況才會在一般啟動時自動建表;跨 backend 資料須明確停機、備份並搬移。若 `invitecode_transfer_guard` 留存,表示目的地搬移未完成,插件會拒絕啟用;不要直接刪除 guard 繞過檢查。不要在兩個 backend 同時收集正式玩家資料後直接改回設定。 ## 驗證 diff --git a/docs/testing/evidence/2026-10-02-issue-26-transfer-retest.md b/docs/testing/evidence/2026-10-02-issue-26-transfer-retest.md new file mode 100644 index 0000000..2012d4a --- /dev/null +++ b/docs/testing/evidence/2026-10-02-issue-26-transfer-retest.md @@ -0,0 +1,46 @@ +# Issue #26 整合、完整性預檢與復原驗證 + +日期:2026-10-02。分支:`codex/fix/issue-26-transfer-preflight`,目標 `develop`。 + +## 受測版本 + +在獨立 Worktree `D:\Code\Java\Plugin\InviteCodeKt\worktrees\fix-issue-26-transfer-preflight`,以 `develop` 的 `40e21b01edfc87275eac887b9f1f5ae147ae0542` 整合既有搬移候選 `8c57de5997e8c1b31f57ab883b5f46278500fcbb`,再修正來源完整性預檢及補足測試。主要 checkout 與舊候選 Worktree 保留,不在 `develop` 直接實作。 + +受測 JAR:`invitecode-plugin/build/libs/InviteCode-0.1.0-SNAPSHOT.jar`。 + +SHA-256:`D6AF246F62256E2BEF1FB441DC282B4ADE6001269776D8966C7652F5E264ED6C`。 + +## 執行與結果 + +mise 清單確認已有 `local-8`、`local-11`;本輪以 `mise exec java@local-8 -- java -version` 確認 Java `1.8.0_501`,所有建置與測試沿用該選版及 Wrapper,沒有安裝或修改工具鏈。 + +1. RED:新增 CLI 預覽拒絕孤立 SQLite 邀請碼的測試,原實作出現 `Expected StorageTransferException to be thrown, but nothing was thrown`。來源有錯誤資料仍被判定預檢成功。 +2. GREEN:匯出改為先檢查來源完整性及快照格式,CLI 測試通過;SQLite 用唯讀 PRAGMA 檢查 CHECK/外鍵,MySQL 依白名單與 schema metadata 檢查外鍵關聯。 +3. `mise exec java@local-8 -- .\gradlew.bat check shadowJar --console=plain` 通過;最後補強 trigger SQLState 與來源/備份位元組不變的斷言後,再次執行相同檢查通過。未變模組沿用 Gradle cache/up-to-date,受影響的測試重新執行。 +4. 保留的 JUnit XML 合計 **55 suites、244 tests,0 failures、0 errors、0 skipped**。Java 8 bytecode、JAR 必要 entry/雙 JDBC driver/設定資源檢查通過,`git diff --check` 通過。 + +| 測試 suite | tests | 驗證內容 | +| --- | ---: | --- | +| OfflineStorageTransferMainTest | 3 | SQLite 孤立紀錄在 preview/apply 前拒絕,不建立目的地或備份且來源不變;SQLite→JSON→SQLite 保留 UNCERTAIN、冪等鍵、transition,重開不排入 pending | +| OfflineStorageTransferMysqlIntegrationTest | 2 | 另四種 MySQL 搬移方向保留 PENDING/UNCERTAIN;MySQL 重開讀回;可見併發來源連線拒絕;trigger 匯入失敗回滾、guard 阻擋重新啟動、保留來源/備份、全新 database 重試成功 | +| OfflineStorageTransferTest | 5 | 完整業務表搬移、非空目的地/密鑰拒絕、SQLite 故障回滾及既有 CHECK 違規拒絕 | +| MysqlIntegrationTest | 13 | 含重新啟用外鍵後的孤立來源仍拒絕及既有 MySQL schema/recovery 測試 | +| MysqlStorageContractTest | 2 | MySQL storage contract | +| MysqlRuntimeBootstrapTest | 2 | 同資料庫/密鑰重新開啟、startup 與 transfer lock/guard 的協調 | +| JsonOfflineTransferTest | 2 | staging 失敗不發布、重開讀回及目的檔競爭不覆寫 | + +原始 XML 快照保留於本 Worktree `invitecode-plugin/build/issue26-evidence/xml//`;完整執行 log 位於 `invitecode-plugin/build/issue26-mysql/full-check.log` 與 `final-check.log`。此目錄屬本機驗證產物,不加入 Git。 + +## 隔離範圍與限制 + +MySQL 使用已存在的 `8.4.11` runtime,建立本 Worktree 全新的 `invitecode-plugin/build/issue26-mysql/data`,啟動前確認 port `63386` 無 listener,僅綁定 `127.0.0.1`。各測試使用 UUID 命名的專用 database,執行後只刪除自己建立的 database。未存取既有 MySQL 服務、玩家資料或 Human/Agent Minecraft 實例,也未接入 Velocity。 + +MySQL 故障注入在公開 `OfflineStorageTransfer.import` 的真實 transaction 邊界執行:目的地 trigger 發出 SQLState `45000`,確認回滾與持久 guard;關閉連線池後以 `MysqlRuntimeBootstrap` 重新開啟遭拒,使用新 database 匯入驗證後重開成功。這不是作業系統斷電、kill CLI 或重啟 mysqld 的測試;不宣稱涵蓋那些崩潰時序。 + +MySQL→檔案方向的 dump fixture 只驗證 CLI 要求非空備份的 gate,未證明 dump 可還原;實際維運仍須自行驗證一致性 dump。`--stopped` 仍是操作者確認,不能證明不可見的其他 MySQL 帳號或稍後連入的寫入者已停止。 + +測試結束後正常停止本輪隔離 MySQL,移除暫存憑證並確認 port 已釋放;保留資料目錄與 log 供核對。真人遊戲內驗收維持先前延後安排,本輪未要求追加真人測試。 + +## 交付 + +Agent 驗證完成後保留 task Worktree、JAR、XML 與分支供使用者審閱。Push、PR、merge 及 Issue 關閉尚未執行。下一步依 [Issue #26 驗收條件](https://github.com/Command1264/InviteCodeKt/issues/26)交付新 HEAD,授權後建立目標為 `develop` 的 PR;再依 [Roadmap #1 發行門檻](https://github.com/Command1264/InviteCodeKt/issues/1)核對 Issue #12 與最終發行證據。 diff --git a/invitecode-plugin/build.gradle.kts b/invitecode-plugin/build.gradle.kts index 7870fbe..3d2b3ad 100644 --- a/invitecode-plugin/build.gradle.kts +++ b/invitecode-plugin/build.gradle.kts @@ -149,6 +149,7 @@ val verifyPluginJar by tasks.registering(VerifyPluginJar::class) { "config/messages/en_US.yml", "io/github/command1264/invitecode/plugin/InviteCodePlugin.class", "io/github/command1264/invitecode/plugin/OfflineAnonymizeMain.class", + "io/github/command1264/invitecode/plugin/OfflineStorageTransferMain.class", "org/sqlite/JDBC.class", "com/mysql/cj/jdbc/Driver.class", "com/zaxxer/hikari/HikariDataSource.class", diff --git a/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/MysqlRuntimeBootstrap.kt b/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/MysqlRuntimeBootstrap.kt index dba92d5..8fdac3e 100644 --- a/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/MysqlRuntimeBootstrap.kt +++ b/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/MysqlRuntimeBootstrap.kt @@ -41,23 +41,35 @@ internal class MysqlRuntimeBootstrap( throw error } try { - val initializedBefore = pool.connection.use(MysqlSchemaMigrator::isInitialized) - if (initializedBefore && !explicitMigration) { - pool.connection.use(MysqlSchemaMigrator::requireCurrent) - } else { - MysqlSchemaMigrator(pool, guard).migrate() - } - pool.connection.use { connection -> MysqlSchemaMigrator.bindNetworkKey(connection, hasher.keyId) } - storage = MysqlInviteCodeStorage.open(pool, guard, CodeReservationKey(hasher.keyId, hasher::hashReservedCode)) - if (!initializedBefore) { - storage.saveAuditRecord( - AuditRecord( - UUID.randomUUID(), InvitationAuditAction.STORAGE_MIGRATED, - "system", "automatic first MySQL initialization", now(), - ), + return MysqlTransferCoordinator.withLock(pool) { connection -> + val catalog = requireNotNull(connection.catalog) { "MySQL database is not selected." } + connection.metaData.getTables(catalog, null, "invitecode_transfer_guard", arrayOf("TABLE")).use { tables -> + if (tables.next()) throw MysqlStorageException( + "MySQL backend transfer is incomplete; keep InviteCode stopped, inspect the destination " + + "and restore or restart the offline transfer before enabling this database.", + ) + } + val initializedBefore = MysqlSchemaMigrator.isInitialized(connection) + if (initializedBefore && !explicitMigration) { + MysqlSchemaMigrator.requireCurrent(connection) + } else { + MysqlSchemaMigrator(pool, guard).migrate() + } + MysqlSchemaMigrator.bindNetworkKey(connection, hasher.keyId) + val activeStorage = MysqlInviteCodeStorage.open( + pool, guard, CodeReservationKey(hasher.keyId, hasher::hashReservedCode), ) + storage = activeStorage + if (!initializedBefore) { + activeStorage.saveAuditRecord( + AuditRecord( + UUID.randomUUID(), InvitationAuditAction.STORAGE_MIGRATED, + "system", "automatic first MySQL initialization", now(), + ), + ) + } + MysqlBootstrapResult(activeStorage, hasher, !initializedBefore) } - return MysqlBootstrapResult(storage, hasher, !initializedBefore) } catch (error: Exception) { storage?.close() ?: pool.close() hasher.close() diff --git a/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/MysqlTransferCoordinator.kt b/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/MysqlTransferCoordinator.kt new file mode 100644 index 0000000..be36e0b --- /dev/null +++ b/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/MysqlTransferCoordinator.kt @@ -0,0 +1,37 @@ +package io.github.command1264.invitecode.plugin + +import io.github.command1264.invitecode.storage.sql.MysqlStorageException +import java.nio.charset.StandardCharsets +import java.security.MessageDigest +import java.sql.Connection +import javax.sql.DataSource + +/** Serializes plugin startup with offline transfer staging and publication in one MySQL database. */ +internal object MysqlTransferCoordinator { + fun withLock(pool: DataSource, operation: (Connection) -> T): T = pool.connection.use { connection -> + val database = requireNotNull(connection.catalog) { "MySQL database is not selected." } + val digest = MessageDigest.getInstance("SHA-256") + .digest(database.toByteArray(StandardCharsets.UTF_8)) + .take(20).joinToString("") { "%02x".format(it.toInt() and 0xff) } + val name = "invitecode:transfer:$digest" + val acquired = connection.prepareStatement("SELECT GET_LOCK(?, 10)").use { statement -> + statement.setString(1, name) + statement.executeQuery().use { rows -> rows.next() && rows.getInt(1) == 1 } + } + if (!acquired) throw MysqlStorageException( + "MySQL backend transfer/startup lock timed out; stop all instances and retry.", + ) + try { + operation(connection) + } finally { + connection.prepareStatement("SELECT RELEASE_LOCK(?)").use { statement -> + statement.setString(1, name) + statement.executeQuery().use { rows -> + if (!rows.next() || rows.getInt(1) != 1) throw MysqlStorageException( + "MySQL backend transfer/startup lock was lost; inspect the database before continuing.", + ) + } + } + } + } +} diff --git a/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/OfflineStorageTransferMain.kt b/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/OfflineStorageTransferMain.kt new file mode 100644 index 0000000..7e146d4 --- /dev/null +++ b/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/OfflineStorageTransferMain.kt @@ -0,0 +1,306 @@ +package io.github.command1264.invitecode.plugin + +import io.github.command1264.invitecode.core.MysqlConfiguration +import io.github.command1264.invitecode.core.MysqlTlsMode +import io.github.command1264.invitecode.platform.bukkit.NetworkAddressHasher +import io.github.command1264.invitecode.storage.json.JsonInviteCodeStorage +import io.github.command1264.invitecode.storage.sql.BlockingOperationGuard +import io.github.command1264.invitecode.storage.sql.CodeReservationKey +import io.github.command1264.invitecode.storage.sql.MysqlInviteCodeStorage +import io.github.command1264.invitecode.storage.sql.MysqlSchemaMigrator +import io.github.command1264.invitecode.storage.sql.OfflineStorageTransfer +import io.github.command1264.invitecode.storage.sql.PortableStorageSnapshot +import io.github.command1264.invitecode.storage.sql.SqliteSchemaMigrator +import io.github.command1264.invitecode.storage.sql.SqliteSnapshotAccess +import io.github.command1264.invitecode.storage.sql.StorageDialect +import java.nio.file.Files +import java.nio.file.LinkOption.NOFOLLOW_LINKS +import java.nio.file.Path +import java.nio.file.Paths +import java.nio.file.StandardCopyOption.COPY_ATTRIBUTES +import java.security.MessageDigest +import java.sql.Connection +import java.time.Duration +import java.util.Locale + +/** Explicit offline transfer entry point. It never changes storage.yml or deletes the source. */ +object OfflineStorageTransferMain { + @JvmStatic + fun main(args: Array) { + try { + execute(args) + } catch (error: Exception) { + System.err.println("離線搬移已拒絕:${error.message}") + kotlin.system.exitProcess(1) + } + } + + internal fun execute(args: Array, environment: (String) -> String? = System::getenv) { + val options = parse(args) + require("stopped" in options) { "先停止所有使用來源或目的地的 InviteCode 實例,再指定 --stopped。" } + val source = endpoint("from", options, mustExist = true) + val destination = endpoint("to", options, mustExist = false) + require(source.backend != destination.backend) { "來源與目的 backend 必須不同。" } + if (source.file != null && destination.file != null) { + require(source.file != destination.file) { "來源與目的資料檔不可相同。" } + } + val apply = "apply" in options + if (apply) require("backup" in options) { "正式搬移必須指定已驗證的來源備份 --backup。" } + val backupPath = if (apply) path(options.required("backup")) else null + require(backupPath == null || backupPath != destination.file) { "備份路徑不可與目的資料檔相同。" } + val mysql = if (source.backend == "mysql" || destination.backend == "mysql") mysqlConfig(options) else null + val password = if (mysql != null) environment(options.required("mysql-password-env"), environment) else null + val guard = BlockingOperationGuard { } + hasher(source, options, environment).use { sourceHasher -> + hasher(destination, options, environment).use { destinationHasher -> + require(sourceHasher.keyId == destinationHasher.keyId) { + "兩端 anti-abuse 密鑰不同;請先提供相同密鑰。既有 IP hash 與舊邀請碼保留值不可重新計算。" + } + val keyId = sourceHasher.keyId + val snapshot = export(source, mysql, password, sourceHasher, guard) + require(snapshot.networkKeyId == keyId) { "來源 metadata 與提供的密鑰不一致。" } + preflightDestination(destination, mysql, password) + println("預檢通過:${source.backend} → ${destination.backend};" + + snapshot.tables.joinToString("、") { "${it.name.removePrefix("invitecode_")}=${it.rows.size}" }) + if (!apply) { + println("本次只預覽;備份來源後,使用相同選項加 --apply --backup <路徑> 執行。") + return + } + backup(source, requireNotNull(backupPath)) + // Reject changes between preview and the final source read; the backup is made before publication. + val finalSnapshot = export(source, mysql, password, sourceHasher, guard) + require(finalSnapshot == snapshot) { "來源在預檢後改變;目的地未寫入。停止所有寫入者並重新執行。" } + val checkSourceUnchanged = { + require(export(source, mysql, password, sourceHasher, guard) == finalSnapshot) { + "搬移期間來源發生變化;目的地仍在 staging,禁止 cutover。請檢查所有寫入者。" + } + } + when (destination.backend) { + "sqlite" -> writeSqlite(requireNotNull(destination.file), keyId, finalSnapshot, guard, checkSourceUnchanged) + "json" -> writeJson(requireNotNull(destination.file), destinationHasher, finalSnapshot, guard, checkSourceUnchanged) + "mysql" -> writeMysql(requireNotNull(mysql), requireNotNull(password), finalSnapshot, guard, checkSourceUnchanged) + } + println("目的地已完成全表驗證;來源未改動。確認 storage.yml 僅指向目的地後,再啟動一組 InviteCode 實例。") + } + } + } + + private data class Endpoint(val backend: String, val file: Path?, val secretFile: Path?) + + private fun endpoint(prefix: String, options: Map, mustExist: Boolean): Endpoint { + val backend = options.required("$prefix-backend").lowercase(Locale.ROOT) + require(backend in setOf("sqlite", "json", "mysql")) { "不支援的 $prefix backend:$backend。" } + if (backend == "mysql") return Endpoint(backend, null, null) + val file = path(options.required("$prefix-file")) + val secretFile = path(options.required("$prefix-secret-file")) + require(Files.isRegularFile(secretFile, NOFOLLOW_LINKS)) { "$prefix anti-abuse.key 必須已存在。" } + if (mustExist) { + require(Files.isRegularFile(file, NOFOLLOW_LINKS)) { "來源資料檔必須已存在。" } + if (backend == "sqlite") requireNoWal(file) + } else { + require(!Files.exists(file, NOFOLLOW_LINKS)) { "目的資料檔已存在;不可覆寫。" } + require(Files.isDirectory(requireNotNull(file.parent))) { "目的資料夾必須已存在。" } + } + return Endpoint(backend, file, secretFile) + } + + private fun hasher( + endpoint: Endpoint, options: Map, environment: (String) -> String?, + ): NetworkAddressHasher = + if (endpoint.backend == "mysql") NetworkAddressHasher.fromBase64( + environment(options.required("mysql-secret-env"), environment), + ) + else NetworkAddressHasher.loadExisting(requireNotNull(endpoint.secretFile)) + + private fun export( + source: Endpoint, mysql: MysqlConfiguration?, password: String?, + hasher: NetworkAddressHasher, guard: BlockingOperationGuard, + ): PortableStorageSnapshot = when (source.backend) { + "sqlite" -> SqliteSnapshotAccess.withConnection(requireNotNull(source.file), guard) { connection -> + requireNoWal(requireNotNull(source.file)) + connection.createStatement().use { it.execute("PRAGMA query_only=ON") } + OfflineStorageTransfer.export(connection, StorageDialect.SQLITE, hasher.keyId) + } + "json" -> JsonInviteCodeStorage.open( + requireNotNull(source.file), guard, CodeReservationKey(hasher.keyId, hasher::hashReservedCode), + ).use { storage -> + storage.inspectOffline { OfflineStorageTransfer.export(it, StorageDialect.SQLITE, hasher.keyId) } + } + else -> MysqlInviteCodeStorage.createPool(requireNotNull(mysql), requireNotNull(password)).use { pool -> + MysqlTransferCoordinator.withLock(pool) { connection -> + requireNoOtherMysqlSessions(connection) + connection.isReadOnly = true + connection.transactionIsolation = Connection.TRANSACTION_REPEATABLE_READ + connection.autoCommit = false + try { + OfflineStorageTransfer.export(connection, StorageDialect.MYSQL, hasher.keyId) + } finally { + connection.rollback() + } + } + } + } + + private fun preflightDestination(destination: Endpoint, mysql: MysqlConfiguration?, password: String?) { + if (destination.backend != "mysql") { + require(!Files.exists(requireNotNull(destination.file), NOFOLLOW_LINKS)) { "目的資料檔已出現;停止操作。" } + return + } + MysqlInviteCodeStorage.createPool(requireNotNull(mysql), requireNotNull(password)).use { pool -> + pool.connection.use { connection -> + requireNoOtherMysqlSessions(connection) + val catalog = requireNotNull(connection.catalog) { "MySQL 沒有選定 database。" } + connection.metaData.getTables(catalog, null, "%", arrayOf("TABLE", "VIEW")).use { tables -> + require(!tables.next()) { "MySQL 目的 database 必須完全空白;不可覆寫或重試既有 staging。" } + } + } + } + } + + private fun writeSqlite( + destination: Path, keyId: String, snapshot: PortableStorageSnapshot, guard: BlockingOperationGuard, + checkSourceUnchanged: () -> Unit, + ) { + require(!Files.exists(destination, NOFOLLOW_LINKS)) { "SQLite 目的檔已存在。" } + val staged = Files.createTempFile(requireNotNull(destination.parent), ".${destination.fileName}.", ".staging") + try { + SqliteSchemaMigrator(staged, guard).migrate() + SqliteSnapshotAccess.withConnection(staged, guard) { connection -> + OfflineStorageTransfer.import(connection, StorageDialect.SQLITE, snapshot) + OfflineStorageTransfer.verify(connection, StorageDialect.SQLITE, snapshot) + } + require(snapshot.networkKeyId == keyId) { "SQLite 目的密鑰已改變。" } + checkSourceUnchanged() + // A hard link publishes the fully verified file without replacing an existing destination. + Files.createLink(destination, staged) + SqliteSnapshotAccess.withConnection(destination, guard) { + OfflineStorageTransfer.verify(it, StorageDialect.SQLITE, snapshot) + } + } finally { + Files.deleteIfExists(staged) + } + } + + private fun writeJson( + destination: Path, hasher: NetworkAddressHasher, + snapshot: PortableStorageSnapshot, guard: BlockingOperationGuard, checkSourceUnchanged: () -> Unit, + ) { + JsonInviteCodeStorage.createOfflineFromSqlite(destination, guard) { connection -> + OfflineStorageTransfer.import(connection, StorageDialect.SQLITE, snapshot) + OfflineStorageTransfer.verify(connection, StorageDialect.SQLITE, snapshot) + checkSourceUnchanged() + } + JsonInviteCodeStorage.open(destination, guard, CodeReservationKey(hasher.keyId, hasher::hashReservedCode)).use { + it.inspectOffline { connection -> OfflineStorageTransfer.verify(connection, StorageDialect.SQLITE, snapshot) } + } + } + + private fun writeMysql( + config: MysqlConfiguration, password: String, snapshot: PortableStorageSnapshot, guard: BlockingOperationGuard, + checkSourceUnchanged: () -> Unit, + ) { + MysqlInviteCodeStorage.createPool(config, password).use { pool -> + MysqlTransferCoordinator.withLock(pool) { connection -> + requireNoOtherMysqlSessions(connection) + val catalog = requireNotNull(connection.catalog) + connection.metaData.getTables(catalog, null, "%", arrayOf("TABLE", "VIEW")).use { + require(!it.next()) { "MySQL 目的 database 已有表格;停止操作。" } + } + // This marker blocks plugin startup if DDL, import, or verification is interrupted. + OfflineStorageTransfer.createMysqlTransferGuard(connection) + MysqlSchemaMigrator(pool, guard).migrate() + MysqlSchemaMigrator.bindNetworkKey(connection, snapshot.networkKeyId) + OfflineStorageTransfer.import(connection, StorageDialect.MYSQL, snapshot) + OfflineStorageTransfer.verify(connection, StorageDialect.MYSQL, snapshot) + checkSourceUnchanged() + OfflineStorageTransfer.releaseMysqlTransferGuard(connection) + } + } + } + + /** Requires a dedicated database account, so another plugin connection cannot be hidden. */ + private fun requireNoOtherMysqlSessions(connection: Connection) { + val others = connection.createStatement().use { statement -> + statement.executeQuery( + "SELECT COUNT(*) FROM information_schema.PROCESSLIST WHERE DB = DATABASE() AND ID <> CONNECTION_ID()", + ).use { rows -> rows.next(); rows.getLong(1) } + } + require(others == 0L) { "偵測到其他 MySQL 連線;請先停止所有使用這個 database 的程序。" } + } + + private fun backup(source: Endpoint, backup: Path) { + if (source.backend == "mysql") { + require(Files.isRegularFile(backup, NOFOLLOW_LINKS) && Files.size(backup) > 0) { + "MySQL 來源需要既有且非空的完整備份 dump。" + } + return + } + val file = requireNotNull(source.file) + require(file != backup && !Files.exists(backup, NOFOLLOW_LINKS)) { "備份檔不可覆寫來源或既有檔案。" } + require(Files.isDirectory(requireNotNull(backup.parent))) { "備份資料夾必須已存在。" } + if (source.backend == "sqlite") requireNoWal(file) + Files.copy(file, backup, COPY_ATTRIBUTES) + require(digest(file).contentEquals(digest(backup))) { "來源與備份的 SHA-256 不同;停止搬移。" } + } + + private fun requireNoWal(file: Path) { + require(!Files.exists(file.resolveSibling("${file.fileName}-wal")) && + !Files.exists(file.resolveSibling("${file.fileName}-shm"))) { + "SQLite 仍有 WAL/SHM;先停止實例、checkpoint 並做一致性備份。" + } + } + + private fun digest(file: Path): ByteArray = MessageDigest.getInstance("SHA-256").let { sha -> + Files.newInputStream(file).use { input -> + val bytes = ByteArray(8192) + while (true) { + val count = input.read(bytes) + if (count < 0) break + sha.update(bytes, 0, count) + } + } + sha.digest() + } + + private fun mysqlConfig(options: Map): MysqlConfiguration = MysqlConfiguration( + options.required("mysql-host"), options.required("mysql-port").toInt(), + options.required("mysql-database"), options.required("mysql-username"), + "\${INVITECODE_OFFLINE_PASSWORD}", "\${INVITECODE_OFFLINE_SECRET}", Duration.ofSeconds(10), + MysqlTlsMode.valueOf(options.getOrDefault("mysql-tls", "VERIFY_IDENTITY")), + ) + + private fun environment(name: String, lookup: (String) -> String?): String { + require(Regex("[A-Za-z_][A-Za-z0-9_]*").matches(name)) { "環境變數名稱無效。" } + return lookup(name)?.takeIf(String::isNotBlank) + ?: throw IllegalArgumentException("環境變數 $name 不存在或為空。") + } + + private fun path(raw: String): Path = Paths.get(raw).toAbsolutePath().normalize() + + private fun parse(args: Array): Map { + val flags = setOf("apply", "stopped") + val values = setOf("from-backend", "to-backend", "from-file", "to-file", "from-secret-file", "to-secret-file", + "backup", "mysql-host", "mysql-port", "mysql-database", "mysql-username", "mysql-password-env", + "mysql-secret-env", "mysql-tls") + val result = mutableMapOf() + var index = 0 + while (index < args.size) { + val option = args[index] + val name = option.removePrefix("--") + require(option.startsWith("--") && name in flags + values) { "未知選項 $option。" } + require(name !in result) { "選項 --$name 不可重複。" } + if (name in flags) { + result[name] = "true" + index++ + } else { + require(index + 1 < args.size && !args[index + 1].startsWith("--")) { "選項 --$name 需要值。" } + result[name] = args[index + 1] + index += 2 + } + } + return result + } + + private fun Map.required(name: String): String = get(name)?.takeIf(String::isNotBlank) + ?: throw IllegalArgumentException("缺少 --$name。") +} diff --git a/invitecode-plugin/src/test/kotlin/io/github/command1264/invitecode/plugin/MysqlRuntimeBootstrapTest.kt b/invitecode-plugin/src/test/kotlin/io/github/command1264/invitecode/plugin/MysqlRuntimeBootstrapTest.kt index 5cf8dcf..34688d9 100644 --- a/invitecode-plugin/src/test/kotlin/io/github/command1264/invitecode/plugin/MysqlRuntimeBootstrapTest.kt +++ b/invitecode-plugin/src/test/kotlin/io/github/command1264/invitecode/plugin/MysqlRuntimeBootstrapTest.kt @@ -3,15 +3,23 @@ package io.github.command1264.invitecode.plugin import io.github.command1264.invitecode.core.MysqlConfiguration import io.github.command1264.invitecode.core.MysqlTlsMode import io.github.command1264.invitecode.storage.sql.BlockingOperationGuard +import io.github.command1264.invitecode.storage.sql.MysqlInviteCodeStorage import io.github.command1264.invitecode.storage.sql.MysqlStorageException +import io.github.command1264.invitecode.storage.sql.OfflineStorageTransfer 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 import org.junit.jupiter.api.Assumptions.assumeTrue import java.sql.DriverManager import java.time.Duration import java.util.Base64 import java.util.UUID +import java.util.concurrent.CountDownLatch +import java.util.concurrent.ExecutionException +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit class MysqlRuntimeBootstrapTest { @Test @@ -69,6 +77,34 @@ class MysqlRuntimeBootstrapTest { .encodeToString(ByteArray(32) { 7 }) }).initializeOrOpen() } + val executor = Executors.newSingleThreadExecutor() + try { + val pool = MysqlInviteCodeStorage.createPool(config, password) + pool.use { + var attempt: java.util.concurrent.Future<*>? = null + MysqlTransferCoordinator.withLock(pool) { connection -> + val started = CountDownLatch(1) + attempt = executor.submit { + started.countDown() + MysqlRuntimeBootstrap(config, guard, environment).initializeOrOpen() + } + assertTrue(started.await(5, TimeUnit.SECONDS)) + Thread.sleep(200) + assertFalse(requireNotNull(attempt).isDone) + OfflineStorageTransfer.createMysqlTransferGuard(connection) + } + val interrupted = assertThrows(ExecutionException::class.java) { + requireNotNull(attempt).get(10, TimeUnit.SECONDS) + } + assertTrue(interrupted.cause is MysqlStorageException) + assertTrue(interrupted.cause?.message.orEmpty().contains("transfer is incomplete")) + } + } finally { + executor.shutdownNow() + DriverManager.getConnection("jdbc:mysql://$host:$port/$schema?sslMode=REQUIRED", user, password).use { connection -> + connection.createStatement().use { it.execute("DROP TABLE invitecode_transfer_guard") } + } + } } finally { first.storage.close() first.networkHasher.close() diff --git a/invitecode-plugin/src/test/kotlin/io/github/command1264/invitecode/plugin/OfflineStorageTransferMainTest.kt b/invitecode-plugin/src/test/kotlin/io/github/command1264/invitecode/plugin/OfflineStorageTransferMainTest.kt new file mode 100644 index 0000000..25a1c94 --- /dev/null +++ b/invitecode-plugin/src/test/kotlin/io/github/command1264/invitecode/plugin/OfflineStorageTransferMainTest.kt @@ -0,0 +1,158 @@ +package io.github.command1264.invitecode.plugin + +import io.github.command1264.invitecode.core.StoredPlayer +import io.github.command1264.invitecode.core.RewardActionStatus +import io.github.command1264.invitecode.core.RewardDeliveryCoordinator +import io.github.command1264.invitecode.core.RewardDeliveryStatus +import io.github.command1264.invitecode.core.StoredRewardAction +import io.github.command1264.invitecode.core.StoredRewardDelivery +import io.github.command1264.invitecode.storage.json.JsonInviteCodeStorage +import io.github.command1264.invitecode.storage.sql.BlockingOperationGuard +import io.github.command1264.invitecode.storage.sql.SqliteInviteCodeStorage +import io.github.command1264.invitecode.storage.sql.SqliteSchemaMigrator +import io.github.command1264.invitecode.storage.sql.SqliteSnapshotAccess +import io.github.command1264.invitecode.storage.sql.StorageTransferException +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 +import org.junit.jupiter.api.io.TempDir +import java.nio.file.Files +import java.nio.file.Path +import java.time.Instant +import java.util.UUID + +class OfflineStorageTransferMainTest { + @TempDir lateinit var directory: Path + private val guard = BlockingOperationGuard { } + + @Test + fun `preview rejects an orphaned source before reporting success or creating a backup`() { + val key = directory.resolve("orphan.key") + Files.write(key, ByteArray(32) { 7 }) + val source = directory.resolve("orphan.db") + val destination = directory.resolve("orphan.json") + val backup = directory.resolve("orphan-backup.db") + SqliteSchemaMigrator(source, guard).migrate() + SqliteSnapshotAccess.withConnection(source, guard) { connection -> + connection.createStatement().use { it.execute("PRAGMA foreign_keys=OFF") } + connection.prepareStatement( + "INSERT INTO invitecode_codes(code, inviter_id, activated_at) VALUES (?, ?, ?)", + ).use { statement -> + statement.setString(1, "A1B2C3") + statement.setString(2, UUID.randomUUID().toString()) + statement.setString(3, "2026-01-01T00:00:00Z") + statement.executeUpdate() + } + } + val original = Files.readAllBytes(source) + val options = arrayOf( + "--from-backend", "sqlite", "--from-file", source.toString(), "--from-secret-file", key.toString(), + "--to-backend", "json", "--to-file", destination.toString(), "--to-secret-file", key.toString(), + "--stopped", + ) + val error = assertThrows(StorageTransferException::class.java) { + OfflineStorageTransferMain.execute(options) + } + assertTrue(error.message.orEmpty().contains("foreign-key")) + assertThrows(StorageTransferException::class.java) { + OfflineStorageTransferMain.execute(options + arrayOf("--apply", "--backup", backup.toString())) + } + assertFalse(Files.exists(destination)) + assertFalse(Files.exists(backup)) + assertTrue(original.contentEquals(Files.readAllBytes(source))) + } + + @Test + fun `SQLite to JSON to SQLite preserves uncertain rewards after reopening and never overwrites source`() { + val key = directory.resolve("anti-abuse.key") + Files.write(key, ByteArray(32) { 7 }) + val source = directory.resolve("source.db") + val json = directory.resolve("destination.json") + val result = directory.resolve("result.db") + val player = StoredPlayer(UUID.randomUUID(), Instant.parse("2026-01-01T00:00:00Z"), "Alice") + val delivery = StoredRewardDelivery( + UUID.randomUUID(), null, "welcome", RewardDeliveryStatus.PENDING, + "welcome:${player.id}", player.firstSeenAt, player.firstSeenAt, + ) + val action = StoredRewardAction( + UUID.randomUUID(), delivery.id, null, player.id, 0, "MESSAGE", "welcome", + RewardActionStatus.PENDING, "${delivery.idempotencyKey}:0", player.firstSeenAt, player.firstSeenAt, + ) + SqliteSchemaMigrator(source, guard).migrate() + SqliteInviteCodeStorage.open(source, guard).use { + it.savePlayer(player) + it.saveRewardDelivery(delivery, listOf(action)) + RewardDeliveryCoordinator(it).apply { + begin(action.id, player.firstSeenAt.plusSeconds(1)) + uncertain(action.id, "test interrupted action", player.firstSeenAt.plusSeconds(2)) + } + } + val original = Files.readAllBytes(source) + val first = arrayOf( + "--from-backend", "sqlite", "--from-file", source.toString(), "--from-secret-file", key.toString(), + "--to-backend", "json", "--to-file", json.toString(), "--to-secret-file", key.toString(), "--stopped", + ) + OfflineStorageTransferMain.execute(first) + assertFalse(Files.exists(json)) + val conflictingBackup = assertThrows(IllegalArgumentException::class.java) { + OfflineStorageTransferMain.execute(first + arrayOf("--apply", "--backup", json.toString())) + } + assertTrue(conflictingBackup.message!!.contains("備份路徑不可與目的資料檔相同")) + assertFalse(Files.exists(json)) + OfflineStorageTransferMain.execute(first + arrayOf("--apply", "--backup", directory.resolve("source-backup.db").toString())) + assertTrue(original.contentEquals(Files.readAllBytes(source))) + assertTrue(original.contentEquals(Files.readAllBytes(directory.resolve("source-backup.db")))) + JsonInviteCodeStorage.open(json, guard).use { + assertEquals(player, it.player(player.id)) + assertEquals(RewardActionStatus.UNCERTAIN, it.rewardAction(action.id)?.status) + assertEquals(action.idempotencyKey, it.rewardAction(action.id)?.idempotencyKey) + assertEquals(3, it.rewardActionTransitions(action.id).size) + assertTrue(it.pendingRewardActions(player.id).isEmpty()) + assertEquals(0, it.recoverInterruptedRewardActions(player.firstSeenAt.plusSeconds(10))) + } + + val second = arrayOf( + "--from-backend", "json", "--from-file", json.toString(), "--from-secret-file", key.toString(), + "--to-backend", "sqlite", "--to-file", result.toString(), "--to-secret-file", key.toString(), + "--stopped", "--apply", "--backup", directory.resolve("json-backup.json").toString(), + ) + OfflineStorageTransferMain.execute(second) + SqliteInviteCodeStorage.open(result, guard).use { + assertEquals(player, it.player(player.id)) + assertEquals(RewardActionStatus.UNCERTAIN, it.rewardAction(action.id)?.status) + assertEquals(action.idempotencyKey, it.rewardAction(action.id)?.idempotencyKey) + assertEquals(3, it.rewardActionTransitions(action.id).size) + assertTrue(it.pendingRewardActions(player.id).isEmpty()) + assertEquals(0, it.recoverInterruptedRewardActions(player.firstSeenAt.plusSeconds(10))) + } + } + + @Test + fun `mismatched key and occupied destination are rejected without source changes`() { + val key = directory.resolve("source.key") + val different = directory.resolve("different.key") + Files.write(key, ByteArray(32) { 7 }) + Files.write(different, ByteArray(32) { 8 }) + val source = directory.resolve("source.db") + val destination = directory.resolve("destination.json") + SqliteSchemaMigrator(source, guard).migrate() + val arguments = arrayOf( + "--from-backend", "sqlite", "--from-file", source.toString(), "--from-secret-file", key.toString(), + "--to-backend", "json", "--to-file", destination.toString(), "--to-secret-file", different.toString(), + "--stopped", "--apply", "--backup", directory.resolve("backup.db").toString(), + ) + val mismatch = assertThrows(IllegalArgumentException::class.java) { + OfflineStorageTransferMain.execute(arguments) + } + assertTrue(mismatch.message!!.contains("密鑰不同")) + assertFalse(Files.exists(destination)) + assertFalse(Files.exists(directory.resolve("backup.db"))) + Files.write(destination, byteArrayOf(1)) + val occupied = assertThrows(IllegalArgumentException::class.java) { + OfflineStorageTransferMain.execute(arguments) + } + assertTrue(occupied.message!!.contains("目的資料檔已存在")) + } +} diff --git a/invitecode-plugin/src/test/kotlin/io/github/command1264/invitecode/plugin/OfflineStorageTransferMysqlIntegrationTest.kt b/invitecode-plugin/src/test/kotlin/io/github/command1264/invitecode/plugin/OfflineStorageTransferMysqlIntegrationTest.kt new file mode 100644 index 0000000..41e23c1 --- /dev/null +++ b/invitecode-plugin/src/test/kotlin/io/github/command1264/invitecode/plugin/OfflineStorageTransferMysqlIntegrationTest.kt @@ -0,0 +1,402 @@ +package io.github.command1264.invitecode.plugin + +import io.github.command1264.invitecode.core.RewardActionStatus +import io.github.command1264.invitecode.core.RewardDeliveryStatus +import io.github.command1264.invitecode.core.InviteCodeStorage +import io.github.command1264.invitecode.core.MysqlConfiguration +import io.github.command1264.invitecode.core.MysqlTlsMode +import io.github.command1264.invitecode.core.StoredPlayer +import io.github.command1264.invitecode.core.StoredRewardAction +import io.github.command1264.invitecode.core.StoredRewardDelivery +import io.github.command1264.invitecode.platform.bukkit.NetworkAddressHasher +import io.github.command1264.invitecode.storage.sql.BlockingOperationGuard +import io.github.command1264.invitecode.storage.sql.MysqlInviteCodeStorage +import io.github.command1264.invitecode.storage.sql.MysqlSchemaMigrator +import io.github.command1264.invitecode.storage.sql.MysqlStorageException +import io.github.command1264.invitecode.storage.sql.OfflineStorageTransfer +import io.github.command1264.invitecode.storage.sql.StorageDialect +import io.github.command1264.invitecode.storage.sql.StorageTransferException +import io.github.command1264.invitecode.storage.sql.SqliteInviteCodeStorage +import io.github.command1264.invitecode.storage.sql.SqliteSchemaMigrator +import io.github.command1264.invitecode.storage.sql.SqliteSnapshotAccess +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Assumptions.assumeTrue +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import java.nio.charset.StandardCharsets +import java.nio.file.Files +import java.nio.file.Path +import java.sql.DriverManager +import java.time.Duration +import java.time.Instant +import java.util.Base64 +import java.util.UUID + +class OfflineStorageTransferMysqlIntegrationTest { + @TempDir lateinit var directory: Path + private val guard = BlockingOperationGuard { } + + @Test + fun `all four MySQL directions preserve uncertain and pending actions through repeated cutovers`() { + val host = System.getenv("INVITECODE_TEST_MYSQL_HOST") + val password = System.getenv("INVITECODE_TEST_MYSQL_PASSWORD") + assumeTrue(!host.isNullOrBlank() && !password.isNullOrBlank()) + val port = System.getenv("INVITECODE_TEST_MYSQL_PORT")?.toIntOrNull() ?: 3306 + val user = System.getenv("INVITECODE_TEST_MYSQL_USER") ?: "root" + val adminUrl = "jdbc:mysql://$host:$port/?sslMode=REQUIRED&connectionTimeZone=UTC" + val firstDb = databaseName() + val secondDb = databaseName() + val keyBytes = ByteArray(32) { 7 } + val key = directory.resolve("anti-abuse.key") + Files.write(key, keyBytes) + val secret = Base64.getEncoder().encodeToString(keyBytes) + val lookup: (String) -> String? = { name -> + when (name) { + "TEST_PASSWORD" -> password + "TEST_SECRET" -> secret + else -> null + } + } + val player = StoredPlayer(UUID.randomUUID(), Instant.parse("2026-01-01T00:00:00Z"), "Alice") + val delivery = StoredRewardDelivery( + UUID.randomUUID(), null, "welcome", RewardDeliveryStatus.PENDING, + "welcome:${player.id}", player.firstSeenAt, player.firstSeenAt, + ) + val action = StoredRewardAction( + UUID.randomUUID(), delivery.id, null, player.id, 0, "MESSAGE", "hello", + RewardActionStatus.PENDING, "${delivery.idempotencyKey}:0", player.firstSeenAt, player.firstSeenAt, + ) + val pendingAction = StoredRewardAction( + UUID.randomUUID(), delivery.id, null, player.id, 1, "MESSAGE", "still pending", + RewardActionStatus.PENDING, "${delivery.idempotencyKey}:1", player.firstSeenAt, player.firstSeenAt, + ) + val source = directory.resolve("source.db") + val json = directory.resolve("intermediate.json") + val result = directory.resolve("result.db") + SqliteSchemaMigrator(source, guard).migrate() + SqliteInviteCodeStorage.open(source, guard).use { storage -> + storage.savePlayer(player) + storage.saveRewardDelivery(delivery, listOf(action, pendingAction)) + storage.saveRewardAction(action.copy( + status = RewardActionStatus.PROCESSING, + updatedAt = player.firstSeenAt.plusSeconds(1), + )) + assertEquals(1, storage.recoverInterruptedRewardActions(player.firstSeenAt.plusSeconds(2))) + assertStoredUncertainAction(storage, action, pendingAction) + } + val invitee = UUID.randomUUID() + val invitation = UUID.randomUUID() + val keyId = NetworkAddressHasher.fromBase64(secret).use { it.keyId } + SqliteSnapshotAccess.withConnection(source, guard) { connection -> + connection.createStatement().use { it.execute("PRAGMA foreign_keys=ON") } + fun insert(sql: String, vararg values: Any?) = connection.prepareStatement(sql).use { statement -> + values.forEachIndexed { index, value -> statement.setObject(index + 1, value) } + statement.executeUpdate() + } + insert("INSERT INTO invitecode_players(player_id, first_seen_at, last_known_name) VALUES (?, ?, ?)", + invitee.toString(), "2026-01-02T00:00:00Z", "Bob") + insert("INSERT INTO invitecode_codes(code, inviter_id, activated_at) VALUES (?, ?, ?)", + "A1B2C3", player.id.toString(), "2026-01-01T00:00:00Z") + insert("INSERT INTO invitecode_invitations(invitation_id, inviter_id, inviter_eligibility_generation, " + + "invitee_id, invitee_eligibility_generation, status, claimed_at, qualified_at, " + + "qualification_policy_id, qualification_revision) VALUES (?, ?, 0, ?, 0, 'QUALIFIED', ?, ?, ?, ?)", + invitation.toString(), player.id.toString(), invitee.toString(), + "2026-01-03T00:00:00Z", "2026-01-04T00:00:00Z", "default", "rev-1") + insert("INSERT INTO invitecode_qualification_facts(fact_id, invitation_id, policy_id, " + + "qualification_revision, condition_id, outcome, recorded_at) VALUES (?, ?, ?, ?, ?, ?, ?)", + UUID.randomUUID().toString(), invitation.toString(), "default", "rev-1", "playtime", "PASSED", "2026-01-04T00:00:00Z") + insert("INSERT INTO invitecode_audit_records(audit_id, action, actor, reason, occurred_at, " + + "invitation_id, player_id, details_kind) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", + UUID.randomUUID().toString(), "QUALIFIED", "admin", "accepted", "2026-01-04T00:00:00Z", + invitation.toString(), invitee.toString(), "NONE") + insert("INSERT INTO invitecode_player_login_days(player_id, login_date) VALUES (?, ?)", + invitee.toString(), "2026-01-02") + insert("INSERT INTO invitecode_player_network_hashes(player_id, key_id, network_hash, observed_at, expires_at) " + + "VALUES (?, ?, ?, ?, ?)", player.id.toString(), keyId, "a".repeat(64), + "2026-01-01T00:00:00Z", "2027-01-01T00:00:00Z") + insert("INSERT INTO invitecode_reserved_code_hashes(code_hash, key_id) VALUES (?, ?)", "b".repeat(64), keyId) + } + DriverManager.getConnection(adminUrl, user, password).use { connection -> + connection.createStatement().use { + it.execute("CREATE DATABASE $firstDb") + it.execute("CREATE DATABASE $secondDb") + } + } + try { + val mysqlOptions = arrayOf( + "--mysql-host", host!!, "--mysql-port", port.toString(), "--mysql-username", user, + "--mysql-password-env", "TEST_PASSWORD", "--mysql-secret-env", "TEST_SECRET", + "--mysql-tls", "REQUIRED", "--stopped", "--apply", + ) + val mysqlDump = directory.resolve("synthetic-dump.sql") + // Only exercises the CLI's nonempty-dump gate; restore testing uses real dumps outside this test. + Files.write(mysqlDump, "-- isolated test dump marker\n".toByteArray(StandardCharsets.UTF_8)) + OfflineStorageTransferMain.execute( + arrayOf("--from-backend", "sqlite", "--from-file", source.toString(), + "--from-secret-file", key.toString(), "--to-backend", "mysql", + "--mysql-database", firstDb, "--backup", directory.resolve("source-backup.db").toString()) + mysqlOptions, + lookup, + ) + assertMysqlActionState(host, port, firstDb, user, password!!, secret, action, pendingAction) + DriverManager.getConnection( + "jdbc:mysql://$host:$port/$firstDb?sslMode=REQUIRED&connectionTimeZone=UTC", user, password, + ).use { + val activeWriter = assertThrows(IllegalArgumentException::class.java) { + OfflineStorageTransferMain.execute( + arrayOf("--from-backend", "mysql", "--to-backend", "json", "--to-file", json.toString(), + "--to-secret-file", key.toString(), "--mysql-database", firstDb) + mysqlOptions.dropLast(1), + lookup, + ) + } + assertTrue(activeWriter.message!!.contains("其他 MySQL 連線")) + } + OfflineStorageTransferMain.execute( + arrayOf("--from-backend", "mysql", "--to-backend", "json", "--to-file", json.toString(), + "--to-secret-file", key.toString(), "--mysql-database", firstDb, + "--backup", mysqlDump.toString()) + mysqlOptions, + lookup, + ) + OfflineStorageTransferMain.execute( + arrayOf("--from-backend", "json", "--from-file", json.toString(), + "--from-secret-file", key.toString(), "--to-backend", "mysql", + "--mysql-database", secondDb, "--backup", directory.resolve("json-backup.json").toString()) + mysqlOptions, + lookup, + ) + assertMysqlActionState(host, port, secondDb, user, password, secret, action, pendingAction) + OfflineStorageTransferMain.execute( + arrayOf("--from-backend", "mysql", "--to-backend", "sqlite", "--to-file", result.toString(), + "--to-secret-file", key.toString(), "--mysql-database", secondDb, + "--backup", mysqlDump.toString()) + mysqlOptions, + lookup, + ) + SqliteInviteCodeStorage.open(result, guard).use { storage -> + assertEquals(player, storage.player(player.id)) + assertStoredUncertainAction(storage, action, pendingAction) + } + SqliteSnapshotAccess.withConnection(result, guard) { connection -> + listOf("invitecode_codes", "invitecode_invitations", "invitecode_qualification_facts", + "invitecode_audit_records", "invitecode_player_login_days", + "invitecode_player_network_hashes", "invitecode_reserved_code_hashes").forEach { table -> + connection.createStatement().use { statement -> + statement.executeQuery("SELECT COUNT(*) FROM $table").use { rows -> + rows.next() + assertEquals(1, rows.getInt(1), table) + } + } + } + } + } finally { + DriverManager.getConnection(adminUrl, user, password).use { connection -> + connection.createStatement().use { + it.execute("DROP DATABASE IF EXISTS $firstDb") + it.execute("DROP DATABASE IF EXISTS $secondDb") + } + } + } + } + + @Test + fun `MySQL import trigger failure rolls back and keeps transfer guard until retry in a new database`() { + val host = System.getenv("INVITECODE_TEST_MYSQL_HOST") + val password = System.getenv("INVITECODE_TEST_MYSQL_PASSWORD") + assumeTrue(!host.isNullOrBlank() && !password.isNullOrBlank()) + val mysqlHost = requireNotNull(host) + val mysqlPassword = requireNotNull(password) + val port = System.getenv("INVITECODE_TEST_MYSQL_PORT")?.toIntOrNull() ?: 3306 + val user = System.getenv("INVITECODE_TEST_MYSQL_USER") ?: "root" + val failedDatabase = databaseName() + val retryDatabase = databaseName() + val keyBytes = ByteArray(32) { 19 } + val secret = Base64.getEncoder().encodeToString(keyBytes) + val keyId = NetworkAddressHasher.fromBase64(secret).use { it.keyId } + val environment: (String) -> String? = { name -> + when (name) { + "TEST_PASSWORD" -> password + "TEST_SECRET" -> secret + else -> null + } + } + val config = MysqlConfiguration( + mysqlHost, port, failedDatabase, user, "${'$'}{TEST_PASSWORD}", "${'$'}{TEST_SECRET}", + Duration.ofSeconds(10), MysqlTlsMode.REQUIRED, + ) + val source = directory.resolve("rollback-source.db") + val player = StoredPlayer(UUID.randomUUID(), Instant.parse("2026-02-01T00:00:00Z"), "SourcePlayer") + val delivery = StoredRewardDelivery( + UUID.randomUUID(), null, "recovery-check", RewardDeliveryStatus.PENDING, + "recovery-delivery:${player.id}", player.firstSeenAt, player.firstSeenAt, + ) + val action = StoredRewardAction( + UUID.randomUUID(), delivery.id, null, player.id, 0, "MESSAGE", "keep source", + RewardActionStatus.PENDING, "recovery-action:${player.id}", player.firstSeenAt, player.firstSeenAt, + ) + SqliteSchemaMigrator(source, guard).migrate() + SqliteInviteCodeStorage.open(source, guard).use { storage -> + storage.savePlayer(player) + storage.saveRewardDelivery(delivery, listOf(action)) + storage.saveRewardAction(action.copy( + status = RewardActionStatus.PROCESSING, + updatedAt = player.firstSeenAt.plusSeconds(1), + )) + assertEquals(1, storage.recoverInterruptedRewardActions(player.firstSeenAt.plusSeconds(2))) + } + val snapshot = SqliteSnapshotAccess.withConnection(source, guard) { connection -> + OfflineStorageTransfer.export(connection, StorageDialect.SQLITE, keyId) + } + val original = Files.readAllBytes(source) + val backup = directory.resolve("rollback-source-backup.db") + Files.copy(source, backup) + val adminUrl = "jdbc:mysql://$mysqlHost:$port/?sslMode=REQUIRED&connectionTimeZone=UTC" + DriverManager.getConnection(adminUrl, user, mysqlPassword).use { connection -> + connection.createStatement().use { + it.execute("CREATE DATABASE $failedDatabase") + it.execute("CREATE DATABASE $retryDatabase") + } + } + try { + val failedConfig = config + val failedPool = MysqlInviteCodeStorage.createPool(failedConfig, mysqlPassword) + failedPool.use { pool -> + MysqlSchemaMigrator(pool, guard).migrate() + pool.connection.use { connection -> + // Storage-level integration: the CLI has no stable fault-injection seam. + connection.createStatement().use { + it.execute( + "CREATE TRIGGER reject_transfer_action BEFORE INSERT ON invitecode_reward_actions " + + "FOR EACH ROW SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'injected transfer failure'", + ) + } + } + val error = assertThrows(StorageTransferException::class.java) { + pool.connection.use { connection -> + OfflineStorageTransfer.`import`(connection, StorageDialect.MYSQL, snapshot) + } + } + assertTrue(error.message.orEmpty().contains("import")) + assertEquals("45000", (error.cause as? java.sql.SQLException)?.sqlState) + pool.connection.use { connection -> + assertEquals(true, connection.metaData.getTables( + connection.catalog, null, "invitecode_transfer_guard", arrayOf("TABLE"), + ).use { it.next() }) + assertEquals(0L, rowCount(connection, "invitecode_players")) + assertEquals(0L, rowCount(connection, "invitecode_reward_deliveries")) + assertEquals(0L, rowCount(connection, "invitecode_reward_actions")) + } + } + + val blocked = assertThrows(MysqlStorageException::class.java) { + MysqlRuntimeBootstrap(config, guard, environment).initializeOrOpen() + } + assertTrue(blocked.message.orEmpty().contains("transfer is incomplete")) + assertTrue(original.contentEquals(Files.readAllBytes(source))) + assertTrue(original.contentEquals(Files.readAllBytes(backup))) + SqliteInviteCodeStorage.open(source, guard).use { storage -> + assertEquals(player, storage.player(player.id)) + assertStoredUncertainAction(storage, action) + } + + val retryConfig = config.copy(database = retryDatabase) + MysqlInviteCodeStorage.createPool(retryConfig, mysqlPassword).use { pool -> + MysqlSchemaMigrator(pool, guard).migrate() + pool.connection.use { connection -> + OfflineStorageTransfer.`import`(connection, StorageDialect.MYSQL, snapshot) + OfflineStorageTransfer.verify(connection, StorageDialect.MYSQL, snapshot) + OfflineStorageTransfer.releaseMysqlTransferGuard(connection) + } + } + val reopened = MysqlRuntimeBootstrap(retryConfig, guard, environment).initializeOrOpen() + try { + assertEquals(false, reopened.initialized) + assertEquals(player, reopened.storage.player(player.id)) + assertStoredUncertainAction(reopened.storage, action) + } finally { + reopened.storage.close() + reopened.networkHasher.close() + } + } finally { + DriverManager.getConnection(adminUrl, user, mysqlPassword).use { connection -> + connection.createStatement().use { + it.execute("DROP DATABASE IF EXISTS $failedDatabase") + it.execute("DROP DATABASE IF EXISTS $retryDatabase") + } + } + } + } + + private fun assertMysqlActionState( + host: String, + port: Int, + database: String, + username: String, + password: String, + secret: String, + expected: StoredRewardAction, + pendingExpected: StoredRewardAction, + ) { + val config = MysqlConfiguration( + host, port, database, username, "${'$'}{TEST_PASSWORD}", "${'$'}{TEST_SECRET}", + Duration.ofSeconds(10), MysqlTlsMode.REQUIRED, + ) + val environment: (String) -> String? = { name -> + when (name) { + "TEST_PASSWORD" -> password + "TEST_SECRET" -> secret + else -> null + } + } + val reopened = MysqlRuntimeBootstrap(config, guard, environment).initializeOrOpen() + try { + assertStoredUncertainAction(reopened.storage, expected, pendingExpected) + } finally { + reopened.storage.close() + reopened.networkHasher.close() + } + } + + private fun assertStoredUncertainAction( + storage: InviteCodeStorage, + expected: StoredRewardAction, + pendingExpected: StoredRewardAction? = null, + ) { + val stored = storage.rewardAction(expected.id) + assertEquals(RewardActionStatus.UNCERTAIN, stored?.status) + assertEquals(expected.idempotencyKey, stored?.idempotencyKey) + val transitions = storage.rewardActionTransitions(expected.id) + assertEquals( + listOf( + null to RewardActionStatus.PENDING, + RewardActionStatus.PENDING to RewardActionStatus.PROCESSING, + RewardActionStatus.PROCESSING to RewardActionStatus.UNCERTAIN, + ), + transitions.map { it.previousStatus to it.currentStatus }, + ) + assertEquals( + listOf( + expected.createdAt, + expected.createdAt.plusSeconds(1), + expected.createdAt.plusSeconds(2), + ), + transitions.map { it.occurredAt }, + ) + assertEquals("Interrupted while processing; delivery result is unknown.", transitions.last().lastError) + val pendingActions = storage.pendingRewardActions(expected.recipientId) + assertEquals(false, pendingActions.any { it.id == expected.id }) + pendingExpected?.let { pending -> + assertEquals(RewardActionStatus.PENDING, storage.rewardAction(pending.id)?.status) + assertEquals(pending.idempotencyKey, storage.rewardAction(pending.id)?.idempotencyKey) + assertEquals(1, pendingActions.count { it.id == pending.id && it.position == 1 }) + } + } + + private fun rowCount(connection: java.sql.Connection, table: String): Long = + connection.createStatement().use { statement -> + statement.executeQuery("SELECT COUNT(*) FROM $table").use { rows -> + rows.next() + rows.getLong(1) + } + } + + private fun databaseName(): String = "invitecode_test_${UUID.randomUUID().toString().replace("-", "")}" +} diff --git a/invitecode-storage-json/src/main/kotlin/io/github/command1264/invitecode/storage/json/JsonInviteCodeStorage.kt b/invitecode-storage-json/src/main/kotlin/io/github/command1264/invitecode/storage/json/JsonInviteCodeStorage.kt index ea46f04..935d5e6 100644 --- a/invitecode-storage-json/src/main/kotlin/io/github/command1264/invitecode/storage/json/JsonInviteCodeStorage.kt +++ b/invitecode-storage-json/src/main/kotlin/io/github/command1264/invitecode/storage/json/JsonInviteCodeStorage.kt @@ -102,6 +102,15 @@ class JsonInviteCodeStorage private constructor( fun previewAnonymization(playerId: UUID): AnonymizationPreview = delegate.previewAnonymization(playerId) fun anonymizePlayer(playerId: UUID): AnonymizationResult = persist { delegate.anonymizePlayer(playerId) } + /** The file lock remains held while an offline migration reads the loaded snapshot. */ + fun inspectOffline(operation: (Connection) -> T): T = synchronized(this) { + check(!closed && !failed) { "JSON storage is closed or failed." } + SqliteSnapshotAccess.withConnection(database, guard) { connection -> + connection.createStatement().use { it.execute("PRAGMA query_only=ON") } + operation(connection) + } + } + override fun close() = synchronized(this) { if (closed) return@synchronized closed = true @@ -115,6 +124,49 @@ class JsonInviteCodeStorage private constructor( companion object { const val FORMAT_VERSION = 1 + /** Publish a new JSON destination only after the imported SQLite image passes verification. */ + fun createOfflineFromSqlite( + file: Path, guard: BlockingOperationGuard, importAndVerify: (Connection) -> Unit, + ) { + guard.checkAllowed() + val target = file.toAbsolutePath().normalize() + require(Files.isDirectory(requireNotNull(target.parent))) { "JSON destination directory must exist." } + require(!Files.exists(target)) { "JSON destination already exists; do not overwrite it." } + val lockChannel = FileChannel.open(target.resolveSibling("${target.fileName}.lock"), CREATE, WRITE) + val lock = try { + lockChannel.tryLock() ?: throw JsonStorageException("JSON destination is already open; stop every instance.") + } catch (error: Exception) { + lockChannel.close() + throw error + } + val workingDirectory = try { Files.createTempDirectory("invitecode-json-transfer-") } catch (error: Exception) { + lock.release() + lockChannel.close() + throw error + } + val database = workingDirectory.resolve("working.db") + var staged: Path? = null + try { + val stagedFile = Files.createTempFile(target.parent, ".${target.fileName}.", ".staging") + staged = stagedFile + SqliteSchemaMigrator(database, guard).migrate() + SqliteSnapshotAccess.withConnection(database, guard, importAndVerify) + writeSnapshot(stagedFile, exportSnapshot(database, guard)) + require(!Files.exists(target)) { "JSON destination appeared while transfer was in progress." } + // The hard link publishes complete bytes and cannot replace a concurrently created target. + Files.createLink(target, stagedFile) + } finally { + try { + staged?.let(Files::deleteIfExists) + Files.deleteIfExists(database) + Files.deleteIfExists(workingDirectory) + } finally { + lock.release() + lockChannel.close() + } + } + } + /** Offline-only, explicit snapshot migration; the .previous file keeps the original snapshot. */ fun migrateV8ToV9(file: Path, guard: BlockingOperationGuard) { guard.checkAllowed() diff --git a/invitecode-storage-json/src/test/kotlin/io/github/command1264/invitecode/storage/json/JsonOfflineTransferTest.kt b/invitecode-storage-json/src/test/kotlin/io/github/command1264/invitecode/storage/json/JsonOfflineTransferTest.kt new file mode 100644 index 0000000..de02841 --- /dev/null +++ b/invitecode-storage-json/src/test/kotlin/io/github/command1264/invitecode/storage/json/JsonOfflineTransferTest.kt @@ -0,0 +1,67 @@ +package io.github.command1264.invitecode.storage.json + +import io.github.command1264.invitecode.storage.sql.BlockingOperationGuard +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import java.nio.file.Files +import java.nio.file.Path +import java.util.UUID + +class JsonOfflineTransferTest { + @TempDir lateinit var directory: Path + private val guard = BlockingOperationGuard { } + + @Test + fun `destination is published only after import succeeds and survives restart`() { + val destination = directory.resolve("destination.json") + val id = UUID.randomUUID() + assertThrows(IllegalStateException::class.java) { + JsonInviteCodeStorage.createOfflineFromSqlite(destination, guard) { connection -> + connection.prepareStatement( + "INSERT INTO invitecode_players(player_id, first_seen_at, last_known_name) VALUES (?, ?, ?)", + ).use { statement -> + statement.setString(1, id.toString()) + statement.setString(2, "2026-01-01T00:00:00Z") + statement.setString(3, "Alice") + statement.executeUpdate() + } + error("verification failed") + } + } + assertFalse(Files.exists(destination)) + + JsonInviteCodeStorage.createOfflineFromSqlite(destination, guard) { connection -> + connection.prepareStatement( + "INSERT INTO invitecode_players(player_id, first_seen_at, last_known_name) VALUES (?, ?, ?)", + ).use { statement -> + statement.setString(1, id.toString()) + statement.setString(2, "2026-01-01T00:00:00Z") + statement.setString(3, "Alice") + statement.executeUpdate() + } + } + assertTrue(Files.isRegularFile(destination)) + JsonInviteCodeStorage.open(destination, guard).use { storage -> + assertEquals("Alice", storage.player(id)?.lastKnownName) + } + assertThrows(IllegalArgumentException::class.java) { + JsonInviteCodeStorage.createOfflineFromSqlite(destination, guard) { } + } + } + + @Test + fun `destination created during transfer is never replaced`() { + val destination = directory.resolve("concurrent.json") + val other = "another writer".toByteArray() + assertThrows(IllegalArgumentException::class.java) { + JsonInviteCodeStorage.createOfflineFromSqlite(destination, guard) { + Files.write(destination, other) + } + } + assertTrue(other.contentEquals(Files.readAllBytes(destination))) + } +} diff --git a/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/MysqlSchemaMigrator.kt b/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/MysqlSchemaMigrator.kt index 41d5782..386465d 100644 --- a/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/MysqlSchemaMigrator.kt +++ b/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/MysqlSchemaMigrator.kt @@ -45,12 +45,13 @@ class MysqlSchemaMigrator( private fun migrateLocked(connection: Connection, schema: String) { val ledgerExists = tableExists(connection, schema, LEDGER) if (!ledgerExists) { - val existing = connection.metaData.getTables(schema, null, "%", arrayOf("TABLE", "VIEW")).use { rows -> - rows.next() + val existingObjects = connection.metaData.getTables(schema, null, "%", arrayOf("TABLE", "VIEW")).use { rows -> + buildSet { while (rows.next()) add(rows.getString("TABLE_NAME")) } } - if (existing) throw MysqlStorageException( + if (existingObjects.isNotEmpty() && existingObjects != setOf(TRANSFER_GUARD)) throw MysqlStorageException( "MySQL database is not empty and has no migration ledger; preserve the database and inspect it manually.", ) + if (existingObjects == setOf(TRANSFER_GUARD)) OfflineStorageTransfer.verifyMysqlTransferGuard(connection) connection.createStatement().use { statement -> statement.execute(LEDGER_DDL) } } val otherVersions = connection.createStatement().use { statement -> @@ -138,6 +139,7 @@ class MysqlSchemaMigrator( companion object { const val CURRENT_VERSION = 2 + internal const val TRANSFER_GUARD = "invitecode_transfer_guard" private const val LEDGER = "invitecode_schema_migrations" private const val LEDGER_DDL = """ CREATE TABLE invitecode_schema_migrations ( diff --git a/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/OfflineStorageTransfer.kt b/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/OfflineStorageTransfer.kt new file mode 100644 index 0000000..7404872 --- /dev/null +++ b/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/OfflineStorageTransfer.kt @@ -0,0 +1,456 @@ +package io.github.command1264.invitecode.storage.sql + +import java.sql.Connection +import java.sql.DatabaseMetaData +import java.sql.PreparedStatement +import java.sql.ResultSet +import java.sql.SQLException +import java.sql.Types + +/** Backend whose current, already-initialized schema is used by an offline transfer. */ +enum class StorageDialect { SQLITE, MYSQL } + +/** Values have deliberately narrow types so the portable representation is independent of JDBC drivers. */ +sealed class PortableValue { + data class Text(val value: String) : PortableValue() + data class Integer(val value: Long) : PortableValue() + object Null : PortableValue() +} + +data class PortableRow(val values: List) + +data class PortableTable(val name: String, val columns: List, val rows: List) + +/** Immutable-by-convention payload. Table and column lists are checked against the built-in whitelist on use. */ +data class PortableStorageSnapshot( + val sourceDialect: StorageDialect, + val sourceSchemaVersion: Int, + val networkKeyId: String, + val tables: List, + val formatVersion: Int = FORMAT_VERSION, +) { + companion object { const val FORMAT_VERSION = 1 } +} + +/** + * Transfers a stopped backend's business records. This class never initializes schemas and never issues + * source-side writes. The caller must stop every writer and initialize both schemas before calling it. + */ +object OfflineStorageTransfer { + /** + * Exports all business records. SQLite has no metadata table, so [keyId] comes from the caller; + * MySQL verifies the supplied ID against its unique `invitecode_metadata` row. + */ + @JvmStatic + fun export( + connection: Connection, + dialect: StorageDialect, + keyId: String, + ): PortableStorageSnapshot = guarded("export") { + requireCurrentSchema(connection, dialect) + when (dialect) { + StorageDialect.SQLITE -> Unit + StorageDialect.MYSQL -> require(readMysqlKeyId(connection) == keyId) { + "Supplied network key ID differs from MySQL metadata." + } + } + validateKeyId(keyId) + requireSourceIntegrity(connection, dialect) + val tables = BUSINESS_TABLES.map { spec -> readTable(connection, spec) } + PortableStorageSnapshot(dialect, currentVersion(dialect), keyId, tables).also(::validateSnapshot) + } + + /** Imports atomically into an empty business schema; identical pre-bound MySQL key metadata is allowed. */ + @JvmStatic + fun `import`(connection: Connection, dialect: StorageDialect, snapshot: PortableStorageSnapshot) { + guarded("import") { + validateSnapshot(snapshot) + requireCurrentSchema(connection, dialect) + requireEmptyDestination(connection, dialect, snapshot.networkKeyId) + val originalAutoCommit = connection.autoCommit + check(originalAutoCommit) { + "Storage import requires an idle connection in auto-commit mode so it owns the complete transaction." + } + if (dialect == StorageDialect.MYSQL) createMysqlTransferGuard(connection) + try { + if (dialect == StorageDialect.SQLITE) { + connection.createStatement().use { it.execute("PRAGMA foreign_keys = ON") } + } + connection.autoCommit = false + if (dialect == StorageDialect.MYSQL) ensureMysqlMetadataKey(connection, snapshot.networkKeyId) + BUSINESS_TABLES.forEachIndexed { index, spec -> + val table = snapshot.tables[index] + insertTable(connection, spec, table) + } + verifyRows(connection, snapshot) + connection.commit() + } catch (error: Exception) { + try { + connection.rollback() + } catch (rollbackError: SQLException) { + error.addSuppressed(rollbackError) + throw StorageTransferException( + "Storage import failed and rollback also failed; destination state is uncertain. " + + "Keep both backends offline and inspect the destination before retrying.", error, + ) + } + throw if (error is StorageTransferException) error else StorageTransferException( + "Storage import failed; the destination transaction was rolled back. " + + "Inspect the cause before retrying.", error, + ) + } finally { + try { + connection.autoCommit = originalAutoCommit + } catch (restoreError: SQLException) { + throw StorageTransferException( + "Storage import completed or rolled back, but the connection mode could not be restored; " + + "close the connection and inspect the destination state.", restoreError, + ) + } + } + } + } + + /** Compares every persistent business cell and checks current schema plus destination key identity. */ + @JvmStatic + fun verify(connection: Connection, dialect: StorageDialect, snapshot: PortableStorageSnapshot) { + guarded("verify") { + validateSnapshot(snapshot) + requireCurrentSchema(connection, dialect) + if (dialect == StorageDialect.MYSQL) { + require(readMysqlKeyId(connection) == snapshot.networkKeyId) { + "Destination MySQL network_key_id does not match the snapshot." + } + } + verifyRows(connection, snapshot) + } + } + + /** Creates the persistent MySQL maintenance marker before destination initialization or writes. */ + @JvmStatic + fun createMysqlTransferGuard(connection: Connection) { + guarded("create MySQL transfer guard") { + connection.createStatement().use { it.execute(MYSQL_TRANSFER_GUARD_DDL) } + verifyMysqlTransferGuard(connection) + } + } + + /** Removes the MySQL maintenance marker only after the caller has completed all transfer verification. */ + @JvmStatic + fun releaseMysqlTransferGuard(connection: Connection) { + guarded("release MySQL transfer guard") { + requireCurrentSchema(connection, StorageDialect.MYSQL) + verifyMysqlTransferGuard(connection) + connection.createStatement().use { it.execute("DROP TABLE invitecode_transfer_guard") } + } + } + + internal fun verifyMysqlTransferGuard(connection: Connection) { + val columns = connection.metaData.getColumns(connection.catalog, null, MYSQL_TRANSFER_GUARD, null).use { rows -> + buildList { + while (rows.next()) add( + Triple(rows.getString("COLUMN_NAME"), rows.getString("TYPE_NAME").uppercase(), rows.getInt("NULLABLE")), + ) + } + } + check(columns == listOf(Triple("singleton", "INT", DatabaseMetaData.columnNoNulls))) { + "MySQL transfer guard table has an unexpected structure; preserve it and inspect the database." + } + val primaryKey = connection.metaData.getPrimaryKeys(connection.catalog, null, MYSQL_TRANSFER_GUARD).use { rows -> + if (rows.next()) rows.getString("COLUMN_NAME") else null + } + check(primaryKey == "singleton") { "MySQL transfer guard has an unexpected primary key." } + val properties = connection.prepareStatement( + "SELECT ENGINE FROM information_schema.TABLES WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?", + ).use { statement -> + statement.setString(1, requireNotNull(connection.catalog)) + statement.setString(2, MYSQL_TRANSFER_GUARD) + statement.executeQuery().use { rows -> if (rows.next()) rows.getString(1) else null } + } + check(properties.equals("InnoDB", ignoreCase = true)) { "MySQL transfer guard must use InnoDB." } + val checkCount = connection.prepareStatement( + "SELECT COUNT(*) FROM information_schema.TABLE_CONSTRAINTS " + + "WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND CONSTRAINT_TYPE = 'CHECK'", + ).use { statement -> + statement.setString(1, requireNotNull(connection.catalog)) + statement.setString(2, MYSQL_TRANSFER_GUARD) + statement.executeQuery().use { it.next(); it.getInt(1) } + } + check(checkCount == 1) { "MySQL transfer guard has an unexpected check constraint." } + val rows = connection.createStatement().use { statement -> + statement.executeQuery("SELECT COUNT(*) FROM $MYSQL_TRANSFER_GUARD").use { it.next(); it.getLong(1) } + } + check(rows == 0L) { "MySQL transfer guard must be a marker table without data rows." } + } + + private fun validateSnapshot(snapshot: PortableStorageSnapshot) { + require(snapshot.formatVersion == PortableStorageSnapshot.FORMAT_VERSION) { + "Unsupported portable snapshot format ${snapshot.formatVersion}." + } + require(snapshot.sourceSchemaVersion == currentVersion(snapshot.sourceDialect)) { + "Snapshot source schema version ${snapshot.sourceSchemaVersion} is not current for ${snapshot.sourceDialect}." + } + validateKeyId(snapshot.networkKeyId) + require(snapshot.tables.size == BUSINESS_TABLES.size) { + "Snapshot must contain exactly ${BUSINESS_TABLES.size} business tables." + } + BUSINESS_TABLES.forEachIndexed { index, spec -> + val table = snapshot.tables[index] + require(table.name == spec.name && table.columns == spec.columns.map(Column::name)) { + "Snapshot table layout is invalid at position $index." + } + require(table.rows.all { it.values.size == spec.columns.size }) { + "Snapshot contains a row with an invalid column count in ${spec.name}." + } + table.rows.forEach { row -> + row.values.forEachIndexed { columnIndex, value -> + val column = spec.columns[columnIndex] + require(value == PortableValue.Null && column.nullable || valueMatches(column.type, value)) { + "Snapshot contains an invalid value for ${spec.name}.${column.name}." + } + } + } + } + requireKeyedRowsMatch(snapshot.tables, snapshot.networkKeyId) + } + + private fun requireKeyedRowsMatch(tables: List, keyId: String) { + listOf("invitecode_player_network_hashes", "invitecode_reserved_code_hashes").forEach { name -> + val table = tables.single { it.name == name } + val keyColumn = table.columns.indexOf("key_id") + check(keyColumn >= 0 && table.rows.all { it.values[keyColumn] == PortableValue.Text(keyId) }) { + "$name contains rows from another anti-abuse key; restore the matching key or resolve those rows before transfer." + } + } + } + + private fun requireCurrentSchema(connection: Connection, dialect: StorageDialect) { + when (dialect) { + StorageDialect.SQLITE -> { + val version = connection.createStatement().use { statement -> + statement.executeQuery("SELECT version FROM invitecode_schema_version WHERE singleton = 1").use { rows -> + check(rows.next()) { "SQLite schema version row is missing; initialize the schema first." } + rows.getInt(1).also { check(!rows.next()) { "SQLite schema version row is not unique." } } + } + } + check(version == SqliteSchemaMigrator.currentVersion) { + "SQLite schema version $version is not current (${SqliteSchemaMigrator.currentVersion})." + } + } + StorageDialect.MYSQL -> MysqlSchemaMigrator.requireCurrent(connection) + } + } + + private fun requireSourceIntegrity(connection: Connection, dialect: StorageDialect) { + if (dialect == StorageDialect.SQLITE) { + connection.createStatement().use { statement -> + statement.executeQuery("PRAGMA integrity_check").use { rows -> + check(rows.next() && rows.getString(1) == "ok" && !rows.next()) { + "Source integrity check failed; keep the source offline and restore or repair a verified backup." + } + } + statement.executeQuery("PRAGMA foreign_key_check").use { rows -> + check(!rows.next()) { + "Source foreign-key integrity check failed; restore or repair missing related records before transfer." + } + } + } + return + } + // Re-enabling FOREIGN_KEY_CHECKS does not validate rows previously written while disabled. + // Use the current schema's relationships; never interpolate unchecked metadata as SQL names. + BUSINESS_TABLES.forEach { child -> + val keys = connection.metaData.getImportedKeys(connection.catalog, null, child.name).use { rows -> + buildList { + while (rows.next()) add(Triple( + rows.getString("FKCOLUMN_NAME"), rows.getString("PKTABLE_NAME"), rows.getString("PKCOLUMN_NAME"), + )) + } + } + keys.forEach { (childColumn, parentName, parentColumn) -> + val parent = BUSINESS_TABLES.singleOrNull { it.name == parentName } + check(child.columns.any { it.name == childColumn } && + parent != null && parent.columns.any { it.name == parentColumn }) { + "Source foreign-key layout is unsupported; inspect the schema before transfer." + } + connection.createStatement().use { statement -> + statement.executeQuery( + "SELECT 1 FROM ${child.name} child LEFT JOIN $parentName parent " + + "ON child.$childColumn = parent.$parentColumn " + + "WHERE child.$childColumn IS NOT NULL AND parent.$parentColumn IS NULL LIMIT 1", + ).use { rows -> + check(!rows.next()) { + "Source foreign-key integrity check failed in ${child.name}; " + + "restore or repair missing related records before transfer." + } + } + } + } + } + } + + private fun currentVersion(dialect: StorageDialect): Int = when (dialect) { + StorageDialect.SQLITE -> SqliteSchemaMigrator.currentVersion + StorageDialect.MYSQL -> MysqlSchemaMigrator.CURRENT_VERSION + } + + private fun readMysqlKeyId(connection: Connection): String = connection.prepareStatement( + "SELECT network_key_id FROM invitecode_metadata WHERE singleton = ?", + ).use { statement -> + statement.setInt(1, 1) + statement.executeQuery().use { rows -> + check(rows.next()) { "MySQL network_key_id metadata is missing; bind it before transfer." } + rows.getString(1).also { check(!rows.next()) { "MySQL metadata singleton row is not unique." } } + } + } + + private fun ensureMysqlMetadataKey(connection: Connection, keyId: String) { + val existing = connection.createStatement().use { statement -> + statement.executeQuery("SELECT network_key_id FROM invitecode_metadata WHERE singleton = 1").use { rows -> + if (rows.next()) rows.getString(1).also { check(!rows.next()) { "MySQL metadata singleton row is not unique." } } + else null + } + } + if (existing == null) connection.prepareStatement( + "INSERT INTO invitecode_metadata(singleton, network_key_id) VALUES (?, ?)", + ).use { statement -> + statement.setInt(1, 1) + statement.setString(2, keyId) + check(statement.executeUpdate() == 1) { "Could not bind destination MySQL metadata to the snapshot key ID." } + } else check(existing == keyId) { "Destination MySQL network_key_id differs from the snapshot." } + } + + private fun requireEmptyDestination(connection: Connection, dialect: StorageDialect, expectedKey: String) { + BUSINESS_TABLES.forEach { spec -> + val count = connection.createStatement().use { statement -> + statement.executeQuery("SELECT COUNT(*) FROM ${spec.name}").use { rows -> rows.next(); rows.getLong(1) } + } + check(count == 0L) { "Destination table ${spec.name} is not empty; refusing to overwrite existing data." } + } + if (dialect == StorageDialect.MYSQL) { + val rows = connection.createStatement().use { statement -> + statement.executeQuery("SELECT singleton, network_key_id FROM invitecode_metadata").use { result -> + val values = mutableListOf>() + while (result.next()) values += result.getInt(1) to result.getString(2) + values + } + } + check(rows.isEmpty() || rows == listOf(1 to expectedKey)) { + "Destination MySQL metadata must be empty or contain only the matching singleton network_key_id row." + } + } + } + + private fun readTable(connection: Connection, spec: TableSpec): PortableTable { + val sql = "SELECT ${spec.columns.joinToString(", ") { it.name }} FROM ${spec.name}" + val rows = connection.createStatement().use { statement -> + statement.executeQuery(sql).use { result -> + buildList { + while (result.next()) add(PortableRow(spec.columns.mapIndexed { index, column -> + readValue(result, index + 1, column) + })) + } + } + } + return PortableTable(spec.name, spec.columns.map(Column::name), rows) + } + + private fun readValue(result: ResultSet, index: Int, column: Column): PortableValue = when (column.type) { + ValueType.TEXT -> result.getString(index)?.let(PortableValue::Text) ?: PortableValue.Null + ValueType.INTEGER -> { + val value = result.getLong(index) + if (result.wasNull()) PortableValue.Null else PortableValue.Integer(value) + } + } + + private fun insertTable(connection: Connection, spec: TableSpec, table: PortableTable) { + if (table.rows.isEmpty()) return + val sql = "INSERT INTO ${spec.name} (${spec.columns.joinToString(", ") { it.name }}) " + + "VALUES (${spec.columns.joinToString(", ") { "?" }})" + connection.prepareStatement(sql).use { statement -> + table.rows.forEach { row -> + row.values.forEachIndexed { index, value -> bind(statement, index + 1, value, spec.columns[index]) } + statement.addBatch() + } + val outcomes = statement.executeBatch() + check(outcomes.size == table.rows.size && outcomes.all { it >= 0 || it == java.sql.Statement.SUCCESS_NO_INFO }) { + "Destination did not insert every row of ${spec.name}." + } + } + } + + private fun bind(statement: PreparedStatement, index: Int, value: PortableValue, column: Column) { + when (value) { + is PortableValue.Text -> statement.setString(index, value.value) + is PortableValue.Integer -> statement.setLong(index, value.value) + PortableValue.Null -> statement.setNull(index, if (column.type == ValueType.TEXT) Types.VARCHAR else Types.BIGINT) + } + } + + private fun verifyRows(connection: Connection, snapshot: PortableStorageSnapshot) { + BUSINESS_TABLES.forEachIndexed { index, spec -> + val actual = readTable(connection, spec) + val expected = snapshot.tables[index] + check(actual.rows.size == expected.rows.size) { + "Row count mismatch for ${spec.name}: expected ${expected.rows.size}, found ${actual.rows.size}." + } + check(actual.rows.toSet() == expected.rows.toSet() && actual.rows.size == expected.rows.size) { + "Stored values do not match the snapshot in ${spec.name}." + } + } + } + + private fun valueMatches(type: ValueType, value: PortableValue): Boolean = when (type) { + ValueType.TEXT -> value is PortableValue.Text + ValueType.INTEGER -> value is PortableValue.Integer + } + + private fun validateKeyId(value: String) { + require(Regex("[0-9a-f]{64}").matches(value)) { "network_key_id must be 64 lowercase hexadecimal characters." } + } + + private inline fun guarded(operation: String, block: () -> T): T = try { + block() + } catch (error: StorageTransferException) { + throw error + } catch (error: Exception) { + val detail = if (error is SQLException) { + "SQLState ${error.sqlState ?: "unknown"}, code ${error.errorCode}" + } else { + error.message ?: error.javaClass.simpleName + } + throw StorageTransferException("Storage transfer $operation failed ($detail).", error) + } + + private enum class ValueType { TEXT, INTEGER } + private data class Column(val name: String, val type: ValueType, val nullable: Boolean = false) + private data class TableSpec(val name: String, val columns: List) + private fun text(name: String, nullable: Boolean = false) = Column(name, ValueType.TEXT, nullable) + private fun integer(name: String, nullable: Boolean = false) = Column(name, ValueType.INTEGER, nullable) + + /** SQL names and column lists are fixed here; values are always bound parameters. Order is FK-safe. */ + private val BUSINESS_TABLES = listOf( + TableSpec("invitecode_players", listOf(text("player_id"), text("first_seen_at"), text("last_known_name", true), integer("eligibility_generation"))), + TableSpec("invitecode_codes", listOf(text("code"), text("inviter_id"), text("activated_at"), text("retired_at", true))), + TableSpec("invitecode_invitations", listOf(text("invitation_id"), text("inviter_id"), integer("inviter_eligibility_generation"), text("invitee_id"), integer("invitee_eligibility_generation"), text("status"), text("claimed_at"), text("qualified_at", true), text("qualification_policy_id", true), text("qualification_revision", true))), + TableSpec("invitecode_qualification_facts", listOf(text("fact_id"), text("invitation_id"), text("policy_id"), text("qualification_revision"), text("condition_id"), text("outcome"), text("recorded_at"))), + TableSpec("invitecode_reward_deliveries", listOf(text("delivery_id"), text("invitation_id", true), text("reward_id"), text("status"), text("idempotency_key"), text("created_at"), text("updated_at"))), + TableSpec("invitecode_reward_actions", listOf(text("action_id"), text("reward_delivery_id"), text("invitation_id", true), text("recipient_id"), integer("position"), text("action_type"), text("payload"), text("status"), text("idempotency_key"), text("created_at"), text("updated_at"), text("last_error", true))), + TableSpec("invitecode_audit_records", listOf(text("audit_id"), text("action"), text("actor"), text("reason"), text("occurred_at"), text("invitation_id", true), text("player_id", true), text("details_kind"), text("previous_inviter_id", true), text("new_inviter_id", true), text("qualification_policy_id", true), text("qualification_revision", true))), + TableSpec("invitecode_reward_delivery_transitions", listOf(integer("transition_id"), text("delivery_id"), text("previous_status", true), text("current_status"), text("occurred_at"), text("actor", true), text("reason", true))), + TableSpec("invitecode_reward_action_transitions", listOf(integer("transition_id"), text("action_id"), text("previous_status", true), text("current_status"), text("occurred_at"), text("last_error", true), text("actor", true), text("reason", true))), + TableSpec("invitecode_player_login_days", listOf(text("player_id"), text("login_date"))), + TableSpec("invitecode_player_network_hashes", listOf(text("player_id"), text("key_id"), text("network_hash"), text("observed_at"), text("expires_at"))), + TableSpec("invitecode_reserved_code_hashes", listOf(text("code_hash"), text("key_id"))), + ) + + private const val MYSQL_TRANSFER_GUARD = "invitecode_transfer_guard" + private const val MYSQL_TRANSFER_GUARD_DDL = """ + CREATE TABLE IF NOT EXISTS invitecode_transfer_guard ( + singleton INT NOT NULL PRIMARY KEY, + CONSTRAINT invitecode_transfer_guard_singleton CHECK (singleton = 1) + ) ENGINE=InnoDB + """ +} + +class StorageTransferException(message: String, cause: Throwable? = null) : IllegalStateException(message, cause) diff --git a/invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/MysqlIntegrationTest.kt b/invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/MysqlIntegrationTest.kt index d71ca77..ae476c6 100644 --- a/invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/MysqlIntegrationTest.kt +++ b/invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/MysqlIntegrationTest.kt @@ -41,6 +41,50 @@ class MysqlStorageContractTest : StorageContractTest() { } class MysqlIntegrationTest { + @Test + fun `export rejects orphaned MySQL rows even after foreign key checks are reenabled`() = withMysqlSchema { _, pool -> + MysqlSchemaMigrator(pool, BlockingOperationGuard { }).migrate() + val keyId = "a".repeat(64) + pool.connection.use { connection -> + MysqlSchemaMigrator.bindNetworkKey(connection, keyId) + connection.createStatement().use { it.execute("SET FOREIGN_KEY_CHECKS=0") } + try { + connection.prepareStatement( + "INSERT INTO invitecode_codes(code, inviter_id, activated_at) VALUES (?, ?, ?)", + ).use { statement -> + statement.setString(1, "A1B2C3") + statement.setString(2, UUID.randomUUID().toString()) + statement.setString(3, "2026-01-01T00:00:00Z") + statement.executeUpdate() + } + } finally { + connection.createStatement().use { it.execute("SET FOREIGN_KEY_CHECKS=1") } + } + val failure = assertThrows(StorageTransferException::class.java) { + OfflineStorageTransfer.export(connection, StorageDialect.MYSQL, keyId) + } + assertEquals(true, failure.message.orEmpty().contains("foreign-key")) + connection.createStatement().use { statement -> + statement.executeQuery("SELECT COUNT(*) FROM invitecode_codes").use { rows -> + rows.next() + assertEquals(1, rows.getInt(1)) + } + } + } + } + + @Test + fun `schema migration accepts only the transfer guard before first initialization`() = withMysqlSchema { _, pool -> + pool.connection.use { OfflineStorageTransfer.createMysqlTransferGuard(it) } + assertEquals(MysqlSchemaMigrator.CURRENT_VERSION, MysqlSchemaMigrator(pool, BlockingOperationGuard { }).migrate()) + pool.connection.use { connection -> + MysqlSchemaMigrator.requireCurrent(connection) + OfflineStorageTransfer.verifyMysqlTransferGuard(connection) + OfflineStorageTransfer.releaseMysqlTransferGuard(connection) + assertEquals(false, connection.metaData.getTables(connection.catalog, null, "invitecode_transfer_guard", arrayOf("TABLE")).use { it.next() }) + } + } + @Test fun `MySQL anonymization preserves tombstone and permits a fresh player record`() = withMysqlSchema { _, pool -> val guard = BlockingOperationGuard { } diff --git a/invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/OfflineStorageTransferTest.kt b/invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/OfflineStorageTransferTest.kt new file mode 100644 index 0000000..9742e7a --- /dev/null +++ b/invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/OfflineStorageTransferTest.kt @@ -0,0 +1,180 @@ +package io.github.command1264.invitecode.storage.sql + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import java.nio.file.Path +import java.sql.Connection +import java.sql.DriverManager +import java.util.UUID + +class OfflineStorageTransferTest { + @TempDir lateinit var directory: Path + private val keyId = "a".repeat(64) + + @Test + fun `export rejects historical check constraint violations without repairing the source`() { + val source = database("invalid-generation.db") + SqliteSchemaMigrator(source, BlockingOperationGuard { }).migrate() + connect(source).use { connection -> + connection.createStatement().use { it.execute("PRAGMA ignore_check_constraints=ON") } + connection.prepareStatement( + "INSERT INTO invitecode_players(player_id, first_seen_at, eligibility_generation) VALUES (?, ?, -1)", + ).use { statement -> + statement.setString(1, UUID.randomUUID().toString()) + statement.setString(2, "2026-01-01T00:00:00Z") + statement.executeUpdate() + } + } + connect(source).use { connection -> + val failure = assertThrows(StorageTransferException::class.java) { + OfflineStorageTransfer.export(connection, StorageDialect.SQLITE, keyId) + } + assertEquals(true, failure.message.orEmpty().contains("integrity check failed")) + connection.createStatement().use { statement -> + statement.executeQuery("SELECT eligibility_generation FROM invitecode_players").use { rows -> + rows.next() + assertEquals(-1, rows.getInt(1)) + } + } + } + } + + @Test + fun `sqlite transfer preserves all business rows including rewards transitions and reserved hashes`() { + val source = database("source.db") + val destination = database("destination.db") + SqliteSchemaMigrator(source, BlockingOperationGuard { }).migrate() + SqliteSchemaMigrator(destination, BlockingOperationGuard { }).migrate() + seed(source) + + val snapshot = connect(source).use { OfflineStorageTransfer.export(it, StorageDialect.SQLITE, keyId) } + assertEquals(12, snapshot.tables.size) + assertEquals(keyId, snapshot.networkKeyId) + assertEquals(9, snapshot.sourceSchemaVersion) + + connect(destination).use { OfflineStorageTransfer.`import`(it, StorageDialect.SQLITE, snapshot) } + connect(destination).use { OfflineStorageTransfer.verify(it, StorageDialect.SQLITE, snapshot) } + connect(destination).use { connection -> + assertEquals(1, count(connection, "invitecode_reward_deliveries")) + assertEquals(1, count(connection, "invitecode_reward_actions")) + assertEquals(2, count(connection, "invitecode_reward_delivery_transitions")) + assertEquals(2, count(connection, "invitecode_reward_action_transitions")) + assertEquals(1, count(connection, "invitecode_reserved_code_hashes")) + assertEquals(1, count(connection, "invitecode_player_network_hashes")) + } + } + + @Test + fun `sqlite import rejects a nonempty destination without changing its rows`() { + val source = database("nonempty-source.db") + val destination = database("nonempty-destination.db") + SqliteSchemaMigrator(source, BlockingOperationGuard { }).migrate() + SqliteSchemaMigrator(destination, BlockingOperationGuard { }).migrate() + seed(source) + connect(destination).use { connection -> + connection.prepareStatement( + "INSERT INTO invitecode_players(player_id, first_seen_at) VALUES (?, ?)", + ).use { statement -> + statement.setString(1, UUID.randomUUID().toString()) + statement.setString(2, "2026-01-01T00:00:00Z") + statement.executeUpdate() + } + } + val snapshot = connect(source).use { OfflineStorageTransfer.export(it, StorageDialect.SQLITE, keyId) } + + assertThrows(StorageTransferException::class.java) { + connect(destination).use { OfflineStorageTransfer.`import`(it, StorageDialect.SQLITE, snapshot) } + } + connect(destination).use { assertEquals(1, count(it, "invitecode_players")) } + } + + @Test + fun `source with a different historical hash key is rejected`() { + val source = database("wrong-key.db") + SqliteSchemaMigrator(source, BlockingOperationGuard { }).migrate() + seed(source) + val error = assertThrows(StorageTransferException::class.java) { + connect(source).use { OfflineStorageTransfer.export(it, StorageDialect.SQLITE, "d".repeat(64)) } + } + assertEquals(true, error.message.orEmpty().contains("another anti-abuse key")) + } + + @Test + fun `sqlite import failure rolls back every inserted table`() { + val source = database("rollback-source.db") + val destination = database("rollback-destination.db") + SqliteSchemaMigrator(source, BlockingOperationGuard { }).migrate() + SqliteSchemaMigrator(destination, BlockingOperationGuard { }).migrate() + seed(source) + val snapshot = connect(source).use { OfflineStorageTransfer.export(it, StorageDialect.SQLITE, keyId) } + connect(destination).use { connection -> + connection.createStatement().use { + it.execute( + "CREATE TRIGGER injected_transfer_failure BEFORE INSERT ON invitecode_reserved_code_hashes " + + "BEGIN SELECT RAISE(ABORT, 'injected transfer failure'); END", + ) + } + assertThrows(StorageTransferException::class.java) { + OfflineStorageTransfer.`import`(connection, StorageDialect.SQLITE, snapshot) + } + BUSINESS_TABLES.forEach { table -> assertEquals(0, count(connection, table)) } + } + } + + private fun seed(path: Path) = connect(path).use { connection -> + connection.createStatement().use { it.execute("PRAGMA foreign_keys = ON") } + val inviter = UUID.randomUUID().toString() + val invitee = UUID.randomUUID().toString() + val invitation = UUID.randomUUID().toString() + val delivery = UUID.randomUUID().toString() + val action = UUID.randomUUID().toString() + fun insert(sql: String, vararg values: Any?) = connection.prepareStatement(sql).use { statement -> + values.forEachIndexed { index, value -> statement.setObject(index + 1, value) } + statement.executeUpdate() + } + insert("INSERT INTO invitecode_players(player_id, first_seen_at, last_known_name, eligibility_generation) VALUES (?, ?, ?, ?)", inviter, "2026-01-01T00:00:00Z", null, 2) + insert("INSERT INTO invitecode_players(player_id, first_seen_at, last_known_name, eligibility_generation) VALUES (?, ?, ?, ?)", invitee, "2026-01-02T00:00:00Z", "Invitee", 0) + insert("INSERT INTO invitecode_codes(code, inviter_id, activated_at, retired_at) VALUES (?, ?, ?, ?)", "A1B2C3", inviter, "2026-01-01T00:00:00Z", null) + insert("""INSERT INTO invitecode_invitations(invitation_id, inviter_id, inviter_eligibility_generation, + invitee_id, invitee_eligibility_generation, status, claimed_at, qualified_at, qualification_policy_id, + qualification_revision) VALUES (?, ?, 2, ?, 0, 'QUALIFIED', ?, ?, ?, ?)""", + invitation, inviter, invitee, "2026-01-03T00:00:00Z", "2026-01-04T00:00:00Z", "default", "rev-1") + insert("INSERT INTO invitecode_qualification_facts(fact_id, invitation_id, policy_id, qualification_revision, condition_id, outcome, recorded_at) VALUES (?, ?, ?, ?, ?, ?, ?)", + UUID.randomUUID().toString(), invitation, "default", "rev-1", "playtime", "PASSED", "2026-01-04T00:00:00Z") + insert("INSERT INTO invitecode_reward_deliveries(delivery_id, invitation_id, reward_id, status, idempotency_key, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)", + delivery, invitation, "invitee-reward", "DELIVERED", "delivery:$delivery", "2026-01-04T00:00:00Z", "2026-01-05T00:00:00Z") + insert("INSERT INTO invitecode_reward_actions(action_id, reward_delivery_id, invitation_id, recipient_id, position, action_type, payload, status, idempotency_key, created_at, updated_at, last_error) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + action, delivery, invitation, invitee, 0, "MESSAGE", "welcome", "DELIVERED", "action:$action", "2026-01-04T00:00:00Z", "2026-01-05T00:00:00Z", null) + insert("INSERT INTO invitecode_audit_records(audit_id, action, actor, reason, occurred_at, invitation_id, player_id, details_kind, previous_inviter_id, new_inviter_id, qualification_policy_id, qualification_revision) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + UUID.randomUUID().toString(), "QUALIFIED", "admin", "accepted", "2026-01-04T00:00:00Z", invitation, invitee, "NONE", null, inviter, "default", "rev-1") + insert("INSERT INTO invitecode_reward_delivery_transitions(transition_id, delivery_id, previous_status, current_status, occurred_at, actor, reason) VALUES (?, ?, ?, ?, ?, ?, ?)", + 101, delivery, null, "PENDING", "2026-01-04T00:00:00Z", null, null) + insert("INSERT INTO invitecode_reward_delivery_transitions(transition_id, delivery_id, previous_status, current_status, occurred_at, actor, reason) VALUES (?, ?, ?, ?, ?, ?, ?)", + 108, delivery, "PENDING", "DELIVERED", "2026-01-05T00:00:00Z", "admin", "completed") + insert("INSERT INTO invitecode_reward_action_transitions(transition_id, action_id, previous_status, current_status, occurred_at, last_error, actor, reason) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", + 202, action, null, "PROCESSING", "2026-01-04T00:00:00Z", null, null, null) + insert("INSERT INTO invitecode_reward_action_transitions(transition_id, action_id, previous_status, current_status, occurred_at, last_error, actor, reason) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", + 209, action, "PROCESSING", "DELIVERED", "2026-01-05T00:00:00Z", null, "admin", "completed") + insert("INSERT INTO invitecode_player_login_days(player_id, login_date) VALUES (?, ?)", invitee, "2026-01-02") + insert("INSERT INTO invitecode_player_network_hashes(player_id, key_id, network_hash, observed_at, expires_at) VALUES (?, ?, ?, ?, ?)", + inviter, keyId, "b".repeat(64), "2026-01-01T00:00:00Z", "2027-01-01T00:00:00Z") + insert("INSERT INTO invitecode_reserved_code_hashes(code_hash, key_id) VALUES (?, ?)", "c".repeat(64), keyId) + } + + private fun database(name: String): Path = directory.resolve(name) + private fun connect(path: Path): Connection = DriverManager.getConnection("jdbc:sqlite:${path.toAbsolutePath()}") + private fun count(connection: Connection, table: String): Int = connection.createStatement().use { statement -> + statement.executeQuery("SELECT COUNT(*) FROM $table").use { rows -> rows.next(); rows.getInt(1) } + } + + private companion object { + val BUSINESS_TABLES = listOf( + "invitecode_players", "invitecode_codes", "invitecode_invitations", "invitecode_qualification_facts", + "invitecode_reward_deliveries", "invitecode_reward_actions", "invitecode_audit_records", + "invitecode_reward_delivery_transitions", "invitecode_reward_action_transitions", + "invitecode_player_login_days", "invitecode_player_network_hashes", "invitecode_reserved_code_hashes", + ) + } +}