databaseStartupAdmission.test.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import { expect, it, vi } from "vitest";
  2. import type { DatabaseStartupState } from "@zcode/shared";
  3. import { DatabaseStartupAdmission } from "../src/renderer/src/databaseStartupAdmission.js";
  4. const state = (
  5. startupId: string,
  6. phase: DatabaseStartupState["phase"] = "ready",
  7. sequence = 1,
  8. ): DatabaseStartupState => ({
  9. schemaVersion: 1,
  10. startupId,
  11. attemptId: startupId + "-attempt",
  12. sequence,
  13. phase,
  14. startedAt: 100,
  15. updatedAt: 200,
  16. disk: [],
  17. });
  18. it.each([true, false])("requires the same Host for ready and port, stateFirst=%s", (stateFirst) => {
  19. const gate = new DatabaseStartupAdmission();
  20. const port = { close: vi.fn() } as unknown as MessagePort;
  21. if (stateFirst) {
  22. gate.acceptState(state("new", "ready", 2));
  23. expect(gate.takeReadyPort()).toBeUndefined();
  24. gate.acceptPort({ databaseStartupId: "new" }, port);
  25. } else {
  26. gate.acceptPort({ databaseStartupId: "new" }, port);
  27. expect(gate.takeReadyPort()).toBeUndefined();
  28. gate.acceptState(state("new", "ready", 2));
  29. }
  30. expect(gate.takeReadyPort()).toBe(port);
  31. expect(gate.takeReadyPort()).toBeUndefined();
  32. });
  33. it("rejects untagged ports, stale snapshots and closes replaced ports", () => {
  34. const gate = new DatabaseStartupAdmission();
  35. const old = { close: vi.fn() } as unknown as MessagePort;
  36. const current = { close: vi.fn() } as unknown as MessagePort;
  37. gate.acceptPort(null, old);
  38. expect(old.close).toHaveBeenCalledOnce();
  39. gate.acceptPort({ databaseStartupId: "a" }, old);
  40. gate.acceptPort({ databaseStartupId: "b" }, current);
  41. expect(old.close).toHaveBeenCalledTimes(2);
  42. gate.acceptState(state("b", "preparing_host_storage", 2));
  43. expect(gate.acceptState(state("b", "ready", 1))).toBe(false);
  44. expect(gate.takeReadyPort()).toBeUndefined();
  45. });
  46. it("never combines a previous Host ready with a new Host port", () => {
  47. const gate = new DatabaseStartupAdmission();
  48. const port = { close: vi.fn() } as unknown as MessagePort;
  49. gate.acceptState(state("old"));
  50. gate.acceptPort({ databaseStartupId: "new" }, port);
  51. expect(gate.takeReadyPort()).toBeUndefined();
  52. gate.acceptState(state("new", "preparing_host_storage"));
  53. expect(gate.takeReadyPort()).toBeUndefined();
  54. gate.acceptState(state("new", "ready", 2));
  55. expect(gate.takeReadyPort()).toBe(port);
  56. });