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

e2e.config.ts

181 lines6.9 KB

1// Scenarios: e2e tests that run against the real dev stack. See docs/operations/scenarios.md.
2import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import { mobile, type DeviceProvider } from "@e2e-dev/mobile";
5import { web } from "@e2e-dev/web";
6import * as HostProcess from "@t3tools/shared/HostProcess";
7import { createAgentDeviceClient } from "agent-device";
8import type { E2EConfig } from "e2e";
9import * as Effect from "effect/Effect";
10import * as Path from "effect/Path";
11import * as SecureRandom from "effect/crypto/SecureRandom";
12import * as Schedule from "effect/Schedule";
13​
14import { run, ScenarioError } from "./scenarios/shell.ts";
15​
16// e2e loads this module for its values, so the paths and the host are resolved once, here.
17const resolved = await Effect.gen(function* () {
18 const path = yield* Path.Path;
19 const env = yield* HostProcess.Environment;
20 const scripts = yield* path.fromFileUrl(new URL(".", import.meta.url));
21 const home = path.resolve(scripts, "../.t3/scenarios");
22 // A pooled device reaches this machine over the tailnet, not localhost.
23 const host = yield* run("tailscale", ["ip", "-4"]).pipe(
24 Effect.map((result) => result.stdout.trim().split("\n")[0] ?? ""),
25 Effect.orElseSucceed(() => ""),
26 );
27 return {
28 node: yield* HostProcess.ExecutablePath,
29 scripts,
30 /** The checkout whose app runs. `prove-scenario.ts` points it at a base or head worktree. */
31 appDir: path.resolve(scripts, env.T3_SCENARIO_APP_DIR ?? ".."),
32 home,
33 startApp: path.join(scripts, "scenarios/start-app.ts"),
34 mobile: {
35 host: host || "127.0.0.1",
36 // A mobile target has no `app.url`, so e2e cannot pick these ports.
37 serverPort: Number(env.T3_SCENARIO_SERVER_PORT ?? 13_990),
38 metroPort: Number(env.T3_SCENARIO_METRO_PORT ?? 8_190),
39 },
40 };
41}).pipe(Effect.provide(NodeServices.layer), Effect.runPromise);
42​
43export const APP_DIR = resolved.appDir;
44/** T3 homes only scenarios use, recreated on every run. `.t3` is gitignored. */
45export const T3_HOME = resolved.home;
46export const MOBILE_T3_HOME = `${T3_HOME}-mobile`;
47export const MOBILE = resolved.mobile;
48const startApp = resolved.startApp;
49​
50/**
51 * Leases a device from the Simlock pool, whose gateway speaks agent-device's lease protocol.
52 * `retainOnClose` keeps the device when the engine closes its session between attempts.
53 */
54const simlock = (device: string): DeviceProvider => {
55 const connect = Effect.fn("simlock.connect")(function* (
56 env: Readonly<Record<string, string | undefined>>,
57 ) {
58 const daemonBaseUrl = env.SIMLOCK_AGENT_DEVICE_URL;
59 const daemonAuthToken = env.AGENT_DEVICE_DAEMON_AUTH_TOKEN;
60 if (daemonBaseUrl === undefined || daemonAuthToken === undefined) {
61 return yield* new ScenarioError({
62 message: "SIMLOCK_AGENT_DEVICE_URL and AGENT_DEVICE_DAEMON_AUTH_TOKEN are not set.",
63 });
64 }
65 return { daemonBaseUrl, daemonAuthToken };
66 });
67 const call = <A>(description: string, request: () => Promise<A>) =>
68 Effect.tryPromise({
69 try: request,
70 catch: (cause) => new ScenarioError({ message: `${description}: ${String(cause)}` }),
71 });
72 const acquire = Effect.fn("simlock.acquire")(function* (
73 request: Parameters<DeviceProvider["acquire"]>[0],
74 ) {
75 const daemon = yield* connect(request.env);
76 const client = createAgentDeviceClient(daemon);
77 const platform = request.platform === "android" ? "android" : "ios";
78 const scope = { tenant: "t3-scenarios", runId: `${request.runId}-${request.slot}` };
79 // Simlock takes the lease id from the caller: 32 hex characters.
80 const leaseId = (yield* (yield* SecureRandom.SecureRandom).uuidV4()).replaceAll("-", "");
81 const lease = yield* call(`The pool leased no ${device}`, () =>
82 client.leases.allocate({ ...scope, platform, device, retainOnClose: true, leaseId }),
83 ).pipe(
84 // A busy gateway answers its health probe late, which the client reports as unavailable.
85 Effect.tapError(() => Effect.sync(() => request.log("the pool is busy; asking again"))),
86 Effect.retry({ schedule: Schedule.spaced("10 seconds"), times: 12 }),
87 );
88 const leaseScope = { ...scope, leaseId: lease.leaseId, leaseBackend: lease.backend };
89 // The pool answers `boot` with the leased device; a worker hosts several, so name ours.
90 const leased = yield* call("The pool did not name the leased device", () =>
91 createAgentDeviceClient({ ...daemon, ...leaseScope }).devices.boot({ platform }),
92 ).pipe(
93 // e2e releases only the leases `acquire` returned.
94 Effect.tapError(() =>
95 call("release", () => client.leases.release({ leaseId: lease.leaseId })).pipe(
96 Effect.ignore,
97 ),
98 ),
99 );
100 return {
101 id: lease.leaseId,
102 daemon: { baseUrl: daemon.daemonBaseUrl, authToken: daemon.daemonAuthToken },
103 deviceId: leased.id,
104 client: {
105 ...leaseScope,
106 ...(lease.leaseProvider === undefined ? {} : { leaseProvider: lease.leaseProvider }),
107 },
108 };
109 });
110 return {
111 name: "simlock",
112 acquire: (request) =>
113 acquire(request).pipe(Effect.provide(NodeCrypto.layer), Effect.runPromise),
114 release: (lease, context) =>
115 connect(context.env).pipe(
116 Effect.flatMap((daemon) =>
117 call("release", () =>
118 createAgentDeviceClient(daemon).leases.release({ leaseId: lease.id }),
119 ),
120 ),
121 Effect.asVoid,
122 Effect.runPromise,
123 ),
124 };
125};
126​
127export default {
128 tests: "scenarios/**/*.e2e.ts",
129 targets: [
130 {
131 name: "web",
132 engine: web({ viewport: { width: 1280, height: 800 } }),
133 app: {
134 url: "http://127.0.0.1:0",
135 // Vite answers before the server does; this path is proxied to the server.
136 readyUrl: "http://127.0.0.1:{port}/.well-known/t3/environment",
137 command: {
138 executable: resolved.node,
139 args: [startApp, "web", T3_HOME, "{port}"],
140 cwd: APP_DIR,
141 startupTimeout: 300_000,
142 log: ".e2e/app.log",
143 },
144 },
145 },
146 {
147 name: "ios",
148 engine: mobile({
149 platform: "ios",
150 device: simlock("iPhone 18 Pro"),
151 session: "t3-scenarios",
152 }),
153 app: {
154 bundleId: "com.t3tools.t3code.dev",
155 // Metro starts after the server listens, so it answering means both are up.
156 readyUrl: `http://127.0.0.1:${MOBILE.metroPort}/status`,
157 command: {
158 executable: resolved.node,
159 args: [
160 startApp,
161 "mobile",
162 MOBILE_T3_HOME,
163 String(MOBILE.serverPort),
164 String(MOBILE.metroPort),
165 MOBILE.host,
166 ],
167 cwd: APP_DIR,
168 startupTimeout: 300_000,
169 log: ".e2e/mobile-app.log",
170 },
171 },
172 },
173 ],
174 // One server holds every test's state, and a dev stack is heavy.
175 workers: 1,
176 timeout: 300_000,
177 assertionTimeout: 15_000,
178 video: "on",
179 trace: "on",
180 reporters: ["list", "markdown"],
181} satisfies E2EConfig;