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

browser.ts

239 lines9.2 KB

1import * as HostProcess from "@t3tools/shared/HostProcess";
2import * as Console from "effect/Console";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import * as Option from "effect/Option";
6import * as Path from "effect/Path";
7import * as Schema from "effect/Schema";
8import { Command } from "effect/cli";
9import * as ChildProcess from "effect/process/ChildProcess";
10import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
11​
12import * as PreviewBrowserHost from "../preview/PreviewBrowserHost.ts";
13import { resolveBaseDir } from "../os-jank.ts";
14import { baseDirFlag } from "./config.ts";
15import { resolveRootCliCommand } from "./invocation.ts";
16​
17export class BrowserSetupStepError extends Schema.TaggedError<BrowserSetupStepError>()(
18 "BrowserSetupStepError",
19 { step: Schema.String, detail: Schema.String },
20) {
21 override get message(): string {
22 return `Could not ${this.step}: ${this.detail}`;
23 }
25​
26const runStep = Effect.fn("browserSetup.runStep")(function* (
27 step: string,
28 command: string,
29 args: ReadonlyArray<string>,
30) {
31 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
32 const exitCode = yield* spawner
33 .exitCode(
34 ChildProcess.make(command, args, { stdin: "inherit", stdout: "inherit", stderr: "inherit" }),
35 )
36 .pipe(Effect.mapError((cause) => new BrowserSetupStepError({ step, detail: String(cause) })));
37 if (exitCode !== 0) {
38 return yield* new BrowserSetupStepError({ step, detail: `${command} exited with ${exitCode}` });
39 }
40});
41​
42/**
43 * Under `sudo` the process home is root's, so an unspecified home falls back to
44 * the invoking user's `~/.t3`.
45 */
46const setupBaseDir = Effect.fn("browserSetup.baseDir")(function* (explicit: Option.Option<string>) {
47 const env = yield* HostProcess.Environment;
48 const raw = Option.getOrUndefined(explicit) ?? env.T3CODE_HOME;
49 if (raw !== undefined || env.SUDO_USER === undefined) return yield* resolveBaseDir(raw);
50 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
51 const entry = yield* spawner
52 .string(
53 ChildProcess.make("getent", ["passwd", env.SUDO_USER], { stdin: "ignore", stderr: "ignore" }),
54 )
55 .pipe(Effect.orElseSucceed(() => ""));
56 const home = entry.trim().split(":")[5];
57 const path = yield* Path.Path;
58 return home ? path.join(home, ".t3") : yield* resolveBaseDir(undefined);
59});
60​
61const aptOffers = Effect.fn("browserSetup.aptOffers")(function* (name: string) {
62 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
63 const policy = yield* spawner
64 .string(ChildProcess.make("apt-cache", ["policy", name], { stdin: "ignore", stderr: "ignore" }))
65 .pipe(Effect.orElseSucceed(() => ""));
66 const candidate = /Candidate:\s*(\S+)/.exec(policy)?.[1];
67 return candidate !== undefined && candidate !== "(none)";
68});
69​
70const installedBrowser = Effect.fn("browserSetup.installedBrowser")(function* (baseDir: string) {
71 const fs = yield* FileSystem.FileSystem;
72 const path = yield* Path.Path;
73 const root = path.join(baseDir, "tools", "chrome-headless-shell");
74 for (const platform of yield* fs.readDirectory(root).pipe(Effect.orElseSucceed(() => []))) {
75 for (const version of yield* fs
76 .readDirectory(path.join(root, platform))
77 .pipe(Effect.orElseSucceed(() => []))) {
78 const executable = path.join(root, platform, version, "chrome-headless-shell");
79 if (yield* fs.exists(executable).pipe(Effect.orElseSucceed(() => false))) {
80 return Option.some(executable);
81 }
82 }
83 }
84 return Option.none<string>();
85});
86​
87/**
88 * Chrome starts without fonts, but pages then render no text. Without
89 * fontconfig there is no `fc-match` at all, which counts as no font.
90 */
91const fontAvailable = Effect.gen(function* () {
92 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
93 const font = yield* spawner
94 .string(
95 ChildProcess.make("fc-match", ["--format=%{file}", "sans-serif"], {
96 stdin: "ignore",
97 stderr: "ignore",
98 }),
99 )
100 .pipe(
101 Effect.timeout("5 seconds"),
102 Effect.orElseSucceed(() => ""),
103 );
104 return font.trim() !== "";
105}).pipe(Effect.withSpan("browserSetup.fontAvailable"));
106​
107const FONT_PACKAGES = ["fontconfig", "fonts-liberation"];
108​
109const browserSetupCommand = Command.make("setup", { baseDir: baseDirFlag }).pipe(
110 Command.withDescription(
111 "Set up this Linux host for T3's browser: allow Chrome's sandbox and install its libraries and fonts.",
112 ),
113 Command.withHandler(({ baseDir }) =>
114 Effect.gen(function* () {
115 if ((yield* HostProcess.Platform) !== "linux") {
116 return yield* Console.log("Nothing to set up: T3's browser runs as is on this system.");
117 }
118 const fs = yield* FileSystem.FileSystem;
119 const isRoot = (yield* HostProcess.UserId) === 0;
120 const setupCommand = yield* resolveRootCliCommand(PreviewBrowserHost.SETUP_SUBCOMMAND);
121 // Root, unless sudo came from another user, is likely the server's own account.
122 const env = yield* HostProcess.Environment;
123 const rootWarning =
124 isRoot && (env.SUDO_USER ?? "root") === "root" && !PreviewBrowserHost.sandboxDisabled(env)
125 ? new PreviewBrowserHost.PreviewBrowserRootError().message
126 : undefined;
127​
128 const needsProfile = yield* PreviewBrowserHost.sandboxBlocked;
129 const browser = yield* installedBrowser(yield* setupBaseDir(baseDir));
130 const missing = Option.isSome(browser)
131 ? yield* PreviewBrowserHost.missingLibraries(browser.value)
132 : [];
133 const needsFonts = !(yield* fontAvailable);
134 const hasApt = yield* fs.exists("/usr/bin/apt-get").pipe(Effect.orElseSucceed(() => false));
135​
136 if (!needsProfile && missing.length === 0 && !needsFonts) {
137 return yield* Console.log(
138 rootWarning ??
139 (Option.isSome(browser)
140 ? "This host is ready for T3's browser."
141 : "Chrome's sandbox is allowed here. T3's browser installs on first use; if it then reports missing libraries, run this again."),
142 );
143 }
144​
145 if (!isRoot) {
146 if (needsProfile) {
147 yield* Console.log(
148 `This host blocks the sandbox T3's browser runs in. Setup installs an AppArmor profile at ${PreviewBrowserHost.APPARMOR_PROFILE_PATH} that allows it.`,
149 );
150 }
151 if (missing.length > 0) {
152 yield* Console.log(`T3's browser is missing ${missing.join(", ")}; setup installs them.`);
153 }
154 if (needsFonts) {
155 yield* Console.log(
156 "T3's browser needs fontconfig and system fonts; setup installs them.",
157 );
158 }
159 return yield* Console.log(`\nThis needs root. Run:\n\n ${setupCommand}\n`);
160 }
161​
162 if (needsProfile) {
163 yield* fs
164 .writeFileString(
165 PreviewBrowserHost.APPARMOR_PROFILE_PATH,
166 PreviewBrowserHost.APPARMOR_PROFILE,
167 )
168 .pipe(
169 Effect.mapError(
170 (cause) =>
171 new BrowserSetupStepError({
172 step: `write ${PreviewBrowserHost.APPARMOR_PROFILE_PATH}`,
173 detail: cause.message,
174 }),
175 ),
176 );
177 yield* runStep("load the AppArmor profile", "apparmor_parser", [
178 "-r",
179 PreviewBrowserHost.APPARMOR_PROFILE_PATH,
180 ]);
181 yield* Console.log("Allowed Chrome's sandbox for T3's browser.");
182 }
183​
184 if ((missing.length > 0 || needsFonts) && !hasApt) {
185 if (missing.length > 0) {
186 yield* Console.log(
187 `T3's browser is missing ${missing.join(", ")}. Install them with your package manager, then run this again.`,
188 );
189 }
190 if (needsFonts) {
191 yield* Console.log(
192 "T3's browser needs fontconfig and system fonts. Install them with your package manager, then run this again.",
193 );
194 }
195 return;
196 }
197 if (missing.length > 0 || needsFonts) {
198 yield* runStep("refresh the package lists", "apt-get", ["update"]);
199 }
200​
201 if (missing.length > 0) {
202 const packages = yield* Effect.forEach(PreviewBrowserHost.DEBIAN_PACKAGES, (names) =>
203 Effect.findFirst(names, aptOffers).pipe(Effect.map(Option.getOrElse(() => names[0]!))),
204 );
205 yield* runStep("install the browser's libraries", "apt-get", [
206 "install",
207 "-y",
208 "--no-install-recommends",
209 ...packages,
210 ]);
211 yield* Console.log("Installed the browser's libraries.");
212 }
213​
214 if (needsFonts) {
215 yield* runStep("install the browser's fonts", "apt-get", [
216 "install",
217 "-y",
218 "--no-install-recommends",
219 ...FONT_PACKAGES,
220 ]);
221 if (!(yield* fontAvailable)) {
222 return yield* Console.log(
223 "Font packages are installed, but Fontconfig still finds no system font. Check its configuration and run setup again.",
224 );
225 }
226 yield* Console.log(
227 "Installed the browser's fonts. Restart the T3 server if browser tabs were already open.",
228 );
229 }
230​
231 yield* Console.log(rootWarning ?? "This host is ready for T3's browser.");
232 }),
233 ),
234);
235​
236export const browserCommand = Command.make("browser").pipe(
237 Command.withDescription("Manage T3's headless browser on this host."),
238 Command.withSubcommands([browserSetupCommand]),
239);