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