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

PreviewBrowser.test.ts

202 lines8.2 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 version?: string;
77 readonly archive?: Buffer;
78 readonly sha256?: string;
79 readonly body?: Stream.Stream<Uint8Array>;
80 readonly wait?: Duration.Input;
81 readonly unsupported?: boolean;
82 } = {},
83) {
84 const fs = yield* FileSystem.FileSystem;
85 const path = yield* Path.Path;
86 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-preview-browser-test-" });
87 const archive = options.archive ?? browserArchive;
88 const crypto = yield* Crypto.Crypto;
89 const sha256 =
90 options.sha256 ?? Hex.encode(yield* crypto.digest("SHA-256", archive).pipe(Effect.orDie));
91 const requests: Array<string> = [];
92 const browser = yield* PreviewBrowser.makePreviewBrowser({
93 baseDir,
94 release: options.unsupported
95 ? null
96 : {
97 version: options.version ?? "1.2.3",
98 platform: "fixture",
99 url: "https://storage.googleapis.com/chrome-headless-shell-fixture.zip",
100 bytes: archive.byteLength,
101 sha256,
102 },
103 ...(options.wait === undefined ? {} : { wait: options.wait }),
104 }).pipe(
105 Effect.provideService(HostProcess.Platform, hostPlatform),
106 Effect.provideService(HostProcess.Architecture, "x64"),
107 Effect.provideService(
108 HttpClient.HttpClient,
109 HttpClient.make((request) =>
110 Effect.sync(() => {
111 requests.push(request.url);
112 const response = HttpClientResponse.fromWeb(request, new Response(null));
113 return Object.defineProperty(response, "stream", {
114 value: options.body ?? Stream.make(archive.subarray(0, 40), archive.subarray(40)),
115 });
116 }),
117 ),
118 ),
119 );
120 const installRoot = path.join(baseDir, "tools", "chrome-headless-shell", "fixture");
121 return { browser, fs, path, baseDir, installRoot, requests };
122});
123​
124it.layer(NodeServices.layer)("PreviewBrowser", (it) => {
125 it.effect.each(["0.8.0", "1.2.3"])("retains another version when installing %s", (current) =>
126 Effect.gen(function* () {
127 const { browser, fs, path, installRoot, requests } = yield* makeHarness({ version: current });
128 yield* fs.makeDirectory(path.join(installRoot, "0.9.0"), { recursive: true });
129 yield* fs.makeDirectory(path.join(installRoot, "0.10.0"));
130 const active = path.join(installRoot, ".install-other");
131 const abandoned = path.join(installRoot, ".install-abandoned");
132 yield* fs.makeDirectory(active);
133 yield* fs.makeDirectory(abandoned);
134 const twoHoursAgo = DateTime.toDate(DateTime.subtract(yield* DateTime.now, { hours: 2 }));
135 yield* fs.utimes(abandoned, twoHoursAgo, twoHoursAgo);
136 expect(yield* browser.installed).toEqual(Option.none());
137​
138 const executable = yield* browser.executable;
139​
140 const version = path.join(installRoot, current);
141 expect(executable).toBe(path.join(version, executableName));
142 expect(yield* fs.readFileString(path.join(version, "locales", "en-US.pak"))).toBe("strings");
143 if (hostPlatform !== "win32") {
144 const mode = (file: string) =>
145 fs.stat(path.join(version, file)).pipe(Effect.map((info) => info.mode & 0o777));
146 expect(yield* mode(executableName)).toBe(0o755);
147 expect(yield* mode("libEGL.so")).toBe(0o755);
148 expect(yield* mode(path.join("locales", "en-US.pak"))).toBe(0o644);
149 }
150 expect((yield* fs.readDirectory(installRoot)).toSorted()).toEqual(
151 [".install-other", "0.10.0", current].toSorted(),
152 );
153 expect(yield* browser.executable).toBe(executable);
154 expect(yield* browser.installed).toEqual(Option.some(executable));
155 expect(requests).toHaveLength(1);
156 }),
157 );
158​
159 it.effect.each([
160 { name: "a hash mismatch", sha256: "0".repeat(64) },
161 { name: "a short download", body: Stream.make(browserArchive.subarray(0, -1)) },
162 {
163 name: "an oversized download",
164 body: Stream.make(browserArchive, Buffer.from("extra")),
165 },
166 ])("rejects $name, installs nothing, and retries on the next call", (testCase) =>
167 Effect.gen(function* () {
168 const { browser, fs, installRoot, requests } = yield* makeHarness(testCase);
169​
170 const error = yield* browser.executable.pipe(Effect.flip);
171​
172 expect(error._tag).toBe("PreviewBrowserInstallError");
173 expect(error.message).toMatch(/^T3 could not install its headless browser: .+ Try again\.$/);
174 expect(yield* fs.readDirectory(installRoot)).toEqual([]);
175 yield* browser.executable.pipe(Effect.flip);
176 expect(requests).toHaveLength(2);
177 }),
178 );
179​
180 it.effect.each([
181 { name: "a parent-directory entry", entry: `${ROOT}../escape` },
182 { name: "an absolute entry", entry: "/escape" },
183 { name: "an entry outside the top directory", entry: "escape" },
184 ])("rejects an archive with $name", (testCase) =>
185 Effect.gen(function* () {
186 const { browser, fs, path, baseDir, installRoot } = yield* makeHarness({
187 archive: makeZip([
188 { name: `${ROOT}${executableName}`, data: "#!/bin/sh\n", mode: 0o100755 },
189 { name: testCase.entry, data: "escaped", mode: 0o100644 },
190 ]),
191 });
192​
193 const error = yield* browser.executable.pipe(Effect.flip);
194​
195 expect(error._tag).toBe("PreviewBrowserInstallError");
196 expect(yield* fs.readDirectory(installRoot)).toEqual([]);
197 expect(yield* fs.exists(path.join(baseDir, "tools", "chrome-headless-shell", "escape"))).toBe(
198 false,
199 );
200 }),
201 );
202});