Open History to see the last commit
1import { AVAILABLE_CONNECTION_STATE } from "@t3tools/client-runtime/connection";
2import { EnvironmentId, type ServerConfig } from "@t3tools/contracts";
3import { AsyncResult, Atom } from "effect/reactivity";
4import { afterEach, describe, expect, it, vi } from "vite-plus/test";
5
6import { environmentCatalog } from "~/connection/catalog";
7import { appAtomRegistry } from "~/rpc/atomRegistry";
8import { serverEnvironment } from "~/state/server";
9import type { ServerUpdateOutcome, ServerUpdateTarget } from "../ServerUpdateAction";
10import type { UpdateEverythingRun } from "./updateEverything.logic";
11import {
12 retryFailedUpdateRunServers,
13 setUpdateEverythingRun,
14 startDesktopUpdateLaunchNotice,
15} from "./updateEverythingRun";
16
17function relaunchWhileRestarting(environmentId: EnvironmentId) {
18 const now = 1_800_000_000_000;
19 vi.useFakeTimers({ now });
20 const store = new Map([
21 [
22 "t3code:update-everything-result:v1",
23 JSON.stringify({
24 savedAt: now,
25 localVersion: null,
26 updatedServers: 0,
27 updatedProviders: 0,
28 failures: [],
29 handedOff: [{ environmentId, label: "Slow", targetVersion: "9.9.9", startedAt: now }],
30 }),
31 ],
32 ]);
33 vi.stubGlobal("window", {
34 localStorage: {
35 getItem: (key: string) => store.get(key) ?? null,
36 removeItem: (key: string) => store.delete(key),
37 },
38 });
39 return startDesktopUpdateLaunchNotice();
40}
41
42describe("startDesktopUpdateLaunchNotice", () => {
43 afterEach(() => {
44 vi.useRealTimers();
45 vi.unstubAllGlobals();
46 });
47
48 it("keeps a server that is still restarting from looking idle after the app relaunches", async () => {
49 const environmentId = EnvironmentId.make("slow-machine");
50 const stop = relaunchWhileRestarting(environmentId);
51 try {
52 // Lets the registry run its cleanup of unobserved atoms before the UI mounts.
53 await vi.advanceTimersByTimeAsync(1_000);
54 expect(appAtomRegistry.get(serverEnvironment.updateStateAtom(environmentId))).toMatchObject({
55 status: "running",
56 stage: "resuming",
57 targetVersion: "9.9.9",
58 });
59 } finally {
60 await vi.advanceTimersByTimeAsync(32 * 60 * 1000);
61 stop();
62 }
63 });
64
65 it("retries the connection to a restarting server instead of waiting out its backoff", async () => {
66 const environmentId = EnvironmentId.make("backing-off-machine");
67 using _connection = vi
68 .spyOn(environmentCatalog, "stateAtom")
69 .mockReturnValue(
70 Atom.make(
71 AsyncResult.success({ ...AVAILABLE_CONNECTION_STATE, phase: "backoff" as const }),
72 ) as unknown as ReturnType<typeof environmentCatalog.stateAtom>,
73 );
74 using retryNow = vi
75 .spyOn(environmentCatalog.retryNow, "run")
76 .mockResolvedValue(AsyncResult.success(undefined));
77 const stop = relaunchWhileRestarting(environmentId);
78 try {
79 await vi.advanceTimersByTimeAsync(1_000);
80 expect(retryNow).toHaveBeenCalledWith(appAtomRegistry, environmentId);
81 } finally {
82 await vi.advanceTimersByTimeAsync(32 * 60 * 1000);
83 stop();
84 }
85 });
86
87 it("clears the restored state when the server never comes back", async () => {
88 const environmentId = EnvironmentId.make("lost-machine");
89 const stateAtom = serverEnvironment.updateStateAtom(environmentId);
90 const stop = relaunchWhileRestarting(environmentId);
91 // Observed like the UI does, so the registry cannot reset it by dropping the atom.
92 const release = appAtomRegistry.mount(stateAtom);
93 try {
94 await vi.advanceTimersByTimeAsync(32 * 60 * 1000);
95 expect(appAtomRegistry.get(stateAtom)).toEqual({ status: "idle" });
96 } finally {
97 release();
98 stop();
99 }
100 });
101});
102
103describe("retryFailedUpdateRunServers", () => {
104 it("settles a failed server that already restarted on the target and retries only the others", () => {
105 const targetVersion = "9.9.9";
106 const serverVersions = new Map([
107 [EnvironmentId.make("already-updated"), targetVersion],
108 [EnvironmentId.make("behind"), "9.9.8"],
109 ]);
110 using _config = vi
111 .spyOn(serverEnvironment, "configValueAtom")
112 .mockImplementation((environmentId) =>
113 Atom.make({
114 environment: { serverVersion: serverVersions.get(environmentId!) },
115 } as unknown as ServerConfig),
116 );
117 const rejection = "Remote updates must select a newer server version.";
118 const failedMachine = (environmentId: EnvironmentId) => ({
119 environmentId,
120 label: environmentId,
121 updatesProviders: false,
122 server: {
123 environmentId,
124 serverLabel: environmentId,
125 selfUpdate: "boot-service" as const,
126 targetVersion,
127 },
128 handedOffVersion: null,
129 startedAt: 0,
130 result: "failed" as const,
131 failure: rejection,
132 providerFailure: null,
133 });
134 setUpdateEverythingRun(() => ({
135 localVersion: null,
136 phase: "servers",
137 restartAt: null,
138 machines: [...serverVersions.keys()].map(failedMachine),
139 }));
140 const update = vi.fn(
141 (_target: ServerUpdateTarget) => new Promise<ServerUpdateOutcome>(() => {}),
142 );
143
144 retryFailedUpdateRunServers(update);
145
146 let run: UpdateEverythingRun | null = null;
147 setUpdateEverythingRun((current) => {
148 run = current;
149 return null;
150 });
151 expect(update.mock.calls.map(([target]) => target.environmentId)).toEqual(["behind"]);
152 expect(
153 (run as UpdateEverythingRun | null)?.machines.map(({ environmentId, result, server }) => ({
154 environmentId,
155 result,
156 retryable: server !== null,
157 })),
158 ).toEqual([
159 { environmentId: "already-updated", result: "done", retryable: false },
160 { environmentId: "behind", result: null, retryable: true },
161 ]);
162 });
163});