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

DeviceHubOperations.ts

296 lines11.4 KB

1import {
2 DeviceBootError,
3 type DeviceHostId,
4 DeviceOperationError,
5 type DevicePlatform,
6} from "@t3tools/contracts";
7import * as Duration from "effect/Duration";
8import * as Effect from "effect/Effect";
9import * as Option from "effect/Option";
10import * as Schema from "effect/Schema";
11import { HttpClient, HttpClientError, HttpClientRequest, HttpClientResponse } from "effect/http";
12​
13import type { DeviceHostReady, DeviceOperations, HostDevice } from "./DeviceHost.ts";
14​
15const BOOT_TIMEOUT = Duration.minutes(3);
16const SCREENSHOT_TIMEOUT = Duration.seconds(20);
17// Let the hub's 30 s simctl timeout report its cause first.
18const LIST_TIMEOUT_SECONDS = 40;
19// expo-device-hub 0.19.1 reports a failed simulator listing only as text; its error ids are hashes.
20const SIMULATOR_LIST_FAILED =
21 /^\[apple-utils\] (?:Failed to (?:run `xcrun simctl list devices|parse JSON output:|list devices:)|`xcrun simctl list devices --json` did not respond within )/;
22​
23const HubDevice = Schema.Struct({
24 id: Schema.String,
25 name: Schema.String,
26 version: Schema.String,
27 platform: Schema.Literals(["ios", "android"]),
28 booted: Schema.Boolean,
29 physical: Schema.Boolean,
30});
31const HubDeviceList = Schema.Struct({
32 simulators: Schema.Array(HubDevice),
33 emulators: Schema.Array(HubDevice),
34 errors: Schema.optional(
35 Schema.Array(Schema.Struct({ message: Schema.String, error: Schema.optional(Schema.String) })),
36 ),
37});
38const HubActionResult = Schema.Struct({
39 ok: Schema.Boolean,
40 id: Schema.optional(Schema.String),
41 serial: Schema.optional(Schema.String),
42 error: Schema.optional(Schema.String),
43 errors: Schema.optional(
44 Schema.Array(Schema.Struct({ message: Schema.String, error: Schema.optional(Schema.String) })),
45 ),
46});
47​
48// Hub diagnostics can carry a whole stderr dump.
49const boundDiagnostics = (text: string) =>
50 text.length > 2_000 ? `${text.slice(0, 1_999)}…` : text;
51​
52// The hub's `error` is a util.inspect of Node's exec error; the stack and the
53// inspected fields follow the first frame, so keep the lines before it.
54const errorHead = (error: string) => {
55 const lines = error.split(/\r?\n/);
56 const firstFrame = lines.findIndex((line) => /^\s+at /.test(line));
57 return (firstFrame === -1 ? lines : lines.slice(0, firstFrame))
58 .map((line) => line.trim())
59 .filter(Boolean)
60 .join(" ");
61};
62​
63const vendorPrefix = (platform: DevicePlatform) =>
64 platform === "ios" ? "/vendor/serve-sim" : "/vendor/serve-emu";
65​
66/** Device operations for a host that runs expo-device-hub at `origin`. */
67export const makeDeviceHubOperations = (options: {
68 readonly hostId: DeviceHostId;
69 readonly origin: string;
70 readonly http: HttpClient.HttpClient;
71 readonly run: DeviceHostReady["run"];
72 /** Android gates listing AVDs, which the hub does not report until they boot. */
73 readonly platformAvailable: (platform: DevicePlatform) => Effect.Effect<boolean>;
74}): DeviceOperations => {
75 const { hostId, origin, run } = options;
76 const httpClient = options.http.pipe(HttpClient.withScope);
77​
78 const fetchJson = Effect.fn("DeviceHubOperations.fetchJson")(function* <A, I>(
79 request: HttpClientRequest.HttpClientRequest,
80 schema: Schema.Codec<A, I>,
81 ) {
82 return yield* httpClient
83 .execute(request)
84 .pipe(
85 Effect.flatMap(HttpClientResponse.filterStatusOk),
86 Effect.flatMap(HttpClientResponse.schemaBodyJson(schema)),
87 Effect.scoped,
88 );
89 });
90​
91 const hubJson = <A, I>(
92 request: HttpClientRequest.HttpClientRequest,
93 schema: Schema.Codec<A, I>,
94 operation: string,
95 timeout: Duration.Input = Duration.seconds(15),
96 ) =>
97 fetchJson(request, schema).pipe(
98 Effect.timeout(timeout),
99 Effect.mapError(
100 (cause) => new DeviceOperationError({ operation, reason: "request_failed", cause }),
101 ),
102 );
103​
104 const postJson = (path: string, body: Record<string, string>, operation: string) =>
105 HttpClientRequest.post(`${origin}${path}`).pipe(
106 HttpClientRequest.bodyJson(body),
107 Effect.mapError(
108 (cause) => new DeviceOperationError({ operation, reason: "invalid_payload", cause }),
109 ),
110 );
111​
112 // Booting alone does not attach a serve-sim helper; the grid start does both
113 // and is idempotent for a booted simulator.
114 const attachIosStream = (udid: string, operation: string) =>
115 postJson(`${vendorPrefix("ios")}/grid/api/start`, { udid }, operation).pipe(
116 Effect.flatMap((request) => hubJson(request, HubActionResult, "attach stream", BOOT_TIMEOUT)),
117 );
118​
119 const list: DeviceOperations["list"] = Effect.gen(function* () {
120 const listed = yield* fetchJson(
121 HttpClientRequest.get(`${origin}/api/devices`),
122 HubDeviceList,
123 ).pipe(
124 Effect.mapError(
125 (cause) => new DeviceOperationError({ operation: "list", reason: "request_failed", cause }),
126 ),
127 Effect.timeoutOption(Duration.seconds(LIST_TIMEOUT_SECONDS)),
128 );
129 if (Option.isNone(listed)) {
130 return {
131 devices: [],
132 detail: `The device hub did not answer within ${LIST_TIMEOUT_SECONDS} seconds.`,
133 incompletePlatforms: yield* Effect.filter(["ios", "android"] as const, (platform) =>
134 options.platformAvailable(platform),
135 ),
136 };
137 }
138 const hubList = listed.value;
139 const devices: Array<HostDevice> = [...hubList.simulators, ...hubList.emulators];
140 const androidAvailable = yield* options.platformAvailable("android");
141 const warnings = hubList.errors?.filter(
142 (error) =>
143 // The host summary already explains a missing Android SDK; the hub's failed probes are noise.
144 !(!androidAvailable && error.message.startsWith("[android-utils] ")) &&
145 // CoreSimulator can retain deleted devices; their optional usage timestamps are absent.
146 !(
147 error.message.startsWith("[apple-utils] Failed to read CoreSimulator plist at ") &&
148 /\/CoreSimulator\/Devices\/[^/]+\/device\.plist:$/.test(error.message) &&
149 /(?:^Error:\s*ENOENT:|\bcode:\s*['"]ENOENT['"])/.test(error.error ?? "")
150 ),
151 );
152 const details =
153 warnings?.map((error) => {
154 const head = errorHead(error.error ?? "");
155 return boundDiagnostics(head ? `${error.message} ${head}` : error.message);
156 }) ?? [];
157 let androidDiscoveryIncomplete = false;
158 if (androidAvailable) {
159 const avds = yield* run("emulator", ["-list-avds"]);
160 // Discovered devices stay listed; the AVDs that could not be listed are a warning.
161 if (avds.code !== 0) {
162 androidDiscoveryIncomplete = true;
163 details.push(
164 `Could not list Android virtual devices (emulator -list-avds, exit code ${avds.code}). Discovered devices remain available.`,
165 );
166 }
167 for (const name of (avds.code === 0 ? avds.stdout : "")
168 .split(/\r?\n/)
169 .map((line) => line.trim())
170 .filter(Boolean)) {
171 if (!devices.some((device) => device.platform === "android" && device.name === name)) {
172 devices.push({
173 id: name,
174 name,
175 platform: "android",
176 version: "Android",
177 booted: false,
178 physical: false,
179 });
180 }
181 }
182 }
183 const simulatorsUnlisted =
184 hubList.simulators.length === 0 &&
185 (hubList.errors ?? []).some((error) => SIMULATOR_LIST_FAILED.test(error.message));
186 return {
187 devices,
188 detail: details.join("\n") || undefined,
189 androidDiscoveryIncomplete,
190 ...(simulatorsUnlisted ? { incompletePlatforms: ["ios"] as const } : {}),
191 };
192 }).pipe(Effect.withSpan("DeviceHubOperations.list"));
193​
194 const boot: DeviceOperations["boot"] = Effect.fn("DeviceHubOperations.boot")(function* (device) {
195 const result = yield* postJson(
196 "/api/devices/boot",
197 { platform: device.platform, id: device.id, name: device.name },
198 "boot",
199 ).pipe(Effect.flatMap((request) => hubJson(request, HubActionResult, "boot", BOOT_TIMEOUT)));
200 if (!result.ok) {
201 // Keep the hub's launch command and nested failure available to agents for recovery.
202 const diagnostics = [
203 result.error,
204 ...(result.errors ?? []).flatMap((error) => [error.message, error.error]),
205 ]
206 .filter((text) => text?.trim())
207 .join("\n\n");
208 return yield* new DeviceBootError({
209 hostId,
210 deviceId: device.id,
211 reason: /insufficient.*(?:disk|space)|not enough.*(?:disk|space)|no space left/i.test(
212 diagnostics,
213 )
214 ? "disk_space"
215 : /timed? out|timeout/i.test(diagnostics)
216 ? "timeout"
217 : "launch_failed",
218 ...(diagnostics ? { diagnostics: boundDiagnostics(diagnostics) } : {}),
219 cause: result,
220 });
221 }
222 if (device.platform === "ios") yield* attachIosStream(device.id, "boot");
223 return result.serial ?? result.id ?? device.id;
224 });
225​
226 const attach: DeviceOperations["attach"] = (device) =>
227 device.platform === "ios"
228 ? attachIosStream(device.id, "open").pipe(Effect.asVoid)
229 : Effect.void;
230​
231 const shutdown: DeviceOperations["shutdown"] = Effect.fn("DeviceHubOperations.shutdown")(
232 function* (device) {
233 const postShutdown = (path: string, body: Record<string, string>) =>
234 postJson(path, body, "shutdown").pipe(
235 Effect.flatMap((request) => hubJson(request, HubActionResult, "shutdown")),
236 Effect.flatMap((result) =>
237 result.ok
238 ? Effect.void
239 : Effect.fail(
240 new DeviceOperationError({
241 operation: "shutdown",
242 reason: "hub_rejected",
243 cause: result,
244 }),
245 ),
246 ),
247 );
248 // serve-sim's shutdown closes its in-process capture session before it
249 // runs `simctl shutdown`; the hub's generic shutdown can leave that
250 // session cached across a reboot. serve-sim runs simctl bare, though, so
251 // a simulator that is already off fails there.
252 yield* device.platform === "ios"
253 ? postShutdown(`${vendorPrefix("ios")}/grid/api/shutdown`, { udid: device.id }).pipe(
254 Effect.catch((cause) =>
255 list.pipe(
256 Effect.flatMap(({ devices }) =>
257 devices.find((candidate) => candidate.id === device.id)?.booted === false
258 ? Effect.logInfo("iOS simulator was already shut down", { deviceId: device.id })
259 : Effect.fail(cause),
260 ),
261 ),
262 ),
263 )
264 : postShutdown("/api/devices/shutdown", { platform: device.platform, id: device.id });
265 },
266 );
267​
268 const screenshot: DeviceOperations["screenshot"] = (device) =>
269 httpClient
270 .execute(
271 HttpClientRequest.post(
272 `${origin}${vendorPrefix(device.platform)}/api/screenshot?device=${encodeURIComponent(device.id)}`,
273 ),
274 )
275 .pipe(
276 Effect.flatMap(HttpClientResponse.filterStatusOk),
277 Effect.flatMap((response) => response.arrayBuffer),
278 Effect.map((buffer) => new Uint8Array(buffer)),
279 Effect.scoped,
280 Effect.timeout(SCREENSHOT_TIMEOUT),
281 Effect.mapError(
282 (cause) =>
283 new DeviceOperationError({
284 operation: "screenshot",
285 reason:
286 HttpClientError.isHttpClientError(cause) && cause.reason._tag === "StatusCodeError"
287 ? "hub_rejected"
288 : "request_failed",
289 cause,
290 }),
291 ),
292 Effect.withSpan("DeviceHubOperations.screenshot"),
293 );
294​
295 return { list, boot, attach, shutdown, screenshot };
296};