controller.test.ts 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. import { describe, expect, it, vi } from "vitest";
  2. import { SessionLifecycleController } from "../../src/session-lifecycle/index.js";
  3. function fixture() {
  4. const runtimes = new Set<string>();
  5. const known = new Set(["a", "b"]);
  6. const host = {
  7. exists: vi.fn(async (id: string) => known.has(id)),
  8. hasRuntime: (id: string) => runtimes.has(id),
  9. activate: vi.fn(async (id: string) => {
  10. runtimes.add(id);
  11. }),
  12. assertCanStop: vi.fn(),
  13. release: vi.fn(async (id: string) => {
  14. runtimes.delete(id);
  15. }),
  16. onChange: vi.fn(),
  17. };
  18. return { host, runtimes, known, lifecycle: new SessionLifecycleController(host) };
  19. }
  20. describe("session runtime lifecycle", () => {
  21. it("does not treat a deleted persistent session as ready even if its old runtime remains", async () => {
  22. const { lifecycle, known } = fixture();
  23. await lifecycle.ensureReady("a");
  24. known.delete("a");
  25. await expect(lifecycle.ensureReady("a")).rejects.toMatchObject({ code: "sessionNotFound" });
  26. });
  27. it("queries without activating and rejects unknown identities", async () => {
  28. const { lifecycle, host } = fixture();
  29. expect(await lifecycle.getState("a")).toMatchObject({
  30. sessionId: "a",
  31. state: "unloaded",
  32. lastError: null,
  33. });
  34. await expect(lifecycle.getState("missing")).rejects.toMatchObject({ code: "sessionNotFound" });
  35. expect(host.activate).not.toHaveBeenCalled();
  36. });
  37. it("joins concurrent startup and does not expose a registered partial instance as ready", async () => {
  38. const { lifecycle, host, runtimes } = fixture();
  39. const gate = Promise.withResolvers<void>();
  40. host.activate.mockImplementation(async (id) => {
  41. runtimes.add(id);
  42. await gate.promise;
  43. });
  44. const first = lifecycle.ensureReady("a");
  45. const second = lifecycle.ensureReady("a");
  46. expect((await lifecycle.getState("a")).state).toBe("starting");
  47. gate.resolve();
  48. await Promise.all([first, second]);
  49. await lifecycle.ensureReady("a");
  50. expect(host.activate).toHaveBeenCalledTimes(1);
  51. expect((await lifecycle.getState("a")).state).toBe("ready");
  52. });
  53. it("waits for real release before recreating and joins duplicate stops", async () => {
  54. const { lifecycle, host, runtimes } = fixture();
  55. await lifecycle.ensureReady("a");
  56. const gate = Promise.withResolvers<void>();
  57. host.release.mockImplementation(async (id) => {
  58. runtimes.delete(id);
  59. await gate.promise;
  60. });
  61. const stop = lifecycle.stop("a");
  62. const duplicate = lifecycle.stop("a");
  63. const ready = lifecycle.ensureReady("a");
  64. expect((await lifecycle.getState("a")).state).toBe("stopping");
  65. expect(host.activate).toHaveBeenCalledTimes(1);
  66. gate.resolve();
  67. await Promise.all([stop, duplicate, ready]);
  68. expect(host.release).toHaveBeenCalledTimes(1);
  69. expect(host.activate).toHaveBeenCalledTimes(2);
  70. });
  71. it("owns the whole restart including its unloaded interval", async () => {
  72. const { lifecycle, host } = fixture();
  73. await lifecycle.ensureReady("a");
  74. const gate = Promise.withResolvers<void>();
  75. host.release.mockImplementation(async () => gate.promise);
  76. const restart = lifecycle.restart("a");
  77. const duplicate = lifecycle.restart("a");
  78. const ready = lifecycle.ensureReady("a");
  79. await expect(lifecycle.stop("a")).rejects.toMatchObject({ code: "conflict" });
  80. gate.resolve();
  81. await Promise.all([restart, duplicate, ready]);
  82. expect(host.release).toHaveBeenCalledTimes(1);
  83. expect(host.activate).toHaveBeenCalledTimes(2);
  84. });
  85. it("coalesces restart during startup without overlapping instances", async () => {
  86. const { lifecycle, host } = fixture();
  87. const gate = Promise.withResolvers<void>();
  88. host.activate.mockImplementation(async (id) => {
  89. if (id === "a") await gate.promise;
  90. });
  91. const pending = lifecycle.ensureReady("a");
  92. await expect(lifecycle.stop("a")).rejects.toMatchObject({ code: "conflict" });
  93. const restarting = lifecycle.restart("a");
  94. const duplicate = lifecycle.restart("a");
  95. expect(host.release).not.toHaveBeenCalled();
  96. await lifecycle.ensureReady("b");
  97. expect((await lifecycle.getState("b")).state).toBe("ready");
  98. gate.resolve();
  99. await pending;
  100. await Promise.all([restarting, duplicate]);
  101. expect(host.activate.mock.calls.filter(([id]) => id === "a")).toHaveLength(2);
  102. expect(host.release).toHaveBeenCalledTimes(1);
  103. });
  104. it("reserves restart before earlier startup observers can stop the runtime", async () => {
  105. const { lifecycle, host } = fixture();
  106. const gate = Promise.withResolvers<void>();
  107. host.activate.mockImplementationOnce(async () => gate.promise);
  108. const startup = lifecycle.ensureReady("a");
  109. const competingStop = startup.then(() => lifecycle.stop("a"));
  110. const rejection = expect(competingStop).rejects.toMatchObject({ code: "conflict" });
  111. const restart = lifecycle.restart("a");
  112. void restart.catch(() => undefined);
  113. gate.resolve();
  114. await rejection;
  115. await restart;
  116. expect(host.release).toHaveBeenCalledTimes(1);
  117. expect(host.activate).toHaveBeenCalledTimes(2);
  118. });
  119. it("invalidates history-only resources even when no runtime is loaded", async () => {
  120. const { lifecycle, host } = fixture();
  121. await lifecycle.restart("a");
  122. expect(host.release).toHaveBeenCalledWith("a");
  123. expect(host.activate).toHaveBeenCalledTimes(1);
  124. });
  125. it("keeps lifecycle versions monotonic across stop and reopen", async () => {
  126. const { lifecycle } = fixture();
  127. await lifecycle.ensureReady("a");
  128. const first = await lifecycle.getState("a");
  129. await lifecycle.stop("a");
  130. const stopped = await lifecycle.getState("a");
  131. await lifecycle.ensureReady("a");
  132. const reopened = await lifecycle.getState("a");
  133. expect(stopped.revision).toBeGreaterThan(first.revision);
  134. expect(reopened.revision).toBeGreaterThan(stopped.revision);
  135. expect(reopened.generation).toBeGreaterThan(first.generation);
  136. });
  137. it("keeps a rejected preflight ready and preserves its instance", async () => {
  138. const { lifecycle, host } = fixture();
  139. await lifecycle.ensureReady("a");
  140. host.assertCanStop.mockImplementation(() => {
  141. throw new Error("busy");
  142. });
  143. await expect(lifecycle.stop("a")).rejects.toThrow("busy");
  144. expect((await lifecycle.getState("a")).state).toBe("ready");
  145. expect(host.release).not.toHaveBeenCalled();
  146. });
  147. it("cleans partial startup and allows an explicit retry", async () => {
  148. const { lifecycle, host, runtimes } = fixture();
  149. host.activate.mockImplementationOnce(async (id) => {
  150. runtimes.add(id);
  151. throw new Error("init failed");
  152. });
  153. await expect(lifecycle.ensureReady("a")).rejects.toThrow("init failed");
  154. expect(await lifecycle.getState("a")).toMatchObject({
  155. state: "unloaded",
  156. lastError: { operation: "ensureReady" },
  157. });
  158. expect(host.release).toHaveBeenCalledTimes(1);
  159. await lifecycle.ensureReady("a");
  160. expect(await lifecycle.getState("a")).toMatchObject({ state: "ready", lastError: null });
  161. });
  162. it("quarantines failed release and never restarts or replays cleanup", async () => {
  163. const { lifecycle, host, runtimes } = fixture();
  164. await lifecycle.ensureReady("a");
  165. host.release.mockImplementation(async (id) => {
  166. runtimes.delete(id);
  167. throw new Error("resource timeout");
  168. });
  169. const stopping = lifecycle.stop("a");
  170. const waiting = lifecycle.ensureReady("a");
  171. await expect(stopping).rejects.toThrow("resource timeout");
  172. await expect(waiting).rejects.toThrow("resource timeout");
  173. expect((await lifecycle.getState("a")).state).toBe("faulted");
  174. for (const action of ["ensureReady", "stop", "restart"] as const) {
  175. await expect(lifecycle[action]("a")).rejects.toMatchObject({ code: "recoveryRequired" });
  176. }
  177. expect(host.activate).toHaveBeenCalledTimes(1);
  178. expect(host.release).toHaveBeenCalledTimes(1);
  179. });
  180. it("quarantines initialization cleanup failure with both errors retained", async () => {
  181. const { lifecycle, host } = fixture();
  182. host.activate.mockRejectedValue(new Error("init failed"));
  183. host.release.mockRejectedValue(new Error("cleanup failed"));
  184. await expect(lifecycle.ensureReady("a")).rejects.toBeInstanceOf(AggregateError);
  185. expect((await lifecycle.getState("a")).state).toBe("faulted");
  186. });
  187. });