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

updateEverything.logic.ts

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