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