Open History to see the last commit
1import { AVAILABLE_CONNECTION_STATE } from "@t3tools/client-runtime/connection";
2import { EnvironmentId, type ServerConfig, type ServerSelfUpdateOutcome } from "@t3tools/contracts";
3import * as Effect from "effect/Effect";
4import { AsyncResult, Atom } from "effect/reactivity";
5import { afterEach, describe, expect, it, vi } from "vite-plus/test";
6
7import { environmentCatalog } from "~/connection/catalog";
8import { appAtomRegistry } from "~/rpc/atomRegistry";
9import { serverEnvironment } from "~/state/server";
10import { toastManager } from "../ui/toast";
11import type { ServerUpdateOutcome, ServerUpdateTarget } from "../ServerUpdateAction";
12import type { RestoredRetry, UpdateEverythingRun } from "./updateEverything.logic";
13import {
14 retryFailedUpdateRunServers,
15 saveUpdateEverythingResult,
16 setUpdateEverythingRun,
17 startDesktopUpdateLaunchNotice,
18} from "./updateEverythingRun";
19
20function relaunchWhileRestarting(environmentId: EnvironmentId, updateId?: string) {
21 const now = 1_800_000_000_000;
22 vi.useFakeTimers({ now });
23 const store = new Map([
24 [
25 "t3code:update-everything-result:v1",
26 JSON.stringify({
27 savedAt: now,
28 localVersion: null,
29 updatedServers: 0,
30 updatedProviders: 0,
31 failures: [],
32 handedOff: [
33 {
34 environmentId,
35 label: "Slow",
36 targetVersion: "9.9.9",
37 startedAt: now,
38 ...(updateId === undefined ? {} : { updateId }),
39 },
40 ],
41 }),
42 ],
43 ]);
44 vi.stubGlobal("window", {
45 localStorage: {
46 getItem: (key: string) => store.get(key) ?? null,
47 removeItem: (key: string) => store.delete(key),
48 },
49 });
50 return startDesktopUpdateLaunchNotice();
51}
52
53describe("startDesktopUpdateLaunchNotice", () => {
54 afterEach(() => {
55 vi.useRealTimers();
56 vi.unstubAllGlobals();
57 });
58
59 it("keeps a restored track switch out of the capsule's retry", async () => {
60 const environmentId = EnvironmentId.make("switching-machine");
61 const now = 1_800_000_000_000;
62 vi.useFakeTimers({ now });
63 const store = new Map<string, string>();
64 vi.stubGlobal("window", {
65 localStorage: {
66 getItem: (key: string) => store.get(key) ?? null,
67 setItem: (key: string, value: string) => store.set(key, value),
68 removeItem: (key: string) => store.delete(key),
69 },
70 });
71 setUpdateEverythingRun(() => ({
72 trackSwitch: true,
73 localVersion: "9.9.9",
74 phase: "installing",
75 restartAt: null,
76 machines: [
77 {
78 environmentId,
79 label: "Switching",
80 updatesProviders: false,
81 server: null,
82 handedOffVersion: "9.9.9",
83 startedAt: now,
84 result: null,
85 failure: null,
86 providerFailure: null,
87 },
88 ],
89 }));
90 saveUpdateEverythingResult({
91 localVersion: "9.9.9",
92 updatedServers: 0,
93 updatedProviders: 0,
94 failures: [],
95 restarting: [],
96 });
97 setUpdateEverythingRun(() => null);
98
99 const stop = startDesktopUpdateLaunchNotice();
100 let run: UpdateEverythingRun | null = null;
101 setUpdateEverythingRun((current) => (run = current));
102 try {
103 expect(run).toMatchObject({ trackSwitch: true, machines: [{ environmentId }] });
104 } finally {
105 await vi.advanceTimersByTimeAsync(32 * 60 * 1000);
106 stop();
107 setUpdateEverythingRun(() => null);
108 }
109 });
110
111 it("keeps a server that is still restarting from looking idle after the app relaunches", async () => {
112 const environmentId = EnvironmentId.make("slow-machine");
113 const stop = relaunchWhileRestarting(environmentId);
114 try {
115 // Lets the registry run its cleanup of unobserved atoms before the UI mounts.
116 await vi.advanceTimersByTimeAsync(1_000);
117 expect(appAtomRegistry.get(serverEnvironment.updateStateAtom(environmentId))).toMatchObject({
118 status: "running",
119 stage: "resuming",
120 targetVersion: "9.9.9",
121 });
122 } finally {
123 await vi.advanceTimersByTimeAsync(32 * 60 * 1000);
124 stop();
125 }
126 });
127
128 it("retries the connection to a restarting server instead of waiting out its backoff", async () => {
129 const environmentId = EnvironmentId.make("backing-off-machine");
130 using _connection = vi
131 .spyOn(environmentCatalog, "stateAtom")
132 .mockReturnValue(
133 Atom.make(
134 AsyncResult.success({ ...AVAILABLE_CONNECTION_STATE, phase: "backoff" as const }),
135 ) as unknown as ReturnType<typeof environmentCatalog.stateAtom>,
136 );
137 using retryNow = vi.spyOn(environmentCatalog.retryNow, "run").mockReturnValue(Effect.void);
138 const stop = relaunchWhileRestarting(environmentId);
139 try {
140 await vi.advanceTimersByTimeAsync(1_000);
141 expect(retryNow).toHaveBeenCalledWith(appAtomRegistry, environmentId);
142 } finally {
143 await vi.advanceTimersByTimeAsync(32 * 60 * 1000);
144 stop();
145 }
146 });
147
148 it("clears the restored state when the server never comes back", async () => {
149 const environmentId = EnvironmentId.make("lost-machine");
150 const stateAtom = serverEnvironment.updateStateAtom(environmentId);
151 const stop = relaunchWhileRestarting(environmentId);
152 // Observed like the UI does, so the registry cannot reset it by dropping the atom.
153 const release = appAtomRegistry.mount(stateAtom);
154 try {
155 await vi.advanceTimersByTimeAsync(32 * 60 * 1000);
156 expect(appAtomRegistry.get(stateAtom)).toEqual({ status: "idle" });
157 } finally {
158 release();
159 stop();
160 }
161 });
162
163 it("reports this update's rollback instead of restarting until the timeout", async () => {
164 const environmentId = EnvironmentId.make("rolled-back-machine");
165 const stateAtom = serverEnvironment.updateStateAtom(environmentId);
166 const outcomeAtom = Atom.make<AsyncResult.AsyncResult<ServerSelfUpdateOutcome>>(
167 AsyncResult.initial(),
168 );
169 using _outcome = vi.spyOn(serverEnvironment, "updateOutcome").mockReturnValue(outcomeAtom);
170 using addToast = vi.spyOn(toastManager, "add");
171 const stop = relaunchWhileRestarting(environmentId, "update-2");
172 const release = appAtomRegistry.mount(stateAtom);
173 const outcome = (id: string, reason: string) =>
174 AsyncResult.success<ServerSelfUpdateOutcome>({
175 id,
176 fromVersion: "9.9.8",
177 targetVersion: "9.9.9",
178 status: "rolled-back",
179 reason,
180 });
181 try {
182 expect(appAtomRegistry.get(stateAtom)).toMatchObject({
183 status: "running",
184 updateId: "update-2",
185 });
186 appAtomRegistry.set(outcomeAtom, outcome("update-1", "an earlier attempt"));
187 expect(appAtomRegistry.get(stateAtom)).toMatchObject({ status: "running" });
188
189 appAtomRegistry.set(outcomeAtom, outcome("update-2", "candidate-exited:1"));
190 expect(appAtomRegistry.get(stateAtom)).toEqual({ status: "idle" });
191 expect(addToast).toHaveBeenCalledWith(
192 expect.objectContaining({
193 type: "error",
194 description: expect.objectContaining({
195 props: expect.objectContaining({ children: "Slow: candidate-exited:1" }),
196 }),
197 }),
198 );
199 } finally {
200 release();
201 stop();
202 }
203 });
204});
205
206describe("retryFailedUpdateRunServers", () => {
207 it("settles a failed server that already restarted on the target and retries only the others", () => {
208 const targetVersion = "9.9.9";
209 const serverVersions = new Map([
210 [EnvironmentId.make("already-updated"), targetVersion],
211 [EnvironmentId.make("behind"), "9.9.8"],
212 ]);
213 using _config = vi
214 .spyOn(serverEnvironment, "configValueAtom")
215 .mockImplementation((environmentId) =>
216 Atom.make({
217 environment: { serverVersion: serverVersions.get(environmentId!) },
218 } as unknown as ServerConfig),
219 );
220 const rejection = "Remote updates must select a newer server version.";
221 const failedMachine = (environmentId: EnvironmentId) => ({
222 environmentId,
223 label: environmentId,
224 updatesProviders: false,
225 server: {
226 environmentId,
227 serverLabel: environmentId,
228 selfUpdate: "boot-service" as const,
229 targetVersion,
230 },
231 handedOffVersion: null,
232 startedAt: 0,
233 result: "failed" as const,
234 failure: rejection,
235 providerFailure: null,
236 });
237 setUpdateEverythingRun(() => ({
238 localVersion: null,
239 phase: "servers",
240 restartAt: null,
241 machines: [...serverVersions.keys()].map(failedMachine),
242 }));
243 const update = vi.fn(
244 (_target: ServerUpdateTarget) => new Promise<ServerUpdateOutcome>(() => {}),
245 );
246
247 retryFailedUpdateRunServers(update);
248
249 let run: UpdateEverythingRun | null = null;
250 setUpdateEverythingRun((current) => {
251 run = current;
252 return null;
253 });
254 expect(update.mock.calls.map(([target]) => target.environmentId)).toEqual(["behind"]);
255 expect(
256 (run as UpdateEverythingRun | null)?.machines.map(({ environmentId, result, server }) => ({
257 environmentId,
258 result,
259 retryable: server !== null,
260 })),
261 ).toEqual([
262 { environmentId: "already-updated", result: "done", retryable: false },
263 { environmentId: "behind", result: null, retryable: true },
264 ]);
265 });
266
267 it("retries a row restored after a relaunch with the target it is given", () => {
268 const environmentId = EnvironmentId.make("restored");
269 const currentId = EnvironmentId.make("restored-current");
270 // Rendered as current, but the server went back to the old version before the click.
271 const staleId = EnvironmentId.make("restored-stale");
272 using _config = vi.spyOn(serverEnvironment, "configValueAtom").mockImplementation((id) =>
273 Atom.make({
274 environment: { serverVersion: id === currentId ? "9.9.9" : "9.9.8" },
275 } as unknown as ServerConfig),
276 );
277 setUpdateEverythingRun(() => ({
278 localVersion: null,
279 phase: "servers",
280 restartAt: null,
281 machines: [
282 {
283 environmentId,
284 label: "restored",
285 updatesProviders: false,
286 server: null,
287 handedOffVersion: "9.9.9",
288 startedAt: 0,
289 result: "failed",
290 failure: "Not back after 32 minutes",
291 providerFailure: null,
292 },
293 {
294 environmentId: currentId,
295 label: "restored-current",
296 updatesProviders: false,
297 server: null,
298 handedOffVersion: "9.9.9",
299 startedAt: 0,
300 result: "failed",
301 failure: "Not back after 32 minutes",
302 providerFailure: null,
303 },
304 {
305 environmentId: staleId,
306 label: "restored-stale",
307 updatesProviders: false,
308 server: null,
309 handedOffVersion: "9.9.9",
310 startedAt: 0,
311 result: "failed",
312 failure: "Not back after 32 minutes",
313 providerFailure: null,
314 },
315 ],
316 }));
317 const target: ServerUpdateTarget = {
318 environmentId,
319 serverLabel: "restored",
320 selfUpdate: "boot-service",
321 targetVersion: "9.9.9",
322 };
323 const update = vi.fn(
324 (_target: ServerUpdateTarget) => new Promise<ServerUpdateOutcome>(() => {}),
325 );
326
327 retryFailedUpdateRunServers(
328 update,
329 new Map<EnvironmentId, RestoredRetry>([
330 [environmentId, target],
331 [currentId, "current"],
332 [staleId, "current"],
333 ]),
334 );
335
336 let run: UpdateEverythingRun | null = null;
337 setUpdateEverythingRun((current) => {
338 run = current;
339 return null;
340 });
341 expect(update.mock.calls.map(([called]) => called)).toEqual([target]);
342 // Downloading again, not "restarting" from the old handoff, and retryable if it fails again.
343 expect((run as UpdateEverythingRun | null)?.machines).toMatchObject([
344 { result: null, server: target, handedOffVersion: null },
345 { result: "done", failure: null },
346 { result: "failed", failure: "Not back after 32 minutes" },
347 ]);
348 });
349});