Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

PreviewBrowser.ts

449 lines16.9 KB

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