remoteSchemaMigrations.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. import { DatabaseSync } from "node:sqlite";
  2. import type { DatabaseMigrationFacts } from "@zcode/shared";
  3. import { mkdtemp, rm } from "node:fs/promises";
  4. import { tmpdir } from "node:os";
  5. import { join, resolve } from "node:path";
  6. import { Worker } from "node:worker_threads";
  7. import { once } from "node:events";
  8. import { build } from "esbuild";
  9. import { afterEach, expect, it } from "vitest";
  10. import { runTasksDatabaseMigrations } from "#src/session/tasksDatabase/migrations.js";
  11. import { migrateControllerRemoteWorkspaceIdentity } from "#src/session/controllerRemoteIdentityMigration.js";
  12. import { SourceServerWorkspaceAliasRepo } from "#src/session/sourceServerWorkspaceAliasRepo.js";
  13. const roots: string[] = [];
  14. afterEach(async () => {
  15. await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
  16. });
  17. async function fixture() {
  18. const root = await mkdtemp(join(tmpdir(), "zcode-remote-schema-"));
  19. roots.push(root);
  20. const taskDbPath = join(root, "tasks.sqlite");
  21. const sessionDbPath = join(root, "session.sqlite");
  22. return { taskDbPath, sessionDbPath, backupRoot: join(root, "backups") };
  23. }
  24. it("已迁移 Controller 无源行重连在其他连接持写锁时只读返回,checksum 仍校验", async () => {
  25. const options = await fixture();
  26. const writer = new DatabaseSync(options.taskDbPath);
  27. const input = {
  28. dbPath: options.taskDbPath,
  29. oldWorkspaceKey: "remote:ssh:old:22:u:/repo",
  30. newWorkspaceKey: "remote:server:source:/repo",
  31. };
  32. try {
  33. writer.exec("PRAGMA journal_mode = WAL");
  34. await runTasksDatabaseMigrations(writer);
  35. writer
  36. .prepare(`INSERT INTO tasks
  37. (workspace_key, workspace_path, workspace_identity, task_id, created_at, updated_at)
  38. VALUES (?, '/repo', ?, 'task-1', 1, 1)`)
  39. .run(input.oldWorkspaceKey, input.oldWorkspaceKey);
  40. await migrateControllerRemoteWorkspaceIdentity(input);
  41. const ledger = writer.prepare("SELECT * FROM tasks_schema_migration ORDER BY id").all();
  42. const audit = writer.prepare("SELECT * FROM controller_remote_identity_migrations").all();
  43. writer.exec("BEGIN IMMEDIATE; UPDATE tasks SET updated_at = 2");
  44. // 保持真实写锁直到断言结束;错误实现无法靠等待 writer 释放而偶然通过。
  45. await expect(migrateControllerRemoteWorkspaceIdentity(input)).resolves.toMatchObject({
  46. status: "completed",
  47. before: { tasks: 0 },
  48. after: { tasks: 1 },
  49. });
  50. writer.exec("ROLLBACK");
  51. expect(writer.prepare("SELECT * FROM tasks_schema_migration ORDER BY id").all()).toEqual(
  52. ledger,
  53. );
  54. expect(writer.prepare("SELECT * FROM controller_remote_identity_migrations").all()).toEqual(
  55. audit,
  56. );
  57. writer.exec(`UPDATE tasks_schema_migration SET checksum = 'broken'
  58. WHERE id = '0004_controller_remote_identity'; BEGIN IMMEDIATE`);
  59. await expect(migrateControllerRemoteWorkspaceIdentity(input)).rejects.toThrow(/checksum/);
  60. } finally {
  61. if (writer.isTransaction) writer.exec("ROLLBACK");
  62. writer.close();
  63. }
  64. });
  65. it("Source 管理查询在已迁移 task 库持写锁时只读返回", async () => {
  66. const options = await fixture();
  67. const writer = new DatabaseSync(options.taskDbPath);
  68. const repo = new SourceServerWorkspaceAliasRepo(options);
  69. try {
  70. writer.exec("PRAGMA journal_mode = WAL");
  71. await repo.getFailedPathCount();
  72. const ledger = writer.prepare("SELECT * FROM tasks_schema_migration").all();
  73. writer.exec("BEGIN IMMEDIATE");
  74. await expect(repo.getFailedPathCount()).resolves.toBe(0);
  75. await expect(repo.getAbandonedPathCount()).resolves.toBe(0);
  76. writer.exec("ROLLBACK");
  77. expect(writer.prepare("SELECT * FROM tasks_schema_migration").all()).toEqual(ledger);
  78. } finally {
  79. if (writer.isTransaction) writer.exec("ROLLBACK");
  80. writer.close();
  81. }
  82. });
  83. it("Source 已有 alias 在 session 库持写锁时可解析,identity 账本不变且 checksum 仍校验", async () => {
  84. const options = await fixture();
  85. const writer = new DatabaseSync(options.sessionDbPath);
  86. const canonicalKey = "remote:ssh:one:22:u:/repo";
  87. const input = { workspacePath: "/repo", legacyRouteHint: canonicalKey };
  88. const repo = new SourceServerWorkspaceAliasRepo(options);
  89. try {
  90. writer.exec(`PRAGMA journal_mode = WAL;
  91. CREATE TABLE session (id TEXT PRIMARY KEY, workspace_id TEXT, directory TEXT, path TEXT, time_updated INTEGER)`);
  92. writer
  93. .prepare("INSERT INTO session VALUES ('session-1', ?, '/repo', '/repo', 1)")
  94. .run(canonicalKey);
  95. await repo.resolveCanonicalWorkspaceKey(input);
  96. const ledger = writer.prepare("SELECT * FROM schema_migration").all();
  97. writer.exec("BEGIN IMMEDIATE; UPDATE session SET time_updated = 2");
  98. await expect(repo.resolveCanonicalWorkspaceKey(input)).resolves.toEqual({
  99. canonicalKey,
  100. mergedKeys: [],
  101. });
  102. writer.exec("ROLLBACK");
  103. expect(writer.prepare("SELECT * FROM schema_migration").all()).toEqual(ledger);
  104. writer.exec(`UPDATE schema_migration SET checksum = 'broken'
  105. WHERE id = '0024_session_database_identity'; BEGIN IMMEDIATE`);
  106. await expect(repo.resolveCanonicalWorkspaceKey(input)).rejects.toThrow(/checksum/);
  107. } finally {
  108. if (writer.isTransaction) writer.exec("ROLLBACK");
  109. writer.close();
  110. }
  111. });
  112. it("并发 Source/Core 初始化只记账一次,默认业务表与远端扩展可以交错接管", async () => {
  113. const options = await fixture();
  114. const compiled = await build({
  115. entryPoints: [resolve("packages/services/src/session/tasksDatabase/migrations.ts")],
  116. bundle: true,
  117. write: false,
  118. platform: "node",
  119. format: "cjs",
  120. // #src 属于各自 package;全局 alias 会把 shared 的入口错误重定向到 services。
  121. });
  122. const gate = new SharedArrayBuffer(4);
  123. const workers = ["source-server", "base", "source-server"].map(
  124. (scope) =>
  125. new Worker(
  126. `${compiled.outputFiles[0]!.text}
  127. const { parentPort, workerData } = require('node:worker_threads');
  128. const db = new (require('node:sqlite').DatabaseSync)(workerData.path);
  129. db.exec('PRAGMA busy_timeout = 5000');
  130. parentPort.postMessage('ready');
  131. Atomics.wait(new Int32Array(workerData.gate), 0, 0);
  132. module.exports.runTasksDatabaseMigrations(db, workerData.scope).then(() => db.close());`,
  133. { eval: true, workerData: { path: options.taskDbPath, scope, gate } },
  134. ),
  135. );
  136. try {
  137. const exits = workers.map((worker) => once(worker, "exit"));
  138. await Promise.all(workers.map((worker) => once(worker, "message")));
  139. Atomics.store(new Int32Array(gate), 0, 1);
  140. Atomics.notify(new Int32Array(gate), 0);
  141. expect(await Promise.all(exits)).toEqual([[0], [0], [0]]);
  142. const db = new DatabaseSync(options.taskDbPath);
  143. try {
  144. expect(db.prepare("SELECT id FROM tasks_schema_migration ORDER BY id").all()).toEqual([
  145. { id: "0001_adopt_task_schema" },
  146. { id: "0002_provider_selection" },
  147. { id: "0003_official_glm_selection" },
  148. { id: "0004_project_execution_scopes" },
  149. { id: "0005_source_server_workspace_schema" },
  150. { id: "0006_task_group_admissions" },
  151. ]);
  152. expect(db.prepare("PRAGMA integrity_check").get()?.integrity_check).toBe("ok");
  153. } finally {
  154. db.close();
  155. }
  156. } finally {
  157. await Promise.all(workers.map((worker) => worker.terminate()));
  158. }
  159. });
  160. it("Controller 与 Source 的附加表登记到同库账本,保留旧记录且不混用专属表", async () => {
  161. const options = await fixture();
  162. const db = new DatabaseSync(options.taskDbPath);
  163. try {
  164. await runTasksDatabaseMigrations(db);
  165. const oldLedger = db.prepare("SELECT * FROM tasks_schema_migration ORDER BY id").all();
  166. await migrateControllerRemoteWorkspaceIdentity({
  167. dbPath: options.taskDbPath,
  168. oldWorkspaceKey: "remote:ssh:old:22:u:/repo",
  169. newWorkspaceKey: "remote:server:source:/repo",
  170. });
  171. expect(db.prepare("SELECT id FROM tasks_schema_migration WHERE id LIKE '0004%'").get()).toEqual(
  172. {
  173. id: "0004_controller_remote_identity",
  174. },
  175. );
  176. expect(
  177. db.prepare("SELECT 1 FROM sqlite_master WHERE name='workspace_alias'").get(),
  178. ).toBeUndefined();
  179. const beforeReopen = db.prepare("SELECT * FROM tasks_schema_migration ORDER BY id").all();
  180. await migrateControllerRemoteWorkspaceIdentity({
  181. dbPath: options.taskDbPath,
  182. oldWorkspaceKey: "remote:ssh:old:22:u:/repo",
  183. newWorkspaceKey: "remote:server:source:/repo",
  184. });
  185. expect(db.prepare("SELECT * FROM tasks_schema_migration ORDER BY id").all()).toEqual(
  186. beforeReopen,
  187. );
  188. expect(
  189. db
  190. .prepare(
  191. "SELECT * FROM tasks_schema_migration WHERE id != '0004_controller_remote_identity' AND id != '0005_source_server_workspace_schema' ORDER BY id",
  192. )
  193. .all(),
  194. ).toEqual(oldLedger);
  195. } finally {
  196. db.close();
  197. }
  198. const sourceOptions = await fixture();
  199. const sourceDb = new DatabaseSync(sourceOptions.taskDbPath);
  200. try {
  201. const repo = new SourceServerWorkspaceAliasRepo(sourceOptions);
  202. await expect(repo.getFailedPathCount()).resolves.toBe(0);
  203. expect(sourceDb.prepare("SELECT id FROM tasks_schema_migration").all()).toEqual([
  204. { id: "0005_source_server_workspace_schema" },
  205. ]);
  206. expect(
  207. sourceDb
  208. .prepare("SELECT 1 FROM sqlite_master WHERE name='controller_remote_identity_migrations'")
  209. .get(),
  210. ).toBeUndefined();
  211. const sourceLedger = sourceDb.prepare("SELECT * FROM tasks_schema_migration").all();
  212. await repo.getFailedPathCount();
  213. await runTasksDatabaseMigrations(sourceDb);
  214. expect(
  215. sourceDb.prepare("SELECT * FROM tasks_schema_migration WHERE id LIKE '0005%'").all(),
  216. ).toEqual(sourceLedger);
  217. } finally {
  218. sourceDb.close();
  219. }
  220. });
  221. it("Source schema 和正式账本原子提交,记账失败回滚,checksum 损坏明确拒绝", async () => {
  222. const options = await fixture();
  223. const db = new DatabaseSync(options.taskDbPath);
  224. try {
  225. await runTasksDatabaseMigrations(db);
  226. db.exec(`CREATE TRIGGER reject_remote_migration BEFORE INSERT ON tasks_schema_migration
  227. WHEN NEW.id = '0005_source_server_workspace_schema'
  228. BEGIN SELECT RAISE(ABORT, 'injected ledger failure'); END;`);
  229. const repo = new SourceServerWorkspaceAliasRepo(options);
  230. await expect(repo.getFailedPathCount()).rejects.toThrow("injected ledger failure");
  231. expect(
  232. db.prepare("SELECT 1 FROM sqlite_master WHERE name='workspace_alias'").get(),
  233. ).toBeUndefined();
  234. db.exec("DROP TRIGGER reject_remote_migration");
  235. await expect(repo.getFailedPathCount()).resolves.toBe(0);
  236. db.exec(
  237. "UPDATE tasks_schema_migration SET checksum='broken' WHERE id='0005_source_server_workspace_schema'",
  238. );
  239. await expect(repo.getFailedPathCount()).rejects.toThrow(/checksum/);
  240. } finally {
  241. db.close();
  242. }
  243. });
  244. it("接管无旧版本标记的完整表时,保留活动计划的 phase 和 session generation", async () => {
  245. const options = await fixture();
  246. const db = new DatabaseSync(options.taskDbPath);
  247. try {
  248. const repo = new SourceServerWorkspaceAliasRepo(options);
  249. await repo.getFailedPathCount();
  250. db.exec(`INSERT INTO workspace_migration_ledger
  251. (migration_id, path, canonical_key, variant_keys_json, status, phase, task_backup_path,
  252. created_at, updated_at, session_db_generation)
  253. VALUES ('active-plan', '/repo', 'canonical', '[]', 'running', 'task-db-merged', '/backup', 1, 2, 'frozen-generation');
  254. DELETE FROM workspace_migration_schema_version;
  255. DELETE FROM tasks_schema_migration WHERE id='0005_source_server_workspace_schema';`);
  256. const before = db.prepare("SELECT * FROM workspace_migration_ledger").all();
  257. await repo.getFailedPathCount();
  258. expect(db.prepare("SELECT * FROM workspace_migration_ledger").all()).toEqual(before);
  259. } finally {
  260. db.close();
  261. }
  262. });
  263. it("Source 首次创建 session identity 表时登记 schema_migration,已有 identity 保持不变", async () => {
  264. const options = await fixture();
  265. const taskDb = new DatabaseSync(options.taskDbPath);
  266. const sessionDb = new DatabaseSync(options.sessionDbPath);
  267. const canonical = "remote:ssh:one:22:u:/repo";
  268. const variant = "remote:ssh:two:22:u:/repo";
  269. try {
  270. await runTasksDatabaseMigrations(taskDb);
  271. const insert = taskDb.prepare(`INSERT INTO tasks
  272. (workspace_key, workspace_path, workspace_identity, task_id, created_at, updated_at)
  273. VALUES (?, '/repo', ?, ?, 1, ?)`);
  274. insert.run(canonical, canonical, "task-1", 20);
  275. insert.run(variant, variant, "task-2", 10);
  276. sessionDb.exec(`CREATE TABLE session (id TEXT PRIMARY KEY, workspace_id TEXT, directory TEXT, path TEXT, time_updated INTEGER);
  277. CREATE TABLE zcode_database_identity (scope TEXT PRIMARY KEY, identity TEXT NOT NULL);
  278. INSERT INTO zcode_database_identity VALUES ('session', 'legacy-generation');`);
  279. const repo = new SourceServerWorkspaceAliasRepo(options);
  280. await repo.resolveCanonicalWorkspaceKey({ workspacePath: "/repo", legacyRouteHint: canonical });
  281. expect(sessionDb.prepare("SELECT id FROM schema_migration").all()).toEqual([
  282. { id: "0024_session_database_identity" },
  283. ]);
  284. expect(sessionDb.prepare("SELECT identity FROM zcode_database_identity").get()).toEqual({
  285. identity: "legacy-generation",
  286. });
  287. } finally {
  288. sessionDb.close();
  289. taskDb.close();
  290. }
  291. });
  292. it.each(["base", "controller-remote", "source-server"] as const)(
  293. "启动门禁与 %s scope 共用事务,已迁移时也完成交接提交",
  294. async (scope) => {
  295. const db = new DatabaseSync(":memory:");
  296. try {
  297. const migration: DatabaseMigrationFacts = {
  298. kind: "initialize",
  299. executedCount: 0,
  300. committedCount: 0,
  301. };
  302. const phases: string[] = [];
  303. db.exec("BEGIN IMMEDIATE");
  304. await runTasksDatabaseMigrations(db, {
  305. scope,
  306. transactionOpen: true,
  307. migration,
  308. onProgress: (phase) => phases.push(phase),
  309. });
  310. const expectedCount = scope === "base" ? 5 : 1;
  311. expect(db.isTransaction).toBe(false);
  312. expect(migration).toEqual({
  313. kind: "initialize",
  314. executedCount: expectedCount,
  315. committedCount: expectedCount,
  316. lastAppliedMigrationId: null,
  317. });
  318. expect(phases.filter((phase) => phase === "migrating")).toHaveLength(expectedCount);
  319. expect(phases.at(-1)).toBe("committing");
  320. const ledger = db.prepare("SELECT * FROM tasks_schema_migration ORDER BY id").all();
  321. const repeated: DatabaseMigrationFacts = {
  322. kind: "none",
  323. executedCount: 0,
  324. committedCount: 0,
  325. };
  326. db.exec("BEGIN IMMEDIATE");
  327. await runTasksDatabaseMigrations(db, { scope, transactionOpen: true, migration: repeated });
  328. expect(db.isTransaction).toBe(false);
  329. expect(repeated).toEqual({
  330. kind: "none",
  331. executedCount: 0,
  332. committedCount: 0,
  333. lastAppliedMigrationId: ledger.at(-1)?.id,
  334. });
  335. expect(db.prepare("SELECT * FROM tasks_schema_migration ORDER BY id").all()).toEqual(ledger);
  336. } finally {
  337. if (db.isTransaction) db.exec("ROLLBACK");
  338. db.close();
  339. }
  340. },
  341. );