-
Notifications
You must be signed in to change notification settings - Fork 123
Expand file tree
/
Copy pathdevices.ts
More file actions
163 lines (152 loc) · 5.21 KB
/
devices.ts
File metadata and controls
163 lines (152 loc) · 5.21 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
import { runCmd, whichCmd } from '../../utils/exec.ts';
import type { ExecResult } from '../../utils/exec.ts';
import { AppError, asAppError } from '../../utils/errors.ts';
import type { DeviceInfo } from '../../utils/device.ts';
import { Deadline, retryWithPolicy } from '../../utils/retry.ts';
import { classifyBootFailure } from '../boot-diagnostics.ts';
const EMULATOR_SERIAL_PREFIX = 'emulator-';
const ANDROID_BOOT_POLL_MS = 1000;
function adbArgs(serial: string, args: string[]): string[] {
return ['-s', serial, ...args];
}
function isEmulatorSerial(serial: string): boolean {
return serial.startsWith(EMULATOR_SERIAL_PREFIX);
}
async function readAndroidBootProp(serial: string): Promise<ExecResult> {
return runCmd('adb', adbArgs(serial, ['shell', 'getprop', 'sys.boot_completed']), {
allowFailure: true,
});
}
async function resolveAndroidDeviceName(serial: string, rawModel: string): Promise<string> {
const modelName = rawModel.replace(/_/g, ' ').trim();
if (!isEmulatorSerial(serial)) return modelName || serial;
const avd = await runCmd('adb', adbArgs(serial, ['emu', 'avd', 'name']), {
allowFailure: true,
});
const avdName = avd.stdout.trim();
if (avd.exitCode === 0 && avdName) {
return avdName.replace(/_/g, ' ');
}
return modelName || serial;
}
export async function listAndroidDevices(): Promise<DeviceInfo[]> {
const adbAvailable = await whichCmd('adb');
if (!adbAvailable) {
throw new AppError('TOOL_MISSING', 'adb not found in PATH');
}
const result = await runCmd('adb', ['devices', '-l']);
const lines = result.stdout.split('\n').map((l: string) => l.trim());
const entries = lines
.filter((line) => line.length > 0 && !line.startsWith('List of devices'))
.map((line) => line.split(/\s+/))
.filter((parts) => parts[1] === 'device')
.map((parts) => ({
serial: parts[0],
rawModel: (parts.find((p: string) => p.startsWith('model:')) ?? '').replace('model:', ''),
}));
const devices = await Promise.all(entries.map(async ({ serial, rawModel }) => {
const [name, booted] = await Promise.all([
resolveAndroidDeviceName(serial, rawModel),
isAndroidBooted(serial),
]);
return {
platform: 'android',
id: serial,
name,
kind: isEmulatorSerial(serial) ? 'emulator' : 'device',
booted,
} satisfies DeviceInfo;
}));
return devices;
}
export async function isAndroidBooted(serial: string): Promise<boolean> {
try {
const result = await readAndroidBootProp(serial);
return result.stdout.trim() === '1';
} catch {
return false;
}
}
export async function waitForAndroidBoot(serial: string, timeoutMs = 60000): Promise<void> {
const deadline = Deadline.fromTimeoutMs(timeoutMs);
const maxAttempts = Math.max(1, Math.ceil(timeoutMs / ANDROID_BOOT_POLL_MS));
let lastBootResult: ExecResult | undefined;
let timedOut = false;
try {
await retryWithPolicy(
async ({ deadline: attemptDeadline }) => {
if (attemptDeadline?.isExpired()) {
timedOut = true;
throw new AppError('COMMAND_FAILED', 'Android boot deadline exceeded', {
serial,
timeoutMs,
elapsedMs: deadline.elapsedMs(),
message: 'timeout',
});
}
const result = await readAndroidBootProp(serial);
lastBootResult = result;
if (result.stdout.trim() === '1') return;
throw new AppError('COMMAND_FAILED', 'Android device is still booting', {
serial,
stdout: result.stdout,
stderr: result.stderr,
exitCode: result.exitCode,
});
},
{
maxAttempts,
baseDelayMs: ANDROID_BOOT_POLL_MS,
maxDelayMs: ANDROID_BOOT_POLL_MS,
jitter: 0,
shouldRetry: (error) => {
const reason = classifyBootFailure({
error,
stdout: lastBootResult?.stdout,
stderr: lastBootResult?.stderr,
});
return reason !== 'PERMISSION_DENIED' && reason !== 'TOOL_MISSING' && reason !== 'BOOT_TIMEOUT';
},
},
{ deadline },
);
} catch (error) {
const appErr = asAppError(error);
const stdout = lastBootResult?.stdout;
const stderr = lastBootResult?.stderr;
const exitCode = lastBootResult?.exitCode;
const reason = classifyBootFailure({
error,
stdout,
stderr,
});
const baseDetails = {
serial,
timeoutMs,
elapsedMs: deadline.elapsedMs(),
reason,
stdout,
stderr,
exitCode,
};
if (timedOut || reason === 'BOOT_TIMEOUT') {
throw new AppError('COMMAND_FAILED', 'Android device did not finish booting in time', baseDetails);
}
if (appErr.code === 'TOOL_MISSING' || reason === 'TOOL_MISSING') {
throw new AppError('TOOL_MISSING', appErr.message, {
...baseDetails,
...(appErr.details ?? {}),
});
}
if (reason === 'PERMISSION_DENIED' || reason === 'DEVICE_UNAVAILABLE' || reason === 'DEVICE_OFFLINE') {
throw new AppError('COMMAND_FAILED', appErr.message, {
...baseDetails,
...(appErr.details ?? {}),
});
}
throw new AppError(appErr.code, appErr.message, {
...baseDetails,
...(appErr.details ?? {}),
}, appErr.cause);
}
}