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

DeviceHubOperations.ts

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