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

useUpdateEverything.ts

243 lines9.3 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 // Desktop-managed servers use their app feed; only npm installs need to wait for publication.
62 const needsNpm = behindServers.some((server) => server.selfUpdate !== "desktop-managed");
63 const published = useNpmReleasePublished(needsNpm ? targetVersion : null);
64 const servers = published
65 ? behindServers
66 : behindServers.filter((server) => server.selfUpdate === "desktop-managed");
67 const skipped: ReadonlyArray<SkippedMachine> = [
68 ...unreachable,
69 ...behindServers
70 .filter((server) => !servers.includes(server))
71 .map((server) => ({
72 environmentId: server.environmentId,
73 label: server.serverLabel,
74 reason: `t3@${targetVersion} is not on npm yet`,
75 })),
76 ];
77 const restarts = collectRestartingMachines(machines, servers, localUpdateVersion !== null);
78 const providers = useProviderUpdates();
79 const updateServer = useServerUpdate();
80​
81 const { summary, lines } = describeUpdateEverything({
82 localVersion: localUpdateVersion,
83 servers,
84 providerMachines: providers.machines.map((machine) => ({
85 environmentId: machine.environmentId,
86 label: machine.label,
87 providers: machine.candidates.map(
88 (candidate) => PROVIDER_DISPLAY_NAMES[candidate.driver] ?? candidate.driver,
89 ),
90 })),
91 });
92​
93 return {
94 hasUpdates: servers.length > 0 || providers.machines.length > 0,
95 summary,
96 lines,
97 restarts,
98 skipped,
99 run: async ({
100 downloadLocal,
101 installLocal,
102 }: {
103 downloadLocal?: (reportError: ReportLocalUpdateError) => Promise<boolean>;
104 installLocal?: (reportError: ReportLocalUpdateError) => Promise<boolean>;
105 }) => {
106 const localFailures: Array<string> = [];
107 const reportLocalError: ReportLocalUpdateError = (title, description) => {
108 localFailures.push(`${title}: ${description}`);
109 };
110 const startedAt = Date.now();
111 const machinesById = new Map<UpdateRunMachine["environmentId"], UpdateRunMachine>();
112 for (const machine of providers.machines) {
113 machinesById.set(machine.environmentId, {
114 environmentId: machine.environmentId,
115 label: machine.label,
116 updatesProviders: true,
117 server: null,
118 handedOffVersion: null,
119 startedAt,
120 result: null,
121 failure: null,
122 providerFailure: null,
123 });
124 }
125 for (const server of servers) {
126 const existing = machinesById.get(server.environmentId);
127 machinesById.set(server.environmentId, {
128 environmentId: server.environmentId,
129 label: server.serverLabel,
130 updatesProviders: existing?.updatesProviders ?? false,
131 server,
132 handedOffVersion: null,
133 startedAt,
134 result: null,
135 failure: null,
136 providerFailure: null,
137 });
138 }
139 const localVersion = installLocal ? localUpdateVersion : null;
140 setUpdateEverythingRun(() => ({
141 localVersion,
142 phase: "providers",
143 restartAt: null,
144 machines: Array.from(machinesById.values()),
145 }));
146 const providerFailures = new Map<UpdateRunMachine["environmentId"], string>();
147 const finishedServers: Array<{ label: string; outcome: ServerUpdateOutcome }> = [];
148 try {
149 const outcome = await runUpdateEverything({
150 ...(downloadLocal ? { downloadLocal: () => downloadLocal(reportLocalError) } : {}),
151 updateProviders: async () => {
152 const runs = await providers.updateAll({ quiet: true });
153 const outcomes = runs.map((run) => {
154 const runOutcome = getProviderUpdateRunOutcome(run);
155 if (runOutcome.status !== "updated") {
156 providerFailures.set(
157 run.environmentId,
158 runOutcome.status === "failed" ? runOutcome.line : "Provider update interrupted",
159 );
160 }
161 return runOutcome;
162 });
163 for (const machine of machinesById.values()) {
164 if (machine.server === null) {
165 settleUpdateRunMachine(
166 machine.environmentId,
167 providerFailures.get(machine.environmentId) ?? null,
168 );
169 }
170 }
171 const serversStartedAt = Date.now();
172 setUpdateEverythingRun(
173 (run) =>
174 run && {
175 ...run,
176 phase: "servers",
177 machines: run.machines.map((machine) =>
178 machine.server === null ? machine : { ...machine, startedAt: serversStartedAt },
179 ),
180 },
181 );
182 return outcomes;
183 },
184 updateServers: async () => {
185 const runs = servers.map(async (server) => {
186 const serverOutcome = await updateServer(server, { quiet: true });
187 settleUpdateRunMachine(
188 server.environmentId,
189 serverOutcome.status === "failed"
190 ? serverOutcome.message
191 : (providerFailures.get(server.environmentId) ?? null),
192 {
193 serverUpdated: serverOutcome.status !== "failed",
194 providerFailure: providerFailures.get(server.environmentId) ?? null,
195 },
196 );
197 const finished = { label: server.serverLabel, outcome: serverOutcome };
198 finishedServers.push(finished);
199 return finished;
200 });
201 await Promise.all(
202 servers.map((server, index) =>
203 waitForServerUpdateHandoff(server.environmentId, runs[index]!),
204 ),
205 );
206 return runs;
207 },
208 });
209 const result = (finished: ReadonlyArray<{ label: string; outcome: ServerUpdateOutcome }>) =>
210 collectUpdateEverythingResult({
211 localVersion: null,
212 localFailures,
213 servers: finished,
214 providers: outcome.providers,
215 });
216 if (outcome.localReady && installLocal) {
217 if (await waitForUpdateRestart(UPDATE_RESTART_DELAY_MS)) {
218 setUpdateEverythingRun(
219 (run) => run && { ...run, phase: "installing", restartAt: null },
220 );
221 saveUpdateEverythingResult({ ...result(finishedServers), localVersion });
222 if (await installLocal(reportLocalError)) return;
223 clearSavedUpdateEverythingResult();
224 }
225 }
226 setUpdateEverythingRun(
227 (run) =>
228 run &&
229 closeFinishedUpdateRun({
230 ...run,
231 phase: "servers",
232 restartAt: null,
233 localVersion: null,
234 }),
235 );
236 showUpdateEverythingResult(result(await Promise.all(outcome.servers)));
237 } catch (error) {
238 setUpdateEverythingRun(() => null);
239 throw error;
240 }
241 },
242 };