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

updateEverything.logic.ts

658 lines23.0 KB

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