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

PreviewBrowser.test.ts

292 lines11.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 Deferred from "effect/Deferred";
5import * as Crypto from "effect/Crypto";
6import type * as Duration from "effect/Duration";
7import * as DateTime from "effect/DateTime";
8import * as Effect from "effect/Effect";
9import * as Hex from "effect/encoding/Hex";
10import * as Fiber from "effect/Fiber";
11import * as FileSystem from "effect/FileSystem";
12import * as Option from "effect/Option";
13import * as Path from "effect/Path";
14import * as Stream from "effect/Stream";
15import * as TestClock from "effect/testing/TestClock";
16import { HttpClient, HttpClientResponse } from "effect/http";
17import * as NodeZlib from "node:zlib";
18​
19import * as PreviewBrowser from "./PreviewBrowser.ts";
20​
21// POSIX modes cannot be checked on NTFS, so follow the host like the Antigravity suite.
22const hostPlatform: NodeJS.Platform =
23 HostProcess.Platform.defaultValue() === "win32" ? "win32" : "linux";
24const executableName =
25 hostPlatform === "win32" ? "chrome-headless-shell.exe" : "chrome-headless-shell";
26const ROOT = "chrome-headless-shell-fixture/";
27​
28const makeZip = (
29 entries: ReadonlyArray<{ readonly name: string; readonly data?: string; readonly mode: number }>,
30) => {
31 const records: Array<Buffer> = [];
32 const directory: Array<Buffer> = [];
33 let offset = 0;
34 for (const entry of entries) {
35 const name = Buffer.from(entry.name);
36 const data = Buffer.from(entry.data ?? "");
37 const crc = NodeZlib.crc32(data);
38 const local = Buffer.alloc(30);
39 local.writeUInt32LE(0x04034b50, 0);
40 local.writeUInt16LE(20, 4);
41 local.writeUInt32LE(crc, 14);
42 local.writeUInt32LE(data.length, 18);
43 local.writeUInt32LE(data.length, 22);
44 local.writeUInt16LE(name.length, 26);
45 const central = Buffer.alloc(46);
46 central.writeUInt32LE(0x02014b50, 0);
47 central.writeUInt16LE((3 << 8) | 20, 4);
48 central.writeUInt16LE(20, 6);
49 central.writeUInt32LE(crc, 16);
50 central.writeUInt32LE(data.length, 20);
51 central.writeUInt32LE(data.length, 24);
52 central.writeUInt16LE(name.length, 28);
53 central.writeUInt32LE((entry.mode << 16) >>> 0, 38);
54 central.writeUInt32LE(offset, 42);
55 records.push(local, name, data);
56 directory.push(central, name);
57 offset += local.length + name.length + data.length;
58 }
59 const centralDirectory = Buffer.concat(directory);
60 const end = Buffer.alloc(22);
61 end.writeUInt32LE(0x06054b50, 0);
62 end.writeUInt16LE(entries.length, 8);
63 end.writeUInt16LE(entries.length, 10);
64 end.writeUInt32LE(centralDirectory.length, 12);
65 end.writeUInt32LE(offset, 16);
66 return Buffer.concat([...records, centralDirectory, end]);
67};
68​
69const browserArchive = makeZip([
70 { name: ROOT, mode: 0o40755 },
71 { name: `${ROOT}${executableName}`, data: "#!/bin/sh\n", mode: 0o100755 },
72 { name: `${ROOT}libEGL.so`, data: "library", mode: 0o100755 },
73 { name: `${ROOT}locales/`, mode: 0o40755 },
74 { name: `${ROOT}locales/en-US.pak`, data: "strings", mode: 0o100644 },
75]);
76​
77const makeHarness = Effect.fn("test.makePreviewBrowser")(function* (
78 options: {
79 readonly archive?: Buffer;
80 readonly sha256?: string;
81 readonly body?: Stream.Stream<Uint8Array>;
82 readonly wait?: Duration.Input;
83 readonly unsupported?: boolean;
84 } = {},
85) {
86 const fs = yield* FileSystem.FileSystem;
87 const path = yield* Path.Path;
88 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-preview-browser-test-" });
89 const archive = options.archive ?? browserArchive;
90 const crypto = yield* Crypto.Crypto;
91 const sha256 =
92 options.sha256 ?? Hex.encode(yield* crypto.digest("SHA-256", archive).pipe(Effect.orDie));
93 const requests: Array<string> = [];
94 const browser = yield* PreviewBrowser.makePreviewBrowser({
95 baseDir,
96 release: options.unsupported
97 ? null
98 : {
99 version: "1.2.3",
100 platform: "fixture",
101 url: "https://storage.googleapis.com/chrome-headless-shell-fixture.zip",
102 bytes: archive.byteLength,
103 sha256,
104 },
105 ...(options.wait === undefined ? {} : { wait: options.wait }),
106 }).pipe(
107 Effect.provideService(HostProcess.Platform, hostPlatform),
108 Effect.provideService(HostProcess.Architecture, "x64"),
109 Effect.provideService(
110 HttpClient.HttpClient,
111 HttpClient.make((request) =>
112 Effect.sync(() => {
113 requests.push(request.url);
114 const response = HttpClientResponse.fromWeb(request, new Response(null));
115 return Object.defineProperty(response, "stream", {
116 value: options.body ?? Stream.make(archive.subarray(0, 40), archive.subarray(40)),
117 });
118 }),
119 ),
120 ),
121 );
122 const installRoot = path.join(baseDir, "tools", "chrome-headless-shell", "fixture");
123 return { browser, fs, path, baseDir, installRoot, requests };
124});
125​
126it.layer(NodeServices.layer)("PreviewBrowser", (it) => {
127 it.effect("installs a verified download with its file modes and then reuses it", () =>
128 Effect.gen(function* () {
129 const { browser, fs, path, installRoot, requests } = yield* makeHarness();
130 yield* fs.makeDirectory(path.join(installRoot, "1.0.0"), { recursive: true });
131 const active = path.join(installRoot, ".install-other");
132 const abandoned = path.join(installRoot, ".install-abandoned");
133 yield* fs.makeDirectory(active);
134 yield* fs.makeDirectory(abandoned);
135 const twoHoursAgo = DateTime.toDate(DateTime.subtract(yield* DateTime.now, { hours: 2 }));
136 yield* fs.utimes(abandoned, twoHoursAgo, twoHoursAgo);
137 expect(yield* browser.installed).toEqual(Option.none());
138​
139 const executable = yield* browser.executable;
140​
141 const version = path.join(installRoot, "1.2.3");
142 expect(executable).toBe(path.join(version, executableName));
143 expect(yield* fs.readFileString(path.join(version, "locales", "en-US.pak"))).toBe("strings");
144 if (hostPlatform !== "win32") {
145 const mode = (file: string) =>
146 fs.stat(path.join(version, file)).pipe(Effect.map((info) => info.mode & 0o777));
147 expect(yield* mode(executableName)).toBe(0o755);
148 expect(yield* mode("libEGL.so")).toBe(0o755);
149 expect(yield* mode(path.join("locales", "en-US.pak"))).toBe(0o644);
150 }
151 expect((yield* fs.readDirectory(installRoot)).toSorted()).toEqual([
152 ".install-other",
153 "1.2.3",
154 ]);
155 expect(yield* browser.executable).toBe(executable);
156 expect(yield* browser.installed).toEqual(Option.some(executable));
157 expect(requests).toHaveLength(1);
158 }),
159 );
160​
161 it.effect.each([
162 { name: "a hash mismatch", sha256: "0".repeat(64) },
163 { name: "a short download", body: Stream.make(browserArchive.subarray(0, -1)) },
164 {
165 name: "an oversized download",
166 body: Stream.make(browserArchive, Buffer.from("extra")),
167 },
168 ])("rejects $name, installs nothing, and retries on the next call", (testCase) =>
169 Effect.gen(function* () {
170 const { browser, fs, installRoot, requests } = yield* makeHarness(testCase);
171​
172 const error = yield* browser.executable.pipe(Effect.flip);
173​
174 expect(error._tag).toBe("PreviewBrowserInstallError");
175 expect(error.message).toMatch(/^T3 could not install its headless browser: .+ Try again\.$/);
176 expect(yield* fs.readDirectory(installRoot)).toEqual([]);
177 yield* browser.executable.pipe(Effect.flip);
178 expect(requests).toHaveLength(2);
179 }),
180 );
181​
182 it.effect.each([
183 { name: "a parent-directory entry", entry: `${ROOT}../escape` },
184 { name: "an absolute entry", entry: "/escape" },
185 { name: "an entry outside the top directory", entry: "escape" },
186 ])("rejects an archive with $name", (testCase) =>
187 Effect.gen(function* () {
188 const { browser, fs, path, baseDir, installRoot } = yield* makeHarness({
189 archive: makeZip([
190 { name: `${ROOT}${executableName}`, data: "#!/bin/sh\n", mode: 0o100755 },
191 { name: testCase.entry, data: "escaped", mode: 0o100644 },
192 ]),
193 });
194​
195 const error = yield* browser.executable.pipe(Effect.flip);
196​
197 expect(error._tag).toBe("PreviewBrowserInstallError");
198 expect(yield* fs.readDirectory(installRoot)).toEqual([]);
199 expect(yield* fs.exists(path.join(baseDir, "tools", "chrome-headless-shell", "escape"))).toBe(
200 false,
201 );
202 }),
203 );
204​
205 it.effect("shares one install between callers and finishes it after they stop waiting", () =>
206 Effect.gen(function* () {
207 const firstChunkSent = yield* Deferred.make<void>();
208 const finishDownload = yield* Deferred.make<void>();
209 const { browser, requests } = yield* makeHarness({
210 wait: "45 seconds",
211 body: Stream.concat(
212 Stream.make(browserArchive.subarray(0, 100)),
213 Stream.fromEffect(
214 Deferred.succeed(firstChunkSent, undefined).pipe(
215 Effect.andThen(Deferred.await(finishDownload)),
216 Effect.as(browserArchive.subarray(100)),
217 ),
218 ),
219 ),
220 });
221​
222 const callers = yield* Effect.forEach([1, 2], () =>
223 Effect.forkChild(browser.executable.pipe(Effect.flip)),
224 );
225 yield* Deferred.await(firstChunkSent);
226 yield* TestClock.adjust("45 seconds");
227 for (const caller of callers) {
228 expect(yield* Fiber.join(caller)).toMatchObject({
229 _tag: "PreviewBrowserInstallingError",
230 downloadedBytes: 100,
231 unpacking: false,
232 });
233 }
234​
235 yield* Deferred.succeed(finishDownload, undefined);
236 expect(yield* browser.executable).toMatch(new RegExp(`${executableName}$`));
237 expect(requests).toHaveLength(1);
238 }),
239 );
240​
241 it.effect("reports hosts Chrome for Testing does not build for without downloading", () =>
242 Effect.gen(function* () {
243 const { browser, requests } = yield* makeHarness({ unsupported: true });
244 expect((yield* browser.executable.pipe(Effect.flip))._tag).toBe(
245 "PreviewBrowserUnsupportedError",
246 );
247 expect(yield* browser.installed).toEqual(Option.none());
248 expect(requests).toEqual([]);
249 }),
250 );
251});
252​
253it("pins one Chrome for Testing build per host", () => {
254 const hosts = [
255 ["linux", "x64"],
256 ["linux", "arm64"],
257 ["darwin", "arm64"],
258 ["darwin", "x64"],
259 ["win32", "x64"],
260 ["win32", "arm64"],
261 ["win32", "ia32"],
262 ["linux", "ia32"],
263 ["freebsd", "x64"],
264 ] as const;
265 expect(
266 hosts.map(([platform, arch]) => PreviewBrowser.previewBrowserRelease(platform, arch)?.platform),
267 ).toEqual([
268 "linux64",
269 "linux-arm64",
270 "mac-arm64",
271 "mac-x64",
272 "win64",
273 "win64",
274 "win32",
275 undefined,
276 undefined,
277 ]);
278 expect(PreviewBrowser.previewBrowserRelease("linux", "x64")).toMatchObject({
279 url: "https://storage.googleapis.com/chrome-for-testing-public/154.0.8037.92/linux64/chrome-headless-shell-linux64.zip",
280 bytes: 120_477_194,
281 });
282});
283​
284it("tells the agent how far the install has come", () => {
285 expect(
286 new PreviewBrowser.PreviewBrowserInstallingError({
287 downloadedBytes: 37_200_000,
288 totalBytes: 120_477_194,
289 unpacking: false,
290 }).message,
291 ).toBe("T3 is installing its headless browser (37 of 120 MB downloaded). Try again in a minute.");
292});