Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import { PROVIDER_DISPLAY_NAMES } from "@t3tools/contracts";
3import { Atom } from "effect/reactivity";
4
5import { APP_VERSION } from "~/branding";
6import { isDesktopLocalConnectionTarget } from "~/connection/desktopLocal";
7import { isElectron } from "~/env";
8import { useEnvironments } from "~/state/environments";
9import { useNpmReleasePublished } from "~/state/npmRelease";
10import { serverEnvironment } from "~/state/server";
11import { environmentSession } 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 machinesAtom = Atom.make((get) =>
43 environments.map((environment) => ({
44 environmentId: environment.environmentId,
45 label: environment.label,
46 serverConfig: environment.serverConfig,
47 connected: environment.connection.phase === "connected",
48 hostedByThisApp:
49 isElectron &&
50 (environment.entry.target._tag === "PrimaryConnectionTarget" ||
51 isDesktopLocalConnectionTarget(environment.entry.target)),
52 canMaintain: canUpdateServer(
53 get(environmentSession.sessionStateAtom(environment.environmentId)),
54 ),
55 updateState: get(serverEnvironment.updateStateAtom(environment.environmentId)),
56 })),
57 );
58 const machines = useAtomValue(machinesAtom);
59 const { targets: behindServers, skipped: unreachable } = collectServerUpdateTargets(
60 machines,
61 targetVersion,
62 );
63 // A desktop-managed server installs from its own app's update feed, so only
64 // servers that download t3 from npm wait for npm to publish the version.
65 const needsNpm = behindServers.some((server) => server.selfUpdate !== "desktop-managed");
66 const published = useNpmReleasePublished(needsNpm ? targetVersion : null);
67 const servers = published
68 ? behindServers
69 : behindServers.filter((server) => server.selfUpdate === "desktop-managed");
70 const skipped: ReadonlyArray<SkippedMachine> = [
71 ...unreachable,
72 ...behindServers
73 .filter((server) => !servers.includes(server))
74 .map((server) => ({
75 environmentId: server.environmentId,
76 label: server.serverLabel,
77 reason: `t3@${targetVersion} is not on npm yet`,
78 })),
79 ];
80 const restarts = collectRestartingMachines(machines, servers, localUpdateVersion !== null);
81 const providers = useProviderUpdates();
82 const updateServer = useServerUpdate();
83
84 const { summary, lines } = describeUpdateEverything({
85 localVersion: localUpdateVersion,
86 servers,
87 providerMachines: providers.machines.map((machine) => ({
88 environmentId: machine.environmentId,
89 label: machine.label,
90 providers: machine.candidates.map(
91 (candidate) => PROVIDER_DISPLAY_NAMES[candidate.driver] ?? candidate.driver,
92 ),
93 })),
94 });
95
96 return {
97 hasUpdates: servers.length > 0 || providers.machines.length > 0,
98 summary,
99 lines,
100 restarts,
101 skipped,
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 localVersion,
145 phase: "providers",
146 restartAt: null,
147 machines: Array.from(machinesById.values()),
148 }));
149 const providerFailures = new Map<UpdateRunMachine["environmentId"], string>();
150 const finishedServers: Array<{ label: string; outcome: ServerUpdateOutcome }> = [];
151 try {
152 const outcome = await runUpdateEverything({
153 ...(downloadLocal ? { downloadLocal: () => downloadLocal(reportLocalError) } : {}),
154 updateProviders: async () => {
155 const runs = await providers.updateAll({ quiet: true });
156 const outcomes = runs.map((run) => {
157 const runOutcome = getProviderUpdateRunOutcome(run);
158 if (runOutcome.status !== "updated") {
159 providerFailures.set(
160 run.environmentId,
161 runOutcome.status === "failed" ? runOutcome.line : "Provider update interrupted",
162 );
163 }
164 return runOutcome;
165 });
166 for (const machine of machinesById.values()) {
167 if (machine.server === null) {
168 settleUpdateRunMachine(
169 machine.environmentId,
170 providerFailures.get(machine.environmentId) ?? null,
171 );
172 }
173 }
174 const serversStartedAt = Date.now();
175 setUpdateEverythingRun(
176 (run) =>
177 run && {
178 ...run,
179 phase: "servers",
180 machines: run.machines.map((machine) =>
181 machine.server === null ? machine : { ...machine, startedAt: serversStartedAt },
182 ),
183 },
184 );
185 return outcomes;
186 },
187 updateServers: async () => {
188 const runs = servers.map(async (server) => {
189 const serverOutcome = await updateServer(server, { quiet: true });
190 settleUpdateRunMachine(
191 server.environmentId,
192 serverOutcome.status === "failed"
193 ? serverOutcome.message
194 : (providerFailures.get(server.environmentId) ?? null),
195 {
196 serverUpdated: serverOutcome.status !== "failed",
197 providerFailure: providerFailures.get(server.environmentId) ?? null,
198 },
199 );
200 const finished = { label: server.serverLabel, outcome: serverOutcome };
201 finishedServers.push(finished);
202 return finished;
203 });
204 await Promise.all(
205 servers.map((server, index) =>
206 waitForServerUpdateHandoff(server.environmentId, runs[index]!),
207 ),
208 );
209 return runs;
210 },
211 });
212 const result = (finished: ReadonlyArray<{ label: string; outcome: ServerUpdateOutcome }>) =>
213 collectUpdateEverythingResult({
214 localVersion: null,
215 localFailures,
216 servers: finished,
217 providers: outcome.providers,
218 });
219 if (outcome.localReady && installLocal) {
220 if (await waitForUpdateRestart(UPDATE_RESTART_DELAY_MS)) {
221 setUpdateEverythingRun(
222 (run) => run && { ...run, phase: "installing", restartAt: null },
223 );
224 saveUpdateEverythingResult({ ...result(finishedServers), localVersion });
225 if (await installLocal(reportLocalError)) return;
226 clearSavedUpdateEverythingResult();
227 }
228 }
229 setUpdateEverythingRun(
230 (run) =>
231 run &&
232 closeFinishedUpdateRun({
233 ...run,
234 phase: "servers",
235 restartAt: null,
236 localVersion: null,
237 }),
238 );
239 showUpdateEverythingResult(result(await Promise.all(outcome.servers)));
240 } catch (error) {
241 setUpdateEverythingRun(() => null);
242 throw error;
243 }
244 },
245 };
246}