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

mobile-e2e.ts

337 lines11.6 KB

1#!/usr/bin/env node
2// @effect-diagnostics nodeBuiltinImport:off globalDate:off - Host-side device automation uses Node subprocess and filesystem APIs directly.
3​
4import * as NodeChildProcess from "node:child_process";
5import * as NodeFSP from "node:fs/promises";
6import * as NodeOS from "node:os";
7import * as NodePath from "node:path";
8import * as NodeProcess from "node:process";
9import * as NodeURL from "node:url";
10​
11import { Device, type Pool, poolError, run } from "./mobile-e2e/device.ts";
12import { runJourney, type StepResult } from "./mobile-e2e/journey.ts";
13import { POSES, type Pose } from "./mobile-e2e/poses.ts";
14import {
15 failedChecks,
16 poolBlocked,
17 poseFailed,
18 type PoseResult,
19 renderReport,
20} from "./mobile-e2e/report.ts";
21import { reviewPose } from "./mobile-e2e/review.ts";
22import {
23 reserveAvailablePort,
24 startShowcaseEnvironments,
25 stopProcess,
26 waitForPort,
27} from "./mobile-showcase.ts";
28import { SHOWCASE_ENVIRONMENTS } from "./mobile-showcase-environment.ts";
29​
30const REPO_ROOT = NodePath.resolve(NodePath.dirname(NodeURL.fileURLToPath(import.meta.url)), "..");
31​
32const log = (scope: string, message: string) => NodeProcess.stderr.write(`[${scope}] ${message}\n`);
33​
34/** This machine's Tailscale address (100.64.0.0/10), which pool devices reach it on. */
35function tailnetAddress(): string {
36 for (const addresses of Object.values(NodeOS.networkInterfaces())) {
37 for (const address of addresses ?? []) {
38 const [first, second] = address.address.split(".").map(Number);
39 if (address.family === "IPv4" && first === 100 && second! >= 64 && second! < 128)
40 return address.address;
41 }
42 }
43 throw new Error("No Tailscale IPv4 address: pool devices reach Metro and the fixture over it.");
45​
46async function mapConcurrent<T, R>(
47 items: ReadonlyArray<T>,
48 limit: number,
49 task: (item: T) => Promise<R>,
50): Promise<R[]> {
51 const results: R[] = Array.from({ length: items.length });
52 let next = 0;
53 await Promise.all(
54 Array.from({ length: Math.min(limit, items.length) }, async () => {
55 while (next < items.length) {
56 const index = next++;
57 results[index] = await task(items[index]!);
58 }
59 }),
60 );
61 return results;
63​
64async function issuePairUrl(
65 environment: { readonly baseDir: string; readonly port: number },
66 host: string,
67) {
68 const { stdout } = await run(
69 NodeProcess.execPath,
70 [
71 "apps/server/src/bin.ts",
72 "auth",
73 "pairing",
74 "create",
75 "--base-dir",
76 environment.baseDir,
77 "--base-url",
78 `http://${host}:${environment.port}`,
79 "--ttl",
80 "15m",
81 "--json",
82 ],
83 { cwd: REPO_ROOT },
84 );
85 const { pairUrl } = JSON.parse(
86 stdout.slice(stdout.indexOf("{"), stdout.lastIndexOf("}") + 1),
87 ) as {
88 pairUrl?: string;
89 };
90 if (!pairUrl) throw new Error("The pairing command returned no pairUrl.");
91 return pairUrl;
93​
94async function runPose(
95 pose: Pose,
96 pool: Pool,
97 runId: string,
98 outputDirectory: string,
99 metroUrl: string,
100 pair: () => Promise<string>,
101): Promise<PoseResult> {
102 const directory = NodePath.join(outputDirectory, pose.id);
103 await NodeFSP.mkdir(directory, { recursive: true });
104 const steps: StepResult[] = [];
105 let device: Device | null = null;
106 try {
107 log(pose.id, `leasing ${pose.device}`);
108 device = await Device.lease(pose, pool, runId);
109 log(pose.id, "installing the dev client");
110 await device.install();
111 await device.prepare();
112 await device.launch(metroUrl);
113 log(pose.id, "pairing and walking the app");
114 await runJourney(device, directory, pair, steps);
115 return { pose, steps };
116 } catch (error) {
117 const message = error instanceof Error ? error.message : String(error);
118 if (!device) return { pose, steps, error: message };
119 // What the device showed when the journey stopped is usually the whole diagnosis.
120 const stopped = NodePath.join(directory, "stopped.png");
121 const shot = await device.screenshot(stopped).then(
122 () => stopped,
123 () => undefined,
124 );
125 const labels = await device.snapshot().then(
126 (snapshot) =>
127 snapshot.nodes
128 .map((node) => node.label)
129 .filter(Boolean)
130 .slice(0, 12)
131 .join(" | "),
132 () => "",
133 );
134 return {
135 pose,
136 steps,
137 error: labels ? `${message} (screen: ${labels})` : message,
138 ...(shot ? { stopped: shot } : {}),
139 };
140 } finally {
141 await device?.release();
142 }
144​
145async function main() {
146 const args = NodeProcess.argv.slice(2);
147 if (args.includes("--list")) {
148 for (const pose of POSES)
149 NodeProcess.stdout.write(
150 `${pose.id}\t${pose.device}${pose.pending ? `\t(pending: ${pose.pending})` : ""}\n`,
151 );
152 return;
153 }
154 const values = (flag: string) =>
155 args.flatMap((arg, index) => (args[index - 1] === flag ? [arg] : []));
156 const selected = values("--pose");
157 const unknown = selected.filter((id) => !POSES.some((pose) => pose.id === id));
158 if (unknown.length) throw new Error(`Unknown pose ${unknown.join(", ")}. Run with --list.`);
159 const platforms = values("--platform");
160 const poses = POSES.filter(
161 (pose) =>
162 (selected.length === 0 ? !pose.pending : selected.includes(pose.id)) &&
163 (platforms.length === 0 || platforms.includes(pose.platform)),
164 );
165 const concurrencyFlag = values("--concurrency")[0];
166 const concurrency = concurrencyFlag ? Number(concurrencyFlag) : undefined;
167 const review = !args.includes("--no-review");
168​
169 const agentDeviceUrl = NodeProcess.env.SIMLOCK_AGENT_DEVICE_URL;
170 const token = NodeProcess.env.AGENT_DEVICE_DAEMON_AUTH_TOKEN;
171 if (!agentDeviceUrl || !token)
172 throw new Error(
173 "Set SIMLOCK_AGENT_DEVICE_URL (<gateway>/v1/agent-device) and AGENT_DEVICE_DAEMON_AUTH_TOKEN (a Simlock agent token) to run on the device pool.",
174 );
175 const host = tailnetAddress();
176​
177 const runId = new Date().toISOString().replaceAll(/[:.]/g, "-");
178 const outputDirectory = NodePath.join(REPO_ROOT, "artifacts/mobile-e2e", runId);
179 await NodeFSP.mkdir(outputDirectory, { recursive: true });
180 const rootDir = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-mobile-e2e-"));
181 const workspace = await NodeFSP.realpath(outputDirectory);
182 const config = NodePath.join(rootDir, "agent-device.json");
183 await NodeFSP.writeFile(
184 config,
185 JSON.stringify({
186 daemonBaseUrl: agentDeviceUrl,
187 daemonAuthToken: token,
188 stateDir: NodePath.join(rootDir, "agent-device"),
189 }),
190 { mode: 0o600 },
191 );
192 const pool: Pool = {
193 repoRoot: REPO_ROOT,
194 agentDevice: NodePath.join(REPO_ROOT, "scripts/node_modules/agent-device/bin/agent-device.mjs"),
195 agentDeviceUrl,
196 workspace,
197 env: { ...NodeProcess.env, AGENT_DEVICE_CONFIG: config, PWD: workspace },
198 };
199​
200 const servers: NodeChildProcess.ChildProcess[] = [];
201 let metro: NodeChildProcess.ChildProcess | null = null;
202 try {
203 log("e2e", "starting the fixture server");
204 const [environment] = await startShowcaseEnvironments(
205 rootDir,
206 (server) => servers.push(server),
207 SHOWCASE_ENVIRONMENTS.slice(0, 1),
208 );
209 if (!environment) throw new Error("The fixture server did not start.");
210 const metroPort = await reserveAvailablePort();
211 metro = NodeChildProcess.spawn(
212 "vp",
213 [
214 "exec",
215 "expo",
216 "start",
217 "--dev-client",
218 "--scheme",
219 "t3code-dev",
220 "--lan",
221 "--port",
222 String(metroPort),
223 ],
224 {
225 cwd: NodePath.join(REPO_ROOT, "apps/mobile"),
226 env: { ...NodeProcess.env, APP_VARIANT: "development", CI: "1" },
227 stdio: ["ignore", "ignore", "inherit"],
228 // Its own group, so stopping it also stops the expo child that owns the port.
229 detached: true,
230 },
231 );
232 await waitForPort(metroPort, "Metro", 120_000);
233 // Warm each platform's bundle once, instead of on every device at once, and have its dev
234 // client cached before any lease: a cache miss builds, which can outlast a lease.
235 for (const platform of new Set(poses.map((pose) => pose.platform))) {
236 log("e2e", `preparing the ${platform} dev client`);
237 await run(
238 NodeProcess.execPath,
239 ["scripts/mobile-native-client.ts", "ensure", platform, "--prepare"],
240 { cwd: REPO_ROOT, timeoutMs: 1_800_000 },
241 );
242 log("e2e", `bundling for ${platform}`);
243 await run("curl", [
244 "-sf",
245 "-o",
246 "/dev/null",
247 `http://127.0.0.1:${metroPort}/apps/mobile/index.bundle?platform=${platform}&dev=true&minify=false`,
248 ]);
249 }
250​
251 const attempt = (pose: Pose, session: string) =>
252 runPose(pose, pool, session, outputDirectory, `http://${host}:${metroPort}`, () =>
253 issuePairUrl(environment, host),
254 );
255 const runOne = async (pose: Pose) => {
256 let result = await attempt(pose, runId);
257 // A pose that failed before its first screen usually met the pool, not the app.
258 for (
259 let retry = 1;
260 retry <= 2 && result.error && (result.steps.length === 0 || poolError(result.error));
261 retry++
262 ) {
263 log(pose.id, `retrying after: ${result.error.split("\n")[0]}`);
264 result = await attempt(pose, `${runId}-retry${retry}`);
265 }
266 return result;
267 };
268 // Each platform has its own workers, so each gets its own limit; one Mac runs every
269 // iOS simulator, and recording several at once on a shared pool times it out.
270 const byPlatform = await Promise.all(
271 (["ios", "android"] as const).map((platform) =>
272 mapConcurrent(
273 poses.filter((pose) => pose.platform === platform),
274 concurrency ?? (platform === "ios" ? 2 : 3),
275 runOne,
276 ),
277 ),
278 );
279 const results = poses.map((pose) => byPlatform.flat().find((result) => result.pose === pose)!);
280​
281 const reviewed = review
282 ? await mapConcurrent(results, 4, async (result) => {
283 log(result.pose.id, "agent review");
284 const findings = await reviewPose(result, outputDirectory).catch((error) => {
285 log(result.pose.id, `review failed: ${error instanceof Error ? error.message : error}`);
286 return [];
287 });
288 return { ...result, findings };
289 })
290 : results;
291​
292 const report = NodePath.join(outputDirectory, "index.html");
293 await NodeFSP.writeFile(report, renderReport(reviewed, outputDirectory));
294 await NodeFSP.writeFile(
295 NodePath.join(outputDirectory, "report.json"),
296 JSON.stringify(reviewed, null, 2),
297 );
298 for (const result of reviewed) {
299 const failures = failedChecks(result).map(
300 (item) => `${item.step}: ${item.name} (${item.detail})`,
301 );
302 log(
303 result.pose.id,
304 [poolBlocked(result) ? `blocked by the pool: ${result.error}` : result.error, ...failures]
305 .filter(Boolean)
306 .join("; ") ||
307 `passed${result.findings?.length ? `, ${result.findings.length} review findings` : ""}`,
308 );
309 }
310 const failed = reviewed.filter((result) => poseFailed(result) && !poolBlocked(result)).length;
311 const blocked = reviewed.filter(poolBlocked).length;
312 NodeProcess.stdout.write(
313 `${JSON.stringify({
314 report,
315 poses: reviewed.length,
316 failed,
317 blocked,
318 findings: reviewed.reduce((count, result) => count + (result.findings?.length ?? 0), 0),
319 })}\n`,
320 );
321 // A pose the pool blocked was not tested, so it fails the run too.
322 process.exitCode = failed || blocked ? 1 : 0;
323 } finally {
324 if (metro?.pid) {
325 try {
326 NodeProcess.kill(-metro.pid, "SIGTERM");
327 } catch {}
328 await stopProcess(metro);
329 }
330 await Promise.all(servers.map((server) => stopProcess(server)));
331 await NodeFSP.rm(rootDir, { recursive: true, force: true });
332 }
334​
335if (import.meta.main) {
336 await main();