Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

updateEverythingRun.tsx

375 lines12.4 KB

1import { useAtomValue } from "@effect/atom-react";
2import { EnvironmentId } from "@t3tools/contracts";
3import * as Option from "effect/Option";
4import * as Schema from "effect/Schema";
5import { Atom } from "effect/reactivity";
6import { useEffect } from "react";
7​
8import { APP_VERSION } from "~/branding";
9import { appAtomRegistry } from "~/rpc/atomRegistry";
10import { useDesktopUpdateState } from "~/state/desktopUpdate";
11import { serverEnvironment } from "~/state/server";
12import { resolveVersionMismatch } from "~/versionSkew";
13import type { ServerUpdateOutcome, ServerUpdateTarget } from "../ServerUpdateAction";
14import { stackedThreadToast, toastManager } from "../ui/toast";
15import {
16 closeFinishedUpdateRun,
17 getUpdateEverythingToastView,
18 isServerUpdateHandedOff,
19 type UpdateEverythingResult,
20 type UpdateEverythingRun,
21 type UpdateRunMachine,
22} from "./updateEverything.logic";
23​
24/** The running "update everything" pass, or null. Outlives the sidebar button. */
25const updateEverythingRunAtom = Atom.make<UpdateEverythingRun | null>(null).pipe(
26 Atom.keepAlive,
27 Atom.withLabel("update-everything-run"),
28);
29​
30export function useUpdateEverythingRun(): UpdateEverythingRun | null {
31 return useAtomValue(updateEverythingRunAtom);
33​
34/** Starts, changes, or ends (null) the running pass. */
35export function setUpdateEverythingRun(
36 update: (run: UpdateEverythingRun | null) => UpdateEverythingRun | null,
37): void {
38 appAtomRegistry.update(updateEverythingRunAtom, update);
40​
41function updateRunMachines(update: (machine: UpdateRunMachine) => UpdateRunMachine): void {
42 setUpdateEverythingRun(
43 (run) => run && closeFinishedUpdateRun({ ...run, machines: run.machines.map(update) }),
44 );
46​
47/** Records the result of every update for one machine. `failure` is null when
48 it succeeded. A server that updated is no longer retried, even when the
49 machine failed for its providers. The run ends once every machine is done. */
50export function settleUpdateRunMachine(
51 environmentId: EnvironmentId,
52 failure: string | null,
53 {
54 serverUpdated = false,
55 providerFailure,
56 }: { readonly serverUpdated?: boolean; readonly providerFailure?: string | null } = {},
57): void {
58 updateRunMachines((machine) =>
59 machine.environmentId === environmentId
60 ? {
61 ...machine,
62 result: failure === null ? "done" : "failed",
63 failure,
64 ...(serverUpdated ? { server: null } : {}),
65 ...(providerFailure === undefined ? {} : { providerFailure }),
66 }
67 : machine,
68 );
70​
71/** Retries each failed server update in the run. */
72export function retryFailedUpdateRunServers(
73 update: (
74 target: ServerUpdateTarget,
75 options: { readonly quiet: boolean },
76 ) => Promise<ServerUpdateOutcome>,
77): void {
78 const failed = (appAtomRegistry.get(updateEverythingRunAtom)?.machines ?? []).flatMap(
79 (machine) =>
80 machine.result === "failed" && machine.server !== null
81 ? [{ target: machine.server, providerFailure: machine.providerFailure }]
82 : [],
83 );
84 const targets = failed.map(({ target }) => target);
85 const retried = new Set(targets.map((target) => target.environmentId));
86 const startedAt = Date.now();
87 updateRunMachines((machine) =>
88 retried.has(machine.environmentId)
89 ? { ...machine, result: null, failure: null, startedAt }
90 : machine,
91 );
92 for (const { target, providerFailure } of failed) {
93 void update(target, { quiet: true }).then((outcome) =>
94 settleUpdateRunMachine(
95 target.environmentId,
96 // A skipped retry (no permission, disconnected, interrupted) did not update.
97 outcome.status === "updated"
98 ? providerFailure
99 : outcome.status === "failed"
100 ? outcome.message
101 : "Could not start the update",
102 { serverUpdated: outcome.status === "updated" },
103 ),
104 );
105 }
107​
108/** Drops the finished machines, which ends a run that only kept failures. */
109export function dismissSettledUpdateRunMachines(): void {
110 setUpdateEverythingRun(
111 (run) =>
112 run &&
113 closeFinishedUpdateRun({
114 ...run,
115 machines: run.machines.filter((machine) => machine.result === null),
116 }),
117 );
119​
120/** Resolves once a server restarts into its update, or its update `finished` first. */
121export function waitForServerUpdateHandoff(
122 environmentId: EnvironmentId,
123 finished: Promise<unknown>,
124): Promise<void> {
125 return new Promise((resolve) => {
126 let done = false;
127 const finish = () => {
128 if (done) return;
129 done = true;
130 queueMicrotask(() => unsubscribe());
131 resolve();
132 };
133 const unsubscribe = appAtomRegistry.subscribe(
134 serverEnvironment.updateStateAtom(environmentId),
135 (state) => {
136 if (isServerUpdateHandedOff(state)) finish();
137 },
138 { immediate: true },
139 );
140 void finished.then(finish, finish);
141 });
143​
144let decideRestart: ((restart: boolean) => void) | null = null;
145​
146/**
147 * Counts down to this app's relaunch. Resolves true when the countdown ends,
148 * or false when the user chose to restart later with {@link postponeUpdateRestart}.
149 */
150export function waitForUpdateRestart(delayMs: number): Promise<boolean> {
151 return new Promise((resolve) => {
152 const decide = (restart: boolean) => {
153 clearTimeout(timer);
154 decideRestart = null;
155 resolve(restart);
156 };
157 const timer = setTimeout(() => decide(true), delayMs);
158 decideRestart = decide;
159 setUpdateEverythingRun(
160 (run) => run && { ...run, phase: "countdown", restartAt: Date.now() + delayMs },
161 );
162 });
164​
165/** Keeps this app on its version. Its downloaded update waits on the update button. */
166export function postponeUpdateRestart(): void {
167 decideRestart?.(false);
169​
170const SAVED_RESULT_KEY = "t3code:update-everything-result:v1";
171// A result older than this belongs to an install that never relaunched the app.
172const SAVED_RESULT_MAX_AGE_MS = 10 * 60 * 1000;
173// Covers a background service's 30-minute trial start, like the server update itself.
174const HANDOFF_TIMEOUT_MS = 32 * 60 * 1000;
175​
176const HandedOffServer = Schema.Struct({
177 environmentId: EnvironmentId,
178 label: Schema.String,
179 targetVersion: Schema.String,
180 startedAt: Schema.Number,
181});
182type HandedOffServer = typeof HandedOffServer.Type;
183​
184const SavedResult = Schema.Struct({
185 savedAt: Schema.Number,
186 localVersion: Schema.NullOr(Schema.String),
187 updatedServers: Schema.Number,
188 updatedProviders: Schema.Number,
189 failures: Schema.Array(Schema.String),
190 // Older saved results have no handed-off servers.
191 handedOff: Schema.optional(Schema.Array(HandedOffServer)),
192});
193const decodeSavedResult = Schema.decodeUnknownOption(Schema.fromJsonString(SavedResult));
194​
195/**
196 * Keeps a result through this app's relaunch. Call it right before the
197 * install. Servers still restarting are saved too, so the sidebar keeps
198 * following them after the relaunch.
199 */
200export function saveUpdateEverythingResult(result: UpdateEverythingResult): void {
201 const run = appAtomRegistry.get(updateEverythingRunAtom);
202 const handedOff = (run?.machines ?? []).flatMap((machine): HandedOffServer[] => {
203 if (machine.result !== null) return [];
204 const state = appAtomRegistry.get(serverEnvironment.updateStateAtom(machine.environmentId));
205 // A desktop-managed server installs its own feed's version, which only its
206 // update state knows. A server followed from an earlier relaunch keeps its version.
207 const targetVersion =
208 machine.handedOffVersion ??
209 (state.status === "running" ? state.targetVersion : machine.server?.targetVersion);
210 if (targetVersion === undefined) return [];
211 return [
212 {
213 environmentId: machine.environmentId,
214 label: machine.label,
215 targetVersion,
216 startedAt: machine.startedAt,
217 },
218 ];
219 });
220 try {
221 window.localStorage.setItem(
222 SAVED_RESULT_KEY,
223 JSON.stringify({
224 savedAt: Date.now(),
225 localVersion: result.localVersion,
226 updatedServers: result.updatedServers,
227 updatedProviders: result.updatedProviders,
228 failures: result.failures,
229 handedOff,
230 } satisfies typeof SavedResult.Type),
231 );
232 } catch {
233 // Without storage the summary is lost with the relaunch; the update still runs.
234 }
236​
237export function clearSavedUpdateEverythingResult(): void {
238 try {
239 window.localStorage.removeItem(SAVED_RESULT_KEY);
240 } catch {
241 // Nothing to clear.
242 }
244​
245function takeSavedUpdateEverythingResult(): typeof SavedResult.Type | null {
246 try {
247 const raw = window.localStorage.getItem(SAVED_RESULT_KEY);
248 if (raw === null) return null;
249 window.localStorage.removeItem(SAVED_RESULT_KEY);
250 return Option.getOrNull(
251 Option.filter(
252 decodeSavedResult(raw),
253 (saved) => Date.now() - saved.savedAt < SAVED_RESULT_MAX_AGE_MS,
254 ),
255 );
256 } catch {
257 return null;
258 }
260​
261/** Shows the one summary toast for a finished pass. */
262export function showUpdateEverythingResult(result: UpdateEverythingResult): void {
263 const view = getUpdateEverythingToastView(result, APP_VERSION);
264 if (!view) return;
265 toastManager.add(
266 stackedThreadToast({
267 type: view.type,
268 title: view.title,
269 ...(view.description
270 ? { description: <span className="whitespace-pre-line">{view.description}</span> }
271 : {}),
272 }),
273 );
275​
276/**
277 * Follows servers that were restarting when this app relaunched. Each is done
278 * once it reports its target version, or failed after the handoff timeout.
279 * One toast reports them all at the end.
280 */
281function followHandedOffServers(servers: ReadonlyArray<HandedOffServer>): void {
282 // A server already past the timeout still shows, then fails on its first timer tick.
283 if (servers.length === 0) return;
284 setUpdateEverythingRun(() => ({
285 localVersion: null,
286 phase: "servers",
287 restartAt: null,
288 machines: servers.map((server) => ({
289 environmentId: server.environmentId,
290 label: server.label,
291 updatesProviders: false,
292 server: null,
293 handedOffVersion: server.targetVersion,
294 startedAt: server.startedAt,
295 result: null,
296 failure: null,
297 providerFailure: null,
298 })),
299 }));
300 let remaining = servers.length;
301 let updatedServers = 0;
302 const failures: string[] = [];
303 for (const server of servers) {
304 let settled = false;
305 const settle = (failure: string | null) => {
306 if (settled) return;
307 settled = true;
308 clearTimeout(timer);
309 queueMicrotask(() => unsubscribe());
310 settleUpdateRunMachine(server.environmentId, failure);
311 if (failure === null) updatedServers += 1;
312 else failures.push(`${server.label}: ${failure}`);
313 remaining -= 1;
314 if (remaining === 0) {
315 showUpdateEverythingResult({
316 localVersion: null,
317 updatedServers,
318 updatedProviders: 0,
319 failures,
320 restarting: [],
321 });
322 }
323 };
324 const timer = setTimeout(
325 () => settle(`Not back after ${HANDOFF_TIMEOUT_MS / 60_000} minutes`),
326 server.startedAt + HANDOFF_TIMEOUT_MS - Date.now(),
327 );
328 const unsubscribe = appAtomRegistry.subscribe(
329 serverEnvironment.configValueAtom(server.environmentId),
330 (config) => {
331 if (
332 config !== null &&
333 resolveVersionMismatch(config.environment.serverVersion, server.targetVersion) === null
334 ) {
335 settle(null);
336 }
337 },
338 { immediate: true },
339 );
340 }
342​
343let notifiedNotAppliedVersion: string | null = null;
344​
345/**
346 * Desktop launch notices for updates: the summary of a pass that ended with
347 * this app's relaunch, and a warning when the last install did not apply.
348 * Servers still restarting from that pass stay in the sidebar until they are
349 * back. Mount once at the app root.
350 */
351export function DesktopUpdateLaunchNotice() {
352 const notAppliedVersion = useDesktopUpdateState()?.notAppliedVersion ?? null;
353​
354 useEffect(() => {
355 const saved = takeSavedUpdateEverythingResult();
356 if (!saved) return;
357 const handedOff = saved.handedOff ?? [];
358 showUpdateEverythingResult({ ...saved, restarting: handedOff.map((server) => server.label) });
359 followHandedOffServers(handedOff);
360 }, []);
361​
362 useEffect(() => {
363 if (notAppliedVersion === null || notifiedNotAppliedVersion === notAppliedVersion) return;
364 notifiedNotAppliedVersion = notAppliedVersion;
365 toastManager.add(
366 stackedThreadToast({
367 type: "error",
368 title: "Update did not apply",
369 description: `T3 Code is still on ${APP_VERSION}. Install ${notAppliedVersion} again from the update button.`,
370 }),
371 );
372 }, [notAppliedVersion]);
373​
374 return null;