storage-startup.test.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import { mkdtemp, rm } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { Writable } from "node:stream";
  5. import { afterEach, describe, expect, it } from "vitest";
  6. import { DatabaseSync } from "node:sqlite";
  7. import { zcodeStorageStartupStateSchema } from "@zcode/shared";
  8. import { openProtocolStartupStorage } from "../src/zcode-protocol/storage-startup.js";
  9. const dirs: string[] = [];
  10. afterEach(async () => {
  11. for (const dir of dirs.splice(0)) await rm(dir, { recursive: true, force: true });
  12. });
  13. describe("迁移前的 stdio 启动控制帧", () => {
  14. it("真实 Writable 回调完成前不执行 SQL;无账号/Provider 参数也能准备数据库", async () => {
  15. const dir = await mkdtemp(join(tmpdir(), "zcode-storage-wire-"));
  16. dirs.push(dir);
  17. const dbPath = join(dir, "db.sqlite");
  18. const packets: unknown[] = [];
  19. let release!: () => void;
  20. let observed!: () => void;
  21. const barrier = new Promise<void>((resolve) => {
  22. observed = resolve;
  23. });
  24. const output = new Writable({
  25. write(chunk, _encoding, callback) {
  26. const packet = JSON.parse(String(chunk));
  27. packets.push(packet);
  28. if (
  29. packet.params.phase === "migrating" &&
  30. packet.params.migrationId === "0001_base_session_store"
  31. ) {
  32. release = () => callback();
  33. observed();
  34. } else callback();
  35. },
  36. });
  37. const diagnostics: unknown[] = [];
  38. const opening = openProtocolStartupStorage({
  39. dbPath,
  40. output,
  41. onProgress: (progress) => {
  42. diagnostics.push(progress);
  43. },
  44. });
  45. await barrier;
  46. const reader = new DatabaseSync(dbPath);
  47. try {
  48. expect(
  49. reader.prepare("SELECT 1 FROM sqlite_schema WHERE name='session'").get(),
  50. ).toBeUndefined();
  51. } finally {
  52. reader.close();
  53. release();
  54. }
  55. const store = await opening;
  56. try {
  57. const states = packets.map((packet) => {
  58. const envelope = packet as { method: string; params: unknown };
  59. expect(envelope.method).toBe("startup/storageState");
  60. return zcodeStorageStartupStateSchema.parse(envelope.params);
  61. });
  62. expect(states.at(-1)?.phase).toBe("ready");
  63. expect(new Set(states.map((s) => s.attemptId)).size).toBe(1);
  64. expect(states.map((s) => s.sequence)).toEqual(states.map((_, i) => i + 1));
  65. expect(JSON.stringify(packets)).not.toContain(dir);
  66. expect(diagnostics).toEqual(states);
  67. } finally {
  68. store.close();
  69. }
  70. });
  71. });