Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - Effect has no incremental digest.
2import * as EffectNodeStream from "@effect/platform-node/NodeStream";
3import { HostProcessArchitecture, HostProcessPlatform } from "@t3tools/shared/hostProcess";
4import * as Cause from "effect/Cause";
5import * as Clock from "effect/Clock";
6import * as Context from "effect/Context";
7import * as Deferred from "effect/Deferred";
8import type * as Duration from "effect/Duration";
9import * as Effect from "effect/Effect";
10import * as Exit from "effect/Exit";
11import * as FileSystem from "effect/FileSystem";
12import * as Layer from "effect/Layer";
13import * as Option from "effect/Option";
14import * as Path from "effect/Path";
15import * as Schema from "effect/Schema";
16import * as Semaphore from "effect/Semaphore";
17import * as Stream from "effect/Stream";
18import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
19import * as NodeCrypto from "node:crypto";
20
21import * as ServerConfig from "../config.ts";
22import { openZipArchive } from "../zipArchive.ts";
23
24// HTML previews only ever run T3's own pinned Chrome for Testing headless
25// shell, never a browser the user installed. To bump the pin, pick a version
26// from https://googlechromelabs.github.io/chrome-for-testing/known-good-versions-with-downloads.json,
27// download each platform's chrome-headless-shell zip, and replace the version
28// and every byte count and SHA-256 below. Hosts drop the old build after the
29// new one installs.
30const VERSION = "154.0.8037.92";
31const ARCHIVES = {
32 linux64: {
33 bytes: 120_477_194,
34 sha256: "636aa5c79f2693632e9921b8bbb050038ba11672e02346c06c20f991aed096f9",
35 },
36 "linux-arm64": {
37 bytes: 121_182_296,
38 sha256: "0ed0e47d9e9f639197f508d62ada09e5c6b4c4c60edab3160a9312a733091df6",
39 },
40 "mac-arm64": {
41 bytes: 99_221_129,
42 sha256: "77da14e75d7f2568e6f7898d3df7cdc6faac74b15e903b2c9d486ebb6ca9b929",
43 },
44 "mac-x64": {
45 bytes: 104_748_425,
46 sha256: "a54292aaacbb77f76f6ef47558e7c51ab884044e0adacca315567f83c060bcc4",
47 },
48 win32: {
49 bytes: 114_295_943,
50 sha256: "56b30d2d6c35775ebf8dc3618680f6529e1c38c87f7feb28a16e9904273d51f7",
51 },
52 win64: {
53 bytes: 120_822_223,
54 sha256: "3ac2561f02d9d87aadc0399d00b9002d718a4c365624fa67db9e7bfaf6b1a568",
55 },
56} as const;
57
58const chromePlatform = (platform: NodeJS.Platform, arch: NodeJS.Architecture) => {
59 switch (platform) {
60 case "linux":
61 return arch === "x64" ? "linux64" : arch === "arm64" ? "linux-arm64" : null;
62 case "darwin":
63 return arch === "arm64" ? "mac-arm64" : arch === "x64" ? "mac-x64" : null;
64 case "win32":
65 // There is no Windows arm64 build; Windows on Arm runs the x64 one under emulation.
66 return arch === "ia32" ? "win32" : arch === "x64" || arch === "arm64" ? "win64" : null;
67 default:
68 return null;
69 }
70};
71
72export interface PreviewBrowserRelease {
73 readonly version: string;
74 /** Chrome for Testing's platform name, which also names the archive's top directory. */
75 readonly platform: string;
76 readonly url: string;
77 readonly bytes: number;
78 readonly sha256: string;
79}
80
81export const previewBrowserRelease = (
82 platform: NodeJS.Platform,
83 arch: NodeJS.Architecture,
84): PreviewBrowserRelease | null => {
85 const chrome = chromePlatform(platform, arch);
86 return chrome === null
87 ? null
88 : {
89 version: VERSION,
90 platform: chrome,
91 url: `https://storage.googleapis.com/chrome-for-testing-public/${VERSION}/${chrome}/chrome-headless-shell-${chrome}.zip`,
92 ...ARCHIVES[chrome],
93 };
94};
95
96const megabytes = (bytes: number) => Math.round(bytes / 1_000_000);
97
98export class PreviewBrowserInstallError extends Schema.TaggedError<PreviewBrowserInstallError>()(
99 "PreviewBrowserInstallError",
100 { detail: Schema.String, cause: Schema.optional(Schema.Defect()) },
101) {
102 override get message(): string {
103 return `T3 could not install its HTML preview browser: ${this.detail} Call html_preview again to retry.`;
104 }
105}
106const isInstallError = Schema.is(PreviewBrowserInstallError);
107
108export class PreviewBrowserInstallingError extends Schema.TaggedError<PreviewBrowserInstallingError>()(
109 "PreviewBrowserInstallingError",
110 { downloadedBytes: Schema.Number, totalBytes: Schema.Number, unpacking: Schema.Boolean },
111) {
112 override get message(): string {
113 const progress = this.unpacking
114 ? "unpacking"
115 : `${megabytes(this.downloadedBytes)} of ${megabytes(this.totalBytes)} MB downloaded`;
116 return `T3 is installing its HTML preview browser (${progress}). Call html_preview again in a minute.`;
117 }
118}
119
120export class PreviewBrowserUnsupportedError extends Schema.TaggedError<PreviewBrowserUnsupportedError>()(
121 "PreviewBrowserUnsupportedError",
122 { platform: Schema.String, arch: Schema.String },
123) {
124 override get message(): string {
125 return `HTML previews are not available on ${this.platform}-${this.arch}: Chrome for Testing has no headless shell for it. html_render still works without a preview.`;
126 }
127}
128
129export class PreviewBrowser extends Context.Service<
130 PreviewBrowser,
131 {
132 /**
133 * Path to the installed headless shell. The first call starts the
134 * install; callers wait for it up to a bound and then get its progress
135 * instead, while the install keeps running.
136 */
137 readonly executable: Effect.Effect<
138 string,
139 PreviewBrowserInstallError | PreviewBrowserInstallingError | PreviewBrowserUnsupportedError
140 >;
141 /** The installed headless shell, if any. Never starts or waits on an install. */
142 readonly installed: Effect.Effect<Option.Option<string>>;
143 }
144>()("t3/htmlRender/PreviewBrowser") {}
145
146export interface PreviewBrowserOptions {
147 readonly baseDir: string;
148 readonly release?: PreviewBrowserRelease | null;
149 /** How long a caller waits on an install in progress. Provider tool calls time out near 60s. */
150 readonly wait?: Duration.Input;
151}
152
153const DOWNLOAD_TIMEOUT = "15 minutes";
154// Longer than any install can run: the download times out at 15 minutes.
155const STAGING_STALE_AFTER_MS = 60 * 60_000;
156
157const wrapFailure = (detail: string) => (cause: unknown) =>
158 isInstallError(cause) ? cause : new PreviewBrowserInstallError({ detail, cause });
159
160type InstallState =
161 | { readonly _tag: "idle" }
162 | {
163 readonly _tag: "installing";
164 readonly done: Deferred.Deferred<string, PreviewBrowserInstallError>;
165 }
166 | { readonly _tag: "installed"; readonly executable: string }
167 | { readonly _tag: "failed"; readonly error: PreviewBrowserInstallError };
168
169export const makePreviewBrowser = Effect.fn("PreviewBrowser.make")(function* (
170 options: PreviewBrowserOptions,
171) {
172 const fs = yield* FileSystem.FileSystem;
173 const path = yield* Path.Path;
174 const http = yield* HttpClient.HttpClient;
175 // Installs belong to the service, so they finish even when no caller is still waiting.
176 const serviceScope = yield* Effect.scope;
177 const platform = yield* HostProcessPlatform;
178 const arch = yield* HostProcessArchitecture;
179 const release =
180 options.release === undefined ? previewBrowserRelease(platform, arch) : options.release;
181 const wait = options.wait ?? "45 seconds";
182 const installRoot = path.join(
183 options.baseDir,
184 "tools",
185 "chrome-headless-shell",
186 release?.platform ?? `${platform}-${arch}`,
187 );
188 const executableName =
189 platform === "win32" ? "chrome-headless-shell.exe" : "chrome-headless-shell";
190 const gate = yield* Semaphore.make(1);
191 let state: InstallState = { _tag: "idle" };
192 const progress = { downloadedBytes: 0, unpacking: false };
193
194 // The version directory appears by one rename of a fully unpacked tree, so a
195 // runnable binary there is the complete-install marker.
196 const installedExecutable = (release: PreviewBrowserRelease) => {
197 const executable = path.join(installRoot, release.version, executableName);
198 return fs.stat(executable).pipe(
199 Effect.map((info) =>
200 info.type === "File" && (platform === "win32" || (info.mode & 0o111) !== 0)
201 ? Option.some(executable)
202 : Option.none<string>(),
203 ),
204 Effect.orElseSucceed(() => Option.none<string>()),
205 );
206 };
207
208 const download = Effect.fn("PreviewBrowser.download")(
209 function* (release: PreviewBrowserRelease, archivePath: string) {
210 const response = yield* http
211 .execute(HttpClientRequest.get(release.url))
212 .pipe(Effect.flatMap(HttpClientResponse.filterStatusOk));
213 const contentLength = response.headers["content-length"];
214 const contentEncoding = response.headers["content-encoding"]?.trim().toLowerCase();
215 if (
216 (contentEncoding === undefined || contentEncoding === "identity") &&
217 contentLength !== undefined &&
218 Number(contentLength) !== release.bytes
219 ) {
220 return yield* new PreviewBrowserInstallError({
221 detail: "The download size did not match the pinned release.",
222 });
223 }
224 const hash = NodeCrypto.createHash("sha256");
225 yield* response.stream.pipe(
226 Stream.tap((chunk) =>
227 Effect.suspend(() => {
228 progress.downloadedBytes += chunk.byteLength;
229 if (progress.downloadedBytes > release.bytes) {
230 return Effect.fail(
231 new PreviewBrowserInstallError({
232 detail: "The download was larger than the pinned release.",
233 }),
234 );
235 }
236 hash.update(chunk);
237 return Effect.void;
238 }),
239 ),
240 Stream.run(fs.sink(archivePath, { flag: "wx", mode: 0o600 })),
241 );
242 if (progress.downloadedBytes !== release.bytes || hash.digest("hex") !== release.sha256) {
243 return yield* new PreviewBrowserInstallError({
244 detail: "The download failed its size or SHA-256 check. Nothing was installed.",
245 });
246 }
247 },
248 Effect.timeout(DOWNLOAD_TIMEOUT),
249 Effect.mapError(
250 wrapFailure(
251 "The download from storage.googleapis.com failed. Check this machine's network access.",
252 ),
253 ),
254 );
255
256 const extract = Effect.fn("PreviewBrowser.extract")(
257 function* (release: PreviewBrowserRelease, archivePath: string, destination: string) {
258 const archive = yield* openZipArchive(
259 archivePath,
260 (detail, cause) => new PreviewBrowserInstallError({ detail, cause }),
261 );
262 const unsafe = new PreviewBrowserInstallError({
263 detail: "The archive contains an unexpected or unsafe entry.",
264 });
265 const root = `chrome-headless-shell-${release.platform}/`;
266 yield* fs.makeDirectory(destination);
267 let foundExecutable = false;
268 for (;;) {
269 const entry = yield* archive.next;
270 if (!entry) break;
271 const unixMode = entry.externalFileAttributes >>> 16;
272 const unixType = unixMode & 0o170000;
273 const isDirectory = entry.fileName.endsWith("/");
274 // Everything sits under the one top directory, which is stripped.
275 const relative = entry.fileName.startsWith(root) ? entry.fileName.slice(root.length) : null;
276 const target = relative === null ? null : path.resolve(destination, relative);
277 if (
278 relative === null ||
279 target === null ||
280 (relative !== "" && !target.startsWith(`${destination}${path.sep}`)) ||
281 relative.split("/").includes("..") ||
282 (unixType !== 0 && unixType !== (isDirectory ? 0o040000 : 0o100000)) ||
283 (entry.generalPurposeBitFlag & 1) !== 0 ||
284 ![0, 8].includes(entry.compressionMethod)
285 ) {
286 return yield* unsafe;
287 }
288 if (isDirectory) {
289 yield* fs.makeDirectory(target, { recursive: true });
290 continue;
291 }
292 yield* fs.makeDirectory(path.dirname(target), { recursive: true });
293 yield* Effect.gen(function* () {
294 const readable = yield* archive.streamEntry(entry);
295 yield* EffectNodeStream.fromReadable<Uint8Array, PreviewBrowserInstallError>({
296 evaluate: () => readable,
297 onError: wrapFailure("Could not unpack the browser."),
298 }).pipe(Stream.run(fs.sink(target, { flag: "wx" })));
299 }).pipe(Effect.scoped);
300 // The binary and its shared libraries carry exec bits in the archive.
301 if (platform !== "win32" && (unixMode & 0o777) !== 0) {
302 yield* fs.chmod(target, unixMode & 0o777);
303 }
304 if (relative === executableName) foundExecutable = true;
305 }
306 if (!foundExecutable) {
307 return yield* new PreviewBrowserInstallError({
308 detail: "The archive does not contain chrome-headless-shell.",
309 });
310 }
311 },
312 Effect.scoped,
313 Effect.mapError(
314 wrapFailure("Could not unpack the browser. Check free disk space in T3's home directory."),
315 ),
316 );
317
318 const install = Effect.fn("PreviewBrowser.install")(
319 function* (release: PreviewBrowserRelease) {
320 yield* Effect.gen(function* () {
321 yield* fs.makeDirectory(installRoot, { recursive: true });
322 // Staging shares the install root's filesystem so publishing is one rename.
323 const staging = yield* fs.makeTempDirectoryScoped({
324 directory: installRoot,
325 prefix: ".install-",
326 });
327 const archivePath = path.join(staging, "download.zip");
328 const unpacked = path.join(staging, "browser");
329 yield* download(release, archivePath);
330 progress.unpacking = true;
331 yield* extract(release, archivePath, unpacked);
332 const destination = path.join(installRoot, release.version);
333 // A directory left without a runnable binary would block the rename.
334 yield* fs.remove(destination, { recursive: true, force: true });
335 yield* fs.rename(unpacked, destination);
336 }).pipe(Effect.scoped);
337 // Older builds and abandoned staging directories. Two servers can share a
338 // home, so a staging directory touched within the last hour may be another
339 // server's install in progress and stays.
340 const entries = yield* fs.readDirectory(installRoot);
341 const now = yield* Clock.currentTimeMillis;
342 yield* Effect.forEach(
343 entries.filter((name) => name !== release.version),
344 (name) =>
345 Effect.gen(function* () {
346 const target = path.join(installRoot, name);
347 if (name.startsWith(".install-")) {
348 const info = yield* fs.stat(target);
349 const modifiedAt = Option.match(info.mtime, {
350 onNone: () => now,
351 onSome: (date) => date.getTime(),
352 });
353 if (now - modifiedAt < STAGING_STALE_AFTER_MS) return;
354 }
355 yield* fs.remove(target, { recursive: true, force: true });
356 }).pipe(
357 Effect.catch((cause) =>
358 Effect.logWarning("Could not remove an old preview browser.", { name, cause }),
359 ),
360 ),
361 { discard: true },
362 );
363 return path.join(installRoot, release.version, executableName);
364 },
365 Effect.mapError(wrapFailure("Could not save the browser in T3's home directory.")),
366 );
367
368 // Joins the current install or starts one. A failure is reported once, then cleared.
369 const join = (release: PreviewBrowserRelease) =>
370 gate.withPermit(
371 Effect.gen(function* () {
372 if (state._tag === "installing") return state;
373 if (state._tag === "failed") {
374 const failed = state;
375 state = { _tag: "idle" };
376 return failed;
377 }
378 const installed = yield* installedExecutable(release);
379 if (Option.isSome(installed)) {
380 state = { _tag: "installed", executable: installed.value };
381 return state;
382 }
383 const done = yield* Deferred.make<string, PreviewBrowserInstallError>();
384 progress.downloadedBytes = 0;
385 progress.unpacking = false;
386 const installing: InstallState = { _tag: "installing", done };
387 state = installing;
388 yield* install(release).pipe(
389 Effect.onExit((exit) =>
390 gate
391 .withPermit(
392 Effect.sync(() => {
393 state = Exit.isSuccess(exit)
394 ? { _tag: "installed", executable: exit.value }
395 : {
396 _tag: "failed",
397 error: Option.getOrElse(
398 Cause.findErrorOption(exit.cause),
399 () => new PreviewBrowserInstallError({ detail: "The install stopped." }),
400 ),
401 };
402 }),
403 )
404 .pipe(Effect.andThen(Deferred.done(done, exit))),
405 ),
406 Effect.ignoreCause,
407 // Server shutdown closes the service scope and stops an install in progress.
408 Effect.interruptible,
409 Effect.forkIn(serviceScope),
410 );
411 return installing;
412 }),
413 );
414
415 // A waiter that saw the failure has reported it; the next call retries.
416 const clearFailure = (error: PreviewBrowserInstallError) =>
417 gate.withPermit(
418 Effect.sync(() => {
419 if (state._tag === "failed" && state.error === error) state = { _tag: "idle" };
420 }),
421 );
422
423 const executable = Effect.gen(function* () {
424 if (release === null) {
425 return yield* new PreviewBrowserUnsupportedError({ platform, arch });
426 }
427 const current = yield* join(release);
428 switch (current._tag) {
429 case "installed":
430 return current.executable;
431 case "failed":
432 return yield* current.error;
433 case "installing":
434 return yield* Deferred.await(current.done).pipe(
435 Effect.tapError(clearFailure),
436 Effect.timeoutOrElse({
437 duration: wait,
438 orElse: () =>
439 Effect.fail(
440 new PreviewBrowserInstallingError({
441 downloadedBytes: progress.downloadedBytes,
442 totalBytes: release.bytes,
443 unpacking: progress.unpacking,
444 }),
445 ),
446 }),
447 );
448 }
449 }).pipe(Effect.withSpan("PreviewBrowser.executable"));
450
451 const installed = release === null ? Effect.succeedNone : installedExecutable(release);
452
453 return PreviewBrowser.of({ executable, installed });
454});
455
456export const layer = Layer.effect(
457 PreviewBrowser,
458 Effect.gen(function* () {
459 const config = yield* ServerConfig.ServerConfig;
460 return yield* makePreviewBrowser({ baseDir: config.baseDir });
461 }),
462);