Open History to see the last commit
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>;
36}
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(
316 "keeps a refused create's record for the reaper without counting it after a restart",
317 () =>
318 Effect.gen(function* () {
319 const fs = yield* FileSystem.FileSystem;
320 const path = yield* Path.Path;
321 const server = yield* ServerConfig.ServerConfig;
322 const ledger = path.join(server.stateDir, "device", "eas", "eas.json");
323 // Expo refuses the create and lists nothing.
324 const expo = fakeExpo({ rejectCreate: true, omitCreatedFromActive: true });
325 const first = yield* Scope.make();
326 const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), first);
327 const ready = yield* host.ensureReady(() => Effect.void);
328 const [catalogDevice] = (yield* ready.devices.list).devices;
329 yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
330 const entries = JSON.parse(yield* fs.readFileString(ledger)) as Array<{
331 refused?: boolean;
332 }>;
333 expect(entries.map((entry) => entry.refused)).toEqual([true]);
334 yield* Scope.close(first, Exit.void);
335 // A later server cannot even list the app: the record must not hold a slot.
336 const later = fakeExpo({ failList: () => true });
337 const restarted = yield* makeHost(
338 later,
339 config({ maxConcurrentSessions: 1 }),
340 yield* Scope.make(),
341 );
342 const readyAgain = yield* restarted.ensureReady(() => Effect.void);
343 const [device] = (yield* readyAgain.devices.list).devices;
344 expect(yield* readyAgain.devices.boot(device!)).toBe("session-1");
345 }).pipe(Effect.scoped, Effect.provide(layer)),
346 );
347
348 it.effect(
349 "does not sweep a replacement's session from a listing in flight when its scope closes",
350 () =>
351 Effect.gen(function* () {
352 const gate = yield* makeGate;
353 let armed = false;
354 const expo = fakeExpo({ sessionGate: () => (armed ? gate : undefined) });
355 const first = yield* Scope.make();
356 const old = yield* makeHost(expo, config(), first);
357 const oldReady = yield* old.ensureReady(() => Effect.void);
358 const [catalogDevice] = (yield* oldReady.devices.list).devices;
359 expect(yield* oldReady.devices.boot(catalogDevice!)).toBe("session-1");
360 // Long enough that the listing reads the session's status and a sweep is due.
361 yield* TestClock.adjust("2 minutes");
362 armed = true;
363 const listing = yield* oldReady.devices.list.pipe(Effect.forkChild);
364 yield* Deferred.await(gate.requested);
365 // Settings saved while the old listing waits on Expo.
366 yield* Scope.close(first, Exit.void);
367 const replacement = yield* makeHost(expo, config(), yield* Scope.make());
368 const ready = yield* replacement.ensureReady(() => Effect.void);
369 const [device] = (yield* ready.devices.list).devices;
370 expect(yield* ready.devices.boot(device!)).toBe("session-2");
371 yield* Deferred.succeed(gate.release, undefined);
372 yield* Fiber.join(listing);
373 expect(expo.stopped()).toEqual(["session-1"]);
374 }).pipe(Effect.scoped, Effect.provide(layer)),
375 );
376
377 it.effect("stops the session a refused create made anyway", () =>
378 Effect.gen(function* () {
379 // Expo refuses the create but lists a session by its name.
380 const expo = fakeExpo({ rejectCreate: true });
381 const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), yield* Scope.make());
382 const ready = yield* host.ensureReady(() => Effect.void);
383 const [catalogDevice] = (yield* ready.devices.list).devices;
384 const failure = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
385 expect(failure.message).toContain("Not allowed");
386 expect(expo.stopped()).toEqual(["orphan"]);
387 }).pipe(Effect.scoped, Effect.provide(layer)),
388 );
389
390 it.effect("records a session before creating it and refuses to start without the record", () =>
391 Effect.gen(function* () {
392 const fs = yield* FileSystem.FileSystem;
393 const path = yield* Path.Path;
394 const server = yield* ServerConfig.ServerConfig;
395 // A directory where the ledger file should be: it can be neither read nor written.
396 yield* fs.makeDirectory(path.join(server.stateDir, "device", "eas", "eas.json"), {
397 recursive: true,
398 });
399 const expo = fakeExpo();
400 const host = yield* makeHost(expo, config(), yield* Scope.make());
401 const ready = yield* host.ensureReady(() => Effect.void);
402 const [catalogDevice] = (yield* ready.devices.list).devices;
403 const failure = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
404 expect(failure.message).toContain("could not be read");
405 expect(expo.named("T3CreateEasSimulatorSession")).toHaveLength(0);
406 }).pipe(Effect.scoped, Effect.provide(layer)),
407 );
408
409 it.effect("keeps a session it could not stop counted, listed, and retried", () =>
410 Effect.gen(function* () {
411 let stopFails = true;
412 const expo = fakeExpo({ failStop: () => stopFails });
413 const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), yield* Scope.make());
414 const ready = yield* host.ensureReady(() => Effect.void);
415 const [catalogDevice] = (yield* ready.devices.list).devices;
416 yield* ready.devices.boot(catalogDevice!);
417 yield* ready.devices.shutdown({ id: "session-1", platform: "ios" }).pipe(Effect.flip);
418 expect((yield* ready.devices.list).devices.map((device) => device.id)).toContain("session-1");
419 const refused = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
420 expect(refused.message).toContain("limited to 1 running session");
421 stopFails = false;
422 yield* ready.devices.list;
423 expect((yield* ready.devices.list).devices.map((device) => device.id)).toEqual(["eas-ios"]);
424 expect(expo.stopped().filter((id) => id === "session-1").length).toBeGreaterThanOrEqual(2);
425 }).pipe(Effect.scoped, Effect.provide(layer)),
426 );
427
428 it.effect("lets go of a stopping session Expo has ended although its stop keeps failing", () =>
429 Effect.gen(function* () {
430 let status = "IN_PROGRESS";
431 const expo = fakeExpo({ failStop: () => true, status: () => status });
432 const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), yield* Scope.make());
433 const ready = yield* host.ensureReady(() => Effect.void);
434 const [catalogDevice] = (yield* ready.devices.list).devices;
435 yield* ready.devices.boot(catalogDevice!);
436 yield* ready.devices.shutdown({ id: "session-1", platform: "ios" }).pipe(Effect.flip);
437 expect((yield* ready.devices.list).devices.map((device) => device.id)).toContain("session-1");
438 // Expo ended it by itself: the stop keeps failing, but the status says so.
439 status = "STOPPED";
440 expect((yield* ready.devices.list).devices.map((device) => device.id)).toEqual(["eas-ios"]);
441 status = "IN_PROGRESS";
442 expect(yield* ready.devices.boot(catalogDevice!)).toBe("session-2");
443 }).pipe(Effect.scoped, Effect.provide(layer)),
444 );
445
446 it.effect("asks for an EAS project before starting anything when none can be found", () =>
447 Effect.gen(function* () {
448 const expo = fakeExpo();
449 const host = yield* makeHost(expo, config({ appId: undefined }), yield* Scope.make());
450 const ready = yield* host.ensureReady(() => Effect.void);
451 const [catalogDevice] = (yield* ready.devices.list).devices;
452 const failure = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
453 expect(failure.message).toContain("Choose one for this host in Settings");
454 expect(expo.named("T3CreateEasSimulatorSession")).toHaveLength(0);
455 }).pipe(Effect.scoped, Effect.provide(layer)),
456 );
457
458 it.effect("stops a session that is still starting when the host stops", () =>
459 Effect.gen(function* () {
460 const previewGate = yield* makeGate;
461 const expo = fakeExpo({ previewGate });
462 const host = yield* makeHost(expo, config(), yield* Scope.make());
463 const ready = yield* host.ensureReady(() => Effect.void);
464 const [catalogDevice] = (yield* ready.devices.list).devices;
465 const booting = yield* ready.devices.boot(catalogDevice!).pipe(Effect.forkChild);
466 yield* Deferred.await(previewGate.requested);
467 // Never released: stopping must not wait for the session to become ready.
468 yield* host.stop;
469 expect(expo.stopped()).toEqual(["session-1"]);
470 const failure = yield* Fiber.join(booting).pipe(Effect.flip);
471 expect(failure.message).toContain("was stopped while the session started");
472 expect((yield* ready.devices.list).devices.map((device) => device.id)).toEqual(["eas-ios"]);
473 }).pipe(Effect.scoped, Effect.provide(layer)),
474 );
475});