Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

EasDeviceHost.test.ts

907 lines42.2 KB

1import { describe, expect, it } from "@effect/vitest";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import type { EasDeviceHostConfig } from "@t3tools/contracts";
4import * as Deferred from "effect/Deferred";
5import * as Effect from "effect/Effect";
6import * as Fiber from "effect/Fiber";
7import * as Exit from "effect/Exit";
8import * as FileSystem from "effect/FileSystem";
9import * as Layer from "effect/Layer";
10import * as Path from "effect/Path";
11import * as Scope from "effect/Scope";
12import * as TestClock from "effect/testing/TestClock";
13import { HttpClient, HttpClientResponse } from "effect/http";
14​
15import * as ServerConfig from "../config.ts";
16import * as ProcessRunner from "../processRunner.ts";
17import * as EasDeviceHost from "./EasDeviceHost.ts";
18​
19const APP_ID = "d763fcb8-d37c-41ea-a773-b54a0ab4a454";
20​
21const config = (overrides: Partial<EasDeviceHostConfig> = {}): EasDeviceHostConfig => ({
22 kind: "eas",
23 id: "eas",
24 label: "EAS Simulator",
25 appId: APP_ID,
26 accessToken: "expo-token",
27 maxSessionMinutes: 25,
28 idleMinutes: 5,
29 maxConcurrentSessions: 2,
30 ...overrides,
31});
32​
33interface Gate {
34 readonly requested: Deferred.Deferred<void>;
35 readonly release: Deferred.Deferred<void>;
37const makeGate = Effect.all({
38 requested: Deferred.make<void>(),
39 release: Deferred.make<void>(),
40});
41​
42/** Expo's API and one session's preview host, recording what was asked of them. */
43const fakeExpo = (
44 options: {
45 readonly status?: () => string;
46 readonly failCreate?: boolean;
47 /** Expo answers the create with GraphQL errors: a refusal. */
48 readonly rejectCreate?: boolean;
49 readonly failStop?: () => boolean;
50 readonly failList?: () => boolean;
51 readonly active?: ReadonlyArray<{ id: string; status: string; name: string }>;
52 readonly previewGate?: Gate;
53 readonly createGate?: Gate;
54 /** Holds the first session read it answers with a gate. */
55 readonly sessionGate?: () => Gate | undefined;
56 readonly activeIncludesCreated?: boolean;
57 readonly failPreview?: boolean;
58 readonly omitCreatedFromActive?: boolean;
59 } = {},
60) => {
61 const calls: Array<{ operation: string; variables: Record<string, unknown> }> = [];
62 let created = 0;
63 let createdName = "";
64 let previewFails = options.failPreview ?? false;
65 let createFails = options.failCreate ?? false;
66 let sessionGated = false;
67 const http = HttpClient.make((request) =>
68 Effect.gen(function* () {
69 const url = new URL(request.url);
70 if (url.origin === "https://preview.test") {
71 expect(request.headers.authorization).toBe("Bearer preview-token");
72 if (options.previewGate) {
73 yield* Deferred.succeed(options.previewGate.requested, undefined);
74 yield* Deferred.await(options.previewGate.release);
75 }
76 if (previewFails) {
77 return HttpClientResponse.fromWeb(request, new Response("bad gateway", { status: 502 }));
78 }
79 return HttpClientResponse.fromWeb(request, Response.json({ device: "UDID-1" }));
80 }
81 const body =
82 request.body._tag === "Uint8Array"
83 ? (JSON.parse(new TextDecoder().decode(request.body.body)) as {
84 query: string;
85 variables: Record<string, { name?: string } & Record<string, unknown>>;
86 })
87 : { query: "", variables: {} };
88 expect(request.headers.authorization).toBe("Bearer expo-token");
89 const operation = /(?:query|mutation) (\w+)/.exec(body.query)?.[1] ?? "unknown";
90 calls.push({ operation, variables: body.variables });
91 if (operation === "T3CreateEasSimulatorSession") {
92 createdName = body.variables.input?.name ?? "";
93 if (options.createGate) {
94 yield* Deferred.succeed(options.createGate.requested, undefined);
95 yield* Deferred.await(options.createGate.release);
96 }
97 if (createFails)
98 return HttpClientResponse.fromWeb(request, new Response("bad gateway", { status: 502 }));
99 if (options.rejectCreate)
100 return HttpClientResponse.fromWeb(
101 request,
102 Response.json({ errors: [{ message: "Not allowed" }] }),
103 );
104 }
105 if (operation === "T3StopEasSimulatorSession" && options.failStop?.()) {
106 return HttpClientResponse.fromWeb(request, new Response("bad gateway", { status: 502 }));
107 }
108 if (operation === "T3ActiveEasSimulatorSessions" && options.failList?.()) {
109 return HttpClientResponse.fromWeb(request, new Response("bad gateway", { status: 502 }));
110 }
111 const sessionGate =
112 operation === "T3EasSimulatorSession" ? options.sessionGate?.() : undefined;
113 if (sessionGate && !sessionGated) {
114 sessionGated = true;
115 yield* Deferred.succeed(sessionGate.requested, undefined);
116 yield* Deferred.await(sessionGate.release);
117 }
118 const data =
119 operation === "T3EasSimulatorAvailability"
120 ? {
121 app: {
122 byId: {
123 ownerAccount: {
124 name: "pingdotgg",
125 accountFeatureGates: { "device-run-sessions": true },
126 },
127 },
128 },
129 }
130 : operation === "T3CreateEasSimulatorSession"
131 ? { deviceRunSession: { createDeviceRunSession: { id: `session-${++created}` } } }
132 : operation === "T3ActiveEasSimulatorSessions"
133 ? {
134 app: {
135 byId: {
136 deviceRunSessionsPaginated: {
137 edges: [
138 ...(options.omitCreatedFromActive
139 ? []
140 : [{ node: { id: "orphan", status: "NEW", name: createdName } }]),
141 {
142 node: {
143 id: "someone-else",
144 status: "IN_PROGRESS",
145 name: "T3 Code · EAS Simulator · 000000",
146 },
147 },
148 ...(options.active ?? []).map((node) => ({ node })),
149 ...(options.activeIncludesCreated && created > 0
150 ? [
151 {
152 node: {
153 id: `session-${created}`,
154 status: "STARTING",
155 name: createdName,
156 },
157 },
158 ]
159 : []),
160 ],
161 },
162 },
163 },
164 }
165 : operation === "T3EasSimulatorSession"
166 ? {
167 deviceRunSessions: {
168 byId: {
169 id: body.variables.id,
170 status: options.status?.() ?? "IN_PROGRESS",
171 remoteConfig: {
172 __typename: "AgentDeviceRunSessionRemoteConfig",
173 agentDeviceRemoteSessionUrl: "https://agent.test",
174 agentDeviceRemoteSessionToken: "agent-token",
175 webPreviewToken: "preview-token",
176 previewApiUrl: "https://preview.test?token=preview-token",
177 },
178 },
179 },
180 }
181 : {
182 deviceRunSession: {
183 ensureDeviceRunSessionStopped: { id: body.variables.id, status: "STOPPED" },
184 },
185 };
186 return HttpClientResponse.fromWeb(request, Response.json({ data }));
187 }),
188 );
189 const named = (operation: string) => calls.filter((call) => call.operation === operation);
190 const stopped = () => named("T3StopEasSimulatorSession").map((call) => call.variables.id);
191 const allowPreview = () => {
192 previewFails = false;
193 };
194 const allowCreate = () => {
195 createFails = false;
196 };
197 return { http, named, stopped, allowPreview, allowCreate };
198};
199​
200const layer = Layer.mergeAll(
201 ProcessRunner.layer,
202 ServerConfig.layerTest(process.cwd(), { prefix: "t3-eas-host-" }),
203).pipe(Layer.provideMerge(NodeServices.layer));
204​
205const makeHost = (
206 expo: ReturnType<typeof fakeExpo>,
207 hostConfig: EasDeviceHostConfig,
208 scope: Scope.Scope,
209) =>
210 EasDeviceHost.make(hostConfig).pipe(
211 Effect.provideService(HttpClient.HttpClient, expo.http),
212 Effect.provideService(Scope.Scope, scope),
213 );
214​
215describe("EAS Simulator host", () => {
216 it.effect("starts a bounded session and routes its stream and agent to that session", () =>
217 Effect.gen(function* () {
218 const expo = fakeExpo();
219 const scope = yield* Scope.make();
220 const host = yield* makeHost(expo, config(), scope);
221 const ready = yield* host.ensureReady(() => Effect.void);
222 const catalog = (yield* ready.devices.list).devices;
223 expect(catalog.map((device) => [device.id, device.booted])).toEqual([["eas-ios", false]]);
224​
225 expect(yield* ready.devices.boot(catalog[0]!)).toBe("session-1");
226 expect(expo.named("T3CreateEasSimulatorSession")[0]?.variables.input).toMatchObject({
227 appId: APP_ID,
228 platform: "IOS",
229 type: "AGENT_DEVICE",
230 maxRunTimeMinutes: 25,
231 maxIdleTimeMinutes: 5,
232 });
233 const listed = (yield* ready.devices.list).devices;
234 expect(listed.find((device) => device.id === "session-1")?.booted).toBe(true);
235 expect(yield* ready.devices.agentEndpoint!("session-1")).toEqual({
236 baseUrl: "https://agent.test",
237 token: "agent-token",
238 agentDeviceId: "UDID-1",
239 });
240​
241 const routed = yield* ready.upstream!(
242 "/vendor/serve-sim/helper/session-1/webrtc/offer",
243 new URLSearchParams("hostId=eas"),
244 );
245 expect(routed).toEqual({
246 url: "https://preview.test/helper/UDID-1/webrtc/offer?hostId=eas",
247 headers: { authorization: "Bearer preview-token" },
248 protocols: ["serve-sim.token.preview-token"],
249 });
250 expect(
251 yield* ready.upstream!(
252 "/vendor/serve-sim/helper/ws",
253 new URLSearchParams("device=session-1"),
254 ),
255 ).toMatchObject({ url: "https://preview.test/helper/ws?device=UDID-1" });
256 expect(yield* ready.upstream!("/vendor/serve-emu/ws", new URLSearchParams())).toBeNull();
257 expect(
258 yield* ready.upstream!("/vendor/serve-sim/helper/%E0/config", new URLSearchParams()),
259 ).toBeNull();
260​
261 yield* Scope.close(scope, Exit.void);
262 expect(expo.named("T3StopEasSimulatorSession").map((call) => call.variables.id)).toEqual([
263 "session-1",
264 ]);
265 }).pipe(Effect.scoped, Effect.provide(layer)),
266 );
267​
268 it.effect("refuses to start past its session limit", () =>
269 Effect.gen(function* () {
270 const expo = fakeExpo();
271 const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), yield* Scope.make());
272 const ready = yield* host.ensureReady(() => Effect.void);
273 const [catalogDevice] = (yield* ready.devices.list).devices;
274 yield* ready.devices.boot(catalogDevice!);
275 const refused = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
276 expect(refused.message).toBe(
277 "EAS Simulator is unavailable: EAS Simulator is limited to 1 running session. Close one in the Device panel first.",
278 );
279 expect(expo.named("T3CreateEasSimulatorSession")).toHaveLength(1);
280 }).pipe(Effect.scoped, Effect.provide(layer)),
281 );
282​
283 it.effect("tells concurrent sessions apart although EAS gives each the same UDID", () =>
284 Effect.gen(function* () {
285 const expo = fakeExpo();
286 const scope = yield* Scope.make();
287 const host = yield* makeHost(expo, config({ maxConcurrentSessions: 2 }), scope);
288 const ready = yield* host.ensureReady(() => Effect.void);
289 const [catalogDevice] = (yield* ready.devices.list).devices;
290 expect(yield* ready.devices.boot(catalogDevice!)).toBe("session-1");
291 expect(yield* ready.devices.boot(catalogDevice!)).toBe("session-2");
292 expect((yield* ready.devices.list).devices.map((device) => device.id)).toEqual([
293 "eas-ios",
294 "session-1",
295 "session-2",
296 ]);
297 expect(
298 yield* ready.upstream!(
299 "/vendor/serve-sim/api",
300 new URLSearchParams("device=session-2&hostId=eas"),
301 ),
302 ).toMatchObject({ url: "https://preview.test/api?device=UDID-1&hostId=eas" });
303​
304 yield* ready.devices.shutdown({ id: "session-1", platform: "ios" });
305 expect(expo.stopped()).toEqual(["session-1"]);
306 expect((yield* ready.devices.list).devices.map((device) => device.id)).toEqual([
307 "eas-ios",
308 "session-2",
309 ]);
310 yield* Scope.close(scope, Exit.void);
311 expect(expo.stopped()).toEqual(["session-1", "session-2"]);
312 }).pipe(Effect.scoped, Effect.provide(layer)),
313 );
314​
315 it.effect("stops only the sessions a previous server recorded, found by name", () =>
316 Effect.gen(function* () {
317 const fs = yield* FileSystem.FileSystem;
318 const path = yield* Path.Path;
319 const server = yield* ServerConfig.ServerConfig;
320 const ledger = path.join(server.stateDir, "device", "eas", "eas.json");
321 yield* fs.makeDirectory(path.dirname(ledger), { recursive: true });
322 yield* fs.writeFileString(
323 ledger,
324 JSON.stringify([
325 { name: "T3 Code · EAS Simulator · left", appId: APP_ID, recordedAt: 0 },
326 // Recorded long enough ago that Expo has ended it, so the record goes.
327 { name: "T3 Code · EAS Simulator · gone", appId: APP_ID, recordedAt: -181 * 60_000 },
328 // Recorded just now and not listed yet: kept for a later sweep.
329 { name: "T3 Code · EAS Simulator · new", appId: APP_ID, recordedAt: 0 },
330 ]),
331 );
332 const expo = fakeExpo({
333 active: [
334 { id: "left-behind", status: "IN_PROGRESS", name: "T3 Code · EAS Simulator · left" },
335 ],
336 });
337 const host = yield* makeHost(expo, config(), yield* Scope.make());
338 yield* host.ensureReady(() => Effect.void);
339 // The sweep runs in the background, so readiness does not wait on Expo.
340 const ledgerNames = Effect.map(
341 Effect.flatMap(fs.readFileString(ledger), (text) =>
342 Effect.try(() => JSON.parse(text) as ReadonlyArray<{ name: string }>),
343 ),
344 (entries) => entries.map((entry) => entry.name),
345 );
346 yield* Effect.eventually(
347 Effect.flatMap(ledgerNames, (names) =>
348 names.length === 1 ? Effect.void : Effect.fail("not swept yet"),
349 ),
350 );
351 expect(expo.stopped()).toEqual(["left-behind"]);
352 expect(yield* ledgerNames).toEqual(["T3 Code · EAS Simulator · new"]);
353 }).pipe(Effect.scoped, Effect.provide(layer)),
354 );
355​
356 it.effect("counts a fresh record a previous server left until Expo lists it or would have", () =>
357 Effect.gen(function* () {
358 const fs = yield* FileSystem.FileSystem;
359 const path = yield* Path.Path;
360 const server = yield* ServerConfig.ServerConfig;
361 const ledger = path.join(server.stateDir, "device", "eas", "eas.json");
362 yield* fs.makeDirectory(path.dirname(ledger), { recursive: true });
363 yield* fs.writeFileString(
364 ledger,
365 JSON.stringify([{ name: "T3 Code · EAS Simulator · new", appId: APP_ID, recordedAt: 0 }]),
366 );
367 const expo = fakeExpo();
368 const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), yield* Scope.make());
369 const ready = yield* host.ensureReady(() => Effect.void);
370 const [catalogDevice] = (yield* ready.devices.list).devices;
371 // The record is fresh and Expo does not list it yet: it holds the slot.
372 const refused = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
373 expect(refused.message).toContain("still being cleaned up");
374 yield* TestClock.adjust("6 minutes");
375 yield* ready.devices.list;
376 expect(yield* ready.devices.boot(catalogDevice!)).toBe("session-1");
377 }).pipe(Effect.scoped, Effect.provide(layer)),
378 );
379​
380 it.effect("counts an old record a previous server left until a sweep stops its session", () =>
381 Effect.gen(function* () {
382 const fs = yield* FileSystem.FileSystem;
383 const path = yield* Path.Path;
384 const server = yield* ServerConfig.ServerConfig;
385 const ledger = path.join(server.stateDir, "device", "eas", "eas.json");
386 yield* fs.makeDirectory(path.dirname(ledger), { recursive: true });
387 yield* fs.writeFileString(
388 ledger,
389 JSON.stringify([
390 { name: "T3 Code · EAS Simulator · old", appId: APP_ID, recordedAt: -10 * 60_000 },
391 ]),
392 );
393 const expo = fakeExpo({
394 active: [
395 { id: "old-session", status: "IN_PROGRESS", name: "T3 Code · EAS Simulator · old" },
396 ],
397 });
398 const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), yield* Scope.make());
399 const ready = yield* host.ensureReady(() => Effect.void);
400 // Listing sweeps before anything starts, so the old session is stopped first.
401 const [catalogDevice] = (yield* ready.devices.list).devices;
402 expect(expo.stopped()).toContain("old-session");
403 expect(yield* ready.devices.boot(catalogDevice!)).toBe("session-1");
404 }).pipe(Effect.scoped, Effect.provide(layer)),
405 );
406​
407 it.effect("keeps an old record counted while the listing that would find it fails", () =>
408 Effect.gen(function* () {
409 const fs = yield* FileSystem.FileSystem;
410 const path = yield* Path.Path;
411 const server = yield* ServerConfig.ServerConfig;
412 const ledger = path.join(server.stateDir, "device", "eas", "eas.json");
413 yield* fs.makeDirectory(path.dirname(ledger), { recursive: true });
414 yield* fs.writeFileString(
415 ledger,
416 JSON.stringify([
417 { name: "T3 Code · EAS Simulator · old", appId: APP_ID, recordedAt: -10 * 60_000 },
418 ]),
419 );
420 let listFails = true;
421 const expo = fakeExpo({
422 active: [
423 { id: "old-session", status: "IN_PROGRESS", name: "T3 Code · EAS Simulator · old" },
424 ],
425 failList: () => listFails,
426 });
427 const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), yield* Scope.make());
428 const ready = yield* host.ensureReady(() => Effect.void);
429 const [catalogDevice] = (yield* ready.devices.list).devices;
430 // The sweep could not look, so the record still holds the slot.
431 const refused = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
432 expect(refused.message).toContain("still being cleaned up");
433 listFails = false;
434 yield* ready.devices.list;
435 expect(expo.stopped()).toContain("old-session");
436 expect(yield* ready.devices.boot(catalogDevice!)).toBe("session-1");
437 }).pipe(Effect.scoped, Effect.provide(layer)),
438 );
439​
440 it.effect(
441 "frees the slot of a record Expo has ended by now, but keeps it until a listing confirms",
442 () =>
443 Effect.gen(function* () {
444 const fs = yield* FileSystem.FileSystem;
445 const path = yield* Path.Path;
446 const server = yield* ServerConfig.ServerConfig;
447 const ledger = path.join(server.stateDir, "device", "eas", "eas.json");
448 yield* fs.makeDirectory(path.dirname(ledger), { recursive: true });
449 yield* fs.writeFileString(
450 ledger,
451 JSON.stringify([
452 { name: "T3 Code · EAS Simulator · gone", appId: APP_ID, recordedAt: -181 * 60_000 },
453 {
454 name: "T3 Code · EAS Simulator · refused",
455 appId: APP_ID,
456 recordedAt: -181 * 60_000,
457 refused: true,
458 },
459 // No queue holds a session for a day: forgotten unconfirmed.
460 {
461 name: "T3 Code · EAS Simulator · ancient",
462 appId: APP_ID,
463 recordedAt: -25 * 60 * 60_000,
464 },
465 ]),
466 );
467 // The app is gone, say: listing it fails for good.
468 const expo = fakeExpo({ failList: () => true });
469 const host = yield* makeHost(
470 expo,
471 config({ maxConcurrentSessions: 1 }),
472 yield* Scope.make(),
473 );
474 const ready = yield* host.ensureReady(() => Effect.void);
475 const [catalogDevice] = (yield* ready.devices.list).devices;
476 expect(yield* ready.devices.boot(catalogDevice!)).toBe("session-1");
477 const names = (JSON.parse(yield* fs.readFileString(ledger)) as Array<{ name: string }>).map(
478 (entry) => entry.name,
479 );
480 // The listing never confirmed the two: a queued session could still be
481 // running, so their records stay for the reaper.
482 expect(names.filter((name) => !/[0-9a-f]{6}$/.test(name))).toEqual([
483 "T3 Code · EAS Simulator · gone",
484 "T3 Code · EAS Simulator · refused",
485 ]);
486 }).pipe(Effect.scoped, Effect.provide(layer)),
487 );
488​
489 it.effect(
490 "keeps a refused create's record for the reaper without counting it after a restart",
491 () =>
492 Effect.gen(function* () {
493 const fs = yield* FileSystem.FileSystem;
494 const path = yield* Path.Path;
495 const server = yield* ServerConfig.ServerConfig;
496 const ledger = path.join(server.stateDir, "device", "eas", "eas.json");
497 // Expo refuses the create and lists nothing.
498 const expo = fakeExpo({ rejectCreate: true, omitCreatedFromActive: true });
499 const first = yield* Scope.make();
500 const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), first);
501 const ready = yield* host.ensureReady(() => Effect.void);
502 const [catalogDevice] = (yield* ready.devices.list).devices;
503 yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
504 const entries = JSON.parse(yield* fs.readFileString(ledger)) as Array<{
505 refused?: boolean;
506 }>;
507 expect(entries.map((entry) => entry.refused)).toEqual([true]);
508 yield* Scope.close(first, Exit.void);
509 // A later server cannot even list the app: the record must not hold a slot.
510 const later = fakeExpo({ failList: () => true });
511 const restarted = yield* makeHost(
512 later,
513 config({ maxConcurrentSessions: 1 }),
514 yield* Scope.make(),
515 );
516 const readyAgain = yield* restarted.ensureReady(() => Effect.void);
517 const [device] = (yield* readyAgain.devices.list).devices;
518 expect(yield* readyAgain.devices.boot(device!)).toBe("session-1");
519 }).pipe(Effect.scoped, Effect.provide(layer)),
520 );
521​
522 it.effect("leaves a replacement's session alone once its own scope has closed", () =>
523 Effect.gen(function* () {
524 // One Expo for both instances: they share the record and the account.
525 const expo = fakeExpo();
526 const first = yield* Scope.make();
527 const old = yield* makeHost(expo, config(), first);
528 const oldReady = yield* old.ensureReady(() => Effect.void);
529 const [catalogDevice] = (yield* oldReady.devices.list).devices;
530 expect(yield* oldReady.devices.boot(catalogDevice!)).toBe("session-1");
531 // Settings saved: the old instance goes, a replacement takes its id.
532 yield* Scope.close(first, Exit.void);
533 expect(expo.stopped()).toEqual(["session-1"]);
534 const replacement = yield* makeHost(expo, config(), yield* Scope.make());
535 const ready = yield* replacement.ensureReady(() => Effect.void);
536 const [device] = (yield* ready.devices.list).devices;
537 expect(yield* ready.devices.boot(device!)).toBe("session-2");
538 // A listing still running on the old instance must not sweep the new
539 // session, which it does not own but its replacement does.
540 yield* TestClock.adjust("2 minutes");
541 yield* oldReady.devices.list;
542 expect(expo.stopped()).toEqual(["session-1"]);
543 }).pipe(Effect.scoped, Effect.provide(layer)),
544 );
545​
546 it.effect(
547 "does not sweep a replacement's session from a listing in flight when its scope closes",
548 () =>
549 Effect.gen(function* () {
550 const gate = yield* makeGate;
551 let armed = false;
552 const expo = fakeExpo({ sessionGate: () => (armed ? gate : undefined) });
553 const first = yield* Scope.make();
554 const old = yield* makeHost(expo, config(), first);
555 const oldReady = yield* old.ensureReady(() => Effect.void);
556 const [catalogDevice] = (yield* oldReady.devices.list).devices;
557 expect(yield* oldReady.devices.boot(catalogDevice!)).toBe("session-1");
558 // Long enough that the listing reads the session's status and a sweep is due.
559 yield* TestClock.adjust("2 minutes");
560 armed = true;
561 const listing = yield* oldReady.devices.list.pipe(Effect.forkChild);
562 yield* Deferred.await(gate.requested);
563 // Settings saved while the old listing waits on Expo.
564 yield* Scope.close(first, Exit.void);
565 const replacement = yield* makeHost(expo, config(), yield* Scope.make());
566 const ready = yield* replacement.ensureReady(() => Effect.void);
567 const [device] = (yield* ready.devices.list).devices;
568 expect(yield* ready.devices.boot(device!)).toBe("session-2");
569 yield* Deferred.succeed(gate.release, undefined);
570 yield* Fiber.join(listing);
571 expect(expo.stopped()).toEqual(["session-1"]);
572 }).pipe(Effect.scoped, Effect.provide(layer)),
573 );
574​
575 it.effect("waits for a record write in flight before its scope closes", () =>
576 Effect.gen(function* () {
577 const fs = yield* FileSystem.FileSystem;
578 const gate = yield* makeGate;
579 let armed = false;
580 // The ledger read inside a write waits on the gate once armed.
581 const gatedFs: FileSystem.FileSystem = {
582 ...fs,
583 readFileString: (path, encoding) =>
584 Effect.gen(function* () {
585 if (armed && path.endsWith("eas.json")) {
586 armed = false;
587 yield* Deferred.succeed(gate.requested, undefined);
588 yield* Deferred.await(gate.release);
589 }
590 return yield* fs.readFileString(path, encoding);
591 }),
592 };
593 let status = "IN_PROGRESS";
594 // Nothing is listed, so the close's own sweep writes nothing: only the
595 // write in flight can hold the close.
596 const expo = fakeExpo({ status: () => status, omitCreatedFromActive: true });
597 const first = yield* Scope.make();
598 const old = yield* makeHost(expo, config(), first).pipe(
599 Effect.provideService(FileSystem.FileSystem, gatedFs),
600 );
601 const oldReady = yield* old.ensureReady(() => Effect.void);
602 const [catalogDevice] = (yield* oldReady.devices.list).devices;
603 expect(yield* oldReady.devices.boot(catalogDevice!)).toBe("session-1");
604 // Expo ended the session; the next listing forgets its record.
605 status = "STOPPED";
606 yield* TestClock.adjust("20 seconds");
607 armed = true;
608 const listing = yield* oldReady.devices.list.pipe(Effect.forkChild);
609 yield* Deferred.await(gate.requested);
610 // Settings saved while that write is in flight: closing waits for it.
611 const listingsBefore = expo.named("T3ActiveEasSimulatorSessions").length;
612 const closing = yield* Scope.close(first, Exit.void).pipe(Effect.forkChild);
613 // The close reads the record and lists sessions in real time: yield until
614 // its sweep has listed, then a good deal more, before looking at it.
615 while (expo.named("T3ActiveEasSimulatorSessions").length === listingsBefore) {
616 yield* Effect.yieldNow;
617 }
618 for (let i = 0; i < 200; i++) yield* Effect.yieldNow;
619 expect(closing.pollUnsafe()).toBeUndefined();
620 yield* Deferred.succeed(gate.release, undefined);
621 yield* Fiber.join(listing);
622 yield* Fiber.join(closing);
623 const replacement = yield* makeHost(expo, config(), yield* Scope.make());
624 const ready = yield* replacement.ensureReady(() => Effect.void);
625 const [device] = (yield* ready.devices.list).devices;
626 status = "IN_PROGRESS";
627 expect(yield* ready.devices.boot(device!)).toBe("session-2");
628 // The old write landed first, so the replacement's record is intact.
629 const path = yield* Path.Path;
630 const server = yield* ServerConfig.ServerConfig;
631 const entries = JSON.parse(
632 yield* fs.readFileString(path.join(server.stateDir, "device", "eas", "eas.json")),
633 ) as Array<{ name: string }>;
634 expect(entries).toHaveLength(1);
635 }).pipe(Effect.scoped, Effect.provide(layer)),
636 );
637​
638 it.effect("keeps an old record whose session is listed but cannot be stopped", () =>
639 Effect.gen(function* () {
640 const fs = yield* FileSystem.FileSystem;
641 const path = yield* Path.Path;
642 const server = yield* ServerConfig.ServerConfig;
643 const ledger = path.join(server.stateDir, "device", "eas", "eas.json");
644 yield* fs.makeDirectory(path.dirname(ledger), { recursive: true });
645 yield* fs.writeFileString(
646 ledger,
647 JSON.stringify([
648 { name: "T3 Code · EAS Simulator · old", appId: APP_ID, recordedAt: -181 * 60_000 },
649 ]),
650 );
651 // Expo still lists it (queued for hours, say) and refuses to stop it.
652 const expo = fakeExpo({
653 active: [
654 { id: "old-session", status: "IN_PROGRESS", name: "T3 Code · EAS Simulator · old" },
655 ],
656 failStop: () => true,
657 });
658 const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), yield* Scope.make());
659 const ready = yield* host.ensureReady(() => Effect.void);
660 const [catalogDevice] = (yield* ready.devices.list).devices;
661 // Found and still running: its slot stays taken and its record stays.
662 const refused = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
663 expect(refused.message).toContain("still being cleaned up");
664 const names = (JSON.parse(yield* fs.readFileString(ledger)) as Array<{ name: string }>).map(
665 (entry) => entry.name,
666 );
667 expect(names).toContain("T3 Code · EAS Simulator · old");
668 }).pipe(Effect.scoped, Effect.provide(layer)),
669 );
670​
671 it.effect("stops the session a refused create made anyway", () =>
672 Effect.gen(function* () {
673 // Expo refuses the create but lists a session by its name.
674 const expo = fakeExpo({ rejectCreate: true });
675 const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), yield* Scope.make());
676 const ready = yield* host.ensureReady(() => Effect.void);
677 const [catalogDevice] = (yield* ready.devices.list).devices;
678 const failure = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
679 expect(failure.message).toContain("Not allowed");
680 expect(expo.stopped()).toEqual(["orphan"]);
681 }).pipe(Effect.scoped, Effect.provide(layer)),
682 );
683​
684 it.effect("records a session before creating it and refuses to start without the record", () =>
685 Effect.gen(function* () {
686 const fs = yield* FileSystem.FileSystem;
687 const path = yield* Path.Path;
688 const server = yield* ServerConfig.ServerConfig;
689 // A directory where the ledger file should be: it can be neither read nor written.
690 yield* fs.makeDirectory(path.join(server.stateDir, "device", "eas", "eas.json"), {
691 recursive: true,
692 });
693 const expo = fakeExpo();
694 const host = yield* makeHost(expo, config(), yield* Scope.make());
695 const ready = yield* host.ensureReady(() => Effect.void);
696 const [catalogDevice] = (yield* ready.devices.list).devices;
697 const failure = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
698 expect(failure.message).toContain("could not be read");
699 expect(expo.named("T3CreateEasSimulatorSession")).toHaveLength(0);
700 }).pipe(Effect.scoped, Effect.provide(layer)),
701 );
702​
703 it.effect("keeps a session tracked when the open that started it is interrupted", () =>
704 Effect.gen(function* () {
705 const createGate = yield* makeGate;
706 const expo = fakeExpo({ createGate });
707 const scope = yield* Scope.make();
708 const host = yield* makeHost(expo, config(), scope);
709 const ready = yield* host.ensureReady(() => Effect.void);
710 const [catalogDevice] = (yield* ready.devices.list).devices;
711 const opening = yield* ready.devices.boot(catalogDevice!).pipe(Effect.forkChild);
712 yield* Deferred.await(createGate.requested);
713 yield* Fiber.interrupt(opening);
714 yield* Deferred.succeed(createGate.release, undefined);
715 // The start goes on in the host and tracks its session.
716 yield* Effect.eventually(
717 ready.devices.list.pipe(
718 Effect.flatMap(({ devices }) =>
719 devices.some((device) => device.id === "session-1")
720 ? Effect.void
721 : Effect.fail("not tracked yet"),
722 ),
723 ),
724 );
725 yield* Scope.close(scope, Exit.void);
726 expect(expo.stopped()).toEqual(["session-1"]);
727 }).pipe(Effect.scoped, Effect.provide(layer)),
728 );
729​
730 it.effect("keeps a session it could not stop counted, listed, and retried", () =>
731 Effect.gen(function* () {
732 let stopFails = true;
733 const expo = fakeExpo({ failStop: () => stopFails });
734 const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), yield* Scope.make());
735 const ready = yield* host.ensureReady(() => Effect.void);
736 const [catalogDevice] = (yield* ready.devices.list).devices;
737 yield* ready.devices.boot(catalogDevice!);
738 yield* ready.devices.shutdown({ id: "session-1", platform: "ios" }).pipe(Effect.flip);
739 expect((yield* ready.devices.list).devices.map((device) => device.id)).toContain("session-1");
740 const refused = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
741 expect(refused.message).toContain("limited to 1 running session");
742 stopFails = false;
743 yield* ready.devices.list;
744 expect((yield* ready.devices.list).devices.map((device) => device.id)).toEqual(["eas-ios"]);
745 expect(expo.stopped().filter((id) => id === "session-1").length).toBeGreaterThanOrEqual(2);
746 }).pipe(Effect.scoped, Effect.provide(layer)),
747 );
748​
749 it.effect("lets go of a stopping session Expo has ended although its stop keeps failing", () =>
750 Effect.gen(function* () {
751 let status = "IN_PROGRESS";
752 const expo = fakeExpo({ failStop: () => true, status: () => status });
753 const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), yield* Scope.make());
754 const ready = yield* host.ensureReady(() => Effect.void);
755 const [catalogDevice] = (yield* ready.devices.list).devices;
756 yield* ready.devices.boot(catalogDevice!);
757 yield* ready.devices.shutdown({ id: "session-1", platform: "ios" }).pipe(Effect.flip);
758 expect((yield* ready.devices.list).devices.map((device) => device.id)).toContain("session-1");
759 // Expo ended it by itself: the stop keeps failing, but the status says so.
760 status = "STOPPED";
761 expect((yield* ready.devices.list).devices.map((device) => device.id)).toEqual(["eas-ios"]);
762 status = "IN_PROGRESS";
763 expect(yield* ready.devices.boot(catalogDevice!)).toBe("session-2");
764 }).pipe(Effect.scoped, Effect.provide(layer)),
765 );
766​
767 it.effect("asks for an EAS project before starting anything when none can be found", () =>
768 Effect.gen(function* () {
769 const expo = fakeExpo();
770 const host = yield* makeHost(expo, config({ appId: undefined }), yield* Scope.make());
771 const ready = yield* host.ensureReady(() => Effect.void);
772 const [catalogDevice] = (yield* ready.devices.list).devices;
773 const failure = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
774 expect(failure.message).toContain("Choose one for this host in Settings");
775 expect(expo.named("T3CreateEasSimulatorSession")).toHaveLength(0);
776 }).pipe(Effect.scoped, Effect.provide(layer)),
777 );
778 it.effect("stops listing sessions Expo already ended", () =>
779 Effect.gen(function* () {
780 let status = "IN_PROGRESS";
781 const expo = fakeExpo({ status: () => status });
782 const host = yield* makeHost(expo, config(), yield* Scope.make());
783 const ready = yield* host.ensureReady(() => Effect.void);
784 const [catalogDevice] = (yield* ready.devices.list).devices;
785 yield* ready.devices.boot(catalogDevice!);
786 status = "STOPPED";
787 yield* TestClock.adjust("20 seconds");
788 expect((yield* ready.devices.list).devices.map((device) => device.id)).toEqual(["eas-ios"]);
789 expect(yield* ready.devices.agentEndpoint!("session-1").pipe(Effect.flip)).toMatchObject({
790 reason: "This EAS Simulator device is no longer running.",
791 });
792 }).pipe(Effect.scoped, Effect.provide(layer)),
793 );
794​
795 it.effect("stops a session that is still starting when the host stops", () =>
796 Effect.gen(function* () {
797 const previewGate = yield* makeGate;
798 const expo = fakeExpo({ previewGate });
799 const host = yield* makeHost(expo, config(), yield* Scope.make());
800 const ready = yield* host.ensureReady(() => Effect.void);
801 const [catalogDevice] = (yield* ready.devices.list).devices;
802 const booting = yield* ready.devices.boot(catalogDevice!).pipe(Effect.forkChild);
803 yield* Deferred.await(previewGate.requested);
804 // Never released: stopping must not wait for the session to become ready.
805 yield* host.stop;
806 expect(expo.stopped()).toEqual(["session-1"]);
807 const failure = yield* Fiber.join(booting).pipe(Effect.flip);
808 expect(failure.message).toContain("was stopped while the session started");
809 expect((yield* ready.devices.list).devices.map((device) => device.id)).toEqual(["eas-ios"]);
810 }).pipe(Effect.scoped, Effect.provide(layer)),
811 );
812​
813 it.effect("leaves a start in progress to its owner when the sweep runs", () =>
814 Effect.gen(function* () {
815 const previewGate = yield* makeGate;
816 // Expo lists the starting session by name, as it does while it boots.
817 const expo = fakeExpo({ previewGate, activeIncludesCreated: true });
818 const fs = yield* FileSystem.FileSystem;
819 const path = yield* Path.Path;
820 const server = yield* ServerConfig.ServerConfig;
821 const host = yield* makeHost(expo, config(), yield* Scope.make());
822 const ready = yield* host.ensureReady(() => Effect.void);
823 const [catalogDevice] = (yield* ready.devices.list).devices;
824 const booting = yield* ready.devices.boot(catalogDevice!).pipe(Effect.forkChild);
825 yield* Deferred.await(previewGate.requested);
826 yield* TestClock.adjust("61 seconds");
827 yield* ready.devices.list;
828 expect(expo.stopped()).toEqual([]);
829 const ledger = path.join(server.stateDir, "device", "eas", "eas.json");
830 expect(JSON.parse(yield* fs.readFileString(ledger))).toHaveLength(1);
831 yield* Deferred.succeed(previewGate.release, undefined);
832 expect(yield* Fiber.join(booting)).toBe("session-1");
833 }).pipe(Effect.scoped, Effect.provide(layer)),
834 );
835​
836 it.effect("keeps a session counted when its start fails and stopping it fails too", () =>
837 Effect.gen(function* () {
838 let stopFails = true;
839 const expo = fakeExpo({ failPreview: true, failStop: () => stopFails });
840 const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), yield* Scope.make());
841 const ready = yield* host.ensureReady(() => Effect.void);
842 const [catalogDevice] = (yield* ready.devices.list).devices;
843 // The preview probe is retried a few seconds apart before the start gives up.
844 const failing = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip, Effect.forkChild);
845 while (failing.pollUnsafe() === undefined) yield* TestClock.adjust("1 second");
846 yield* Fiber.join(failing);
847 const refused = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
848 expect(refused.message).toContain("still being cleaned up");
849 expect(expo.named("T3CreateEasSimulatorSession")).toHaveLength(1);
850 stopFails = false;
851 yield* ready.devices.list;
852 expect(expo.stopped().at(-1)).toBe("session-1");
853 expo.allowPreview();
854 expect(yield* ready.devices.boot(catalogDevice!)).toBe("session-2");
855 }).pipe(Effect.scoped, Effect.provide(layer)),
856 );
857​
858 it.effect("stops only its own session when creating one fails after Expo made it", () =>
859 Effect.gen(function* () {
860 const expo = fakeExpo({ failCreate: true });
861 const host = yield* makeHost(expo, config(), yield* Scope.make());
862 const ready = yield* host.ensureReady(() => Effect.void);
863 const [catalogDevice] = (yield* ready.devices.list).devices;
864 yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
865 expect(expo.stopped()).toEqual(["orphan"]);
866 }).pipe(Effect.scoped, Effect.provide(layer)),
867 );
868​
869 it.effect("counts a create whose outcome is unknown against the limit, then frees it", () =>
870 Effect.gen(function* () {
871 // Create fails and the session is not listed yet, so the outcome is unknown.
872 const expo = fakeExpo({ failCreate: true, omitCreatedFromActive: true });
873 const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), yield* Scope.make());
874 const ready = yield* host.ensureReady(() => Effect.void);
875 const [catalogDevice] = (yield* ready.devices.list).devices;
876 yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
877 // The slot is held: Expo may have made the session.
878 const refused = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
879 expect(refused.message).toContain("still being cleaned up");
880 expect(expo.named("T3CreateEasSimulatorSession")).toHaveLength(1);
881 // After Expo would have listed it, the slot frees and a new start runs.
882 yield* TestClock.adjust("6 minutes");
883 yield* ready.devices.list;
884 expo.allowCreate();
885 expect(yield* ready.devices.boot(catalogDevice!)).toBe("session-1");
886 }).pipe(Effect.scoped, Effect.provide(layer)),
887 );
888​
889 it.effect("holds the slot when a failed create’s session is listed but its stop fails", () =>
890 Effect.gen(function* () {
891 let stopFails = true;
892 // Create fails, Expo lists the session by name, and stopping it fails too.
893 const expo = fakeExpo({ failCreate: true, failStop: () => stopFails });
894 const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), yield* Scope.make());
895 const ready = yield* host.ensureReady(() => Effect.void);
896 const [catalogDevice] = (yield* ready.devices.list).devices;
897 yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
898 const refused = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
899 expect(refused.message).toContain("still being cleaned up");
900 stopFails = false;
901 yield* ready.devices.list;
902 expect(expo.stopped()).toContain("orphan");
903 expo.allowCreate();
904 expect(yield* ready.devices.boot(catalogDevice!)).toBe("session-1");
905 }).pipe(Effect.scoped, Effect.provide(layer)),
906 );
907});