|
| 1 | +import { |
| 2 | + DeviceBootError, |
| 3 | + type DeviceHostId, |
| 4 | + DeviceOperationError, |
| 5 | + type DevicePlatform, |
| 6 | +} from "@t3tools/contracts"; |
| 7 | +import * as Duration from "effect/Duration"; |
| 8 | +import * as Effect from "effect/Effect"; |
| 9 | +import * as Schema from "effect/Schema"; |
| 10 | +import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; |
| 11 | + |
| 12 | +import type { DeviceHostReady, DeviceOperations, HostDevice } from "./DeviceHost.ts"; |
| 13 | + |
| 14 | +const BOOT_TIMEOUT = Duration.minutes(3); |
| 15 | +const SCREENSHOT_TIMEOUT = Duration.seconds(20); |
| 16 | + |
| 17 | +const 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 | +}); |
| 25 | +const 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 | +}); |
| 32 | +const 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 | + |
| 42 | +const 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`. */ |
| 46 | +export 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 warnings = hubList.errors?.filter( |
| 101 | + (error) => |
| 102 | + // CoreSimulator can retain deleted devices; their optional usage timestamps are absent. |
| 103 | + !( |
| 104 | + error.message.startsWith("[apple-utils] Failed to read CoreSimulator plist at ") && |
| 105 | + /\/CoreSimulator\/Devices\/[^/]+\/device\.plist:$/.test(error.message) && |
| 106 | + /(?:^Error:\s*ENOENT:|\bcode:\s*['"]ENOENT['"])/.test(error.error ?? "") |
| 107 | + ), |
| 108 | + ); |
| 109 | + const details = warnings?.map((error) => error.message) ?? []; |
| 110 | + let androidDiscoveryIncomplete = false; |
| 111 | + if (yield* options.androidAvailable) { |
| 112 | + const avds = yield* run("emulator", ["-list-avds"]); |
| 113 | + // Discovered devices stay listed; the AVDs that could not be listed are a warning. |
| 114 | + if (avds.code !== 0) { |
| 115 | + androidDiscoveryIncomplete = true; |
| 116 | + details.push( |
| 117 | + `Could not list Android virtual devices (emulator -list-avds, exit code ${avds.code}). Discovered devices remain available.`, |
| 118 | + ); |
| 119 | + } |
| 120 | + for (const name of (avds.code === 0 ? avds.stdout : "") |
| 121 | + .split(/\r?\n/) |
| 122 | + .map((line) => line.trim()) |
| 123 | + .filter(Boolean)) { |
| 124 | + if (!devices.some((device) => device.platform === "android" && device.name === name)) { |
| 125 | + devices.push({ |
| 126 | + id: name, |
| 127 | + name, |
| 128 | + platform: "android", |
| 129 | + version: "Android", |
| 130 | + booted: false, |
| 131 | + physical: false, |
| 132 | + }); |
| 133 | + } |
| 134 | + } |
| 135 | + } |
| 136 | + return { |
| 137 | + devices, |
| 138 | + detail: details.join("\n") || undefined, |
| 139 | + androidDiscoveryIncomplete, |
| 140 | + }; |
| 141 | + }).pipe(Effect.withSpan("DeviceHubOperations.list")); |
| 142 | + |
| 143 | + const boot: DeviceOperations["boot"] = Effect.fn("DeviceHubOperations.boot")(function* (device) { |
| 144 | + const result = yield* postJson( |
| 145 | + "/api/devices/boot", |
| 146 | + { platform: device.platform, id: device.id, name: device.name }, |
| 147 | + "boot", |
| 148 | + ).pipe(Effect.flatMap((request) => hubJson(request, HubActionResult, "boot", BOOT_TIMEOUT))); |
| 149 | + if (!result.ok) { |
| 150 | + // Keep the hub's launch command and nested failure available to agents for recovery. |
| 151 | + const diagnostics = [ |
| 152 | + result.error, |
| 153 | + ...(result.errors ?? []).flatMap((error) => [error.message, error.error]), |
| 154 | + ] |
| 155 | + .filter((text) => text?.trim()) |
| 156 | + .join("\n\n"); |
| 157 | + return yield* new DeviceBootError({ |
| 158 | + hostId, |
| 159 | + deviceId: device.id, |
| 160 | + reason: /insufficient.*(?:disk|space)|not enough.*(?:disk|space)|no space left/i.test( |
| 161 | + diagnostics, |
| 162 | + ) |
| 163 | + ? "disk_space" |
| 164 | + : /timed? out|timeout/i.test(diagnostics) |
| 165 | + ? "timeout" |
| 166 | + : "launch_failed", |
| 167 | + ...(diagnostics |
| 168 | + ? { |
| 169 | + diagnostics: |
| 170 | + diagnostics.length > 2_000 ? `${diagnostics.slice(0, 1_999)}…` : diagnostics, |
| 171 | + } |
| 172 | + : {}), |
| 173 | + cause: result, |
| 174 | + }); |
| 175 | + } |
| 176 | + if (device.platform === "ios") yield* attachIosStream(device.id, "boot"); |
| 177 | + return result.serial ?? result.id ?? device.id; |
| 178 | + }); |
| 179 | + |
| 180 | + const attach: DeviceOperations["attach"] = (device) => |
| 181 | + device.platform === "ios" |
| 182 | + ? attachIosStream(device.id, "open").pipe(Effect.asVoid) |
| 183 | + : Effect.void; |
| 184 | + |
| 185 | + const shutdown: DeviceOperations["shutdown"] = Effect.fn("DeviceHubOperations.shutdown")( |
| 186 | + function* (device) { |
| 187 | + const postShutdown = (path: string, body: Record<string, string>) => |
| 188 | + postJson(path, body, "shutdown").pipe( |
| 189 | + Effect.flatMap((request) => hubJson(request, HubActionResult, "shutdown")), |
| 190 | + Effect.flatMap((result) => |
| 191 | + result.ok |
| 192 | + ? Effect.void |
| 193 | + : Effect.fail( |
| 194 | + new DeviceOperationError({ |
| 195 | + operation: "shutdown", |
| 196 | + reason: "hub_rejected", |
| 197 | + cause: result, |
| 198 | + }), |
| 199 | + ), |
| 200 | + ), |
| 201 | + ); |
| 202 | + // serve-sim's shutdown closes its in-process capture session before it |
| 203 | + // runs `simctl shutdown`; the hub's generic shutdown can leave that |
| 204 | + // session cached across a reboot. serve-sim runs simctl bare, though, so |
| 205 | + // a simulator that is already off fails there. |
| 206 | + yield* device.platform === "ios" |
| 207 | + ? postShutdown(`${vendorPrefix("ios")}/grid/api/shutdown`, { udid: device.id }).pipe( |
| 208 | + Effect.catch((cause) => |
| 209 | + list.pipe( |
| 210 | + Effect.flatMap(({ devices }) => |
| 211 | + devices.find((candidate) => candidate.id === device.id)?.booted === false |
| 212 | + ? Effect.logInfo("iOS simulator was already shut down", { deviceId: device.id }) |
| 213 | + : Effect.fail(cause), |
| 214 | + ), |
| 215 | + ), |
| 216 | + ), |
| 217 | + ) |
| 218 | + : postShutdown("/api/devices/shutdown", { platform: device.platform, id: device.id }); |
| 219 | + }, |
| 220 | + ); |
| 221 | + |
| 222 | + const screenshot: DeviceOperations["screenshot"] = (device) => |
| 223 | + httpClient |
| 224 | + .execute( |
| 225 | + HttpClientRequest.post( |
| 226 | + `${origin}${vendorPrefix(device.platform)}/api/screenshot?device=${encodeURIComponent(device.id)}`, |
| 227 | + ), |
| 228 | + ) |
| 229 | + .pipe( |
| 230 | + Effect.flatMap(HttpClientResponse.filterStatusOk), |
| 231 | + Effect.flatMap((response) => response.arrayBuffer), |
| 232 | + Effect.map((buffer) => new Uint8Array(buffer)), |
| 233 | + Effect.scoped, |
| 234 | + Effect.timeout(SCREENSHOT_TIMEOUT), |
| 235 | + Effect.mapError( |
| 236 | + (cause) => |
| 237 | + new DeviceOperationError({ |
| 238 | + operation: "screenshot", |
| 239 | + reason: "request_failed", |
| 240 | + cause, |
| 241 | + }), |
| 242 | + ), |
| 243 | + Effect.withSpan("DeviceHubOperations.screenshot"), |
| 244 | + ); |
| 245 | + |
| 246 | + return { list, boot, attach, shutdown, screenshot }; |
| 247 | +}; |
0 commit comments