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

useUpdateEverything.ts

305 lines12.1 KB

1import { msg, useMessages } from "gt-react";
2import { useAtomValue } from "@effect/atom-react";
3import { connectionErrorText } from "@t3tools/client-runtime/connection";
4import { PROVIDER_DISPLAY_NAMES } from "@t3tools/contracts";
5import { cliReleaseChannelOf, desktopUpdateChannelOf } from "@t3tools/shared/cliRelease";
6import * as AsyncResult from "effect/reactivity/AsyncResult";
7import { Atom } from "effect/reactivity";
8​
9import { APP_VERSION } from "~/branding";
10import { isDesktopLocalConnectionTarget } from "~/connection/desktopLocal";
11import { isElectron } from "~/env";
12import { useEnvironments } from "~/state/environments";
13import { environmentIdsKey } from "~/state/environmentAtomList";
14import { npmReleaseAtom } from "~/state/npmRelease";
15import { environmentUpdateStatesAtom, serverEnvironment } from "~/state/server";
16import { environmentSessionStatesAtom } from "~/state/session";
17import { useAtomCommand } from "~/state/use-atom-command";
18import { getProviderUpdateRunOutcome } from "../ProviderUpdateLaunchNotification.logic";
19import { useProviderUpdates } from "../ProviderUpdatesAction";
20import { canUpdateServer, type ServerUpdateOutcome, useServerUpdate } from "../ServerUpdateAction";
21import {
22 type ChannelSwitchRelease,
23 closeFinishedUpdateRun,
24 collectChannelSwitchTargets,
25 collectRestartingMachines,
26 collectServerUpdateTargets,
27 collectUpdateEverythingResult,
28 describeUpdateEverything,
29 resolveFleetTargetVersion,
30 runUpdateEverything,
31 type UpdateRunMachine,
32} from "./updateEverything.logic";
33import {
34 clearSavedUpdateEverythingResult,
35 saveUpdateEverythingResult,
36 setUpdateEverythingRun,
37 settleUpdateRunMachine,
38 showUpdateEverythingResult,
39 waitForServerUpdateHandoff,
40 waitForUpdateRestart,
41} from "./updateEverythingRun";
42​
43const UPDATE_RESTART_DELAY_MS = 5_000;
44​
45/** Servers this desktop app runs; they update with it. */
46export function isHostedByThisApp(
47 environment: ReturnType<typeof useEnvironments>["environments"][number],
48) {
49 return (
50 isElectron &&
51 (environment.entry.target._tag === "PrimaryConnectionTarget" ||
52 isDesktopLocalConnectionTarget(environment.entry.target))
53 );
55​
56export type ReportLocalUpdateError = (title: string, description: string) => void;
57​
58const noRegistryLookupAtom = Atom.make(AsyncResult.initial<null>());
59​
60/**
61 * `channelSwitch` makes the run move the fleet to that release's track instead of updating it.
62 * `lookUpNewest` asks the registry for the newest release while the confirm dialog is open, so
63 * servers get the build this app's download will resolve, not the one its last check found.
64 */
65export function useUpdateEverything(
66 localUpdateVersion: string | null,
67 channelSwitch?: ChannelSwitchRelease,
68 lookUpNewest = false,
69) {
70 const { environments } = useEnvironments();
71 const resolve = useMessages();
72 const environmentIds = environmentIdsKey(environments.map(({ environmentId }) => environmentId));
73 const sessionStates = useAtomValue(environmentSessionStatesAtom(environmentIds));
74 const updateStates = useAtomValue(environmentUpdateStatesAtom(environmentIds));
75 const machines = environments.map((environment, index) => ({
76 environmentId: environment.environmentId,
77 label: environment.label,
78 serverConfig: environment.serverConfig,
79 connected: environment.connection.phase === "connected",
80 connectionError: connectionErrorText(environment.connection, resolve),
81 turnedOff: !environment.entry.enabled,
82 hostedByThisApp: isHostedByThisApp(environment),
83 canMaintain: canUpdateServer(sessionStates[index]!),
84 updateState: updateStates[index]!,
85 }));
86 // Servers follow the registry only when this app updates in the same run, so they never move
87 // ahead of it. Preview builds have no registry track. A managed fleet can install from an update
88 // mirror that trails the registry, so it keeps the version this app found.
89 const registry = useAtomValue(
90 lookUpNewest &&
91 localUpdateVersion !== null &&
92 cliReleaseChannelOf(APP_VERSION) !== "preview" &&
93 machines.every((machine) => machine.serverConfig?.managedPolicy === undefined)
94 ? npmReleaseAtom(desktopUpdateChannelOf(APP_VERSION))
95 : noRegistryLookupAtom,
96 );
97 const targetVersion = resolveFleetTargetVersion(
98 localUpdateVersion ?? APP_VERSION,
99 AsyncResult.isSuccess(registry) ? (registry.value?.version ?? null) : null,
100 );
101 const { targets: servers, skipped } = channelSwitch
102 ? collectChannelSwitchTargets(machines, channelSwitch, resolve)
103 : collectServerUpdateTargets(machines, targetVersion, resolve);
104 // Track-only hosts save a setting and restart nothing, so they are neither listed nor counted.
105 const moving = servers.filter((server) => server.trackOnly !== true);
106 const restarts = collectRestartingMachines(machines, moving, localUpdateVersion !== null);
107 const providerUpdates = useProviderUpdates();
108 // A track switch moves app and servers only; provider updates stay a separate choice.
109 const providers = channelSwitch ? { machines: [], updateAll: async () => [] } : providerUpdates;
110 const updateServer = useServerUpdate();
111 const stageServerUpdate = useAtomCommand(serverEnvironment.stageServerUpdate, {
112 reportFailure: false,
113 });
114​
115 const view = describeUpdateEverything(
116 {
117 localVersion: localUpdateVersion,
118 localMachines: machines.filter((machine) => machine.hostedByThisApp),
119 servers: moving,
120 skipped,
121 providerMachines: providers.machines.map((machine) => ({
122 environmentId: machine.environmentId,
123 label: machine.label,
124 providers: machine.candidates.map(
125 (candidate) => PROVIDER_DISPLAY_NAMES[candidate.driver] ?? candidate.driver,
126 ),
127 })),
128 },
129 resolve,
130 );
131​
132 return {
133 hasUpdates: servers.length > 0 || providers.machines.length > 0,
134 machines,
135 ...view,
136 restarts,
137 run: async ({
138 downloadLocal,
139 installLocal,
140 }: {
141 downloadLocal?: (reportError: ReportLocalUpdateError) => Promise<boolean>;
142 installLocal?: (reportError: ReportLocalUpdateError) => Promise<boolean>;
143 }) => {
144 const localFailures: Array<string> = [];
145 const reportLocalError: ReportLocalUpdateError = (title, description) => {
146 localFailures.push(`${title}: ${description}`);
147 };
148 const startedAt = Date.now();
149 const machinesById = new Map<UpdateRunMachine["environmentId"], UpdateRunMachine>();
150 for (const machine of providers.machines) {
151 machinesById.set(machine.environmentId, {
152 environmentId: machine.environmentId,
153 label: machine.label,
154 updatesProviders: true,
155 server: null,
156 handedOffVersion: null,
157 startedAt,
158 result: null,
159 failure: null,
160 providerFailure: null,
161 });
162 }
163 for (const server of servers) {
164 const existing = machinesById.get(server.environmentId);
165 machinesById.set(server.environmentId, {
166 environmentId: server.environmentId,
167 label: server.serverLabel,
168 updatesProviders: existing?.updatesProviders ?? false,
169 server,
170 handedOffVersion: null,
171 startedAt,
172 result: null,
173 failure: null,
174 providerFailure: null,
175 });
176 }
177 const localVersion = installLocal ? localUpdateVersion : null;
178 setUpdateEverythingRun(() => ({
179 ...(channelSwitch ? { trackSwitch: true } : {}),
180 localVersion,
181 phase: "providers",
182 restartAt: null,
183 machines: Array.from(machinesById.values()),
184 }));
185 const providerFailures = new Map<UpdateRunMachine["environmentId"], string>();
186 const finishedServers: Array<{ label: string; outcome: ServerUpdateOutcome }> = [];
187 try {
188 const outcome = await runUpdateEverything({
189 ...(downloadLocal ? { downloadLocal: () => downloadLocal(reportLocalError) } : {}),
190 updateProviders: async () => {
191 const runs = await providers.updateAll({ quiet: true });
192 const outcomes = runs.map((run) => {
193 const runOutcome = getProviderUpdateRunOutcome(run);
194 if (runOutcome.status !== "updated") {
195 providerFailures.set(
196 run.environmentId,
197 runOutcome.status === "failed"
198 ? runOutcome.line
199 : resolve(msg("Provider update interrupted")),
200 );
201 }
202 return runOutcome;
203 });
204 for (const machine of machinesById.values()) {
205 if (machine.server === null) {
206 settleUpdateRunMachine(
207 machine.environmentId,
208 providerFailures.get(machine.environmentId) ?? null,
209 );
210 }
211 }
212 const serversStartedAt = Date.now();
213 setUpdateEverythingRun(
214 (run) =>
215 run && {
216 ...run,
217 phase: "servers",
218 machines: run.machines.map((machine) =>
219 machine.server === null ? machine : { ...machine, startedAt: serversStartedAt },
220 ),
221 },
222 );
223 return outcomes;
224 },
225 ...(providers.machines.length > 0
226 ? {
227 stageServers: () =>
228 new Map(
229 servers
230 .filter(
231 (server) =>
232 machines.find((machine) => machine.environmentId === server.environmentId)
233 ?.serverConfig?.environment.capabilities.serverUpdateStaging === true,
234 )
235 .map((server) => [
236 server.environmentId,
237 stageServerUpdate({
238 environmentId: server.environmentId,
239 input: { targetVersion: server.targetVersion, stageOnly: true },
240 }),
241 ]),
242 ),
243 }
244 : {}),
245 updateServers: async (staged) => {
246 const runs = servers.map(async (server) => {
247 await staged.get(server.environmentId);
248 const serverOutcome = await updateServer(server, { quiet: true });
249 settleUpdateRunMachine(
250 server.environmentId,
251 serverOutcome.status === "failed"
252 ? serverOutcome.message
253 : (providerFailures.get(server.environmentId) ?? null),
254 {
255 serverUpdated: serverOutcome.status !== "failed",
256 providerFailure: providerFailures.get(server.environmentId) ?? null,
257 },
258 );
259 const finished = { label: server.serverLabel, outcome: serverOutcome };
260 finishedServers.push(finished);
261 return finished;
262 });
263 await Promise.all(
264 servers.map((server, index) =>
265 waitForServerUpdateHandoff(server.environmentId, runs[index]!),
266 ),
267 );
268 return runs;
269 },
270 });
271 const result = (finished: ReadonlyArray<{ label: string; outcome: ServerUpdateOutcome }>) =>
272 collectUpdateEverythingResult({
273 localVersion: null,
274 localFailures,
275 servers: finished,
276 providers: outcome.providers,
277 });
278 if (outcome.localReady && installLocal) {
279 if (await waitForUpdateRestart(UPDATE_RESTART_DELAY_MS)) {
280 setUpdateEverythingRun(
281 (run) => run && { ...run, phase: "installing", restartAt: null },
282 );
283 saveUpdateEverythingResult({ ...result(finishedServers), localVersion });
284 if (await installLocal(reportLocalError)) return;
285 clearSavedUpdateEverythingResult();
286 }
287 }
288 setUpdateEverythingRun(
289 (run) =>
290 run &&
291 closeFinishedUpdateRun({
292 ...run,
293 phase: "servers",
294 restartAt: null,
295 localVersion: null,
296 }),
297 );
298 showUpdateEverythingResult(result(await Promise.all(outcome.servers)));
299 } catch (error) {
300 setUpdateEverythingRun(() => null);
301 throw error;
302 }
303 },
304 };