Open History to see the last commit
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(
175 /^T3 could not install its HTML preview browser: .+ Call html_preview again to retry\.$/,
176 );
177 expect(yield* fs.readDirectory(installRoot)).toEqual([]);
178 yield* browser.executable.pipe(Effect.flip);
179 expect(requests).toHaveLength(2);
180 }),
181 );
182
183 it.effect.each([
184 { name: "a parent-directory entry", entry: `${ROOT}../escape` },
185 { name: "an absolute entry", entry: "/escape" },
186 { name: "an entry outside the top directory", entry: "escape" },
187 ])("rejects an archive with $name", (testCase) =>
188 Effect.gen(function* () {
189 const { browser, fs, path, baseDir, installRoot } = yield* makeHarness({
190 archive: makeZip([
191 { name: `${ROOT}${executableName}`, data: "#!/bin/sh\n", mode: 0o100755 },
192 { name: testCase.entry, data: "escaped", mode: 0o100644 },
193 ]),
194 });
195
196 const error = yield* browser.executable.pipe(Effect.flip);
197
198 expect(error._tag).toBe("PreviewBrowserInstallError");
199 expect(yield* fs.readDirectory(installRoot)).toEqual([]);
200 expect(yield* fs.exists(path.join(baseDir, "tools", "chrome-headless-shell", "escape"))).toBe(
201 false,
202 );
203 }),
204 );
205
206 it.effect("shares one install between callers and finishes it after they stop waiting", () =>
207 Effect.gen(function* () {
208 const firstChunkSent = yield* Deferred.make<void>();
209 const finishDownload = yield* Deferred.make<void>();
210 const { browser, requests } = yield* makeHarness({
211 wait: "45 seconds",
212 body: Stream.concat(
213 Stream.make(browserArchive.subarray(0, 100)),
214 Stream.fromEffect(
215 Deferred.succeed(firstChunkSent, undefined).pipe(
216 Effect.andThen(Deferred.await(finishDownload)),
217 Effect.as(browserArchive.subarray(100)),
218 ),
219 ),
220 ),
221 });
222
223 const callers = yield* Effect.forEach([1, 2], () =>
224 Effect.forkChild(browser.executable.pipe(Effect.flip)),
225 );
226 yield* Deferred.await(firstChunkSent);
227 yield* TestClock.adjust("45 seconds");
228 for (const caller of callers) {
229 expect(yield* Fiber.join(caller)).toMatchObject({
230 _tag: "PreviewBrowserInstallingError",
231 downloadedBytes: 100,
232 unpacking: false,
233 });
234 }
235
236 // The install belongs to the service, so it outlives the callers that gave up on it.
237 yield* Deferred.succeed(finishDownload, undefined);
238 expect(yield* browser.executable).toMatch(new RegExp(`${executableName}$`));
239 expect(requests).toHaveLength(1);
240 }),
241 );
242
243 it.effect("reports hosts Chrome for Testing does not build for without downloading", () =>
244 Effect.gen(function* () {
245 const { browser, requests } = yield* makeHarness({ unsupported: true });
246 expect((yield* browser.executable.pipe(Effect.flip))._tag).toBe(
247 "PreviewBrowserUnsupportedError",
248 );
249 expect(yield* browser.installed).toEqual(Option.none());
250 expect(requests).toEqual([]);
251 }),
252 );
253});
254
255it("pins one Chrome for Testing build per host", () => {
256 const hosts = [
257 ["linux", "x64"],
258 ["linux", "arm64"],
259 ["darwin", "arm64"],
260 ["darwin", "x64"],
261 ["win32", "x64"],
262 ["win32", "arm64"],
263 ["win32", "ia32"],
264 ["linux", "ia32"],
265 ["freebsd", "x64"],
266 ] as const;
267 expect(
268 hosts.map(([platform, arch]) => PreviewBrowser.previewBrowserRelease(platform, arch)?.platform),
269 ).toEqual([
270 "linux64",
271 "linux-arm64",
272 "mac-arm64",
273 "mac-x64",
274 "win64",
275 "win64",
276 "win32",
277 undefined,
278 undefined,
279 ]);
280 expect(PreviewBrowser.previewBrowserRelease("linux", "x64")).toMatchObject({
281 url: "https://storage.googleapis.com/chrome-for-testing-public/154.0.8037.92/linux64/chrome-headless-shell-linux64.zip",
282 bytes: 120_477_194,
283 });
284});
285
286it("tells the agent how far the install has come", () => {
287 expect(
288 new PreviewBrowser.PreviewBrowserInstallingError({
289 downloadedBytes: 37_200_000,
290 totalBytes: 120_477_194,
291 unpacking: false,
292 }).message,
293 ).toBe(
294 "T3 is installing its HTML preview browser (37 of 120 MB downloaded). Call html_preview again in a minute.",
295 );
296});