Open History to see the last commit
1import {
2 ServerSelfUpdateError,
3 type ServerSelfUpdateCapability,
4 type ServerSelfUpdateInput,
5 type ServerSelfUpdateProgressEvent,
6 type ServerSelfUpdateProgressStage,
7 type ServerSelfUpdateResult,
8 type ThreadId,
9} from "@t3tools/contracts";
10import * as HostProcess from "@t3tools/shared/HostProcess";
11import * as Cause from "effect/Cause";
12import * as Config from "effect/Config";
13import * as Context from "effect/Context";
14import * as Duration from "effect/Duration";
15import * as Effect from "effect/Effect";
16import * as HashSet from "effect/HashSet";
17import * as Option from "effect/Option";
18import * as Ref from "effect/Ref";
19import * as FileSystem from "effect/FileSystem";
20import * as Layer from "effect/Layer";
21import * as Path from "effect/Path";
22import * as Queue from "effect/Queue";
23import * as Stream from "effect/Stream";
24import { HttpClient } from "effect/http";
25
26import { CLI_RELEASE_BASE_URL_ENV } from "@t3tools/shared/cliRelease";
27
28import packageJson from "../../package.json" with { type: "json" };
29import * as ServerConfig from "../config.ts";
30import * as DesktopAppUpdate from "../desktopUpdate/DesktopAppUpdate.ts";
31import * as ProcessRunner from "../processRunner.ts";
32import {
33 ensurePinnedRuntimeInstalled,
34 pinnedRuntimeCommand,
35 PinnedRuntimeInstallError,
36 PinnedRuntimePreflightBlockedError,
37 prunePinnedRuntimes,
38} from "./pinnedRuntime.ts";
39import { decodeServicePreflightResult } from "./servicePreflight.ts";
40import * as ServiceLauncherClient from "./serviceLauncherClient.ts";
41import { isExactServiceVersion, SERVICE_LAUNCHER_PROTOCOL } from "./serviceProtocol.ts";
42
43const PREFLIGHT_TIMEOUT = Duration.seconds(30);
44
45export function resolveServerSelfUpdateCapability(input: {
46 readonly desktopManaged: boolean;
47 readonly launcherManaged: boolean;
48}): ServerSelfUpdateCapability | null {
49 if (input.desktopManaged) return "desktop-managed" as const;
50 return input.launcherManaged ? ("boot-service" as const) : null;
51}
52
53export class ServerSelfUpdate extends Context.Service<
54 ServerSelfUpdate,
55 {
56 readonly update: (
57 input: ServerSelfUpdateInput,
58 reportProgress?: (
59 stage: ServerSelfUpdateProgressStage,
60 ) => Effect.Effect<void, ServerSelfUpdateError>,
61 onHandoffAccepted?: () => Effect.Effect<void>,
62 ) => Effect.Effect<ServerSelfUpdateResult, ServerSelfUpdateError>;
63 readonly commitDesktopUpdate: (
64 requestId: string,
65 onHandoffAccepted?: () => Effect.Effect<void>,
66 ) => Effect.Effect<never, ServerSelfUpdateError>;
67 }
68>()("t3/cloud/selfUpdate/ServerSelfUpdate") {}
69
70export const withRunningThreadContinuation = Effect.fn(
71 "cloud.server_self_update.withRunningThreadContinuation",
72)(function* (input: {
73 readonly mode: ServerConfig.RuntimeMode;
74 readonly selfUpdate: ServerSelfUpdate["Service"];
75 readonly prepare: Effect.Effect<ReadonlyArray<ThreadId>, ServerSelfUpdateError>;
76 readonly clear: (
77 threadIds: ReadonlyArray<ThreadId>,
78 ) => Effect.Effect<void, ServerSelfUpdateError>;
79}) {
80 const desktopContinuationTokens = yield* Ref.make(HashSet.empty<string>());
81 const clearOnError = <A>(
82 effect: Effect.Effect<A, ServerSelfUpdateError>,
83 threadIds: () => ReadonlyArray<ThreadId>,
84 handoffAccepted: () => boolean,
85 ): Effect.Effect<A, ServerSelfUpdateError> =>
86 effect.pipe(
87 Effect.catchCause((cause) =>
88 (handoffAccepted() && Cause.hasInterruptsOnly(cause)
89 ? Effect.void
90 : input.clear(threadIds())
91 ).pipe(Effect.andThen(Effect.failCause(cause))),
92 ),
93 );
94
95 const update: ServerSelfUpdate["Service"]["update"] = (
96 request,
97 reportProgress = () => Effect.void,
98 ) => {
99 let prepared = false;
100 let handoffAccepted = false;
101 let continuationThreadIds: ReadonlyArray<ThreadId> = [];
102 return clearOnError(
103 input.selfUpdate
104 .update(
105 request,
106 (stage) =>
107 (request.continueRunningThreads === true &&
108 input.mode !== "desktop" &&
109 stage === "installing" &&
110 !prepared
111 ? input.prepare.pipe(
112 Effect.tap((threadIds) =>
113 Effect.sync(() => {
114 prepared = true;
115 continuationThreadIds = threadIds;
116 }),
117 ),
118 Effect.asVoid,
119 )
120 : Effect.void
121 ).pipe(Effect.andThen(reportProgress(stage))),
122 () =>
123 Effect.sync(() => {
124 handoffAccepted = true;
125 }),
126 )
127 .pipe(
128 Effect.tap((result) => {
129 if (
130 result.method === "desktop-app" &&
131 result.desktopUpdateToken !== undefined &&
132 request.continueRunningThreads === true
133 ) {
134 return Ref.update(desktopContinuationTokens, HashSet.add(result.desktopUpdateToken));
135 }
136 return Effect.void;
137 }),
138 ),
139 () => continuationThreadIds,
140 () => handoffAccepted,
141 );
142 };
143
144 return ServerSelfUpdate.of({
145 update,
146 commitDesktopUpdate: Effect.fn("selfUpdate.commitDesktopUpdate")(function* (requestId) {
147 const shouldContinue = yield* Ref.modify(desktopContinuationTokens, (tokens) => [
148 HashSet.has(tokens, requestId),
149 HashSet.remove(tokens, requestId),
150 ]);
151 let handoffAccepted = false;
152 let continuationThreadIds: ReadonlyArray<ThreadId> = [];
153 return yield* clearOnError(
154 Effect.gen(function* () {
155 continuationThreadIds = shouldContinue ? yield* input.prepare : [];
156 return yield* input.selfUpdate.commitDesktopUpdate(requestId, () =>
157 Effect.sync(() => {
158 handoffAccepted = true;
159 }),
160 );
161 }),
162 () => continuationThreadIds,
163 () => handoffAccepted,
164 ).pipe(
165 Effect.catchCause((cause) =>
166 (shouldContinue && !handoffAccepted
167 ? Ref.update(desktopContinuationTokens, HashSet.add(requestId))
168 : Effect.void
169 ).pipe(Effect.andThen(Effect.failCause(cause))),
170 ),
171 );
172 }),
173 });
174});
175
176export const make = Effect.fn("cloud.server_self_update.make")(function* () {
177 const serverConfig = yield* ServerConfig.ServerConfig;
178 const desktopAppUpdate = yield* DesktopAppUpdate.DesktopAppUpdate;
179 const launcher = yield* ServiceLauncherClient.ServiceLauncherClient;
180 const runner = yield* ProcessRunner.ProcessRunner;
181 const fs = yield* FileSystem.FileSystem;
182 const path = yield* Path.Path;
183 const platform = yield* HostProcess.Platform;
184 const arch = yield* HostProcess.Architecture;
185 const httpClient = yield* HttpClient.HttpClient;
186 const releaseBaseUrl = Option.getOrUndefined(
187 yield* Config.String(CLI_RELEASE_BASE_URL_ENV).pipe(Config.option),
188 );
189 const inFlight = yield* Ref.make(false);
190
191 // A managed server starting means its launcher has settled on a version, so runtimes left by
192 // earlier updates can go.
193 if (launcher.managed) {
194 yield* prunePinnedRuntimes({ baseDir: serverConfig.baseDir, keep: [packageJson.version] }).pipe(
195 Effect.tap((removed) =>
196 removed.length === 0
197 ? Effect.void
198 : Effect.logInfo("Removed unused t3 runtimes.", { versions: removed }),
199 ),
200 Effect.forkScoped,
201 );
202 }
203
204 const capability: ServerSelfUpdateCapability | null =
205 serverConfig.mode === "desktop" ? "desktop-managed" : launcher.managed ? "boot-service" : null;
206 const failWith = (reason: string, cause?: unknown) =>
207 cause === undefined
208 ? new ServerSelfUpdateError({ reason })
209 : new ServerSelfUpdateError({ reason, cause });
210
211 const update: ServerSelfUpdate["Service"]["update"] = Effect.fn(
212 "cloud.server_self_update.update",
213 )(function* (input, reportProgress = () => Effect.void, onHandoffAccepted = () => Effect.void) {
214 if (capability === "desktop-managed") {
215 if (desktopAppUpdate.available) {
216 return yield* desktopAppUpdate.run(reportProgress);
217 }
218 return yield* failWith(
219 "This server is managed by the T3 Code desktop app on its machine; update the desktop app to update it.",
220 );
221 }
222 if (capability === null) {
223 return yield* failWith(
224 "Remote updates require the T3 Code background service. Run `t3 service install` on the server machine.",
225 );
226 }
227
228 const targetVersion = input.targetVersion.trim();
229 if (!isExactServiceVersion(targetVersion)) {
230 return yield* failWith(`'${targetVersion}' is not an exact t3 version.`);
231 }
232 if (yield* Ref.getAndSet(inFlight, true)) {
233 return yield* failWith("A server update is already in progress.");
234 }
235
236 return yield* Effect.gen(function* () {
237 yield* reportProgress("downloading");
238 const paths = yield* ensurePinnedRuntimeInstalled({
239 baseDir: serverConfig.baseDir,
240 version: targetVersion,
241 fs,
242 path,
243 runner,
244 httpClient,
245 platform,
246 arch,
247 releaseBaseUrl,
248 validate: (runtime) =>
249 runner
250 .run({
251 command: pinnedRuntimeCommand(runtime).command,
252 args: [
253 ...pinnedRuntimeCommand(runtime).args,
254 "__service-preflight",
255 "--database-path",
256 serverConfig.dbPath,
257 "--launcher-protocol",
258 String(SERVICE_LAUNCHER_PROTOCOL),
259 ],
260 timeout: PREFLIGHT_TIMEOUT,
261 })
262 .pipe(
263 Effect.mapError(
264 (cause) =>
265 new PinnedRuntimeInstallError({
266 step: "running the staged service preflight",
267 cause,
268 }),
269 ),
270 Effect.flatMap(
271 (
272 result,
273 ): Effect.Effect<
274 void,
275 PinnedRuntimeInstallError | PinnedRuntimePreflightBlockedError
276 > => {
277 if (result.code !== 0) {
278 return Effect.fail(
279 new PinnedRuntimeInstallError({
280 step: "running the staged service preflight",
281 exitCode: Number(result.code),
282 stdoutLength: result.stdout.length,
283 stderrLength: result.stderr.length,
284 }),
285 );
286 }
287 let parsed: unknown;
288 try {
289 parsed = JSON.parse(result.stdout.trim());
290 } catch (cause) {
291 return Effect.fail(
292 new PinnedRuntimeInstallError({
293 step: "decoding the staged service preflight",
294 cause,
295 }),
296 );
297 }
298 const preflight = decodeServicePreflightResult(parsed);
299 if (preflight === undefined || preflight.version !== targetVersion) {
300 return Effect.fail(
301 new PinnedRuntimeInstallError({
302 step: "verifying the staged service preflight",
303 }),
304 );
305 }
306 return preflight.status === "ready"
307 ? Effect.void
308 : Effect.fail(
309 new PinnedRuntimePreflightBlockedError({
310 version: targetVersion,
311 reason: preflight.reason,
312 }),
313 );
314 },
315 ),
316 ),
317 }).pipe(
318 Effect.mapError((error) =>
319 error._tag === "PinnedRuntimePreflightBlockedError"
320 ? failWith(error.reason, error)
321 : failWith(`Could not prepare t3@${targetVersion}.`, error),
322 ),
323 );
324
325 yield* reportProgress("installing");
326 const updateId = yield* Effect.uninterruptible(
327 launcher.requestUpdate({ targetVersion, dbPath: serverConfig.dbPath }).pipe(
328 Effect.mapError((error) =>
329 failWith(
330 error._tag === "ServiceLauncherRejectedError"
331 ? error.reason
332 : "Could not ask the service launcher to activate the prepared update.",
333 error,
334 ),
335 ),
336 Effect.tap(() => onHandoffAccepted()),
337 ),
338 );
339
340 yield* Effect.logInfo("Server update prepared; handing off to the service launcher.", {
341 updateId,
342 targetVersion,
343 runtimePath: paths.entryPath,
344 });
345 return { targetVersion, method: "boot-service" as const, updateId };
346 }).pipe(Effect.onError(() => Ref.set(inFlight, false)));
347 });
348
349 return ServerSelfUpdate.of({
350 update,
351 commitDesktopUpdate: (requestId, onHandoffAccepted) =>
352 desktopAppUpdate.commit(requestId, onHandoffAccepted),
353 });
354});
355
356export const layer = Layer.effect(ServerSelfUpdate, make()).pipe(
357 Layer.provide(ProcessRunner.layer),
358);
359
360// The RPC stream used to own this fiber, so a dropped client socket interrupted
361// the download. Offers after the queue shuts down are ignored; the update
362// still finishes, and the in-flight guard stays as it was.
363export const updateProgressStream = (
364 selfUpdate: ServerSelfUpdate["Service"],
365 input: ServerSelfUpdateInput,
366) =>
367 Stream.callback<ServerSelfUpdateProgressEvent, ServerSelfUpdateError>((queue) => {
368 const offer = (event: ServerSelfUpdateProgressEvent) =>
369 Queue.offer(queue, event).pipe(Effect.ignore);
370
371 return selfUpdate
372 .update(input, (stage) => offer({ type: "progress", stage }))
373 .pipe(
374 Effect.flatMap((result) => offer({ type: "complete", result })),
375 Effect.catchTags({
376 ServerSelfUpdateError: (error) => Queue.fail(queue, error).pipe(Effect.ignore),
377 }),
378 Effect.andThen(Queue.end(queue).pipe(Effect.ignore)),
379 Effect.forkDetach,
380 );
381 });