Repository navigation
Expand file tree
/
Copy pathperf.ts
More file actions
330 lines (303 loc) · 11.1 KB
/
Copy pathperf.ts
File metadata and controls
330 lines (303 loc) · 11.1 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
320
321
322
323
324
325
326
327
328
329
330
import path from 'node:path';
import type { DeviceInfo } from '@agent-device/kernel/device';
import { AppError } from '@agent-device/kernel/errors';
import { requireExecSuccess } from '@agent-device/host-kit/command';
import {
androidAdbResultError,
resolveAndroidAdbExecutor,
runAdbShell,
type AndroidAdbExecutor,
} from './adb-executor.ts';
import { parseNumericToken } from './perf-parsing.ts';
import { requireAndroidAdbHost, type AndroidAdbFileHost } from './adb-host.ts';
const ANDROID_MEMORY_SAMPLE_METHOD = 'adb-shell-dumpsys-meminfo';
const ANDROID_HPROF_SNAPSHOT_METHOD = 'adb-shell-am-dumpheap';
const ANDROID_PERF_TIMEOUT_MS = 15_000;
const ANDROID_HEAP_DUMP_TIMEOUT_MS = 120_000;
const ANDROID_REMOTE_HEAP_DIR = '/data/local/tmp';
const ANDROID_MEMORY_TOP_CONSUMER_LIMIT = 5;
export type AndroidPerfOptions = {
adb?: AndroidAdbExecutor;
files?: Pick<AndroidAdbFileHost, 'ensureDirectory' | 'remove' | 'stat'>;
};
export type AndroidMemoryPerfSample = {
totalPssKb: number;
totalRssKb?: number;
measuredAt: string;
method: typeof ANDROID_MEMORY_SAMPLE_METHOD;
topConsumers?: AndroidMemoryConsumer[];
};
export type AndroidMemoryConsumer = {
name: string;
pssKb: number;
};
export type AndroidHeapSnapshotResult = {
available: true;
kind: 'android-hprof';
path: string;
sizeBytes: number;
measuredAt: string;
method: typeof ANDROID_HPROF_SNAPSHOT_METHOD;
packageName: string;
pid: number;
remotePath: string;
};
export async function sampleAndroidMemoryPerf(
device: DeviceInfo,
packageName: string,
options: AndroidPerfOptions = {},
): Promise<AndroidMemoryPerfSample> {
const adb = resolveAndroidAdbExecutor(device, options.adb);
try {
const result = await runAdbShell(adb, ['dumpsys', 'meminfo', packageName], {
timeoutMs: ANDROID_PERF_TIMEOUT_MS,
});
return parseAndroidMemInfoSample(result.stdout, packageName, new Date().toISOString());
} catch (error) {
throw annotateAndroidPerfSamplingError('memory', packageName, error);
}
}
export async function captureAndroidHeapSnapshot(
device: DeviceInfo,
packageName: string,
outPath: string,
options: AndroidPerfOptions = {},
): Promise<AndroidHeapSnapshotResult> {
const adb = resolveAndroidAdbExecutor(device, options.adb);
const files = options.files ?? requireAndroidAdbHost().files;
const pid = await resolveAndroidAppPid(adb, packageName);
const remotePath = buildAndroidRemoteHeapPath(packageName);
await files.ensureDirectory(path.dirname(outPath));
const hadLocalArtifact = await fileExists(files, outPath);
try {
requireExecSuccess(
await runAdbShell(adb, ['am', 'dumpheap', packageName, remotePath], {
allowFailure: true,
timeoutMs: ANDROID_HEAP_DUMP_TIMEOUT_MS,
}),
`Failed to capture Android heap dump for ${packageName}`,
(dumpResult) => ({
kind: 'android-hprof',
package: packageName,
pid,
remotePath,
hint: resolveAndroidHeapDumpHint(dumpResult.stdout, dumpResult.stderr),
}),
);
const pullResult = await adb(['pull', remotePath, outPath], {
allowFailure: true,
timeoutMs: ANDROID_HEAP_DUMP_TIMEOUT_MS,
});
if (pullResult.exitCode !== 0) {
await cleanupLocalArtifact(files, outPath, hadLocalArtifact);
// The site hint wins over the classified one (attachAdbFailureHint never
// overwrites), but the classifier still tags adbFailure/retriable.
// fallow-ignore-next-line code-duplication
throw androidAdbResultError(
`Failed to pull Android heap dump for ${packageName}`,
pullResult,
{
kind: 'android-hprof',
package: packageName,
pid,
remotePath,
path: outPath,
hint: 'Verify the daemon can write the requested --out path and retry. The heap dump stays on-device only until cleanup runs.',
},
);
}
// fallow-ignore-next-line code-duplication
const artifactStat = await files.stat(outPath).catch(() => null);
if (!artifactStat?.isFile || artifactStat.size <= 0) {
await cleanupLocalArtifact(files, outPath, hadLocalArtifact);
throw new AppError('COMMAND_FAILED', `Android heap dump artifact is missing or empty`, {
kind: 'android-hprof',
package: packageName,
pid,
path: outPath,
remotePath,
hint: 'Retry with a writable --out path. If the file is still empty, inspect adb pull output with --debug.',
});
}
return {
available: true,
kind: 'android-hprof',
path: outPath,
sizeBytes: artifactStat.size,
measuredAt: new Date().toISOString(),
method: ANDROID_HPROF_SNAPSHOT_METHOD,
packageName,
pid,
remotePath,
};
} finally {
await runAdbShell(adb, ['rm', '-f', remotePath], {
allowFailure: true,
timeoutMs: ANDROID_PERF_TIMEOUT_MS,
}).catch(() => {});
}
}
async function fileExists(
files: Pick<AndroidAdbFileHost, 'stat'>,
filePath: string,
): Promise<boolean> {
return await files
.stat(filePath)
.then((stat) => stat.isFile)
.catch(() => false);
}
async function cleanupLocalArtifact(
files: Pick<AndroidAdbFileHost, 'remove'>,
filePath: string,
existedBefore: boolean,
): Promise<void> {
if (existedBefore) return;
await files.remove(filePath, { force: true }).catch(() => {});
}
export function parseAndroidMemInfoSample(
stdout: string,
packageName: string,
measuredAt: string,
): AndroidMemoryPerfSample {
if (/no process found for:/i.test(stdout)) {
throw new AppError(
'COMMAND_FAILED',
`Android meminfo did not find a running process for ${packageName}`,
{
metric: 'memory',
package: packageName,
hint: 'Run open <app> for this session again to ensure the Android app is active, then retry perf.',
},
);
}
const totalPssKb = matchLabeledNumber(stdout, 'TOTAL PSS') ?? matchTotalRowPss(stdout);
if (totalPssKb === undefined) {
throw new AppError(
'COMMAND_FAILED',
`Failed to parse Android meminfo output for ${packageName}`,
{
metric: 'memory',
package: packageName,
hint: 'Retry perf after reopening the app session. If the problem persists, capture adb shell dumpsys meminfo output for debugging.',
},
);
}
return {
totalPssKb,
totalRssKb: matchLabeledNumber(stdout, 'TOTAL RSS'),
measuredAt,
method: ANDROID_MEMORY_SAMPLE_METHOD,
topConsumers: parseAndroidMemInfoTopConsumers(stdout),
};
}
async function resolveAndroidAppPid(adb: AndroidAdbExecutor, packageName: string): Promise<number> {
const result = await runAdbShell(adb, ['pidof', packageName], {
allowFailure: true,
timeoutMs: ANDROID_PERF_TIMEOUT_MS,
});
const pid = result.stdout
.trim()
.split(/\s+/)
.map(Number)
.find((value) => Number.isInteger(value) && value > 0);
if (result.exitCode === 0 && pid !== undefined) return pid;
throw new AppError('COMMAND_FAILED', `No running Android process found for ${packageName}`, {
kind: 'android-hprof',
package: packageName,
stdout: result.stdout,
stderr: result.stderr,
hint: 'Run open <app> for this session again to ensure the Android app is active, then retry perf memory snapshot.',
});
}
function buildAndroidRemoteHeapPath(packageName: string): string {
const safePackage = packageName.replaceAll(/[^a-zA-Z0-9._-]/g, '_');
return `${ANDROID_REMOTE_HEAP_DIR}/agent-device-${safePackage}-${Date.now()}.hprof`;
}
function resolveAndroidHeapDumpHint(stdout: string, stderr: string): string {
const text = `${stdout}\n${stderr}`.toLowerCase();
if (text.includes('profileable') || text.includes('debuggable') || text.includes('not allowed')) {
return 'Android heap dumps require a debuggable/profileable app process on many devices. Use a debug/profileable build, reopen the app, then retry.';
}
if (text.includes('permission') || text.includes('denied')) {
return 'The device denied heap dump access. Use a debug/profileable build or a device image that permits app heap dumping.';
}
return 'Reopen the app to refresh the process, then retry perf memory snapshot. If it still fails, rerun it with --json and read the adb am dumpheap output in error.details.stderr.';
}
function parseAndroidMemInfoTopConsumers(stdout: string): AndroidMemoryConsumer[] | undefined {
const consumers = stdout.split('\n').flatMap((line) => readAndroidMemInfoConsumer(line) ?? []);
const topConsumers = consumers
.sort((left, right) => right.pssKb - left.pssKb)
.slice(0, ANDROID_MEMORY_TOP_CONSUMER_LIMIT);
return topConsumers.length > 0 ? topConsumers : undefined;
}
function readAndroidMemInfoConsumer(rawLine: string): AndroidMemoryConsumer | undefined {
const line = rawLine.trim();
if (shouldSkipAndroidMemInfoConsumerLine(line)) return undefined;
const match = line.match(/^(.+?)\s+([0-9][0-9,]*(?:\(\d+\))?)(?:\s|$)/);
if (!match) return undefined;
return buildAndroidMemInfoConsumer(match[1], match[2]);
}
function shouldSkipAndroidMemInfoConsumerLine(line: string): boolean {
if (!line || line.startsWith('**') || line.startsWith('-') || line.includes(':')) return true;
const looksLikeDataRow = /^\S.+\s+\d/.test(line);
const isHeaderRow = /^(pss|total|native|dalvik|unknown|app summary\b)/i.test(line);
return isHeaderRow && !looksLikeDataRow;
}
function buildAndroidMemInfoConsumer(
rawName: string | undefined,
rawPssKb: string | undefined,
): AndroidMemoryConsumer | undefined {
const name = rawName?.trim();
const pssKb = rawPssKb ? parseNumericToken(rawPssKb) : null;
if (!name || name === 'TOTAL' || pssKb === null || pssKb <= 0) return undefined;
if (/^(pss|private|shared|heap|size|alloc|free)$/i.test(name)) return undefined;
return { name, pssKb };
}
function annotateAndroidPerfSamplingError(
metric: 'memory',
packageName: string,
error: unknown,
): AppError {
if (error instanceof AppError) {
return new AppError(
error.code,
error.message,
{
...(error.details ?? {}),
metric,
package: packageName,
},
error,
);
}
return new AppError(
'COMMAND_FAILED',
`Failed to sample Android ${metric} for ${packageName}`,
{
metric,
package: packageName,
},
error,
);
}
function matchLabeledNumber(text: string, label: string): number | undefined {
const escapedLabel = label.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`);
const match = text.match(new RegExp(`${escapedLabel}:\\s*([0-9][0-9,]*)`, 'i'));
if (!match) return undefined;
const token = match[1];
return token === undefined ? undefined : (parseNumericToken(token) ?? undefined);
}
function matchTotalRowPss(text: string): number | undefined {
for (const rawLine of text.split('\n')) {
const line = rawLine.trim();
// Skip the "TOTAL PSS:" summary line and only match the tabular TOTAL row.
if (!/^TOTAL\b(?!\s+PSS:)/.test(line)) continue;
const firstValue = line
.split(/\s+/)
.slice(1)
.find((token) => parseNumericToken(token) !== null);
if (!firstValue) return undefined;
return parseNumericToken(firstValue) ?? undefined;
}
return undefined;
}