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

DeviceHubOperations.ts

423 lines16.6 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// The hub's Android shutdown waits up to 30 s for the emulator to leave adb after the kill.
18const ANDROID_SHUTDOWN_TIMEOUT = Duration.seconds(45);
19const ADB_DEVICES_TIMEOUT = Duration.seconds(10);
20// Let the hub's 30 s simctl timeout report its cause first.
21const LIST_TIMEOUT_SECONDS = 40;
22// expo-device-hub 0.19.1 reports a failed simulator listing only as text; its error ids are hashes.
23const SIMULATOR_LIST_FAILED =
24 /^\[apple-utils\] (?:Failed to (?:run `xcrun simctl list devices|parse JSON output:|list devices:)|`xcrun simctl list devices --json` did not respond within )/;
25// The hub passes numeric display IDs that Xcode 26 rejects; iOS 27 needs them for multiple displays.
26// expo-device-hub 0.22.1 returns no Android devices when avdmanager fails, before it runs adb.
27const AVDMANAGER_LIST_FAILED = "[android-utils] Failed to run `avdmanager list avd`";
28const GETPROP_LINE = /^\[([^\]]+)\]: \[(.*)\]$/;
29const runsOnXcode26Runtime = (version: string) => Number(/^iOS (\d+)/.exec(version)?.[1]) <= 26;
30const DEFAULT_DISPLAY_SCREENSHOT = `f=$(mktemp -t t3-screenshot) || exit 1
31trap 'rm -f "$f"' 0
32xcrun simctl io "$1" screenshot --type=png "$f" >/dev/null && base64 -i "$f"`;
33​
34const HubDevice = Schema.Struct({
35 id: Schema.String,
36 name: Schema.String,
37 version: Schema.String,
38 platform: Schema.Literals(["ios", "android"]),
39 booted: Schema.Boolean,
40 physical: Schema.Boolean,
41});
42const HubDeviceList = Schema.Struct({
43 simulators: Schema.Array(HubDevice),
44 emulators: Schema.Array(HubDevice),
45 errors: Schema.optional(
46 Schema.Array(Schema.Struct({ message: Schema.String, error: Schema.optional(Schema.String) })),
47 ),
48});
49const HubActionResult = Schema.Struct({
50 ok: Schema.Boolean,
51 id: Schema.optional(Schema.String),
52 serial: Schema.optional(Schema.String),
53 error: Schema.optional(Schema.String),
54 errors: Schema.optional(
55 Schema.Array(Schema.Struct({ message: Schema.String, error: Schema.optional(Schema.String) })),
56 ),
57});
58​
59// Hub diagnostics can carry a whole stderr dump.
60const boundDiagnostics = (text: string) =>
61 text.length > 2_000 ? `${text.slice(0, 1_999)}…` : text;
62​
63// The hub's `error` is a util.inspect of Node's exec error; the stack and the
64// inspected fields follow the first frame, so keep the lines before it.
65const errorHead = (error: string) => {
66 const lines = error.split(/\r?\n/);
67 const firstFrame = lines.findIndex((line) => /^\s+at /.test(line));
68 return (firstFrame === -1 ? lines : lines.slice(0, firstFrame))
69 .map((line) => line.trim())
70 .filter(Boolean)
71 .join(" ");
72};
73​
74const vendorPrefix = (platform: DevicePlatform) =>
75 platform === "ios" ? "/vendor/serve-sim" : "/vendor/serve-emu";
76​
77/** Device operations for a host that runs expo-device-hub at `origin`. */
78export const makeDeviceHubOperations = (options: {
79 readonly hostId: DeviceHostId;
80 readonly origin: string;
81 readonly token?: string | undefined;
82 readonly http: HttpClient.HttpClient;
83 readonly run: DeviceHostReady["run"];
84 /** Android gates listing AVDs, which the hub does not report until they boot. */
85 readonly platformAvailable: (platform: DevicePlatform) => Effect.Effect<boolean>;
86}): DeviceOperations => {
87 const { hostId, origin, run } = options;
88 const { token } = options;
89 const httpClient = (
90 token === undefined
91 ? options.http
92 : options.http.pipe(HttpClient.mapRequest(HttpClientRequest.bearerToken(token)))
93 ).pipe(HttpClient.withScope);
94​
95 const fetchJson = Effect.fn("DeviceHubOperations.fetchJson")(function* <A, I>(
96 request: HttpClientRequest.HttpClientRequest,
97 schema: Schema.Codec<A, I>,
98 ) {
99 return yield* httpClient
100 .execute(request)
101 .pipe(
102 Effect.flatMap(HttpClientResponse.filterStatusOk),
103 Effect.flatMap(HttpClientResponse.schemaBodyJson(schema)),
104 Effect.scoped,
105 );
106 });
107​
108 const hubJson = <A, I>(
109 request: HttpClientRequest.HttpClientRequest,
110 schema: Schema.Codec<A, I>,
111 operation: string,
112 timeout: Duration.Input = Duration.seconds(15),
113 ) =>
114 fetchJson(request, schema).pipe(
115 Effect.timeout(timeout),
116 Effect.mapError(
117 (cause) => new DeviceOperationError({ operation, reason: "request_failed", cause }),
118 ),
119 );
120​
121 const postJson = (path: string, body: Record<string, string>, operation: string) =>
122 HttpClientRequest.post(`${origin}${path}`).pipe(
123 HttpClientRequest.bodyJson(body),
124 Effect.mapError(
125 (cause) => new DeviceOperationError({ operation, reason: "invalid_payload", cause }),
126 ),
127 );
128​
129 // Booting alone does not attach a serve-sim helper; the grid start does both
130 // and is idempotent for a booted simulator.
131 const attachIosStream = (udid: string, operation: string) =>
132 postJson(`${vendorPrefix("ios")}/grid/api/start`, { udid }, operation).pipe(
133 Effect.flatMap((request) => hubJson(request, HubActionResult, "attach stream", BOOT_TIMEOUT)),
134 );
135​
136 // Mirrors the hub's own adb discovery for when it skips it.
137 const listAdbDevices = Effect.gen(function* () {
138 const listed = yield* run("adb", ["devices", "-l"]);
139 if (listed.code !== 0) return undefined;
140 const serials = listed.stdout
141 .split(/\r?\n/)
142 .map((line) => line.trim().split(/\s+/))
143 .flatMap(([serial, state]) => (serial && state === "device" ? [serial] : []));
144 return yield* Effect.forEach(serials, (serial) =>
145 Effect.gen(function* () {
146 const getprop = yield* run("adb", ["-s", serial, "shell", "getprop"]);
147 const props = new Map(
148 getprop.stdout.split(/\r?\n/).flatMap((line) => {
149 const match = GETPROP_LINE.exec(line.trim());
150 return match ? [[match[1]!, match[2]!] as const] : [];
151 }),
152 );
153 const emulator = props.get("ro.kernel.qemu") === "1" || props.get("ro.boot.qemu") === "1";
154 const avdName = emulator
155 ? (yield* run("adb", ["-s", serial, "emu", "avd", "name"])).stdout
156 .split(/\r?\n/)
157 .map((line) => line.trim())
158 .find((line) => line && line !== "OK" && !line.startsWith("KO"))
159 : undefined;
160 const model = props.get("ro.product.model");
161 const manufacturer = props.get("ro.product.manufacturer");
162 const release = props.get("ro.build.version.release");
163 return {
164 id: serial,
165 name: emulator
166 ? (avdName ?? serial)
167 : model
168 ? [manufacturer, model].filter(Boolean).join(" ")
169 : serial,
170 platform: "android",
171 version: release
172 ? `Android ${/^\d+$/.test(release) ? `${release}.0` : release}`
173 : "Android",
174 booted: true,
175 physical: !emulator,
176 } satisfies HostDevice;
177 }),
178 );
179 });
180​
181 const list: DeviceOperations["list"] = Effect.gen(function* () {
182 const listed = yield* fetchJson(
183 HttpClientRequest.get(`${origin}/api/devices`),
184 HubDeviceList,
185 ).pipe(
186 Effect.mapError(
187 (cause) => new DeviceOperationError({ operation: "list", reason: "request_failed", cause }),
188 ),
189 Effect.timeoutOption(Duration.seconds(LIST_TIMEOUT_SECONDS)),
190 );
191 if (Option.isNone(listed)) {
192 return {
193 devices: [],
194 detail: `The device hub did not answer within ${LIST_TIMEOUT_SECONDS} seconds.`,
195 incompletePlatforms: yield* Effect.filter(["ios", "android"] as const, (platform) =>
196 options.platformAvailable(platform),
197 ),
198 };
199 }
200 const hubList = listed.value;
201 const devices: Array<HostDevice> = [...hubList.simulators, ...hubList.emulators];
202 const androidAvailable = yield* options.platformAvailable("android");
203 const warnings = hubList.errors?.filter(
204 (error) =>
205 // The host summary already explains a missing Android SDK; the hub's failed probes are noise.
206 !(!androidAvailable && error.message.startsWith("[android-utils] ")) &&
207 // CoreSimulator can retain deleted devices; their optional usage timestamps are absent.
208 !(
209 error.message.startsWith("[apple-utils] Failed to read CoreSimulator plist at ") &&
210 /\/CoreSimulator\/Devices\/[^/]+\/device\.plist:$/.test(error.message) &&
211 /(?:^Error:\s*ENOENT:|\bcode:\s*['"]ENOENT['"])/.test(error.error ?? "")
212 ),
213 );
214 const details =
215 warnings?.map((error) => {
216 const head = errorHead(error.error ?? "");
217 return boundDiagnostics(head ? `${error.message} ${head}` : error.message);
218 }) ?? [];
219 let androidDiscoveryIncomplete = false;
220 if (androidAvailable) {
221 if (hubList.errors?.some((error) => error.message.startsWith(AVDMANAGER_LIST_FAILED))) {
222 const adbDevices = yield* listAdbDevices;
223 if (adbDevices === undefined) {
224 androidDiscoveryIncomplete = true;
225 details.push("Could not list Android devices (adb devices -l).");
226 } else {
227 devices.push(...adbDevices);
228 }
229 }
230 const avds = yield* run("emulator", ["-list-avds"]);
231 // Discovered devices stay listed; the AVDs that could not be listed are a warning.
232 if (avds.code !== 0) {
233 androidDiscoveryIncomplete = true;
234 details.push(
235 `Could not list Android virtual devices (emulator -list-avds, exit code ${avds.code}). Discovered devices remain available.`,
236 );
237 }
238 for (const name of (avds.code === 0 ? avds.stdout : "")
239 .split(/\r?\n/)
240 .map((line) => line.trim())
241 .filter(Boolean)) {
242 if (!devices.some((device) => device.platform === "android" && device.name === name)) {
243 devices.push({
244 id: name,
245 name,
246 platform: "android",
247 version: "Android",
248 booted: false,
249 physical: false,
250 });
251 }
252 }
253 }
254 const simulatorsUnlisted =
255 hubList.simulators.length === 0 &&
256 (hubList.errors ?? []).some((error) => SIMULATOR_LIST_FAILED.test(error.message));
257 return {
258 devices,
259 detail: details.join("\n") || undefined,
260 androidDiscoveryIncomplete,
261 ...(simulatorsUnlisted ? { incompletePlatforms: ["ios"] as const } : {}),
262 };
263 }).pipe(Effect.withSpan("DeviceHubOperations.list"));
264​
265 const boot: DeviceOperations["boot"] = Effect.fn("DeviceHubOperations.boot")(function* (device) {
266 const result = yield* postJson(
267 "/api/devices/boot",
268 { platform: device.platform, id: device.id, name: device.name },
269 "boot",
270 ).pipe(Effect.flatMap((request) => hubJson(request, HubActionResult, "boot", BOOT_TIMEOUT)));
271 if (!result.ok) {
272 // Keep the hub's launch command and nested failure available to agents for recovery.
273 const diagnostics = [
274 result.error,
275 ...(result.errors ?? []).flatMap((error) => [error.message, error.error]),
276 ]
277 .filter((text) => text?.trim())
278 .join("\n\n");
279 return yield* new DeviceBootError({
280 hostId,
281 deviceId: device.id,
282 reason: /insufficient.*(?:disk|space)|not enough.*(?:disk|space)|no space left/i.test(
283 diagnostics,
284 )
285 ? "disk_space"
286 : /timed? out|timeout/i.test(diagnostics)
287 ? "timeout"
288 : "launch_failed",
289 ...(diagnostics ? { diagnostics: boundDiagnostics(diagnostics) } : {}),
290 cause: result,
291 });
292 }
293 if (device.platform === "ios") yield* attachIosStream(device.id, "boot");
294 return result.serial ?? result.id ?? device.id;
295 });
296​
297 const attach: DeviceOperations["attach"] = (device) =>
298 device.platform === "ios"
299 ? attachIosStream(device.id, "open").pipe(Effect.asVoid)
300 : Effect.void;
301​
302 // The hub rejects a shutdown once `adb emu kill` has no serial left, as on a retry after an
303 // exit that outlasted the request. Like the hub, count an emulator as off once adb no longer
304 // lists its serial in any state.
305 const emulatorExited = (serial: string) =>
306 /^emulator-\d+$/.test(serial)
307 ? run("adb", ["devices"], { timeoutMs: Duration.toMillis(ADB_DEVICES_TIMEOUT) }).pipe(
308 Effect.map(
309 ({ code, stdout }) =>
310 code === 0 &&
311 !stdout.split(/\r?\n/).some((line) => line.trim().split(/\s+/)[0] === serial),
312 ),
313 Effect.orElseSucceed(() => false),
314 )
315 : Effect.succeed(false);
316​
317 const shutdown: DeviceOperations["shutdown"] = Effect.fn("DeviceHubOperations.shutdown")(
318 function* (device) {
319 const postShutdown = (path: string, body: Record<string, string>, timeout?: Duration.Input) =>
320 postJson(path, body, "shutdown").pipe(
321 Effect.flatMap((request) => hubJson(request, HubActionResult, "shutdown", timeout)),
322 Effect.flatMap((result) =>
323 result.ok
324 ? Effect.void
325 : Effect.fail(
326 new DeviceOperationError({
327 operation: "shutdown",
328 reason: "hub_rejected",
329 cause: result,
330 }),
331 ),
332 ),
333 );
334 // serve-sim's shutdown closes its in-process capture session before it
335 // runs `simctl shutdown`; the hub's generic shutdown can leave that
336 // session cached across a reboot. serve-sim runs simctl bare, though, so
337 // a simulator that is already off fails there.
338 yield* device.platform === "ios"
339 ? postShutdown(`${vendorPrefix("ios")}/grid/api/shutdown`, { udid: device.id }).pipe(
340 Effect.catch((cause) =>
341 list.pipe(
342 Effect.flatMap(({ devices }) =>
343 devices.find((candidate) => candidate.id === device.id)?.booted === false
344 ? Effect.logInfo("iOS simulator was already shut down", { deviceId: device.id })
345 : Effect.fail(cause),
346 ),
347 ),
348 ),
349 )
350 : postShutdown(
351 "/api/devices/shutdown",
352 { platform: device.platform, id: device.id },
353 ANDROID_SHUTDOWN_TIMEOUT,
354 ).pipe(
355 Effect.catch((cause) =>
356 emulatorExited(device.id).pipe(
357 Effect.flatMap((exited) =>
358 exited
359 ? Effect.logInfo("Android emulator has exited", {
360 deviceId: device.id,
361 })
362 : Effect.fail(cause),
363 ),
364 ),
365 ),
366 );
367 },
368 );
369​
370 const defaultDisplayScreenshot = Effect.fn("DeviceHubOperations.defaultDisplayScreenshot")(
371 function* (udid: string) {
372 const capture = yield* run("sh", ["-c", DEFAULT_DISPLAY_SCREENSHOT, "sh", udid], {
373 timeoutMs: Duration.toMillis(SCREENSHOT_TIMEOUT),
374 maxOutputBytes: 64 * 1024 * 1024,
375 });
376 if (capture.code !== 0) {
377 return yield* new DeviceOperationError({
378 operation: "screenshot",
379 reason: "command_failed",
380 exitCode: capture.code,
381 cause: capture.stderr.trim(),
382 });
383 }
384 return new Uint8Array(Buffer.from(capture.stdout, "base64"));
385 },
386 );
387​
388 const screenshot: DeviceOperations["screenshot"] = (device) =>
389 httpClient
390 .execute(
391 HttpClientRequest.post(
392 `${origin}${vendorPrefix(device.platform)}/api/screenshot?device=${encodeURIComponent(device.id)}`,
393 ),
394 )
395 .pipe(
396 Effect.flatMap(HttpClientResponse.filterStatusOk),
397 Effect.flatMap((response) => response.arrayBuffer),
398 Effect.map((buffer) => new Uint8Array(buffer)),
399 Effect.scoped,
400 Effect.timeout(SCREENSHOT_TIMEOUT),
401 Effect.mapError(
402 (cause) =>
403 new DeviceOperationError({
404 operation: "screenshot",
405 reason:
406 HttpClientError.isHttpClientError(cause) && cause.reason._tag === "StatusCodeError"
407 ? "hub_rejected"
408 : "request_failed",
409 cause,
410 }),
411 ),
412 Effect.catchIf(
413 (error) =>
414 device.platform === "ios" &&
415 runsOnXcode26Runtime(device.version) &&
416 error.reason === "hub_rejected",
417 () => defaultDisplayScreenshot(device.id),
418 ),
419 Effect.withSpan("DeviceHubOperations.screenshot"),
420 );
421​
422 return { list, boot, attach, shutdown, screenshot };
423};