Repository navigation
Expand file tree
/
Copy pathsdb.ts
More file actions
201 lines (180 loc) · 7.07 KB
/
Copy pathsdb.ts
File metadata and controls
201 lines (180 loc) · 7.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
import { execFile, spawn } from 'node:child_process';
import net from 'node:net';
import { setTimeout as sleep } from 'node:timers/promises';
import { promisify } from 'node:util';
import { Deadline, pollUntilSettled } from '@agent-device/host-kit/retry';
import { AppError } from '@agent-device/kernel/errors';
import { listTargets, type PageTunnel } from '@agent-device/tv-cdp';
import { toolError, type HostEnv } from './tools.ts';
const run = promisify(execFile);
const SDB_PORT = 26101;
const CONNECT_HINT =
'Check that the TV is on, in Developer Mode with this host IP set, and reachable with sdb connect <ip>.';
// was_kill returns before the app process is gone; a debug launch that races it lands on the
// still-running app and blocks.
const KILL_SETTLE_MS = 2000;
export type SdbDevice = Readonly<{
serial: string;
state: string;
model: string;
}>;
export function parseDevices(output: string): SdbDevice[] {
return output
.split('\n')
.slice(1)
.map((line) => line.trim().split(/\s+/))
.filter(([serial, state]) => serial && state)
.map(([serial, state, model]) => ({ serial: serial!, state: state!, model: model ?? '' }));
}
type TizenApp = Readonly<{ id: string; name: string }>;
// `0 vd_applist` prints one block per user app, each field as `--app_title =Name----`.
export function parseAppList(output: string): TizenApp[] {
const apps: TizenApp[] = [];
let title = '';
for (const line of output.split('\n')) {
const field = line.match(/^-+([a-z_]+)\s*=(.*?)-+\s*$/);
if (!field) continue;
const [, key, raw = ''] = field;
const value = raw.trim();
if (key === 'app_id') title = '';
else if (key === 'app_title') title = value;
else if (key === 'app_tizen_id' && value) apps.push({ id: value, name: title || value });
}
return apps;
}
export const parseDebugPort = (output: string) => {
const port = Number(output.match(/port:\s*(\d+)/)?.[1]);
return port || undefined;
};
/** `192.0.2.10` and `192.0.2.10:26101` name the same TV; anything else is taken as a serial. */
export function sdbSerial(device: string): string {
return /^[\d.]+$/.test(device) ? `${device}:${SDB_PORT}` : device;
}
async function freeLocalPort(): Promise<number> {
const server = net.createServer();
await new Promise<void>((resolve, reject) => {
server.once('error', reject);
server.listen(0, '127.0.0.1', resolve);
});
const { port } = server.address() as net.AddressInfo;
await new Promise((resolve) => server.close(resolve));
return port;
}
export function createSdb(bin: () => string, env: HostEnv) {
const sdb = async (args: string[], timeout = 60_000) => {
try {
return (await run(bin(), args, { env, timeout })).stdout;
} catch (error) {
if (error instanceof AppError) throw error;
throw toolError(`sdb ${args.filter((arg) => arg !== '-s').join(' ')}`, error, CONNECT_HINT);
}
};
const listDevices = async () => parseDevices(await sdb(['devices']));
const forDevice = (serial: string) => {
const shell0 = (...args: string[]) => sdb(['-s', serial, 'shell', '0', ...args]);
// `0 debug` is a launch, not an attach: against a running app it blocks forever with no
// output, so the caller kills the app first and this bounds the wait.
const debugLaunch = (appId: string, timeoutMs: number) =>
new Promise<number>((resolve, reject) => {
const child = spawn(bin(), ['-s', serial, 'shell', '0', 'debug', appId], { env });
let output = '';
let settled = false;
const finish = (settle: () => void) => {
if (settled) return;
settled = true;
clearTimeout(timer);
child.kill();
settle();
};
const timer = setTimeout(
() =>
finish(() =>
reject(
new AppError('COMMAND_FAILED', `${appId} gave no debug port in ${timeoutMs}ms`, {
...(output.trim() ? { output: output.trim() } : {}),
hint: output.trim()
? `Check that ${appId} is installed with a debug-enabled package.`
: `${appId} was probably still running. Close it on the TV and retry.`,
}),
),
),
timeoutMs,
);
const read = (chunk: Buffer) => {
output += chunk;
const port = parseDebugPort(output);
if (port) finish(() => resolve(port));
};
child.stdout.on('data', read);
child.stderr.on('data', read);
child.on('error', (error) => finish(() => reject(toolError('sdb', error, CONNECT_HINT))));
child.on('close', () => {
const port = parseDebugPort(output);
finish(() =>
port
? resolve(port)
: reject(
new AppError('COMMAND_FAILED', `sdb debug ${appId} exited without a port`, {
output: output.trim(),
hint: `Check that ${appId} is installed on the TV.`,
}),
),
);
});
});
// A forward lives in the sdb server, not in a child process, so it ends only when removed; a TV
// that drops off the network shows up as the page socket closing.
async function forward(remotePort: number) {
const localPort = await freeLocalPort();
await sdb(['-s', serial, 'forward', `tcp:${localPort}`, `tcp:${remotePort}`]);
const listeners: (() => void)[] = [];
let open = true;
return {
localPort,
onClose: (listener: () => void) => listeners.push(listener),
close: () => {
if (!open) return;
open = false;
void sdb(['-s', serial, 'forward', '--remove', `tcp:${localPort}`]).catch(() => {});
for (const listener of listeners) listener();
},
};
}
return {
serial,
async kill(appId: string) {
await shell0('was_kill', appId);
},
// A stale forward answers for a dead port, so every launch opens a fresh one.
async launch(appId: string, timeoutMs = 60_000): Promise<PageTunnel> {
await shell0('was_kill', appId).catch(() => {});
await sleep(KILL_SETTLE_MS);
const remotePort = await debugLaunch(appId, timeoutMs);
const tunnel = await forward(remotePort);
const { value: target } = await pollUntilSettled({
deadline: Deadline.fromTimeoutMs(timeoutMs),
intervalMs: 500,
settled: (found) => found !== undefined,
probe: async () => (await listTargets(tunnel.localPort).catch(() => []))[0],
});
if (target) return { target, onClose: tunnel.onClose, close: tunnel.close };
tunnel.close();
throw new AppError(
'COMMAND_FAILED',
`${appId} opened debug port ${remotePort} but showed no page within ${timeoutMs}ms`,
{ hint: `Retry open ${appId}.` },
);
},
async listApps() {
return parseAppList(await shell0('vd_applist'));
},
};
};
return {
listDevices,
async connect(serial: string) {
await sdb(['connect', serial], 30_000);
},
forDevice,
};
}