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

pool.ts

116 lines4.3 KB

1// @effect-diagnostics nodeBuiltinImport:off globalTimers:off globalFetch:off - host-side lease bookkeeping.
2/** Simlock leases for mobile:behavior and mobile:metrics: one agent-device config, leases kept alive. */
3import * as NodeFSP from "node:fs/promises";
4import * as NodeOS from "node:os";
5import * as NodePath from "node:path";
6import * as NodeProcess from "node:process";
7​
8import { Device, type Pool, poolError } from "../mobile-e2e/device.ts";
9import type { Pose } from "../mobile-e2e/poses.ts";
10​
11export interface PoolAccess {
12 readonly pool: Pool;
13 /** The agent-device config file a run's `--device-config` names. */
14 readonly config: string;
15 readonly stateDir: string;
16 readonly token: string;
17 readonly close: () => Promise<void>;
19​
20/** Writes the pool's agent-device config; `close` removes it. `workspace` must already exist. */
21export async function openPool(repoRoot: string, workspace: string): Promise<PoolAccess> {
22 const agentDeviceUrl = NodeProcess.env.SIMLOCK_AGENT_DEVICE_URL;
23 const token = NodeProcess.env.AGENT_DEVICE_DAEMON_AUTH_TOKEN;
24 if (!agentDeviceUrl || !token)
25 throw new Error(
26 "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.",
27 );
28 const rootDir = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-mobile-pool-"));
29 const config = NodePath.join(rootDir, "agent-device.json");
30 const stateDir = NodePath.join(rootDir, "agent-device");
31 await NodeFSP.writeFile(
32 config,
33 JSON.stringify({ daemonBaseUrl: agentDeviceUrl, daemonAuthToken: token, stateDir }),
34 { mode: 0o600 },
35 );
36 const real = await NodeFSP.realpath(workspace);
37 return {
38 pool: {
39 repoRoot,
40 agentDevice: NodePath.join(
41 repoRoot,
42 "scripts/node_modules/agent-device/bin/agent-device.mjs",
43 ),
44 agentDeviceUrl,
45 workspace: real,
46 env: { ...NodeProcess.env, AGENT_DEVICE_CONFIG: config, PWD: real },
47 },
48 config,
49 stateDir,
50 token,
51 close: () => NodeFSP.rm(rootDir, { recursive: true, force: true }),
52 };
54​
55/** Leases a device for `pose` and installs the dev client, retrying once on a pool hiccup. */
56export async function leaseAndInstall(
57 pose: Pose,
58 pool: Pool,
59 runId: string,
60 log: (message: string) => void,
61): Promise<Device> {
62 for (let attempt = 1; ; attempt++) {
63 let device: Device | null = null;
64 try {
65 log(`leasing ${pose.device}`);
66 device = await Device.lease(pose, pool, attempt === 1 ? runId : `${runId}-retry`);
67 log("installing the dev client");
68 await device.install();
69 return device;
70 } catch (error) {
71 const message = error instanceof Error ? error.message : String(error);
72 await device?.release();
73 if (attempt >= 2 || !poolError(message)) throw error;
74 log(`retrying after: ${message.split("\n")[0]}`);
75 }
76 }
78​
79/** Keeps a lease alive while cases run: they go minutes without an agent-device call. */
80export function renewWhileRunning(access: PoolAccess, session: string) {
81 const gateway = access.pool.agentDeviceUrl.replace(/\/v1\/agent-device\/?$/, "");
82 const timer = setInterval(() => {
83 const record = NodePath.join(access.stateDir, "remote-connections", `${session}.json`);
84 void NodeFSP.readFile(record, "utf8")
85 .then((text) => (JSON.parse(text) as { leaseId: string }).leaseId)
86 .then((leaseId) =>
87 fetch(`${gateway}/v1/leases/${encodeURIComponent(leaseId)}/renew`, {
88 method: "POST",
89 headers: { authorization: `Bearer ${access.token}` },
90 }),
91 )
92 .catch(() => undefined);
93 }, 90_000);
94 return () => clearInterval(timer);
96​
97/**
98 * Releases the lease if the process dies on an uncaught error, which skips every finalizer; a
99 * leaked lease holds the device until the pool's TTL. Returns the function that unregisters it.
100 */
101export function releaseOnCrash(device: Device, access: PoolAccess) {
102 const crash = (error: unknown) => {
103 NodeProcess.stderr.write(`Crashed (${String(error)}); releasing ${device.session}.\n`);
104 void device
105 .release()
106 .catch(() => undefined)
107 .then(() => access.close())
108 .finally(() => NodeProcess.exit(1));
109 };
110 process.on("uncaughtException", crash);
111 process.on("unhandledRejection", crash);
112 return () => {
113 process.off("uncaughtException", crash);
114 process.off("unhandledRejection", crash);
115 };