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

useUpdateEverything.ts

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