Open History to see the last commit
1/**
2 * Cloud simulators from EAS Simulator. A device exists only while a session
3 * runs, and every session bills the Expo account until it stops, so this host
4 * bounds each one, stops all of them when it stops, and stops sessions a
5 * previous server left behind. It never touches sessions it did not start.
6 */
7import {
8 DeviceBootError,
9 type DeviceHostSummary,
10 DeviceHostUnavailableError,
11 DeviceOperationError,
12 type DevicePlatform,
13 type EasDeviceHostConfig,
14} from "@t3tools/contracts";
15import * as Cause from "effect/Cause";
16import * as Clock from "effect/Clock";
17import * as Duration from "effect/Duration";
18import * as Effect from "effect/Effect";
19import * as Exit from "effect/Exit";
20import * as Fiber from "effect/Fiber";
21import * as FiberSet from "effect/FiberSet";
22import * as FileSystem from "effect/FileSystem";
23import * as Option from "effect/Option";
24import * as Path from "effect/Path";
25import * as Random from "effect/Random";
26import * as Redacted from "effect/Redacted";
27import * as Schedule from "effect/Schedule";
28import * as Schema from "effect/Schema";
29import * as Semaphore from "effect/Semaphore";
30import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
31import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";
32import * as HostProcess from "@t3tools/shared/HostProcess";
33
34import * as ServerConfig from "../config.ts";
35import * as DeviceHost from "./DeviceHost.ts";
36import { findEasProjectId } from "./easProjectId.ts";
37import { type ExpoApi, makeExpoApi, resolveExpoCredential } from "./ExpoApi.ts";
38
39const POLL_INTERVAL = Duration.seconds(5);
40// How stale a running session's status may get before listing rechecks it.
41const STATUS_TTL_MS = 15_000;
42// Expo's own CLI waits this long once a worker picks the session up.
43const START_TIMEOUT = Duration.minutes(15);
44const PREVIEW_TIMEOUT = Duration.seconds(20);
45const SERVE_SIM_PREFIX = "/vendor/serve-sim";
46
47/** EAS picks the simulator model; one entry starts a session. */
48const CATALOG: ReadonlyArray<DeviceHost.HostDevice> = [
49 {
50 id: "eas-ios",
51 platform: "ios",
52 name: "iPhone (EAS Simulator)",
53 version: "Cloud",
54 booted: false,
55 physical: false,
56 },
57];
58
59interface RunningSession {
60 readonly sessionId: string;
61 readonly name: string;
62 readonly udid: string;
63 readonly preview: { readonly origin: string; readonly token: Redacted.Redacted<string> };
64 readonly agent: DeviceHost.AgentDaemonEndpoint;
65 /** Set once a stop has been asked for but Expo has not confirmed it. */
66 stopping: boolean;
67}
68
69/**
70 * Every session this host may have started, recorded by its unique name before
71 * Expo is asked to create it, so a server that crashes at any point can still
72 * find and stop the session on its next start.
73 */
74const LedgerEntry = Schema.Struct({
75 name: Schema.String,
76 appId: Schema.String,
77 recordedAt: Schema.Number,
78 /** Expo refused the create: nothing should run, but the reaper still looks. */
79 refused: Schema.optional(Schema.Boolean),
80});
81type LedgerEntry = typeof LedgerEntry.Type;
82const Ledger = Schema.fromJsonString(Schema.Array(LedgerEntry));
83const decodeLedger = Schema.decodeUnknownEffect(Ledger);
84const encodeLedger = Schema.encodeSync(Ledger);
85// How often listing looks for recorded sessions this host no longer tracks.
86const REAP_INTERVAL_MS = 60_000;
87// Expo's ready queue is unbounded despite its 115-minute session limit and five-minute cleanup.
88// Unlisted sessions stop counting after this lifetime; forget their records only once
89// confirmed not running or after a day unconfirmed.
90const RECORD_LIFETIME_MS = 180 * 60_000;
91const RECORD_MAX_AGE_MS = 24 * 60 * 60_000;
92// Expo lists a session it made within seconds; a create with an unknown
93// outcome stops counting against the limit once it has had this long.
94const UNCERTAIN_CREATE_MS = 5 * 60_000;
95// One failed request to Expo during a minutes-long start does not end the start.
96const TRANSIENT_RETRY = { times: 3, schedule: Schedule.spaced("2 seconds") } as const;
97const decodePreviewApi = Schema.decodeUnknownEffect(Schema.Struct({ device: Schema.String }));
98
99/** A malformed escape names no device, so the proxy answers 404 instead of failing. */
100const decodePathSegment = (segment: string): string | null => {
101 try {
102 return decodeURIComponent(segment);
103 } catch {
104 return null;
105 }
106};
107
108export const make = Effect.fn("EasDeviceHost.make")(function* (config: EasDeviceHostConfig) {
109 const http = yield* HttpClient.HttpClient;
110 const fs = yield* FileSystem.FileSystem;
111 const path = yield* Path.Path;
112 const server = yield* ServerConfig.ServerConfig;
113 const services = yield* Effect.context<
114 FileSystem.FileSystem | Path.Path | Effect.Services<ReturnType<typeof findEasProjectId>>
115 >();
116 const hostId = config.id;
117 const ledgerPath = path.join(server.stateDir, "device", "eas", `${hostId}.json`);
118 // Keyed by Expo's session id, which is also the device id: every EAS
119 // simulator reports the same UDID, so the UDID cannot tell sessions apart.
120 const sessions = new Map<string, RunningSession>();
121 const checkedAt = new Map<string, number>();
122 const startLock = yield* Semaphore.make(1);
123 const ledgerLock = yield* Semaphore.make(1);
124 // One sweep at a time: two would stop the same session twice.
125 const reapLock = yield* Semaphore.make(1);
126 // Starts run in the host rather than the caller: a client that disconnects
127 // while a session boots leaves it running and tracked, and stopping or
128 // closing the host interrupts the start, which then stops its session.
129 const starts = yield* FiberSet.make<string, unknown>();
130 // The startup sweep for recorded leftovers.
131 const background = yield* FiberSet.make<void, never>();
132 // Sessions this host owns that `sessions` does not hold: starts in progress,
133 // and sessions whose stop after a failed start failed too. The reaper leaves
134 // them alone and they count against the limit.
135 const starting = new Set<string>();
136 const unresolved = new Map<string, { readonly sessionId: string }>();
137 // Creates whose outcome is unknown (no answer, or a server error), and
138 // fresh records a previous server left: Expo may have made the session.
139 // Each listing looks for it, and it counts against the limit until found
140 // or until Expo would have listed it by now. The reaper handles these.
141 const uncertain = new Map<string, { readonly entry: LedgerEntry; readonly until: number }>();
142 const ownedNames = () =>
143 new Set([
144 ...[...sessions.values()].map((session) => session.name),
145 ...starting,
146 ...unresolved.keys(),
147 ]);
148 // Bumped whenever the host stops its sessions, so a start that finishes
149 // afterwards stops its own session instead of leaving it untracked.
150 let epoch = 0;
151 // Set once the host's scope closes. A listing still running on this
152 // instance then neither sweeps nor writes the ledger: a replacement with
153 // the same id owns the sessions and the record now.
154 let closed = false;
155 let reapedAt = 0;
156 let ready: DeviceHost.DeviceHostReady | null = null;
157
158 const unavailable = (reason: string, cause?: unknown) =>
159 new DeviceHostUnavailableError({
160 hostId,
161 hostLabel: config.label,
162 reason,
163 ...(cause === undefined ? {} : { cause }),
164 });
165
166 const api: Effect.Effect<ExpoApi, DeviceHostUnavailableError> = resolveExpoCredential(
167 config.accessToken,
168 ).pipe(
169 Effect.map((credential) => makeExpoApi(http, credential)),
170 Effect.provide(services),
171 Effect.mapError((error) => unavailable(error.message, error)),
172 );
173
174 /** A missing ledger is empty; an unreadable one is an error, never an empty list. */
175 const readLedger = fs.readFileString(ledgerPath).pipe(
176 Effect.catchIf(
177 (error) => error.reason._tag === "NotFound",
178 () => Effect.succeed("[]"),
179 ),
180 Effect.flatMap(decodeLedger),
181 Effect.mapError((cause) =>
182 unavailable(
183 `The record of running EAS sessions at ${ledgerPath} could not be read. Fix or remove it.`,
184 cause,
185 ),
186 ),
187 );
188 const writeLedger = Effect.fn("EasDeviceHost.writeLedger")(function* (
189 update: (entries: ReadonlyArray<LedgerEntry>) => ReadonlyArray<LedgerEntry>,
190 ) {
191 if (closed) return yield* unavailable(`${config.label} was replaced or removed.`);
192 const entries = update(yield* readLedger);
193 yield* writeFileStringAtomically({
194 filePath: ledgerPath,
195 contents: encodeLedger(entries),
196 }).pipe(
197 Effect.provide(services),
198 Effect.mapError((cause) =>
199 unavailable(
200 `The record of running EAS sessions at ${ledgerPath} could not be written.`,
201 cause,
202 ),
203 ),
204 );
205 }, ledgerLock.withPermit);
206 const markRefused = (name: string) =>
207 writeLedger((entries) =>
208 entries.map((entry) => (entry.name === name ? { ...entry, refused: true } : entry)),
209 ).pipe(
210 Effect.catch((cause) =>
211 Effect.logWarning("Could not update the EAS session record", { name, cause }),
212 ),
213 );
214 const forgetEntry = (name: string) =>
215 writeLedger((entries) => entries.filter((entry) => entry.name !== name)).pipe(
216 Effect.catch((cause) =>
217 Effect.logWarning("Could not update the EAS session record", { name, cause }),
218 ),
219 );
220
221 /** Stops a session and, once Expo confirms it, drops it from the ledger. */
222 const stopSession = (expo: ExpoApi, sessionId: string, name: string) =>
223 expo.stop(sessionId).pipe(
224 Effect.andThen(forgetEntry(name)),
225 Effect.tapError((cause) =>
226 Effect.logWarning("Could not stop EAS Simulator session", { sessionId, cause }),
227 ),
228 );
229
230 /** Finds recorded sessions by name, so a session whose id never arrived is found too. */
231 const stopRecorded = (expo: ExpoApi, entries: ReadonlyArray<LedgerEntry>) => {
232 const found = new Set<string>();
233 const listed = new Set<string>();
234 return Effect.forEach(
235 [...new Set(entries.map((entry) => entry.appId))],
236 (appId) =>
237 expo.activeSessions(appId).pipe(
238 Effect.flatMap((active) =>
239 Effect.forEach(
240 entries.filter((entry) => entry.appId === appId),
241 (entry) =>
242 Effect.gen(function* () {
243 const running = active.filter((session) => session.name === entry.name);
244 if (running.length > 0) {
245 found.add(entry.name);
246 return yield* Effect.forEach(
247 running,
248 (session) =>
249 stopSession(expo, session.id, entry.name).pipe(
250 // Still running and billed: owned, counted, and retried by listing.
251 Effect.catch(() =>
252 Effect.sync(
253 () => void unresolved.set(entry.name, { sessionId: session.id }),
254 ),
255 ),
256 ),
257 { discard: true },
258 );
259 }
260 }),
261 { discard: true },
262 ),
263 ),
264 Effect.tap(() => Effect.sync(() => void listed.add(appId))),
265 Effect.ignore,
266 ),
267 { discard: true, concurrency: 4 },
268 ).pipe(
269 Effect.as({ found, listed } as {
270 readonly found: ReadonlySet<string>;
271 /** The apps whose listing succeeded; a failed one rules nothing out. */
272 readonly listed: ReadonlySet<string>;
273 }),
274 );
275 };
276
277 /**
278 * Retries the stop of a session whose stop failed. A session Expo already
279 * ended is let go even if stopping it keeps failing.
280 */
281 const retryUnresolved = (expo: ExpoApi, name: string, sessionId: string) =>
282 stopSession(expo, sessionId, name).pipe(
283 Effect.catch(() =>
284 expo
285 .session(sessionId)
286 .pipe(
287 Effect.flatMap((current) =>
288 current.status === "STOPPED" || current.status === "ERRORED"
289 ? forgetEntry(name)
290 : Effect.fail(current.status),
291 ),
292 ),
293 ),
294 Effect.andThen(Effect.sync(() => void unresolved.delete(name))),
295 Effect.ignore,
296 );
297
298 /**
299 * Records a previous server left count against the limit until a sweep
300 * finds them (a fresh one until Expo would have listed it by now), so a
301 * restart cannot start past it.
302 */
303 const adoptRecorded = Effect.gen(function* () {
304 const now = yield* Clock.currentTimeMillis;
305 const owned = ownedNames();
306 for (const entry of yield* readLedger) {
307 const until = Math.max(entry.recordedAt + UNCERTAIN_CREATE_MS, now);
308 // A refused create made nothing: its record is for the reaper only.
309 if (!owned.has(entry.name) && !entry.refused) uncertain.set(entry.name, { entry, until });
310 }
311 }).pipe(Effect.ignore);
312
313 /**
314 * Stops recorded sessions this host does not own: a previous server's, or
315 * a failed or uncertain start's. An uncertain one found (stopped, or
316 * unresolved if that failed) or long enough unlisted frees its slot; its
317 * record stays until it expires.
318 */
319 const reapLeftovers = Effect.fn("EasDeviceHost.reapLeftovers")(
320 function* (expo: ExpoApi) {
321 if (closed) return;
322 reapedAt = yield* Clock.currentTimeMillis;
323 const entries = yield* readLedger;
324 const owned = ownedNames();
325 const leftovers = entries.filter((entry) => !owned.has(entry.name));
326 const { found, listed } = yield* stopRecorded(expo, leftovers);
327 for (const [name, { entry, until }] of uncertain) {
328 if (found.has(name) || (reapedAt >= until && listed.has(entry.appId))) {
329 uncertain.delete(name);
330 }
331 }
332 // Expo has ended these by now unless they waited in its queue: the slot
333 // goes whatever the listing says (the app may be gone, or belong to
334 // another account); the record goes once a listing confirms Expo does
335 // not run it, or once no queue could have held it.
336 for (const entry of leftovers) {
337 const age = reapedAt - entry.recordedAt;
338 if (age > RECORD_LIFETIME_MS) uncertain.delete(entry.name);
339 if (found.has(entry.name)) continue;
340 if ((age > RECORD_LIFETIME_MS && listed.has(entry.appId)) || age > RECORD_MAX_AGE_MS) {
341 yield* forgetEntry(entry.name);
342 }
343 }
344 },
345 reapLock.withPermit,
346 Effect.catch((cause) =>
347 Effect.logWarning("Could not stop recorded EAS Simulator sessions", { cause }),
348 ),
349 );
350
351 const previewDevice = (origin: string, token: Redacted.Redacted<string>) =>
352 http
353 .execute(
354 HttpClientRequest.get(`${origin}/api`).pipe(
355 HttpClientRequest.bearerToken(Redacted.value(token)),
356 ),
357 )
358 .pipe(
359 Effect.flatMap(HttpClientResponse.filterStatusOk),
360 Effect.flatMap((response) => response.json),
361 Effect.flatMap(decodePreviewApi),
362 Effect.map((api) => api.device),
363 Effect.scoped,
364 Effect.timeout(PREVIEW_TIMEOUT),
365 Effect.retry(TRANSIENT_RETRY),
366 );
367
368 const awaitRunning = Effect.fn("EasDeviceHost.awaitRunning")(
369 function* (expo: ExpoApi, sessionId: string) {
370 for (;;) {
371 const session = yield* expo.session(sessionId).pipe(
372 Effect.retry(TRANSIENT_RETRY),
373 Effect.mapError((error) => unavailable(error.message, error)),
374 );
375 if (session.status === "STOPPED" || session.status === "ERRORED") {
376 return yield* new DeviceBootError({
377 hostId,
378 deviceId: sessionId,
379 reason: "launch_failed",
380 cause: new Error(`EAS Simulator session ended (${session.status}) before it was ready`),
381 });
382 }
383 if (session.status === "IN_PROGRESS" && session.endpoints) return session.endpoints;
384 yield* Effect.sleep(POLL_INTERVAL);
385 }
386 },
387 (poll, _expo, sessionId) =>
388 poll.pipe(
389 Effect.timeoutOrElse({
390 duration: START_TIMEOUT,
391 orElse: () =>
392 Effect.fail(
393 new DeviceBootError({
394 hostId,
395 deviceId: sessionId,
396 reason: "timeout",
397 cause: new Error("EAS Simulator session did not start in time"),
398 }),
399 ),
400 }),
401 ),
402 );
403
404 const reserveSlot = (name: string) =>
405 startLock.withPermit(
406 Effect.suspend(() => {
407 const pending = unresolved.size + uncertain.size;
408 if (sessions.size + starting.size + pending >= config.maxConcurrentSessions) {
409 const limit = `${config.label} is limited to ${config.maxConcurrentSessions} running ${config.maxConcurrentSessions === 1 ? "session" : "sessions"}.`;
410 return Effect.fail(
411 unavailable(
412 pending > 0
413 ? `${limit} ${pending === 1 ? "A session" : `${pending} sessions`} that failed to start or stop ${pending === 1 ? "is" : "are"} still being cleaned up; try again shortly.`
414 : `${limit} Close one in the Device panel first.`,
415 ),
416 );
417 }
418 starting.add(name);
419 return Effect.void;
420 }),
421 );
422
423 const startSession = Effect.fn("EasDeviceHost.startSession")(function* (
424 device: DeviceHost.HostDevice,
425 context: DeviceHost.DeviceOpenContext | undefined,
426 startedIn: number,
427 ) {
428 const name = `T3 Code · ${config.label} · ${(yield* Random.nextIntBetween(0, 0xffffff)).toString(16).padStart(6, "0")}`;
429 // The credential comes first: without one, the answer is how to sign in,
430 // not that the limit is reached.
431 const expo = yield* api;
432 return yield* Effect.acquireUseRelease(
433 reserveSlot(name),
434 () =>
435 Effect.gen(function* () {
436 const appId =
437 config.appId ??
438 Option.getOrUndefined(
439 context?.workspaceRoot
440 ? yield* findEasProjectId(context.workspaceRoot).pipe(Effect.provide(services))
441 : Option.none<string>(),
442 );
443 if (!appId) {
444 return yield* unavailable(
445 "No EAS project to run the session under. Choose one for this host in Settings, or open the device from a thread whose project names extra.eas.projectId in app.json or its app config.",
446 );
447 }
448 const access = yield* expo
449 .availability(appId)
450 .pipe(Effect.mapError((error) => unavailable(error.message, error)));
451 if (!access.available) {
452 return yield* unavailable(
453 `EAS Simulator is not enabled for the ${access.account} Expo account.`,
454 );
455 }
456 const entry = { name, appId, recordedAt: yield* Clock.currentTimeMillis };
457 // Recorded first: a session the ledger cannot hold is never started.
458 yield* writeLedger((entries) => [...entries, entry]);
459 if (epoch !== startedIn) {
460 yield* forgetEntry(name);
461 return yield* unavailable(`${config.label} was stopped while the session started.`);
462 }
463 // Create runs uninterrupted (Expo's API answers within 30 seconds) and
464 // the stop below is in place before anything can interrupt the start,
465 // so a session Expo made is always either tracked or stopped.
466 return yield* Effect.uninterruptibleMask((restore) =>
467 Effect.gen(function* () {
468 const sessionId = yield* expo
469 .create({
470 appId,
471 platform: device.platform,
472 name,
473 maxRunTimeMinutes: config.maxSessionMinutes,
474 maxIdleTimeMinutes: config.idleMinutes,
475 })
476 .pipe(
477 // Unless Expo refused, it may have made the session before
478 // failing to answer. Unlisted, it stays counted for a while.
479 // Refused, it made nothing: the slot frees, but the record
480 // stays for the reaper in case the refusal was misread.
481 Effect.tapError((error) =>
482 error.rejected
483 ? stopRecorded(expo, [entry]).pipe(
484 Effect.flatMap(({ found }) =>
485 found.has(name) ? Effect.void : markRefused(name),
486 ),
487 )
488 : stopRecorded(expo, [entry]).pipe(
489 Effect.flatMap(({ found }) =>
490 found.has(name)
491 ? Effect.void
492 : Effect.map(Clock.currentTimeMillis, (now) => {
493 uncertain.set(name, {
494 entry,
495 until: now + UNCERTAIN_CREATE_MS,
496 });
497 }),
498 ),
499 ),
500 ),
501 Effect.mapError((error) => unavailable(error.message, error)),
502 );
503 return yield* restore(trackSession(expo, sessionId, name, startedIn)).pipe(
504 Effect.onError(() =>
505 stopSession(expo, sessionId, name).pipe(
506 // Still running and billed: owned, counted, and retried by listing.
507 Effect.catch(() => Effect.sync(() => void unresolved.set(name, { sessionId }))),
508 ),
509 ),
510 );
511 }),
512 );
513 }),
514 () => Effect.sync(() => void starting.delete(name)),
515 );
516 });
517
518 /** Waits for a created session and starts tracking it. */
519 const trackSession = Effect.fn("EasDeviceHost.trackSession")(function* (
520 expo: ExpoApi,
521 sessionId: string,
522 name: string,
523 startedIn: number,
524 ) {
525 const endpoints = yield* awaitRunning(expo, sessionId);
526 if (!endpoints.preview) {
527 return yield* new DeviceBootError({
528 hostId,
529 deviceId: sessionId,
530 reason: "launch_failed",
531 cause: new Error("EAS Simulator returned no preview endpoint"),
532 });
533 }
534 const origin = new URL(endpoints.preview.url).origin;
535 const udid = yield* previewDevice(origin, endpoints.preview.token).pipe(
536 Effect.mapError(
537 (cause) =>
538 new DeviceBootError({
539 hostId,
540 deviceId: sessionId,
541 reason: "launch_failed",
542 cause,
543 }),
544 ),
545 );
546 if (epoch !== startedIn) {
547 return yield* unavailable(`${config.label} was stopped while the session started.`);
548 }
549 sessions.set(sessionId, {
550 sessionId,
551 name,
552 udid,
553 preview: { origin, token: endpoints.preview.token },
554 agent: {
555 baseUrl: endpoints.agentDevice.url,
556 token: Redacted.value(endpoints.agentDevice.token),
557 },
558 stopping: false,
559 });
560 return sessionId;
561 });
562
563 const sessionFor = (deviceId: string) => Option.fromNullishOr(sessions.get(deviceId));
564
565 const forget = (session: RunningSession) =>
566 Effect.sync(() => {
567 sessions.delete(session.sessionId);
568 checkedAt.delete(session.sessionId);
569 });
570
571 /**
572 * Expo ends sessions on its own at their run or idle limit; stop listing
573 * those. A stop that failed earlier is retried, and recorded sessions nothing
574 * tracks are reaped now and then.
575 */
576 const dropEnded = Effect.gen(function* () {
577 if (closed) return;
578 const now = yield* Clock.currentTimeMillis;
579 const stale = [...sessions.values()].filter(
580 (session) =>
581 session.stopping || now - (checkedAt.get(session.sessionId) ?? 0) > STATUS_TTL_MS,
582 );
583 const reapDue = now - reapedAt > REAP_INTERVAL_MS;
584 if (stale.length === 0 && unresolved.size === 0 && uncertain.size === 0 && !reapDue) return;
585 const reap = reapDue || uncertain.size > 0;
586 if (reap) reapedAt = now;
587 const expo = yield* api.pipe(
588 // Without a credential no sweep can look; a record Expo would have
589 // listed by now still stops counting, so the limit is not held forever.
590 Effect.tapError(() =>
591 Effect.sync(() => {
592 for (const [name, { until }] of uncertain) if (now >= until) uncertain.delete(name);
593 }),
594 ),
595 );
596 yield* Effect.forEach(
597 [...unresolved],
598 ([name, { sessionId }]) => retryUnresolved(expo, name, sessionId),
599 { discard: true, concurrency: 4 },
600 );
601 yield* Effect.forEach(
602 stale,
603 (session) =>
604 (session.stopping
605 ? stopSession(expo, session.sessionId, session.name).pipe(
606 Effect.andThen(forget(session)),
607 // A session Expo already ended is let go even if stopping it keeps failing.
608 Effect.catch(() =>
609 expo
610 .session(session.sessionId)
611 .pipe(
612 Effect.flatMap((current) =>
613 current.status === "STOPPED" || current.status === "ERRORED"
614 ? forget(session).pipe(Effect.andThen(forgetEntry(session.name)))
615 : Effect.fail(current.status),
616 ),
617 ),
618 ),
619 )
620 : expo
621 .session(session.sessionId)
622 .pipe(
623 Effect.flatMap((current) =>
624 current.status === "STOPPED" || current.status === "ERRORED"
625 ? forget(session).pipe(Effect.andThen(forgetEntry(session.name)))
626 : Effect.sync(() => void checkedAt.set(session.sessionId, now)),
627 ),
628 )
629 ).pipe(Effect.ignore),
630 { discard: true, concurrency: 4 },
631 );
632 if (reap) yield* reapLeftovers(expo);
633 }).pipe(Effect.ignore);
634
635 /**
636 * Stops a tracked session. Until Expo confirms, it stays tracked: listed,
637 * counted against the limit, and retried by the next listing.
638 */
639 const stopTracked = (expo: ExpoApi, session: RunningSession) =>
640 Effect.suspend(() => {
641 session.stopping = true;
642 return stopSession(expo, session.sessionId, session.name);
643 }).pipe(Effect.andThen(forget(session)));
644
645 const devices: DeviceHost.DeviceOperations = {
646 list: dropEnded.pipe(
647 Effect.andThen(
648 Effect.sync(() => ({
649 devices: [
650 ...CATALOG,
651 ...[...sessions.values()].map((session): DeviceHost.HostDevice => ({
652 id: session.sessionId,
653 platform: "ios",
654 name: "iPhone (EAS Simulator)",
655 version: "Cloud",
656 booted: true,
657 physical: false,
658 })),
659 ],
660 detail: undefined,
661 })),
662 ),
663 ),
664 boot: (device, context) => {
665 if (sessions.has(device.id)) return Effect.succeed(device.id);
666 // Read before anything yields, so a stop that lands while the start
667 // reads settings or files is seen.
668 const startedIn = epoch;
669 return startSession(device, context, startedIn).pipe(
670 FiberSet.run(starts),
671 Effect.flatMap(Fiber.await),
672 Effect.flatMap((exit) =>
673 Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)
674 ? Effect.fail(unavailable(`${config.label} was stopped while the session started.`))
675 : exit,
676 ),
677 );
678 },
679 attach: () => Effect.void,
680 shutdown: (device) =>
681 Option.match(sessionFor(device.id), {
682 onNone: () => Effect.void,
683 onSome: (session) =>
684 api.pipe(
685 Effect.flatMap((expo) => stopTracked(expo, session)),
686 Effect.asVoid,
687 Effect.mapError(
688 (cause) =>
689 new DeviceOperationError({
690 operation: "shutdown",
691 reason: "request_failed",
692 cause,
693 }),
694 ),
695 ),
696 }),
697 screenshot: (device) =>
698 Option.match(sessionFor(device.id), {
699 onNone: () =>
700 Effect.fail(
701 new DeviceOperationError({
702 operation: "screenshot",
703 reason: "request_failed",
704 cause: new Error("The EAS Simulator session is not running"),
705 }),
706 ),
707 onSome: (session) =>
708 http
709 .execute(
710 HttpClientRequest.post(
711 `${session.preview.origin}/api/screenshot?device=${encodeURIComponent(session.udid)}`,
712 ).pipe(HttpClientRequest.bearerToken(Redacted.value(session.preview.token))),
713 )
714 .pipe(
715 Effect.flatMap(HttpClientResponse.filterStatusOk),
716 Effect.flatMap((response) => response.arrayBuffer),
717 Effect.map((buffer) => new Uint8Array(buffer)),
718 Effect.scoped,
719 Effect.timeout(PREVIEW_TIMEOUT),
720 Effect.mapError(
721 (cause) =>
722 new DeviceOperationError({
723 operation: "screenshot",
724 reason: "request_failed",
725 cause,
726 }),
727 ),
728 ),
729 }),
730 agentEndpoint: (deviceId) =>
731 Option.match(sessionFor(deviceId), {
732 onNone: () => Effect.fail(unavailable("This EAS Simulator device is no longer running.")),
733 // agent-device selects the simulator by its UDID, not the session id T3 shows.
734 onSome: (session) => Effect.succeed({ ...session.agent, agentDeviceId: session.udid }),
735 }),
736 endsDevices: true,
737 };
738
739 /**
740 * serve-sim runs at the root of each session's preview host and wants its
741 * token on every request. Clients name the device by its session id; serve-sim
742 * knows it by its UDID, so the id is swapped for the UDID in the path and in
743 * the `device` parameter.
744 */
745 const upstream: NonNullable<DeviceHost.DeviceHostReady["upstream"]> = (hubPath, search) =>
746 Effect.sync(() => {
747 if (!hubPath.startsWith(`${SERVE_SIM_PREFIX}/`)) return null;
748 const helper = /^\/vendor\/serve-sim\/helper\/([^/]+)\//.exec(hubPath);
749 const deviceId = helper ? decodePathSegment(helper[1]!) : search.get("device");
750 if (helper && deviceId === null) return null;
751 const session =
752 deviceId !== null && deviceId !== undefined
753 ? sessions.get(deviceId)
754 : sessions.size === 1
755 ? [...sessions.values()][0]
756 : undefined;
757 if (!session) return null;
758 const path = helper
759 ? `/helper/${encodeURIComponent(session.udid)}${hubPath.slice(helper[0].length - 1)}`
760 : hubPath.slice(SERVE_SIM_PREFIX.length);
761 const params = new URLSearchParams(search);
762 if (params.has("device")) params.set("device", session.udid);
763 const query = params.size > 0 ? `?${params.toString()}` : "";
764 const token = Redacted.value(session.preview.token);
765 return {
766 url: `${session.preview.origin}${path}${query}`,
767 headers: { authorization: `Bearer ${token}` },
768 protocols: [`serve-sim.token.${token}`],
769 };
770 });
771
772 const nodePath = yield* HostProcess.ExecutablePath;
773 const ensureReady: DeviceHost.DeviceHost["Service"]["ensureReady"] = Effect.fn(
774 "EasDeviceHost.ensureReady",
775 )(function* () {
776 if (ready) return ready;
777 yield* adoptRecorded;
778 // Without a credential the host is still ready: opening a device then
779 // says how to sign in, and listing reaps once one is there.
780 yield* FiberSet.run(background)(api.pipe(Effect.flatMap(reapLeftovers), Effect.ignore));
781 ready = {
782 nodePath,
783 hub: { origin: "https://api.expo.dev" },
784 devices,
785 upstream,
786 // Device settings run simctl on the simulator's own machine, which EAS does not expose.
787 run: () =>
788 Effect.succeed({
789 stdout: "",
790 stderr: "EAS Simulator devices cannot run host commands.",
791 code: 127,
792 }),
793 helpers: { serveSimAxSettings: null, serveSimCli: null },
794 };
795 return ready;
796 });
797
798 // A session whose stop fails stays tracked for the next listing to retry,
799 // and stays in the ledger for the next server if this one closes first.
800 const stopAll = Effect.gen(function* () {
801 epoch++;
802 // Interrupted starts stop the sessions they created before this returns.
803 yield* FiberSet.clear(starts);
804 yield* FiberSet.clear(background);
805 const expo = yield* api;
806 yield* Effect.forEach(
807 [...sessions.values()],
808 (session) => stopTracked(expo, session).pipe(Effect.ignore),
809 { discard: true, concurrency: 4 },
810 );
811 yield* Effect.forEach(
812 [...unresolved],
813 ([name, { sessionId }]) => retryUnresolved(expo, name, sessionId),
814 { discard: true, concurrency: 4 },
815 );
816 // Also stop a recorded session a create with an unknown outcome made after all.
817 yield* reapLeftovers(expo);
818 }).pipe(Effect.ignore);
819 yield* Effect.addFinalizer(() =>
820 stopAll.pipe(
821 // Under the ledger lock, so a write still in flight lands before a
822 // replacement writes its own, which that write would overwrite.
823 Effect.andThen(
824 ledgerLock.withPermit(
825 Effect.sync(() => {
826 closed = true;
827 }),
828 ),
829 ),
830 ),
831 );
832
833 const platformAvailability = (platform: DevicePlatform) =>
834 Effect.succeed(
835 platform === "ios"
836 ? { platform, available: true }
837 : {
838 platform,
839 available: false,
840 reason: "EAS Simulator Android emulators are not supported yet.",
841 },
842 );
843
844 const summary: Effect.Effect<DeviceHostSummary> = Effect.all([
845 platformAvailability("ios"),
846 platformAvailability("android"),
847 ]).pipe(
848 Effect.map((platforms) => ({
849 id: hostId,
850 label: config.label,
851 kind: "eas" as const,
852 platforms,
853 // Nothing to install: the hub and agent-device daemon run in each session.
854 hubInstalled: true,
855 agentDeviceInstalled: true,
856 })),
857 );
858
859 return DeviceHost.DeviceHost.of({
860 id: hostId,
861 label: config.label,
862 summary,
863 platformAvailability,
864 ensureReady,
865 ensureAgentReady: (onPhase) =>
866 ensureReady(onPhase).pipe(Effect.map((value) => ({ ...value, agentDevice: null }))),
867 current: Effect.sync(() => ready),
868 stopAgent: Effect.void,
869 // Unlike machines the user owns, every running session here is billed.
870 stop: stopAll,
871 });
872});