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