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

DeviceToolchain.ts

267 lines9.7 KB

1import type { DeviceToolVersions } from "@t3tools/contracts";
2/**
3 * Pinned installs of the two external tools device support is built on.
4 *
5 * `expo-device-hub` streams simulator and emulator screens and `agent-device`
6 * drives them. Each is npm-installed separately after its matching consent
7 * step into `<baseDir>/tools/<name>/<version>` and executed from there with the
8 * resolved Node runtime, never `npx`: an ephemeral
9 * npx cache would make every first `device_open` after a reboot depend on the
10 * registry, and the pinned versions are part of the contract the injected
11 * agent instructions describe.
12 *
13 * Install follows the pinned-runtime recipe: stage into a temp sibling, write a
14 * sentinel only after npm exits 0, then rename into place. npm extracts files
15 * before it finishes, so an entry file alone does not prove a usable tree.
16 */
17import * as Duration from "effect/Duration";
18import * as Effect from "effect/Effect";
19import * as FileSystem from "effect/FileSystem";
20import * as Option from "effect/Option";
21import * as Path from "effect/Path";
22import * as PlatformError from "effect/PlatformError";
23import * as Schema from "effect/Schema";
24import * as Semaphore from "effect/Semaphore";
25​
26import * as ProcessRunner from "../processRunner.ts";
27​
28const DEVICE_HUB_PACKAGE = "expo-device-hub";
29export const DEVICE_HUB_VERSION = "0.15.3";
30const AGENT_DEVICE_PACKAGE = "agent-device";
31export const AGENT_DEVICE_VERSION = "0.21.23";
32​
33const INSTALL_TIMEOUT = Duration.minutes(10);
34const installLock = Semaphore.makeUnsafe(1);
35​
36export interface DeviceToolPaths {
37 readonly installDir: string;
38 /** Absolute path of the tool's entry script, run with a resolved Node runtime. */
39 readonly entryPath: string;
40 readonly sentinelPath: string;
42​
43export interface DeviceToolchainPaths {
44 readonly hub: DeviceToolPaths;
45 readonly agentDevice: DeviceToolPaths;
47​
48export class DeviceToolchainInstallError extends Schema.TaggedError<DeviceToolchainInstallError>()(
49 "DeviceToolchainInstallError",
50 {
51 tool: Schema.String,
52 step: Schema.String,
53 exitCode: Schema.optional(Schema.Number),
54 cause: Schema.optional(Schema.Defect()),
55 },
56) {
57 override get message(): string {
58 const suffix = this.exitCode === undefined ? "" : ` (exit code ${this.exitCode})`;
59 return `Installing ${this.tool} failed while ${this.step}${suffix}.`;
60 }
62​
63interface ToolSpec {
64 readonly name: string;
65 readonly version: string;
66 readonly entry: ReadonlyArray<string>;
68​
69const HUB_SPEC: ToolSpec = {
70 name: DEVICE_HUB_PACKAGE,
71 version: DEVICE_HUB_VERSION,
72 entry: ["dist", "server", "cli.mjs"],
73};
74​
75const AGENT_DEVICE_SPEC: ToolSpec = {
76 name: AGENT_DEVICE_PACKAGE,
77 version: AGENT_DEVICE_VERSION,
78 entry: ["bin", "agent-device.mjs"],
79};
80​
81const toolPaths = (path: Path.Path, baseDir: string, spec: ToolSpec): DeviceToolPaths => {
82 const installDir = path.join(baseDir, "tools", spec.name, spec.version);
83 return {
84 installDir,
85 entryPath: path.join(installDir, "node_modules", spec.name, ...spec.entry),
86 sentinelPath: path.join(installDir, ".install-complete"),
87 };
88};
89​
90const deviceToolchainPaths = (path: Path.Path, baseDir: string): DeviceToolchainPaths => ({
91 hub: toolPaths(path, baseDir, HUB_SPEC),
92 agentDevice: toolPaths(path, baseDir, AGENT_DEVICE_SPEC),
93});
94​
95/** Keep daemon state (daemon.json, sessions) in userdata, separate from tool installs. */
96export const agentDeviceStateDir = (path: Path.Path, stateDir: string): string =>
97 path.join(stateDir, "device", "agent-device");
98​
99const isInstalled = Effect.fn("DeviceToolchain.isInstalled")(function* (
100 fs: FileSystem.FileSystem,
101 paths: DeviceToolPaths,
102 version: string,
103) {
104 const [entryExists, sentinel] = yield* Effect.all([
105 fs.exists(paths.entryPath),
106 fs.readFileString(paths.sentinelPath).pipe(Effect.option),
107 ]).pipe(Effect.orElseSucceed(() => [false, Option.none<string>()] as const));
108 return entryExists && Option.isSome(sentinel) && sentinel.value.trim() === version;
109});
110​
111const installTool = Effect.fn("DeviceToolchain.installTool")(function* (
112 spec: ToolSpec,
113 paths: DeviceToolPaths,
114) {
115 const fs = yield* FileSystem.FileSystem;
116 const path = yield* Path.Path;
117 const runner = yield* ProcessRunner.ProcessRunner;
118 const fail = (step: string) => (cause: unknown) =>
119 new DeviceToolchainInstallError({ tool: spec.name, step, cause });
120​
121 if (yield* isInstalled(fs, paths, spec.version)) return paths;
122​
123 const parentDir = path.dirname(paths.installDir);
124 yield* fs
125 .remove(paths.installDir, { recursive: true, force: true })
126 .pipe(Effect.mapError(fail("removing an incomplete install")));
127 yield* fs
128 .makeDirectory(parentDir, { recursive: true })
129 .pipe(Effect.mapError(fail("preparing the install directory")));
130 const stagingDir = yield* fs
131 .makeTempDirectory({ directory: parentDir, prefix: ".staging-" })
132 .pipe(Effect.mapError(fail("preparing the install directory")));
133​
134 return yield* Effect.gen(function* () {
135 const installArgs = [
136 "install",
137 "--prefix",
138 stagingDir,
139 "--no-fund",
140 "--no-audit",
141 `${spec.name}@${spec.version}`,
142 ];
143 const result = yield* runner
144 .run({ command: "npm", args: installArgs, timeout: INSTALL_TIMEOUT })
145 .pipe(
146 Effect.catchTags({
147 ProcessSpawnError: (error) =>
148 error.cause instanceof PlatformError.PlatformError &&
149 error.cause.reason._tag === "NotFound"
150 ? runner.run({
151 command: "pnpm",
152 args: ["--package=npm@11", "dlx", "npm", ...installArgs],
153 timeout: INSTALL_TIMEOUT,
154 })
155 : Effect.fail(error),
156 }),
157 Effect.mapError(fail("running npm install")),
158 );
159 if (result.code !== 0) {
160 return yield* new DeviceToolchainInstallError({
161 tool: spec.name,
162 step: "running npm install",
163 exitCode: Number(result.code),
164 cause: result,
165 });
166 }
167 const stagedEntry = path.join(stagingDir, "node_modules", spec.name, ...spec.entry);
168 if (!(yield* fs.exists(stagedEntry).pipe(Effect.orElseSucceed(() => false)))) {
169 return yield* new DeviceToolchainInstallError({
170 tool: spec.name,
171 step: "verifying the installed entry point",
172 });
173 }
174 yield* fs
175 .writeFileString(path.join(stagingDir, ".install-complete"), `${spec.version}\n`)
176 .pipe(Effect.mapError(fail("recording the completed install")));
177 yield* fs.rename(stagingDir, paths.installDir).pipe(
178 Effect.catch((cause) =>
179 // A concurrent server may have published the same version first.
180 isInstalled(fs, paths, spec.version).pipe(
181 Effect.flatMap((published) =>
182 published ? Effect.void : Effect.fail(fail("publishing the install")(cause)),
183 ),
184 ),
185 ),
186 );
187 return paths;
188 }).pipe(
189 Effect.ensuring(fs.remove(stagingDir, { recursive: true, force: true }).pipe(Effect.ignore)),
190 );
191});
192​
193const ensureTool = Effect.fn("DeviceToolchain.ensureTool")(function* (
194 baseDir: string,
195 spec: ToolSpec,
196 select: (paths: DeviceToolchainPaths) => DeviceToolPaths,
197) {
198 const path = yield* Path.Path;
199 const paths = deviceToolchainPaths(path, baseDir);
200 return yield* installLock.withPermit(installTool(spec, select(paths)));
201});
202​
203export const ensureDeviceHub = (baseDir: string) =>
204 ensureTool(baseDir, HUB_SPEC, (paths) => paths.hub);
205​
206export const ensureAgentDevice = (baseDir: string) =>
207 ensureTool(baseDir, AGENT_DEVICE_SPEC, (paths) => paths.agentDevice);
208​
209const isToolInstalled = Effect.fn("DeviceToolchain.isToolInstalled")(function* (
210 baseDir: string,
211 spec: ToolSpec,
212 select: (paths: DeviceToolchainPaths) => DeviceToolPaths,
213) {
214 const fs = yield* FileSystem.FileSystem;
215 const path = yield* Path.Path;
216 const paths = deviceToolchainPaths(path, baseDir);
217 return yield* isInstalled(fs, select(paths), spec.version);
218});
219​
220export const isDeviceHubInstalled = (baseDir: string) =>
221 isToolInstalled(baseDir, HUB_SPEC, (paths) => paths.hub);
222​
223export const isAgentDeviceInstalled = (baseDir: string) =>
224 isToolInstalled(baseDir, AGENT_DEVICE_SPEC, (paths) => paths.agentDevice);
225​
226/** Read completed installs without downloading or starting either tool. */
227export const deviceToolVersions = Effect.fn("DeviceToolchain.versions")(function* (
228 baseDir: string,
229 running: { hub?: string; agent?: string } = {},
230) {
231 const fs = yield* FileSystem.FileSystem;
232 const path = yield* Path.Path;
233 const inspect = Effect.fn("DeviceToolchain.inspect")(function* (spec: ToolSpec) {
234 const directory = path.join(baseDir, "tools", spec.name);
235 const names = yield* fs.readDirectory(directory).pipe(
236 Effect.catchIf(
237 (error) => error.reason._tag === "NotFound",
238 () => Effect.succeed([]),
239 ),
240 );
241 const versions = yield* Effect.filter(names, (version) =>
242 /^[0-9]+\.[0-9]+\.[0-9]+(?:-[a-zA-Z0-9.-]+)?$/.test(version)
243 ? Effect.gen(function* () {
244 const paths = toolPaths(path, baseDir, { ...spec, version });
245 const sentinel = yield* fs.readFileString(paths.sentinelPath).pipe(
246 Effect.catchIf(
247 (error) => error.reason._tag === "NotFound",
248 () => Effect.succeed(null),
249 ),
250 );
251 return sentinel?.trim() === version && (yield* fs.exists(paths.entryPath));
252 })
253 : Effect.succeed(false),
254 );
255 return {
256 requiredVersion: spec.version,
257 installedVersions: versions.sort(),
258 runningVersion: (spec.name === DEVICE_HUB_PACKAGE ? running.hub : running.agent) ?? null,
259 };
260 });
261 return yield* Effect.gen(function* () {
262 return {
263 hub: yield* inspect(HUB_SPEC),
264 agent: yield* inspect(AGENT_DEVICE_SPEC),
265 } satisfies DeviceToolVersions;
266 }).pipe(Effect.orElseSucceed(() => undefined));
267});