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

SimlockDeviceHost.ts

545 lines19.6 KB

1/**
2 * Alpha: devices leased from a Simlock gateway the user runs. Opening a device
3 * takes a lease through the gateway's agent-device front, so agents drive it
4 * with the same session; closing it returns the device to the pool, wiped.
5 * A lease left by a server that crashed ends one TTL after its last renewal.
6 */
7import {
8 DeviceBootError,
9 type DeviceHostSummary,
10 DeviceHostUnavailableError,
11 DeviceOperationError,
12 type DevicePlatform,
13 type SimlockDeviceHostConfig,
14} from "@t3tools/contracts";
15import * as Clock from "effect/Clock";
16import * as Duration from "effect/Duration";
17import * as Effect from "effect/Effect";
18import * as FiberMap from "effect/FiberMap";
19import * as FileSystem from "effect/FileSystem";
20import * as Option from "effect/Option";
21import * as Path from "effect/Path";
22import * as Random from "effect/Random";
23import * as Schema from "effect/Schema";
24import * as Semaphore from "effect/Semaphore";
25import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
26import * as HostProcess from "@t3tools/shared/HostProcess";
27import type { NodeRuntimeUnavailableError } from "@t3tools/shared/nodeRuntime";
28​
29import * as ServerConfig from "../config.ts";
30import * as ProcessRunner from "../processRunner.ts";
31import { writeAgentDeviceConfig } from "./AgentDeviceTarget.ts";
32import * as DeviceHost from "./DeviceHost.ts";
33​
34const CATALOG_TTL_MS = 60_000;
35const REQUEST_TIMEOUT = Duration.seconds(15);
36// The gateway queues a lease request for up to five minutes when every device is busy.
37const OPEN_TIMEOUT = Duration.minutes(7);
38const COMMAND_TIMEOUT = Duration.minutes(2);
39// Renewal keeps a watched but idle device; a lease this server stops renewing ends after LEASE_TTL.
40const RENEW_INTERVAL = Duration.minutes(2);
41const LEASE_TTL_MS = 10 * 60_000;
42const STREAM_PATH = /^\/vendor\/serve-sim\/helper\/([^/]+)\/stream\.avcc$/;
43const INPUT_PATH = "/vendor/serve-sim/helper/ws";
44​
45const Catalog = Schema.Struct({
46 platforms: Schema.Array(
47 Schema.Struct({
48 platform: Schema.String,
49 modelRuntimes: Schema.Record(Schema.String, Schema.Array(Schema.String)),
50 modelClasses: Schema.optional(Schema.Record(Schema.String, Schema.String)),
51 modelWorkers: Schema.optional(Schema.Record(Schema.String, Schema.Array(Schema.String))),
52 }),
53 ),
54});
55const decodeCatalog = Schema.decodeUnknownEffect(Catalog);
56const decodeSessionRecord = Schema.decodeUnknownEffect(
57 Schema.fromJsonString(Schema.Struct({ leaseId: Schema.String })),
58);
59const decodeCliFailure = Schema.decodeUnknownOption(
60 Schema.fromJsonString(
61 Schema.Struct({
62 error: Schema.Struct({ message: Schema.String, hint: Schema.optional(Schema.String) }),
63 }),
64 ),
65);
66​
67interface Lease {
68 readonly leaseId: string;
69 readonly platform: DevicePlatform;
70 readonly name: string;
71 readonly version: string;
72 readonly session: string;
73 readonly dir: string;
74 readonly configPath: string;
75 readonly installDirectory: string;
77​
78const catalogId = (platform: DevicePlatform, model: string) => `simlock:${platform}:${model}`;
79const parseCatalogId = (id: string) => {
80 const match = /^simlock:(ios|android):(.+)$/.exec(id);
81 return match ? { platform: match[1] as DevicePlatform, model: match[2]! } : null;
82};
83const platformVersion = (platform: DevicePlatform, runtime: string | undefined) =>
84 `${platform === "ios" ? "iOS" : "Android"}${runtime ? ` ${runtime}` : ""}`;
85​
86/** T3's own agent-device CLI, installed on first use. */
87export type AgentDeviceCli = Effect.Effect<
88 { readonly nodePath: string; readonly entryPath: string },
89 DeviceHost.DeviceHostError | NodeRuntimeUnavailableError
90>;
91​
92export const make = Effect.fn("SimlockDeviceHost.make")(function* (
93 config: SimlockDeviceHostConfig,
94 agentDeviceCli: AgentDeviceCli,
95) {
96 const http = yield* HttpClient.HttpClient;
97 const fs = yield* FileSystem.FileSystem;
98 const path = yield* Path.Path;
99 const runner = yield* ProcessRunner.ProcessRunner;
100 const server = yield* ServerConfig.ServerConfig;
101 const services = yield* Effect.context<FileSystem.FileSystem | Path.Path>();
102 const environment = yield* HostProcess.Environment;
103 const hostId = config.id;
104 const gateway = config.gatewayUrl.replace(/\/$/, "");
105 const agentDeviceUrl = `${gateway}/v1/agent-device`;
106 const hostDir = path.join(server.stateDir, "device", "simlock", hostId);
107 const leases = new Map<string, Lease>();
108 let starting = 0;
109 // Bumped by every stop, so an open that finishes after one returns its lease instead of keeping it.
110 let stops = 0;
111 const slotLock = yield* Semaphore.make(1);
112 const keepAlive = yield* FiberMap.make<string>();
113 let catalog: {
114 readonly at: number;
115 readonly devices: ReadonlyArray<DeviceHost.HostDevice>;
116 } | null = null;
117 let ready: DeviceHost.DeviceHostReady | null = null;
118 let cli: { readonly nodePath: string; readonly entryPath: string } | null = null;
119​
120 const unavailable = (reason: string, cause?: unknown) =>
121 new DeviceHostUnavailableError({
122 hostId,
123 hostLabel: config.label,
124 reason,
125 ...(cause === undefined ? {} : { cause }),
126 });
127​
128 const request = (
129 method: "GET" | "POST" | "DELETE",
130 route: string,
131 body?: Readonly<Record<string, unknown>>,
132 ) =>
133 http
134 .execute(
135 (method === "GET"
136 ? HttpClientRequest.get(`${gateway}${route}`)
137 : method === "POST"
138 ? HttpClientRequest.post(`${gateway}${route}`).pipe(
139 HttpClientRequest.bodyJsonUnsafe(body ?? {}),
140 )
141 : HttpClientRequest.delete(`${gateway}${route}`)
142 ).pipe(HttpClientRequest.bearerToken(config.agentToken)),
143 )
144 .pipe(
145 Effect.flatMap(HttpClientResponse.filterStatusOk),
146 Effect.flatMap((response) => response.json),
147 Effect.scoped,
148 Effect.timeout(REQUEST_TIMEOUT),
149 );
150​
151 const agentEnvironment: NodeJS.ProcessEnv = Object.fromEntries(
152 Object.entries({
153 ...environment,
154 ELECTRON_RUN_AS_NODE: "1",
155 AGENT_DEVICE_NO_UPDATE_NOTIFIER: "1",
156 NO_COLOR: "1",
157 FORCE_COLOR: "0",
158 }).filter(
159 ([name]) =>
160 !/^AGENT_DEVICE_(DAEMON_BASE_URL|DAEMON_AUTH_TOKEN|CONFIG|STATE_DIR|SESSION)$/.test(name),
161 ),
162 );
163​
164 /** Runs T3's own agent-device CLI against the lease's session; its failure message is the reason. */
165 const agentDevice = Effect.fn("SimlockDeviceHost.agentDevice")(function* (
166 lease: Pick<Lease, "session" | "configPath">,
167 args: ReadonlyArray<string>,
168 options: { readonly cwd?: string; readonly timeout?: Duration.Input } = {},
169 ) {
170 if (!cli) return yield* unavailable(`${config.label} is not ready.`);
171 const result = yield* runner
172 .run({
173 command: cli.nodePath,
174 args: [
175 cli.entryPath,
176 ...args,
177 "--session",
178 lease.session,
179 "--config",
180 lease.configPath,
181 "--json",
182 ],
183 env: agentEnvironment,
184 ...(options.cwd ? { cwd: options.cwd } : {}),
185 timeout: options.timeout ?? COMMAND_TIMEOUT,
186 })
187 .pipe(Effect.mapError((cause) => unavailable("agent-device could not run.", cause)));
188 if (result.code !== 0) {
189 const failure = decodeCliFailure(result.stdout);
190 return yield* unavailable(
191 Option.match(failure, {
192 onNone: () => `agent-device ${args[0]} failed (exit code ${result.code ?? "none"}).`,
193 onSome: ({ error }) => (error.hint ? `${error.message} ${error.hint}` : error.message),
194 }),
195 );
196 }
197 return result.stdout;
198 });
199​
200 const loadCatalog = Effect.gen(function* () {
201 const now = yield* Clock.currentTimeMillis;
202 if (catalog && now - catalog.at < CATALOG_TTL_MS) return catalog.devices;
203 if (!config.agentToken) {
204 return yield* unavailable(`Add an agent token for ${config.label} in Settings.`);
205 }
206 const decoded = yield* request("GET", "/v1/catalog").pipe(
207 Effect.flatMap(decodeCatalog),
208 Effect.mapError((cause) =>
209 unavailable(
210 `Could not reach the Simlock gateway at ${gateway}, or it refused the agent token.`,
211 cause,
212 ),
213 ),
214 );
215 const devices = decoded.platforms.flatMap((entry) => {
216 if (entry.platform !== "ios" && entry.platform !== "android") return [];
217 const platform: DevicePlatform = entry.platform;
218 return Object.entries(entry.modelRuntimes).flatMap(([model, runtimes]) => {
219 const kind = entry.modelClasses?.[model];
220 const workers = entry.modelWorkers?.[model];
221 if (runtimes.length === 0 || (workers !== undefined && workers.length === 0)) return [];
222 if (kind !== undefined && kind !== "phone" && kind !== "tablet") return [];
223 return [
224 {
225 id: catalogId(platform, model),
226 platform,
227 name: model,
228 version: platformVersion(platform, runtimes.at(-1)),
229 booted: false,
230 physical: false,
231 } satisfies DeviceHost.HostDevice,
232 ];
233 });
234 });
235 catalog = { at: now, devices };
236 return devices;
237 });
238​
239 const forget = (lease: Lease) =>
240 Effect.suspend(() => {
241 leases.delete(lease.leaseId);
242 return fs.remove(lease.dir, { recursive: true, force: true }).pipe(Effect.ignore);
243 });
244​
245 /** Ends the lease through its session, or over HTTP when the session is gone. */
246 const release = Effect.fn("SimlockDeviceHost.release")(function* (lease: Lease) {
247 yield* agentDevice(lease, ["close"]).pipe(
248 Effect.catch(() => request("DELETE", `/v1/leases/${encodeURIComponent(lease.leaseId)}`)),
249 Effect.tapError((cause) =>
250 Effect.logWarning("Could not release Simlock lease", { leaseId: lease.leaseId, cause }),
251 ),
252 Effect.ignore,
253 );
254 yield* forget(lease);
255 });
256​
257 /** Renews until the lease ends on its own or reaches its maximum age, then releases it. */
258 const renewLoop = Effect.fn("SimlockDeviceHost.renewLoop")(function* (lease: Lease) {
259 const deadline =
260 (yield* Clock.currentTimeMillis) +
261 Duration.toMillis(Duration.minutes(config.maxLeaseMinutes));
262 while (true) {
263 const left = deadline - (yield* Clock.currentTimeMillis);
264 yield* Effect.sleep(Duration.millis(Math.min(left, Duration.toMillis(RENEW_INTERVAL))));
265 if ((yield* Clock.currentTimeMillis) >= deadline) break;
266 const renewed = yield* request(
267 "POST",
268 `/v1/leases/${encodeURIComponent(lease.leaseId)}/renew`,
269 { ttlMs: LEASE_TTL_MS },
270 ).pipe(Effect.result);
271 if (renewed._tag === "Success") continue;
272 const error = renewed.failure;
273 // Simlock ended it (lease_lost, an agent's close, or its TTL): stop listing it.
274 if (
275 error._tag === "HttpClientError" &&
276 error.reason._tag === "StatusCodeError" &&
277 error.reason.response.status === 404
278 ) {
279 return yield* forget(lease);
280 }
281 yield* Effect.logWarning("Could not renew Simlock lease", { leaseId: lease.leaseId, error });
282 }
283 yield* Effect.logInfo("Releasing Simlock lease at its maximum age", {
284 leaseId: lease.leaseId,
285 });
286 yield* release(lease);
287 });
288​
289 const reserveSlot = slotLock.withPermit(
290 Effect.suspend(() => {
291 if (leases.size + starting >= config.maxLeases) {
292 return Effect.fail(
293 unavailable(
294 `${config.label} is limited to ${config.maxLeases} ${config.maxLeases === 1 ? "device" : "devices"} at once. Close one in the Device panel first.`,
295 ),
296 );
297 }
298 starting++;
299 return Effect.void;
300 }),
301 );
302​
303 const openLease = Effect.fn("SimlockDeviceHost.openLease")(function* (
304 device: DeviceHost.HostDevice,
305 context: DeviceHost.DeviceOpenContext | undefined,
306 ) {
307 const target = parseCatalogId(device.id);
308 if (!target) {
309 return yield* new DeviceBootError({
310 hostId,
311 deviceId: device.id,
312 reason: "launch_failed",
313 cause: new Error("This Simlock device is no longer leased. Open it again from the list."),
314 });
315 }
316 const suffix = (yield* Random.nextIntBetween(0, 0xffffff)).toString(16).padStart(6, "0");
317 const session = `t3-${suffix}`;
318 const dir = path.join(hostDir, suffix);
319 const configPath = path.join(dir, "agent-device.json");
320 yield* writeAgentDeviceConfig(configPath, {
321 baseUrl: agentDeviceUrl,
322 token: config.agentToken,
323 stateDir: dir,
324 }).pipe(
325 Effect.provide(services),
326 Effect.mapError((cause) => unavailable("Could not write the agent-device config.", cause)),
327 );
328 // agent-device ties installs to the directory that opened the session.
329 const installDirectory = context?.workspaceRoot
330 ? yield* fs.realPath(context.workspaceRoot).pipe(Effect.orElseSucceed(() => dir))
331 : dir;
332 const pending = { session, configPath };
333 const stopsAtOpen = stops;
334 return yield* Effect.gen(function* () {
335 yield* agentDevice(pending, ["connect", "proxy", "--daemon-base-url", agentDeviceUrl]);
336 yield* agentDevice(
337 pending,
338 ["open", "--platform", target.platform, "--device", target.model],
339 { cwd: installDirectory, timeout: OPEN_TIMEOUT },
340 );
341 const record = yield* fs
342 .readFileString(path.join(dir, "remote-connections", `${session}.json`))
343 .pipe(
344 Effect.flatMap(decodeSessionRecord),
345 Effect.mapError((cause) => unavailable("agent-device recorded no Simlock lease.", cause)),
346 );
347 const opened: Lease = {
348 leaseId: record.leaseId,
349 platform: target.platform,
350 name: target.model,
351 version: device.version,
352 session,
353 dir,
354 configPath,
355 installDirectory,
356 };
357 if (stops !== stopsAtOpen)
358 return yield* unavailable("Device support stopped while the device was opening.");
359 leases.set(opened.leaseId, opened);
360 yield* FiberMap.run(keepAlive, opened.leaseId, renewLoop(opened));
361 return opened.leaseId;
362 }).pipe(
363 // A failed or interrupted open may still hold a lease: close the session either way.
364 Effect.onExit((exit) =>
365 exit._tag === "Success"
366 ? Effect.void
367 : agentDevice(pending, ["close"]).pipe(
368 Effect.ignore,
369 Effect.andThen(fs.remove(dir, { recursive: true, force: true }).pipe(Effect.ignore)),
370 ),
371 ),
372 Effect.mapError((error) =>
373 error._tag === "DeviceHostUnavailableError"
374 ? new DeviceBootError({
375 hostId,
376 deviceId: device.id,
377 reason: "launch_failed",
378 cause: new Error(error.reason),
379 })
380 : error,
381 ),
382 );
383 });
384​
385 const leaseFor = (deviceId: string) => Option.fromNullishOr(leases.get(deviceId));
386 const operationError = (operation: string) => (cause: unknown) =>
387 new DeviceOperationError({ operation, reason: "request_failed", cause });
388​
389 const screenshotLease = Effect.fn("SimlockDeviceHost.screenshot")(
390 function* (lease: Lease) {
391 const file = path.join(
392 lease.dir,
393 `screenshot-${(yield* Random.nextIntBetween(0, 0xffffff)).toString(16)}.png`,
394 );
395 yield* agentDevice(lease, ["screenshot", file]);
396 return yield* fs
397 .readFile(file)
398 .pipe(Effect.ensuring(fs.remove(file, { force: true }).pipe(Effect.ignore)));
399 },
400 Effect.mapError(operationError("screenshot")),
401 );
402​
403 const devices: DeviceHost.DeviceOperations = {
404 list: loadCatalog.pipe(
405 Effect.mapError(operationError("list")),
406 Effect.map((available) => ({
407 devices: [
408 ...available,
409 ...[...leases.values()].map((lease): DeviceHost.HostDevice => ({
410 id: lease.leaseId,
411 platform: lease.platform,
412 name: lease.name,
413 version: lease.version,
414 booted: true,
415 physical: false,
416 })),
417 ],
418 detail: undefined,
419 })),
420 ),
421 boot: (device, context) =>
422 leases.has(device.id)
423 ? Effect.succeed(device.id)
424 : Effect.acquireUseRelease(
425 reserveSlot,
426 () => openLease(device, context),
427 () => Effect.sync(() => void starting--),
428 ),
429 attach: () => Effect.void,
430 shutdown: (device) =>
431 Option.match(leaseFor(device.id), {
432 onNone: () => Effect.void,
433 onSome: (lease) =>
434 FiberMap.remove(keepAlive, lease.leaseId).pipe(Effect.andThen(release(lease))),
435 }),
436 screenshot: (device) =>
437 Option.match(leaseFor(device.id), {
438 onNone: () =>
439 Effect.fail(operationError("screenshot")(new Error("The Simlock lease has ended"))),
440 onSome: screenshotLease,
441 }),
442 agentEndpoint: (deviceId) =>
443 Option.match(leaseFor(deviceId), {
444 onNone: () => Effect.fail(unavailable("This Simlock lease has ended.")),
445 onSome: (lease) =>
446 Effect.succeed({
447 baseUrl: agentDeviceUrl,
448 token: config.agentToken,
449 agentDeviceId: null,
450 session: lease.session,
451 stateDir: lease.dir,
452 installDirectory: lease.installDirectory,
453 }),
454 }),
455 endsDevices: true,
456 };
457​
458 /**
459 * The client speaks serve-sim to every Simlock lease: its AVCC stream and its input
460 * socket map to the lease's own stream and input routes, which take the agent token.
461 */
462 const upstream: NonNullable<DeviceHost.DeviceHostReady["upstream"]> = (hubPath, search) =>
463 Effect.sync(() => {
464 const stream = STREAM_PATH.exec(hubPath);
465 let deviceId: string | null;
466 try {
467 deviceId = stream
468 ? decodeURIComponent(stream[1]!)
469 : hubPath === INPUT_PATH
470 ? search.get("device")
471 : null;
472 } catch {
473 return null;
474 }
475 const lease = deviceId === null ? undefined : leases.get(deviceId);
476 if (!lease) return null;
477 return {
478 url: `${gateway}/v1/leases/${encodeURIComponent(lease.leaseId)}/${stream ? "stream" : "input"}`,
479 headers: { authorization: `Bearer ${config.agentToken}` },
480 protocols: [],
481 };
482 });
483​
484 const ensureReady: DeviceHost.DeviceHost["Service"]["ensureReady"] = Effect.fn(
485 "SimlockDeviceHost.ensureReady",
486 )(function* (onPhase) {
487 if (ready) return ready;
488 // A missing token or unreachable gateway does not stop readiness: listing
489 // and opening devices say what is wrong instead.
490 yield* onPhase("installing");
491 cli = yield* agentDeviceCli;
492 const { nodePath } = cli;
493 ready = {
494 nodePath,
495 hub: { origin: gateway },
496 devices,
497 upstream,
498 // Simlock relays only simctl, adb, and devicectl, and only to a lease's owner.
499 run: () =>
500 Effect.succeed({
501 stdout: "",
502 stderr: "Simlock devices cannot run host commands.",
503 code: 127,
504 }),
505 helpers: { serveSimAxSettings: null, serveSimCli: null },
506 };
507 return ready;
508 });
509​
510 const stopAll = Effect.gen(function* () {
511 stops++;
512 yield* FiberMap.clear(keepAlive);
513 yield* Effect.forEach([...leases.values()], release, { discard: true, concurrency: 4 });
514 }).pipe(Effect.ignore);
515 yield* Effect.addFinalizer(() => stopAll);
516​
517 const platformAvailability = (platform: DevicePlatform) =>
518 Effect.succeed({ platform, available: true });
519​
520 const summary: Effect.Effect<DeviceHostSummary> = Effect.succeed({
521 id: hostId,
522 label: config.label,
523 kind: "simlock" as const,
524 platforms: [
525 { platform: "ios" as const, available: true },
526 { platform: "android" as const, available: true },
527 ],
528 hubInstalled: true,
529 agentDeviceInstalled: true,
530 });
531​
532 return DeviceHost.DeviceHost.of({
533 id: hostId,
534 label: config.label,
535 summary,
536 platformAvailability,
537 ensureReady,
538 ensureAgentReady: Effect.fn("SimlockDeviceHost.ensureAgentReady")(function* (onPhase) {
539 return { ...(yield* ensureReady(onPhase)), agentDevice: null };
540 }),
541 current: Effect.sync(() => ready),
542 stopAgent: Effect.void,
543 stop: stopAll,
544 });
545});