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

PreviewBrowser.test.ts

292 lines11.3 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { expect, it } from "@effect/vitest";
3import { HostProcessArchitecture, HostProcessPlatform } from "@t3tools/shared/hostProcess";
4import * as Deferred from "effect/Deferred";
5import type * as Duration from "effect/Duration";
6import * as DateTime from "effect/DateTime";
7import * as Effect from "effect/Effect";
8import * as Fiber from "effect/Fiber";
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 * as TestClock from "effect/testing/TestClock";
14import { HttpClient, HttpClientResponse } from "effect/http";
15import * as NodeCrypto from "node:crypto";
16import * as NodeZlib from "node:zlib";
17​
18import * as PreviewBrowser from "./PreviewBrowser.ts";
19​
20// POSIX modes cannot be checked on NTFS, so follow the host like the Antigravity suite.
21const hostPlatform: NodeJS.Platform =
22 HostProcessPlatform.defaultValue() === "win32" ? "win32" : "linux";
23const executableName =
24 hostPlatform === "win32" ? "chrome-headless-shell.exe" : "chrome-headless-shell";
25const ROOT = "chrome-headless-shell-fixture/";
26​
27/** A stored ZIP whose entries carry Unix modes, like Chrome for Testing's archives. */
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 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: options.sha256 ?? NodeCrypto.createHash("sha256").update(archive).digest("hex"),
101 },
102 ...(options.wait === undefined ? {} : { wait: options.wait }),
103 }).pipe(
104 Effect.provideService(HostProcessPlatform, hostPlatform),
105 Effect.provideService(HostProcessArchitecture, "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 // Another server's install in progress, and one abandoned two hours ago.
129 const active = path.join(installRoot, ".install-other");
130 const abandoned = path.join(installRoot, ".install-abandoned");
131 yield* fs.makeDirectory(active);
132 yield* fs.makeDirectory(abandoned);
133 const twoHoursAgo = DateTime.toDate(DateTime.subtract(yield* DateTime.now, { hours: 2 }));
134 yield* fs.utimes(abandoned, twoHoursAgo, twoHoursAgo);
135 expect(yield* browser.installed).toEqual(Option.none());
136​
137 const executable = yield* browser.executable;
138​
139 const version = path.join(installRoot, "1.2.3");
140 expect(executable).toBe(path.join(version, executableName));
141 expect(yield* fs.readFileString(path.join(version, "locales", "en-US.pak"))).toBe("strings");
142 if (hostPlatform !== "win32") {
143 const mode = (file: string) =>
144 fs.stat(path.join(version, file)).pipe(Effect.map((info) => info.mode & 0o777));
145 expect(yield* mode(executableName)).toBe(0o755);
146 expect(yield* mode("libEGL.so")).toBe(0o755);
147 expect(yield* mode(path.join("locales", "en-US.pak"))).toBe(0o644);
148 }
149 // The old build and stale staging directories are gone; a fresh one stays.
150 expect((yield* fs.readDirectory(installRoot)).toSorted()).toEqual([
151 ".install-other",
152 "1.2.3",
153 ]);
154 expect(yield* browser.executable).toBe(executable);
155 expect(yield* browser.installed).toEqual(Option.some(executable));
156 expect(requests).toHaveLength(1);
157 }),
158 );
159​
160 it.effect.each([
161 { name: "a hash mismatch", sha256: "0".repeat(64) },
162 { name: "a short download", body: Stream.make(browserArchive.subarray(0, -1)) },
163 {
164 name: "an oversized download",
165 body: Stream.make(browserArchive, Buffer.from("extra")),
166 },
167 ])("rejects $name, installs nothing, and retries on the next call", (testCase) =>
168 Effect.gen(function* () {
169 const { browser, fs, installRoot, requests } = yield* makeHarness(testCase);
170​
171 const error = yield* browser.executable.pipe(Effect.flip);
172​
173 expect(error._tag).toBe("PreviewBrowserInstallError");
174 expect(error.message).toMatch(/^T3 could not install its headless browser: .+ Try again\.$/);
175 expect(yield* fs.readDirectory(installRoot)).toEqual([]);
176 yield* browser.executable.pipe(Effect.flip);
177 expect(requests).toHaveLength(2);
178 }),
179 );
180​
181 it.effect.each([
182 { name: "a parent-directory entry", entry: `${ROOT}../escape` },
183 { name: "an absolute entry", entry: "/escape" },
184 { name: "an entry outside the top directory", entry: "escape" },
185 ])("rejects an archive with $name", (testCase) =>
186 Effect.gen(function* () {
187 const { browser, fs, path, baseDir, installRoot } = yield* makeHarness({
188 archive: makeZip([
189 { name: `${ROOT}${executableName}`, data: "#!/bin/sh\n", mode: 0o100755 },
190 { name: testCase.entry, data: "escaped", mode: 0o100644 },
191 ]),
192 });
193​
194 const error = yield* browser.executable.pipe(Effect.flip);
195​
196 expect(error._tag).toBe("PreviewBrowserInstallError");
197 expect(yield* fs.readDirectory(installRoot)).toEqual([]);
198 expect(yield* fs.exists(path.join(baseDir, "tools", "chrome-headless-shell", "escape"))).toBe(
199 false,
200 );
201 }),
202 );
203​
204 it.effect("shares one install between callers and finishes it after they stop waiting", () =>
205 Effect.gen(function* () {
206 const firstChunkSent = yield* Deferred.make<void>();
207 const finishDownload = yield* Deferred.make<void>();
208 const { browser, requests } = yield* makeHarness({
209 wait: "45 seconds",
210 body: Stream.concat(
211 Stream.make(browserArchive.subarray(0, 100)),
212 Stream.fromEffect(
213 Deferred.succeed(firstChunkSent, undefined).pipe(
214 Effect.andThen(Deferred.await(finishDownload)),
215 Effect.as(browserArchive.subarray(100)),
216 ),
217 ),
218 ),
219 });
220​
221 const callers = yield* Effect.forEach([1, 2], () =>
222 Effect.forkChild(browser.executable.pipe(Effect.flip)),
223 );
224 yield* Deferred.await(firstChunkSent);
225 yield* TestClock.adjust("45 seconds");
226 for (const caller of callers) {
227 expect(yield* Fiber.join(caller)).toMatchObject({
228 _tag: "PreviewBrowserInstallingError",
229 downloadedBytes: 100,
230 unpacking: false,
231 });
232 }
233​
234 // The install belongs to the service, so it outlives the callers that gave up on it.
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});