Open History to see the last commit
1import type { ServerUpdateState } from "@t3tools/client-runtime/state/server";
2import type {
3 DesktopUpdateChannel,
4 EnvironmentId,
5 ServerConfig,
6 ServerSelfUpdateCapability,
7} from "@t3tools/contracts";
8import { cliReleaseChannelOf, desktopUpdateChannelOf } from "@t3tools/shared/cliRelease";
9import { compareSemverVersions } from "@t3tools/shared/semver";
10
11import {
12 resolveServerSelfUpdateCapability,
13 resolveVersionMismatch,
14 supportsDesktopAppUpdate,
15} from "~/versionSkew";
16import type { ServerUpdateOutcome, ServerUpdateTarget } from "../ServerUpdateAction";
17
18export interface UpdateEverythingMachine {
19 readonly environmentId: EnvironmentId;
20 readonly label: string;
21 readonly serverConfig: {
22 readonly environment: ServerConfig["environment"];
23 readonly settings: Pick<ServerConfig["settings"], "continueThreadsAfterServerUpdate">;
24 } | null;
25 readonly connected: boolean;
26 readonly hostedByThisApp: boolean;
27 readonly canMaintain: boolean;
28 readonly updateState: ServerUpdateState;
29}
30
31export interface RestartingMachine {
32 readonly environmentId: EnvironmentId;
33 readonly continuesThreads: boolean;
34}
35
36export function collectRestartingMachines(
37 machines: ReadonlyArray<UpdateEverythingMachine>,
38 servers: ReadonlyArray<Pick<ServerUpdateTarget, "environmentId">>,
39 installsLocal: boolean,
40): RestartingMachine[] {
41 const updated = new Set(servers.map((server) => server.environmentId));
42 return machines.flatMap((machine) => {
43 const config = machine.serverConfig;
44 if (
45 config === null ||
46 !machine.connected ||
47 !(updated.has(machine.environmentId) || (installsLocal && machine.hostedByThisApp))
48 ) {
49 return [];
50 }
51 return [
52 {
53 environmentId: machine.environmentId,
54 continuesThreads: config.settings.continueThreadsAfterServerUpdate === true,
55 },
56 ];
57 });
58}
59
60export interface SkippedMachine {
61 readonly environmentId: EnvironmentId;
62 readonly label: string;
63 readonly reason: string;
64}
65
66/** Skip current and app-hosted servers; the latter update with the app and would relaunch mid-run.
67 * Desktop-managed servers use their own feed. Each server's updater checks that it can install the
68 * release before it restarts, so no registry precheck runs here. */
69export function collectServerUpdateTargets(
70 machines: ReadonlyArray<UpdateEverythingMachine>,
71 targetVersion: string,
72): {
73 readonly targets: ServerUpdateTarget[];
74 readonly skipped: SkippedMachine[];
75} {
76 const targets: ServerUpdateTarget[] = [];
77 const skipped: SkippedMachine[] = [];
78 for (const machine of machines) {
79 const config = machine.serverConfig;
80 if (machine.hostedByThisApp) continue;
81 if (
82 config !== null &&
83 resolveVersionMismatch(config.environment.serverVersion, targetVersion) === null
84 ) {
85 continue;
86 }
87 const skip = (reason: string) =>
88 skipped.push({ environmentId: machine.environmentId, label: machine.label, reason });
89 const unavailable = unavailableReason(machine);
90 if (config === null || unavailable !== null) {
91 skip(unavailable ?? "not connected");
92 continue;
93 }
94 const selfUpdate = resolveServerSelfUpdateCapability(config);
95 const desktopAppUpdate = supportsDesktopAppUpdate(config);
96 if (selfUpdate === null) {
97 skip("needs a manual update");
98 continue;
99 }
100 if (selfUpdate === "desktop-managed" && !desktopAppUpdate) {
101 skip("needs a newer desktop app");
102 continue;
103 }
104 const serverVersion = config.environment.serverVersion;
105 if (
106 selfUpdate !== "desktop-managed" &&
107 cliReleaseChannelOf(serverVersion) !== cliReleaseChannelOf(targetVersion)
108 ) {
109 skip(`on the ${cliReleaseChannelOf(serverVersion)} channel`);
110 continue;
111 }
112 const target: ServerUpdateTarget = {
113 environmentId: machine.environmentId,
114 serverLabel: machine.label,
115 selfUpdate,
116 installation: config.environment.capabilities.serverInstallation,
117 desktopAppUpdate,
118 targetVersion,
119 };
120 targets.push(target);
121 }
122 return { targets, skipped };
123}
124
125function unavailableReason(machine: UpdateEverythingMachine): string | null {
126 if (machine.serverConfig === null || !machine.connected) return "not connected";
127 if (!machine.canMaintain) return "no permission";
128 if (machine.updateState.status === "running") return "already updating";
129 return null;
130}
131
132/** The latest release on the track a fleet switches to, as npm reports it. */
133export interface ChannelSwitchRelease {
134 readonly channel: DesktopUpdateChannel;
135 readonly version: string;
136 readonly databaseMigration: number | undefined;
137}
138
139export const channelSwitchLabel = (channel: DesktopUpdateChannel) =>
140 channel === "nightly" ? "Nightly" : "Stable";
141
142/** Stable and Nightly each build their own commits, so either can hold migrations the other lacks.
143 * Crossing tracks needs proof that the target release knows every migration the database holds. */
144const crossesTrack = (fromVersion: string, release: ChannelSwitchRelease) =>
145 desktopUpdateChannelOf(fromVersion) !== release.channel;
146
147function channelSwitchBlockReason(
148 fromVersion: string,
149 release: ChannelSwitchRelease,
150 currentMigration: number | undefined,
151): string | null {
152 if (!crossesTrack(fromVersion, release)) return null;
153 const from = channelSwitchLabel(desktopUpdateChannelOf(fromVersion));
154 // Servers and releases from before this check report no migration number.
155 if (currentMigration === undefined) {
156 return `its server predates database checks; update it on ${from} first`;
157 }
158 if (release.databaseMigration === undefined) {
159 return `${release.version} predates database checks; wait for a newer ${channelSwitchLabel(release.channel)} release`;
160 }
161 return currentMigration > release.databaseMigration
162 ? `its database has changes ${release.version} does not support yet; stay on ${from} until ${channelSwitchLabel(release.channel)} has them`
163 : null;
164}
165
166/** This app's reinstall restarts every server it hosts, so each of their databases must allow the
167 * switch. `backendCount` is the desktop's own inventory: a backend still starting has no client
168 * entry yet. A cached config can outlive its connection, so only a connected server's head counts. */
169export function localSwitchBlockReason(
170 appVersion: string,
171 release: ChannelSwitchRelease,
172 hosted: ReadonlyArray<{
173 readonly connected: boolean;
174 readonly databaseMigration: number | undefined;
175 }>,
176 backendCount: number,
177): string | null {
178 if (!crossesTrack(appVersion, release)) return null;
179 if (
180 hosted.length === 0 ||
181 hosted.length < backendCount ||
182 hosted.some((server) => !server.connected)
183 ) {
184 return "its server is not connected, so its database cannot be checked";
185 }
186 return (
187 hosted
188 .map((server) => channelSwitchBlockReason(appVersion, release, server.databaseMigration))
189 .find((reason) => reason !== null) ?? null
190 );
191}
192
193/** Servers move to the release; desktop-managed hosts reinstall their app on its track. A desktop
194 * host already current gets a track-only request, since its saved track may still differ. */
195export function collectChannelSwitchTargets(
196 machines: ReadonlyArray<UpdateEverythingMachine>,
197 release: ChannelSwitchRelease,
198): { readonly targets: ServerUpdateTarget[]; readonly skipped: SkippedMachine[] } {
199 const targets: ServerUpdateTarget[] = [];
200 const skipped: SkippedMachine[] = [];
201 for (const machine of machines) {
202 const config = machine.serverConfig;
203 if (machine.hostedByThisApp) continue;
204 const skip = (reason: string) =>
205 skipped.push({ environmentId: machine.environmentId, label: machine.label, reason });
206 const target = (
207 selfUpdate: ServerSelfUpdateCapability,
208 targetVersion: string,
209 ): ServerUpdateTarget => ({
210 environmentId: machine.environmentId,
211 serverLabel: machine.label,
212 selfUpdate,
213 installation: config?.environment.capabilities.serverInstallation,
214 desktopAppUpdate: config !== null && supportsDesktopAppUpdate(config),
215 targetVersion,
216 ...(selfUpdate === "desktop-managed" ? { channel: release.channel } : {}),
217 ...(release.databaseMigration === undefined
218 ? {}
219 : { targetDatabaseMigration: release.databaseMigration }),
220 });
221 const serverVersion = config?.environment.serverVersion;
222 const sameTrack = serverVersion !== undefined && isOnTrack(serverVersion, release.channel);
223 if (
224 config !== null &&
225 sameTrack &&
226 resolveVersionMismatch(serverVersion, release.version) === null
227 ) {
228 const move = trackSwitchMove(config, true);
229 if (
230 !("skip" in move) &&
231 move.selfUpdate === "desktop-managed" &&
232 unavailableReason(machine) === null
233 ) {
234 targets.push({ ...target(move.selfUpdate, serverVersion), trackOnly: true });
235 }
236 continue;
237 }
238 const unavailable = unavailableReason(machine);
239 if (config === null || serverVersion === undefined || unavailable !== null) {
240 skip(unavailable ?? "not connected");
241 continue;
242 }
243 const move = trackSwitchMove(config, sameTrack);
244 if ("skip" in move) {
245 skip(move.skip);
246 continue;
247 }
248 const blocked = channelSwitchBlockReason(
249 serverVersion,
250 release,
251 config.environment.databaseMigration,
252 );
253 if (blocked !== null) {
254 skip(blocked);
255 continue;
256 }
257 // Service launchers only accept newer versions, so leaving for an older release is manual.
258 if (
259 move.selfUpdate === "boot-service" &&
260 compareSemverVersions(release.version, serverVersion) <= 0
261 ) {
262 skip(
263 `run \`t3 update --channel ${release.channel === "nightly" ? "nightly" : "stable"} --allow-downgrade\` there`,
264 );
265 continue;
266 }
267 targets.push(target(move.selfUpdate, release.version));
268 }
269 return { targets, skipped };
270}
271
272/** A remote host on the other track that a switch can still move, for retrying a partial switch. */
273export function awaitsTrackSwitch(
274 machine: Pick<UpdateEverythingMachine, "serverConfig" | "hostedByThisApp">,
275 channel: DesktopUpdateChannel,
276): boolean {
277 const config = machine.serverConfig;
278 return (
279 !machine.hostedByThisApp &&
280 config !== null &&
281 !isOnTrack(config.environment.serverVersion, channel) &&
282 !("skip" in trackSwitchMove(config, false))
283 );
284}
285
286function isOnTrack(version: string, channel: DesktopUpdateChannel): boolean {
287 return cliReleaseChannelOf(version) !== "preview" && desktopUpdateChannelOf(version) === channel;
288}
289
290/** How a switch moves a host, or why it never can from here, whatever the release. */
291function trackSwitchMove(
292 config: NonNullable<UpdateEverythingMachine["serverConfig"]>,
293 sameTrack: boolean,
294): { readonly selfUpdate: ServerSelfUpdateCapability } | { readonly skip: string } {
295 if (cliReleaseChannelOf(config.environment.serverVersion) === "preview") {
296 return { skip: "runs a preview build" };
297 }
298 const selfUpdate = resolveServerSelfUpdateCapability(config);
299 if (selfUpdate === null) return { skip: "needs a manual update" };
300 if (selfUpdate !== "desktop-managed") return { selfUpdate };
301 if (config.environment.capabilities.desktopAppChannelSwitch !== true) {
302 return { skip: "needs a newer desktop app" };
303 }
304 // Squirrel.Mac renames the bundle for the new track and then cannot relaunch it.
305 if (!sameTrack && config.environment.platform.os === "darwin") {
306 return { skip: "switch the Mac app on that Mac" };
307 }
308 return { selfUpdate };
309}
310
311export interface UpdateEverythingSteps<Providers, Servers> {
312 readonly downloadLocal?: () => Promise<boolean>;
313 readonly updateProviders: () => Promise<Providers>;
314 readonly updateServers: () => Promise<Servers>;
315}
316
317/** Finish provider installs before server restarts. Install this app last when localReady; failed
318 * downloads skip only that install. */
319export async function runUpdateEverything<Providers, Servers>(
320 steps: UpdateEverythingSteps<Providers, Servers>,
321): Promise<{
322 readonly localReady: boolean;
323 readonly providers: Providers;
324 readonly servers: Servers;
325}> {
326 const [localReady, remote] = await Promise.all([
327 steps.downloadLocal?.() ?? Promise.resolve(true),
328 steps
329 .updateProviders()
330 .then(async (providers) => ({ providers, servers: await steps.updateServers() })),
331 ]);
332 return { localReady, ...remote };
333}
334
335export type UpdateRunMachineStatus =
336 | "providers"
337 | "waiting"
338 | "downloading"
339 | "restarting"
340 | "done"
341 | "failed";
342
343export interface UpdateRunMachine {
344 readonly environmentId: EnvironmentId;
345 readonly label: string;
346 readonly updatesProviders: boolean;
347 readonly server: ServerUpdateTarget | null;
348 readonly handedOffVersion: string | null;
349 readonly startedAt: number;
350 readonly result: "done" | "failed" | null;
351 readonly failure: string | null;
352 readonly providerFailure: string | null;
353}
354
355export interface UpdateEverythingRun {
356 /** Track switches retry through their planner, which re-checks each database. */
357 readonly trackSwitch?: boolean;
358 readonly localVersion: string | null;
359 readonly phase: "providers" | "servers" | "countdown" | "installing";
360 readonly restartAt: number | null;
361 readonly machines: ReadonlyArray<UpdateRunMachine>;
362}
363
364export function resolveUpdateRunMachineStatus(
365 machine: UpdateRunMachine,
366 phase: UpdateEverythingRun["phase"],
367 serverState: ServerUpdateState,
368): UpdateRunMachineStatus {
369 if (machine.result !== null) return machine.result;
370 if (machine.handedOffVersion !== null) return "restarting";
371 if (phase === "providers" && machine.updatesProviders) return "providers";
372 if (machine.server !== null && serverState.status === "running") {
373 return serverState.stage === "resuming" ? "restarting" : "downloading";
374 }
375 return "waiting";
376}
377
378export function isServerUpdateHandedOff(state: ServerUpdateState): boolean {
379 return state.status === "running" && state.stage === "resuming";
380}
381
382export function closeFinishedUpdateRun(run: UpdateEverythingRun): UpdateEverythingRun | null {
383 return run.phase === "servers" &&
384 run.localVersion === null &&
385 run.machines.every((machine) => machine.result === "done")
386 ? null
387 : run;
388}
389
390const UPDATE_SLOW_AFTER_MS = 3 * 60 * 1000;
391
392export function formatUpdateElapsed(ms: number): string {
393 const minutes = Math.floor(ms / 60_000);
394 if (minutes < 1) return "<1m";
395 if (minutes < 60) return `${minutes}m`;
396 return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
397}
398
399export interface UpdateRunMachineView {
400 readonly machine: UpdateRunMachine;
401 readonly status: UpdateRunMachineStatus;
402}
403
404export type UpdateRunLocalState =
405 | { readonly status: "downloading"; readonly percent: number | null }
406 | { readonly status: "waiting" }
407 | null;
408
409export interface UpdateCapsuleView {
410 readonly tone: "default" | "slow" | "failed";
411 readonly label: string;
412 readonly slow?: { readonly status: string; readonly elapsed: string };
413 readonly action: "later" | "retry" | "dismiss" | null;
414}
415
416const isActive = (status: UpdateRunMachineStatus) => status !== "done" && status !== "failed";
417
418export function describeUpdateCapsule(
419 run: UpdateEverythingRun,
420 machines: ReadonlyArray<UpdateRunMachineView>,
421 local: UpdateRunLocalState,
422 now: number,
423): UpdateCapsuleView {
424 if (run.phase === "countdown" && run.restartAt !== null) {
425 const seconds = Math.max(0, Math.ceil((run.restartAt - now) / 1000));
426 return { tone: "default", label: `Restart in ${seconds}s`, action: "later" };
427 }
428 if (run.phase === "installing") {
429 return { tone: "default", label: "Restarting…", action: null };
430 }
431 const active = machines.filter(({ status }) => isActive(status) && status !== "waiting");
432 const slowest = active.toSorted((a, b) => a.machine.startedAt - b.machine.startedAt)[0];
433 if (slowest && now - slowest.machine.startedAt >= UPDATE_SLOW_AFTER_MS) {
434 return {
435 tone: "slow",
436 label: slowest.machine.label,
437 slow: {
438 status: RUN_STATUS_LABELS[slowest.status],
439 elapsed: formatUpdateElapsed(now - slowest.machine.startedAt),
440 },
441 action: null,
442 };
443 }
444 const done = machines.filter(({ status }) => status === "done").length;
445 if (machines.some(({ status }) => isActive(status))) {
446 return { tone: "default", label: `${done} of ${machines.length} updated`, action: null };
447 }
448 if (local?.status === "downloading") {
449 return {
450 tone: "default",
451 label: `Downloading${local.percent === null ? "" : ` ${Math.floor(local.percent)}%`}`,
452 action: null,
453 };
454 }
455 const failed = machines.filter(({ status }) => status === "failed");
456 if (failed.length > 0) {
457 return {
458 tone: "failed",
459 label: failed.length === 1 ? `${failed[0]!.machine.label} failed` : `${failed.length} failed`,
460 action:
461 !run.trackSwitch && failed.some(({ machine }) => machine.server !== null)
462 ? "retry"
463 : "dismiss",
464 };
465 }
466 return { tone: "default", label: `${done} of ${machines.length} updated`, action: null };
467}
468
469export const RUN_STATUS_LABELS: Record<UpdateRunMachineStatus, string> = {
470 providers: "updating providers",
471 waiting: "waiting",
472 downloading: "downloading",
473 restarting: "restarting",
474 done: "done",
475 failed: "failed",
476};
477
478export interface UpdateEverythingResult {
479 readonly localVersion: string | null;
480 readonly updatedServers: number;
481 readonly updatedProviders: number;
482 readonly failures: ReadonlyArray<string>;
483 readonly restarting: ReadonlyArray<string>;
484}
485
486export function collectUpdateEverythingResult(input: {
487 readonly localVersion: string | null;
488 readonly localFailures: ReadonlyArray<string>;
489 readonly servers: ReadonlyArray<{
490 readonly label: string;
491 readonly outcome: ServerUpdateOutcome;
492 }>;
493 readonly providers: ReadonlyArray<
494 | { readonly status: "interrupted" | "updated" }
495 | { readonly status: "failed"; readonly line: string }
496 >;
497}): UpdateEverythingResult {
498 return {
499 localVersion: input.localVersion,
500 updatedServers: input.servers.filter(({ outcome }) => outcome.status === "updated").length,
501 updatedProviders: input.providers.filter((outcome) => outcome.status === "updated").length,
502 restarting: [],
503 failures: [
504 ...input.localFailures.map((failure) => `This app: ${failure}`),
505 ...input.servers.flatMap(({ label, outcome }) =>
506 outcome.status === "failed" ? [`${label}: ${outcome.message}`] : [],
507 ),
508 ...input.providers.flatMap((outcome) => (outcome.status === "failed" ? [outcome.line] : [])),
509 ],
510 };
511}
512
513export function getUpdateEverythingToastView(
514 result: UpdateEverythingResult,
515 appVersion: string,
516): {
517 readonly type: "success" | "error";
518 readonly title: string;
519 readonly description?: string;
520} | null {
521 const parts = [
522 result.localVersion !== null && result.localVersion === appVersion ? "this app" : null,
523 countLabel(result.updatedServers, "server"),
524 countLabel(result.updatedProviders, "provider"),
525 ].filter((part) => part !== null);
526 const restarting =
527 result.restarting.length === 0
528 ? []
529 : [
530 `${joinList(result.restarting)} ${result.restarting.length === 1 ? "is" : "are"} still restarting.`,
531 ];
532 if (result.failures.length === 0) {
533 if (parts.length === 0) return null;
534 return {
535 type: "success",
536 title: `Updated ${joinList(parts)}`,
537 ...(restarting.length === 0 ? {} : { description: restarting.join("\n") }),
538 };
539 }
540 return {
541 type: "error",
542 title: parts.length === 0 ? "Update failed" : `Updated ${joinList(parts)}`,
543 description: [...result.failures, ...restarting].join("\n"),
544 };
545}
546
547export interface UpdateEverythingPlan {
548 readonly localVersion: string | null;
549 /** Machines whose servers this app hosts; this app's update restarts them. */
550 readonly localMachines: ReadonlyArray<{
551 readonly environmentId: EnvironmentId;
552 readonly label: string;
553 }>;
554 readonly servers: ReadonlyArray<
555 Pick<ServerUpdateTarget, "environmentId" | "serverLabel" | "selfUpdate" | "targetVersion">
556 >;
557 readonly providerMachines: ReadonlyArray<{
558 readonly environmentId: EnvironmentId;
559 readonly label: string;
560 readonly providers: ReadonlyArray<string>;
561 }>;
562 readonly skipped: ReadonlyArray<SkippedMachine>;
563}
564
565export interface UpdateEverythingRow {
566 readonly environmentId: EnvironmentId | null;
567 readonly label: string;
568 readonly app: "this-app" | "server" | "desktop-app" | null;
569 readonly skipped: string | null;
570 readonly providers: ReadonlyArray<string>;
571}
572
573function countLabel(count: number, noun: string): string | null {
574 return count === 0 ? null : `${count} ${noun}${count === 1 ? "" : "s"}`;
575}
576
577function joinList(parts: ReadonlyArray<string>): string {
578 if (parts.length <= 2) return parts.join(" and ");
579 return `${parts.slice(0, -1).join(", ")}, and ${parts.at(-1)}`;
580}
581
582/** One row per machine: this app's machines first, then servers, provider-only, and skipped. */
583export function describeUpdateEverything(plan: UpdateEverythingPlan): {
584 readonly summary: string;
585 readonly version: string | null;
586 readonly providerCount: number;
587 readonly rows: ReadonlyArray<UpdateEverythingRow>;
588} {
589 const providerCount = plan.providerMachines.reduce(
590 (count, machine) => count + machine.providers.length,
591 0,
592 );
593 const summary = `Update ${joinList(
594 [
595 plan.localVersion ? "this app" : null,
596 countLabel(plan.servers.length, "server"),
597 countLabel(providerCount, "provider"),
598 ].filter((part) => part !== null),
599 )}`;
600
601 const rows = new Map<EnvironmentId | null, UpdateEverythingRow>();
602 const update = (
603 environmentId: EnvironmentId | null,
604 label: string,
605 change: Partial<UpdateEverythingRow>,
606 ) => {
607 const row = rows.get(environmentId) ?? {
608 environmentId,
609 label,
610 app: null,
611 skipped: null,
612 providers: [],
613 };
614 rows.set(environmentId, { ...row, ...change });
615 };
616 if (plan.localVersion) {
617 if (plan.localMachines.length === 0) update(null, "This app", { app: "this-app" });
618 for (const machine of plan.localMachines) {
619 update(machine.environmentId, machine.label, { app: "this-app" });
620 }
621 }
622 for (const server of plan.servers) {
623 update(server.environmentId, server.serverLabel, {
624 app: server.selfUpdate === "desktop-managed" ? "desktop-app" : "server",
625 });
626 }
627 for (const machine of plan.providerMachines) {
628 update(machine.environmentId, machine.label, { providers: machine.providers });
629 }
630 for (const machine of plan.skipped) {
631 update(machine.environmentId, machine.label, { skipped: machine.reason });
632 }
633
634 return {
635 summary,
636 version:
637 plan.localVersion ??
638 plan.servers.find((server) => server.selfUpdate !== "desktop-managed")?.targetVersion ??
639 null,
640 providerCount,
641 rows: Array.from(rows.values()),
642 };
643}