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

useUpdateEverything.ts

268 lines10.5 KB

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