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

session.ts

227 lines9.0 KB

1// @effect-diagnostics nodeBuiltinImport:off - owns Metro.
2/**
3 * One device's run state, shared by mobile:behavior and mobile:metrics: an isolated server with a
4 * long settled thread, a Metro serving a checkout with the behavior probe, and the dev client opened
5 * on it and paired with the server. Everything stops when the caller's scope closes.
6 */
7import * as NodeChildProcess from "node:child_process";
8import * as NodeFS from "node:fs";
9import * as NodeOS from "node:os";
10import * as NodePath from "node:path";
11import type { ThreadId } from "@t3tools/contracts";
12import * as Console from "effect/Console";
13import * as Effect from "effect/Effect";
14import { FetchHttpClient, HttpClient } from "effect/http";
15​
16import { APP_ID, DeviceError, makeDevice, SCHEME, type ProbeState } from "./device.ts";
17import { freePort, startEnvironment, uuid, type EnvironmentOptions } from "./environment.ts";
18import { serveReleaseBytecode } from "./release-bytecode.ts";
19​
20const REPO_ROOT = NodePath.resolve(import.meta.dirname, "../..");
21​
22/** This machine's address as the simulator sees it: the tailnet address, else the first LAN IPv4. */
23export function reachableHost(): string {
24 const tailnet = NodeChildProcess.spawnSync("tailscale", ["ip", "-4"], { encoding: "utf8" });
25 const ip = tailnet.status === 0 ? tailnet.stdout.trim().split("\n")[0] : undefined;
26 if (ip) return ip;
27 const lan = Object.values(NodeOS.networkInterfaces())
28 .flatMap((entries) => entries ?? [])
29 .find((entry) => entry.family === "IPv4" && !entry.internal);
30 return lan?.address ?? "127.0.0.1";
32​
33/**
34 * `dev` serves the development bundle; `release` serves the production bundle as Hermes bytecode
35 * (see release-bytecode.ts) to the same dev client.
36 */
37export type Build = "dev" | "release";
38​
39/** Metro with the behavior probe compiled in, stopped with its process group when the scope ends. */
40export const startMetro = Effect.fn("session.startMetro")(function* (input: {
41 readonly host: string;
42 readonly out: string;
43 /** The checkout whose app Metro serves; defaults to this one. */
44 readonly checkout?: string;
45 readonly env?: Readonly<Record<string, string>>;
46 readonly build?: Build;
47}) {
48 const checkout = input.checkout ?? REPO_ROOT;
49 const release = input.build === "release";
50 const port = yield* freePort();
51 // In release mode the app opens the bytecode proxy on `port`, which fronts Metro.
52 const metroPort = release ? yield* freePort() : port;
53 const log = NodeFS.openSync(NodePath.join(input.out, "metro.log"), "w");
54 yield* Effect.acquireRelease(
55 Effect.sync(() =>
56 NodeChildProcess.spawn(
57 "npx",
58 [
59 "expo",
60 "start",
61 "--dev-client",
62 "--scheme",
63 SCHEME,
64 "--lan",
65 "--port",
66 String(metroPort),
67 ...(release ? ["--no-dev", "--minify"] : []),
68 ],
69 {
70 cwd: NodePath.join(checkout, "apps/mobile"),
71 detached: true,
72 stdio: ["ignore", log, log],
73 env: {
74 ...process.env,
75 APP_VARIANT: "development",
76 CI: "1",
77 // Lazily fetched chunks sometimes arrive broken on pool emulators and throw SyntaxErrors.
78 EXPO_NO_METRO_LAZY: "1",
79 EXPO_PUBLIC_T3_BEHAVIOR_PROBE: "1",
80 REACT_NATIVE_PACKAGER_HOSTNAME: input.host,
81 ...input.env,
82 },
83 },
84 ),
85 ),
86 (child) => Effect.sync(() => child.pid !== undefined && process.kill(-child.pid, "SIGTERM")),
87 );
88 const metro = `http://${input.host}:${port}`;
89 for (let attempt = 0; ; attempt++) {
90 const ready = yield* HttpClient.get(`http://${input.host}:${metroPort}/status`).pipe(
91 Effect.flatMap((response) => response.text),
92 Effect.provide(FetchHttpClient.layer),
93 Effect.orElseSucceed(() => ""),
94 );
95 if (ready.includes("running")) break;
96 if (attempt >= 120)
97 return yield* new DeviceError({
98 message: `Metro never started; see ${input.out}/metro.log.`,
99 });
100 yield* Effect.sleep("1 second");
101 }
102 if (!release) return metro;
103 yield* Console.error("Compiling the production bundle to Hermes bytecode (a few minutes)...");
104 const bytes = yield* serveReleaseBytecode({ port, metroPort, checkout, out: input.out });
105 yield* Console.error(`Serving ${Math.round(bytes / 1024)} KB of release bytecode on ${metro}.`);
106 return metro;
107});
108​
109export interface SessionOptions {
110 readonly out: string;
111 readonly host: string;
112 readonly agentDevice: string;
113 readonly targetArgs: ReadonlyArray<string>;
114 readonly deviceName: string;
115 readonly platform?: "ios" | "android";
116 readonly fold?: "closed" | "open";
117 readonly forgetOtherEnvironments: boolean;
118 /** Turns in the long settled thread every run seeds. */
119 readonly longTurns: number;
120 readonly homeThreads?: number;
121 readonly checkout?: string;
122 readonly metroEnv?: Readonly<Record<string, string>>;
123 readonly build?: Build;
124 readonly environment?: EnvironmentOptions;
126​
127export const startSession = Effect.fn("session.start")(function* (options: SessionOptions) {
128 const env = yield* startEnvironment({
129 baseDir: NodePath.join(options.out, "env"),
130 deviceHost: options.host,
131 ...options.environment,
132 });
133 for (let index = 0; index < (options.homeThreads ?? 0); index++) {
134 yield* env.createEmptyThread(`Bench inbox thread ${index + 1}`);
135 }
136 const tag = (yield* uuid).slice(0, 4);
137 yield* Console.error(`Seeding a ${options.longTurns}-turn thread on ${env.origin}...`);
138 const longTitle = `Long settled thread ${tag}`;
139 const longThread: ThreadId = yield* env.longThread(longTitle, options.longTurns);
140​
141 const metro = yield* startMetro({
142 host: options.host,
143 out: options.out,
144 ...(options.checkout ? { checkout: options.checkout } : {}),
145 ...(options.metroEnv ? { env: options.metroEnv } : {}),
146 ...(options.build ? { build: options.build } : {}),
147 });
148 const device = makeDevice({
149 agentDevice: options.agentDevice,
150 targetArgs: options.targetArgs,
151 metro,
152 deviceName: options.deviceName,
153 });
154 yield* Console.error(`Opening the dev client against ${metro}...`);
155 // agent-device answers iOS's "Open in" prompt; the flags keep dev-menu chrome off the app.
156 const metroUrl = new URL(metro);
157 const launchUrl = `${SCHEME}://expo-development-client/?url=${encodeURIComponent(metro)}&disableOnboarding=1&__expo_disable_fab=1&__expo_disable_auto_launch=1`;
158 yield* device
159 .run(
160 [
161 "open",
162 APP_ID,
163 "--relaunch",
164 "--metro-host",
165 metroUrl.hostname,
166 "--metro-port",
167 metroUrl.port,
168 "--launch-url",
169 launchUrl,
170 ],
171 240_000,
172 )
173 .pipe(Effect.retry({ times: 2 }));
174 for (let attempt = 0; ; attempt++) {
175 const loaded = yield* device
176 .evaluate("typeof __t3Behavior")
177 .pipe(Effect.orElseSucceed(() => ""));
178 if (loaded === "object") break;
179 // iOS asks before a URL opens another app; busy hosts can miss the first accept.
180 if (options.platform !== "android" && attempt % 5 === 0) {
181 yield* device.acceptOpenPrompt.pipe(Effect.ignore);
182 }
183 if (attempt > 120)
184 return yield* new DeviceError({
185 message:
186 "The probe never loaded. Is this a dev client built from this checkout's native fingerprint?",
187 });
188 yield* Effect.sleep("2 seconds");
189 }
190 if (options.fold) yield* device.fold(options.fold);
191 const forget = (ids: ReadonlyArray<string>) =>
192 device
193 .evaluate(`__t3Behavior.forgetEnvironments(${JSON.stringify(ids)})`)
194 .pipe(Effect.andThen(Effect.sleep("3 seconds")));
195 const pair = Effect.gen(function* () {
196 const pairing = yield* env.pairingUrl();
197 yield* device.openUrl(
198 `${SCHEME}://connections/new?pairingUrl=${encodeURIComponent(pairing)}&autoConnect=1`,
199 );
200 });
201 yield* pair;
202 // Registered once pairing starts, so a stopped run never leaves its environment in the app.
203 yield* Effect.addFinalizer(() => forget([env.environmentId]).pipe(Effect.ignore));
204 const seeded = (state: ProbeState) => state.homeList !== null && longThread in state.threads;
205 // A busy pool simulator sometimes drops the first pairing link; a fresh credential retries it.
206 yield* device
207 .waitFor("the paired environment's threads on Home", seeded, 60_000)
208 .pipe(
209 Effect.catch(() =>
210 pair.pipe(
211 Effect.andThen(
212 device.waitFor("the paired environment's threads on Home", seeded, 60_000),
213 ),
214 ),
215 ),
216 );
217 // Other saved environments keep cached threads (some stuck working) that skew status cases.
218 const others = (yield* device.state).environments.filter((id) => id !== env.environmentId);
219 if (others.length > 0 && !options.forgetOtherEnvironments)
220 return yield* new DeviceError({
221 message: `The app has ${others.length} other saved environment(s). Use a device with no other connections, or pass --forget-other-environments on a disposable device.`,
222 });
223 if (others.length > 0) yield* forget(others);
224 return { env, device, metro, longThread, longTitle, seeded };
225});
226​
227export type Session = Effect.Success<ReturnType<typeof startSession>>;