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