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

e2e.config.ts

194 lines7.5 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 // e2e gives the app only PATH, HOME and the temp directory. A scenario that needs more names
35 // it here: exact names or prefixes ending in `*`, separated by commas.
36 inheritEnv: (env.T3_SCENARIO_INHERIT_ENV ?? "")
37 .split(",")
38 .map((name) => name.trim())
39 .filter((name) => name !== ""),
40 mobile: {
41 host: host || "127.0.0.1",
42 // A mobile target has no `app.url`, so e2e cannot pick these ports.
43 serverPort: Number(env.T3_SCENARIO_SERVER_PORT ?? 13_990),
44 metroPort: Number(env.T3_SCENARIO_METRO_PORT ?? 8_190),
45 },
46 };
47}).pipe(Effect.provide(NodeServices.layer), Effect.runPromise);
48​
49export const APP_DIR = resolved.appDir;
50/** T3 homes only scenarios use, recreated on every run. `.t3` is gitignored. */
51export const T3_HOME = resolved.home;
52export const MOBILE_T3_HOME = `${T3_HOME}-mobile`;
53export const MOBILE = resolved.mobile;
54const startApp = resolved.startApp;
55/**
56 * The one address e2e opens the web app at and the app is told to bind. Never `localhost`: the
57 * runner and the app can resolve that name to different addresses.
58 */
59const LOOPBACK = "127.0.0.1";
60​
61/**
62 * Leases a device from the Simlock pool, whose gateway speaks agent-device's lease protocol.
63 * `retainOnClose` keeps the device when the engine closes its session between attempts.
64 */
65const simlock = (device: string): DeviceProvider => {
66 const connect = Effect.fn("simlock.connect")(function* (
67 env: Readonly<Record<string, string | undefined>>,
68 ) {
69 const daemonBaseUrl = env.SIMLOCK_AGENT_DEVICE_URL;
70 const daemonAuthToken = env.AGENT_DEVICE_DAEMON_AUTH_TOKEN;
71 if (daemonBaseUrl === undefined || daemonAuthToken === undefined) {
72 return yield* new ScenarioError({
73 message: "SIMLOCK_AGENT_DEVICE_URL and AGENT_DEVICE_DAEMON_AUTH_TOKEN are not set.",
74 });
75 }
76 return { daemonBaseUrl, daemonAuthToken };
77 });
78 const call = <A>(description: string, request: () => Promise<A>) =>
79 Effect.tryPromise({
80 try: request,
81 catch: (cause) => new ScenarioError({ message: `${description}: ${String(cause)}` }),
82 });
83 const acquire = Effect.fn("simlock.acquire")(function* (
84 request: Parameters<DeviceProvider["acquire"]>[0],
85 ) {
86 const daemon = yield* connect(request.env);
87 const client = createAgentDeviceClient(daemon);
88 const platform = request.platform === "android" ? "android" : "ios";
89 const scope = { tenant: "t3-scenarios", runId: `${request.runId}-${request.slot}` };
90 // Simlock takes the lease id from the caller: 32 hex characters.
91 const leaseId = (yield* (yield* SecureRandom.SecureRandom).uuidV4()).replaceAll("-", "");
92 const lease = yield* call(`The pool leased no ${device}`, () =>
93 client.leases.allocate({ ...scope, platform, device, retainOnClose: true, leaseId }),
94 ).pipe(
95 // A busy gateway answers its health probe late, which the client reports as unavailable.
96 Effect.tapError(() => Effect.sync(() => request.log("the pool is busy; asking again"))),
97 Effect.retry({ schedule: Schedule.spaced("10 seconds"), times: 12 }),
98 );
99 const leaseScope = { ...scope, leaseId: lease.leaseId, leaseBackend: lease.backend };
100 // The pool answers `boot` with the leased device; a worker hosts several, so name ours.
101 const leased = yield* call("The pool did not name the leased device", () =>
102 createAgentDeviceClient({ ...daemon, ...leaseScope }).devices.boot({ platform }),
103 ).pipe(
104 // e2e releases only the leases `acquire` returned.
105 Effect.tapError(() =>
106 call("release", () => client.leases.release({ leaseId: lease.leaseId })).pipe(
107 Effect.ignore,
108 ),
109 ),
110 );
111 return {
112 id: lease.leaseId,
113 daemon: { baseUrl: daemon.daemonBaseUrl, authToken: daemon.daemonAuthToken },
114 deviceId: leased.id,
115 client: {
116 ...leaseScope,
117 ...(lease.leaseProvider === undefined ? {} : { leaseProvider: lease.leaseProvider }),
118 },
119 };
120 });
121 return {
122 name: "simlock",
123 acquire: (request) =>
124 acquire(request).pipe(Effect.provide(NodeCrypto.layer), Effect.runPromise),
125 release: (lease, context) =>
126 connect(context.env).pipe(
127 Effect.flatMap((daemon) =>
128 call("release", () =>
129 createAgentDeviceClient(daemon).leases.release({ leaseId: lease.id }),
130 ),
131 ),
132 Effect.asVoid,
133 Effect.runPromise,
134 ),
135 };
136};
137​
138export default {
139 tests: "scenarios/**/*.e2e.ts",
140 targets: [
141 {
142 name: "web",
143 engine: web({ viewport: { width: 1280, height: 800 } }),
144 app: {
145 url: `http://${LOOPBACK}:0`,
146 // Vite answers before the server does; this path is proxied to the server.
147 readyUrl: `http://${LOOPBACK}:{port}/.well-known/t3/environment`,
148 command: {
149 executable: resolved.node,
150 args: [startApp, "web", T3_HOME, LOOPBACK, "{port}"],
151 cwd: APP_DIR,
152 inheritEnv: resolved.inheritEnv,
153 startupTimeout: 300_000,
154 log: ".e2e/app.log",
155 },
156 },
157 },
158 {
159 name: "ios",
160 engine: mobile({
161 platform: "ios",
162 device: simlock("iPhone 18 Pro"),
163 session: "t3-scenarios",
164 }),
165 app: {
166 bundleId: "com.t3tools.t3code.dev",
167 // Metro starts after the server listens, so it answering means both are up.
168 readyUrl: `http://127.0.0.1:${MOBILE.metroPort}/status`,
169 command: {
170 executable: resolved.node,
171 args: [
172 startApp,
173 "mobile",
174 MOBILE_T3_HOME,
175 String(MOBILE.serverPort),
176 String(MOBILE.metroPort),
177 MOBILE.host,
178 ],
179 cwd: APP_DIR,
180 inheritEnv: resolved.inheritEnv,
181 startupTimeout: 300_000,
182 log: ".e2e/mobile-app.log",
183 },
184 },
185 },
186 ],
187 // One server holds every test's state, and a dev stack is heavy.
188 workers: 1,
189 timeout: 300_000,
190 assertionTimeout: 15_000,
191 video: "on",
192 trace: "on",
193 reporters: ["list", "markdown"],
194} satisfies E2EConfig;