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

DeviceToolchain.ts

265 lines9.4 KB

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