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

updateEverything.logic.ts

426 lines14.2 KB

1import type { ServerUpdateState } from "@t3tools/client-runtime/state/server";
2import type { EnvironmentId, ServerConfig } from "@t3tools/contracts";
3import { cliReleaseChannelOf } from "@t3tools/shared/cliRelease";
4​
5import {
6 resolveServerSelfUpdateCapability,
7 resolveVersionMismatch,
8 supportsDesktopAppUpdate,
9 supportsServerUpdateThreadContinuation,
10} from "~/versionSkew";
11import type { ServerUpdateOutcome, ServerUpdateTarget } from "../ServerUpdateAction";
12​
13export interface UpdateEverythingMachine {
14 readonly environmentId: EnvironmentId;
15 readonly label: string;
16 readonly serverConfig: {
17 readonly environment: ServerConfig["environment"];
18 readonly settings: Pick<ServerConfig["settings"], "continueThreadsAfterServerUpdate">;
19 } | null;
20 readonly connected: boolean;
21 readonly hostedByThisApp: boolean;
22 readonly canMaintain: boolean;
23 readonly updateState: ServerUpdateState;
25​
26export interface RestartingMachine {
27 readonly environmentId: EnvironmentId;
28 readonly continuesThreads: boolean;
30​
31export function collectRestartingMachines(
32 machines: ReadonlyArray<UpdateEverythingMachine>,
33 servers: ReadonlyArray<Pick<ServerUpdateTarget, "environmentId">>,
34 installsLocal: boolean,
35): RestartingMachine[] {
36 const updated = new Set(servers.map((server) => server.environmentId));
37 return machines.flatMap((machine) => {
38 const config = machine.serverConfig;
39 if (
40 config === null ||
41 !machine.connected ||
42 !(updated.has(machine.environmentId) || (installsLocal && machine.hostedByThisApp))
43 ) {
44 return [];
45 }
46 return [
47 {
48 environmentId: machine.environmentId,
49 continuesThreads:
50 config.environment.capabilities.threadRestartContinuation === true &&
51 config.settings.continueThreadsAfterServerUpdate === true,
52 },
53 ];
54 });
56​
57export interface SkippedMachine {
58 readonly environmentId: EnvironmentId;
59 readonly label: string;
60 readonly reason: string;
62​
63/**
64 * Two kinds are in neither list: servers already on the target, and servers this app hosts,
65 * which would relaunch the app mid-run and update with the app's own install anyway. A
66 * desktop-managed server follows its own app's update feed, so the channel rule does not apply
67 * to it.
68 */
69export function collectServerUpdateTargets(
70 machines: ReadonlyArray<UpdateEverythingMachine>,
71 targetVersion: string,
72): { readonly targets: ServerUpdateTarget[]; readonly skipped: SkippedMachine[] } {
73 const targets: ServerUpdateTarget[] = [];
74 const skipped: SkippedMachine[] = [];
75 for (const machine of machines) {
76 const config = machine.serverConfig;
77 if (machine.hostedByThisApp) continue;
78 if (
79 config !== null &&
80 resolveVersionMismatch(config.environment.serverVersion, targetVersion) === null
81 ) {
82 continue;
83 }
84 const skip = (reason: string) =>
85 skipped.push({ environmentId: machine.environmentId, label: machine.label, reason });
86 if (config === null || !machine.connected) {
87 skip("not connected");
88 continue;
89 }
90 if (!machine.canMaintain) {
91 skip("no permission");
92 continue;
93 }
94 if (machine.updateState.status === "running") {
95 skip("already updating");
96 continue;
97 }
98 const selfUpdate = resolveServerSelfUpdateCapability(config);
99 const desktopAppUpdate = supportsDesktopAppUpdate(config);
100 if (selfUpdate === null) {
101 skip("needs a manual update");
102 continue;
103 }
104 if (selfUpdate === "desktop-managed" && !desktopAppUpdate) {
105 skip("needs a newer desktop app");
106 continue;
107 }
108 const serverVersion = config.environment.serverVersion;
109 if (
110 selfUpdate !== "desktop-managed" &&
111 cliReleaseChannelOf(serverVersion) !== cliReleaseChannelOf(targetVersion)
112 ) {
113 skip(`on the ${cliReleaseChannelOf(serverVersion)} channel`);
114 continue;
115 }
116 targets.push({
117 environmentId: machine.environmentId,
118 serverLabel: machine.label,
119 selfUpdate,
120 installation: config.environment.capabilities.serverInstallation,
121 desktopAppUpdate,
122 threadContinuation: supportsServerUpdateThreadContinuation(config),
123 continueThreadsAfterServerUpdate: config.settings.continueThreadsAfterServerUpdate ?? false,
124 targetVersion,
125 });
126 }
127 return { targets, skipped };
129​
130export interface UpdateEverythingSteps<Providers, Servers> {
131 readonly downloadLocal?: () => Promise<boolean>;
132 readonly updateProviders: () => Promise<Providers>;
133 readonly updateServers: () => Promise<Servers>;
135​
136/**
137 * Providers finish before any server restarts, so no install is cut off. The caller installs this app afterwards when `localReady`, because
138 * the relaunch ends the run; a failed download skips only that install.
139 */
140export async function runUpdateEverything<Providers, Servers>(
141 steps: UpdateEverythingSteps<Providers, Servers>,
142): Promise<{
143 readonly localReady: boolean;
144 readonly providers: Providers;
145 readonly servers: Servers;
146}> {
147 const [localReady, remote] = await Promise.all([
148 steps.downloadLocal?.() ?? Promise.resolve(true),
149 steps
150 .updateProviders()
151 .then(async (providers) => ({ providers, servers: await steps.updateServers() })),
152 ]);
153 return { localReady, ...remote };
155​
156export type UpdateRunMachineStatus =
157 | "providers"
158 | "waiting"
159 | "downloading"
160 | "restarting"
161 | "done"
162 | "failed";
163​
164export interface UpdateRunMachine {
165 readonly environmentId: EnvironmentId;
166 readonly label: string;
167 readonly updatesProviders: boolean;
168 readonly server: ServerUpdateTarget | null;
169 readonly handedOffVersion: string | null;
170 readonly startedAt: number;
171 readonly result: "done" | "failed" | null;
172 readonly failure: string | null;
173 readonly providerFailure: string | null;
175​
176export interface UpdateEverythingRun {
177 readonly localVersion: string | null;
178 readonly phase: "providers" | "servers" | "countdown" | "installing";
179 readonly restartAt: number | null;
180 readonly machines: ReadonlyArray<UpdateRunMachine>;
182​
183export function resolveUpdateRunMachineStatus(
184 machine: UpdateRunMachine,
185 phase: UpdateEverythingRun["phase"],
186 serverState: ServerUpdateState,
187): UpdateRunMachineStatus {
188 if (machine.result !== null) return machine.result;
189 if (machine.handedOffVersion !== null) return "restarting";
190 if (phase === "providers" && machine.updatesProviders) return "providers";
191 if (machine.server !== null && serverState.status === "running") {
192 return serverState.stage === "resuming" ? "restarting" : "downloading";
193 }
194 return "waiting";
196​
197export function isServerUpdateHandedOff(state: ServerUpdateState): boolean {
198 return state.status === "running" && state.stage === "resuming";
200​
201export function closeFinishedUpdateRun(run: UpdateEverythingRun): UpdateEverythingRun | null {
202 return run.phase === "servers" &&
203 run.localVersion === null &&
204 run.machines.every((machine) => machine.result === "done")
205 ? null
206 : run;
208​
209const UPDATE_SLOW_AFTER_MS = 3 * 60 * 1000;
210​
211export function formatUpdateElapsed(ms: number): string {
212 const minutes = Math.floor(ms / 60_000);
213 if (minutes < 1) return "<1m";
214 if (minutes < 60) return `${minutes}m`;
215 return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
217​
218export interface UpdateRunMachineView {
219 readonly machine: UpdateRunMachine;
220 readonly status: UpdateRunMachineStatus;
222​
223export type UpdateRunLocalState =
224 | { readonly status: "downloading"; readonly percent: number | null }
225 | { readonly status: "waiting" }
226 | null;
227​
228export interface UpdateCapsuleView {
229 readonly tone: "default" | "slow" | "failed";
230 readonly label: string;
231 readonly slow?: { readonly status: string; readonly elapsed: string };
232 readonly action: "later" | "retry" | "dismiss" | null;
234​
235const isActive = (status: UpdateRunMachineStatus) => status !== "done" && status !== "failed";
236​
237export function describeUpdateCapsule(
238 run: UpdateEverythingRun,
239 machines: ReadonlyArray<UpdateRunMachineView>,
240 local: UpdateRunLocalState,
241 now: number,
242): UpdateCapsuleView {
243 if (run.phase === "countdown" && run.restartAt !== null) {
244 const seconds = Math.max(0, Math.ceil((run.restartAt - now) / 1000));
245 return { tone: "default", label: `Restart in ${seconds}s`, action: "later" };
246 }
247 if (run.phase === "installing") {
248 return { tone: "default", label: "Restarting…", action: null };
249 }
250 const active = machines.filter(({ status }) => isActive(status) && status !== "waiting");
251 const slowest = active.toSorted((a, b) => a.machine.startedAt - b.machine.startedAt)[0];
252 if (slowest && now - slowest.machine.startedAt >= UPDATE_SLOW_AFTER_MS) {
253 return {
254 tone: "slow",
255 label: slowest.machine.label,
256 slow: {
257 status: RUN_STATUS_LABELS[slowest.status],
258 elapsed: formatUpdateElapsed(now - slowest.machine.startedAt),
259 },
260 action: null,
261 };
262 }
263 const done = machines.filter(({ status }) => status === "done").length;
264 if (machines.some(({ status }) => isActive(status))) {
265 return { tone: "default", label: `${done} of ${machines.length} updated`, action: null };
266 }
267 if (local?.status === "downloading") {
268 return {
269 tone: "default",
270 label: `Downloading${local.percent === null ? "" : ` ${Math.floor(local.percent)}%`}`,
271 action: null,
272 };
273 }
274 const failed = machines.filter(({ status }) => status === "failed");
275 if (failed.length > 0) {
276 return {
277 tone: "failed",
278 label: failed.length === 1 ? `${failed[0]!.machine.label} failed` : `${failed.length} failed`,
279 action: failed.some(({ machine }) => machine.server !== null) ? "retry" : "dismiss",
280 };
281 }
282 return { tone: "default", label: `${done} of ${machines.length} updated`, action: null };
284​
285export const RUN_STATUS_LABELS: Record<UpdateRunMachineStatus, string> = {
286 providers: "updating providers",
287 waiting: "waiting",
288 downloading: "downloading",
289 restarting: "restarting",
290 done: "done",
291 failed: "failed",
292};
293​
294export interface UpdateEverythingResult {
295 readonly localVersion: string | null;
296 readonly updatedServers: number;
297 readonly updatedProviders: number;
298 readonly failures: ReadonlyArray<string>;
299 readonly restarting: ReadonlyArray<string>;
301​
302export function collectUpdateEverythingResult(input: {
303 readonly localVersion: string | null;
304 readonly localFailures: ReadonlyArray<string>;
305 readonly servers: ReadonlyArray<{
306 readonly label: string;
307 readonly outcome: ServerUpdateOutcome;
308 }>;
309 readonly providers: ReadonlyArray<
310 | { readonly status: "interrupted" | "updated" }
311 | { readonly status: "failed"; readonly line: string }
312 >;
313}): UpdateEverythingResult {
314 return {
315 localVersion: input.localVersion,
316 updatedServers: input.servers.filter(({ outcome }) => outcome.status === "updated").length,
317 updatedProviders: input.providers.filter((outcome) => outcome.status === "updated").length,
318 restarting: [],
319 failures: [
320 ...input.localFailures.map((failure) => `This app: ${failure}`),
321 ...input.servers.flatMap(({ label, outcome }) =>
322 outcome.status === "failed" ? [`${label}: ${outcome.message}`] : [],
323 ),
324 ...input.providers.flatMap((outcome) => (outcome.status === "failed" ? [outcome.line] : [])),
325 ],
326 };
328​
329export function getUpdateEverythingToastView(
330 result: UpdateEverythingResult,
331 appVersion: string,
332): {
333 readonly type: "success" | "error";
334 readonly title: string;
335 readonly description?: string;
336} | null {
337 const parts = [
338 result.localVersion !== null && result.localVersion === appVersion ? "this app" : null,
339 countLabel(result.updatedServers, "server"),
340 countLabel(result.updatedProviders, "provider"),
341 ].filter((part) => part !== null);
342 const restarting =
343 result.restarting.length === 0
344 ? []
345 : [
346 `${joinList(result.restarting)} ${result.restarting.length === 1 ? "is" : "are"} still restarting.`,
347 ];
348 if (result.failures.length === 0) {
349 if (parts.length === 0) return null;
350 return {
351 type: "success",
352 title: `Updated ${joinList(parts)}`,
353 ...(restarting.length === 0 ? {} : { description: restarting.join("\n") }),
354 };
355 }
356 return {
357 type: "error",
358 title: parts.length === 0 ? "Update failed" : `Updated ${joinList(parts)}`,
359 description: [...result.failures, ...restarting].join("\n"),
360 };
362​
363export interface UpdateEverythingPlan {
364 readonly localVersion: string | null;
365 readonly servers: ReadonlyArray<
366 Pick<ServerUpdateTarget, "environmentId" | "serverLabel" | "selfUpdate" | "targetVersion">
367 >;
368 readonly providerMachines: ReadonlyArray<{
369 readonly environmentId: EnvironmentId;
370 readonly label: string;
371 readonly providers: ReadonlyArray<string>;
372 }>;
374​
375function countLabel(count: number, noun: string): string | null {
376 return count === 0 ? null : `${count} ${noun}${count === 1 ? "" : "s"}`;
378​
379function joinList(parts: ReadonlyArray<string>): string {
380 if (parts.length <= 2) return parts.join(" and ");
381 return `${parts.slice(0, -1).join(", ")}, and ${parts.at(-1)}`;
383​
384export function describeUpdateEverything(plan: UpdateEverythingPlan): {
385 readonly summary: string;
386 readonly lines: ReadonlyArray<string>;
387} {
388 const providerCount = plan.providerMachines.reduce(
389 (count, machine) => count + machine.providers.length,
390 0,
391 );
392 const summary = `Update ${joinList(
393 [
394 plan.localVersion ? "this app" : null,
395 countLabel(plan.servers.length, "server"),
396 countLabel(providerCount, "provider"),
397 ].filter((part) => part !== null),
398 )}`;
399​
400 const machines = new Map<EnvironmentId, { label: string; items: string[] }>();
401 const itemsFor = (environmentId: EnvironmentId, label: string) => {
402 const existing = machines.get(environmentId);
403 if (existing) return existing.items;
404 const items: string[] = [];
405 machines.set(environmentId, { label, items });
406 return items;
407 };
408 for (const server of plan.servers) {
409 itemsFor(server.environmentId, server.serverLabel).push(
410 server.selfUpdate === "desktop-managed"
411 ? "desktop app update"
412 : `server to ${server.targetVersion}`,
413 );
414 }
415 for (const machine of plan.providerMachines) {
416 itemsFor(machine.environmentId, machine.label).push(...machine.providers);
417 }
418​
419 return {
420 summary,
421 lines: [
422 ...(plan.localVersion ? [`This app: ${plan.localVersion}, restarts last`] : []),
423 ...Array.from(machines.values(), ({ label, items }) => `${label}: ${items.join(", ")}`),
424 ],
425 };