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