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