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

session.ts

231 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 deviceConfig: string;
114 readonly deviceSession: string;
115 /** Simulator UDID; empty for a Simlock lease, whose gateway picks it. */
116 readonly device: string;
117 readonly deviceName: string;
118 readonly fold?: "closed" | "open";
119 readonly forgetOtherEnvironments: boolean;
120 /** Turns in the long settled thread every run seeds. */
121 readonly longTurns: number;
122 readonly checkout?: string;
123 readonly metroEnv?: Readonly<Record<string, string>>;
124 readonly build?: Build;
125 readonly environment?: EnvironmentOptions;
127​
128export const startSession = Effect.fn("session.start")(function* (options: SessionOptions) {
129 const env = yield* startEnvironment({
130 baseDir: NodePath.join(options.out, "env"),
131 deviceHost: options.host,
132 ...options.environment,
133 });
134 const tag = (yield* uuid).slice(0, 4);
135 yield* Console.error(`Seeding a ${options.longTurns}-turn thread on ${env.origin}...`);
136 const longTitle = `Long settled thread ${tag}`;
137 const longThread: ThreadId = yield* env.longThread(longTitle, options.longTurns);
138​
139 const metro = yield* startMetro({
140 host: options.host,
141 out: options.out,
142 ...(options.checkout ? { checkout: options.checkout } : {}),
143 ...(options.metroEnv ? { env: options.metroEnv } : {}),
144 ...(options.build ? { build: options.build } : {}),
145 });
146 const device = makeDevice({
147 agentDevice: options.agentDevice,
148 targetArgs: [
149 "--platform",
150 "ios",
151 ...(options.device ? ["--udid", options.device] : []),
152 "--config",
153 options.deviceConfig,
154 "--session",
155 options.deviceSession,
156 ],
157 metro,
158 deviceName: options.deviceName,
159 });
160 yield* Console.error(`Opening the dev client against ${metro}...`);
161 // agent-device answers iOS's "Open in" prompt; the flags keep dev-menu chrome off the app.
162 const metroUrl = new URL(metro);
163 const launchUrl = `${SCHEME}://expo-development-client/?url=${encodeURIComponent(metro)}&disableOnboarding=1&__expo_disable_fab=1&__expo_disable_auto_launch=1`;
164 yield* device
165 .run(
166 [
167 "open",
168 APP_ID,
169 "--relaunch",
170 "--metro-host",
171 metroUrl.hostname,
172 "--metro-port",
173 metroUrl.port,
174 "--launch-url",
175 launchUrl,
176 ],
177 240_000,
178 )
179 .pipe(Effect.retry({ times: 2 }));
180 for (let attempt = 0; ; attempt++) {
181 const loaded = yield* device
182 .evaluate("typeof __t3Behavior")
183 .pipe(Effect.orElseSucceed(() => ""));
184 if (loaded === "object") break;
185 // iOS asks before a URL opens another app; busy hosts can miss the first accept.
186 if (attempt % 5 === 0) yield* device.acceptOpenPrompt.pipe(Effect.ignore);
187 if (attempt > 120)
188 return yield* new DeviceError({
189 message:
190 "The probe never loaded. Is this a dev client built from this checkout's native fingerprint?",
191 });
192 yield* Effect.sleep("2 seconds");
193 }
194 if (options.fold) yield* device.fold(options.fold);
195 const forget = (ids: ReadonlyArray<string>) =>
196 device
197 .evaluate(`__t3Behavior.forgetEnvironments(${JSON.stringify(ids)})`)
198 .pipe(Effect.andThen(Effect.sleep("3 seconds")));
199 const pair = Effect.gen(function* () {
200 const pairing = yield* env.pairingUrl();
201 yield* device.openUrl(
202 `${SCHEME}://connections/new?pairingUrl=${encodeURIComponent(pairing)}&autoConnect=1`,
203 );
204 });
205 yield* pair;
206 // Registered once pairing starts, so a stopped run never leaves its environment in the app.
207 yield* Effect.addFinalizer(() => forget([env.environmentId]).pipe(Effect.ignore));
208 const seeded = (state: ProbeState) => state.homeList !== null && longThread in state.threads;
209 // A busy pool simulator sometimes drops the first pairing link; a fresh credential retries it.
210 yield* device
211 .waitFor("the paired environment's threads on Home", seeded, 60_000)
212 .pipe(
213 Effect.catch(() =>
214 pair.pipe(
215 Effect.andThen(
216 device.waitFor("the paired environment's threads on Home", seeded, 60_000),
217 ),
218 ),
219 ),
220 );
221 // Other saved environments keep cached threads (some stuck working) that skew status cases.
222 const others = (yield* device.state).environments.filter((id) => id !== env.environmentId);
223 if (others.length > 0 && !options.forgetOtherEnvironments)
224 return yield* new DeviceError({
225 message: `The app has ${others.length} other saved environment(s). Use a simulator with no other connections, or pass --forget-other-environments to remove them.`,
226 });
227 if (others.length > 0) yield* forget(others);
228 return { env, device, metro, longThread, longTitle, seeded };
229});
230​
231export type Session = Effect.Success<ReturnType<typeof startSession>>;