Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { expect, it } from "@effect/vitest";
3import * as HostProcess from "@t3tools/shared/HostProcess";
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as Layer from "effect/Layer";
7import * as PlatformError from "effect/PlatformError";
8import * as Sink from "effect/Sink";
9import * as Stream from "effect/Stream";
10import * as TestConsole from "effect/testing/TestConsole";
11import { Command } from "effect/cli";
12import * as ChildProcess from "effect/process/ChildProcess";
13import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
14
15import { browserCommand } from "./browser.ts";
16
17const BROWSER = "/t3/tools/chrome-headless-shell/linux64/154/chrome-headless-shell";
18const FONT = "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf";
19
20/**
21 * Records every command. `fc-match` is missing until fonts are installed, unless
22 * the host starts with a font; the browser fails to load libnss3 when asked to.
23 */
24const fakeSpawner = (host: { readonly font?: string; readonly missingLibrary?: boolean }) => {
25 const commands: Array<ReadonlyArray<string>> = [];
26 let font = host.font;
27 const spawner = ChildProcessSpawner.make((command) =>
28 Effect.gen(function* () {
29 if (!ChildProcess.isStandardCommand(command)) return yield* Effect.die("Unexpected pipeline");
30 commands.push([command.command, ...command.args]);
31 if (command.command === "apt-get" && command.args.includes("fonts-liberation")) font = FONT;
32 if (command.command === "fc-match" && font === undefined) {
33 return yield* PlatformError.systemError({
34 _tag: "NotFound",
35 module: "ChildProcess",
36 method: "spawn",
37 });
38 }
39 const output =
40 command.command === "fc-match"
41 ? font!
42 : command.command === BROWSER && host.missingLibrary
43 ? "error while loading shared libraries: libnss3.so: cannot open shared object file"
44 : command.command === "ldd"
45 ? "\tlibnss3.so => not found\n"
46 : "";
47 const bytes = Stream.make(new TextEncoder().encode(output));
48 return ChildProcessSpawner.makeHandle({
49 pid: ChildProcessSpawner.ProcessId(1),
50 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
51 isRunning: Effect.succeed(false),
52 kill: () => Effect.void,
53 unref: Effect.succeed(Effect.void),
54 stdin: Sink.drain,
55 stdout: bytes,
56 stderr: Stream.empty,
57 all: bytes,
58 getInputFd: () => Sink.drain,
59 getOutputFd: () => Stream.empty,
60 });
61 }),
62 );
63 return { spawner, commands };
64};
65
66/** A Linux host with apt and T3's browser installed under `/t3`. */
67const runSetup = (host: {
68 readonly root: boolean;
69 readonly font?: string;
70 readonly missingLibrary?: boolean;
71}) => {
72 const { spawner, commands } = fakeSpawner(host);
73 const fs = FileSystem.makeNoop({
74 exists: (path) => Effect.succeed(path === "/usr/bin/apt-get" || path === BROWSER),
75 readDirectory: (path) =>
76 Effect.succeed(path.endsWith("chrome-headless-shell") ? ["linux64"] : ["154"]),
77 });
78 return Effect.gen(function* () {
79 yield* Command.runWith(browserCommand, { version: "0.0.0" })(["setup", "--base-dir", "/t3"]);
80 return { commands, output: (yield* TestConsole.logLines).join("\n") };
81 }).pipe(
82 Effect.provideService(FileSystem.FileSystem, fs),
83 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
84 Effect.provideService(HostProcess.Platform, "linux"),
85 Effect.provideService(HostProcess.UserId, host.root ? 0 : 1000),
86 // Root through sudo from a regular user, so setup reports ready instead of the root warning.
87 Effect.provideService(HostProcess.Environment, host.root ? { SUDO_USER: "alice" } : {}),
88 Effect.provide(Layer.mergeAll(NodeServices.layer, TestConsole.layer)),
89 );
90};
91
92const aptGet = (commands: ReadonlyArray<ReadonlyArray<string>>) =>
93 commands.filter(([name]) => name === "apt-get");
94
95it.effect("setup in a root shell warns that the server cannot run as root", () =>
96 Effect.gen(function* () {
97 // Every file read fails, so setup finds nothing to install and changes nothing.
98 yield* Command.runWith(browserCommand, { version: "0.0.0" })([
99 "setup",
100 "--base-dir",
101 "/nonexistent",
102 ]).pipe(
103 Effect.provide(FileSystem.layerNoop({})),
104 Effect.provideService(
105 ChildProcessSpawner.ChildProcessSpawner,
106 fakeSpawner({ font: FONT }).spawner,
107 ),
108 Effect.provideService(HostProcess.Platform, "linux"),
109 Effect.provideService(HostProcess.UserId, 0),
110 // A root user who follows the old advice runs setup through sudo.
111 Effect.provideService(HostProcess.Environment, { SUDO_USER: "root" }),
112 );
113 const output = (yield* TestConsole.logLines).join("\n");
114 expect(output).toContain("Chrome will not start its sandbox as root");
115 expect(output).not.toContain("ready");
116 }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, TestConsole.layer))),
117);
118
119it.effect("setup without root does not report a host without fonts as ready", () =>
120 Effect.gen(function* () {
121 const { commands, output } = yield* runSetup({ root: false });
122 expect(output).toContain(
123 "T3's browser needs fontconfig and system fonts; setup installs them.",
124 );
125 expect(output).toContain("This needs root. Run:");
126 expect(output).not.toContain("ready");
127 expect(aptGet(commands)).toEqual([]);
128 }),
129);
130
131it.effect("setup as root installs missing libraries and fonts after one package refresh", () =>
132 Effect.gen(function* () {
133 const { commands, output } = yield* runSetup({ root: true, missingLibrary: true });
134 const apt = aptGet(commands);
135 expect(apt.filter(([, action]) => action === "update")).toHaveLength(1);
136 expect(apt.find((args) => args.includes("libnss3"))).toBeDefined();
137 expect(apt).toContainEqual([
138 "apt-get",
139 "install",
140 "-y",
141 "--no-install-recommends",
142 "fontconfig",
143 "fonts-liberation",
144 ]);
145 expect(output).toContain("Installed the browser's fonts.");
146 expect(output).toContain("This host is ready for T3's browser.");
147 }),
148);