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

browser.ts

176 lines7.0 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​
87const browserSetupCommand = Command.make("setup", { baseDir: baseDirFlag }).pipe(
88 Command.withDescription(
89 "Set up this Linux host for T3's browser: allow Chrome's sandbox and install its libraries.",
90 ),
91 Command.withHandler(({ baseDir }) =>
92 Effect.gen(function* () {
93 if ((yield* HostProcess.Platform) !== "linux") {
94 return yield* Console.log("Nothing to set up: T3's browser runs as is on this system.");
95 }
96 const fs = yield* FileSystem.FileSystem;
97 const isRoot = (yield* HostProcess.UserId) === 0;
98 const setupCommand = yield* resolveRootCliCommand(PreviewBrowserHost.SETUP_SUBCOMMAND);
99​
100 const needsProfile = yield* PreviewBrowserHost.sandboxBlocked;
101 const browser = yield* installedBrowser(yield* setupBaseDir(baseDir));
102 const missing = Option.isSome(browser)
103 ? yield* PreviewBrowserHost.missingLibraries(browser.value)
104 : [];
105 const hasApt = yield* fs.exists("/usr/bin/apt-get").pipe(Effect.orElseSucceed(() => false));
106​
107 if (!needsProfile && missing.length === 0) {
108 return yield* Console.log(
109 Option.isSome(browser)
110 ? "This host is ready for T3's browser."
111 : "Chrome's sandbox is allowed here. T3's browser installs on first use; if it then reports missing libraries, run this again.",
112 );
113 }
114​
115 if (!isRoot) {
116 if (needsProfile) {
117 yield* Console.log(
118 `This host blocks the sandbox T3's browser runs in. Setup installs an AppArmor profile at ${PreviewBrowserHost.APPARMOR_PROFILE_PATH} that allows it.`,
119 );
120 }
121 if (missing.length > 0) {
122 yield* Console.log(`T3's browser is missing ${missing.join(", ")}; setup installs them.`);
123 }
124 return yield* Console.log(`\nThis needs root. Run:\n\n ${setupCommand}\n`);
125 }
126​
127 if (needsProfile) {
128 yield* fs
129 .writeFileString(
130 PreviewBrowserHost.APPARMOR_PROFILE_PATH,
131 PreviewBrowserHost.APPARMOR_PROFILE,
132 )
133 .pipe(
134 Effect.mapError(
135 (cause) =>
136 new BrowserSetupStepError({
137 step: `write ${PreviewBrowserHost.APPARMOR_PROFILE_PATH}`,
138 detail: cause.message,
139 }),
140 ),
141 );
142 yield* runStep("load the AppArmor profile", "apparmor_parser", [
143 "-r",
144 PreviewBrowserHost.APPARMOR_PROFILE_PATH,
145 ]);
146 yield* Console.log("Allowed Chrome's sandbox for T3's browser.");
147 }
148​
149 if (missing.length > 0) {
150 if (!hasApt) {
151 return yield* Console.log(
152 `T3's browser is missing ${missing.join(", ")}. Install them with your package manager, then run this again.`,
153 );
154 }
155 yield* runStep("refresh the package lists", "apt-get", ["update"]);
156 const packages = yield* Effect.forEach(PreviewBrowserHost.DEBIAN_PACKAGES, (names) =>
157 Effect.findFirst(names, aptOffers).pipe(Effect.map(Option.getOrElse(() => names[0]!))),
158 );
159 yield* runStep("install the browser's libraries", "apt-get", [
160 "install",
161 "-y",
162 "--no-install-recommends",
163 ...packages,
164 ]);
165 yield* Console.log("Installed the browser's libraries.");
166 }
167​
168 yield* Console.log("This host is ready for T3's browser.");
169 }),
170 ),
171);
172​
173export const browserCommand = Command.make("browser").pipe(
174 Command.withDescription("Manage T3's headless browser on this host."),
175 Command.withSubcommands([browserSetupCommand]),
176);