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