Open History to see the last commit
1import * as Duration from "effect/Duration";
2import * as Effect from "effect/Effect";
3import * as Encoding from "effect/Encoding";
4import * as FileSystem from "effect/FileSystem";
5import * as Path from "effect/Path";
6import * as Schema from "effect/Schema";
7import * as Option from "effect/Option";
8import * as Semaphore from "effect/Semaphore";
9import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
10
11import {
12 CLI_RELEASE_CHECKSUMS_FILE,
13 cliArchiveFileName,
14 cliArchivePlatformKey,
15 cliArchiveTarCommand,
16 cliReleaseDownloadBaseUrl,
17 parseChecksums,
18} from "@t3tools/shared/cliRelease";
19
20import * as ProcessRunner from "../processRunner.ts";
21
22/**
23 * A pinned runtime is an exact t3 release archive unpacked into
24 * <baseDir>/runtime/versions/<version>: the self-contained executable, the
25 * web client, and the native packages beside it. The boot service points its
26 * unit or launch agent at the executable, and server self-update installs the
27 * target version here before switching over. The runtime never depends on a
28 * Node or npm on the machine; the only npm involvement in T3 Code is the `t3`
29 * package for people who prefer `npx t3` or `npm install -g t3`, and even a
30 * CLI installed that way pins an archive when it sets up the service.
31 */
32const PINNED_RUNTIME_DIR = "runtime";
33const PINNED_RUNTIME_INSTALL_TIMEOUT = Duration.minutes(10);
34const PINNED_RUNTIME_ARCHIVE_FILE = "t3-runtime-archive";
35// Boot-service setup and remote update can construct separate layers. Serialize
36// the complete install transaction across every caller in this process.
37const pinnedRuntimeInstallLock = Semaphore.makeUnsafe(1);
38
39export interface PinnedRuntimePaths {
40 readonly versionDir: string;
41 /** The executable. Its existence is what marks a runtime as present. */
42 readonly entryPath: string;
43 readonly sentinelPath: string;
44}
45
46/** The exact command that runs a pinned runtime. */
47export function pinnedRuntimeCommand(paths: PinnedRuntimePaths): {
48 readonly command: string;
49 readonly args: ReadonlyArray<string>;
50} {
51 return { command: paths.entryPath, args: [] };
52}
53
54export function pinnedRuntimePaths(
55 path: Path.Path,
56 baseDir: string,
57 version: string,
58 platform: NodeJS.Platform,
59): PinnedRuntimePaths {
60 const versionDir = path.join(baseDir, PINNED_RUNTIME_DIR, "versions", version);
61 return {
62 versionDir,
63 entryPath: path.join(versionDir, platform === "win32" ? "t3.exe" : "t3"),
64 sentinelPath: path.join(versionDir, ".install-complete"),
65 };
66}
67
68export class PinnedRuntimeInstallError extends Schema.TaggedError<PinnedRuntimeInstallError>()(
69 "PinnedRuntimeInstallError",
70 {
71 step: Schema.String,
72 exitCode: Schema.optional(Schema.Number),
73 stdoutLength: Schema.optional(Schema.Number),
74 stderrLength: Schema.optional(Schema.Number),
75 cause: Schema.optional(Schema.Defect()),
76 },
77) {
78 override get message(): string {
79 return this.exitCode === undefined
80 ? `Pinned runtime install failed while ${this.step}.`
81 : `Pinned runtime install failed while ${this.step} (exit code ${this.exitCode}).`;
82 }
83}
84
85export class PinnedRuntimePreflightBlockedError extends Schema.TaggedError<PinnedRuntimePreflightBlockedError>()(
86 "PinnedRuntimePreflightBlockedError",
87 {
88 version: Schema.String,
89 reason: Schema.String,
90 },
91) {
92 override get message(): string {
93 return this.reason;
94 }
95}
96
97/**
98 * Installs the t3 release archive for `version` into the pinned runtime
99 * directory unless a complete install is already there, and returns its
100 * paths. The sentinel is written only after extraction and validation
101 * succeed; checking the entry file alone is not enough, since tar writes the
102 * executable before the last native package and a killed install leaves a
103 * plausible-looking but broken tree behind.
104 */
105interface PinnedRuntimeInstallInput {
106 readonly baseDir: string;
107 readonly version: string;
108 readonly fs: FileSystem.FileSystem;
109 readonly path: Path.Path;
110 readonly runner: ProcessRunner.ProcessRunner["Service"];
111 readonly validate: (
112 paths: PinnedRuntimePaths,
113 ) => Effect.Effect<void, PinnedRuntimeInstallError | PinnedRuntimePreflightBlockedError>;
114 readonly platform: NodeJS.Platform;
115 readonly arch: string;
116 readonly httpClient: HttpClient.HttpClient;
117 readonly releaseBaseUrl?: string | undefined;
118}
119
120const fetchReleaseAsset = Effect.fn("cloud.pinned_runtime.fetch_release_asset")(function* (
121 httpClient: HttpClient.HttpClient,
122 url: string,
123 step: string,
124) {
125 // The install lock is held for the whole transaction, so a stalled download
126 // must fail rather than block every other caller.
127 return yield* httpClient.execute(HttpClientRequest.get(url)).pipe(
128 Effect.flatMap(HttpClientResponse.filterStatusOk),
129 Effect.flatMap((response) => response.arrayBuffer),
130 Effect.map((buffer) => new Uint8Array(buffer)),
131 Effect.mapError((cause) => new PinnedRuntimeInstallError({ step, cause })),
132 Effect.timeoutOrElse({
133 duration: PINNED_RUNTIME_INSTALL_TIMEOUT,
134 orElse: () => Effect.fail(new PinnedRuntimeInstallError({ step: `${step} (timed out)` })),
135 }),
136 );
137});
138
139/**
140 * Downloads the release archive for this platform, verifies it against the
141 * release's checksum file, and unpacks it so the executable sits directly in
142 * the staging directory. Only `tar` is required on the host; every supported
143 * OS ships one that reads gzip and zip.
144 */
145const installFromArchive = Effect.fn("cloud.pinned_runtime.install_archive")(function* (
146 input: PinnedRuntimeInstallInput,
147 stagingDir: string,
148) {
149 const { fs, path } = input;
150 const platformKey = cliArchivePlatformKey(input.platform, input.arch);
151 if (platformKey === undefined) {
152 return yield* new PinnedRuntimeInstallError({
153 step: `selecting a t3 release archive for ${input.platform}-${input.arch}`,
154 });
155 }
156 const httpClient = input.httpClient;
157 const baseUrl = cliReleaseDownloadBaseUrl(input.version, input.releaseBaseUrl);
158 const fileName = cliArchiveFileName(input.version, platformKey);
159
160 const checksums = parseChecksums(
161 new TextDecoder().decode(
162 yield* fetchReleaseAsset(
163 httpClient,
164 `${baseUrl}/${CLI_RELEASE_CHECKSUMS_FILE}`,
165 "downloading the t3 release checksums",
166 ),
167 ),
168 );
169 const expected = checksums.get(fileName);
170 if (expected === undefined) {
171 return yield* new PinnedRuntimeInstallError({
172 step: `finding ${fileName} in the t3 release checksums`,
173 });
174 }
175 const archive = yield* fetchReleaseAsset(
176 httpClient,
177 `${baseUrl}/${fileName}`,
178 "downloading the t3 release archive",
179 );
180 const digest = yield* Effect.tryPromise({
181 try: () => crypto.subtle.digest("SHA-256", archive),
182 catch: (cause) =>
183 new PinnedRuntimeInstallError({ step: "verifying the t3 release archive", cause }),
184 });
185 if (Encoding.encodeHex(new Uint8Array(digest)) !== expected) {
186 return yield* new PinnedRuntimeInstallError({
187 step: "verifying the t3 release archive checksum",
188 });
189 }
190
191 const archivePath = path.join(stagingDir, PINNED_RUNTIME_ARCHIVE_FILE);
192 yield* fs
193 .writeFile(archivePath, archive)
194 .pipe(
195 Effect.mapError(
196 (cause) => new PinnedRuntimeInstallError({ step: "writing the t3 release archive", cause }),
197 ),
198 );
199 const extractStep = "extracting the t3 release archive";
200 // The archive wraps everything in one directory named after its stem;
201 // strip it so the executable lands at <versionDir>/t3.
202 yield* input.runner
203 .run({
204 command: cliArchiveTarCommand(input.platform, process.env),
205 args: ["-xf", archivePath, "-C", stagingDir, "--strip-components=1"],
206 timeout: PINNED_RUNTIME_INSTALL_TIMEOUT,
207 })
208 .pipe(
209 Effect.mapError((cause) => new PinnedRuntimeInstallError({ step: extractStep, cause })),
210 Effect.filterOrFail(
211 (result) => result.code === 0,
212 (result) =>
213 new PinnedRuntimeInstallError({
214 step: extractStep,
215 exitCode: Number(result.code),
216 stdoutLength: result.stdout.length,
217 stderrLength: result.stderr.length,
218 }),
219 ),
220 );
221 yield* fs.remove(archivePath, { force: true }).pipe(Effect.ignore);
222});
223
224const installPinnedRuntime = Effect.fn("cloud.pinned_runtime.ensure_installed")(function* (
225 input: PinnedRuntimeInstallInput,
226) {
227 const { fs } = input;
228 const paths = pinnedRuntimePaths(input.path, input.baseDir, input.version, input.platform);
229 const [versionDirExists, entryExists, sentinel] = yield* Effect.all([
230 fs.exists(paths.versionDir),
231 fs.exists(paths.entryPath),
232 fs.readFileString(paths.sentinelPath).pipe(Effect.option),
233 ]).pipe(
234 Effect.mapError(
235 (cause) => new PinnedRuntimeInstallError({ step: "checking the pinned runtime", cause }),
236 ),
237 );
238 const alreadyPinned =
239 entryExists && Option.isSome(sentinel) && sentinel.value.trim() === input.version;
240 if (alreadyPinned) {
241 yield* input.validate(paths);
242 return paths;
243 }
244 if (versionDirExists) {
245 yield* fs.remove(paths.versionDir, { recursive: true, force: true }).pipe(
246 Effect.mapError(
247 (cause) =>
248 new PinnedRuntimeInstallError({
249 step: "removing an incomplete pinned runtime",
250 cause,
251 }),
252 ),
253 );
254 }
255
256 const versionsDir = input.path.dirname(paths.versionDir);
257 yield* fs.makeDirectory(versionsDir, { recursive: true }).pipe(
258 Effect.mapError(
259 (cause) =>
260 new PinnedRuntimeInstallError({
261 step: "preparing the pinned runtime directory",
262 cause,
263 }),
264 ),
265 );
266 const stagingDir = yield* fs
267 .makeTempDirectory({
268 directory: versionsDir,
269 prefix: ".staging-",
270 })
271 .pipe(
272 Effect.mapError(
273 (cause) =>
274 new PinnedRuntimeInstallError({
275 step: "preparing the pinned runtime directory",
276 cause,
277 }),
278 ),
279 );
280 const stagingPaths: PinnedRuntimePaths = {
281 versionDir: stagingDir,
282 entryPath: input.path.join(stagingDir, input.path.relative(paths.versionDir, paths.entryPath)),
283 sentinelPath: input.path.join(stagingDir, ".install-complete"),
284 };
285
286 return yield* Effect.gen(function* () {
287 yield* installFromArchive(input, stagingDir);
288
289 yield* input.validate(stagingPaths);
290 yield* fs
291 .writeFileString(stagingPaths.sentinelPath, `${input.version}\n`)
292 .pipe(
293 Effect.mapError(
294 (cause) =>
295 new PinnedRuntimeInstallError({ step: "recording the completed install", cause }),
296 ),
297 );
298 const published = yield* fs.rename(stagingDir, paths.versionDir).pipe(
299 Effect.as(true),
300 Effect.catch((cause) =>
301 Effect.all([
302 fs.exists(paths.entryPath),
303 fs.readFileString(paths.sentinelPath).pipe(Effect.option),
304 ]).pipe(
305 Effect.mapError(
306 (checkCause) =>
307 new PinnedRuntimeInstallError({
308 step: "checking a concurrently published pinned runtime",
309 cause: checkCause,
310 }),
311 ),
312 Effect.flatMap(([publishedEntryExists, publishedSentinel]) =>
313 publishedEntryExists &&
314 Option.isSome(publishedSentinel) &&
315 publishedSentinel.value.trim() === input.version
316 ? Effect.succeed(false)
317 : Effect.fail(
318 new PinnedRuntimeInstallError({
319 step: "publishing the pinned runtime",
320 cause,
321 }),
322 ),
323 ),
324 ),
325 ),
326 );
327 if (!published) yield* input.validate(paths);
328 return paths;
329 }).pipe(
330 Effect.ensuring(fs.remove(stagingDir, { recursive: true, force: true }).pipe(Effect.ignore)),
331 );
332});
333
334export const ensurePinnedRuntimeInstalled = (input: PinnedRuntimeInstallInput) =>
335 pinnedRuntimeInstallLock.withPermit(installPinnedRuntime(input));