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

headlessChrome.ts

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