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

headlessChrome.ts

609 lines22.1 KB

1import * as Deferred from "effect/Deferred";
2import * as Effect from "effect/Effect";
3import * as Fiber from "effect/Fiber";
4import * as FileSystem from "effect/FileSystem";
5import * as Option from "effect/Option";
6import * as Path from "effect/Path";
7import * as Queue from "effect/Queue";
8import * as Schema from "effect/Schema";
9import * as Stream from "effect/Stream";
10import * as ChildProcess from "effect/process/ChildProcess";
11import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
12​
13import { publicProxy } from "./publicProxy.ts";
14​
15export class HtmlRenderBrowserError extends Schema.TaggedError<HtmlRenderBrowserError>()(
16 "HtmlRenderBrowserError",
17 { reason: Schema.String, cause: Schema.optional(Schema.Defect()) },
18) {
19 override get message(): string {
20 return `Headless Chrome could not render the page: ${this.reason}.`;
21 }
23​
24/** The browser died at startup because this host cannot give it a sandbox. */
25export class HtmlRenderSandboxUnavailableError extends Schema.TaggedError<HtmlRenderSandboxUnavailableError>()(
26 "HtmlRenderSandboxUnavailableError",
27 {},
28) {
29 override get message(): string {
30 return "Chrome's sandbox is unavailable on this host.";
31 }
33​
34type BrowserFailure = HtmlRenderBrowserError | HtmlRenderSandboxUnavailableError;
35​
36export interface ConsoleMessage {
37 readonly level: "log" | "info" | "warning" | "error";
38 readonly text: string;
40​
41const MAX_CONSOLE_MESSAGES = 20;
42const MAX_CONSOLE_TEXT_CHARS = 500;
43const VIEWPORT_HEIGHT = 800;
44const MAX_CAPTURE_HEIGHT = 4_000;
45const CAPTURE_TIMEOUT = "20 seconds";
46// Pages load from this made-up web origin, never from a file. Chrome refuses
47// local files to every web page, frame, worker, and popup, so a page cannot
48// read files the agent's provider withholds; local images reach it already
49// inlined as data URIs. `.localhost` keeps it a secure context that may still
50// load plain-http resources, and the request never leaves the browser.
51// All of the browser's traffic goes through `publicProxy`, which only reaches
52// public addresses, so a page cannot reach this machine's local network. The
53// main frame also stays on the page and the browser opens no popups, so a
54// capture always shows the page itself.
55const PAGE_ORIGIN = "http://t3-page.localhost";
56const PAGE_URL = `${PAGE_ORIGIN}/page.html`;
57// Stack traces and load errors name the page this way instead of its URL.
58const PAGE_NAME = "page.html";
59// Each measuring load reads its own copy of the page off the pipe.
60const MEASURE_CONCURRENCY = 3;
61​
62const textEncoder = new TextEncoder();
63​
64/**
65 * A page as the base64 bytes `PAGE_URL` serves, encoded once however often it
66 * loads. Node's encoder, since pages run to 25 MiB.
67 */
68const pageBody = (html: string) =>
69 Buffer.from(Buffer.from(html, "utf8").toString("base64"), "latin1");
70// What Chrome prints before aborting when it cannot sandbox itself, e.g. on
71// Ubuntu 23.10+ where AppArmor restricts unprivileged user namespaces.
72const NO_SANDBOX_SIGNATURE = "No usable sandbox";
73​
74const CdpMessage = Schema.fromJsonString(
75 Schema.Struct({
76 id: Schema.optional(Schema.Number),
77 method: Schema.optional(Schema.String),
78 sessionId: Schema.optional(Schema.String),
79 params: Schema.optional(Schema.Unknown),
80 result: Schema.optional(Schema.Unknown),
81 error: Schema.optional(Schema.Struct({ message: Schema.String })),
82 }),
83);
84const decodeCdpMessage = Schema.decodeUnknownOption(CdpMessage);
85const encodeCdpCommand = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
86const RemoteObject = Schema.Struct({
87 type: Schema.String,
88 value: Schema.optional(Schema.Unknown),
89 description: Schema.optional(Schema.String),
90});
91const decodeConsoleApiCalled = Schema.decodeUnknownOption(
92 Schema.Struct({ type: Schema.String, args: Schema.Array(RemoteObject) }),
93);
94const decodeExceptionThrown = Schema.decodeUnknownOption(
95 Schema.Struct({
96 exceptionDetails: Schema.Struct({
97 text: Schema.String,
98 exception: Schema.optional(RemoteObject),
99 }),
100 }),
101);
102const decodeRequestPaused = Schema.decodeUnknownOption(
103 Schema.Struct({
104 requestId: Schema.String,
105 request: Schema.Struct({ url: Schema.String }),
106 frameId: Schema.optional(Schema.String),
107 resourceType: Schema.optional(Schema.String),
108 }),
109);
110const decodeLogEntryAdded = Schema.decodeUnknownOption(
111 Schema.Struct({
112 entry: Schema.Struct({
113 level: Schema.String,
114 text: Schema.String,
115 url: Schema.optional(Schema.String),
116 }),
117 }),
118);
119​
120const remoteObjectText = (value: typeof RemoteObject.Type) =>
121 typeof value.value === "string"
122 ? value.value
123 : (value.description ?? (value.value === undefined ? value.type : String(value.value)));
124​
125const CONSOLE_LEVELS: Readonly<Record<string, ConsoleMessage["level"]>> = {
126 log: "log",
127 debug: "log",
128 dir: "log",
129 dirxml: "log",
130 table: "log",
131 trace: "log",
132 info: "info",
133 warning: "warning",
134 error: "error",
135 assert: "error",
136};
137​
138/** Everything the page logs, uncaught exceptions, and the browser's own load errors. */
139const consoleMessageFromEvent = (method: string, params: unknown): ConsoleMessage | undefined => {
140 if (method === "Runtime.consoleAPICalled") {
141 const event = Option.getOrUndefined(decodeConsoleApiCalled(params));
142 const level = event === undefined ? undefined : CONSOLE_LEVELS[event.type];
143 return event && level ? { level, text: event.args.map(remoteObjectText).join(" ") } : undefined;
144 }
145 if (method === "Runtime.exceptionThrown") {
146 const details = Option.getOrUndefined(decodeExceptionThrown(params))?.exceptionDetails;
147 return details
148 ? { level: "error", text: details.exception?.description ?? details.text }
149 : undefined;
150 }
151 if (method === "Log.entryAdded") {
152 const entry = Option.getOrUndefined(decodeLogEntryAdded(params))?.entry;
153 return entry && (entry.level === "error" || entry.level === "warning")
154 ? { level: entry.level, text: entry.url ? `${entry.text} ${entry.url}` : entry.text }
155 : undefined;
156 }
157 return undefined;
158};
159​
160// Resolves after web fonts load and two frames paint, so late layout lands in the capture.
161const SETTLE_EXPRESSION =
162 "document.fonts.ready.then(() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => resolve(true)))))";
163// The root's scroll height never drops below the viewport, so a short page
164// reports its own box height instead.
165const MEASURE_EXPRESSION =
166 "(() => { const root = document.documentElement; return root.scrollHeight > root.clientHeight ? root.scrollHeight : root.getBoundingClientRect().height; })()";
167​
168const Ignored = Schema.Unknown;
169const Navigation = Schema.Struct({ errorText: Schema.optional(Schema.String) });
170const Measured = Schema.Struct({ result: Schema.Struct({ value: Schema.Finite }) });
171​
172interface PageEvents {
173 /** The page's main frame, which only ever shows `PAGE_URL`. */
174 readonly mainFrameId: string;
175 /** The page served for `PAGE_URL`, from `pageBody`. */
176 body: Uint8Array | undefined;
177 loaded: Deferred.Deferred<void, BrowserFailure> | undefined;
178 readonly consoleMessages: Array<ConsoleMessage>;
179 omittedConsoleMessages: number;
181​
182/**
183 * Starts the headless shell for the life of the scope, speaking CDP over
184 * `--remote-debugging-pipe` (fd 3 in, fd 4 out, NUL-delimited JSON). Scope
185 * close kills the process group. Each page is its own target, so pages load
186 * in parallel.
187 */
188const launchBrowser = Effect.fnUntraced(function* (input: {
189 readonly executable: string;
190 readonly noSandbox: boolean;
191 readonly profileDirectory: string;
192}) {
193 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
194 const proxyPort = yield* publicProxy.pipe(
195 Effect.mapError(
196 (cause) => new HtmlRenderBrowserError({ reason: "the preview proxy could not start", cause }),
197 ),
198 );
199 const outgoing = yield* Queue.unbounded<Uint8Array>();
200 const child = yield* spawner
201 .spawn(
202 ChildProcess.make(
203 input.executable,
204 [
205 "--headless=new",
206 "--remote-debugging-pipe",
207 "--no-first-run",
208 "--no-default-browser-check",
209 "--disable-gpu",
210 "--hide-scrollbars",
211 "--mute-audio",
212 "--block-new-web-contents",
213 `--proxy-server=socks5://127.0.0.1:${proxyPort}`,
214 // Loopback would otherwise skip the proxy.
215 "--proxy-bypass-list=<-loopback>",
216 // WebRTC would otherwise send UDP, which no proxy carries.
217 "--force-webrtc-ip-handling-policy=disable_non_proxied_udp",
218 ...(input.noSandbox ? ["--no-sandbox"] : []),
219 `--user-data-dir=${input.profileDirectory}`,
220 "about:blank",
221 ],
222 {
223 stdin: "ignore",
224 stdout: "ignore",
225 stderr: "pipe",
226 forceKillAfter: "2 seconds",
227 additionalFds: {
228 fd3: { type: "input", stream: Stream.fromQueue(outgoing) },
229 fd4: { type: "output" },
230 },
231 },
232 ),
233 )
234 .pipe(
235 Effect.mapError(
236 (cause) =>
237 new HtmlRenderBrowserError({ reason: "the browser could not be started", cause }),
238 ),
239 );
240​
241 let stderrTail = "";
242 let sandboxUnavailable = false;
243 const stderrReader = yield* child.stderr.pipe(
244 Stream.decodeText(),
245 Stream.runForEach((text) =>
246 Effect.sync(() => {
247 stderrTail = (stderrTail + text).slice(-1_024);
248 if (stderrTail.includes(NO_SANDBOX_SIGNATURE)) sandboxUnavailable = true;
249 }),
250 ),
251 Effect.ignore,
252 Effect.forkScoped,
253 );
254​
255 const pending = new Map<
256 number,
257 { readonly method: string; readonly reply: Deferred.Deferred<unknown, BrowserFailure> }
258 >();
259 const pages = new Map<string, PageEvents>();
260 let disconnected: BrowserFailure | undefined;
261 let nextId = 0;
262​
263 // A command whose reply nobody awaits; `receive` drops replies without a waiter.
264 const post = (method: string, params: Record<string, unknown>, sessionId: string) =>
265 Queue.offer(
266 outgoing,
267 new TextEncoder().encode(
268 `${encodeCdpCommand({ id: ++nextId, method, params, sessionId })}\0`,
269 ),
270 ).pipe(Effect.asVoid);
271​
272 // Serves the page. Its body is shared bytes between two small JSON halves,
273 // queued together, so loading a page of up to 25 MiB at several widths never
274 // copies it on this side.
275 const fulfillPage = (sessionId: string, requestId: string, body: Uint8Array) =>
276 Queue.offerAll(outgoing, [
277 textEncoder.encode(
278 `{"id":${++nextId},"sessionId":${JSON.stringify(sessionId)},"method":"Fetch.fulfillRequest","params":{"requestId":${JSON.stringify(requestId)},"responseCode":200,"responseHeaders":[{"name":"Content-Type","value":"text/html; charset=utf-8"}],"body":"`,
279 ),
280 body,
281 textEncoder.encode('"}}\0'),
282 ]).pipe(Effect.asVoid);
283​
284 const receive = (raw: string) => {
285 const message = Option.getOrUndefined(decodeCdpMessage(raw));
286 if (message?.id !== undefined) {
287 const waiter = pending.get(message.id);
288 pending.delete(message.id);
289 if (!waiter) return Effect.void;
290 return message.error
291 ? Deferred.fail(
292 waiter.reply,
293 new HtmlRenderBrowserError({
294 reason: `${waiter.method} failed`,
295 cause: message.error.message,
296 }),
297 )
298 : Deferred.succeed(waiter.reply, message.result);
299 }
300 const sessionId = message?.sessionId;
301 const page = sessionId === undefined ? undefined : pages.get(sessionId);
302 if (sessionId === undefined || !page || !message?.method) return Effect.void;
303 if (message.method === "Page.loadEventFired") {
304 return page.loaded ? Deferred.succeed(page.loaded, undefined) : Effect.void;
305 }
306 if (message.method === "Fetch.requestPaused") {
307 const paused = Option.getOrUndefined(decodeRequestPaused(message.params));
308 if (!paused) return Effect.void;
309 const body = page.body;
310 const url = paused.request.url.split("#", 1)[0]!;
311 if (url === PAGE_URL && body !== undefined) {
312 return fulfillPage(sessionId, paused.requestId, body);
313 }
314 // A frame inside the page may show another site; Local Network Access
315 // still covers it. The main frame and T3's own origin serve nothing else.
316 const otherSiteFrame =
317 paused.resourceType === "Document" &&
318 paused.frameId !== page.mainFrameId &&
319 !url.startsWith(`${PAGE_ORIGIN}/`);
320 return otherSiteFrame
321 ? post("Fetch.continueRequest", { requestId: paused.requestId }, sessionId)
322 : post(
323 "Fetch.failRequest",
324 { requestId: paused.requestId, errorReason: "AccessDenied" },
325 sessionId,
326 );
327 }
328 const consoleMessage = consoleMessageFromEvent(message.method, message.params);
329 if (!consoleMessage) return Effect.void;
330 if (page.consoleMessages.length >= MAX_CONSOLE_MESSAGES) {
331 page.omittedConsoleMessages += 1;
332 return Effect.void;
333 }
334 const text = consoleMessage.text.replaceAll(PAGE_URL, PAGE_NAME);
335 page.consoleMessages.push({
336 level: consoleMessage.level,
337 text:
338 text.length > MAX_CONSOLE_TEXT_CHARS ? `${text.slice(0, MAX_CONSOLE_TEXT_CHARS)}…` : text,
339 });
340 return Effect.void;
341 };
342​
343 // The pipe closes when the browser exits. A sandbox abort says why on
344 // stderr, which may still be draining, so give it a moment.
345 const disconnect = Effect.gen(function* () {
346 yield* Fiber.await(stderrReader).pipe(Effect.timeout("1 second"), Effect.ignore);
347 const error = sandboxUnavailable
348 ? new HtmlRenderSandboxUnavailableError()
349 : new HtmlRenderBrowserError({ reason: "the browser exited unexpectedly" });
350 disconnected = error;
351 const waiters = [...pending.values()];
352 pending.clear();
353 yield* Effect.forEach(waiters, ({ reply }) => Deferred.fail(reply, error), { discard: true });
354 yield* Effect.forEach(
355 pages.values(),
356 (page) => (page.loaded ? Deferred.fail(page.loaded, error) : Effect.void),
357 { discard: true },
358 );
359 });
360​
361 // Decoded text chunks may split a message anywhere, and a screenshot reply spans many.
362 let partial: Array<string> = [];
363 yield* child.getOutputFd(4).pipe(
364 Stream.decodeText(),
365 Stream.runForEach((text) => {
366 const complete: Array<string> = [];
367 let start = 0;
368 for (let end = text.indexOf("\0"); end !== -1; end = text.indexOf("\0", start)) {
369 partial.push(text.slice(start, end));
370 complete.push(partial.join(""));
371 partial = [];
372 start = end + 1;
373 }
374 if (start < text.length) partial.push(text.slice(start));
375 return Effect.forEach(complete, receive, { discard: true });
376 }),
377 Effect.ignore,
378 // Interruption means the scope is closing on purpose; only an exit disconnects.
379 Effect.andThen(disconnect),
380 Effect.forkScoped,
381 );
382​
383 const send = <A>(
384 method: string,
385 params: Record<string, unknown>,
386 result: Schema.Decoder<A>,
387 sessionId?: string,
388 ) =>
389 Effect.gen(function* () {
390 if (disconnected) return yield* disconnected;
391 const id = ++nextId;
392 const reply = yield* Deferred.make<unknown, BrowserFailure>();
393 pending.set(id, { method, reply });
394 const message = encodeCdpCommand({ id, method, params, ...(sessionId ? { sessionId } : {}) });
395 yield* Queue.offer(outgoing, new TextEncoder().encode(`${message}\0`));
396 return yield* Deferred.await(reply).pipe(
397 Effect.flatMap(Schema.decodeUnknownEffect(result)),
398 Effect.mapError((error) =>
399 error._tag === "HtmlRenderBrowserError" ||
400 error._tag === "HtmlRenderSandboxUnavailableError"
401 ? error
402 : new HtmlRenderBrowserError({
403 reason: `${method} returned an unexpected result`,
404 cause: error,
405 }),
406 ),
407 );
408 });
409​
410 /** A fresh page at `width`; each `load` navigates it and measures the settled layout. */
411 const openPage = Effect.fnUntraced(function* (width: number) {
412 const { targetId } = yield* send(
413 "Target.createTarget",
414 { url: "about:blank" },
415 Schema.Struct({ targetId: Schema.String }),
416 );
417 const { sessionId } = yield* send(
418 "Target.attachToTarget",
419 { targetId, flatten: true },
420 Schema.Struct({ sessionId: Schema.String }),
421 );
422 const events: PageEvents = {
423 // A page target's id is its main frame's id.
424 mainFrameId: targetId,
425 body: undefined,
426 loaded: undefined,
427 consoleMessages: [],
428 omittedConsoleMessages: 0,
429 };
430 pages.set(sessionId, events);
431 yield* send("Page.enable", {}, Ignored, sessionId);
432 yield* send("Runtime.enable", {}, Ignored, sessionId);
433 yield* send("Log.enable", {}, Ignored, sessionId);
434 // Previews have no use for WebRTC, whose ICE servers can make the browser
435 // resolve names outside the proxy. Runs before page scripts in every frame.
436 yield* send(
437 "Page.addScriptToEvaluateOnNewDocument",
438 {
439 source: "delete window.RTCPeerConnection; delete window.webkitRTCPeerConnection;",
440 runImmediately: true,
441 },
442 Ignored,
443 sessionId,
444 );
445 // Pauses T3's own origin, to serve the page, and every document, to keep
446 // the main frame on it.
447 yield* send(
448 "Fetch.enable",
449 {
450 patterns: [
451 { urlPattern: `${PAGE_ORIGIN}/*` },
452 { urlPattern: "*", resourceType: "Document" },
453 ],
454 },
455 Ignored,
456 sessionId,
457 );
458 yield* send(
459 "Emulation.setDeviceMetricsOverride",
460 { width, height: VIEWPORT_HEIGHT, deviceScaleFactor: 1, mobile: false },
461 Ignored,
462 sessionId,
463 );
464​
465 /** Loads a page from `pageBody`, so callers loading it often encode it once. */
466 const load = Effect.fnUntraced(function* (body: Uint8Array, urlFragment: string) {
467 const loaded = yield* Deferred.make<void, BrowserFailure>();
468 events.body = body;
469 events.loaded = loaded;
470 const navigation = yield* send(
471 "Page.navigate",
472 { url: `${PAGE_URL}${urlFragment}` },
473 Navigation,
474 sessionId,
475 );
476 if (navigation.errorText) {
477 return yield* new HtmlRenderBrowserError({ reason: "the page could not be opened" });
478 }
479 yield* Deferred.await(loaded);
480 yield* send(
481 "Runtime.evaluate",
482 { expression: SETTLE_EXPRESSION, awaitPromise: true },
483 Ignored,
484 sessionId,
485 );
486 const measured = yield* send(
487 "Runtime.evaluate",
488 { expression: MEASURE_EXPRESSION, returnByValue: true },
489 Measured,
490 sessionId,
491 );
492 return Math.max(0, Math.ceil(measured.result.value));
493 });
494​
495 const screenshot = (height: number) =>
496 send(
497 "Page.captureScreenshot",
498 {
499 format: "png",
500 captureBeyondViewport: true,
501 clip: { x: 0, y: 0, width, height, scale: 1 },
502 },
503 Schema.Struct({ data: Schema.String }),
504 sessionId,
505 ).pipe(Effect.map(({ data }) => data));
506​
507 const consoleMessages = (): ReadonlyArray<ConsoleMessage> =>
508 events.omittedConsoleMessages === 0
509 ? [...events.consoleMessages]
510 : [
511 ...events.consoleMessages,
512 {
513 level: "warning",
514 text: `${events.omittedConsoleMessages} more console messages were omitted.`,
515 },
516 ];
517​
518 // Frees the page in the browser once it is no longer needed.
519 const close = send("Target.closeTarget", { targetId }, Ignored).pipe(
520 Effect.ensuring(Effect.sync(() => pages.delete(sessionId))),
521 Effect.ignore,
522 );
523​
524 return { load, screenshot, consoleMessages, close };
525 });
526​
527 return { openPage };
528});
529​
530/** A temporary directory for the browser profile, removed with the scope. */
531const scratchDirectory = Effect.gen(function* () {
532 const fileSystem = yield* FileSystem.FileSystem;
533 return yield* Effect.acquireRelease(
534 fileSystem.makeTempDirectory({ prefix: "t3-html-preview-" }),
535 (directory) => fileSystem.remove(directory, { recursive: true }).pipe(Effect.ignore),
536 ).pipe(
537 Effect.mapError(
538 (cause) =>
539 new HtmlRenderBrowserError({ reason: "a temporary directory could not be created", cause }),
540 ),
541 );
542});
543​
544/** Loads `html` at `width` and returns a PNG of the top of the page. */
545export const captureHtmlScreenshot = Effect.fn("headlessChrome.captureHtmlScreenshot")(
546 function* (input: {
547 readonly executable: string;
548 readonly noSandbox: boolean;
549 readonly html: string;
550 readonly width: number;
551 readonly urlFragment: string;
552 }) {
553 const path = yield* Path.Path;
554 const directory = yield* scratchDirectory;
555 const browser = yield* launchBrowser({
556 executable: input.executable,
557 noSandbox: input.noSandbox,
558 profileDirectory: path.join(directory, "profile"),
559 });
560 const page = yield* browser.openPage(input.width);
561 const contentHeight = yield* page.load(pageBody(input.html), input.urlFragment);
562 const capturedHeight = Math.max(1, Math.min(contentHeight, MAX_CAPTURE_HEIGHT));
563 const png = yield* page.screenshot(capturedHeight);
564 return { png, contentHeight, capturedHeight, consoleMessages: page.consoleMessages() };
565 },
566 Effect.scoped,
567 Effect.timeoutOrElse({
568 duration: CAPTURE_TIMEOUT,
569 orElse: () =>
570 Effect.fail(
571 new HtmlRenderBrowserError({
572 reason: `the page did not finish loading within ${CAPTURE_TIMEOUT}`,
573 }),
574 ),
575 }),
576);
577​
578/**
579 * Content heights of the page at each width, each from a fresh load, since
580 * pages often lay themselves out from the width once at load. One browser,
581 * a few widths at a time.
582 */
583export const measureHtmlHeights = Effect.fn("headlessChrome.measureHtmlHeights")(function* (input: {
584 readonly executable: string;
585 readonly noSandbox: boolean;
586 readonly html: string;
587 readonly widths: ReadonlyArray<number>;
588 readonly urlFragment: string;
589}) {
590 const path = yield* Path.Path;
591 const directory = yield* scratchDirectory;
592 const browser = yield* launchBrowser({
593 executable: input.executable,
594 noSandbox: input.noSandbox,
595 profileDirectory: path.join(directory, "profile"),
596 });
597 const body = pageBody(input.html);
598 return yield* Effect.forEach(
599 input.widths,
600 (width) =>
601 browser.openPage(width).pipe(
602 Effect.flatMap((page) =>
603 page.load(body, input.urlFragment).pipe(Effect.ensuring(page.close)),
604 ),
605 Effect.map((height) => [width, height] as const),
606 ),
607 { concurrency: MEASURE_CONCURRENCY },
608 );
609}, Effect.scoped);