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