sourceServerWorkspaceAliasRepo.concurrent.test.ts 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. import { DatabaseSync } from "node:sqlite";
  2. import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. import { join } from "node:path";
  5. import { afterEach, describe, expect, it } from "vitest";
  6. import { buildServerRemoteWorkspaceIdentity } from "@zcode/shared";
  7. import { getWorkspaceHash } from "#src/paths.js";
  8. import {
  9. SourceServerWorkspaceAliasRepo,
  10. type SourceServerWorkspaceAliasRepoOptions,
  11. } from "#src/session/sourceServerWorkspaceAliasRepo.js";
  12. import { TaskIndexRepo } from "#src/session/taskIndexRepo.js";
  13. import { seedTaskIndex } from "./helpers/taskIndexFixture.js";
  14. import { createSourceServerWorkspaceService } from "#src/source-server-workspace/sourceServerWorkspaceService.js";
  15. import { SourceServerWorkspaceIdentityMapper } from "#src/source-server-workspace/sourceServerWorkspaceIdentityChannelServer.js";
  16. const workspacePath = "/srv/project";
  17. const keyA = "remote:ssh:host-a.example.com:22:user:/srv/project";
  18. const keyB = "remote:ssh:host-b.example.com:22:user:/srv/project";
  19. const roots: string[] = [];
  20. afterEach(async () => {
  21. await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
  22. });
  23. async function setup(options: SourceServerWorkspaceAliasRepoOptions = {}) {
  24. const root = await mkdtemp(join(tmpdir(), "zcode-alias-concurrent-"));
  25. roots.push(root);
  26. const taskDbPath = join(root, "tasks-index.sqlite");
  27. const index = new TaskIndexRepo(undefined, undefined, taskDbPath);
  28. await index.ensureReady();
  29. index.close();
  30. const repo = new SourceServerWorkspaceAliasRepo({
  31. taskDbPath,
  32. sessionDbPath: join(root, "missing.sqlite"),
  33. backupRoot: join(root, "backups"),
  34. ...options,
  35. });
  36. return { root, taskDbPath, repo };
  37. }
  38. async function seedVariants(taskDbPath: string) {
  39. const index = new TaskIndexRepo(undefined, undefined, taskDbPath);
  40. try {
  41. for (const [workspaceIdentity, taskId, updatedAt] of [
  42. [keyA, "task-a", 10],
  43. [keyB, "task-b", 20],
  44. ] as const) {
  45. await seedTaskIndex(index, {
  46. meta: {
  47. taskId,
  48. traceId: `trace-${taskId}`,
  49. title: taskId,
  50. workspacePath,
  51. workspaceIdentity,
  52. createdAt: 1,
  53. updatedAt,
  54. mode: "default",
  55. status: "completed",
  56. },
  57. });
  58. }
  59. } finally {
  60. index.close();
  61. }
  62. }
  63. async function writeConfig(root: string, key: string, name: string, value: string) {
  64. const directory = join(root, "sessions", getWorkspaceHash(workspacePath, key));
  65. await mkdir(directory, { recursive: true });
  66. await writeFile(join(directory, name), value);
  67. return join(directory, name);
  68. }
  69. function readState(taskDbPath: string) {
  70. const db = new DatabaseSync(taskDbPath);
  71. try {
  72. return {
  73. alias: db
  74. .prepare("SELECT canonical_key FROM workspace_alias WHERE path = ?")
  75. .get(workspacePath),
  76. ledgers: db
  77. .prepare(
  78. "SELECT migration_id, canonical_key, status, phase FROM workspace_migration_ledger ORDER BY rowid",
  79. )
  80. .all(),
  81. tasks: db.prepare("SELECT workspace_key, task_id FROM tasks ORDER BY task_id").all(),
  82. };
  83. } finally {
  84. db.close();
  85. }
  86. }
  87. describe("Source Server canonical alias admission", () => {
  88. it.each([workspacePath, ` ${workspacePath} `])(
  89. "keeps concurrent first responses, persisted alias and mapper consistent for %s",
  90. async (secondPath) => {
  91. const { taskDbPath, repo } = await setup();
  92. const mapper = new SourceServerWorkspaceIdentityMapper();
  93. const stableIdentity = buildServerRemoteWorkspaceIdentity({
  94. serverId: "server-1",
  95. workspacePath,
  96. });
  97. const service = createSourceServerWorkspaceService(repo, {
  98. onResolved: ({ canonicalWorkspaceKey }) => {
  99. mapper.register({ stableIdentity, canonicalIdentity: canonicalWorkspaceKey });
  100. },
  101. });
  102. const responses = await Promise.all([
  103. service.resolveWorkspace({ workspacePath, legacyRouteHint: keyA }),
  104. service.resolveWorkspace({ workspacePath: secondPath, legacyRouteHint: keyB }),
  105. ]);
  106. expect(responses.map((response) => response.canonicalWorkspaceKey)).toEqual([keyA, keyA]);
  107. expect(readState(taskDbPath).alias).toEqual({ canonical_key: keyA });
  108. expect(mapper.mapIncoming(stableIdentity)).toBe(keyA);
  109. expect(mapper.mapOutgoing(keyA)).toBe(stableIdentity);
  110. },
  111. );
  112. it("merges concurrent variants and config directories once", async () => {
  113. const { root, taskDbPath, repo } = await setup();
  114. await seedVariants(taskDbPath);
  115. await writeConfig(root, keyA, "a.json", "source config");
  116. await writeConfig(root, keyB, "b.json", "canonical config");
  117. const results = await Promise.allSettled([
  118. repo.resolveCanonicalWorkspaceKey({ workspacePath, legacyRouteHint: keyA }),
  119. repo.resolveCanonicalWorkspaceKey({ workspacePath, legacyRouteHint: keyB }),
  120. ]);
  121. expect(results).toEqual([
  122. {
  123. status: "fulfilled",
  124. value: { canonicalKey: keyB, mergedKeys: [keyA], migrationId: expect.any(String) },
  125. },
  126. { status: "fulfilled", value: { canonicalKey: keyB, mergedKeys: [] } },
  127. ]);
  128. expect(readState(taskDbPath)).toEqual({
  129. alias: { canonical_key: keyB },
  130. ledgers: [
  131. {
  132. migration_id: expect.any(String),
  133. canonical_key: keyB,
  134. status: "completed",
  135. phase: "completed",
  136. },
  137. ],
  138. tasks: [
  139. { workspace_key: keyB, task_id: "task-a" },
  140. { workspace_key: keyB, task_id: "task-b" },
  141. ],
  142. });
  143. const canonicalDirectory = join(root, "sessions", getWorkspaceHash(workspacePath, keyB));
  144. expect(await readFile(join(canonicalDirectory, "a.json"), "utf8")).toBe("source config");
  145. expect(await readFile(join(canonicalDirectory, "b.json"), "utf8")).toBe("canonical config");
  146. });
  147. it.each([workspacePath, ` ${workspacePath} `])(
  148. "releases a failed migration and lets retry resume without reentering admission for %s",
  149. async (retryPath) => {
  150. let failPreflight = true;
  151. const { taskDbPath, repo } = await setup({
  152. afterPhaseCommitted: (phase) => {
  153. if (phase === "preflight" && failPreflight) {
  154. failPreflight = false;
  155. throw new Error("interrupted before backup");
  156. }
  157. },
  158. });
  159. await seedVariants(taskDbPath);
  160. await expect(repo.resolveCanonicalWorkspaceKey({ workspacePath })).rejects.toThrow(
  161. "interrupted before backup",
  162. );
  163. const [failed] = readState(taskDbPath).ledgers;
  164. expect(failed).toMatchObject({ status: "failed", phase: "preflight" });
  165. const results = await Promise.allSettled([
  166. repo.retryFailedWorkspace(retryPath),
  167. repo.resolveCanonicalWorkspaceKey({ workspacePath }),
  168. ]);
  169. expect(results).toEqual([
  170. {
  171. status: "fulfilled",
  172. value: { canonicalKey: keyB, mergedKeys: [keyA], migrationId: failed?.migration_id },
  173. },
  174. { status: "fulfilled", value: { canonicalKey: keyB, mergedKeys: [] } },
  175. ]);
  176. expect(readState(taskDbPath).ledgers).toEqual([
  177. {
  178. migration_id: failed?.migration_id,
  179. canonical_key: keyB,
  180. status: "completed",
  181. phase: "completed",
  182. },
  183. ]);
  184. },
  185. );
  186. it.each([workspacePath, ` ${workspacePath} `])(
  187. "queues abandon before resolve after a failed retry for %s",
  188. async (abandonPath) => {
  189. const { root, taskDbPath, repo } = await setup();
  190. await seedVariants(taskDbPath);
  191. const sourceConfig = await writeConfig(root, keyA, "settings.json", "source");
  192. await writeConfig(root, keyB, "settings.json", "canonical");
  193. await expect(repo.resolveCanonicalWorkspaceKey({ workspacePath })).rejects.toThrow(
  194. "config conflict",
  195. );
  196. await expect(repo.retryFailedWorkspace(workspacePath)).rejects.toThrow("config conflict");
  197. const results = await Promise.allSettled([
  198. repo.abandonFailedWorkspace(abandonPath),
  199. repo.resolveCanonicalWorkspaceKey({ workspacePath }),
  200. ]);
  201. expect(results).toEqual([
  202. { status: "fulfilled", value: undefined },
  203. { status: "fulfilled", value: { canonicalKey: keyB, mergedKeys: [] } },
  204. ]);
  205. expect(readState(taskDbPath).ledgers).toEqual([
  206. { migration_id: expect.any(String), canonical_key: keyB, status: "abandoned", phase: null },
  207. ]);
  208. await rm(sourceConfig);
  209. await expect(repo.retryFailedWorkspace(workspacePath)).resolves.toMatchObject({
  210. canonicalKey: keyB,
  211. mergedKeys: [keyA],
  212. });
  213. await expect(repo.resolveCanonicalWorkspaceKey({ workspacePath })).resolves.toEqual({
  214. canonicalKey: keyB,
  215. mergedKeys: [],
  216. });
  217. },
  218. );
  219. it("lets another path resolve while a migration is waiting for IO", async () => {
  220. const entered = Promise.withResolvers<void>();
  221. const release = Promise.withResolvers<void>();
  222. const { taskDbPath, repo } = await setup({
  223. afterPhaseCommitted: async (phase) => {
  224. if (phase !== "preflight") return;
  225. entered.resolve();
  226. await release.promise;
  227. },
  228. });
  229. await seedVariants(taskDbPath);
  230. const migration = repo.resolveCanonicalWorkspaceKey({ workspacePath });
  231. const otherPath = "/srv/other";
  232. const otherHint = "remote:ssh:host-a.example.com:22:user:/srv/other";
  233. try {
  234. await entered.promise;
  235. await expect(
  236. repo.resolveCanonicalWorkspaceKey({ workspacePath: otherPath, legacyRouteHint: otherHint }),
  237. ).resolves.toEqual({ canonicalKey: otherHint, mergedKeys: [] });
  238. } finally {
  239. release.resolve();
  240. await migration;
  241. }
  242. expect(readState(taskDbPath).alias).toEqual({ canonical_key: keyB });
  243. });
  244. });