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

updateEverything.logic.ts

501 lines18.6 KB

1import type { ServerUpdateState } from "@t3tools/client-runtime/state/server";
2import type { EnvironmentId, ServerConfig } from "@t3tools/contracts";
3import { cliReleaseChannelOf } from "@t3tools/shared/cliRelease";
4​
5import {
6 resolveServerSelfUpdateCapability,
7 resolveVersionMismatch,
8 supportsDesktopAppUpdate,
9 supportsServerUpdateThreadContinuation,
10} from "~/versionSkew";
11import type { ServerUpdateOutcome, ServerUpdateTarget } from "../ServerUpdateAction";
12​
13export interface UpdateEverythingMachine {
14 readonly environmentId: EnvironmentId;
15 readonly label: string;
16 readonly serverConfig: {
17 readonly environment: ServerConfig["environment"];
18 readonly settings: Pick<ServerConfig["settings"], "continueThreadsAfterServerUpdate">;
19 } | null;
20 readonly connected: boolean;
21 /** Served by the desktop app this client runs in (the primary backend or a
22 local WSL backend). Its server updates when the app installs. */
23 readonly hostedByThisApp: boolean;
24 /** The session holds the scope a server update needs. */
25 readonly canMaintain: boolean;
26 readonly updateState: ServerUpdateState;
28​
29/** A server that restarts during a run. */
30export interface RestartingMachine {
31 readonly environmentId: EnvironmentId;
32 /** The server resumes interrupted threads after it restarts. */
33 readonly continuesThreads: boolean;
35​
36/**
37 * The servers a run restarts: each server it updates, and the servers this app
38 * hosts when this app installs. Provider updates restart nothing.
39 */
40export function collectRestartingMachines(
41 machines: ReadonlyArray<UpdateEverythingMachine>,
42 servers: ReadonlyArray<Pick<ServerUpdateTarget, "environmentId">>,
43 installsLocal: boolean,
44): RestartingMachine[] {
45 const updated = new Set(servers.map((server) => server.environmentId));
46 return machines.flatMap((machine) => {
47 const config = machine.serverConfig;
48 if (
49 config === null ||
50 !machine.connected ||
51 !(updated.has(machine.environmentId) || (installsLocal && machine.hostedByThisApp))
52 ) {
53 return [];
54 }
55 return [
56 {
57 environmentId: machine.environmentId,
58 continuesThreads:
59 config.environment.capabilities.threadRestartContinuation === true &&
60 config.settings.continueThreadsAfterServerUpdate === true,
61 },
62 ];
63 });
65​
66/** A machine the run leaves alone, with a short reason such as "not connected". */
67export interface SkippedMachine {
68 readonly environmentId: EnvironmentId;
69 readonly label: string;
70 readonly reason: string;
72​
73/**
74 * The servers that "update everything" moves to `targetVersion`: connected,
75 * permitted, able to update over RPC, behind the target, and on its release
76 * channel. Every other behind server comes back in `skipped` with a reason for
77 * the confirmation; a machine that never connected has an unknown version, so
78 * it counts as skipped. Two kinds are in neither list: servers already on the
79 * target, and servers this app hosts, which would relaunch the app mid-run
80 * and update with the app's own install anyway. A desktop-managed server
81 * follows its own app's update feed, so the channel rule does not apply to it.
82 */
83export function collectServerUpdateTargets(
84 machines: ReadonlyArray<UpdateEverythingMachine>,
85 targetVersion: string,
86): { readonly targets: ServerUpdateTarget[]; readonly skipped: SkippedMachine[] } {
87 const targets: ServerUpdateTarget[] = [];
88 const skipped: SkippedMachine[] = [];
89 for (const machine of machines) {
90 const config = machine.serverConfig;
91 if (machine.hostedByThisApp) continue;
92 if (
93 config !== null &&
94 resolveVersionMismatch(config.environment.serverVersion, targetVersion) === null
95 ) {
96 continue;
97 }
98 const skip = (reason: string) =>
99 skipped.push({ environmentId: machine.environmentId, label: machine.label, reason });
100 if (config === null || !machine.connected) {
101 skip("not connected");
102 continue;
103 }
104 if (!machine.canMaintain) {
105 skip("no permission");
106 continue;
107 }
108 if (machine.updateState.status === "running") {
109 skip("already updating");
110 continue;
111 }
112 const selfUpdate = resolveServerSelfUpdateCapability(config);
113 const desktopAppUpdate = supportsDesktopAppUpdate(config);
114 if (selfUpdate === null) {
115 skip("needs a manual update");
116 continue;
117 }
118 if (selfUpdate === "desktop-managed" && !desktopAppUpdate) {
119 skip("needs a newer desktop app");
120 continue;
121 }
122 const serverVersion = config.environment.serverVersion;
123 if (
124 selfUpdate !== "desktop-managed" &&
125 cliReleaseChannelOf(serverVersion) !== cliReleaseChannelOf(targetVersion)
126 ) {
127 skip(`on the ${cliReleaseChannelOf(serverVersion)} channel`);
128 continue;
129 }
130 targets.push({
131 environmentId: machine.environmentId,
132 serverLabel: machine.label,
133 selfUpdate,
134 installation: config.environment.capabilities.serverInstallation,
135 desktopAppUpdate,
136 threadContinuation: supportsServerUpdateThreadContinuation(config),
137 continueThreadsAfterServerUpdate: config.settings.continueThreadsAfterServerUpdate ?? false,
138 targetVersion,
139 });
140 }
141 return { targets, skipped };
143​
144export interface UpdateEverythingSteps<Providers, Servers> {
145 /** Downloads this app's update. Resolves true when it is ready to install.
146 Without it, `localReady` is true: there is nothing to download. */
147 readonly downloadLocal?: () => Promise<boolean>;
148 readonly updateProviders: () => Promise<Providers>;
149 readonly updateServers: () => Promise<Servers>;
151​
152/**
153 * Runs the remote half of one "update everything" pass and returns each
154 * step's results. Providers finish before any server restarts, so no install
155 * is cut off. The local download runs alongside the remote work. The caller
156 * installs this app afterwards when `localReady`, because the relaunch ends
157 * the run; a failed download skips only that install.
158 */
159export async function runUpdateEverything<Providers, Servers>(
160 steps: UpdateEverythingSteps<Providers, Servers>,
161): Promise<{
162 readonly localReady: boolean;
163 readonly providers: Providers;
164 readonly servers: Servers;
165}> {
166 const [localReady, remote] = await Promise.all([
167 steps.downloadLocal?.() ?? Promise.resolve(true),
168 steps
169 .updateProviders()
170 .then(async (providers) => ({ providers, servers: await steps.updateServers() })),
171 ]);
172 return { localReady, ...remote };
174​
175/** The current state of one machine in a running pass. */
176export type UpdateRunMachineStatus =
177 | "providers"
178 | "waiting"
179 | "downloading"
180 | "restarting"
181 | "done"
182 | "failed";
183​
184/** One machine in a running "update everything" pass. */
185export interface UpdateRunMachine {
186 readonly environmentId: EnvironmentId;
187 readonly label: string;
188 readonly updatesProviders: boolean;
189 /** The server update this machine runs, kept so a failure can be retried.
190 Null for a provider-only machine, or a server this app handed off before
191 it relaunched. */
192 readonly server: ServerUpdateTarget | null;
193 /** The version a handed-off server comes back on. This app relaunched while
194 that server restarted, so its version is the only signal left. */
195 readonly handedOffVersion: string | null;
196 /** When its current update started, for the elapsed time. */
197 readonly startedAt: number;
198 /** Set when every update for this machine has finished. */
199 readonly result: "done" | "failed" | null;
200 /** Why it failed, when `result` is "failed". */
201 readonly failure: string | null;
202 /** This machine's provider failure, kept apart so a server retry does not clear it. */
203 readonly providerFailure: string | null;
205​
206/**
207 * A running "update everything" pass, kept until every machine finished. A
208 * failed machine keeps it open, so the sidebar can offer a retry.
209 */
210export interface UpdateEverythingRun {
211 /** The version this app installs, or null when it does not install (or the
212 user chose to restart later). */
213 readonly localVersion: string | null;
214 /** Providers update first, then servers. "countdown" waits `restartAt` to
215 relaunch this app, which can still be postponed. */
216 readonly phase: "providers" | "servers" | "countdown" | "installing";
217 readonly restartAt: number | null;
218 readonly machines: ReadonlyArray<UpdateRunMachine>;
220​
221/** Status of one machine, from the run and that server's own update state. */
222export function resolveUpdateRunMachineStatus(
223 machine: UpdateRunMachine,
224 phase: UpdateEverythingRun["phase"],
225 serverState: ServerUpdateState,
226): UpdateRunMachineStatus {
227 if (machine.result !== null) return machine.result;
228 if (machine.handedOffVersion !== null) return "restarting";
229 if (phase === "providers" && machine.updatesProviders) return "providers";
230 if (machine.server !== null && serverState.status === "running") {
231 return serverState.stage === "resuming" ? "restarting" : "downloading";
232 }
233 return "waiting";
235​
236/** A server is handed off once it restarts into its update: it finishes
237 without this app, so this app can relaunch. */
238export function isServerUpdateHandedOff(state: ServerUpdateState): boolean {
239 return state.status === "running" && state.stage === "resuming";
241​
242/** Ends the run once nothing is left to show: every machine done and this
243 app not installing. Failures keep it open. */
244export function closeFinishedUpdateRun(run: UpdateEverythingRun): UpdateEverythingRun | null {
245 return run.phase === "servers" &&
246 run.localVersion === null &&
247 run.machines.every((machine) => machine.result === "done")
248 ? null
249 : run;
251​
252/** An update this long is slower than usual, so the sidebar points it out. */
253export const UPDATE_SLOW_AFTER_MS = 3 * 60 * 1000;
254​
255/** Elapsed time in whole minutes, such as "6m" or "1h 4m". */
256export function formatUpdateElapsed(ms: number): string {
257 const minutes = Math.floor(ms / 60_000);
258 if (minutes < 1) return "<1m";
259 if (minutes < 60) return `${minutes}m`;
260 return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
262​
263export interface UpdateRunMachineView {
264 readonly machine: UpdateRunMachine;
265 readonly status: UpdateRunMachineStatus;
267​
268/** This app's own part of a run, for the sidebar. */
269export type UpdateRunLocalState =
270 | { readonly status: "downloading"; readonly percent: number | null }
271 | { readonly status: "waiting" }
272 | null;
273​
274/** What the expanded sidebar update button says, and its inline action. */
275export interface UpdateCapsuleView {
276 readonly tone: "default" | "slow" | "failed";
277 readonly label: string;
278 /** For a slow machine, its status and elapsed time, such as "restarting" and "6m". */
279 readonly slow?: { readonly status: string; readonly elapsed: string };
280 readonly action: "later" | "retry" | "dismiss" | null;
282​
283const isActive = (status: UpdateRunMachineStatus) => status !== "done" && status !== "failed";
284​
285/**
286 * The one line the expanded update button shows for a run, most urgent
287 * first: this app's restart countdown, a slow machine, overall progress, and
288 * last any failure once nothing else is running.
289 */
290export function describeUpdateCapsule(
291 run: UpdateEverythingRun,
292 machines: ReadonlyArray<UpdateRunMachineView>,
293 local: UpdateRunLocalState,
294 now: number,
295): UpdateCapsuleView {
296 if (run.phase === "countdown" && run.restartAt !== null) {
297 const seconds = Math.max(0, Math.ceil((run.restartAt - now) / 1000));
298 return { tone: "default", label: `Restart in ${seconds}s`, action: "later" };
299 }
300 if (run.phase === "installing") {
301 return { tone: "default", label: "Restarting…", action: null };
302 }
303 const active = machines.filter(({ status }) => isActive(status) && status !== "waiting");
304 const slowest = active.toSorted((a, b) => a.machine.startedAt - b.machine.startedAt)[0];
305 if (slowest && now - slowest.machine.startedAt >= UPDATE_SLOW_AFTER_MS) {
306 return {
307 tone: "slow",
308 label: slowest.machine.label,
309 slow: {
310 status: RUN_STATUS_LABELS[slowest.status],
311 elapsed: formatUpdateElapsed(now - slowest.machine.startedAt),
312 },
313 action: null,
314 };
315 }
316 const done = machines.filter(({ status }) => status === "done").length;
317 if (machines.some(({ status }) => isActive(status))) {
318 return { tone: "default", label: `${done} of ${machines.length} updated`, action: null };
319 }
320 if (local?.status === "downloading") {
321 return {
322 tone: "default",
323 label: `Downloading${local.percent === null ? "" : ` ${Math.floor(local.percent)}%`}`,
324 action: null,
325 };
326 }
327 const failed = machines.filter(({ status }) => status === "failed");
328 if (failed.length > 0) {
329 return {
330 tone: "failed",
331 label: failed.length === 1 ? `${failed[0]!.machine.label} failed` : `${failed.length} failed`,
332 action: failed.some(({ machine }) => machine.server !== null) ? "retry" : "dismiss",
333 };
334 }
335 return { tone: "default", label: `${done} of ${machines.length} updated`, action: null };
337​
338export const RUN_STATUS_LABELS: Record<UpdateRunMachineStatus, string> = {
339 providers: "updating providers",
340 waiting: "waiting",
341 downloading: "downloading",
342 restarting: "restarting",
343 done: "done",
344 failed: "failed",
345};
346​
347/** What one pass did. It is saved before this app installs, so it outlives the relaunch. */
348export interface UpdateEverythingResult {
349 /** The version this app installed last, or null when it did not install. */
350 readonly localVersion: string | null;
351 readonly updatedServers: number;
352 readonly updatedProviders: number;
353 /** One line per failure, each naming its machine. */
354 readonly failures: ReadonlyArray<string>;
355 /** Servers still restarting into their update when this app relaunched. */
356 readonly restarting: ReadonlyArray<string>;
358​
359/** Counts what a pass updated and lists each failure with its machine. */
360export function collectUpdateEverythingResult(input: {
361 readonly localVersion: string | null;
362 /** This app's own download or install failures. */
363 readonly localFailures: ReadonlyArray<string>;
364 readonly servers: ReadonlyArray<{
365 readonly label: string;
366 readonly outcome: ServerUpdateOutcome;
367 }>;
368 readonly providers: ReadonlyArray<
369 | { readonly status: "interrupted" | "updated" }
370 | { readonly status: "failed"; readonly line: string }
371 >;
372}): UpdateEverythingResult {
373 return {
374 localVersion: input.localVersion,
375 updatedServers: input.servers.filter(({ outcome }) => outcome.status === "updated").length,
376 updatedProviders: input.providers.filter((outcome) => outcome.status === "updated").length,
377 restarting: [],
378 failures: [
379 ...input.localFailures.map((failure) => `This app: ${failure}`),
380 ...input.servers.flatMap(({ label, outcome }) =>
381 outcome.status === "failed" ? [`${label}: ${outcome.message}`] : [],
382 ),
383 ...input.providers.flatMap((outcome) => (outcome.status === "failed" ? [outcome.line] : [])),
384 ],
385 };
387​
388/**
389 * The one toast for a finished pass, such as "Updated this app, 8 servers,
390 * and 3 providers" with a line per failure. `appVersion` is the version this
391 * app runs now: after the relaunch it tells whether the local install
392 * applied. Null when nothing finished, for example every request was
393 * interrupted.
394 */
395export function getUpdateEverythingToastView(
396 result: UpdateEverythingResult,
397 appVersion: string,
398): {
399 readonly type: "success" | "error";
400 readonly title: string;
401 readonly description?: string;
402} | null {
403 const parts = [
404 result.localVersion !== null && result.localVersion === appVersion ? "this app" : null,
405 countLabel(result.updatedServers, "server"),
406 countLabel(result.updatedProviders, "provider"),
407 ].filter((part) => part !== null);
408 const restarting =
409 result.restarting.length === 0
410 ? []
411 : [
412 `${joinList(result.restarting)} ${result.restarting.length === 1 ? "is" : "are"} still restarting.`,
413 ];
414 if (result.failures.length === 0) {
415 if (parts.length === 0) return null;
416 return {
417 type: "success",
418 title: `Updated ${joinList(parts)}`,
419 ...(restarting.length === 0 ? {} : { description: restarting.join("\n") }),
420 };
421 }
422 return {
423 type: "error",
424 title: parts.length === 0 ? "Update failed" : `Updated ${joinList(parts)}`,
425 description: [...result.failures, ...restarting].join("\n"),
426 };
428​
429export interface UpdateEverythingPlan {
430 /** The version this desktop app installs, or null when it is not updating. */
431 readonly localVersion: string | null;
432 readonly servers: ReadonlyArray<
433 Pick<ServerUpdateTarget, "environmentId" | "serverLabel" | "selfUpdate" | "targetVersion">
434 >;
435 readonly providerMachines: ReadonlyArray<{
436 readonly environmentId: EnvironmentId;
437 readonly label: string;
438 /** Display names of the outdated providers on that machine. */
439 readonly providers: ReadonlyArray<string>;
440 }>;
442​
443function countLabel(count: number, noun: string): string | null {
444 return count === 0 ? null : `${count} ${noun}${count === 1 ? "" : "s"}`;
446​
447function joinList(parts: ReadonlyArray<string>): string {
448 if (parts.length <= 2) return parts.join(" and ");
449 return `${parts.slice(0, -1).join(", ")}, and ${parts.at(-1)}`;
451​
452/**
453 * Text for the sidebar tooltip and the confirmation. `summary` reads like
454 * "Update this app, 2 servers, and 3 providers". `lines` has one entry per
455 * machine, this app first, such as "alvin: server to 0.0.50, Codex, Claude".
456 */
457export function describeUpdateEverything(plan: UpdateEverythingPlan): {
458 readonly summary: string;
459 readonly lines: ReadonlyArray<string>;
460} {
461 const providerCount = plan.providerMachines.reduce(
462 (count, machine) => count + machine.providers.length,
463 0,
464 );
465 const summary = `Update ${joinList(
466 [
467 plan.localVersion ? "this app" : null,
468 countLabel(plan.servers.length, "server"),
469 countLabel(providerCount, "provider"),
470 ].filter((part) => part !== null),
471 )}`;
472​
473 const machines = new Map<EnvironmentId, { label: string; items: string[] }>();
474 const itemsFor = (environmentId: EnvironmentId, label: string) => {
475 const existing = machines.get(environmentId);
476 if (existing) return existing.items;
477 const items: string[] = [];
478 machines.set(environmentId, { label, items });
479 return items;
480 };
481 for (const server of plan.servers) {
482 // A desktop-managed server installs whatever its own app's update feed
483 // offers, so it has no target version to show.
484 itemsFor(server.environmentId, server.serverLabel).push(
485 server.selfUpdate === "desktop-managed"
486 ? "desktop app update"
487 : `server to ${server.targetVersion}`,
488 );
489 }
490 for (const machine of plan.providerMachines) {
491 itemsFor(machine.environmentId, machine.label).push(...machine.providers);
492 }
493​
494 return {
495 summary,
496 lines: [
497 ...(plan.localVersion ? [`This app: ${plan.localVersion}, restarts last`] : []),
498 ...Array.from(machines.values(), ({ label, items }) => `${label}: ${items.join(", ")}`),
499 ],
500 };