sourceServerUpdateCancellation.test.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. import { PassThrough } from "node:stream";
  2. import { describe, expect, it, vi } from "vitest";
  3. import { appSettingsSchema, type ServerRemoteInfo } from "@zcode/shared";
  4. import type { IServiceAccessor } from "@zcode/services";
  5. import type { ServerReleaseAsset, SourceServerTransportAdapter } from "@zcode/server/source-server";
  6. import { SourceServerConnectionManager } from "@desktop/host/sourceServerConnectionManager.js";
  7. import { SourceServerDirectory } from "@desktop/host/sourceServerDirectory.js";
  8. import { createSourceServerManagementService } from "@desktop/host/sourceServerManagementService.js";
  9. const profileId = "17ef20b3-622d-4a53-98c1-0cdff29f3e6d";
  10. const sourceServerId = "3cd4f9da-cd79-426c-9d70-75f36e9f6a87";
  11. const target = { kind: "docker", container: "update-cancellation" } as const;
  12. const serverInfo: ServerRemoteInfo = {
  13. serverId: sourceServerId,
  14. version: "3.8.0",
  15. protocolVersion: 1,
  16. authRequired: true,
  17. workspaces: [],
  18. compatibility: { schemaVersion: 1, productVersion: "3.8.0", minCompatibleVersion: "3.8.0" },
  19. identity: { osUser: "dev", hostname: "example" },
  20. migration: { failedPathCount: 0 },
  21. capabilities: { desktopContinuous: true, websocketRpc: true },
  22. };
  23. const release: ServerReleaseAsset = {
  24. localArchivePath: "/tmp/server.tar.gz",
  25. target: "linux-x64",
  26. version: "3.8.0",
  27. sha256: "a".repeat(64),
  28. sizeBytes: 1024,
  29. urls: ["https://example.com/server.tar.gz"],
  30. };
  31. async function setup(bound = true) {
  32. let settings = appSettingsSchema.parse({ sourceServerDirectoryMigrationVersion: 1 });
  33. let profileSequence = 0;
  34. const directory = new SourceServerDirectory({
  35. settingService: {
  36. get: async () => settings,
  37. update: async (patch) => {
  38. settings = appSettingsSchema.parse({ ...settings, ...patch });
  39. },
  40. } as never,
  41. credentialService: { load: async () => null, save: async () => {}, delete: async () => {} },
  42. createProfileId: () => [
  43. profileId,
  44. "4f0f4d21-2798-4608-9d44-889f9f3dc777",
  45. "78462780-a3bb-4701-a709-a1ecb1dfb39e",
  46. ][profileSequence++]!,
  47. });
  48. const adapter: SourceServerTransportAdapter = {
  49. kind: "docker",
  50. probe: vi.fn(async () => ({
  51. platform: "linux",
  52. arch: "x64",
  53. installed: true,
  54. installedVersion: "3.8.0",
  55. })),
  56. installOrUpdate: vi.fn(async () => {}),
  57. ensureDaemon: vi.fn(async () => ({ port: 43123, ingressToken: "test-token" })),
  58. openChannel: vi.fn(async () => new PassThrough()),
  59. exec: vi.fn(async () => ({ exitCode: 0, stdout: "[]", stderr: "" })),
  60. createFileTransfer: vi.fn(),
  61. cancel: vi.fn(),
  62. };
  63. const closeHandlers: Array<() => void> = [];
  64. const connectServer = vi.fn(async (options) => {
  65. closeHandlers.push(() => options.onClose?.({ code: 1006, reason: "test transport closed" }));
  66. return { serverInfo, services: {} as IServiceAccessor, dispose: vi.fn() };
  67. });
  68. const resolveRelease = vi.fn(async () => release);
  69. const manager = new SourceServerConnectionManager({
  70. directory,
  71. createAdapter: () => adapter,
  72. connectServer,
  73. compatibilityManifest: serverInfo.compatibility!,
  74. });
  75. const management = createSourceServerManagementService({ directory, manager, resolveRelease });
  76. let profile = await directory.ensureProfile(target);
  77. if (bound) {
  78. await manager.connect({ profile, target });
  79. profile = (await directory.snapshot()).profiles[0]!;
  80. }
  81. const reconnected = vi.fn();
  82. manager.onDidReconnect(reconnected);
  83. return {
  84. directory,
  85. adapter,
  86. manager,
  87. management,
  88. profile,
  89. connectServer,
  90. resolveRelease,
  91. closeHandlers,
  92. reconnected,
  93. async addSiblingProfile(container: string) {
  94. const sibling = await directory.ensureProfile({ kind: "docker", container });
  95. await directory.recordHandshake(sibling.profileId, {
  96. sourceServerId,
  97. version: serverInfo.version,
  98. workspaces: [],
  99. });
  100. return sibling.profileId;
  101. },
  102. dispose() {
  103. management.dispose();
  104. manager.dispose();
  105. },
  106. };
  107. }
  108. function hold() {
  109. const entered = Promise.withResolvers<void>();
  110. const settled = Promise.withResolvers<void>();
  111. return {
  112. entered: entered.promise,
  113. finish: settled.resolve,
  114. fail: settled.reject,
  115. async wait() {
  116. entered.resolve();
  117. await settled.promise;
  118. },
  119. };
  120. }
  121. function observe<T>(promise: Promise<T>) {
  122. return promise.then(
  123. (value) => ({ value, error: undefined }),
  124. (error) => ({ value: undefined, error }),
  125. );
  126. }
  127. describe("Source update cancellation", () => {
  128. it.each(["retry", "offline-probe"] as const)(
  129. "dispose prevents late %s failure from restarting recovery",
  130. async (phase) => {
  131. vi.useFakeTimers();
  132. const f = await setup();
  133. const gate = hold();
  134. try {
  135. if (phase === "offline-probe") {
  136. vi.mocked(f.adapter.probe)
  137. .mockRejectedValueOnce(new Error("offline"))
  138. .mockRejectedValueOnce(new Error("offline"))
  139. .mockRejectedValueOnce(new Error("offline"));
  140. }
  141. vi.mocked(f.adapter.probe).mockImplementationOnce(async () => {
  142. await gate.wait();
  143. return { platform: "linux", arch: "x64", installed: true, installedVersion: "3.8.0" };
  144. });
  145. f.closeHandlers[0]!();
  146. await vi.advanceTimersByTimeAsync(phase === "retry" ? 2_000 : 14_000 + 120_000);
  147. await gate.entered;
  148. f.manager.dispose();
  149. gate.finish();
  150. await vi.advanceTimersByTimeAsync(14_000 + 120_000);
  151. expect(f.connectServer).toHaveBeenCalledOnce();
  152. expect(f.manager.getOnlineConnection(sourceServerId)).toBeUndefined();
  153. expect(f.reconnected).not.toHaveBeenCalled();
  154. expect(f.manager.getStateByProfile(profileId).state).toBe("offline");
  155. expect(vi.getTimerCount()).toBe(0);
  156. } finally {
  157. gate.finish();
  158. f.dispose();
  159. vi.useRealTimers();
  160. }
  161. },
  162. );
  163. it.each(["probe", "release", "install", "handshake", "running-tasks"] as const)(
  164. "explicit disconnect wins while %s is pending",
  165. async (phase) => {
  166. const f = await setup();
  167. const gate = hold();
  168. if (phase === "probe")
  169. vi.mocked(f.adapter.probe).mockImplementationOnce(async () => {
  170. await gate.wait();
  171. return { platform: "linux", arch: "x64", installed: true, installedVersion: "3.8.0" };
  172. });
  173. if (phase === "release")
  174. f.resolveRelease.mockImplementationOnce(async () => {
  175. await gate.wait();
  176. return release;
  177. });
  178. if (phase === "install")
  179. vi.mocked(f.adapter.installOrUpdate).mockImplementationOnce(gate.wait);
  180. if (phase === "handshake") {
  181. const original = f.directory.recordHandshake.bind(f.directory);
  182. vi.spyOn(f.directory, "recordHandshake").mockImplementationOnce(async (...args) => {
  183. await gate.wait();
  184. return original(...args);
  185. });
  186. }
  187. if (phase === "running-tasks") {
  188. vi.mocked(f.adapter.installOrUpdate).mockRejectedValueOnce(
  189. Object.assign(new Error("running tasks"), {
  190. code: "source-server-update-running-tasks",
  191. retryable: false,
  192. }),
  193. );
  194. vi.mocked(f.adapter.exec).mockImplementationOnce(async () => {
  195. await gate.wait();
  196. return { exitCode: 0, stdout: "[]", stderr: "" };
  197. });
  198. }
  199. try {
  200. const updating = observe(f.management.updateSource({ profileId }));
  201. await gate.entered;
  202. await f.management.disconnectSource(sourceServerId);
  203. const terminalState = f.manager.getStateByProfile(profileId);
  204. expect(terminalState.state).toBe("offline");
  205. gate.finish();
  206. expect((await updating).error).toMatchObject({ code: "remote-connection-canceled" });
  207. expect(f.manager.getStateByProfile(profileId)).toEqual(terminalState);
  208. expect(f.manager.getOnlineConnection(sourceServerId)).toBeUndefined();
  209. expect(f.reconnected).not.toHaveBeenCalled();
  210. expect(f.connectServer).toHaveBeenCalledTimes(phase === "handshake" ? 2 : 1);
  211. } finally {
  212. gate.finish();
  213. f.dispose();
  214. }
  215. },
  216. );
  217. it.each([true, false])(
  218. "removing a Profile during install stays removed (bound=%s)",
  219. async (bound) => {
  220. const f = await setup(bound);
  221. const gate = hold();
  222. vi.mocked(f.adapter.installOrUpdate).mockImplementationOnce(gate.wait);
  223. try {
  224. const updating = observe(f.management.updateSource({ profileId }));
  225. await gate.entered;
  226. await f.management.removeProfile(profileId);
  227. gate.finish();
  228. expect((await updating).error).toBeInstanceOf(Error);
  229. expect(f.manager.getStateByProfile(profileId).state).toBe("absent");
  230. expect((await f.directory.snapshot()).profiles).toEqual([]);
  231. expect(f.connectServer).toHaveBeenCalledTimes(bound ? 1 : 0);
  232. expect(f.manager.getOnlineConnection(sourceServerId)).toBeUndefined();
  233. } finally {
  234. gate.finish();
  235. f.dispose();
  236. }
  237. },
  238. );
  239. it.each(["success", "failure"] as const)(
  240. "removing a non-current update Profile restores the original owner before late %s",
  241. async (outcome) => {
  242. vi.useFakeTimers();
  243. const f = await setup();
  244. const gate = hold();
  245. try {
  246. const siblingId = await f.addSiblingProfile("update-route-b");
  247. vi.mocked(f.adapter.installOrUpdate).mockImplementationOnce(gate.wait);
  248. const updating = observe(f.management.updateSource({ profileId: siblingId }));
  249. await gate.entered;
  250. f.closeHandlers[0]!();
  251. expect(f.manager.getStateByProfile(profileId).state).toBe("updating");
  252. await f.management.removeProfile(siblingId);
  253. expect(f.manager.getStateByProfile(profileId).state).toBe("retrying");
  254. expect(f.manager.getStateByProfile(siblingId).state).toBe("absent");
  255. await vi.advanceTimersByTimeAsync(2_000);
  256. const recovered = f.manager.getOnlineConnection(sourceServerId);
  257. expect(recovered).toMatchObject({ profileId, sourceServerId });
  258. expect(vi.mocked(f.adapter.probe).mock.lastCall?.[0]).toBe(target);
  259. expect(f.reconnected).toHaveBeenCalledOnce();
  260. if (outcome === "success") gate.finish();
  261. else gate.fail(new Error("late install failure"));
  262. expect((await updating).error).toBeInstanceOf(Error);
  263. expect(f.manager.getOnlineConnection(sourceServerId)).toBe(recovered);
  264. expect(f.manager.getStateByProfile(profileId).state).toBe("online");
  265. expect((await f.directory.snapshot()).profiles.map((profile) => profile.profileId)).toEqual([
  266. profileId,
  267. ]);
  268. expect(f.connectServer).toHaveBeenCalledTimes(2);
  269. } finally {
  270. gate.finish();
  271. f.dispose();
  272. vi.useRealTimers();
  273. }
  274. },
  275. );
  276. it("does not reconnect a healthy owner when its non-current update Profile is removed", async () => {
  277. vi.useFakeTimers();
  278. const f = await setup();
  279. const gate = hold();
  280. try {
  281. const siblingId = await f.addSiblingProfile("update-route-b");
  282. const original = f.manager.getOnlineConnection(sourceServerId);
  283. vi.mocked(f.adapter.installOrUpdate).mockImplementationOnce(gate.wait);
  284. const updating = observe(f.management.updateSource({ profileId: siblingId }));
  285. await gate.entered;
  286. await f.management.removeProfile(siblingId);
  287. gate.finish();
  288. expect((await updating).error).toBeInstanceOf(Error);
  289. await vi.advanceTimersByTimeAsync(14_000);
  290. expect(f.manager.getOnlineConnection(sourceServerId)).toBe(original);
  291. expect(f.manager.getStateByProfile(profileId).state).toBe("online");
  292. expect(f.connectServer).toHaveBeenCalledOnce();
  293. expect(f.reconnected).not.toHaveBeenCalled();
  294. } finally {
  295. gate.finish();
  296. f.dispose();
  297. vi.useRealTimers();
  298. }
  299. });
  300. it("leaves recovery to another update still in flight", async () => {
  301. vi.useFakeTimers();
  302. const f = await setup();
  303. const removedGate = hold();
  304. const retainedGate = hold();
  305. try {
  306. const siblingId = await f.addSiblingProfile("update-route-b");
  307. const retainedId = await f.addSiblingProfile("update-route-c");
  308. vi.mocked(f.adapter.installOrUpdate)
  309. .mockImplementationOnce(removedGate.wait)
  310. .mockImplementationOnce(retainedGate.wait);
  311. const removedUpdate = observe(f.management.updateSource({ profileId: siblingId }));
  312. await removedGate.entered;
  313. const retainedUpdate = observe(f.management.updateSource({ profileId: retainedId }));
  314. await retainedGate.entered;
  315. f.closeHandlers[0]!();
  316. await f.management.removeProfile(siblingId);
  317. removedGate.finish();
  318. expect((await removedUpdate).error).toBeInstanceOf(Error);
  319. await vi.advanceTimersByTimeAsync(14_000);
  320. expect(f.manager.getStateByProfile(profileId).state).toBe("updating");
  321. expect(f.connectServer).toHaveBeenCalledOnce();
  322. retainedGate.fail(new Error("retained update failed"));
  323. expect((await retainedUpdate).error).toBeInstanceOf(Error);
  324. await vi.advanceTimersByTimeAsync(2_000);
  325. expect(f.manager.getOnlineConnection(sourceServerId)).toMatchObject({ profileId });
  326. } finally {
  327. removedGate.finish();
  328. retainedGate.finish();
  329. f.dispose();
  330. vi.useRealTimers();
  331. }
  332. });
  333. it.each(["disconnect", "remove-owner", "dispose"] as const)(
  334. "%s cancels recovery handed back by non-current Profile removal",
  335. async (terminal) => {
  336. vi.useFakeTimers();
  337. const f = await setup();
  338. const gate = hold();
  339. try {
  340. const siblingId = await f.addSiblingProfile("update-route-b");
  341. vi.mocked(f.adapter.installOrUpdate).mockImplementationOnce(gate.wait);
  342. const updating = observe(f.management.updateSource({ profileId: siblingId }));
  343. await gate.entered;
  344. f.closeHandlers[0]!();
  345. await f.management.removeProfile(siblingId);
  346. expect(f.manager.getStateByProfile(profileId).state).toBe("retrying");
  347. if (terminal === "disconnect") await f.management.disconnectSource(sourceServerId);
  348. else if (terminal === "remove-owner") await f.management.removeProfile(profileId);
  349. else f.manager.dispose();
  350. const terminalState = f.manager.getStateByProfile(profileId);
  351. gate.finish();
  352. expect((await updating).error).toBeInstanceOf(Error);
  353. await vi.advanceTimersByTimeAsync(14_000 + 120_000);
  354. if (terminal === "remove-owner")
  355. expect(f.manager.listStates().some((state) => state.profileId === profileId)).toBe(false);
  356. else expect(f.manager.getStateByProfile(profileId)).toEqual(terminalState);
  357. expect(f.manager.getOnlineConnection(sourceServerId)).toBeUndefined();
  358. expect(f.connectServer).toHaveBeenCalledOnce();
  359. } finally {
  360. gate.finish();
  361. f.dispose();
  362. vi.useRealTimers();
  363. }
  364. },
  365. );
  366. it.each(["install", "handshake"] as const)(
  367. "dispose cancels an update waiting for %s",
  368. async (phase) => {
  369. const f = await setup();
  370. const gate = hold();
  371. if (phase === "install")
  372. vi.mocked(f.adapter.installOrUpdate).mockImplementationOnce(gate.wait);
  373. else {
  374. const original = f.directory.recordHandshake.bind(f.directory);
  375. vi.spyOn(f.directory, "recordHandshake").mockImplementationOnce(async (...args) => {
  376. await gate.wait();
  377. return original(...args);
  378. });
  379. }
  380. try {
  381. const updating = observe(f.management.updateSource({ profileId }));
  382. await gate.entered;
  383. f.manager.dispose();
  384. const afterDispose = f.manager.getStateByProfile(profileId);
  385. gate.finish();
  386. expect((await updating).error).toMatchObject({ code: "remote-connection-canceled" });
  387. expect(f.manager.getStateByProfile(profileId)).toEqual(afterDispose);
  388. expect(f.manager.getOnlineConnection(sourceServerId)).toBeUndefined();
  389. } finally {
  390. gate.finish();
  391. f.management.dispose();
  392. }
  393. },
  394. );
  395. it.each(["success", "failure"] as const)(
  396. "a canceled update's late %s cannot replace a newer connection or suppress recovery",
  397. async (outcome) => {
  398. vi.useFakeTimers();
  399. const f = await setup();
  400. const gate = hold();
  401. vi.mocked(f.adapter.installOrUpdate).mockImplementationOnce(gate.wait);
  402. try {
  403. const updating = observe(f.manager.updateServer({ profile: f.profile, target, release }));
  404. await gate.entered;
  405. f.manager.disconnect(sourceServerId);
  406. await f.manager.connect({ profile: f.profile, target });
  407. const newer = f.manager.getOnlineConnection(sourceServerId);
  408. f.closeHandlers[1]!();
  409. expect(f.manager.getStateByProfile(profileId).state).toBe("retrying");
  410. await vi.advanceTimersByTimeAsync(2000);
  411. const recovered = f.manager.getOnlineConnection(sourceServerId);
  412. expect(recovered).toBeDefined();
  413. expect(recovered).not.toBe(newer);
  414. if (outcome === "success") gate.finish();
  415. else gate.fail(new Error("late install failure"));
  416. expect((await updating).error).toMatchObject({ code: "remote-connection-canceled" });
  417. expect(f.manager.getOnlineConnection(sourceServerId)).toBe(recovered);
  418. expect(f.connectServer).toHaveBeenCalledTimes(3);
  419. } finally {
  420. gate.finish();
  421. f.dispose();
  422. vi.useRealTimers();
  423. }
  424. },
  425. );
  426. it("preserves disconnect issued by an invalidation observer before starting the new handshake", async () => {
  427. const f = await setup();
  428. let terminalState;
  429. f.manager.onDidInvalidateConnection(() => {
  430. f.manager.disconnect(sourceServerId);
  431. terminalState = f.manager.getStateByProfile(profileId);
  432. });
  433. try {
  434. const result = await observe(f.manager.updateServer({ profile: f.profile, target, release }));
  435. expect(result.error).toMatchObject({ code: "remote-connection-canceled" });
  436. expect(f.manager.getStateByProfile(profileId)).toEqual(terminalState);
  437. expect(f.connectServer).toHaveBeenCalledOnce();
  438. } finally {
  439. f.dispose();
  440. }
  441. });
  442. it("keeps normal update invalidation and reconnect", async () => {
  443. const f = await setup();
  444. const caller = new AbortController();
  445. const invalidated = vi.fn();
  446. f.manager.onDidInvalidateConnection(invalidated);
  447. try {
  448. await f.manager.updateServer({
  449. profile: f.profile,
  450. target,
  451. release,
  452. context: { signal: caller.signal },
  453. });
  454. const signal = vi.mocked(f.adapter.installOrUpdate).mock.calls[0]![2].signal;
  455. expect(signal).toBeDefined();
  456. expect(signal?.aborted).toBe(false);
  457. expect(invalidated).toHaveBeenCalledOnce();
  458. expect(f.reconnected).toHaveBeenCalledOnce();
  459. expect(f.manager.getStateByProfile(profileId).state).toBe("online");
  460. } finally {
  461. f.dispose();
  462. }
  463. });
  464. });