Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import { PROVIDER_DISPLAY_NAMES } from "@t3tools/contracts";
3
4import { APP_VERSION } from "~/branding";
5import { isDesktopLocalConnectionTarget } from "~/connection/desktopLocal";
6import { isElectron } from "~/env";
7import { useEnvironments } from "~/state/environments";
8import { environmentIdsKey } from "~/state/environmentAtomList";
9import { environmentUpdateStatesAtom } from "~/state/server";
10import { environmentSessionStatesAtom } from "~/state/session";
11import { getProviderUpdateRunOutcome } from "../ProviderUpdateLaunchNotification.logic";
12import { useProviderUpdates } from "../ProviderUpdatesAction";
13import { canUpdateServer, type ServerUpdateOutcome, useServerUpdate } from "../ServerUpdateAction";
14import {
15 type ChannelSwitchRelease,
16 closeFinishedUpdateRun,
17 collectChannelSwitchTargets,
18 collectRestartingMachines,
19 collectServerUpdateTargets,
20 collectUpdateEverythingResult,
21 describeUpdateEverything,
22 runUpdateEverything,
23 type UpdateRunMachine,
24} from "./updateEverything.logic";
25import {
26 clearSavedUpdateEverythingResult,
27 saveUpdateEverythingResult,
28 setUpdateEverythingRun,
29 settleUpdateRunMachine,
30 showUpdateEverythingResult,
31 waitForServerUpdateHandoff,
32 waitForUpdateRestart,
33} from "./updateEverythingRun";
34
35const UPDATE_RESTART_DELAY_MS = 5_000;
36
37/** Servers this desktop app runs; they update with it. */
38export function isHostedByThisApp(
39 environment: ReturnType<typeof useEnvironments>["environments"][number],
40) {
41 return (
42 isElectron &&
43 (environment.entry.target._tag === "PrimaryConnectionTarget" ||
44 isDesktopLocalConnectionTarget(environment.entry.target))
45 );
46}
47
48export type ReportLocalUpdateError = (title: string, description: string) => void;
49
50/** `channelSwitch` makes the run move the fleet to that release's track instead of updating it. */
51export function useUpdateEverything(
52 localUpdateVersion: string | null,
53 channelSwitch?: ChannelSwitchRelease,
54) {
55 const targetVersion = localUpdateVersion ?? APP_VERSION;
56 const { environments } = useEnvironments();
57 const environmentIds = environmentIdsKey(environments.map(({ environmentId }) => environmentId));
58 const sessionStates = useAtomValue(environmentSessionStatesAtom(environmentIds));
59 const updateStates = useAtomValue(environmentUpdateStatesAtom(environmentIds));
60 const machines = environments.map((environment, index) => ({
61 environmentId: environment.environmentId,
62 label: environment.label,
63 serverConfig: environment.serverConfig,
64 connected: environment.connection.phase === "connected",
65 hostedByThisApp: isHostedByThisApp(environment),
66 canMaintain: canUpdateServer(sessionStates[index]!),
67 updateState: updateStates[index]!,
68 }));
69 const { targets: servers, skipped } = channelSwitch
70 ? collectChannelSwitchTargets(machines, channelSwitch)
71 : collectServerUpdateTargets(machines, targetVersion);
72 // Track-only hosts save a setting and restart nothing, so they are neither listed nor counted.
73 const moving = servers.filter((server) => server.trackOnly !== true);
74 const restarts = collectRestartingMachines(machines, moving, localUpdateVersion !== null);
75 const providerUpdates = useProviderUpdates();
76 // A track switch moves app and servers only; provider updates stay a separate choice.
77 const providers = channelSwitch ? { machines: [], updateAll: async () => [] } : providerUpdates;
78 const updateServer = useServerUpdate();
79
80 const view = describeUpdateEverything({
81 localVersion: localUpdateVersion,
82 localMachines: machines.filter((machine) => machine.hostedByThisApp),
83 servers: moving,
84 skipped,
85 providerMachines: providers.machines.map((machine) => ({
86 environmentId: machine.environmentId,
87 label: machine.label,
88 providers: machine.candidates.map(
89 (candidate) => PROVIDER_DISPLAY_NAMES[candidate.driver] ?? candidate.driver,
90 ),
91 })),
92 });
93
94 return {
95 hasUpdates: servers.length > 0 || providers.machines.length > 0,
96 ...view,
97 restarts,
98 run: async ({
99 downloadLocal,
100 installLocal,
101 }: {
102 downloadLocal?: (reportError: ReportLocalUpdateError) => Promise<boolean>;
103 installLocal?: (reportError: ReportLocalUpdateError) => Promise<boolean>;
104 }) => {
105 const localFailures: Array<string> = [];
106 const reportLocalError: ReportLocalUpdateError = (title, description) => {
107 localFailures.push(`${title}: ${description}`);
108 };
109 const startedAt = Date.now();
110 const machinesById = new Map<UpdateRunMachine["environmentId"], UpdateRunMachine>();
111 for (const machine of providers.machines) {
112 machinesById.set(machine.environmentId, {
113 environmentId: machine.environmentId,
114 label: machine.label,
115 updatesProviders: true,
116 server: null,
117 handedOffVersion: null,
118 startedAt,
119 result: null,
120 failure: null,
121 providerFailure: null,
122 });
123 }
124 for (const server of servers) {
125 const existing = machinesById.get(server.environmentId);
126 machinesById.set(server.environmentId, {
127 environmentId: server.environmentId,
128 label: server.serverLabel,
129 updatesProviders: existing?.updatesProviders ?? false,
130 server,
131 handedOffVersion: null,
132 startedAt,
133 result: null,
134 failure: null,
135 providerFailure: null,
136 });
137 }
138 const localVersion = installLocal ? localUpdateVersion : null;
139 setUpdateEverythingRun(() => ({
140 ...(channelSwitch ? { trackSwitch: true } : {}),
141 localVersion,
142 phase: "providers",
143 restartAt: null,
144 machines: Array.from(machinesById.values()),
145 }));
146 const providerFailures = new Map<UpdateRunMachine["environmentId"], string>();
147 const finishedServers: Array<{ label: string; outcome: ServerUpdateOutcome }> = [];
148 try {
149 const outcome = await runUpdateEverything({
150 ...(downloadLocal ? { downloadLocal: () => downloadLocal(reportLocalError) } : {}),
151 updateProviders: async () => {
152 const runs = await providers.updateAll({ quiet: true });
153 const outcomes = runs.map((run) => {
154 const runOutcome = getProviderUpdateRunOutcome(run);
155 if (runOutcome.status !== "updated") {
156 providerFailures.set(
157 run.environmentId,
158 runOutcome.status === "failed" ? runOutcome.line : "Provider update interrupted",
159 );
160 }
161 return runOutcome;
162 });
163 for (const machine of machinesById.values()) {
164 if (machine.server === null) {
165 settleUpdateRunMachine(
166 machine.environmentId,
167 providerFailures.get(machine.environmentId) ?? null,
168 );
169 }
170 }
171 const serversStartedAt = Date.now();
172 setUpdateEverythingRun(
173 (run) =>
174 run && {
175 ...run,
176 phase: "servers",
177 machines: run.machines.map((machine) =>
178 machine.server === null ? machine : { ...machine, startedAt: serversStartedAt },
179 ),
180 },
181 );
182 return outcomes;
183 },
184 updateServers: async () => {
185 const runs = servers.map(async (server) => {
186 const serverOutcome = await updateServer(server, { quiet: true });
187 settleUpdateRunMachine(
188 server.environmentId,
189 serverOutcome.status === "failed"
190 ? serverOutcome.message
191 : (providerFailures.get(server.environmentId) ?? null),
192 {
193 serverUpdated: serverOutcome.status !== "failed",
194 providerFailure: providerFailures.get(server.environmentId) ?? null,
195 },
196 );
197 const finished = { label: server.serverLabel, outcome: serverOutcome };
198 finishedServers.push(finished);
199 return finished;
200 });
201 await Promise.all(
202 servers.map((server, index) =>
203 waitForServerUpdateHandoff(server.environmentId, runs[index]!),
204 ),
205 );
206 return runs;
207 },
208 });
209 const result = (finished: ReadonlyArray<{ label: string; outcome: ServerUpdateOutcome }>) =>
210 collectUpdateEverythingResult({
211 localVersion: null,
212 localFailures,
213 servers: finished,
214 providers: outcome.providers,
215 });
216 if (outcome.localReady && installLocal) {
217 if (await waitForUpdateRestart(UPDATE_RESTART_DELAY_MS)) {
218 setUpdateEverythingRun(
219 (run) => run && { ...run, phase: "installing", restartAt: null },
220 );
221 saveUpdateEverythingResult({ ...result(finishedServers), localVersion });
222 if (await installLocal(reportLocalError)) return;
223 clearSavedUpdateEverythingResult();
224 }
225 }
226 setUpdateEverythingRun(
227 (run) =>
228 run &&
229 closeFinishedUpdateRun({
230 ...run,
231 phase: "servers",
232 restartAt: null,
233 localVersion: null,
234 }),
235 );
236 showUpdateEverythingResult(result(await Promise.all(outcome.servers)));
237 } catch (error) {
238 setUpdateEverythingRun(() => null);
239 throw error;
240 }
241 },
242 };
243}