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 HostProcess from "@t3tools/shared/HostProcess";
5import * as Deferred from "effect/Deferred";
6import * as Effect from "effect/Effect";
7import * as Fiber from "effect/Fiber";
8import * as Exit from "effect/Exit";
9import * as FileSystem from "effect/FileSystem";
10import * as Layer from "effect/Layer";
11import * as Path from "effect/Path";
12import * as Scope from "effect/Scope";
13import * as TestClock from "effect/testing/TestClock";
14import { HttpClient, HttpClientResponse } from "effect/http";
15
16import * as ServerConfig from "../config.ts";
17import * as ProcessRunner from "../processRunner.ts";
18import * as EasDeviceHost from "./EasDeviceHost.ts";
19
20const APP_ID = "d763fcb8-d37c-41ea-a773-b54a0ab4a454";
21
22const config = (overrides: Partial<EasDeviceHostConfig> = {}): EasDeviceHostConfig => ({
23 kind: "eas",
24 id: "eas",
25 label: "EAS Simulator",
26 appId: APP_ID,
27 accessToken: "expo-token",
28 maxSessionMinutes: 25,
29 idleMinutes: 5,
30 maxConcurrentSessions: 2,
31 ...overrides,
32});
33
34interface Gate {
35 readonly requested: Deferred.Deferred<void>;
36 readonly release: Deferred.Deferred<void>;
37}
38const makeGate = Effect.all({
39 requested: Deferred.make<void>(),
40 release: Deferred.make<void>(),
41});
42
43/** Expo's API and one session's preview host, recording what was asked of them. */
44const fakeExpo = (
45 options: {
46 readonly status?: () => string;
47 readonly failCreate?: boolean;
48 /** Expo answers the create with GraphQL errors: a refusal. */
49 readonly rejectCreate?: boolean;
50 readonly failStop?: () => boolean;
51 readonly failList?: () => boolean;
52 readonly active?: ReadonlyArray<{ id: string; status: string; name: string }>;
53 readonly previewGate?: Gate;
54 readonly createGate?: Gate;
55 /** Holds the first session read it answers with a gate. */
56 readonly sessionGate?: () => Gate | undefined;
57 readonly activeIncludesCreated?: boolean;
58 readonly failPreview?: boolean;
59 readonly omitCreatedFromActive?: boolean;
60 } = {},
61) => {
62 const calls: Array<{ operation: string; variables: Record<string, unknown> }> = [];
63 let created = 0;
64 let createdName = "";
65 let previewFails = options.failPreview ?? false;
66 let createFails = options.failCreate ?? false;
67 let sessionGated = false;
68 const http = HttpClient.make((request) =>
69 Effect.gen(function* () {
70 const url = new URL(request.url);
71 if (url.origin === "https://preview.test") {
72 expect(request.headers.authorization).toBe("Bearer preview-token");
73 if (options.previewGate) {
74 yield* Deferred.succeed(options.previewGate.requested, undefined);
75 yield* Deferred.await(options.previewGate.release);
76 }
77 if (previewFails) {
78 return HttpClientResponse.fromWeb(request, new Response("bad gateway", { status: 502 }));
79 }
80 return HttpClientResponse.fromWeb(request, Response.json({ device: "UDID-1" }));
81 }
82 const body =
83 request.body._tag === "Uint8Array"
84 ? (JSON.parse(new TextDecoder().decode(request.body.body)) as {
85 query: string;
86 variables: Record<string, { name?: string } & Record<string, unknown>>;
87 })
88 : { query: "", variables: {} };
89 expect(request.headers.authorization).toBe("Bearer expo-token");
90 const operation = /(?:query|mutation) (\w+)/.exec(body.query)?.[1] ?? "unknown";
91 calls.push({ operation, variables: body.variables });
92 if (operation === "T3CreateEasSimulatorSession") {
93 createdName = body.variables.input?.name ?? "";
94 if (options.createGate) {
95 yield* Deferred.succeed(options.createGate.requested, undefined);
96 yield* Deferred.await(options.createGate.release);
97 }
98 if (createFails)
99 return HttpClientResponse.fromWeb(request, new Response("bad gateway", { status: 502 }));
100 if (options.rejectCreate)
101 return HttpClientResponse.fromWeb(
102 request,
103 Response.json({ errors: [{ message: "Not allowed" }] }),
104 );
105 }
106 if (operation === "T3StopEasSimulatorSession" && options.failStop?.()) {
107 return HttpClientResponse.fromWeb(request, new Response("bad gateway", { status: 502 }));
108 }
109 if (operation === "T3ActiveEasSimulatorSessions" && options.failList?.()) {
110 return HttpClientResponse.fromWeb(request, new Response("bad gateway", { status: 502 }));
111 }
112 const sessionGate =
113 operation === "T3EasSimulatorSession" ? options.sessionGate?.() : undefined;
114 if (sessionGate && !sessionGated) {
115 sessionGated = true;
116 yield* Deferred.succeed(sessionGate.requested, undefined);
117 yield* Deferred.await(sessionGate.release);
118 }
119 const data =
120 operation === "T3EasSimulatorAvailability"
121 ? {
122 app: {
123 byId: {
124 ownerAccount: {
125 name: "pingdotgg",
126 accountFeatureGates: { "device-run-sessions": true },
127 },
128 },
129 },
130 }
131 : operation === "T3CreateEasSimulatorSession"
132 ? { deviceRunSession: { createDeviceRunSession: { id: `session-${++created}` } } }
133 : operation === "T3ActiveEasSimulatorSessions"
134 ? {
135 app: {
136 byId: {
137 deviceRunSessionsPaginated: {
138 edges: [
139 ...(options.omitCreatedFromActive
140 ? []
141 : [{ node: { id: "orphan", status: "NEW", name: createdName } }]),
142 {
143 node: {
144 id: "someone-else",
145 status: "IN_PROGRESS",
146 name: "T3 Code · EAS Simulator · 000000",
147 },
148 },
149 ...(options.active ?? []).map((node) => ({ node })),
150 ...(options.activeIncludesCreated && created > 0
151 ? [
152 {
153 node: {
154 id: `session-${created}`,
155 status: "STARTING",
156 name: createdName,
157 },
158 },
159 ]
160 : []),
161 ],
162 },
163 },
164 },
165 }
166 : operation === "T3EasSimulatorSession"
167 ? {
168 deviceRunSessions: {
169 byId: {
170 id: body.variables.id,
171 status: options.status?.() ?? "IN_PROGRESS",
172 remoteConfig: {
173 __typename: "AgentDeviceRunSessionRemoteConfig",
174 agentDeviceRemoteSessionUrl: "https://agent.test",
175 agentDeviceRemoteSessionToken: "agent-token",
176 webPreviewToken: "preview-token",
177 previewApiUrl: "https://preview.test?token=preview-token",
178 },
179 },
180 },
181 }
182 : {
183 deviceRunSession: {
184 ensureDeviceRunSessionStopped: { id: body.variables.id, status: "STOPPED" },
185 },
186 };
187 return HttpClientResponse.fromWeb(request, Response.json({ data }));
188 }),
189 );
190 const named = (operation: string) => calls.filter((call) => call.operation === operation);
191 const stopped = () => named("T3StopEasSimulatorSession").map((call) => call.variables.id);
192 const allowPreview = () => {
193 previewFails = false;
194 };
195 const allowCreate = () => {
196 createFails = false;
197 };
198 return { http, named, stopped, allowPreview, allowCreate };
199};
200
201const layer = Layer.mergeAll(
202 ProcessRunner.layer,
203 ServerConfig.layerTest(process.cwd(), { prefix: "t3-eas-host-" }),
204).pipe(Layer.provideMerge(NodeServices.layer));
205
206const makeHost = (
207 expo: ReturnType<typeof fakeExpo>,
208 hostConfig: EasDeviceHostConfig,
209 scope: Scope.Scope,
210) =>
211 EasDeviceHost.make(hostConfig).pipe(
212 Effect.provideService(HttpClient.HttpClient, expo.http),
213 Effect.provideService(Scope.Scope, scope),
214 );
215
216describe("EAS Simulator host", () => {
217 it.effect("starts a bounded session and routes its stream and agent to that session", () =>
218 Effect.gen(function* () {
219 const expo = fakeExpo();
220 const scope = yield* Scope.make();
221 const host = yield* makeHost(expo, config(), scope);
222 const ready = yield* host.ensureReady(() => Effect.void);
223 const catalog = (yield* ready.devices.list).devices;
224 expect(catalog.map((device) => [device.id, device.booted])).toEqual([["eas-ios", false]]);
225
226 expect(yield* ready.devices.boot(catalog[0]!)).toBe("session-1");
227 expect(expo.named("T3CreateEasSimulatorSession")[0]?.variables.input).toMatchObject({
228 appId: APP_ID,
229 platform: "IOS",
230 type: "AGENT_DEVICE",
231 maxRunTimeMinutes: 25,
232 maxIdleTimeMinutes: 5,
233 });
234 const listed = (yield* ready.devices.list).devices;
235 expect(listed.find((device) => device.id === "session-1")?.booted).toBe(true);
236 expect(yield* ready.devices.agentEndpoint!("session-1")).toEqual({
237 baseUrl: "https://agent.test",
238 token: "agent-token",
239 agentDeviceId: "UDID-1",
240 });
241
242 const routed = yield* ready.upstream!(
243 "/vendor/serve-sim/helper/session-1/webrtc/offer",
244 new URLSearchParams("hostId=eas"),
245 );
246 expect(routed).toEqual({
247 url: "https://preview.test/helper/UDID-1/webrtc/offer?hostId=eas",
248 headers: { authorization: "Bearer preview-token" },
249 protocols: ["serve-sim.token.preview-token"],
250 });
251 expect(
252 yield* ready.upstream!(
253 "/vendor/serve-sim/helper/ws",
254 new URLSearchParams("device=session-1"),
255 ),
256 ).toMatchObject({ url: "https://preview.test/helper/ws?device=UDID-1" });
257 expect(yield* ready.upstream!("/vendor/serve-emu/ws", new URLSearchParams())).toBeNull();
258 expect(
259 yield* ready.upstream!("/vendor/serve-sim/helper/%E0/config", new URLSearchParams()),
260 ).toBeNull();
261
262 yield* Scope.close(scope, Exit.void);
263 expect(expo.named("T3StopEasSimulatorSession").map((call) => call.variables.id)).toEqual([
264 "session-1",
265 ]);
266 }).pipe(Effect.scoped, Effect.provide(layer)),
267 );
268
269 it.effect("refuses to start past its session limit", () =>
270 Effect.gen(function* () {
271 const expo = fakeExpo();
272 const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), yield* Scope.make());
273 const ready = yield* host.ensureReady(() => Effect.void);
274 const [catalogDevice] = (yield* ready.devices.list).devices;
275 yield* ready.devices.boot(catalogDevice!);
276 const refused = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
277 expect(refused.message).toBe(
278 "EAS Simulator is unavailable: EAS Simulator is limited to 1 running session. Close one in the Device panel first.",
279 );
280 expect(expo.named("T3CreateEasSimulatorSession")).toHaveLength(1);
281 }).pipe(Effect.scoped, Effect.provide(layer)),
282 );
283
284 it.effect("tells concurrent sessions apart although EAS gives each the same UDID", () =>
285 Effect.gen(function* () {
286 const expo = fakeExpo();
287 const scope = yield* Scope.make();
288 const host = yield* makeHost(expo, config({ maxConcurrentSessions: 2 }), scope);
289 const ready = yield* host.ensureReady(() => Effect.void);
290 const [catalogDevice] = (yield* ready.devices.list).devices;
291 expect(yield* ready.devices.boot(catalogDevice!)).toBe("session-1");
292 expect(yield* ready.devices.boot(catalogDevice!)).toBe("session-2");
293 expect((yield* ready.devices.list).devices.map((device) => device.id)).toEqual([
294 "eas-ios",
295 "session-1",
296 "session-2",
297 ]);
298 expect(
299 yield* ready.upstream!(
300 "/vendor/serve-sim/api",
301 new URLSearchParams("device=session-2&hostId=eas"),
302 ),
303 ).toMatchObject({ url: "https://preview.test/api?device=UDID-1&hostId=eas" });
304
305 yield* ready.devices.shutdown({ id: "session-1", platform: "ios" });
306 expect(expo.stopped()).toEqual(["session-1"]);
307 expect((yield* ready.devices.list).devices.map((device) => device.id)).toEqual([
308 "eas-ios",
309 "session-2",
310 ]);
311 yield* Scope.close(scope, Exit.void);
312 expect(expo.stopped()).toEqual(["session-1", "session-2"]);
313 }).pipe(Effect.scoped, Effect.provide(layer)),
314 );
315
316 it.effect(
317 "keeps a refused create's record for the reaper without counting it after a restart",
318 () =>
319 Effect.gen(function* () {
320 const fs = yield* FileSystem.FileSystem;
321 const path = yield* Path.Path;
322 const server = yield* ServerConfig.ServerConfig;
323 const ledger = path.join(server.stateDir, "device", "eas", "eas.json");
324 // Expo refuses the create and lists nothing.
325 const expo = fakeExpo({ rejectCreate: true, omitCreatedFromActive: true });
326 const first = yield* Scope.make();
327 const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), first);
328 const ready = yield* host.ensureReady(() => Effect.void);
329 const [catalogDevice] = (yield* ready.devices.list).devices;
330 yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
331 const entries = JSON.parse(yield* fs.readFileString(ledger)) as Array<{
332 refused?: boolean;
333 }>;
334 expect(entries.map((entry) => entry.refused)).toEqual([true]);
335 yield* Scope.close(first, Exit.void);
336 // A later server cannot even list the app: the record must not hold a slot.
337 const later = fakeExpo({ failList: () => true });
338 const restarted = yield* makeHost(
339 later,
340 config({ maxConcurrentSessions: 1 }),
341 yield* Scope.make(),
342 );
343 const readyAgain = yield* restarted.ensureReady(() => Effect.void);
344 const [device] = (yield* readyAgain.devices.list).devices;
345 expect(yield* readyAgain.devices.boot(device!)).toBe("session-1");
346 }).pipe(Effect.scoped, Effect.provide(layer)),
347 );
348
349 it.effect(
350 "does not sweep a replacement's session from a listing in flight when its scope closes",
351 () =>
352 Effect.gen(function* () {
353 const gate = yield* makeGate;
354 let armed = false;
355 const expo = fakeExpo({ sessionGate: () => (armed ? gate : undefined) });
356 const first = yield* Scope.make();
357 const old = yield* makeHost(expo, config(), first);
358 const oldReady = yield* old.ensureReady(() => Effect.void);
359 const [catalogDevice] = (yield* oldReady.devices.list).devices;
360 expect(yield* oldReady.devices.boot(catalogDevice!)).toBe("session-1");
361 // Long enough that the listing reads the session's status and a sweep is due.
362 yield* TestClock.adjust("2 minutes");
363 armed = true;
364 const listing = yield* oldReady.devices.list.pipe(Effect.forkChild);
365 yield* Deferred.await(gate.requested);
366 // Settings saved while the old listing waits on Expo.
367 yield* Scope.close(first, Exit.void);
368 const replacement = yield* makeHost(expo, config(), yield* Scope.make());
369 const ready = yield* replacement.ensureReady(() => Effect.void);
370 const [device] = (yield* ready.devices.list).devices;
371 expect(yield* ready.devices.boot(device!)).toBe("session-2");
372 yield* Deferred.succeed(gate.release, undefined);
373 yield* Fiber.join(listing);
374 expect(expo.stopped()).toEqual(["session-1"]);
375 }).pipe(Effect.scoped, Effect.provide(layer)),
376 );
377
378 it.effect("stops the session a refused create made anyway", () =>
379 Effect.gen(function* () {
380 // Expo refuses the create but lists a session by its name.
381 const expo = fakeExpo({ rejectCreate: true });
382 const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), yield* Scope.make());
383 const ready = yield* host.ensureReady(() => Effect.void);
384 const [catalogDevice] = (yield* ready.devices.list).devices;
385 const failure = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
386 expect(failure.message).toContain("Not allowed");
387 expect(expo.stopped()).toEqual(["orphan"]);
388 }).pipe(Effect.scoped, Effect.provide(layer)),
389 );
390
391 it.effect("records a session before creating it and refuses to start without the record", () =>
392 Effect.gen(function* () {
393 const fs = yield* FileSystem.FileSystem;
394 const path = yield* Path.Path;
395 const server = yield* ServerConfig.ServerConfig;
396 // A directory where the ledger file should be: it can be neither read nor written.
397 yield* fs.makeDirectory(path.join(server.stateDir, "device", "eas", "eas.json"), {
398 recursive: true,
399 });
400 const expo = fakeExpo();
401 const host = yield* makeHost(expo, config(), yield* Scope.make());
402 const ready = yield* host.ensureReady(() => Effect.void);
403 const [catalogDevice] = (yield* ready.devices.list).devices;
404 const failure = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
405 expect(failure.message).toContain("could not be read");
406 expect(expo.named("T3CreateEasSimulatorSession")).toHaveLength(0);
407 }).pipe(Effect.scoped, Effect.provide(layer)),
408 );
409
410 it.effect("keeps a session it could not stop counted, listed, and retried", () =>
411 Effect.gen(function* () {
412 let stopFails = true;
413 const expo = fakeExpo({ failStop: () => stopFails });
414 const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), yield* Scope.make());
415 const ready = yield* host.ensureReady(() => Effect.void);
416 const [catalogDevice] = (yield* ready.devices.list).devices;
417 yield* ready.devices.boot(catalogDevice!);
418 yield* ready.devices.shutdown({ id: "session-1", platform: "ios" }).pipe(Effect.flip);
419 expect((yield* ready.devices.list).devices.map((device) => device.id)).toContain("session-1");
420 const refused = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
421 expect(refused.message).toContain("limited to 1 running session");
422 stopFails = false;
423 yield* ready.devices.list;
424 expect((yield* ready.devices.list).devices.map((device) => device.id)).toEqual(["eas-ios"]);
425 expect(expo.stopped().filter((id) => id === "session-1").length).toBeGreaterThanOrEqual(2);
426 }).pipe(Effect.scoped, Effect.provide(layer)),
427 );
428
429 it.effect("lets go of a stopping session Expo has ended although its stop keeps failing", () =>
430 Effect.gen(function* () {
431 let status = "IN_PROGRESS";
432 const expo = fakeExpo({ failStop: () => true, status: () => status });
433 const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), yield* Scope.make());
434 const ready = yield* host.ensureReady(() => Effect.void);
435 const [catalogDevice] = (yield* ready.devices.list).devices;
436 yield* ready.devices.boot(catalogDevice!);
437 yield* ready.devices.shutdown({ id: "session-1", platform: "ios" }).pipe(Effect.flip);
438 expect((yield* ready.devices.list).devices.map((device) => device.id)).toContain("session-1");
439 // Expo ended it by itself: the stop keeps failing, but the status says so.
440 status = "STOPPED";
441 expect((yield* ready.devices.list).devices.map((device) => device.id)).toEqual(["eas-ios"]);
442 status = "IN_PROGRESS";
443 expect(yield* ready.devices.boot(catalogDevice!)).toBe("session-2");
444 }).pipe(Effect.scoped, Effect.provide(layer)),
445 );
446
447 it.effect("asks for an EAS project before starting anything when none can be found", () =>
448 Effect.gen(function* () {
449 const expo = fakeExpo();
450 const host = yield* makeHost(expo, config({ appId: undefined }), yield* Scope.make());
451 const ready = yield* host.ensureReady(() => Effect.void);
452 const [catalogDevice] = (yield* ready.devices.list).devices;
453 const failure = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
454 expect(failure.message).toContain("Choose one for this host in Settings");
455 expect(expo.named("T3CreateEasSimulatorSession")).toHaveLength(0);
456 }).pipe(Effect.scoped, Effect.provide(layer)),
457 );
458
459 it.effect("reports iOS unavailable on a server with no Expo credential", () =>
460 Effect.gen(function* () {
461 const fs = yield* FileSystem.FileSystem;
462 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-expo-home-" });
463 const host = yield* makeHost(
464 fakeExpo(),
465 config({ accessToken: "" }),
466 yield* Scope.make(),
467 ).pipe(
468 Effect.provideService(HostProcess.HomeDirectory, home),
469 Effect.provideService(HostProcess.Environment, {}),
470 );
471 const [ios] = (yield* host.summary).platforms;
472 expect(ios).toMatchObject({ platform: "ios", available: false });
473 expect(ios?.reason).toContain("No Expo credential on the server");
474 }).pipe(Effect.scoped, Effect.provide(layer)),
475 );
476
477 it.effect("stops a session that is still starting when the host stops", () =>
478 Effect.gen(function* () {
479 const previewGate = yield* makeGate;
480 const expo = fakeExpo({ previewGate });
481 const host = yield* makeHost(expo, config(), yield* Scope.make());
482 const ready = yield* host.ensureReady(() => Effect.void);
483 const [catalogDevice] = (yield* ready.devices.list).devices;
484 const booting = yield* ready.devices.boot(catalogDevice!).pipe(Effect.forkChild);
485 yield* Deferred.await(previewGate.requested);
486 // Never released: stopping must not wait for the session to become ready.
487 yield* host.stop;
488 expect(expo.stopped()).toEqual(["session-1"]);
489 const failure = yield* Fiber.join(booting).pipe(Effect.flip);
490 expect(failure.message).toContain("was stopped while the session started");
491 expect((yield* ready.devices.list).devices.map((device) => device.id)).toEqual(["eas-ios"]);
492 }).pipe(Effect.scoped, Effect.provide(layer)),
493 );
494});