migration-crash-recovery.test.ts 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import { fork } from "node:child_process";
  2. import { once } from "node:events";
  3. import { mkdtemp, rm } from "node:fs/promises";
  4. import { tmpdir } from "node:os";
  5. import { join } from "node:path";
  6. import { DatabaseSync } from "node:sqlite";
  7. import { describe, expect, it } from "vitest";
  8. import { SqliteSessionStore } from "../src/storage/session-store/sqlite-session-store.js";
  9. describe("迁移进程在提交边界崩溃", () => {
  10. it.each(["committing", "ready"] as const)(
  11. "%s 时终止:以磁盘账本决定重试,不依赖完成通知",
  12. async (stopAt) => {
  13. const root = await mkdtemp(join(tmpdir(), "zcode-migration-crash-"));
  14. const dbPath = join(root, "db.sqlite");
  15. const child = fork(
  16. new URL("./fixtures/session-migration-crash-process.ts", import.meta.url),
  17. {
  18. execArgv: ["--import", "tsx"],
  19. stdio: ["ignore", "ignore", "inherit", "ipc"],
  20. },
  21. );
  22. try {
  23. const barrier = new Promise<void>((resolve, reject) => {
  24. child.once("error", reject);
  25. child.once("exit", () => reject(new Error("child exited before barrier")));
  26. child.on("message", (message: { type?: string }) => {
  27. if (message.type === "listening") child.send({ dbPath, stopAt });
  28. if (message.type === "barrier") resolve();
  29. });
  30. });
  31. await barrier;
  32. const exited = once(child, "exit");
  33. child.kill("SIGKILL");
  34. await exited;
  35. const db = new DatabaseSync(dbPath);
  36. try {
  37. const ledgerExists = Boolean(
  38. db.prepare("SELECT 1 FROM sqlite_schema WHERE name='schema_migration'").get(),
  39. );
  40. expect(ledgerExists).toBe(stopAt === "ready");
  41. const before = ledgerExists
  42. ? db.prepare("SELECT * FROM schema_migration ORDER BY id").all()
  43. : null;
  44. const stages: string[] = [];
  45. const store = await SqliteSessionStore.openStartup(
  46. { dbPath },
  47. {
  48. onProgress: async (s) => {
  49. stages.push(s.phase);
  50. },
  51. },
  52. );
  53. store.close();
  54. expect(stages.includes("migrating")).toBe(stopAt === "committing");
  55. if (before)
  56. expect(db.prepare("SELECT * FROM schema_migration ORDER BY id").all()).toEqual(before);
  57. expect(stages.at(-1)).toBe("ready");
  58. } finally {
  59. db.close();
  60. }
  61. } finally {
  62. if (child.exitCode === null && child.signalCode === null) {
  63. const exited = once(child, "exit");
  64. child.kill("SIGKILL");
  65. await exited;
  66. }
  67. await rm(root, { recursive: true, force: true });
  68. }
  69. },
  70. 15_000,
  71. );
  72. });