Repository navigation
Expand file tree
/
Copy pathinventory.ts
More file actions
319 lines (299 loc) · 9.99 KB
/
Copy pathinventory.ts
File metadata and controls
319 lines (299 loc) · 9.99 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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
import path from 'node:path';
import type { DeviceInfo } from '@agent-device/kernel/device';
import { deviceShellArgv, shellFragment, type ShellWord } from '@agent-device/kernel/device-shell';
import { AppError, asAppError } from '@agent-device/kernel/errors';
import type {
DeviceInventoryHostFor,
HostCommandResult,
PlatformRequestScope,
} from '@agent-device/contracts/platform-runtime-host';
import type { DeviceInventorySource } from '@agent-device/contracts/platform-module';
import type { DeviceInventoryRequest } from '@agent-device/contracts/device';
import { androidDiscoveryCommandError, attachAndroidDiscoveryTimeout } from './adb-failure.ts';
import type { AndroidInventoryConfig } from './inventory-config.ts';
import {
inferAndroidAvdTarget,
isAndroidEmulatorSerial,
normalizeAndroidDeviceName,
parseAndroidAvdList,
parseAndroidDeviceDescription,
parseAndroidDeviceEntries,
parseAndroidEmulatorAvdNameOutput,
parseAndroidFeatureListForTv,
parseAndroidTargetFromCharacteristics,
type AndroidDeviceEntry,
} from './inventory-parsers.ts';
const PROBE_TIMEOUT_MS = 10_000;
const DEVICE_DESCRIPTION_TIMEOUT_MS = 2_000;
const DEVICE_DESCRIPTION_PROBE = shellFragment(
'getprop ro.product.model; getprop ro.build.version.release',
);
const TV_FEATURES = [
'android.software.leanback',
'android.software.leanback_only',
'android.hardware.type.television',
] as const;
type AndroidInventoryContext = Readonly<{
host: DeviceInventoryHostFor<'android'>;
adb: string;
emulator?: string;
scope: PlatformRequestScope;
}>;
export function createAndroidInventory(
host: DeviceInventoryHostFor<'android'>,
config: AndroidInventoryConfig = { sdkRoots: [] },
): DeviceInventorySource {
return {
discover: async (request, scope) => await discoverAndroidDevices(host, config, request, scope),
};
}
async function discoverAndroidDevices(
host: DeviceInventoryHostFor<'android'>,
config: AndroidInventoryConfig,
request: Readonly<DeviceInventoryRequest>,
scope: PlatformRequestScope,
): Promise<readonly DeviceInfo[]> {
await host.toolchains.prepare('android');
const sdkRoots = [...config.sdkRoots, path.join(host.homeDirectory, 'Android', 'Sdk')];
const adb = await resolveTool(host, 'adb', sdkRoots, ['platform-tools', 'adb']);
if (!adb) throw new AppError('TOOL_MISSING', 'adb not found in PATH');
const emulator = await resolveTool(host, 'emulator', sdkRoots, ['emulator', 'emulator']);
const context: AndroidInventoryContext = {
host,
adb,
emulator,
scope,
};
const allowlist = resolveSerialAllowlist(request);
const entries = (await listDeviceEntries(context)).filter(
(entry) => !allowlist || allowlist.has(entry.serial),
);
const running = await mapWithConcurrency(
entries,
3,
async (entry) => await probeRunningDevice(context, entry),
);
return [
...running,
...(request.androidAvdSelection === 'running-only'
? []
: await listStoppedAvds(context, running)),
];
}
function resolveSerialAllowlist(
request: Readonly<DeviceInventoryRequest>,
): ReadonlySet<string> | undefined {
const selected = request.serial?.trim();
const policy = request.androidSerialAllowlist;
if (!selected) return policy ? new Set(policy) : undefined;
if (!policy) return new Set([selected]);
return new Set(policy.includes(selected) ? [selected] : []);
}
async function resolveTool(
host: DeviceInventoryHostFor<'android'>,
executable: string,
sdkRoots: readonly string[],
relativeSegments: readonly string[],
): Promise<string | undefined> {
for (const sdkRoot of sdkRoots) {
const candidate = path.join(sdkRoot, ...relativeSegments);
if (await host.files.isExecutable(candidate)) return candidate;
}
return await host.commands.which(executable);
}
async function listDeviceEntries(context: AndroidInventoryContext): Promise<AndroidDeviceEntry[]> {
const result = await run(context, context.adb, ['devices', '-l']);
if (result.exitCode !== 0) {
throw androidDiscoveryCommandError(
'Failed to list Android devices',
result,
'Verify adb is running and the device appears in `adb devices`.',
);
}
return parseAndroidDeviceEntries(result.stdout);
}
async function probeRunningDevice(
context: AndroidInventoryContext,
entry: AndroidDeviceEntry,
): Promise<DeviceInfo> {
const [name, booted, target, description] = await Promise.all([
resolveDeviceName(context, entry),
isBooted(context, entry.serial),
resolveTarget(context, entry.serial),
readDeviceDescription(context, entry.serial),
]);
return {
platform: 'android',
id: entry.serial,
name,
kind: isAndroidEmulatorSerial(entry.serial) ? 'emulator' : 'device',
target,
...description,
booted,
};
}
/** Best-effort model and OS version read in one shell call; a failed probe leaves both unset. */
async function readDeviceDescription(
context: AndroidInventoryContext,
serial: string,
): Promise<Pick<DeviceInfo, 'model' | 'osVersion'>> {
try {
const result = await runAdbShell(
context,
serial,
[DEVICE_DESCRIPTION_PROBE],
DEVICE_DESCRIPTION_TIMEOUT_MS,
);
return result.exitCode === 0 ? parseAndroidDeviceDescription(result.stdout) : {};
} catch (error) {
if (context.scope.signal.aborted) throw error;
return {};
}
}
async function resolveDeviceName(
context: AndroidInventoryContext,
entry: AndroidDeviceEntry,
): Promise<string> {
const model = entry.rawModel.replaceAll('_', ' ').trim();
if (!isAndroidEmulatorSerial(entry.serial)) return model || entry.serial;
const avdName = await resolveEmulatorAvdName(context, entry.serial);
return avdName?.replaceAll('_', ' ') || model || entry.serial;
}
async function resolveEmulatorAvdName(
context: AndroidInventoryContext,
serial: string,
): Promise<string | undefined> {
for (const prop of ['ro.boot.qemu.avd_name', 'persist.sys.avd_name']) {
const result = await runBestEffortNameProbe(context, adbShellArgv(serial, ['getprop', prop]));
const value = result?.stdout.trim();
if (result?.exitCode === 0 && value) return value;
}
const result = await runBestEffortNameProbe(context, ['-s', serial, 'emu', 'avd', 'name']);
const value = result && parseAndroidEmulatorAvdNameOutput(result.stdout);
return result?.exitCode === 0 ? value : undefined;
}
async function runBestEffortNameProbe(
context: AndroidInventoryContext,
args: readonly string[],
): Promise<HostCommandResult | undefined> {
try {
return await run(context, context.adb, args);
} catch (error) {
const appError = asAppError(error);
if (appError.code === 'COMMAND_FAILED' && typeof appError.details?.timeoutMs === 'number') {
return undefined;
}
throw error;
}
}
async function isBooted(context: AndroidInventoryContext, serial: string): Promise<boolean> {
try {
return (
(await runAdbShell(context, serial, ['getprop', 'sys.boot_completed'])).stdout.trim() === '1'
);
} catch (error) {
if (context.scope.signal.aborted) throw error;
return false;
}
}
async function resolveTarget(
context: AndroidInventoryContext,
serial: string,
): Promise<'mobile' | 'tv'> {
const characteristics = await runAdbShell(context, serial, [
'getprop',
'ro.build.characteristics',
]);
if (parseAndroidTargetFromCharacteristics(commandOutput(characteristics)) === 'tv') return 'tv';
const featureResults = await mapWithConcurrency(
TV_FEATURES,
2,
async (feature) =>
await runAdbShell(context, serial, ['cmd', 'package', 'has-feature', feature]),
);
if (featureResults.some((result) => commandOutput(result).toLowerCase().includes('true'))) {
return 'tv';
}
const featureList = await runAdbShell(context, serial, ['pm', 'list', 'features']);
return parseAndroidFeatureListForTv(commandOutput(featureList)) ? 'tv' : 'mobile';
}
async function listStoppedAvds(
context: AndroidInventoryContext,
running: readonly DeviceInfo[],
): Promise<DeviceInfo[]> {
if (!context.emulator) return [];
let result: HostCommandResult;
try {
result = await run(context, context.emulator, ['-list-avds']);
} catch (error) {
if (context.scope.signal.aborted) throw error;
return [];
}
if (result.exitCode !== 0) return [];
const runningNames = new Set(
running
.filter((device) => device.kind === 'emulator')
.map((device) => normalizeAndroidDeviceName(device.name)),
);
return parseAndroidAvdList(result.stdout)
.filter((name) => !runningNames.has(normalizeAndroidDeviceName(name)))
.map((name) => ({
platform: 'android',
id: name,
name,
kind: 'emulator',
target: inferAndroidAvdTarget(name),
booted: false,
}));
}
function adbShellArgv(serial: string, words: readonly ShellWord[]): readonly string[] {
return deviceShellArgv('adb', 'shell', words, ['-s', serial]);
}
async function runAdbShell(
context: AndroidInventoryContext,
serial: string,
words: readonly ShellWord[],
timeoutMs = PROBE_TIMEOUT_MS,
): Promise<HostCommandResult> {
return await run(context, context.adb, adbShellArgv(serial, words), timeoutMs);
}
async function run(
context: AndroidInventoryContext,
executable: string,
args: readonly string[],
timeoutMs = PROBE_TIMEOUT_MS,
): Promise<HostCommandResult> {
try {
return await context.host.commands.run(
{
executable,
args,
allowFailure: true,
timeoutMs,
},
context.scope.signal,
);
} catch (error) {
throw attachAndroidDiscoveryTimeout(error);
}
}
function commandOutput(result: HostCommandResult): string {
return `${result.stdout}\n${result.stderr}`;
}
async function mapWithConcurrency<T, R>(
values: readonly T[],
concurrency: number,
mapper: (value: T) => Promise<R>,
): Promise<R[]> {
const results = new Array<R>(values.length);
let next = 0;
await Promise.all(
Array.from({ length: Math.min(concurrency, values.length) }, async () => {
while (next < values.length) {
const index = next++;
results[index] = await mapper(values[index]!);
}
}),
);
return results;
}