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

updateEverything.logic.ts

420 lines14.0 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/** Skip current and app-hosted servers; the latter update with the app and would relaunch mid-run.
64 * Desktop-managed servers use their own feed. */
65export function collectServerUpdateTargets(
66 machines: ReadonlyArray<UpdateEverythingMachine>,
67 targetVersion: string,
68): { readonly targets: ServerUpdateTarget[]; readonly skipped: SkippedMachine[] } {
69 const targets: ServerUpdateTarget[] = [];
70 const skipped: SkippedMachine[] = [];
71 for (const machine of machines) {
72 const config = machine.serverConfig;
73 if (machine.hostedByThisApp) continue;
74 if (
75 config !== null &&
76 resolveVersionMismatch(config.environment.serverVersion, targetVersion) === null
77 ) {
78 continue;
79 }
80 const skip = (reason: string) =>
81 skipped.push({ environmentId: machine.environmentId, label: machine.label, reason });
82 if (config === null || !machine.connected) {
83 skip("not connected");
84 continue;
85 }
86 if (!machine.canMaintain) {
87 skip("no permission");
88 continue;
89 }
90 if (machine.updateState.status === "running") {
91 skip("already updating");
92 continue;
93 }
94 const selfUpdate = resolveServerSelfUpdateCapability(config);
95 const desktopAppUpdate = supportsDesktopAppUpdate(config);
96 if (selfUpdate === null) {
97 skip("needs a manual update");
98 continue;
99 }
100 if (selfUpdate === "desktop-managed" && !desktopAppUpdate) {
101 skip("needs a newer desktop app");
102 continue;
103 }
104 const serverVersion = config.environment.serverVersion;
105 if (
106 selfUpdate !== "desktop-managed" &&
107 cliReleaseChannelOf(serverVersion) !== cliReleaseChannelOf(targetVersion)
108 ) {
109 skip(`on the ${cliReleaseChannelOf(serverVersion)} channel`);
110 continue;
111 }
112 targets.push({
113 environmentId: machine.environmentId,
114 serverLabel: machine.label,
115 selfUpdate,
116 installation: config.environment.capabilities.serverInstallation,
117 desktopAppUpdate,
118 threadContinuation: supportsServerUpdateThreadContinuation(config),
119 continueThreadsAfterServerUpdate: config.settings.continueThreadsAfterServerUpdate ?? false,
120 targetVersion,
121 });
122 }
123 return { targets, skipped };
125​
126export interface UpdateEverythingSteps<Providers, Servers> {
127 readonly downloadLocal?: () => Promise<boolean>;
128 readonly updateProviders: () => Promise<Providers>;
129 readonly updateServers: () => Promise<Servers>;
131​
132/** Finish provider installs before server restarts. Install this app last when localReady; failed
133 * downloads skip only that install. */
134export async function runUpdateEverything<Providers, Servers>(
135 steps: UpdateEverythingSteps<Providers, Servers>,
136): Promise<{
137 readonly localReady: boolean;
138 readonly providers: Providers;
139 readonly servers: Servers;
140}> {
141 const [localReady, remote] = await Promise.all([
142 steps.downloadLocal?.() ?? Promise.resolve(true),
143 steps
144 .updateProviders()
145 .then(async (providers) => ({ providers, servers: await steps.updateServers() })),
146 ]);
147 return { localReady, ...remote };
149​
150export type UpdateRunMachineStatus =
151 | "providers"
152 | "waiting"
153 | "downloading"
154 | "restarting"
155 | "done"
156 | "failed";
157​
158export interface UpdateRunMachine {
159 readonly environmentId: EnvironmentId;
160 readonly label: string;
161 readonly updatesProviders: boolean;
162 readonly server: ServerUpdateTarget | null;
163 readonly handedOffVersion: string | null;
164 readonly startedAt: number;
165 readonly result: "done" | "failed" | null;
166 readonly failure: string | null;
167 readonly providerFailure: string | null;
169​
170export interface UpdateEverythingRun {
171 readonly localVersion: string | null;
172 readonly phase: "providers" | "servers" | "countdown" | "installing";
173 readonly restartAt: number | null;
174 readonly machines: ReadonlyArray<UpdateRunMachine>;
176​
177export function resolveUpdateRunMachineStatus(
178 machine: UpdateRunMachine,
179 phase: UpdateEverythingRun["phase"],
180 serverState: ServerUpdateState,
181): UpdateRunMachineStatus {
182 if (machine.result !== null) return machine.result;
183 if (machine.handedOffVersion !== null) return "restarting";
184 if (phase === "providers" && machine.updatesProviders) return "providers";
185 if (machine.server !== null && serverState.status === "running") {
186 return serverState.stage === "resuming" ? "restarting" : "downloading";
187 }
188 return "waiting";
190​
191export function isServerUpdateHandedOff(state: ServerUpdateState): boolean {
192 return state.status === "running" && state.stage === "resuming";
194​
195export function closeFinishedUpdateRun(run: UpdateEverythingRun): UpdateEverythingRun | null {
196 return run.phase === "servers" &&
197 run.localVersion === null &&
198 run.machines.every((machine) => machine.result === "done")
199 ? null
200 : run;
202​
203const UPDATE_SLOW_AFTER_MS = 3 * 60 * 1000;
204​
205export function formatUpdateElapsed(ms: number): string {
206 const minutes = Math.floor(ms / 60_000);
207 if (minutes < 1) return "<1m";
208 if (minutes < 60) return `${minutes}m`;
209 return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
211​
212export interface UpdateRunMachineView {
213 readonly machine: UpdateRunMachine;
214 readonly status: UpdateRunMachineStatus;
216​
217export type UpdateRunLocalState =
218 | { readonly status: "downloading"; readonly percent: number | null }
219 | { readonly status: "waiting" }
220 | null;
221​
222export interface UpdateCapsuleView {
223 readonly tone: "default" | "slow" | "failed";
224 readonly label: string;
225 readonly slow?: { readonly status: string; readonly elapsed: string };
226 readonly action: "later" | "retry" | "dismiss" | null;
228​
229const isActive = (status: UpdateRunMachineStatus) => status !== "done" && status !== "failed";
230​
231export function describeUpdateCapsule(
232 run: UpdateEverythingRun,
233 machines: ReadonlyArray<UpdateRunMachineView>,
234 local: UpdateRunLocalState,
235 now: number,
236): UpdateCapsuleView {
237 if (run.phase === "countdown" && run.restartAt !== null) {
238 const seconds = Math.max(0, Math.ceil((run.restartAt - now) / 1000));
239 return { tone: "default", label: `Restart in ${seconds}s`, action: "later" };
240 }
241 if (run.phase === "installing") {
242 return { tone: "default", label: "Restarting…", action: null };
243 }
244 const active = machines.filter(({ status }) => isActive(status) && status !== "waiting");
245 const slowest = active.toSorted((a, b) => a.machine.startedAt - b.machine.startedAt)[0];
246 if (slowest && now - slowest.machine.startedAt >= UPDATE_SLOW_AFTER_MS) {
247 return {
248 tone: "slow",
249 label: slowest.machine.label,
250 slow: {
251 status: RUN_STATUS_LABELS[slowest.status],
252 elapsed: formatUpdateElapsed(now - slowest.machine.startedAt),
253 },
254 action: null,
255 };
256 }
257 const done = machines.filter(({ status }) => status === "done").length;
258 if (machines.some(({ status }) => isActive(status))) {
259 return { tone: "default", label: `${done} of ${machines.length} updated`, action: null };
260 }
261 if (local?.status === "downloading") {
262 return {
263 tone: "default",
264 label: `Downloading${local.percent === null ? "" : ` ${Math.floor(local.percent)}%`}`,
265 action: null,
266 };
267 }
268 const failed = machines.filter(({ status }) => status === "failed");
269 if (failed.length > 0) {
270 return {
271 tone: "failed",
272 label: failed.length === 1 ? `${failed[0]!.machine.label} failed` : `${failed.length} failed`,
273 action: failed.some(({ machine }) => machine.server !== null) ? "retry" : "dismiss",
274 };
275 }
276 return { tone: "default", label: `${done} of ${machines.length} updated`, action: null };
278​
279export const RUN_STATUS_LABELS: Record<UpdateRunMachineStatus, string> = {
280 providers: "updating providers",
281 waiting: "waiting",
282 downloading: "downloading",
283 restarting: "restarting",
284 done: "done",
285 failed: "failed",
286};
287​
288export interface UpdateEverythingResult {
289 readonly localVersion: string | null;
290 readonly updatedServers: number;
291 readonly updatedProviders: number;
292 readonly failures: ReadonlyArray<string>;
293 readonly restarting: ReadonlyArray<string>;
295​
296export function collectUpdateEverythingResult(input: {
297 readonly localVersion: string | null;
298 readonly localFailures: ReadonlyArray<string>;
299 readonly servers: ReadonlyArray<{
300 readonly label: string;
301 readonly outcome: ServerUpdateOutcome;
302 }>;
303 readonly providers: ReadonlyArray<
304 | { readonly status: "interrupted" | "updated" }
305 | { readonly status: "failed"; readonly line: string }
306 >;
307}): UpdateEverythingResult {
308 return {
309 localVersion: input.localVersion,
310 updatedServers: input.servers.filter(({ outcome }) => outcome.status === "updated").length,
311 updatedProviders: input.providers.filter((outcome) => outcome.status === "updated").length,
312 restarting: [],
313 failures: [
314 ...input.localFailures.map((failure) => `This app: ${failure}`),
315 ...input.servers.flatMap(({ label, outcome }) =>
316 outcome.status === "failed" ? [`${label}: ${outcome.message}`] : [],
317 ),
318 ...input.providers.flatMap((outcome) => (outcome.status === "failed" ? [outcome.line] : [])),
319 ],
320 };
322​
323export function getUpdateEverythingToastView(
324 result: UpdateEverythingResult,
325 appVersion: string,
326): {
327 readonly type: "success" | "error";
328 readonly title: string;
329 readonly description?: string;
330} | null {
331 const parts = [
332 result.localVersion !== null && result.localVersion === appVersion ? "this app" : null,
333 countLabel(result.updatedServers, "server"),
334 countLabel(result.updatedProviders, "provider"),
335 ].filter((part) => part !== null);
336 const restarting =
337 result.restarting.length === 0
338 ? []
339 : [
340 `${joinList(result.restarting)} ${result.restarting.length === 1 ? "is" : "are"} still restarting.`,
341 ];
342 if (result.failures.length === 0) {
343 if (parts.length === 0) return null;
344 return {
345 type: "success",
346 title: `Updated ${joinList(parts)}`,
347 ...(restarting.length === 0 ? {} : { description: restarting.join("\n") }),
348 };
349 }
350 return {
351 type: "error",
352 title: parts.length === 0 ? "Update failed" : `Updated ${joinList(parts)}`,
353 description: [...result.failures, ...restarting].join("\n"),
354 };
356​
357export interface UpdateEverythingPlan {
358 readonly localVersion: string | null;
359 readonly servers: ReadonlyArray<
360 Pick<ServerUpdateTarget, "environmentId" | "serverLabel" | "selfUpdate" | "targetVersion">
361 >;
362 readonly providerMachines: ReadonlyArray<{
363 readonly environmentId: EnvironmentId;
364 readonly label: string;
365 readonly providers: ReadonlyArray<string>;
366 }>;
368​
369function countLabel(count: number, noun: string): string | null {
370 return count === 0 ? null : `${count} ${noun}${count === 1 ? "" : "s"}`;
372​
373function joinList(parts: ReadonlyArray<string>): string {
374 if (parts.length <= 2) return parts.join(" and ");
375 return `${parts.slice(0, -1).join(", ")}, and ${parts.at(-1)}`;
377​
378export function describeUpdateEverything(plan: UpdateEverythingPlan): {
379 readonly summary: string;
380 readonly lines: ReadonlyArray<string>;
381} {
382 const providerCount = plan.providerMachines.reduce(
383 (count, machine) => count + machine.providers.length,
384 0,
385 );
386 const summary = `Update ${joinList(
387 [
388 plan.localVersion ? "this app" : null,
389 countLabel(plan.servers.length, "server"),
390 countLabel(providerCount, "provider"),
391 ].filter((part) => part !== null),
392 )}`;
393​
394 const machines = new Map<EnvironmentId, { label: string; items: string[] }>();
395 const itemsFor = (environmentId: EnvironmentId, label: string) => {
396 const existing = machines.get(environmentId);
397 if (existing) return existing.items;
398 const items: string[] = [];
399 machines.set(environmentId, { label, items });
400 return items;
401 };
402 for (const server of plan.servers) {
403 itemsFor(server.environmentId, server.serverLabel).push(
404 server.selfUpdate === "desktop-managed"
405 ? "desktop app update"
406 : `server to ${server.targetVersion}`,
407 );
408 }
409 for (const machine of plan.providerMachines) {
410 itemsFor(machine.environmentId, machine.label).push(...machine.providers);
411 }
412​
413 return {
414 summary,
415 lines: [
416 ...(plan.localVersion ? [`This app: ${plan.localVersion}, restarts last`] : []),
417 ...Array.from(machines.values(), ({ label, items }) => `${label}: ${items.join(", ")}`),
418 ],
419 };