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

PreviewBrowser.test.ts

201 lines8.1 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { expect, it } from "@effect/vitest";
3import * as HostProcess from "@t3tools/shared/HostProcess";
4import * as Crypto from "effect/Crypto";
5import type * as Duration from "effect/Duration";
6import * as DateTime from "effect/DateTime";
7import * as Effect from "effect/Effect";
8import * as Hex from "effect/encoding/Hex";
9import * as FileSystem from "effect/FileSystem";
10import * as Option from "effect/Option";
11import * as Path from "effect/Path";
12import * as Stream from "effect/Stream";
13import { HttpClient, HttpClientResponse } from "effect/http";
14import * as NodeZlib from "node:zlib";
15​
16import * as PreviewBrowser from "./PreviewBrowser.ts";
17​
18// NTFS cannot enforce POSIX modes; choose the host platform.
19const hostPlatform: NodeJS.Platform =
20 HostProcess.Platform.defaultValue() === "win32" ? "win32" : "linux";
21const executableName =
22 hostPlatform === "win32" ? "chrome-headless-shell.exe" : "chrome-headless-shell";
23const ROOT = "chrome-headless-shell-fixture/";
24​
25const makeZip = (
26 entries: ReadonlyArray<{ readonly name: string; readonly data?: string; readonly mode: number }>,
27) => {
28 const records: Array<Buffer> = [];
29 const directory: Array<Buffer> = [];
30 let offset = 0;
31 for (const entry of entries) {
32 const name = Buffer.from(entry.name);
33 const data = Buffer.from(entry.data ?? "");
34 const crc = NodeZlib.crc32(data);
35 const local = Buffer.alloc(30);
36 local.writeUInt32LE(0x04034b50, 0);
37 local.writeUInt16LE(20, 4);
38 local.writeUInt32LE(crc, 14);
39 local.writeUInt32LE(data.length, 18);
40 local.writeUInt32LE(data.length, 22);
41 local.writeUInt16LE(name.length, 26);
42 const central = Buffer.alloc(46);
43 central.writeUInt32LE(0x02014b50, 0);
44 central.writeUInt16LE((3 << 8) | 20, 4);
45 central.writeUInt16LE(20, 6);
46 central.writeUInt32LE(crc, 16);
47 central.writeUInt32LE(data.length, 20);
48 central.writeUInt32LE(data.length, 24);
49 central.writeUInt16LE(name.length, 28);
50 central.writeUInt32LE((entry.mode << 16) >>> 0, 38);
51 central.writeUInt32LE(offset, 42);
52 records.push(local, name, data);
53 directory.push(central, name);
54 offset += local.length + name.length + data.length;
55 }
56 const centralDirectory = Buffer.concat(directory);
57 const end = Buffer.alloc(22);
58 end.writeUInt32LE(0x06054b50, 0);
59 end.writeUInt16LE(entries.length, 8);
60 end.writeUInt16LE(entries.length, 10);
61 end.writeUInt32LE(centralDirectory.length, 12);
62 end.writeUInt32LE(offset, 16);
63 return Buffer.concat([...records, centralDirectory, end]);
64};
65​
66const browserArchive = makeZip([
67 { name: ROOT, mode: 0o40755 },
68 { name: `${ROOT}${executableName}`, data: "#!/bin/sh\n", mode: 0o100755 },
69 { name: `${ROOT}libEGL.so`, data: "library", mode: 0o100755 },
70 { name: `${ROOT}locales/`, mode: 0o40755 },
71 { name: `${ROOT}locales/en-US.pak`, data: "strings", mode: 0o100644 },
72]);
73​
74const makeHarness = Effect.fn("test.makePreviewBrowser")(function* (
75 options: {
76 readonly archive?: Buffer;
77 readonly sha256?: string;
78 readonly body?: Stream.Stream<Uint8Array>;
79 readonly wait?: Duration.Input;
80 readonly unsupported?: boolean;
81 } = {},
82) {
83 const fs = yield* FileSystem.FileSystem;
84 const path = yield* Path.Path;
85 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-preview-browser-test-" });
86 const archive = options.archive ?? browserArchive;
87 const crypto = yield* Crypto.Crypto;
88 const sha256 =
89 options.sha256 ?? Hex.encode(yield* crypto.digest("SHA-256", archive).pipe(Effect.orDie));
90 const requests: Array<string> = [];
91 const browser = yield* PreviewBrowser.makePreviewBrowser({
92 baseDir,
93 release: options.unsupported
94 ? null
95 : {
96 version: "1.2.3",
97 platform: "fixture",
98 url: "https://storage.googleapis.com/chrome-headless-shell-fixture.zip",
99 bytes: archive.byteLength,
100 sha256,
101 },
102 ...(options.wait === undefined ? {} : { wait: options.wait }),
103 }).pipe(
104 Effect.provideService(HostProcess.Platform, hostPlatform),
105 Effect.provideService(HostProcess.Architecture, "x64"),
106 Effect.provideService(
107 HttpClient.HttpClient,
108 HttpClient.make((request) =>
109 Effect.sync(() => {
110 requests.push(request.url);
111 const response = HttpClientResponse.fromWeb(request, new Response(null));
112 return Object.defineProperty(response, "stream", {
113 value: options.body ?? Stream.make(archive.subarray(0, 40), archive.subarray(40)),
114 });
115 }),
116 ),
117 ),
118 );
119 const installRoot = path.join(baseDir, "tools", "chrome-headless-shell", "fixture");
120 return { browser, fs, path, baseDir, installRoot, requests };
121});
122​
123it.layer(NodeServices.layer)("PreviewBrowser", (it) => {
124 it.effect("installs a verified download with its file modes and then reuses it", () =>
125 Effect.gen(function* () {
126 const { browser, fs, path, installRoot, requests } = yield* makeHarness();
127 yield* fs.makeDirectory(path.join(installRoot, "1.0.0"), { recursive: true });
128 const active = path.join(installRoot, ".install-other");
129 const abandoned = path.join(installRoot, ".install-abandoned");
130 yield* fs.makeDirectory(active);
131 yield* fs.makeDirectory(abandoned);
132 const twoHoursAgo = DateTime.toDate(DateTime.subtract(yield* DateTime.now, { hours: 2 }));
133 yield* fs.utimes(abandoned, twoHoursAgo, twoHoursAgo);
134 expect(yield* browser.installed).toEqual(Option.none());
135​
136 const executable = yield* browser.executable;
137​
138 const version = path.join(installRoot, "1.2.3");
139 expect(executable).toBe(path.join(version, executableName));
140 expect(yield* fs.readFileString(path.join(version, "locales", "en-US.pak"))).toBe("strings");
141 if (hostPlatform !== "win32") {
142 const mode = (file: string) =>
143 fs.stat(path.join(version, file)).pipe(Effect.map((info) => info.mode & 0o777));
144 expect(yield* mode(executableName)).toBe(0o755);
145 expect(yield* mode("libEGL.so")).toBe(0o755);
146 expect(yield* mode(path.join("locales", "en-US.pak"))).toBe(0o644);
147 }
148 expect((yield* fs.readDirectory(installRoot)).toSorted()).toEqual([
149 ".install-other",
150 "1.2.3",
151 ]);
152 expect(yield* browser.executable).toBe(executable);
153 expect(yield* browser.installed).toEqual(Option.some(executable));
154 expect(requests).toHaveLength(1);
155 }),
156 );
157​
158 it.effect.each([
159 { name: "a hash mismatch", sha256: "0".repeat(64) },
160 { name: "a short download", body: Stream.make(browserArchive.subarray(0, -1)) },
161 {
162 name: "an oversized download",
163 body: Stream.make(browserArchive, Buffer.from("extra")),
164 },
165 ])("rejects $name, installs nothing, and retries on the next call", (testCase) =>
166 Effect.gen(function* () {
167 const { browser, fs, installRoot, requests } = yield* makeHarness(testCase);
168​
169 const error = yield* browser.executable.pipe(Effect.flip);
170​
171 expect(error._tag).toBe("PreviewBrowserInstallError");
172 expect(error.message).toMatch(/^T3 could not install its headless browser: .+ Try again\.$/);
173 expect(yield* fs.readDirectory(installRoot)).toEqual([]);
174 yield* browser.executable.pipe(Effect.flip);
175 expect(requests).toHaveLength(2);
176 }),
177 );
178​
179 it.effect.each([
180 { name: "a parent-directory entry", entry: `${ROOT}../escape` },
181 { name: "an absolute entry", entry: "/escape" },
182 { name: "an entry outside the top directory", entry: "escape" },
183 ])("rejects an archive with $name", (testCase) =>
184 Effect.gen(function* () {
185 const { browser, fs, path, baseDir, installRoot } = yield* makeHarness({
186 archive: makeZip([
187 { name: `${ROOT}${executableName}`, data: "#!/bin/sh\n", mode: 0o100755 },
188 { name: testCase.entry, data: "escaped", mode: 0o100644 },
189 ]),
190 });
191​
192 const error = yield* browser.executable.pipe(Effect.flip);
193​
194 expect(error._tag).toBe("PreviewBrowserInstallError");
195 expect(yield* fs.readDirectory(installRoot)).toEqual([]);
196 expect(yield* fs.exists(path.join(baseDir, "tools", "chrome-headless-shell", "escape"))).toBe(
197 false,
198 );
199 }),
200 );
201});