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

useUpdateEverything.ts

244 lines9.4 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 { 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 closeFinishedUpdateRun,
17 collectRestartingMachines,
18 collectServerUpdateTargets,
19 collectUpdateEverythingResult,
20 describeUpdateEverything,
21 runUpdateEverything,
22 type SkippedMachine,
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​
37export type ReportLocalUpdateError = (title: string, description: string) => void;
38​
39export function useUpdateEverything(localUpdateVersion: string | null) {
40 const targetVersion = localUpdateVersion ?? APP_VERSION;
41 const { environments } = useEnvironments();
42 const environmentIds = environmentIdsKey(environments.map(({ environmentId }) => environmentId));
43 const sessionStates = useAtomValue(environmentSessionStatesAtom(environmentIds));
44 const updateStates = useAtomValue(environmentUpdateStatesAtom(environmentIds));
45 const machines = environments.map((environment, index) => ({
46 environmentId: environment.environmentId,
47 label: environment.label,
48 serverConfig: environment.serverConfig,
49 connected: environment.connection.phase === "connected",
50 hostedByThisApp:
51 isElectron &&
52 (environment.entry.target._tag === "PrimaryConnectionTarget" ||
53 isDesktopLocalConnectionTarget(environment.entry.target)),
54 canMaintain: canUpdateServer(sessionStates[index]!),
55 updateState: updateStates[index]!,
56 }));
57 const { targets: behindServers, skipped: unreachable } = collectServerUpdateTargets(
58 machines,
59 targetVersion,
60 );
61 // A desktop-managed server installs from its own app's update feed, so only
62 // servers that download t3 from npm wait for npm to publish the version.
63 const needsNpm = behindServers.some((server) => server.selfUpdate !== "desktop-managed");
64 const published = useNpmReleasePublished(needsNpm ? targetVersion : null);
65 const servers = published
66 ? behindServers
67 : behindServers.filter((server) => server.selfUpdate === "desktop-managed");
68 const skipped: ReadonlyArray<SkippedMachine> = [
69 ...unreachable,
70 ...behindServers
71 .filter((server) => !servers.includes(server))
72 .map((server) => ({
73 environmentId: server.environmentId,
74 label: server.serverLabel,
75 reason: `t3@${targetVersion} is not on npm yet`,
76 })),
77 ];
78 const restarts = collectRestartingMachines(machines, servers, localUpdateVersion !== null);
79 const providers = useProviderUpdates();
80 const updateServer = useServerUpdate();
81​
82 const { summary, lines } = describeUpdateEverything({
83 localVersion: localUpdateVersion,
84 servers,
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 summary,
97 lines,
98 restarts,
99 skipped,
100 run: async ({
101 downloadLocal,
102 installLocal,
103 }: {
104 downloadLocal?: (reportError: ReportLocalUpdateError) => Promise<boolean>;
105 installLocal?: (reportError: ReportLocalUpdateError) => Promise<boolean>;
106 }) => {
107 const localFailures: Array<string> = [];
108 const reportLocalError: ReportLocalUpdateError = (title, description) => {
109 localFailures.push(`${title}: ${description}`);
110 };
111 const startedAt = Date.now();
112 const machinesById = new Map<UpdateRunMachine["environmentId"], UpdateRunMachine>();
113 for (const machine of providers.machines) {
114 machinesById.set(machine.environmentId, {
115 environmentId: machine.environmentId,
116 label: machine.label,
117 updatesProviders: true,
118 server: null,
119 handedOffVersion: null,
120 startedAt,
121 result: null,
122 failure: null,
123 providerFailure: null,
124 });
125 }
126 for (const server of servers) {
127 const existing = machinesById.get(server.environmentId);
128 machinesById.set(server.environmentId, {
129 environmentId: server.environmentId,
130 label: server.serverLabel,
131 updatesProviders: existing?.updatesProviders ?? false,
132 server,
133 handedOffVersion: null,
134 startedAt,
135 result: null,
136 failure: null,
137 providerFailure: null,
138 });
139 }
140 const localVersion = installLocal ? localUpdateVersion : null;
141 setUpdateEverythingRun(() => ({
142 localVersion,
143 phase: "providers",
144 restartAt: null,
145 machines: Array.from(machinesById.values()),
146 }));
147 const providerFailures = new Map<UpdateRunMachine["environmentId"], string>();
148 const finishedServers: Array<{ label: string; outcome: ServerUpdateOutcome }> = [];
149 try {
150 const outcome = await runUpdateEverything({
151 ...(downloadLocal ? { downloadLocal: () => downloadLocal(reportLocalError) } : {}),
152 updateProviders: async () => {
153 const runs = await providers.updateAll({ quiet: true });
154 const outcomes = runs.map((run) => {
155 const runOutcome = getProviderUpdateRunOutcome(run);
156 if (runOutcome.status !== "updated") {
157 providerFailures.set(
158 run.environmentId,
159 runOutcome.status === "failed" ? runOutcome.line : "Provider update interrupted",
160 );
161 }
162 return runOutcome;
163 });
164 for (const machine of machinesById.values()) {
165 if (machine.server === null) {
166 settleUpdateRunMachine(
167 machine.environmentId,
168 providerFailures.get(machine.environmentId) ?? null,
169 );
170 }
171 }
172 const serversStartedAt = Date.now();
173 setUpdateEverythingRun(
174 (run) =>
175 run && {
176 ...run,
177 phase: "servers",
178 machines: run.machines.map((machine) =>
179 machine.server === null ? machine : { ...machine, startedAt: serversStartedAt },
180 ),
181 },
182 );
183 return outcomes;
184 },
185 updateServers: async () => {
186 const runs = servers.map(async (server) => {
187 const serverOutcome = await updateServer(server, { quiet: true });
188 settleUpdateRunMachine(
189 server.environmentId,
190 serverOutcome.status === "failed"
191 ? serverOutcome.message
192 : (providerFailures.get(server.environmentId) ?? null),
193 {
194 serverUpdated: serverOutcome.status !== "failed",
195 providerFailure: providerFailures.get(server.environmentId) ?? null,
196 },
197 );
198 const finished = { label: server.serverLabel, outcome: serverOutcome };
199 finishedServers.push(finished);
200 return finished;
201 });
202 await Promise.all(
203 servers.map((server, index) =>
204 waitForServerUpdateHandoff(server.environmentId, runs[index]!),
205 ),
206 );
207 return runs;
208 },
209 });
210 const result = (finished: ReadonlyArray<{ label: string; outcome: ServerUpdateOutcome }>) =>
211 collectUpdateEverythingResult({
212 localVersion: null,
213 localFailures,
214 servers: finished,
215 providers: outcome.providers,
216 });
217 if (outcome.localReady && installLocal) {
218 if (await waitForUpdateRestart(UPDATE_RESTART_DELAY_MS)) {
219 setUpdateEverythingRun(
220 (run) => run && { ...run, phase: "installing", restartAt: null },
221 );
222 saveUpdateEverythingResult({ ...result(finishedServers), localVersion });
223 if (await installLocal(reportLocalError)) return;
224 clearSavedUpdateEverythingResult();
225 }
226 }
227 setUpdateEverythingRun(
228 (run) =>
229 run &&
230 closeFinishedUpdateRun({
231 ...run,
232 phase: "servers",
233 restartAt: null,
234 localVersion: null,
235 }),
236 );
237 showUpdateEverythingResult(result(await Promise.all(outcome.servers)));
238 } catch (error) {
239 setUpdateEverythingRun(() => null);
240 throw error;
241 }
242 },
243 };