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

updateEverything.logic.ts

1,034 lines34.9 KB

1import {
2 managedNightlyDeniedMessage,
3 managedUpdatesDenial,
4} from "@t3tools/client-runtime/contract-labels";
5import type { ServerUpdateState } from "@t3tools/client-runtime/state/server";
6import {
7 type DesktopUpdateChannel,
8 type EnvironmentId,
9 type ServerConfig,
10 type ServerSelfUpdateCapability,
11} from "@t3tools/contracts";
12import { cliReleaseChannelOf, desktopUpdateChannelOf } from "@t3tools/shared/cliRelease";
13import { compareSemverVersions } from "@t3tools/shared/semver";
14import { msg, plural, part } from "gt-react";
15​
16import { m, type MessageResolver } from "~/i18n/messages";
17import {
18 resolveServerSelfUpdateCapability,
19 resolveVersionMismatch,
20 supportsDesktopAppUpdate,
21} from "~/versionSkew";
22import type { ServerUpdateOutcome, ServerUpdateTarget } from "../ServerUpdateAction";
23​
24export interface UpdateEverythingMachine {
25 readonly environmentId: EnvironmentId;
26 readonly label: string;
27 readonly serverConfig: {
28 readonly environment: ServerConfig["environment"];
29 readonly settings: Pick<ServerConfig["settings"], "continueThreadsAfterServerUpdate">;
30 readonly managedPolicy?: ServerConfig["managedPolicy"];
31 } | null;
32 readonly connected: boolean;
33 /** Why the connection is down, when it says, in the active language. */
34 readonly connectionError?: string | null;
35 /** The saved connection is switched off in Settings, so it never connects. */
36 readonly turnedOff?: boolean;
37 readonly hostedByThisApp: boolean;
38 readonly canMaintain: boolean;
39 readonly updateState: ServerUpdateState;
41​
42export interface RestartingMachine {
43 readonly environmentId: EnvironmentId;
44 readonly continuesThreads: boolean;
46​
47export function collectRestartingMachines(
48 machines: ReadonlyArray<UpdateEverythingMachine>,
49 servers: ReadonlyArray<Pick<ServerUpdateTarget, "environmentId">>,
50 installsLocal: boolean,
51): RestartingMachine[] {
52 const updated = new Set(servers.map((server) => server.environmentId));
53 return machines.flatMap((machine) => {
54 const config = machine.serverConfig;
55 if (
56 config === null ||
57 !machine.connected ||
58 !(updated.has(machine.environmentId) || (installsLocal && machine.hostedByThisApp))
59 ) {
60 return [];
61 }
62 return [
63 {
64 environmentId: machine.environmentId,
65 continuesThreads: config.settings.continueThreadsAfterServerUpdate === true,
66 },
67 ];
68 });
70​
71export interface SkippedMachine {
72 readonly environmentId: EnvironmentId;
73 readonly label: string;
74 readonly reason: string;
76​
77// Desktop servers without the desktop control fd (older apps, WSL backends: wsl.exe cannot pass
78// fds) cannot be updated from here, and their desktop app is not necessarily the stale part.
79const UPDATE_ON_THAT_MACHINE = msg("update T3 Code on that machine");
80​
81/** The registry can know a release this app's own check has not found yet. Only a newer release on
82 * the app's track raises the version servers move to. */
83export function resolveFleetTargetVersion(
84 appTarget: string,
85 registryVersion: string | null,
86): string {
87 return registryVersion !== null &&
88 cliReleaseChannelOf(registryVersion) === cliReleaseChannelOf(appTarget) &&
89 compareSemverVersions(registryVersion, appTarget) > 0
90 ? registryVersion
91 : appTarget;
93​
94/** Skip current and app-hosted servers; the latter update with the app and would relaunch mid-run.
95 * Desktop-managed servers use their own feed. Each server's updater checks that it can install the
96 * release before it restarts, so no registry precheck runs here. */
97export function collectServerUpdateTargets(
98 machines: ReadonlyArray<UpdateEverythingMachine>,
99 targetVersion: string,
100 resolve: MessageResolver = m,
101): {
102 readonly targets: ServerUpdateTarget[];
103 readonly skipped: SkippedMachine[];
104} {
105 const targets: ServerUpdateTarget[] = [];
106 const skipped: SkippedMachine[] = [];
107 for (const machine of machines) {
108 const config = machine.serverConfig;
109 if (machine.hostedByThisApp) continue;
110 if (
111 config !== null &&
112 resolveVersionMismatch(config.environment.serverVersion, targetVersion) === null
113 ) {
114 continue;
115 }
116 const skip = (reason: string) =>
117 skipped.push({ environmentId: machine.environmentId, label: machine.label, reason });
118 const unavailable = unavailableReason(machine, resolve);
119 if (config === null || unavailable !== null) {
120 skip(unavailable ?? resolve(msg("not connected")));
121 continue;
122 }
123 const selfUpdate = resolveServerSelfUpdateCapability(config);
124 const managedDenial = managedMachineUpdateDenial(
125 config,
126 selfUpdate === "desktop-managed" ? undefined : targetVersion,
127 resolve,
128 );
129 if (managedDenial !== undefined) {
130 skip(managedDenial);
131 continue;
132 }
133 const desktopAppUpdate = supportsDesktopAppUpdate(config);
134 if (selfUpdate === null) {
135 skip(resolve(msg("needs a manual update")));
136 continue;
137 }
138 if (selfUpdate === "desktop-managed" && !desktopAppUpdate) {
139 skip(resolve(UPDATE_ON_THAT_MACHINE));
140 continue;
141 }
142 const serverChannel = cliReleaseChannelOf(config.environment.serverVersion);
143 // A desktop app installs its own track's newest release. Nightly builds run ahead of Stable, so a
144 // Nightly host behind a Stable target has something newer; a Stable host may not.
145 if (
146 serverChannel !== cliReleaseChannelOf(targetVersion) &&
147 (selfUpdate !== "desktop-managed" || serverChannel === "stable")
148 ) {
149 skip(resolve(msg`on the ${{ channel: serverChannel }} channel`));
150 continue;
151 }
152 const target: ServerUpdateTarget = {
153 environmentId: machine.environmentId,
154 serverLabel: machine.label,
155 selfUpdate,
156 installation: config.environment.capabilities.serverInstallation,
157 desktopAppUpdate,
158 targetVersion,
159 };
160 targets.push(target);
161 }
162 return { targets, skipped };
164​
165function unavailableReason(
166 machine: UpdateEverythingMachine,
167 resolve: MessageResolver,
168): string | null {
169 if (machine.turnedOff === true) {
170 return resolve(
171 msg({ context: "why a server update was skipped: its saved connection is off" })`turned off`,
172 );
173 }
174 if (!machine.connected) return machine.connectionError ?? resolve(msg("not connected"));
175 if (machine.serverConfig === null)
176 return resolve(
177 msg({
178 context: "why a server update was skipped: its settings have not arrived yet",
179 })`still loading`,
180 );
181 if (!machine.canMaintain) return resolve(msg("no permission"));
182 if (machine.updateState.status === "running") return resolve(msg("already updating"));
183 return null;
185​
186/** The latest release on the track a fleet switches to, as npm reports it. */
187export interface ChannelSwitchRelease {
188 readonly channel: DesktopUpdateChannel;
189 readonly version: string;
190 readonly databaseMigration: number | undefined;
192​
193/** Components pass `useMessages()` so labels follow a language switch. */
194export const channelSwitchLabel = (channel: DesktopUpdateChannel, resolve: MessageResolver = m) =>
195 channel === "nightly"
196 ? resolve(msg({ context: "release track" })`Nightly`)
197 : resolve(msg({ context: "release track" })`Stable`);
198​
199/** Stable and Nightly each build their own commits, so either can hold migrations the other lacks.
200 * Crossing tracks needs proof that the target release knows every migration the database holds. */
201const crossesTrack = (fromVersion: string, release: ChannelSwitchRelease) =>
202 desktopUpdateChannelOf(fromVersion) !== release.channel;
203​
204type ChannelSwitchBlock = "server-predates-checks" | "release-predates-checks" | "unsupported";
205​
206function channelSwitchBlock(
207 fromVersion: string,
208 release: ChannelSwitchRelease,
209 currentMigration: number | undefined,
210): ChannelSwitchBlock | null {
211 if (!crossesTrack(fromVersion, release)) return null;
212 // Servers and releases from before this check report no migration number.
213 if (currentMigration === undefined) return "server-predates-checks";
214 if (release.databaseMigration === undefined) return "release-predates-checks";
215 return currentMigration > release.databaseMigration ? "unsupported" : null;
217​
218function channelSwitchBlockReason(
219 fromVersion: string,
220 release: ChannelSwitchRelease,
221 currentMigration: number | undefined,
222 resolve: MessageResolver,
223): string | null {
224 const block = channelSwitchBlock(fromVersion, release, currentMigration);
225 if (block === null) return null;
226 const from = channelSwitchLabel(desktopUpdateChannelOf(fromVersion), resolve);
227 const to = channelSwitchLabel(release.channel, resolve);
228 const version = release.version;
229 switch (block) {
230 case "server-predates-checks":
231 return resolve(msg`its server predates database checks; update it on ${{ from }} first`);
232 case "release-predates-checks":
233 return resolve(
234 msg`${{ version }} predates database checks; wait for a newer ${{ to }} release`,
235 );
236 case "unsupported":
237 return resolve(
238 msg`its database has changes ${{ version }} does not support yet; stay on ${{ from }} until ${{ to }} has them`,
239 );
240 }
242​
243function localChannelSwitchBlockReason(
244 fromVersion: string,
245 release: ChannelSwitchRelease,
246 block: ChannelSwitchBlock,
247 resolve: MessageResolver,
248): string {
249 const from = channelSwitchLabel(desktopUpdateChannelOf(fromVersion), resolve);
250 const to = channelSwitchLabel(release.channel, resolve);
251 const version = release.version;
252 switch (block) {
253 case "server-predates-checks":
254 return resolve(
255 msg`This app cannot switch: its server predates database checks; update it on ${{ from }} first.`,
256 );
257 case "release-predates-checks":
258 return resolve(
259 msg`This app cannot switch: ${{ version }} predates database checks; wait for a newer ${{ to }} release.`,
260 );
261 case "unsupported":
262 return resolve(
263 msg`This app cannot switch: its database has changes ${{ version }} does not support yet; stay on ${{ from }} until ${{ to }} has them.`,
264 );
265 }
267​
268/** This app's reinstall restarts every server it hosts, so each of their databases must allow the
269 * switch. `backendCount` is the desktop's own inventory: a backend still starting has no client
270 * entry yet. A cached config can outlive its connection, so only a connected server's head counts.
271 * With Local environment off this app runs no server, so its reinstall restarts none. */
272export function localSwitchBlockReason(
273 appVersion: string,
274 release: ChannelSwitchRelease,
275 hosted: ReadonlyArray<{
276 readonly connected: boolean;
277 readonly databaseMigration: number | undefined;
278 }>,
279 backendCount: number,
280 localEnvironmentEnabled: boolean,
281 resolve: MessageResolver = m,
282): string | null {
283 if (!localEnvironmentEnabled || !crossesTrack(appVersion, release)) return null;
284 if (
285 hosted.length === 0 ||
286 hosted.length < backendCount ||
287 hosted.some((server) => !server.connected)
288 ) {
289 return resolve(
290 msg(
291 "This app cannot switch: its server is not connected, so its database cannot be checked.",
292 ),
293 );
294 }
295 const block = hosted
296 .map((server) => channelSwitchBlock(appVersion, release, server.databaseMigration))
297 .find((reason): reason is ChannelSwitchBlock => reason !== null);
298 return block === undefined
299 ? null
300 : localChannelSwitchBlockReason(appVersion, release, block, resolve);
302​
303/**
304 * The server refuses these with the same message; say so before the run instead of after.
305 * `targetVersion` is undefined when the server picks its own version, as desktop apps do.
306 */
307function managedMachineUpdateDenial(
308 config: NonNullable<UpdateEverythingMachine["serverConfig"]>,
309 targetVersion: string | undefined,
310 resolve: MessageResolver,
311): string | undefined {
312 const policy = config.managedPolicy;
313 return (
314 managedUpdatesDenial(policy, resolve) ??
315 (policy !== undefined &&
316 policy.limits?.updates?.allowNightly === false &&
317 targetVersion !== undefined &&
318 cliReleaseChannelOf(targetVersion) !== "stable"
319 ? managedNightlyDeniedMessage(policy.organization, resolve)
320 : undefined)
321 );
323​
324/** Servers move to the release; desktop-managed hosts reinstall their app on its track. A desktop
325 * host already current gets a track-only request, since its saved track may still differ. */
326export function collectChannelSwitchTargets(
327 machines: ReadonlyArray<UpdateEverythingMachine>,
328 release: ChannelSwitchRelease,
329 resolve: MessageResolver = m,
330): { readonly targets: ServerUpdateTarget[]; readonly skipped: SkippedMachine[] } {
331 const targets: ServerUpdateTarget[] = [];
332 const skipped: SkippedMachine[] = [];
333 for (const machine of machines) {
334 const config = machine.serverConfig;
335 if (machine.hostedByThisApp) continue;
336 const skip = (reason: string) =>
337 skipped.push({ environmentId: machine.environmentId, label: machine.label, reason });
338 const target = (
339 selfUpdate: ServerSelfUpdateCapability,
340 targetVersion: string,
341 ): ServerUpdateTarget => ({
342 environmentId: machine.environmentId,
343 serverLabel: machine.label,
344 selfUpdate,
345 installation: config?.environment.capabilities.serverInstallation,
346 desktopAppUpdate: config !== null && supportsDesktopAppUpdate(config),
347 targetVersion,
348 ...(selfUpdate === "desktop-managed" ? { channel: release.channel } : {}),
349 ...(release.databaseMigration === undefined
350 ? {}
351 : { targetDatabaseMigration: release.databaseMigration }),
352 });
353 const serverVersion = config?.environment.serverVersion;
354 const sameTrack = serverVersion !== undefined && isOnTrack(serverVersion, release.channel);
355 if (
356 config !== null &&
357 sameTrack &&
358 resolveVersionMismatch(serverVersion, release.version) === null
359 ) {
360 const move = trackSwitchMove(config, true, resolve);
361 if (
362 !("skip" in move) &&
363 move.selfUpdate === "desktop-managed" &&
364 unavailableReason(machine, resolve) === null &&
365 managedMachineUpdateDenial(config, release.version, resolve) === undefined
366 ) {
367 targets.push({ ...target(move.selfUpdate, serverVersion), trackOnly: true });
368 }
369 continue;
370 }
371 const unavailable = unavailableReason(machine, resolve);
372 if (config === null || serverVersion === undefined || unavailable !== null) {
373 skip(unavailable ?? resolve(msg("not connected")));
374 continue;
375 }
376 const managedDenial = managedMachineUpdateDenial(config, release.version, resolve);
377 if (managedDenial !== undefined) {
378 skip(managedDenial);
379 continue;
380 }
381 const move = trackSwitchMove(config, sameTrack, resolve);
382 if ("skip" in move) {
383 skip(move.skip);
384 continue;
385 }
386 const blocked = channelSwitchBlockReason(
387 serverVersion,
388 release,
389 config.environment.databaseMigration,
390 resolve,
391 );
392 if (blocked !== null) {
393 skip(blocked);
394 continue;
395 }
396 // Service launchers only accept newer versions, so leaving for an older release is manual.
397 if (
398 move.selfUpdate === "boot-service" &&
399 compareSemverVersions(release.version, serverVersion) <= 0
400 ) {
401 skip(
402 resolve(
403 msg`run \`${{ command: `t3 update --channel ${release.channel === "nightly" ? "nightly" : "stable"} --allow-downgrade` }}\` there`,
404 ),
405 );
406 continue;
407 }
408 targets.push(target(move.selfUpdate, release.version));
409 }
410 return { targets, skipped };
412​
413/** A remote host on the other track that a switch can still move, for retrying a partial switch. */
414export function awaitsTrackSwitch(
415 machine: Pick<UpdateEverythingMachine, "serverConfig" | "hostedByThisApp">,
416 channel: DesktopUpdateChannel,
417): boolean {
418 const config = machine.serverConfig;
419 return (
420 !machine.hostedByThisApp &&
421 config !== null &&
422 !isOnTrack(config.environment.serverVersion, channel) &&
423 !("skip" in trackSwitchMove(config, false, m))
424 );
426​
427function isOnTrack(version: string, channel: DesktopUpdateChannel): boolean {
428 return cliReleaseChannelOf(version) !== "preview" && desktopUpdateChannelOf(version) === channel;
430​
431/** How a switch moves a host, or why it never can from here, whatever the release. */
432function trackSwitchMove(
433 config: NonNullable<UpdateEverythingMachine["serverConfig"]>,
434 sameTrack: boolean,
435 resolve: MessageResolver,
436): { readonly selfUpdate: ServerSelfUpdateCapability } | { readonly skip: string } {
437 if (cliReleaseChannelOf(config.environment.serverVersion) === "preview") {
438 return { skip: resolve(msg("runs a preview build")) };
439 }
440 const selfUpdate = resolveServerSelfUpdateCapability(config);
441 if (selfUpdate === null) return { skip: resolve(msg("needs a manual update")) };
442 if (selfUpdate !== "desktop-managed") return { selfUpdate };
443 if (config.environment.capabilities.desktopAppChannelSwitch !== true) {
444 return {
445 skip: resolve(
446 sameTrack ? UPDATE_ON_THAT_MACHINE : msg("change the update track on that machine"),
447 ),
448 };
449 }
450 // Squirrel.Mac renames the bundle for the new track and then cannot relaunch it.
451 if (!sameTrack && config.environment.platform.os === "darwin") {
452 return { skip: resolve(msg("switch the Mac app on that Mac")) };
453 }
454 return { selfUpdate };
456​
457export interface UpdateEverythingSteps<Providers, Servers> {
458 readonly downloadLocal?: () => Promise<boolean>;
459 readonly updateProviders: () => Promise<Providers>;
460 readonly stageServers?: () => ReadonlyMap<EnvironmentId, Promise<unknown>>;
461 readonly updateServers: (
462 staged: ReadonlyMap<EnvironmentId, Promise<unknown>>,
463 ) => Promise<Servers>;
465​
466/** Finish provider installs before server restarts; servers stage meanwhile and each server's
467 * update waits only on its own stage. Install this app last when localReady; failed downloads skip
468 * only that install. */
469export async function runUpdateEverything<Providers, Servers>(
470 steps: UpdateEverythingSteps<Providers, Servers>,
471): Promise<{
472 readonly localReady: boolean;
473 readonly providers: Providers;
474 readonly servers: Servers;
475}> {
476 const staged = new Map(
477 Array.from(steps.stageServers?.() ?? [], ([id, stage]) => [id, stage.catch(() => undefined)]),
478 );
479 const [localReady, remote] = await Promise.all([
480 steps.downloadLocal?.() ?? Promise.resolve(true),
481 steps
482 .updateProviders()
483 .then(async (providers) => ({ providers, servers: await steps.updateServers(staged) })),
484 ]);
485 return { localReady, ...remote };
487​
488export type UpdateRunMachineStatus =
489 | "providers"
490 | "waiting"
491 | "downloading"
492 | "restarting"
493 | "done"
494 | "failed";
495​
496export interface UpdateRunMachine {
497 readonly environmentId: EnvironmentId;
498 readonly label: string;
499 readonly updatesProviders: boolean;
500 readonly server: ServerUpdateTarget | null;
501 readonly handedOffVersion: string | null;
502 readonly startedAt: number;
503 readonly result: "done" | "failed" | null;
504 readonly failure: string | null;
505 readonly providerFailure: string | null;
507​
508export interface UpdateEverythingRun {
509 /** Track switches retry through their planner, which re-checks each database. */
510 readonly trackSwitch?: boolean;
511 readonly localVersion: string | null;
512 readonly phase: "providers" | "servers" | "countdown" | "installing";
513 readonly restartAt: number | null;
514 readonly machines: ReadonlyArray<UpdateRunMachine>;
516​
517export function resolveUpdateRunMachineStatus(
518 machine: UpdateRunMachine,
519 phase: UpdateEverythingRun["phase"],
520 serverState: ServerUpdateState,
521): UpdateRunMachineStatus {
522 if (machine.result !== null) return machine.result;
523 if (machine.handedOffVersion !== null) return "restarting";
524 if (phase === "providers" && machine.updatesProviders) return "providers";
525 if (machine.server !== null && serverState.status === "running") {
526 return serverState.stage === "resuming" ? "restarting" : "downloading";
527 }
528 return "waiting";
530​
531/** "current": the server already runs the target, so retrying it only settles the row. */
532export type RestoredRetry = ServerUpdateTarget | "current";
533​
534/** A row restored after this app relaunched keeps only its target version, so its retry is
535 * rebuilt from the server as it is now, as the dialog would. Null when there is nothing to retry. */
536export function resolveRestoredRetry(
537 machine: UpdateRunMachine,
538 machines: ReadonlyArray<UpdateEverythingMachine>,
539): RestoredRetry | null {
540 const targetVersion = machine.handedOffVersion;
541 if (machine.result !== "failed" || machine.server !== null || targetVersion === null) return null;
542 const current = machines.find(({ environmentId }) => environmentId === machine.environmentId);
543 if (current === undefined) return null;
544 const config = current.serverConfig;
545 if (
546 current.connected &&
547 config !== null &&
548 resolveVersionMismatch(config.environment.serverVersion, targetVersion) === null
549 ) {
550 return "current";
551 }
552 return collectServerUpdateTargets([current], targetVersion).targets[0] ?? null;
554​
555export function isServerUpdateHandedOff(state: ServerUpdateState): boolean {
556 return state.status === "running" && state.stage === "resuming";
558​
559export function closeFinishedUpdateRun(run: UpdateEverythingRun): UpdateEverythingRun | null {
560 return run.phase === "servers" &&
561 run.localVersion === null &&
562 run.machines.every((machine) => machine.result === "done")
563 ? null
564 : run;
566​
567const UPDATE_SLOW_AFTER_MS = 3 * 60 * 1000;
568​
569export function formatUpdateElapsed(ms: number, resolve: MessageResolver = m): string {
570 const minutes = Math.floor(ms / 60_000);
571 if (minutes < 1) return resolve(msg("<1m"));
572 if (minutes < 60) return resolve(msg`${{ minutes }}m`);
573 return resolve(msg`${{ hours: Math.floor(minutes / 60) }}h ${{ minutes: minutes % 60 }}m`);
575​
576export interface UpdateRunMachineView {
577 readonly machine: UpdateRunMachine;
578 readonly status: UpdateRunMachineStatus;
579 readonly restoredRetry: RestoredRetry | null;
581​
582export type UpdateRunLocalState =
583 | { readonly status: "downloading"; readonly percent: number | null }
584 | { readonly status: "waiting" }
585 | null;
586​
587export interface UpdateCapsuleView {
588 readonly tone: "default" | "slow" | "failed";
589 readonly label: string;
590 readonly slow?: { readonly status: string; readonly elapsed: string };
591 readonly action: "later" | "retry" | "dismiss" | null;
593​
594const isActive = (status: UpdateRunMachineStatus) => status !== "done" && status !== "failed";
595​
596export function describeUpdateCapsule(
597 run: UpdateEverythingRun,
598 machines: ReadonlyArray<UpdateRunMachineView>,
599 local: UpdateRunLocalState,
600 now: number,
601 resolve: MessageResolver = m,
602): UpdateCapsuleView {
603 if (run.phase === "countdown" && run.restartAt !== null) {
604 const seconds = Math.max(0, Math.ceil((run.restartAt - now) / 1000));
605 return {
606 tone: "default",
607 label: resolve(msg`Restart in ${{ seconds }}s`),
608 action: "later",
609 };
610 }
611 if (run.phase === "installing") {
612 return { tone: "default", label: resolve(msg("Restarting…")), action: null };
613 }
614 const active = machines.filter(({ status }) => isActive(status) && status !== "waiting");
615 const slowest = active.toSorted((a, b) => a.machine.startedAt - b.machine.startedAt)[0];
616 if (slowest && now - slowest.machine.startedAt >= UPDATE_SLOW_AFTER_MS) {
617 return {
618 tone: "slow",
619 label: slowest.machine.label,
620 slow: {
621 status: resolve(RUN_STATUS_LABELS[slowest.status]),
622 elapsed: formatUpdateElapsed(now - slowest.machine.startedAt, resolve),
623 },
624 action: null,
625 };
626 }
627 const done = machines.filter(({ status }) => status === "done").length;
628 if (machines.some(({ status }) => isActive(status))) {
629 return {
630 tone: "default",
631 label: resolve(msg`${{ done }} of ${{ total: machines.length }} updated`),
632 action: null,
633 };
634 }
635 if (local?.status === "downloading") {
636 return {
637 tone: "default",
638 label:
639 local.percent === null
640 ? resolve(msg("Downloading"))
641 : resolve(msg`Downloading ${{ percent: Math.floor(local.percent) }}%`),
642 action: null,
643 };
644 }
645 const failed = machines.filter(({ status }) => status === "failed");
646 if (failed.length > 0) {
647 return {
648 tone: "failed",
649 label:
650 failed.length === 1
651 ? resolve(msg`${{ machine: failed[0]!.machine.label }} failed`)
652 : resolve(
653 msg`${plural(
654 { count: failed.length },
655 {
656 one: part`${{ count: failed.length }} failed`,
657 other: part`${{ count: failed.length }} failed`,
658 },
659 )}`,
660 ),
661 action:
662 !run.trackSwitch &&
663 failed.some(
664 ({ machine, restoredRetry }) => machine.server !== null || restoredRetry !== null,
665 )
666 ? "retry"
667 : "dismiss",
668 };
669 }
670 return {
671 tone: "default",
672 label: resolve(msg`${{ done }} of ${{ total: machines.length }} updated`),
673 action: null,
674 };
676​
677/** `msg()` strings: resolve them with `m` or `useMessages()` where they show. */
678export const RUN_STATUS_LABELS: Record<UpdateRunMachineStatus, string> = {
679 providers: msg("updating providers"),
680 waiting: msg("waiting"),
681 downloading: msg("downloading"),
682 restarting: msg("restarting"),
683 done: msg("done"),
684 failed: msg("failed"),
685};
686​
687export interface UpdateEverythingResult {
688 readonly localVersion: string | null;
689 readonly updatedServers: number;
690 readonly updatedProviders: number;
691 readonly failures: ReadonlyArray<string>;
692 readonly restarting: ReadonlyArray<string>;
694​
695export function collectUpdateEverythingResult(input: {
696 readonly localVersion: string | null;
697 readonly localFailures: ReadonlyArray<string>;
698 readonly servers: ReadonlyArray<{
699 readonly label: string;
700 readonly outcome: ServerUpdateOutcome;
701 }>;
702 readonly providers: ReadonlyArray<
703 | { readonly status: "interrupted" | "updated" }
704 | { readonly status: "failed"; readonly line: string }
705 >;
706}): UpdateEverythingResult {
707 return {
708 localVersion: input.localVersion,
709 updatedServers: input.servers.filter(({ outcome }) => outcome.status === "updated").length,
710 updatedProviders: input.providers.filter((outcome) => outcome.status === "updated").length,
711 restarting: [],
712 failures: [
713 ...input.localFailures.map((failure) => m(msg`This app: ${{ failure }}`)),
714 ...input.servers.flatMap(({ label, outcome }) =>
715 outcome.status === "failed" ? [`${label}: ${outcome.message}`] : [],
716 ),
717 ...input.providers.flatMap((outcome) => (outcome.status === "failed" ? [outcome.line] : [])),
718 ],
719 };
721​
722export function getUpdateEverythingToastView(
723 result: UpdateEverythingResult,
724 appVersion: string,
725): {
726 readonly type: "success" | "error";
727 readonly title: string;
728 readonly description?: string;
729} | null {
730 const updated = updateTargetsSentence(
731 "updated",
732 {
733 app: result.localVersion !== null && result.localVersion === appVersion,
734 servers: result.updatedServers,
735 providers: result.updatedProviders,
736 },
737 m,
738 );
739 const machines = result.restarting.length === 0 ? "" : joinList(result.restarting, m);
740 const restarting =
741 result.restarting.length === 0
742 ? []
743 : [
744 m(
745 msg`${plural(
746 { count: result.restarting.length },
747 {
748 one: part`${{ machines }} is still restarting.`,
749 other: part`${{ machines }} are still restarting.`,
750 },
751 )}`,
752 ),
753 ];
754 if (result.failures.length === 0) {
755 if (updated === null) return null;
756 return {
757 type: "success",
758 title: updated,
759 ...(restarting.length === 0 ? {} : { description: restarting.join("\n") }),
760 };
761 }
762 return {
763 type: "error",
764 title: updated === null ? m(msg("Update failed")) : updated,
765 description: [...result.failures, ...restarting].join("\n"),
766 };
768​
769export interface UpdateEverythingPlan {
770 readonly localVersion: string | null;
771 /** Machines whose servers this app hosts; this app's update restarts them. */
772 readonly localMachines: ReadonlyArray<{
773 readonly environmentId: EnvironmentId;
774 readonly label: string;
775 }>;
776 readonly servers: ReadonlyArray<
777 Pick<ServerUpdateTarget, "environmentId" | "serverLabel" | "selfUpdate" | "targetVersion">
778 >;
779 readonly providerMachines: ReadonlyArray<{
780 readonly environmentId: EnvironmentId;
781 readonly label: string;
782 readonly providers: ReadonlyArray<string>;
783 }>;
784 readonly skipped: ReadonlyArray<SkippedMachine>;
786​
787export interface UpdateEverythingRow {
788 readonly environmentId: EnvironmentId | null;
789 readonly label: string;
790 readonly app: "this-app" | "server" | "desktop-app" | null;
791 readonly skipped: string | null;
792 readonly providers: ReadonlyArray<string>;
794​
795/** "Update this app, 2 servers, and 3 providers" as one sentence per combination; null when nothing. */
796function updateTargetsSentence(
797 verb: "update" | "updated",
798 targets: { readonly app: boolean; readonly servers: number; readonly providers: number },
799 resolve: MessageResolver,
800): string | null {
801 const { app, servers, providers } = targets;
802 const update = verb === "update";
803 if (app && servers > 0 && providers > 0) {
804 return update
805 ? resolve(
806 msg`Update this app, ${plural(
807 { servers },
808 {
809 one: part`${{ servers }} server`,
810 other: part`${{ servers }} servers`,
811 },
812 )}, and ${plural(
813 { providers },
814 {
815 one: part`${{ providers }} provider`,
816 other: part`${{ providers }} providers`,
817 },
818 )}`,
819 )
820 : resolve(
821 msg`Updated this app, ${plural(
822 { servers },
823 {
824 one: part`${{ servers }} server`,
825 other: part`${{ servers }} servers`,
826 },
827 )}, and ${plural(
828 { providers },
829 {
830 one: part`${{ providers }} provider`,
831 other: part`${{ providers }} providers`,
832 },
833 )}`,
834 );
835 }
836 if (app && servers > 0) {
837 return update
838 ? resolve(
839 msg`Update this app and ${plural(
840 { servers },
841 {
842 one: part`${{ servers }} server`,
843 other: part`${{ servers }} servers`,
844 },
845 )}`,
846 )
847 : resolve(
848 msg`Updated this app and ${plural(
849 { servers },
850 {
851 one: part`${{ servers }} server`,
852 other: part`${{ servers }} servers`,
853 },
854 )}`,
855 );
856 }
857 if (app && providers > 0) {
858 return update
859 ? resolve(
860 msg`Update this app and ${plural(
861 { providers },
862 {
863 one: part`${{ providers }} provider`,
864 other: part`${{ providers }} providers`,
865 },
866 )}`,
867 )
868 : resolve(
869 msg`Updated this app and ${plural(
870 { providers },
871 {
872 one: part`${{ providers }} provider`,
873 other: part`${{ providers }} providers`,
874 },
875 )}`,
876 );
877 }
878 if (servers > 0 && providers > 0) {
879 return update
880 ? resolve(
881 msg`Update ${plural(
882 { servers },
883 {
884 one: part`${{ servers }} server`,
885 other: part`${{ servers }} servers`,
886 },
887 )} and ${plural(
888 { providers },
889 {
890 one: part`${{ providers }} provider`,
891 other: part`${{ providers }} providers`,
892 },
893 )}`,
894 )
895 : resolve(
896 msg`Updated ${plural(
897 { servers },
898 {
899 one: part`${{ servers }} server`,
900 other: part`${{ servers }} servers`,
901 },
902 )} and ${plural(
903 { providers },
904 {
905 one: part`${{ providers }} provider`,
906 other: part`${{ providers }} providers`,
907 },
908 )}`,
909 );
910 }
911 if (app) return update ? resolve(msg("Update this app")) : resolve(msg("Updated this app"));
912 if (servers > 0) {
913 return update
914 ? resolve(
915 msg`Update ${plural(
916 { servers },
917 {
918 one: part`${{ servers }} server`,
919 other: part`${{ servers }} servers`,
920 },
921 )}`,
922 )
923 : resolve(
924 msg`Updated ${plural(
925 { servers },
926 {
927 one: part`${{ servers }} server`,
928 other: part`${{ servers }} servers`,
929 },
930 )}`,
931 );
932 }
933 if (providers > 0) {
934 return update
935 ? resolve(
936 msg`Update ${plural(
937 { providers },
938 {
939 one: part`${{ providers }} provider`,
940 other: part`${{ providers }} providers`,
941 },
942 )}`,
943 )
944 : resolve(
945 msg`Updated ${plural(
946 { providers },
947 {
948 one: part`${{ providers }} provider`,
949 other: part`${{ providers }} providers`,
950 },
951 )}`,
952 );
953 }
954 return null;
956​
957function joinList(parts: ReadonlyArray<string>, resolve: MessageResolver): string {
958 if (parts.length <= 1) return parts.join("");
959 if (parts.length === 2) {
960 return resolve(msg`${{ first: parts[0] }} and ${{ second: parts[1] }}`);
961 }
962 return resolve(msg`${{ items: parts.slice(0, -1).join(", ") }}, and ${{ last: parts.at(-1) }}`);
964​
965/** One row per machine: this app's machines first, then servers, provider-only, and skipped. */
966export function describeUpdateEverything(
967 plan: UpdateEverythingPlan,
968 resolve: MessageResolver = m,
969): {
970 readonly summary: string;
971 readonly version: string | null;
972 readonly providerCount: number;
973 readonly rows: ReadonlyArray<UpdateEverythingRow>;
974} {
975 const providerCount = plan.providerMachines.reduce(
976 (count, machine) => count + machine.providers.length,
977 0,
978 );
979 const summary =
980 updateTargetsSentence(
981 "update",
982 {
983 app: Boolean(plan.localVersion),
984 servers: plan.servers.length,
985 providers: providerCount,
986 },
987 resolve,
988 ) ?? resolve(msg`Update ${{ items: "" }}`);
989​
990 const rows = new Map<EnvironmentId | null, UpdateEverythingRow>();
991 const update = (
992 environmentId: EnvironmentId | null,
993 label: string,
994 change: Partial<UpdateEverythingRow>,
995 ) => {
996 const row = rows.get(environmentId) ?? {
997 environmentId,
998 label,
999 app: null,
1000 skipped: null,
1001 providers: [],
1002 };
1003 rows.set(environmentId, { ...row, ...change });
1004 };
1005 if (plan.localVersion) {
1006 if (plan.localMachines.length === 0) {
1007 update(null, resolve(msg("This app")), { app: "this-app" });
1009 for (const machine of plan.localMachines) {
1010 update(machine.environmentId, machine.label, { app: "this-app" });
1013 for (const server of plan.servers) {
1014 update(server.environmentId, server.serverLabel, {
1015 app: server.selfUpdate === "desktop-managed" ? "desktop-app" : "server",
1016 });
1018 for (const machine of plan.providerMachines) {
1019 update(machine.environmentId, machine.label, { providers: machine.providers });
1021 for (const machine of plan.skipped) {
1022 update(machine.environmentId, machine.label, { skipped: machine.reason });
1024​
1025 return {
1026 summary,
1027 version:
1028 plan.localVersion ??
1029 plan.servers.find((server) => server.selfUpdate !== "desktop-managed")?.targetVersion ??
1030 null,
1031 providerCount,
1032 rows: Array.from(rows.values()),
1033 };