fix(adb): run adb commands under owned supervision and start the adb server explicitly

The adb version probe and device commands now run through runOwnedCommand
in their own process group, keeping adb's SIGTERM-first stop through the
termination policy. A device command's escaped descendants are swept with
its cleanup, and cleanup that fails stays owned by the provider, which
retries it before its next operation.

Device operations start the adb server with an explicit `adb start-server`
first. The server is an external shared service: REA may start it but never
stops it, so a device command never forks it into its own cleanup.

runOwnedCommand gains a byte-limited stdout collector: output beyond
maxStdoutBytes is an output-limit failure, like an exceeded diagnostic
budget, and the collected bytes are kept exactly for binary protocols such
as screencap. Ownership preparation that cannot start its own helper for
lack of host capacity is reported as the command's host-capacity launch
failure.
This commit is contained in:
morluto committed 2026-11-15 21:55:52 -05:00
1 parent 858ff73880
commit b323fd2f01
27 files changed
+1522 -873

No files matched your search

+9 -4
View File
@@ -7,9 +7,11 @@ manages them and never installs platform tools. Every operation composes a
fixed adb argument vector — caller values occupy positional arguments only
and are quoted when adb forwards them to the device shell.
The adb client may start its local server on first device query; that is adb
client behavior, recorded in the tool result when observed.
`inspect_adb_client` probes only the binary and never contacts the server.
Before a device operation, REA runs `adb start-server`, which starts the local
adb server only when none is running. The server is a shared service that
other tools on the host use: REA may start it but never stops it, and a device
command's cleanup does not reach it. `inspect_adb_client` probes only the
binary and never contacts the server.
## Supply tools
@@ -273,7 +275,10 @@ and during shutdown.
cleanup before later work and during shutdown. Cleanup refuses a replacement
directory. Terminal shutdown stops admission and drains active operations.
- The provider holds no long-lived processes; every invocation is one
bounded adb run. The adb server belongs to the caller.
bounded adb run in its own process group. Cancellation or a deadline asks
adb to stop with SIGTERM, then cleanup stops what remains of that run,
including descendants it left behind. The adb server belongs to the host:
REA may start it with `adb start-server` and never stops it.
## Related capability and follow-up lanes
+12 -2
View File
@@ -1,8 +1,12 @@
import { expect, it } from "vitest";
import { afterAll, expect, it } from "vitest";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import { ArtifactResourceScope } from "../resources/index.js";
import { runAdbCapture } from "./AdbCommand.js";
const resources = new ArtifactResourceScope();
afterAll(() => resources.close());
// Exercise the real subprocess capture and public error projection, substituting
// only the bring-your-own executable. These are not Android-device checks.
it.each([
@@ -54,6 +58,7 @@ it.each([
binary: process.execPath,
pathSource: "environment",
environment: { REA_TEST_PRIVATE: "ambient-value-must-not-be-persisted" },
resources,
},
["-e", testCase.source],
{
@@ -94,7 +99,12 @@ it.each([true, false])(
const result = await runAdbCapture(
volatileOutput ? "read_adb_logcat" : "install_adb_package",
{ device: "device" },
{ binary: process.execPath, pathSource: "environment", environment: {} },
{
binary: process.execPath,
pathSource: "environment",
environment: {},
resources,
},
["-e", 'process.stdout.write("X".repeat(4096))'],
{ timeoutMs: 5_000, maxOutputBytes: 1024, volatileOutput },
undefined,
+178 -167
View File
@@ -1,25 +1,71 @@
import { expect, it, vi } from "vitest";
import {
ExecFileOutputCancelledError,
execFileBytes,
} from "../process/ExecFileOutput.js";
import { afterAll, beforeAll, expect, it } from "vitest";
import { probeAdbPathExistence, runAdbCapture } from "./AdbCommand.js";
import type { AdbCommandHost } from "./AdbProcess.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import { spawnOwnedProviderProcess } from "../process/ProviderProcess.js";
import { prepareProcessOwnershipInspection } from "../process/ProcessOwnershipObservation.js";
import { ArtifactResourceScope } from "../resources/index.js";
import { spawnFailure } from "../../tests/support/process/spawnFailure.js";
vi.mock("../process/ExecFileOutput.js", async (importOriginal) => ({
...(await importOriginal<typeof import("../process/ExecFileOutput.js")>()),
execFileBytes: vi.fn(),
}));
const resources = new ArtifactResourceScope();
beforeAll(() => prepareProcessOwnershipInspection());
afterAll(() => resources.close());
const probe = (signal?: AbortSignal) =>
const selection = {
binary: "/host/adb",
pathSource: "environment",
environment: {},
resources,
} as const;
/** A real owned process standing in for adb, running `script` under Node. */
const scripted = (
script: string,
observe?: (stream: "stdout" | "stderr", text: string) => void,
): AdbCommandHost => ({
...selection,
launcher: async (input) => {
const launched = await spawnOwnedProviderProcess({
...input,
command: process.execPath,
arguments: ["-e", script],
});
if (observe !== undefined)
for (const stream of ["stdout", "stderr"] as const)
launched.process[stream]?.on("data", (chunk: Buffer) =>
observe(stream, chunk.toString("utf8")),
);
return launched;
},
});
/** adb exits on its own with this output and status. */
const exits = (
code: number,
output: { readonly stdout?: string; readonly stderr?: string } = {},
): AdbCommandHost =>
scripted(
`process.stdout.write(${JSON.stringify(output.stdout ?? "")});` +
`process.stderr.write(${JSON.stringify(output.stderr ?? "")});` +
`process.exitCode = ${String(code)};`,
);
/** The host refuses to start adb with this launcher error. */
const refused = (failure: unknown): AdbCommandHost => ({
...selection,
launcher: async () => {
throw failure;
},
});
const probe = (host: AdbCommandHost, signal?: AbortSignal) =>
probeAdbPathExistence(
"push_adb_file",
"device",
"/device/path",
{ binary: "/host/adb", pathSource: "environment", environment: {} },
host,
{
timeoutMs: 100,
timeoutMs: 10_000,
maxOutputBytes: 1024,
},
signal,
@@ -28,22 +74,13 @@ const probe = (signal?: AbortSignal) =>
it("classifies the complete diagnostic before shortening its displayed reason", async () => {
const localPath = `/host/${"directory/".repeat(60)}payload.bin`;
const stderr = `adb: error: cannot create '${localPath}': Permission denied`;
vi.mocked(execFileBytes).mockRejectedValueOnce(
Object.assign(new Error("local destination refused"), {
code: 1,
stdout: "",
stderr,
signal: null,
killed: false,
}),
);
await expect(
runAdbCapture(
"pull_adb_file",
{ device: "device", path: "/remote/file", localPath },
{ binary: "/host/adb", pathSource: "environment", environment: {} },
exits(1, { stderr }),
[],
{ timeoutMs: 100, maxOutputBytes: 2048 },
{ timeoutMs: 10_000, maxOutputBytes: 2048 },
undefined,
),
).resolves.toMatchObject({
@@ -57,16 +94,7 @@ it("classifies the complete diagnostic before shortening its displayed reason",
});
it("recognizes only the completed empty false result as absence", async () => {
vi.mocked(execFileBytes).mockRejectedValueOnce(
Object.assign(new Error("test false"), {
code: 1,
stdout: "",
stderr: "",
signal: null,
killed: false,
}),
);
await expect(probe()).resolves.toEqual({
await expect(probe(exits(1))).resolves.toEqual({
ok: true,
value: {
matches: false,
@@ -84,62 +112,89 @@ it("recognizes only the completed empty false result as absence", async () => {
});
it.each([
{ code: 2 },
{ code: "ENOENT" },
{ signal: "SIGTERM" },
{ collectionFailure: true },
{ stdout: "unexpected" },
{ stderr: " " },
])("keeps nonstandard false completion unknown: %j", async (extra) => {
vi.mocked(execFileBytes).mockRejectedValueOnce(
Object.assign(new Error("probe failed"), {
code: 1,
stdout: "",
stderr: "",
signal: null,
killed: false,
...extra,
}),
);
const result = await probe();
expect(result).toMatchObject({
["exit status 2", exits(2)],
["a refused launch", refused(spawnFailure("ENOENT", "/host/adb"))],
[
"a signal exit",
scripted(
"process.kill(process.pid, 'SIGTERM'); setInterval(() => {}, 1000)",
),
],
["unexpected stdout", exits(1, { stdout: "unexpected" })],
["unrecognized stderr", exits(1, { stderr: " " })],
] as const)(
"keeps nonstandard false completion unknown: %s",
async (_case, host) => {
expect(await probe(host)).toMatchObject({
ok: false,
error: { _tag: "AnalysisProtocolError" },
});
},
);
it("keeps a nonstandard false completion's destination status unknown", async () => {
expect(await probe(exits(2))).toMatchObject({
ok: false,
error: {
_tag: "AnalysisProtocolError",
diagnostics: { destination_existence: "unknown" },
capturedOutput: { exit_code: 2 },
},
});
});
it("preserves a probe stopped at its deadline", async () => {
const result = await probeAdbPathExistence(
"push_adb_file",
"device",
"/device/path",
scripted("setInterval(() => {}, 1000)"),
{ timeoutMs: 100, maxOutputBytes: 1024 },
undefined,
);
expect(result).toMatchObject({
ok: false,
error: { _tag: "AnalysisTimeoutError" },
});
});
it.each([
[{ killed: true }, "AnalysisTimeoutError"],
[{ outputTruncated: true }, "AnalysisResourceConstraintError"],
[true, "live", true],
[undefined, "capture", false],
] as const)(
"preserves a stopped or incomplete probe: %j",
async (extra, tag) => {
vi.mocked(execFileBytes).mockRejectedValueOnce(
Object.assign(new Error("probe failed"), {
code: 1,
stdout: "",
stderr: "",
signal: null,
killed: false,
...extra,
}),
"stops output beyond the capture allowance and names its byte value (volatile output: %s)",
async (volatileOutput, kind, retryable) => {
const result = await runAdbCapture(
"list_adb_devices",
{ device: "device" },
scripted(
"process.stdout.write('x'.repeat(64 * 1024)); setInterval(() => {}, 1000)",
),
["devices"],
{
timeoutMs: 10_000,
maxOutputBytes: 1024,
...(volatileOutput === undefined ? {} : { volatileOutput }),
},
undefined,
);
await expect(probe()).resolves.toMatchObject({
ok: false,
error: { _tag: tag },
if (result.ok) throw new Error("Expected a capture refusal");
expect(result.error).toMatchObject({
_tag: "AnalysisResourceConstraintError",
retryable,
capturedOutput: { stdout: "x".repeat(1024), truncated: true },
});
expect(result.error).toHaveProperty("fixedAllowance", {
name: expect.any(String),
kind,
limit: 1024,
unit: "bytes",
});
},
);
it("recognizes an empty successful probe as existence", async () => {
vi.mocked(execFileBytes).mockResolvedValueOnce({
stdout: Buffer.alloc(0),
stderr: Buffer.alloc(0),
});
await expect(probe()).resolves.toEqual({
await expect(probe(exits(0))).resolves.toEqual({
ok: true,
value: {
matches: true,
@@ -159,12 +214,9 @@ it("recognizes an empty successful probe as existence", async () => {
it.each(["stdout", "stderr"] as const)(
"retains unexpected successful %s as unknown",
async (stream) => {
vi.mocked(execFileBytes).mockResolvedValueOnce({
stdout: Buffer.alloc(0),
stderr: Buffer.alloc(0),
[stream]: Buffer.from("unexpected"),
});
await expect(probe()).resolves.toMatchObject({
await expect(
probe(exits(0, { [stream]: "unexpected" })),
).resolves.toMatchObject({
ok: false,
error: {
_tag: "AnalysisProtocolError",
@@ -174,17 +226,35 @@ it.each(["stdout", "stderr"] as const)(
},
);
it("hands back stdout bytes that are not UTF-8 exactly", async () => {
const result = await runAdbCapture(
"capture_adb_screen",
{ device: "device" },
scripted("process.stdout.write(Buffer.from([0x89, 0xff, 0x00]))"),
["exec-out", "screencap", "-p"],
{ timeoutMs: 10_000, maxOutputBytes: 3 },
undefined,
);
if (!result.ok) throw result.error;
expect([...result.value.stdout]).toEqual([0x89, 0xff, 0x00]);
});
it.each([null, "caller stopped", new Error("caller stopped")] as const)(
"uses the command owner's exact %s cancellation reason",
async (reason) => {
const cancelled = Object.assign(new ExecFileOutputCancelledError(reason), {
stdout: "partial",
stderr: "diagnostic",
stdoutBytes: 7,
stderrBytes: 10,
});
vi.mocked(execFileBytes).mockRejectedValueOnce(cancelled);
const result = await probe();
const controller = new AbortController();
const seen = { stdout: "", stderr: "" };
const result = await probe(
scripted(
"process.stdout.write('partial'); process.stderr.write('diagnostic'); setInterval(() => {}, 1000)",
(stream, text) => {
seen[stream] += text;
if (seen.stdout === "partial" && seen.stderr === "diagnostic")
controller.abort(reason);
},
),
controller.signal,
);
expect(result).toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError" },
@@ -192,40 +262,27 @@ it.each([null, "caller stopped", new Error("caller stopped")] as const)(
if (result.ok) throw new Error("Expected owned cancellation");
expect(result.error.cause).toBe(reason);
expect(result.error.capturedOutput).toMatchObject({
stdout: "partial",
stderr: "diagnostic",
stdout_bytes: 7,
stderr_bytes: 10,
});
},
);
it("does not infer cancellation from a foreign ABORT_ERR code", async () => {
const failure = Object.assign(new Error("foreign code"), {
code: "ABORT_ERR",
stdout: "",
stderr: "",
});
vi.mocked(execFileBytes).mockRejectedValueOnce(failure);
expect(await probe()).toMatchObject({
ok: false,
error: { _tag: "AnalysisProtocolError" },
});
});
it("keeps a physical failure even when the later abort reason is that same error", async () => {
const controller = new AbortController();
const failure = new Error("physical command failure");
vi.mocked(execFileBytes).mockImplementationOnce(async () => {
controller.abort(failure);
throw failure;
});
const result = await runAdbCapture(
"inspect_adb_device",
{ device: "device" },
{ binary: "/host/adb", pathSource: "environment", environment: {} },
{
...selection,
launcher: async () => {
controller.abort(failure);
throw failure;
},
},
[],
{ timeoutMs: 100, maxOutputBytes: 1024 },
{ timeoutMs: 10_000, maxOutputBytes: 1024 },
controller.signal,
);
expect(result).toMatchObject({
@@ -241,11 +298,7 @@ const STARTUP_NOTICES = [
it.each(STARTUP_NOTICES)(
"recognizes completed true and false probes with successful startup: %j",
async (stderr) => {
vi.mocked(execFileBytes).mockResolvedValueOnce({
stdout: Buffer.alloc(0),
stderr: Buffer.from(stderr),
});
await expect(probe()).resolves.toMatchObject({
await expect(probe(exits(0, { stderr }))).resolves.toMatchObject({
ok: true,
value: {
matches: true,
@@ -257,16 +310,7 @@ it.each(STARTUP_NOTICES)(
},
},
});
vi.mocked(execFileBytes).mockRejectedValueOnce(
Object.assign(new Error("false"), {
code: 1,
stdout: "",
stderr,
signal: null,
killed: false,
}),
);
await expect(probe()).resolves.toMatchObject({
await expect(probe(exits(1, { stderr }))).resolves.toMatchObject({
ok: true,
value: {
matches: false,
@@ -289,55 +333,31 @@ it.each([
"\n",
" ",
])("refuses an incomplete or unknown startup output: %j", async (stderr) => {
vi.mocked(execFileBytes).mockResolvedValueOnce({
stdout: Buffer.alloc(0),
stderr: Buffer.from(stderr),
});
await expect(probe()).resolves.toMatchObject({
await expect(probe(exits(0, { stderr }))).resolves.toMatchObject({
ok: false,
error: { capturedOutput: { stderr, exit_code: 0 } },
});
vi.mocked(execFileBytes).mockRejectedValueOnce(
Object.assign(new Error("false"), {
code: 1,
stdout: "",
stderr,
signal: null,
killed: false,
}),
);
await expect(probe()).resolves.toMatchObject({
await expect(probe(exits(1, { stderr }))).resolves.toMatchObject({
ok: false,
error: { capturedOutput: { stderr, exit_code: 1 } },
});
});
it("reports an adb that never started without claiming an exit code", async () => {
vi.mocked(execFileBytes).mockRejectedValueOnce(
Object.assign(new Error("spawn ENOTDIR"), {
code: "ENOTDIR",
spawnFailed: true,
stdout: "",
stderr: "",
signal: null,
killed: false,
}),
);
const result = await runAdbCapture(
"list_adb_devices",
{ device: "device" },
{ binary: "/host/adb", pathSource: "environment", environment: {} },
refused(spawnFailure("ENOTDIR", "/host/adb")),
["devices"],
{ timeoutMs: 100, maxOutputBytes: 1024 },
{ timeoutMs: 10_000, maxOutputBytes: 1024 },
undefined,
);
expect(result).toMatchObject({
ok: false,
error: {
_tag: "AnalysisProtocolError",
commandFailure: { code: "ENOTDIR", spawnFailed: true, signal: null },
},
if (result.ok) throw new Error("Expected a launch failure");
expect(result.error).toMatchObject({
_tag: "AnalysisProtocolError",
message: "adb could not be started (ENOTDIR) for list_adb_devices",
});
expect(result.error.capturedOutput).toBeUndefined();
});
it.each([
@@ -355,21 +375,12 @@ it.each([
] as const)(
"reports host launch constraint %s through the shared launch owner rather than as an adb protocol failure",
async (code, resource, retryable, facts) => {
vi.mocked(execFileBytes).mockRejectedValueOnce(
Object.assign(spawnFailure(code, "/host/adb"), {
spawnFailed: true,
stdout: "",
stderr: "",
signal: null,
killed: false,
}),
);
const result = await runAdbCapture(
"list_adb_devices",
{ device: "device" },
{ binary: "/host/adb", pathSource: "environment", environment: {} },
refused(spawnFailure(code, "/host/adb")),
["devices"],
{ timeoutMs: 100, maxOutputBytes: 1024 },
{ timeoutMs: 10_000, maxOutputBytes: 1024 },
undefined,
);
if (result.ok) throw new Error("Expected a launch constraint");
+162 -176
View File
@@ -4,19 +4,18 @@ import {
AnalysisTimeoutError,
AnalysisUnsupportedTargetError,
cancelledBy,
carriedReason,
} from "../domain/analysisErrorCore.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import { fixedAllowanceOptions } from "../domain/fixedAllowanceRemediation.js";
import { err, ok, type Result } from "../domain/result.js";
import { errorMessage } from "../kernel/errorMessage.js";
import {
execFileBytes,
execFileFailureCapturedOutput,
ExecFileOutputCancelledError,
execFileOutputFailure,
type ExecFileOutputFailure,
} from "../process/ExecFileOutput.js";
import { launcherFailureOf } from "../process/launchFailure.js";
adbRunFailureError,
runAdbProcess,
type AdbCommandHost,
type AdbExitedRun,
type AdbRunFailure,
} from "./AdbProcess.js";
import { classifyLaunchFailure } from "../process/classifyProviderOutcome.js";
import { packageChangeFailureReason } from "./AdbShellOutput.js";
import {
@@ -24,7 +23,7 @@ import {
isDaemonStartingNotice,
hasOnlySuccessfulAdbStartupNotices,
} from "./AdbDeviceOutput.js";
import { ADB_BINARY_ENV, type AdbBinarySelection } from "./AdbConfiguration.js";
import { ADB_BINARY_ENV } from "./AdbConfiguration.js";
const STDERR_EXCERPT_CHARACTERS = 512;
@@ -45,25 +44,21 @@ const LOCAL_FILE_DIAGNOSTICS = [
["reading", " locally failed:"],
] as const;
/** Parsed command failure owned by this adapter, separate from its public tag. */
/** adb's own nonzero exit, kept for consumers that read its verdict. */
class AdbProtocolError extends AnalysisProtocolError {
constructor(
message: string,
readonly commandFailure: ExecFileOutputFailure,
cause: unknown,
readonly run: AdbExitedRun,
) {
super(message, {
cause,
capturedOutput: execFileFailureCapturedOutput(commandFailure),
});
super(message, { capturedOutput: run.capturedOutput });
}
}
/** Return the retained process result only for command failures owned here. */
export const adbCommandOutputFailure = (
/** The completed run behind a nonzero adb exit reported here. */
export const adbExitedRunOf = (
error: AnalysisError,
): ExecFileOutputFailure | undefined =>
error instanceof AdbProtocolError ? error.commandFailure : undefined;
): AdbExitedRun | undefined =>
error instanceof AdbProtocolError ? error.run : undefined;
/** adb joins shell operands into a remote POSIX command; quote at that boundary. */
const quoteShellOperand = (value: string): string =>
@@ -105,147 +100,142 @@ export interface AdbCommandTarget {
export const runAdbCapture = async (
operation: string,
target: AdbCommandTarget,
selection: AdbBinarySelection,
host: AdbCommandHost,
arguments_: readonly string[],
limits: AdbRunLimits,
signal: AbortSignal | undefined,
): Promise<Result<{ stdout: Buffer; stderr: Buffer }, AnalysisError>> => {
): Promise<Result<{ stdout: Buffer; stderr: string }, AnalysisError>> => {
if (signal?.aborted === true) return err(cancelledBy(operation, signal));
try {
return ok(
await execFileBytes(selection.binary, arguments_, {
env: selection.environment,
timeout: limits.timeoutMs,
maxBuffer: limits.maxOutputBytes,
stopSignal: "SIGTERM",
...(signal === undefined ? {} : { signal }),
}),
);
} catch (cause) {
const failure = execFileOutputFailure(cause);
if (cause instanceof ExecFileOutputCancelledError)
return err(
cancelledBy(
operation,
carriedReason(cause.cause),
failure === undefined
? {}
: { capturedOutput: execFileFailureCapturedOutput(failure) },
),
);
if (failure === undefined)
return err(
new AnalysisProtocolError(`adb failed for ${operation}`, { cause }),
);
const detail = {
cause,
capturedOutput: execFileFailureCapturedOutput(failure),
};
if (failure.outputTruncated) {
const name = `The adb output capture allowance of ${String(limits.maxOutputBytes)} bytes (this release has no runtime override)`;
const allowance =
limits.volatileOutput === true
? {
fixedAllowance: { name, kind: "live" as const },
retryable: true as const,
}
: fixedAllowanceOptions(name, "capture");
return err(
new AnalysisResourceConstraintError(
operation,
"memory",
`adb output exceeded the ${String(limits.maxOutputBytes)}-byte capture budget`,
{ max_output_bytes: limits.maxOutputBytes },
{ ...detail, ...allowance },
),
);
}
const stderr = failure.stderr.trim();
const excerpt = stderr.slice(0, STDERR_EXCERPT_CHARACTERS);
// Device-state words inside a reported file name are not device verdicts.
// Only leading notices need line parsing. Do not expand a capture-sized
// stderr into an array whose entries can exceed the byte capture budget.
let diagnosticStart = 0;
while (diagnosticStart < stderr.length) {
const newline = stderr.indexOf("\n", diagnosticStart);
const line = stderr
.slice(diagnosticStart, newline === -1 ? stderr.length : newline)
.trimEnd();
if (!isSuccessfulDaemonStartNotice(line) && !isDaemonStartingNotice(line))
break;
diagnosticStart = newline === -1 ? stderr.length : newline + 1;
}
const diagnostic = stderr
.slice(diagnosticStart)
.replace(
/^(?:adb:\s*)?(?:error:\s*)?(?:(?:failed to get feature set|connect failed):\s*)?/iu,
"",
);
if (
/^(?:unauthorized\b|device(?: '[^'\n]*')? (?:unauthorized\b|offline\b|not found\b|still authorizing\b)|still authorizing\b|more than one device\b)/iu.test(
diagnostic,
)
)
return err(
new AnalysisUnsupportedTargetError(
operation,
target.device,
excerpt,
detail,
),
);
if (
/No such file or directory|Permission denied|read: Permission denied/iu.test(
diagnostic,
)
) {
const localPath = target.localPath;
const path =
localPath !== undefined &&
LOCAL_FILE_DIAGNOSTICS.some(([verb, suffix]) =>
[localPath, `'${localPath}'`, `"${localPath}"`].some((operand) =>
diagnostic.startsWith(`${verb} ${operand}${suffix}`),
),
)
? localPath
: (target.path ?? target.device);
return err(
new AnalysisUnsupportedTargetError(operation, path, excerpt, detail),
);
}
if (failure.killed)
return err(
new AnalysisTimeoutError(operation, limits.timeoutMs, {
...detail,
userMessage: `adb ${operation} reached its ${String(limits.timeoutMs)} ms deadline (deadlineExpired). This release has no runtime override.`,
remediationAction: `This ${String(limits.timeoutMs)} ms adb deadline has no runtime override. Allow execution, cleanup and delivery headroom in the outer MCP client deadline. Confirm outstanding work and cleanup before retrying.`,
}),
);
// The host, not adb, refused this launch: it lacked capacity, or the
// request's arguments and the environment exceed the launch limit.
const launch = launcherFailureOf(cause);
if (launch?.kind === "host-exhausted" || launch?.kind === "argument-list")
return err(
classifyLaunchFailure(launch, {
providerId: "adb",
operation,
command: selection.binary,
selection: ADB_BINARY_ENV,
details: detail,
}),
);
const outcome = await runAdbProcess(host, arguments_, limits, signal);
if (!outcome.ok)
return err(
new AdbProtocolError(
failure.spawnFailed === true
? `adb could not be started (${String(failure.code)}) for ${operation}`
: excerpt === ""
? `adb exited with code ${String(failure.code)} for ${operation}`
: excerpt,
failure,
cause,
adbRunFailureError(operation, host, outcome.failure, (failure) =>
adbRunFailure(operation, host, limits, failure),
),
);
const { run } = outcome;
if (run.exitCode === 0) return ok({ stdout: run.stdout, stderr: run.stderr });
return err(adbExitFailure(operation, target, run));
};
/** adb did not exit on its own: it ran out of time or capture, or never started. */
const adbRunFailure = (
operation: string,
host: AdbCommandHost,
limits: AdbRunLimits,
failure: AdbRunFailure,
): AnalysisError => {
const detail = {
cause: failure.cause,
...(failure.capturedOutput === undefined
? {}
: { capturedOutput: failure.capturedOutput }),
};
if (failure.command?.reason === "output-limit") {
const name = `The adb output capture allowance of ${String(limits.maxOutputBytes)} bytes (this release has no runtime override)`;
const facts = { limit: limits.maxOutputBytes, unit: "bytes" };
const allowance =
limits.volatileOutput === true
? {
fixedAllowance: { name, kind: "live" as const, ...facts },
retryable: true as const,
}
: fixedAllowanceOptions(name, "capture", facts);
return new AnalysisResourceConstraintError(
operation,
"memory",
`adb output exceeded the ${String(limits.maxOutputBytes)}-byte capture budget`,
{ max_output_bytes: limits.maxOutputBytes },
{ ...detail, ...allowance },
);
}
if (failure.command?.reason === "timeout")
return new AnalysisTimeoutError(operation, limits.timeoutMs, {
...detail,
userMessage: `adb ${operation} reached its ${String(limits.timeoutMs)} ms deadline (deadlineExpired). This release has no runtime override.`,
remediationAction: `This ${String(limits.timeoutMs)} ms adb deadline has no runtime override. Allow execution, cleanup and delivery headroom in the outer MCP client deadline. Confirm outstanding work and cleanup before retrying.`,
});
// The host, not adb, refused this launch: it lacked capacity, or the
// request's arguments and the environment exceed the launch limit.
const { launch } = failure;
if (launch?.kind === "host-exhausted" || launch?.kind === "argument-list")
return classifyLaunchFailure(launch, {
providerId: "adb",
operation,
command: host.binary,
selection: ADB_BINARY_ENV,
details: detail,
});
return new AnalysisProtocolError(
launch !== undefined
? `adb could not be started (${String(launch.code ?? "no system code")}) for ${operation}`
: `adb failed for ${operation}: ${errorMessage(failure.cause)}`,
detail,
);
};
/** Read adb's verdict from a run that exited nonzero. */
const adbExitFailure = (
operation: string,
target: AdbCommandTarget,
run: AdbExitedRun,
): AnalysisError => {
const detail = { capturedOutput: run.capturedOutput };
const stderr = run.stderr.trim();
const excerpt = stderr.slice(0, STDERR_EXCERPT_CHARACTERS);
// Device-state words inside a reported file name are not device verdicts.
// Only leading notices need line parsing. Do not expand a capture-sized
// stderr into an array whose entries can exceed the byte capture budget.
let diagnosticStart = 0;
while (diagnosticStart < stderr.length) {
const newline = stderr.indexOf("\n", diagnosticStart);
const line = stderr
.slice(diagnosticStart, newline === -1 ? stderr.length : newline)
.trimEnd();
if (!isSuccessfulDaemonStartNotice(line) && !isDaemonStartingNotice(line))
break;
diagnosticStart = newline === -1 ? stderr.length : newline + 1;
}
const diagnostic = stderr
.slice(diagnosticStart)
.replace(
/^(?:adb:\s*)?(?:error:\s*)?(?:(?:failed to get feature set|connect failed):\s*)?/iu,
"",
);
if (
/^(?:unauthorized\b|device(?: '[^'\n]*')? (?:unauthorized\b|offline\b|not found\b|still authorizing\b)|still authorizing\b|more than one device\b)/iu.test(
diagnostic,
)
)
return new AnalysisUnsupportedTargetError(
operation,
target.device,
excerpt,
detail,
);
if (
/No such file or directory|Permission denied|read: Permission denied/iu.test(
diagnostic,
)
) {
const localPath = target.localPath;
const path =
localPath !== undefined &&
LOCAL_FILE_DIAGNOSTICS.some(([verb, suffix]) =>
[localPath, `'${localPath}'`, `"${localPath}"`].some((operand) =>
diagnostic.startsWith(`${verb} ${operand}${suffix}`),
),
)
? localPath
: (target.path ?? target.device);
return new AnalysisUnsupportedTargetError(operation, path, excerpt, detail);
}
return new AdbProtocolError(
excerpt === ""
? `adb exited with code ${String(run.exitCode)} for ${operation}`
: excerpt,
run,
);
};
/** Decode textual adb protocols after the shared byte capture and error boundary. */
@@ -258,7 +248,7 @@ export const runAdb = async (
if (!captured.ok) return captured;
return ok({
stdout: captured.value.stdout.toString("utf8"),
stderr: captured.value.stderr.toString("utf8"),
stderr: captured.value.stderr,
// Byte count of the captured output before UTF-8 decoding, so malformed
// sequences replaced by U+FFFD still report their true captured size.
stdoutBytes: captured.value.stdout.byteLength,
@@ -276,9 +266,9 @@ export const packageChangeRefusal = (
error: AnalysisError,
): Result<never, AnalysisError> | undefined => {
if (!(error instanceof AdbProtocolError)) return undefined;
const failure = error.commandFailure;
const { run } = error;
const reason = packageChangeFailureReason(
`${failure.stdout}\n${failure.stderr}`,
`${run.stdout.toString("utf8")}\n${run.stderr}`,
);
return reason === null
? undefined
@@ -325,11 +315,11 @@ export const probeAdbPathExistence = async (
operation: string,
serial: string,
path: string,
selection: AdbBinarySelection,
host: AdbCommandHost,
limits: AdbRunLimits,
signal: AbortSignal | undefined,
): Promise<Result<AdbPathProbe, AnalysisError>> => {
return probeAdbPath(operation, serial, path, selection, limits, signal, "-e");
return probeAdbPath(operation, serial, path, host, limits, signal, "-e");
};
/** Completed predicate status is independent of recognized host startup notices. */
@@ -337,17 +327,17 @@ export const probeAdbPathDirectory = async (
operation: string,
serial: string,
path: string,
selection: AdbBinarySelection,
host: AdbCommandHost,
limits: AdbRunLimits,
signal: AbortSignal | undefined,
): Promise<Result<AdbPathProbe, AnalysisError>> =>
probeAdbPath(operation, serial, path, selection, limits, signal, "-d");
probeAdbPath(operation, serial, path, host, limits, signal, "-d");
const probeAdbPath = async (
operation: string,
serial: string,
path: string,
selection: AdbBinarySelection,
host: AdbCommandHost,
limits: AdbRunLimits,
signal: AbortSignal | undefined,
predicate: "-d" | "-e",
@@ -357,13 +347,13 @@ const probeAdbPath = async (
const probed = await runAdbCapture(
operation,
{ device: serial, path },
selection,
host,
adbArguments(serial, ["shell", "test", predicate, path]),
{ ...limits, volatileOutput: true },
signal,
);
if (probed.ok) {
const stderr = probed.value.stderr.toString("utf8");
const { stderr } = probed.value;
if (probed.value.stdout.length === 0 && recognizedProbeStderr(stderr))
return ok(completedAdbPathProbe(true, stderr));
return err(
@@ -373,9 +363,9 @@ const probeAdbPath = async (
diagnostics: { [fact]: "unknown" },
capturedOutput: {
stdout: probed.value.stdout.toString("utf8"),
stderr: probed.value.stderr.toString("utf8"),
stderr,
stdout_bytes: probed.value.stdout.length,
stderr_bytes: probed.value.stderr.length,
stderr_bytes: Buffer.byteLength(stderr),
exit_code: 0,
signal: null,
truncated: false,
@@ -386,22 +376,18 @@ const probeAdbPath = async (
}
const error = probed.error;
if (!(error instanceof AdbProtocolError)) return probed;
const failure = error.commandFailure;
const { run } = error;
if (
failure.code === 1 &&
failure.signal === null &&
!failure.killed &&
!failure.outputTruncated &&
failure.collectionFailure !== true &&
failure.stdout === "" &&
recognizedProbeStderr(failure.stderr)
run.exitCode === 1 &&
run.stdout.length === 0 &&
recognizedProbeStderr(run.stderr)
)
return ok(completedAdbPathProbe(false, failure.stderr));
return ok(completedAdbPathProbe(false, run.stderr));
return err(
new AnalysisProtocolError(error.message, {
cause: error.cause,
cause: error,
diagnostics: { [fact]: "unknown" },
capturedOutput: execFileFailureCapturedOutput(failure),
capturedOutput: run.capturedOutput,
}),
);
};
+154 -150
View File
@@ -1,4 +1,5 @@
import {
AnalysisProtocolError,
AnalysisResourceConstraintError,
AnalysisTimeoutError,
cancelledBy,
@@ -9,17 +10,19 @@ import { findWindowsExecutable } from "../process/WindowsExecutable.js";
import { ProviderStartupDeadline } from "../process/ProviderDeadline.js";
import { snapshotEnvironment } from "../process/snapshotEnvironment.js";
import {
execFileOutput,
execFileFailureCapturedOutput,
ExecFileOutputCancelledError,
execFileOutputFailure,
} from "../process/ExecFileOutput.js";
import type { ProviderAvailability } from "../ports/AnalysisProvider.js";
import type { ProviderRejectionCode } from "../domain/providerSelection.js";
import { fixedAllowanceOptions } from "../domain/fixedAllowanceRemediation.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { launcherFailureOf } from "../process/launchFailure.js";
import type { LauncherFailure } from "../process/launchFailure.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import { errorMessage } from "../kernel/errorMessage.js";
import {
adbRunFailureError,
runAdbProcess,
type AdbCommandHost,
type AdbRunFailure,
} from "./AdbProcess.js";
import { classifyLaunchFailure } from "../process/classifyProviderOutcome.js";
/** Environment key selecting the caller's adb binary. */
@@ -174,153 +177,154 @@ export const parseAdbVersionOutput = (stdout: string): AdbClientIdentity => {
* never starts the adb server, so this stays a pure client check.
*/
export const inspectAdbClient = async (
selection: AdbBinarySelection,
host: AdbCommandHost,
signal?: AbortSignal,
): Promise<AdbClientIdentity> => {
try {
const { stdout, stderr } = await execFileOutput(
selection.binary,
["version"],
{
env: selection.environment,
timeout: VERSION_TIMEOUT_MS,
stopSignal: "SIGTERM",
maxBuffer: VERSION_MAX_OUTPUT_BYTES,
...(signal === undefined ? {} : { signal }),
},
);
const identity = parseAdbVersionOutput(stdout);
const hasRecognizedProtocolVersion =
/^Android Debug Bridge version\s+\d+\.\d+\.\d+\s*$/mu.test(stdout);
if (identity.version === null && !hasRecognizedProtocolVersion)
throw new AdbConfigurationFailure(
"version_unresolved",
"The selected adb binary exited successfully but did not report a recognizable protocol or build version",
ADB_VERSION_REMEDIATION,
{
selected_binary: selection.binary,
path_source: selection.pathSource,
version_probe: "unrecognized_output",
stdout,
stderr,
},
);
return identity;
} catch (cause) {
if (cause instanceof AdbConfigurationFailure) throw cause;
const failure = execFileOutputFailure(cause);
if (cause instanceof ExecFileOutputCancelledError)
throw cancelledBy(
"inspect_adb_client",
carriedReason(cause.cause),
failure === undefined
? {}
: { capturedOutput: execFileFailureCapturedOutput(failure) },
);
const diagnostics = {
selected_binary: selection.binary,
path_source: selection.pathSource,
...(failure === undefined || failure.spawnFailed === true
? {}
: { exit_code: failure.code }),
};
const options = {
cause,
diagnostics,
...(failure === undefined
? {}
: { capturedOutput: execFileFailureCapturedOutput(failure) }),
};
if (failure?.outputTruncated === true) {
throw new AnalysisResourceConstraintError(
"inspect_adb_client",
"memory",
`adb version output exceeded the ${String(VERSION_MAX_OUTPUT_BYTES)}-byte capture budget`,
{ max_output_bytes: VERSION_MAX_OUTPUT_BYTES },
{
...options,
...fixedAllowanceOptions(
`The adb version-output capture allowance of ${String(VERSION_MAX_OUTPUT_BYTES)} bytes (this release has no runtime override)`,
"capture",
),
},
);
}
if (failure?.code === "ETIMEDOUT")
throw new AnalysisTimeoutError("inspect_adb_client", VERSION_TIMEOUT_MS, {
...options,
userMessage: `adb version probe reached its ${String(VERSION_TIMEOUT_MS)} ms deadline (deadlineExpired). This release has no runtime override.`,
remediationAction: `This ${String(VERSION_TIMEOUT_MS)} ms adb version probe has no runtime override. Allow execution, cleanup and delivery headroom in the outer MCP client deadline. Confirm outstanding work and cleanup before retrying.`,
});
// The process never started: the launcher's errno is not an exit status,
// and no version probe ran.
const launch = launcherFailureOf(cause);
// The host, not the selected binary, refused this launch.
if (launch?.kind === "host-exhausted" || launch?.kind === "argument-list")
throw classifyLaunchFailure(launch, {
providerId: "adb",
operation: "inspect_adb_client",
command: selection.binary,
fixedArguments: true,
selection: ADB_BINARY_ENV,
details: {
cause,
diagnostics: {
selected_binary: selection.binary,
path_source: selection.pathSource,
},
},
});
if (launch !== undefined) {
const code = launch.code ?? "no system code";
const fromEnvironment = selection.pathSource === "environment";
const facts = {
selected_binary: selection.binary,
path_source: selection.pathSource,
filesystem_error: code,
};
// Nothing executable resolves at the selected path.
if (launch.kind === "missing")
throw new AdbConfigurationFailure(
"binary_missing",
`The selected adb binary was not found: ${selection.binary}`,
ADB_MISSING_REMEDIATION,
facts,
{ cause },
);
throw new AdbConfigurationFailure(
"binary_not_executable",
code === "EACCES" || code === "EPERM"
? `Execution of the selected adb binary was denied (${code}): ${selection.binary}`
: `The selected adb binary could not be started (${code}): ${selection.binary}`,
code === "EACCES"
? fromEnvironment
? ADB_NOT_EXECUTABLE_REMEDIATION
: `Make sure the adb found on PATH is a file with execute permission, not a directory, and that its parent directories have search permission, or set ${ADB_BINARY_ENV} to an absolute path to an executable adb binary.`
: code === "EPERM"
? `The host refused to run this adb binary, for example because of a security policy or file flags; allow it to run, or set ${ADB_BINARY_ENV} to an absolute path to an adb binary the host permits.`
: `Select an adb executable this host can start directly: set ${ADB_BINARY_ENV} to its absolute path, or make it the adb found on PATH.`,
facts,
{ cause },
);
}
throw new AdbConfigurationFailure(
"version_unresolved",
`The selected adb binary did not report a usable version: ${selection.binary}`,
ADB_VERSION_REMEDIATION,
{
selected_binary: selection.binary,
path_source: selection.pathSource,
...(failure === undefined
? {}
: {
exit_code: failure.code,
stderr_excerpt: failure.stderr.slice(0, 512),
}),
},
{ cause },
const outcome = await runAdbProcess(
host,
["version"],
{ timeoutMs: VERSION_TIMEOUT_MS, maxOutputBytes: VERSION_MAX_OUTPUT_BYTES },
signal,
);
if (!outcome.ok) {
const failure = outcome.failure;
// The process never started: the launcher's errno is not an exit status.
const launch = failure.launch;
if (
failure.command === undefined &&
launch !== undefined &&
launch.kind !== "host-exhausted" &&
launch.kind !== "argument-list"
)
throw adbLaunchRefusal(host, launch, failure.cause);
throw adbRunFailureError("inspect_adb_client", host, failure, () =>
versionProbeFailure(host, failure),
);
}
const { run } = outcome;
const stdout = run.stdout.toString("utf8");
if (run.exitCode !== 0)
throw new AdbConfigurationFailure(
"version_unresolved",
`The selected adb binary did not report a usable version: ${host.binary}`,
ADB_VERSION_REMEDIATION,
{
selected_binary: host.binary,
path_source: host.pathSource,
exit_code: run.exitCode,
stderr_excerpt: run.stderr.slice(0, 512),
},
);
const identity = parseAdbVersionOutput(stdout);
const hasRecognizedProtocolVersion =
/^Android Debug Bridge version\s+\d+\.\d+\.\d+\s*$/mu.test(stdout);
if (identity.version === null && !hasRecognizedProtocolVersion)
throw new AdbConfigurationFailure(
"version_unresolved",
"The selected adb binary exited successfully but did not report a recognizable protocol or build version",
ADB_VERSION_REMEDIATION,
{
selected_binary: host.binary,
path_source: host.pathSource,
version_probe: "unrecognized_output",
stdout,
stderr: run.stderr,
},
);
return identity;
};
/** The version probe did not exit on its own. */
const versionProbeFailure = (
host: AdbCommandHost,
failure: AdbRunFailure,
): AnalysisError => {
const facts = {
selected_binary: host.binary,
path_source: host.pathSource,
};
const options = {
cause: failure.cause,
diagnostics: facts,
...(failure.capturedOutput === undefined
? {}
: { capturedOutput: failure.capturedOutput }),
};
if (failure.command?.reason === "output-limit")
return new AnalysisResourceConstraintError(
"inspect_adb_client",
"memory",
`adb version output exceeded the ${String(VERSION_MAX_OUTPUT_BYTES)}-byte capture budget`,
{ max_output_bytes: VERSION_MAX_OUTPUT_BYTES },
{
...options,
...fixedAllowanceOptions(
`The adb version-output capture allowance of ${String(VERSION_MAX_OUTPUT_BYTES)} bytes (this release has no runtime override)`,
"capture",
{ limit: VERSION_MAX_OUTPUT_BYTES, unit: "bytes" },
),
},
);
if (failure.command?.reason === "timeout")
return new AnalysisTimeoutError("inspect_adb_client", VERSION_TIMEOUT_MS, {
...options,
userMessage: `adb version probe reached its ${String(VERSION_TIMEOUT_MS)} ms deadline (deadlineExpired). This release has no runtime override.`,
remediationAction: `This ${String(VERSION_TIMEOUT_MS)} ms adb version probe has no runtime override. Allow execution, cleanup and delivery headroom in the outer MCP client deadline. Confirm outstanding work and cleanup before retrying.`,
});
const launch = failure.launch;
// The host, not the selected binary, refused this launch.
if (launch?.kind === "host-exhausted" || launch?.kind === "argument-list")
return classifyLaunchFailure(launch, {
providerId: "adb",
operation: "inspect_adb_client",
command: host.binary,
fixedArguments: true,
selection: ADB_BINARY_ENV,
details: { cause: failure.cause, diagnostics: facts },
});
return new AnalysisProtocolError(
`adb version probe failed: ${errorMessage(failure.cause)}`,
options,
);
};
/** The selected adb binary could not be started: a repair to its selection. */
const adbLaunchRefusal = (
host: AdbCommandHost,
launch: LauncherFailure,
cause: unknown,
): AdbConfigurationFailure => {
const code = launch.code ?? "no system code";
const fromEnvironment = host.pathSource === "environment";
const facts = {
selected_binary: host.binary,
path_source: host.pathSource,
filesystem_error: code,
};
// Nothing executable resolves at the selected path.
if (launch.kind === "missing")
return new AdbConfigurationFailure(
"binary_missing",
`The selected adb binary was not found: ${host.binary}`,
ADB_MISSING_REMEDIATION,
facts,
{ cause },
);
return new AdbConfigurationFailure(
"binary_not_executable",
code === "EACCES" || code === "EPERM"
? `Execution of the selected adb binary was denied (${code}): ${host.binary}`
: `The selected adb binary could not be started (${code}): ${host.binary}`,
code === "EACCES"
? fromEnvironment
? ADB_NOT_EXECUTABLE_REMEDIATION
: `Make sure the adb found on PATH is a file with execute permission, not a directory, and that its parent directories have search permission, or set ${ADB_BINARY_ENV} to an absolute path to an executable adb binary.`
: code === "EPERM"
? `The host refused to run this adb binary, for example because of a security policy or file flags; allow it to run, or set ${ADB_BINARY_ENV} to an absolute path to an adb binary the host permits.`
: `Select an adb executable this host can start directly: set ${ADB_BINARY_ENV} to its absolute path, or make it the adb found on PATH.`,
facts,
{ cause },
);
};
/** Availability in the shape shared by every provider. */
+2 -2
View File
@@ -6,7 +6,7 @@ import { AnalysisProtocolError } from "../domain/analysisErrorCore.js";
import { err, ok, type Result } from "../domain/result.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import { adbArguments, runAdb, type AdbRunLimits } from "./AdbCommand.js";
import type { AdbBinarySelection } from "./AdbConfiguration.js";
import type { AdbCommandHost } from "./AdbProcess.js";
import {
parseAdbDevicesOutput,
parseGetpropOutput,
@@ -25,7 +25,7 @@ const GETPROP_MAX_OUTPUT_BYTES = 2 * 1024 * 1024;
export interface AdbCommandContext {
readonly operation: AdbRequest["operation"];
readonly request: AdbRequest;
readonly selection: AdbBinarySelection;
readonly selection: AdbCommandHost;
readonly client: AdbClientResult;
readonly provider: AdbProviderIdentity;
readonly signal: AbortSignal | undefined;
+240
View File
@@ -0,0 +1,240 @@
import { randomUUID } from "node:crypto";
import {
AnalysisError,
type AnalysisCapturedOutput,
} from "../domain/analysisErrorBase.js";
import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js";
import { cancelledBy, carriedReason } from "../domain/analysisErrorCore.js";
import { capturedProviderOutput } from "../process/capturedProviderOutput.js";
import { DarwinProcessOwnershipInspectionError } from "../process/DarwinProcessRunTokenReader.js";
import {
launcherFailureOf,
type LauncherFailure,
} from "../process/launchFailure.js";
import {
OwnedCommandFailure,
OwnedCommandStdoutBytes,
prepareOwnedCommand,
preparationHostCapacityFailure,
runOwnedCommand,
} from "../process/OwnedCommand.js";
import type {
ProcessTerminationPolicy,
ProviderProcessSnapshot,
} from "../process/ProviderProcess.js";
import {
bindProcessInspectionCancellations,
processInspectionCancellationError,
processInspectionFailure,
retainArtifactCommandCleanup,
} from "../providers/OwnedCommandCleanup.js";
import type { ArtifactResourceScope } from "../resources/index.js";
import type { AdbBinarySelection } from "./AdbConfiguration.js";
/**
* The selected adb binary and the scope that keeps an adb command whose
* cleanup failed, so the provider retries it before its next operation.
*/
export interface AdbCommandHost extends AdbBinarySelection {
readonly resources: ArtifactResourceScope;
/** Replaces the owned launcher, for tests that control process outcomes. */
readonly launcher?: NonNullable<
Parameters<typeof runOwnedCommand>[2]
>["launcher"];
}
/**
* adb is asked to stop before its process group is killed, as it was before
* owned supervision, so it can close its server connection.
*/
const ADB_TERMINATION: ProcessTerminationPolicy = {
signal: "SIGTERM",
graceMs: 5_000,
};
/** An adb run that exited on its own, with its status and complete output. */
export interface AdbExitedRun {
readonly stdout: Buffer;
readonly stderr: string;
readonly exitCode: number;
readonly capturedOutput: AnalysisCapturedOutput;
}
/** Why an adb run did not exit on its own, with the facts it left. */
export interface AdbRunFailure {
readonly cause: unknown;
readonly command: OwnedCommandFailure | undefined;
/** The host refused to start adb; no adb process ran. */
readonly launch: LauncherFailure | undefined;
readonly capturedOutput: AnalysisCapturedOutput | undefined;
/** Present when adb exited but its process cleanup did not finish. */
readonly exited: AdbExitedRun | undefined;
}
export type AdbRunOutcome =
| { readonly ok: true; readonly run: AdbExitedRun }
| { readonly ok: false; readonly failure: AdbRunFailure };
const exitedRun = (
snapshot: ProviderProcessSnapshot,
stdout: Buffer,
exitCode: number,
): AdbExitedRun => ({
stdout,
stderr: snapshot.stderr.text,
exitCode,
capturedOutput: {
stdout: stdout.toString("utf8"),
stderr: snapshot.stderr.text,
stdout_bytes: stdout.byteLength,
stderr_bytes: snapshot.stderr.observedBytes,
exit_code: exitCode,
signal: null,
truncated: false,
},
});
/** Output an interrupted run left: stdout from the collector, stderr from the supervisor. */
const failureOutput = (
command: OwnedCommandFailure | undefined,
cause: unknown,
stdout: Buffer,
): AnalysisCapturedOutput | undefined => {
if (command?.snapshot == null) {
const preparation = processInspectionFailure(cause);
return preparation instanceof DarwinProcessOwnershipInspectionError
? preparation.capturedOutput
: undefined;
}
const observed = capturedProviderOutput(command.snapshot);
return {
...observed,
// The bytes adb wrote up to its capture limit; `truncated` marks a cut.
stdout: stdout.toString("utf8"),
stdout_bytes: stdout.byteLength,
truncated:
observed.truncated ||
command.reason === "output-limit" ||
command.snapshot.outputIncomplete === true,
};
};
/**
* Run one adb command in an owned process group, with its stdout kept as
* bytes up to `maxOutputBytes`. A nonzero exit is a completed run; the caller
* reads adb's verdict from it.
*/
export const runAdbProcess = async (
host: AdbCommandHost,
arguments_: readonly string[],
limits: { readonly timeoutMs: number; readonly maxOutputBytes: number },
signal: AbortSignal | undefined,
): Promise<AdbRunOutcome> => {
const stdout = new OwnedCommandStdoutBytes();
let exited: AdbExitedRun | undefined;
try {
await prepareOwnedCommand(signal);
await runOwnedCommand(
{
command: host.binary,
arguments: arguments_,
runId: `rea-adb-${randomUUID()}`,
hostEnvironment: host.environment,
sweepTokenOwnedProcesses: true,
},
{
timeoutMs: limits.timeoutMs,
diagnosticBytes: limits.maxOutputBytes,
stdout,
maxStdoutBytes: limits.maxOutputBytes,
acceptNonZeroExit: true,
termination: ADB_TERMINATION,
observeCompleted: (snapshot) => {
// An accepted run exited normally, so it has a numeric status.
if (typeof snapshot.exitCode === "number")
exited = exitedRun(snapshot, stdout.bytes, snapshot.exitCode);
},
},
{
signal,
...(host.launcher === undefined ? {} : { launcher: host.launcher }),
},
);
if (exited === undefined)
throw new OwnedCommandFailure(
"process",
"adb completed without an exit status",
);
return { ok: true, run: exited };
} catch (cause: unknown) {
const command = cause instanceof OwnedCommandFailure ? cause : undefined;
return {
ok: false,
failure: {
cause,
command,
launch:
launcherFailureOf(command?.processError ?? cause) ??
preparationHostCapacityFailure(cause),
capturedOutput: failureOutput(command, cause, stdout.bytes),
exited: command?.cleanupOwner === undefined ? undefined : exited,
},
};
}
};
/**
* Report a failed adb run: caller cancellation and interrupted process
* inspection first, then `classify` for the run's own failure. Process and
* inspection owners whose cleanup failed move to the host's scope; when adb
* had exited, that cleanup failure is the report and keeps adb's output.
*/
export const adbRunFailureError = (
operation: string,
host: AdbCommandHost,
failure: AdbRunFailure,
classify: (failure: AdbRunFailure) => AnalysisError,
): AnalysisError => {
const { cause, command } = failure;
const cleanups = retainArtifactCommandCleanup(
cause,
host.resources,
operation,
failure.exited === undefined
? undefined
: { capturedOutput: failure.exited.capturedOutput },
);
const inspectionCancellation =
command === undefined || command.preparationFailure !== undefined
? processInspectionCancellationError(cause, operation)
: undefined;
let primary: AnalysisError;
if (command?.reason === "cancelled" && command.cancellation !== undefined)
primary =
inspectionCancellation ??
cancelledBy(
operation,
carriedReason(command.cancellation.reason),
failure.capturedOutput === undefined
? {}
: { capturedOutput: failure.capturedOutput },
);
else if (inspectionCancellation !== undefined)
primary = inspectionCancellation;
// Ownership preparation reports its own analysis failure, such as cleanup
// of an earlier preparation it must finish before admitting another launch.
else if (command === undefined && cause instanceof AnalysisError)
primary = cause;
else if (failure.exited !== undefined && cleanups[0] !== undefined)
primary = cleanups[0];
else primary = classify(failure);
for (const cleanup of cleanups)
if (cleanup !== primary)
primary = analysisErrorWithCleanupDependencies(
primary,
cleanup,
operation,
);
return bindProcessInspectionCancellations(cause, primary, operation);
};
+30 -19
View File
@@ -42,29 +42,35 @@ vi.mock("node:fs/promises", async (importOriginal) => {
};
});
vi.mock("../process/ExecFileOutput.js", async (importOriginal) => {
const actual =
await importOriginal<typeof import("../process/ExecFileOutput.js")>();
vi.mock("./AdbProcess.js", async (importOriginal) => {
const actual = await importOriginal<typeof import("./AdbProcess.js")>();
// A host launch refusal reaches the adb process owner through its launcher.
const refusedLaunch = (failure: unknown) => ({
launcher: async () => {
throw failure;
},
});
return {
...actual,
execFileBytes: async (
...arguments_: Parameters<typeof actual.execFileBytes>
runAdbProcess: async (
...[host, command, limits, signal]: Parameters<
typeof actual.runAdbProcess
>
) => {
const failure = adbTestHooks.digestCheckFailure;
if (failure !== undefined && arguments_[1].includes("sha256sum"))
throw failure;
const result = await actual.execFileBytes(...arguments_);
if (arguments_[1].includes("exec-out")) adbTestHooks.afterScreencap?.();
const failure = command.includes("sha256sum")
? adbTestHooks.digestCheckFailure
: command.includes("version")
? adbTestHooks.versionProbeFailure
: undefined;
const result = await actual.runAdbProcess(
failure === undefined ? host : { ...host, ...refusedLaunch(failure) },
command,
limits,
signal,
);
if (command.includes("exec-out")) adbTestHooks.afterScreencap?.();
return result;
},
execFileOutput: async (
...arguments_: Parameters<typeof actual.execFileOutput>
) => {
const failure = adbTestHooks.versionProbeFailure;
if (failure !== undefined && arguments_[1].includes("version"))
throw failure;
return actual.execFileOutput(...arguments_);
},
};
});
@@ -92,7 +98,12 @@ const writeAdbStub = async (
const root = await mkdtemp(join("/tmp", "rea-adb-"));
onTestFinished(() => rm(root, { recursive: true, force: true }));
const binary = join(root, "adb");
await writeFile(binary, `#!/bin/sh\n${body(root)}\n`, { mode: 0o755 });
// A running adb server makes `adb start-server` a successful no-op.
await writeFile(
binary,
`#!/bin/sh\nif [ "$1" = "start-server" ]; then exit 0; fi\n${body(root)}\n`,
{ mode: 0o755 },
);
await chmod(binary, 0o755);
return { binary, root };
};
+38 -31
View File
@@ -5,7 +5,7 @@ import {
absoluteCallerPath,
appendCallerPath,
} from "../filesystem/callerPath.js";
import { execFileFailureCapturedOutput } from "../process/ExecFileOutput.js";
import type { AnalysisCapturedOutput } from "../domain/analysisErrorBase.js";
import { collectNumericIssues } from "./AdbNumericIssues.js";
import {
adbFilesystemErrorCode,
@@ -99,7 +99,7 @@ import {
runtimeControlCapabilityError,
} from "../domain/runtimeControlUnavailableError.js";
import {
adbCommandOutputFailure,
adbExitedRunOf,
adbArguments,
runAdb,
runAdbCapture,
@@ -108,12 +108,13 @@ import {
probeAdbPathExistence,
type AdbRunLimits,
} from "./AdbCommand.js";
import type { AdbCommandHost } from "./AdbProcess.js";
import { startAdbServer } from "./AdbServer.js";
import {
AdbConfigurationFailure,
adbConfigurationAvailability,
inspectAdbClient,
resolveAdbBinary,
type AdbBinarySelection,
type AdbClientIdentity,
} from "./AdbConfiguration.js";
import { snapshotEnvironment } from "../process/snapshotEnvironment.js";
@@ -843,8 +844,12 @@ export class AdbProvider {
((rootOptions) => PrivateRuntimeRoot.create(rootOptions));
}
private selection(signal?: AbortSignal): Promise<AdbBinarySelection> {
return resolveAdbBinary(this.environment, this.platform, signal);
/** The selected adb binary, with this provider retaining its commands' unfinished cleanup. */
private async selection(signal?: AbortSignal): Promise<AdbCommandHost> {
return {
...(await resolveAdbBinary(this.environment, this.platform, signal)),
resources: this.#resources,
};
}
/** Probe the selected adb binary; never contacts devices or the server. */
@@ -1250,7 +1255,7 @@ export class AdbProvider {
const signal = options?.signal;
if (signal?.aborted === true)
return err(cancelledBy(request.operation, signal));
let selection: AdbBinarySelection;
let selection: AdbCommandHost;
let identity: AdbClientIdentity;
try {
selection = await this.selection(signal);
@@ -1280,6 +1285,16 @@ export class AdbProvider {
),
);
}
// Device operations reach the shared adb server, which REA may start
// but never stops; a device command then never forks it.
if (request.operation !== "inspect_adb_client") {
const started = await startAdbServer(
request.operation,
selection,
signal,
);
if (!started.ok) return started;
}
const client = clientIdentityResult(selection, identity);
const provider: AdbProviderIdentity = {
...ADB_PROVIDER_IDENTITY,
@@ -1815,7 +1830,7 @@ export class AdbProvider {
private async pullPackage(
operation: "pull_adb_package",
selection: AdbBinarySelection,
selection: AdbCommandHost,
client: AdbClientResult,
provider: AdbProviderIdentity,
input: {
@@ -2206,7 +2221,7 @@ export class AdbProvider {
private async pullFile(
operation: "pull_adb_file",
selection: AdbBinarySelection,
selection: AdbCommandHost,
client: AdbClientResult,
provider: AdbProviderIdentity,
input: {
@@ -2322,7 +2337,7 @@ export class AdbProvider {
private async pushFile(
operation: "push_adb_file",
selection: AdbBinarySelection,
selection: AdbCommandHost,
client: AdbClientResult,
provider: AdbProviderIdentity,
input: {
@@ -2552,7 +2567,7 @@ export class AdbProvider {
private async installPackage(
operation: "install_adb_package",
selection: AdbBinarySelection,
selection: AdbCommandHost,
client: AdbClientResult,
provider: AdbProviderIdentity,
input: {
@@ -2653,7 +2668,7 @@ export class AdbProvider {
private async uninstallPackage(
operation: "uninstall_adb_package",
selection: AdbBinarySelection,
selection: AdbCommandHost,
client: AdbClientResult,
provider: AdbProviderIdentity,
input: { readonly serial: string; readonly package: string },
@@ -2720,7 +2735,7 @@ export class AdbProvider {
private async startApp(
operation: "start_adb_app",
selection: AdbBinarySelection,
selection: AdbCommandHost,
client: AdbClientResult,
provider: AdbProviderIdentity,
input: { readonly serial: string; readonly package: string },
@@ -2776,7 +2791,7 @@ export class AdbProvider {
private async startActivity(
operation: "start_adb_activity",
selection: AdbBinarySelection,
selection: AdbCommandHost,
client: AdbClientResult,
provider: AdbProviderIdentity,
input: {
@@ -2838,7 +2853,7 @@ export class AdbProvider {
private async runAmStart(
operation: "start_adb_app" | "start_adb_activity",
selection: AdbBinarySelection,
selection: AdbCommandHost,
client: AdbClientResult,
provider: AdbProviderIdentity,
serial: string,
@@ -2856,7 +2871,7 @@ export class AdbProvider {
);
let stdout: string;
let stderr: string;
let capturedOutput: ReturnType<typeof execFileFailureCapturedOutput>;
let capturedOutput: AnalysisCapturedOutput;
let verdict: ReturnType<typeof parseAmStartOutput>;
if (started.ok) {
stdout = started.value.stdout;
@@ -2864,21 +2879,13 @@ export class AdbProvider {
capturedOutput = { stdout, stderr, truncated: false };
verdict = parseAmStartOutput(stdout, stderr);
} else {
const commandFailure = adbCommandOutputFailure(started.error);
const exited = adbExitedRunOf(started.error);
// AOSP ActivityManagerShellCommand returns 1 for class-not-found and
// emits its refusal report on stdout. Other exits remain command errors.
if (
commandFailure === undefined ||
commandFailure.code !== 1 ||
commandFailure.signal !== null ||
commandFailure.killed ||
commandFailure.outputTruncated ||
commandFailure.collectionFailure === true
)
return started;
stdout = commandFailure.stdout;
stderr = commandFailure.stderr;
capturedOutput = execFileFailureCapturedOutput(commandFailure);
if (exited === undefined || exited.exitCode !== 1) return started;
stdout = exited.stdout.toString("utf8");
stderr = exited.stderr;
capturedOutput = exited.capturedOutput;
// Stderr carries adb transport diagnostics, not the Activity Manager
// report, so it cannot establish a target refusal on this path.
verdict = parseAmStartOutput(stdout);
@@ -2928,7 +2935,7 @@ export class AdbProvider {
private async stopApp(
operation: "stop_adb_app",
selection: AdbBinarySelection,
selection: AdbCommandHost,
client: AdbClientResult,
provider: AdbProviderIdentity,
input: { readonly serial: string; readonly package: string },
@@ -2962,7 +2969,7 @@ export class AdbProvider {
private async captureScreen(
operation: "capture_adb_screen",
selection: AdbBinarySelection,
selection: AdbCommandHost,
client: AdbClientResult,
provider: AdbProviderIdentity,
input: { readonly serial: string; readonly output_directory: string },
@@ -3081,7 +3088,7 @@ export class AdbProvider {
private async collectBugreport(
operation: "collect_adb_bugreport",
selection: AdbBinarySelection,
selection: AdbCommandHost,
client: AdbClientResult,
provider: AdbProviderIdentity,
input: { readonly serial: string; readonly output_directory: string },
+55 -66
View File
@@ -2,81 +2,60 @@ import { createHash } from "node:crypto";
import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { expect, it, onTestFinished, vi } from "vitest";
import { execFileBytes, execFileOutput } from "../process/ExecFileOutput.js";
import { expect, it, onTestFinished } from "vitest";
import { AdbProvider } from "./AdbProvider.js";
vi.mock("../process/ExecFileOutput.js", async (importOriginal) => ({
...(await importOriginal<typeof import("../process/ExecFileOutput.js")>()),
execFileBytes: vi.fn(),
execFileOutput: vi.fn(),
}));
const startup =
"* daemon not running; starting now at tcp:5037\n* daemon started successfully\n";
/**
* A Node adb stand-in: it logs each argv and answers the push workflow's
* commands, keeping a copy of the pushed host file for inspection.
*/
const adbFixture = (
root: string,
digestOutput: string,
): string => `#!${process.execPath}
const { appendFileSync, copyFileSync } = require("node:fs");
const args = process.argv.slice(2);
appendFileSync(${JSON.stringify(join(root, "argv.log"))}, JSON.stringify(args) + "\\n");
const out = (stdout, stderr, code) => {
process.stdout.write(stdout);
process.stderr.write(stderr);
process.exitCode = code;
};
const startup = ${JSON.stringify(startup)};
if (args[0] === "version")
out("Android Debug Bridge version 1.0.41\\nVersion 37.0.0-fixture\\n", "", 0);
else if (args[0] === "start-server") out("", "", 0);
else if (args[2] === "shell" && args[3] === "test" && args[4] === "-d")
out("", startup, 0);
else if (args[2] === "shell" && args[3] === "test" && args[4] === "-e")
out("", startup, 1);
else if (args[2] === "push") {
copyFileSync(args[3], ${JSON.stringify(join(root, "pushed.bin"))});
out("1 file pushed\\n", "", 0);
} else if (args[2] === "shell" && args[3] === "sha256sum")
out(${JSON.stringify(digestOutput)}, "", 0);
else out("", "Unexpected adb fixture command", 2);
`;
it.each([false, true])(
"retains startup probe evidence alongside digest observations (recognized=%s)",
async (recognized) => {
vi.clearAllMocks();
const root = await mkdtemp(join(tmpdir(), "rea-adb-probe-evidence-"));
onTestFinished(() => rm(root, { recursive: true, force: true }));
const source = join(root, "input.bin");
const bytes = Buffer.from("caller-owned bytes");
await writeFile(source, bytes);
const digest = createHash("sha256").update(bytes).digest("hex");
const provider = new AdbProvider({
environment: { REA_ADB_PATH: process.execPath },
});
onTestFinished(() => provider.close());
vi.mocked(execFileOutput).mockImplementation(async (_binary, args) => {
expect(args).toEqual(["version"]);
const stdout =
"Android Debug Bridge version 1.0.41\nVersion 37.0.0-fixture\n";
return {
stdout,
stderr: "",
stdoutBytes: Buffer.byteLength(stdout),
stderrBytes: 0,
};
});
const digestOutput = recognized
? `${digest} /sdcard/receiver/input.bin\n`
: "unrecognized sha256sum fixture output\n";
const commands: string[][] = [];
let staged: string | undefined;
vi.mocked(execFileBytes).mockImplementation(async (_binary, args) => {
const command = [...args];
commands.push(command);
expect(command.slice(0, 2)).toEqual(["-s", "device"]);
if (
command[2] === "shell" &&
command[3] === "test" &&
command[4] === "-d"
)
return { stdout: Buffer.alloc(0), stderr: Buffer.from(startup) };
if (
command[2] === "shell" &&
command[3] === "test" &&
command[4] === "-e"
)
throw Object.assign(new Error("absent"), {
code: 1,
signal: null,
killed: false,
stdout: "",
stderr: startup,
});
if (command[2] === "push") {
staged = command[3];
expect(staged).not.toBe(source);
expect((await readFile(staged!)).equals(bytes)).toBe(true);
return {
stdout: Buffer.from("1 file pushed\n"),
stderr: Buffer.alloc(0),
};
}
if (command[2] === "shell" && command[3] === "sha256sum")
return { stdout: Buffer.from(digestOutput), stderr: Buffer.alloc(0) };
throw new Error("Unexpected adb fixture command");
});
const adb = join(root, "adb");
await writeFile(adb, adbFixture(root, digestOutput), { mode: 0o755 });
const provider = new AdbProvider({ environment: { REA_ADB_PATH: adb } });
onTestFinished(() => provider.close());
const result = await provider.execute({
operation: "push_adb_file",
input: {
@@ -118,14 +97,24 @@ it.each([false, true])(
? {}
: { device_sha256sum: { stdout: digestOutput, stderr: "" } }),
});
expect(commands.map((command) => command.slice(2, 5))).toEqual([
["shell", "test", "-d"],
["shell", "test", "-e"],
["push", staged, "/sdcard/receiver"],
["shell", "sha256sum", "/sdcard/receiver/input.bin"],
const commands = (await readFile(join(root, "argv.log"), "utf8"))
.trim()
.split("\n")
.map((line) => JSON.parse(line) as string[]);
const staged = commands.find((command) => command[2] === "push")?.[3];
expect(commands).toEqual([
["version"],
["start-server"],
["-s", "device", "shell", "test", "-d", "/sdcard/receiver"],
["-s", "device", "shell", "test", "-e", "/sdcard/receiver/input.bin"],
["-s", "device", "push", staged, "/sdcard/receiver"],
["-s", "device", "shell", "sha256sum", "/sdcard/receiver/input.bin"],
]);
expect((await readFile(source)).equals(bytes)).toBe(true);
// adb received a staged copy of the caller's bytes, not the caller's file.
expect(staged).toBeDefined();
expect(staged).not.toBe(source);
expect((await readFile(join(root, "pushed.bin"))).equals(bytes)).toBe(true);
expect((await readFile(source)).equals(bytes)).toBe(true);
await expect(stat(staged!)).rejects.toMatchObject({ code: "ENOENT" });
},
);
+86
View File
@@ -0,0 +1,86 @@
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import {
AnalysisProtocolError,
AnalysisTimeoutError,
cancelledBy,
carriedReason,
} from "../domain/analysisErrorCore.js";
import { err, ok, type Result } from "../domain/result.js";
import { classifyLaunchFailure } from "../process/classifyProviderOutcome.js";
import {
execFileFailureCapturedOutput,
execFileOutput,
ExecFileOutputCancelledError,
execFileOutputFailure,
} from "../process/ExecFileOutput.js";
import { launcherFailureOf } from "../process/launchFailure.js";
import { ADB_BINARY_ENV, type AdbBinarySelection } from "./AdbConfiguration.js";
const START_SERVER_TIMEOUT_MS = 30_000;
const START_SERVER_MAX_OUTPUT_BYTES = 64 * 1024;
/**
* Make sure the adb server is running before device commands, with an
* explicit `adb start-server`.
*
* The adb server is an external shared service: other tools on this host use
* it, and REA never stops it. REA may start it here. Only the `start-server`
* client is supervised; the server it forks leaves the client's process group
* and session, so neither this step nor a device command's owned cleanup
* signals it. A server that is already running is left as it is.
*/
export const startAdbServer = async (
operation: string,
selection: AdbBinarySelection,
signal: AbortSignal | undefined,
): Promise<Result<void, AnalysisError>> => {
try {
await execFileOutput(selection.binary, ["start-server"], {
env: selection.environment,
timeout: START_SERVER_TIMEOUT_MS,
maxBuffer: START_SERVER_MAX_OUTPUT_BYTES,
stopSignal: "SIGTERM",
...(signal === undefined ? {} : { signal }),
});
return ok(undefined);
} catch (cause: unknown) {
const failure = execFileOutputFailure(cause);
const observed = {
diagnostics: { adb_step: "start-server" },
...(failure === undefined
? {}
: { capturedOutput: execFileFailureCapturedOutput(failure) }),
};
if (cause instanceof ExecFileOutputCancelledError)
return err(cancelledBy(operation, carriedReason(cause.cause), observed));
const detail = { cause, ...observed };
if (failure?.code === "ETIMEDOUT")
return err(
new AnalysisTimeoutError(operation, START_SERVER_TIMEOUT_MS, {
...detail,
userMessage: `adb start-server reached its ${String(START_SERVER_TIMEOUT_MS)} ms deadline (deadlineExpired). This release has no runtime override.`,
}),
);
const launch = launcherFailureOf(cause);
if (launch?.kind === "host-exhausted" || launch?.kind === "argument-list")
return err(
classifyLaunchFailure(launch, {
providerId: "adb",
operation,
command: selection.binary,
fixedArguments: true,
selection: ADB_BINARY_ENV,
details: detail,
}),
);
const stderr = failure?.stderr.trim().slice(0, 512) ?? "";
return err(
new AnalysisProtocolError(
stderr === ""
? `adb could not start the adb server for ${operation}`
: `adb could not start the adb server for ${operation}: ${stderr}`,
detail,
),
);
}
};
+45 -59
View File
@@ -1,52 +1,47 @@
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { expect, it, onTestFinished, vi } from "vitest";
import { afterAll, expect, it, onTestFinished } from "vitest";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import {
AnalysisResourceConstraintError,
AnalysisTimeoutError,
} from "../domain/analysisErrorCore.js";
import { execFileOutput } from "../process/ExecFileOutput.js";
import { OwnedCommandFailure } from "../process/OwnedCommand.js";
import { ArtifactResourceScope } from "../resources/index.js";
import { spawnFailure } from "../../tests/support/process/spawnFailure.js";
import { inspectAdbClient } from "./AdbConfiguration.js";
vi.mock("../process/ExecFileOutput.js", async (importOriginal) => {
const actual =
await importOriginal<typeof import("../process/ExecFileOutput.js")>();
return { ...actual, execFileOutput: vi.fn(actual.execFileOutput) };
});
const resources = new ArtifactResourceScope();
afterAll(() => resources.close());
const selection = {
binary: "/host/adb",
pathSource: "environment",
environment: {},
resources,
} as const;
/** The error execFile rejects with when its launcher could not start adb. */
const adbSpawnFailure = (code: string): Error =>
Object.assign(spawnFailure(code, selection.binary), {
spawnFailed: true,
stdout: "",
stderr: "",
signal: null,
killed: false,
});
/** The selected adb whose launch fails with `failure`. */
const launchFailing = (failure: unknown) => ({
...selection,
launcher: async () => {
throw failure;
},
});
/** The host refuses to start adb with this errno. */
const refusedWith = (code: string) =>
launchFailing(spawnFailure(code, selection.binary));
it("reports the fixed adb version-probe deadline", async () => {
vi.mocked(execFileOutput).mockRejectedValueOnce(
Object.assign(new Error("deadline"), {
code: "ETIMEDOUT",
stdout: "",
stderr: "",
signal: null,
killed: true,
}),
);
const failure = await inspectAdbClient(selection).catch(
(cause: unknown) => cause,
);
// The owner's deadline outcome, without waiting out the fixed 10 s probe.
const failure = await inspectAdbClient(
launchFailing(
new OwnedCommandFailure("timeout", "Command deadline elapsed."),
),
).catch((cause: unknown) => cause);
expect(failure).toBeInstanceOf(AnalysisTimeoutError);
const projected = projectAnalysisError(failure as AnalysisTimeoutError);
expect(projected).toMatchObject({
@@ -57,32 +52,24 @@ it("reports the fixed adb version-probe deadline", async () => {
});
it("reports the fixed adb version-output cap", async () => {
let selected: string = selection.binary;
if (process.platform === "win32") {
vi.mocked(execFileOutput).mockRejectedValueOnce(
Object.assign(new Error("too much"), {
code: "ERR_CHILD_PROCESS_STDIO_MAXBUFFER",
stdout: "",
stderr: "",
signal: null,
killed: false,
outputTruncated: true,
}),
);
} else {
let host: Parameters<typeof inspectAdbClient>[0] = launchFailing(
new OwnedCommandFailure(
"output-limit",
"Command diagnostic output exceeded its complete-output budget.",
),
);
if (process.platform !== "win32") {
const root = await mkdtemp(join(tmpdir(), "rea-adb-version-cap-"));
onTestFinished(() => rm(root, { recursive: true, force: true }));
selected = join(root, "adb");
const selected = join(root, "adb");
await writeFile(
selected,
`#!${process.execPath}\nprocess.stdout.write("x".repeat(100_000));\n`,
{ mode: 0o755 },
);
host = { ...selection, binary: selected };
}
const failure = await inspectAdbClient({
...selection,
binary: selected,
}).catch((cause: unknown) => cause);
const failure = await inspectAdbClient(host).catch((cause: unknown) => cause);
const projected = projectAnalysisError(
failure as Parameters<typeof projectAnalysisError>[0],
);
@@ -100,20 +87,20 @@ it("reports the fixed adb version-output cap", async () => {
it.skipIf(process.platform !== "win32")(
"classifies an EACCES execute refusal on Windows",
async () => {
vi.mocked(execFileOutput).mockRejectedValueOnce(adbSpawnFailure("EACCES"));
await expect(inspectAdbClient(selection)).rejects.toMatchObject({
code: "binary_not_executable",
diagnostics: {
selected_binary: selection.binary,
filesystem_error: "EACCES",
await expect(inspectAdbClient(refusedWith("EACCES"))).rejects.toMatchObject(
{
code: "binary_not_executable",
diagnostics: {
selected_binary: selection.binary,
filesystem_error: "EACCES",
},
},
});
);
},
);
it("names an EPERM execute refusal separately from missing permission", async () => {
vi.mocked(execFileOutput).mockRejectedValueOnce(adbSpawnFailure("EPERM"));
await expect(inspectAdbClient(selection)).rejects.toMatchObject({
await expect(inspectAdbClient(refusedWith("EPERM"))).rejects.toMatchObject({
code: "binary_not_executable",
remediation: expect.stringContaining("REA_ADB_PATH") as unknown,
diagnostics: {
@@ -125,8 +112,7 @@ it("names an EPERM execute refusal separately from missing permission", async ()
});
it("names any other not-started spawn errno without an exit code", async () => {
vi.mocked(execFileOutput).mockRejectedValueOnce(adbSpawnFailure("EINVAL"));
const failure = await inspectAdbClient(selection).catch(
const failure = await inspectAdbClient(refusedWith("EINVAL")).catch(
(cause: unknown) => cause,
);
expect(failure).toMatchObject({
@@ -152,8 +138,7 @@ it.each([
] as const)(
"reports a host launch constraint %s through the shared launch owner, not as a fault of the selected path",
async (code, retryable, facts) => {
vi.mocked(execFileOutput).mockRejectedValueOnce(adbSpawnFailure(code));
const failure = await inspectAdbClient(selection).catch(
const failure = await inspectAdbClient(refusedWith(code)).catch(
(cause: unknown) => cause,
);
expect(failure).toBeInstanceOf(AnalysisResourceConstraintError);
@@ -219,6 +204,7 @@ it.skipIf(process.platform === "win32").each([
binary,
pathSource: "environment",
environment: {},
resources,
}),
).toEqual({
version: "35.0.2-stub",
+94 -3
View File
@@ -11,8 +11,8 @@ import {
systemProcessOwnershipHost,
} from "./ProcessOwnershipObservation.js";
import { DarwinProcessOwnershipInspectionError } from "./DarwinProcessRunTokenReader.js";
import { finished } from "node:stream";
import type { Readable, Writable } from "node:stream";
import { finished, Transform, Writable } from "node:stream";
import type { Readable } from "node:stream";
import { pipeline } from "node:stream/promises";
import type {
@@ -40,6 +40,7 @@ import {
waitForAbortableDelay,
} from "./ProviderDeadline.js";
import { errorMessage } from "../kernel/errorMessage.js";
import { launcherFailureOf, type LauncherFailure } from "./launchFailure.js";
/** A short-lived command failed its lifecycle or complete-output contract. */
export class OwnedCommandFailure extends Error {
@@ -121,6 +122,12 @@ interface OwnedCommandLimits {
* stays authoritative; a failing stream is a collection failure.
*/
readonly stdout?: Writable;
/**
* With `stdout`, the most bytes the sink receives. Further output fails the
* command as an output-limit failure, like an exceeded diagnostic budget;
* the sink keeps the bytes it received.
*/
readonly maxStdoutBytes?: number;
/**
* Ask the command to stop before owned cleanup kills its process group,
* for a command that rolls back work it started when signaled.
@@ -198,6 +205,24 @@ function throwCommandPreparationFailure(
throw cause;
}
/**
* Ownership preparation could not start a process it needed, such as the
* macOS ownership helper's compiler, because the host lacked capacity. The
* command cannot start for the same reason, so callers report it as their own
* host-capacity launch failure. Other preparation failures, including a
* missing helper compiler, say nothing about the command's executable.
*/
export const preparationHostCapacityFailure = (
cause: unknown,
): LauncherFailure | undefined => {
const preparation =
cause instanceof OwnedCommandFailure ? cause.preparationFailure : cause;
if (!(preparation instanceof DarwinProcessOwnershipInspectionError))
return undefined;
const launch = launcherFailureOf(preparation.cause);
return launch?.kind === "host-exhausted" ? launch : undefined;
};
/** Execute a single owned process with independent cleanup and bounded diagnostic retention. */
export const runOwnedCommand = async (
spawn: OwnedProviderProcessSpawnOptions,
@@ -342,6 +367,16 @@ const collectOwnedCommand = async (
launched.process.stdout,
limits.stdout,
collectionSignal,
limits.maxStdoutBytes === undefined
? undefined
: {
maxBytes: limits.maxStdoutBytes,
exceeded: () => {
exceeded = true;
if (deadline.interruption === undefined)
outputLimitObservedBeforeInterruption = true;
},
},
);
void consumed.then((failed) => {
processFailure ??= failed;
@@ -620,6 +655,57 @@ const finishCommandInput = (
});
};
/** Bytes an owned command wrote to stdout, kept whole for binary protocols. */
export class OwnedCommandStdoutBytes extends Writable {
readonly #chunks: Buffer[] = [];
#length = 0;
/** The bytes received so far. */
get bytes(): Buffer {
return Buffer.concat(this.#chunks, this.#length);
}
override _write(
chunk: Buffer,
_encoding: BufferEncoding,
callback: (error?: Error | null) => void,
): void {
this.#chunks.push(chunk);
this.#length += chunk.byteLength;
callback();
}
}
/**
* Pass at most `maxBytes` to the sink, report the first byte beyond them, and
* keep draining so the command is stopped by its owner rather than by a full
* pipe.
*/
const stdoutLimit = (limit: {
readonly maxBytes: number;
readonly exceeded: () => void;
}): Transform => {
let passed = 0;
let reported = false;
return new Transform({
transform(chunk: Buffer, _encoding, callback) {
const remaining = limit.maxBytes - passed;
if (chunk.byteLength <= remaining) {
passed += chunk.byteLength;
callback(null, chunk);
return;
}
if (remaining > 0) this.push(chunk.subarray(0, remaining));
passed = limit.maxBytes;
if (!reported) {
reported = true;
limit.exceeded();
}
callback();
},
});
};
/**
* Pipe stdout into its sink until `signal` aborts, which destroys both; settles
* with a failure message, never rejects.
@@ -628,13 +714,18 @@ const consumeStdout = (
stdout: Readable | null,
sink: Writable | undefined,
signal: AbortSignal,
limit?: Parameters<typeof stdoutLimit>[0],
): Promise<string | undefined> => {
if (sink === undefined) return Promise.resolve(undefined);
if (stdout === null) {
sink.destroy();
return Promise.resolve("stdout stream is unavailable");
}
return pipeline(stdout, sink, { signal }).then(
return (
limit === undefined
? pipeline(stdout, sink, { signal })
: pipeline(stdout, stdoutLimit(limit), sink, { signal })
).then(
() => undefined,
(cause: unknown) => `stdout stream failed: ${errorMessage(cause)}`,
);
+8 -1
View File
@@ -57,6 +57,7 @@ it
const adb = await workspace.write(
"adb",
`#!/bin/sh
[ "$1" = start-server ] && exit 0
if [ "$1" = version ]; then printf 'Android Debug Bridge version 1.0.41\\nVersion 34.0.5-cli\\n'; exit 0; fi
if [ "$1" = -s ] && [ "$3" = exec-out ]; then /bin/cat "$(dirname "$0")/frame.png"; exit 0; fi
exit 1
@@ -130,6 +131,7 @@ it.skipIf(process.platform === "win32").each([
const adb = await workspace.write(
"adb",
`#!/bin/sh
[ "$1" = start-server ] && exit 0
root=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
printf '%s\\n' "$3" >> "$root/calls"
if [ "$1" = version ]; then
@@ -193,6 +195,7 @@ it.skipIf(process.platform === "win32")(
const adb = await workspace.write(
"adb",
`#!/bin/sh
[ "$1" = start-server ] && exit 0
root=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
if [ "$1" = version ]; then printf 'Android Debug Bridge version 1.0.41\\nVersion 34.0.5-cli\\n'; exit 0; fi
if [ "$1" = -s ] && [ "$3" = shell ] && [ "$4" = test ]; then
@@ -260,6 +263,7 @@ it.skipIf(process.platform === "win32")(
const file = await workspace.write(
"adb",
`#!/bin/sh
[ "$1" = start-server ] && exit 0
printf 'Android Debug Bridge version 1.0.41\\nVersion 34.0.5-cli\\n'
`,
);
@@ -553,6 +557,7 @@ it.skipIf(process.platform === "win32")(
const adb = await workspace.write(
"adb",
`#!/bin/sh
[ "$1" = start-server ] && exit 0
if [ "$1" = version ]; then
printf 'Android Debug Bridge version 1.0.41\\nVersion 34.0.5-cli\\n'
exit 0
@@ -639,6 +644,7 @@ it.skipIf(process.platform === "win32")(
const adb = await workspace.write(
"adb",
`#!/bin/sh
[ "$1" = start-server ] && exit 0
root=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
printf '%s\\n' "$*" >> "$root/calls"
if [ "$1" = version ]; then
@@ -771,6 +777,7 @@ it.skipIf(process.platform === "win32")(
const adb = await workspace.write(
"adb",
`#!/bin/sh
[ "$1" = start-server ] && exit 0
if [ "$1" = "version" ]; then
printf 'Android Debug Bridge version 1.0.41\\nVersion 34.0.5-cli\\nInstalled as %s\\n' "$0"
exit 0
@@ -809,7 +816,7 @@ it.skipIf(process.platform === "win32")(
"exact-serial device model:Pixel transport_id:18446744073709551615";
const binary = await workspace.write(
"adb",
`#!${process.execPath}\nif(process.argv[2]==='version')process.stdout.write('Android Debug Bridge version 1.0.41\\nVersion 35.0.2-inert\\n');\nelse if(process.argv[2]==='devices'&&process.argv[3]==='-l')process.stdout.write(${JSON.stringify(line + "\n")});\nelse throw Error('No other command authorized');\n`,
`#!${process.execPath}\nif(process.argv[2]==='version')process.stdout.write('Android Debug Bridge version 1.0.41\\nVersion 35.0.2-inert\\n');\nelse if(process.argv[2]==='start-server');\nelse if(process.argv[2]==='devices'&&process.argv[3]==='-l')process.stdout.write(${JSON.stringify(line + "\n")});\nelse throw Error('No other command authorized');\n`,
);
await chmod(binary, 0o755);
const result = await serve(["list-adb-devices", "--json"], {
@@ -57,6 +57,7 @@ for (const scenario of scenarios) {
const binary = await workspace.write(
"adb",
`#!/bin/sh
[ "$1" = start-server ] && exit 0
if [ "$1" = version ]; then
printf 'Android Debug Bridge version 1.0.41\\nVersion 34.0.5-stub\\nInstalled as %s\\n' "$0"
exit 0
@@ -15,26 +15,31 @@ const [repo, binary] = process.argv.slice(1);
const load = (path) => import(pathToFileURL(repo + "/dist/" + path));
const { inspectAdbClient } = await load("adb/AdbConfiguration.js");
const { runAdbCapture } = await load("adb/AdbCommand.js");
const selection = { binary, pathSource: "environment", environment: {} };
const { ArtifactResourceScope } = await load("resources/index.js");
const { primaryAnalysisError } = await load("domain/analysisErrorBase.js");
const resources = new ArtifactResourceScope();
const selection = { binary, pathSource: "environment", environment: {}, resources };
// Under pressure, owned launch preparation may also leave cleanup to retry;
// the report's primary failure is still the host's capacity.
const facts = (error) => {
const primary = primaryAnalysisError(error);
return {
tag: primary._tag,
...(primary.cleanupResources.length === 0 ? {} : { cleanupPending: true }),
resource: primary.resource,
retryable: primary.retryable,
reportedLimits: primary.reportedLimits,
};
};
const probe = () =>
inspectAdbClient(selection).then(
(identity) => ({ version: identity.version }),
(cause) => ({
tag: cause._tag,
resource: cause.resource,
retryable: cause.retryable,
reportedLimits: cause.reportedLimits,
}),
(cause) => facts(cause),
);
const command = () =>
runAdbCapture("adb devices", { device: "serial" }, selection, ["devices"],
{ timeoutMs: 10_000, maxOutputBytes: 1024 }, undefined,
).then((result) => result.ok ? { ok: true } : {
tag: result.error._tag,
resource: result.error.resource,
retryable: result.error.retryable,
reportedLimits: result.error.reportedLimits,
});
).then((result) => result.ok ? { ok: true } : facts(result.error));
const handles = [];
for (let index = 0; index < 128; index += 1) {
try {
@@ -47,6 +52,7 @@ for (let index = 0; index < 128; index += 1) {
if (handles.length === 128) throw new Error("Run under a low descriptor limit");
const pressure = { probe: await probe(), command: await command() };
for (const handle of handles) await handle.close();
await resources.retryCleanup();
const after = { probe: await probe(), command: await command() };
process.stdout.write(JSON.stringify({ pressure, after }));
`;
@@ -80,30 +86,29 @@ exit 0
{ timeout: 30_000, maxBuffer: 1024 * 1024 },
);
// The host refused a launch owned supervision needed: adb itself, ps for
// the Linux ownership baseline, or the macOS ownership helper's compiler.
const capacity = {
tag: "AnalysisResourceConstraintError",
resource: "capacity",
retryable: true,
reportedLimits: {
spawn_error: "EMFILE",
exhausted_resource: "file-descriptors",
command: expect.stringMatching(/(?:^|\/)(?:adb|ps|xcrun)$/u) as unknown,
},
};
// An unhandled child error would exit the process before this report.
expect(stderr).toBe("");
expect(JSON.parse(stdout)).toEqual({
pressure: {
probe: {
tag: "AnalysisResourceConstraintError",
resource: "capacity",
retryable: true,
reportedLimits: {
spawn_error: "EMFILE",
exhausted_resource: "file-descriptors",
command: adb,
},
},
command: {
tag: "AnalysisResourceConstraintError",
resource: "capacity",
retryable: true,
reportedLimits: {
spawn_error: "EMFILE",
exhausted_resource: "file-descriptors",
command: adb,
},
},
probe: capacity,
// On macOS the failed helper preparation leaves its root to remove,
// and the next launch reports that pending cleanup until it succeeds.
command:
process.platform === "darwin"
? expect.objectContaining({ cleanupPending: true })
: capacity,
},
after: { probe: { version: "34.0.5-cli" }, command: { ok: true } },
});
@@ -11,6 +11,7 @@ import { setTimeout as delay } from "node:timers/promises";
import { beforeAll, expect, it, vi } from "vitest";
import {
OwnedCommandFailure,
OwnedCommandStdoutBytes,
runOwnedCommand,
} from "../../../src/process/OwnedCommand.js";
import {
@@ -363,6 +364,28 @@ it("streams stdout beyond the diagnostic budget into a sink and returns after it
});
});
it("collects exact stdout bytes within their limit", async () => {
const stdout = new OwnedCommandStdoutBytes();
await runOwnedCommand(
command("process.stdout.write(Buffer.from([0xff, 0x00, 0x41]))"),
{ timeoutMs: 2_000, diagnosticBytes: 1024, stdout, maxStdoutBytes: 3 },
);
expect([...stdout.bytes]).toEqual([0xff, 0x00, 0x41]);
});
it("stops a command whose stdout exceeds its byte limit as an output-limit failure", async () => {
const stdout = new OwnedCommandStdoutBytes();
const failure = await runOwnedCommand(
command(
'process.stdout.write("a".repeat(64 * 1024)); setInterval(() => {}, 1000)',
),
{ timeoutMs: 10_000, diagnosticBytes: 1024, stdout, maxStdoutBytes: 4 },
).catch((cause: unknown) => cause);
expect(failure).toBeInstanceOf(OwnedCommandFailure);
expect(failure).toMatchObject({ reason: "output-limit" });
expect(stdout.bytes.toString()).toBe("aaaa");
});
it("destroys a sink still finishing when the command deadline elapses", async () => {
const sink = new Writable({
write(_chunk, _encoding, callback) {
@@ -10,26 +10,24 @@ import {
} from "node:fs/promises";
import { basename, dirname, join } from "node:path";
import { afterEach, expect, test, vi } from "vitest";
import { adbDouble } from "../../../support/adb/adbProcessDouble.js";
import { AdbProvider } from "../../../../src/adb/AdbProvider.js";
import { projectAnalysisError } from "../../../../src/domain/analysisErrorProjection.js";
import {
execFileBytes,
execFileOutput,
} from "../../../../src/process/ExecFileOutput.js";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
// Exercise real filesystem publication; the Android process reply is simulated.
vi.mock(
"../../../../src/process/ExecFileOutput.js",
async (importOriginal) => ({
...(await importOriginal<
typeof import("../../../../src/process/ExecFileOutput.js")
>()),
execFileBytes: vi.fn(),
execFileOutput: vi.fn(),
}),
);
vi.mock("../../../../src/adb/AdbProcess.js", async (importOriginal) => ({
...(await importOriginal<
typeof import("../../../../src/adb/AdbProcess.js")
>()),
runAdbProcess: (await import("../../../support/adb/adbProcessDouble.js"))
.runAdbProcessDouble,
}));
// A running adb server makes `adb start-server` a successful no-op.
vi.mock("../../../../src/adb/AdbServer.js", () => ({
startAdbServer: async () => ({ ok: true, value: undefined }),
}));
vi.mock("node:fs/promises", async (importOriginal) => {
const actual = await importOriginal<typeof import("node:fs/promises")>();
return {
@@ -47,17 +45,15 @@ const fixture = async (duringCollection?: (root: string) => Promise<void>) => {
const root = await createTestTempDirectory("rea-adb-bugreport-");
const binary = join(root, "adb");
let reportedPath = "";
vi.mocked(execFileOutput).mockImplementation(async (_binary, args) => {
adbDouble.version.mockImplementation(async (args) => {
expect(args).toEqual(["version"]);
const stdout = `Android Debug Bridge version 1.0.41\nVersion 34.0.5-stub\nInstalled as ${binary}\n`;
return {
stdout,
stderr: "",
stdoutBytes: Buffer.byteLength(stdout),
stderrBytes: 0,
};
});
vi.mocked(execFileBytes).mockImplementation(async (_binary, args) => {
adbDouble.device.mockImplementation(async (args) => {
expect(args.slice(0, 3)).toEqual(["-s", "device", "bugreport"]);
const staging = args[3]!;
reportedPath = join(staging, "bugreport test.zip");
@@ -202,7 +198,7 @@ test("returns staging allocation failures without invoking device collection", a
const result = await f.provider.execute(f.request);
if (result.ok) throw new Error("expected output failure");
expect(result.error._tag).toBe("AnalysisOutputError");
expect(execFileBytes).not.toHaveBeenCalled();
expect(adbDouble.device).not.toHaveBeenCalled();
await f.provider.close();
});
@@ -340,7 +336,7 @@ test("refuses an archive reported outside the owned staging directory", async ()
const f = await fixture();
const existing = join(f.root, "bugreport test.zip");
await writeFile(existing, "existing evidence");
vi.mocked(execFileBytes).mockResolvedValueOnce({
adbDouble.device.mockResolvedValueOnce({
stdout: Buffer.from(`Bug report copied to ${existing}\n`),
stderr: Buffer.alloc(0),
});
@@ -354,7 +350,7 @@ test("refuses an archive reported outside the owned staging directory", async ()
test("preserves the primary protocol failure when staging cleanup also fails", async () => {
const f = await fixture();
vi.mocked(execFileBytes).mockResolvedValueOnce({
adbDouble.device.mockResolvedValueOnce({
stdout: Buffer.from("unsupported completion format\n"),
stderr: Buffer.alloc(0),
});
@@ -1,7 +1,7 @@
import { HOST_PLATFORM } from "../../../../src/platform/HostPlatform.js";
import { readFile, writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";
import { beforeEach, expect, onTestFinished, test, vi } from "vitest";
import { afterAll, beforeEach, expect, onTestFinished, test, vi } from "vitest";
import { runAdbCapture } from "../../../../src/adb/AdbCommand.js";
import {
@@ -17,6 +17,8 @@ import { AdbProvider } from "../../../../src/adb/AdbProvider.js";
import { parseEvidence } from "../../../../src/domain/evidence.js";
import { projectAnalysisError } from "../../../../src/domain/analysisErrorProjection.js";
import { AnalysisTimeoutError } from "../../../../src/domain/analysisErrorCore.js";
import { OwnedCommandFailure } from "../../../../src/process/OwnedCommand.js";
import { ArtifactResourceScope } from "../../../../src/resources/index.js";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
import { waitFor } from "../../../support/testWait.js";
@@ -25,31 +27,16 @@ const hooks = vi.hoisted(() => ({
failure: undefined as unknown,
}));
vi.mock("../../../../src/process/ExecFileOutput.js", async (importOriginal) => {
vi.mock("../../../../src/adb/AdbProcess.js", async (importOriginal) => {
const actual =
await importOriginal<
typeof import("../../../../src/process/ExecFileOutput.js")
>();
await importOriginal<typeof import("../../../../src/adb/AdbProcess.js")>();
return {
...actual,
execFileBytes: async (...args: Parameters<typeof actual.execFileBytes>) => {
runAdbProcess: async (...args: Parameters<typeof actual.runAdbProcess>) => {
try {
return await actual.execFileBytes(...args);
} catch (cause: unknown) {
hooks.failure = cause;
throw cause;
} finally {
hooks.afterCommand?.();
}
},
execFileOutput: async (
...args: Parameters<typeof actual.execFileOutput>
) => {
try {
return await actual.execFileOutput(...args);
} catch (cause: unknown) {
hooks.failure = cause;
throw cause;
const outcome = await actual.runAdbProcess(...args);
if (!outcome.ok) hooks.failure = outcome.failure.cause;
return outcome;
} finally {
hooks.afterCommand?.();
}
@@ -62,6 +49,15 @@ beforeEach(() => {
hooks.failure = undefined;
});
const resources = new ArtifactResourceScope();
afterAll(() => resources.close());
/** The selected adb, retaining unfinished command cleanup in this file's scope. */
const host = async (environment: NodeJS.ProcessEnv) => ({
...(await resolveAdbBinary(environment, HOST_PLATFORM.platform)),
resources,
});
const capture = async (
script: string,
signal?: AbortSignal,
@@ -70,10 +66,7 @@ const capture = async (
runAdbCapture(
"inspect_adb_device",
{ device: "device" },
await resolveAdbBinary(
{ ...process.env, REA_ADB_PATH: process.execPath },
HOST_PLATFORM.platform,
),
await host({ ...process.env, REA_ADB_PATH: process.execPath }),
["-e", script],
limits,
signal,
@@ -122,7 +115,7 @@ test("hands completed bytes to the consuming provider after a late abort", async
await capture("process.stdout.write('observed')", controller.signal),
).toEqual({
ok: true,
value: { stdout: Buffer.from("observed"), stderr: Buffer.alloc(0) },
value: { stdout: Buffer.from("observed"), stderr: "" },
});
});
@@ -143,9 +136,10 @@ test("retains the command owner's exact cancellation reason after active process
const error = await failureOf(pending);
expect(error._tag).toBe("AnalysisCancelledError");
expect(error.cause).toBeNull();
expect(hooks.failure).toBeInstanceOf(OwnedCommandFailure);
expect(hooks.failure).toMatchObject({
_tag: "ExecFileOutputCancelledError",
cause: null,
reason: "cancelled",
cancellation: { reason: null },
});
} finally {
controller.abort(null);
@@ -159,10 +153,7 @@ const clientScript = async (source: string) => {
await writeFile(binary, `#!${process.execPath}\n${source}\n`, {
mode: 0o755,
});
return resolveAdbBinary(
{ ...process.env, REA_ADB_PATH: binary },
HOST_PLATFORM.platform,
);
return host({ ...process.env, REA_ADB_PATH: binary });
};
const nativeClientTest = test.skipIf(process.platform === "win32");
@@ -172,10 +163,7 @@ test.each([null, "caller stopped", new Error("caller stopped")] as const)(
const controller = new AbortController();
controller.abort(reason);
const error: unknown = await inspectAdbClient(
await resolveAdbBinary(
{ REA_ADB_PATH: process.execPath },
HOST_PLATFORM.platform,
),
await host({ REA_ADB_PATH: process.execPath }),
controller.signal,
).catch((cause: unknown) => cause);
expect(error).toMatchObject({
@@ -219,10 +207,7 @@ nativeClientTest(
const controller = new AbortController();
hooks.afterCommand = () => controller.abort(null);
const error: unknown = await inspectAdbClient(
await resolveAdbBinary(
{ REA_ADB_PATH: join(root, "missing") },
HOST_PLATFORM.platform,
),
await host({ REA_ADB_PATH: join(root, "missing") }),
controller.signal,
).catch((cause: unknown) => cause);
expect(error).toMatchObject({
@@ -1,44 +1,40 @@
import { readFile, writeFile, type FileHandle } from "node:fs/promises";
import { join } from "node:path";
import { afterEach, expect, onTestFinished, test, vi } from "vitest";
import { adbDouble } from "../../../support/adb/adbProcessDouble.js";
import { AdbProvider } from "../../../../src/adb/AdbProvider.js";
import * as regularFile from "../../../../src/filesystem/RegularFile.js";
import { OwnedFileHandle } from "../../../../src/filesystem/OwnedFileHandle.js";
import {
execFileBytes,
execFileOutput,
} from "../../../../src/process/ExecFileOutput.js";
import { AnalysisCancelledError } from "../../../../src/domain/analysisErrorCore.js";
import { projectAnalysisError } from "../../../../src/domain/analysisErrorProjection.js";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
vi.mock(
"../../../../src/process/ExecFileOutput.js",
async (importOriginal) => ({
...(await importOriginal<
typeof import("../../../../src/process/ExecFileOutput.js")
>()),
execFileBytes: vi.fn(),
execFileOutput: vi.fn(),
}),
);
vi.mock("../../../../src/adb/AdbProcess.js", async (importOriginal) => ({
...(await importOriginal<
typeof import("../../../../src/adb/AdbProcess.js")
>()),
runAdbProcess: (await import("../../../support/adb/adbProcessDouble.js"))
.runAdbProcessDouble,
}));
// A running adb server makes `adb start-server` a successful no-op.
vi.mock("../../../../src/adb/AdbServer.js", () => ({
startAdbServer: async () => ({ ok: true, value: undefined }),
}));
afterEach(() => vi.restoreAllMocks());
const fixture = async () => {
const root = await createTestTempDirectory("rea-adb-hash-consumer-");
const binary = join(root, "adb");
vi.mocked(execFileOutput).mockImplementation(async () => {
adbDouble.version.mockImplementation(async () => {
const stdout = `Android Debug Bridge version 1.0.41\nVersion 34.0.5-stub\nInstalled as ${binary}\n`;
return {
stdout,
stderr: "",
stdoutBytes: Buffer.byteLength(stdout),
stderrBytes: 0,
};
});
vi.mocked(execFileBytes).mockImplementation(async (_binary, args) => {
adbDouble.device.mockImplementation(async (args) => {
const last = args.at(-1)!;
if (args.includes("pull")) {
await writeFile(last, "pulled bytes");
@@ -2,12 +2,9 @@ import { createHash } from "node:crypto";
import { lstat, open, readFile, rm, writeFile } from "node:fs/promises";
import { basename, dirname, join } from "node:path";
import { afterEach, expect, onTestFinished, test, vi } from "vitest";
import { adbDouble } from "../../../support/adb/adbProcessDouble.js";
import { AdbProvider } from "../../../../src/adb/AdbProvider.js";
import {
execFileBytes,
execFileOutput,
} from "../../../../src/process/ExecFileOutput.js";
import { parseEvidence } from "../../../../src/domain/evidence.js";
import { primaryAnalysisError } from "../../../../src/domain/analysisErrorBase.js";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
@@ -16,16 +13,17 @@ import { AdbInputSnapshotFailure } from "../../../../src/adb/AdbInputSnapshot.js
import { AnalysisOutputError } from "../../../../src/domain/analysisErrorCore.js";
import { OwnedFileHandle } from "../../../../src/filesystem/OwnedFileHandle.js";
vi.mock(
"../../../../src/process/ExecFileOutput.js",
async (importOriginal) => ({
...(await importOriginal<
typeof import("../../../../src/process/ExecFileOutput.js")
>()),
execFileBytes: vi.fn(),
execFileOutput: vi.fn(),
}),
);
vi.mock("../../../../src/adb/AdbProcess.js", async (importOriginal) => ({
...(await importOriginal<
typeof import("../../../../src/adb/AdbProcess.js")
>()),
runAdbProcess: (await import("../../../support/adb/adbProcessDouble.js"))
.runAdbProcessDouble,
}));
// A running adb server makes `adb start-server` a successful no-op.
vi.mock("../../../../src/adb/AdbServer.js", () => ({
startAdbServer: async () => ({ ok: true, value: undefined }),
}));
vi.mock("node:fs/promises", async (importOriginal) => {
const actual = await importOriginal<typeof import("node:fs/promises")>();
return {
@@ -50,26 +48,18 @@ const fixture = async () => {
const output = (stdout: string) => ({
stdout,
stderr: "",
stdoutBytes: Buffer.byteLength(stdout),
stderrBytes: 0,
});
vi.mocked(execFileOutput).mockImplementation(async (_binary, args) => {
adbDouble.version.mockImplementation(async (args) => {
if (args[0] === "version")
return output(
`Android Debug Bridge version 1.0.41\nVersion 34.0.5-stub\nInstalled as ${binary}\n`,
);
throw new Error(`Unexpected ADB fixture command: ${JSON.stringify(args)}`);
});
vi.mocked(execFileBytes).mockImplementation(async (_binary, args) => {
adbDouble.device.mockImplementation(async (args) => {
if (args[2] === "shell" && args[3] === "test" && args[5] === devicePath) {
if (args[4] === "-d")
throw Object.assign(new Error("Selected destination is a file"), {
code: 1,
stdout: "",
stderr: "",
signal: null,
killed: false,
});
// The selected destination is a file.
if (args[4] === "-d") return { exitCode: 1 };
if (args[4] === "-e")
return { stdout: Buffer.alloc(0), stderr: Buffer.alloc(0) };
}
@@ -397,7 +387,7 @@ test.each([
const localPath = join(outputDirectory, "remote.bin");
const pulledBytes = Buffer.from("device bytes");
let closeAttempts = 0;
vi.mocked(execFileBytes).mockImplementation(async (_binary, args) => {
adbDouble.device.mockImplementation(async (args) => {
if (args[2] === "pull") {
await actualFs.writeFile(args[4]!, pulledBytes);
}
@@ -488,17 +478,15 @@ test.each([false, true])(
const reason = new Error("caller cancelled after split digest close");
let closeAttempts = 0;
const version = `Android Debug Bridge version 1.0.41\nVersion 34.0.5-stub\nInstalled as ${f.root}/adb\n`;
vi.mocked(execFileOutput).mockImplementation(async (_binary, args) => {
adbDouble.version.mockImplementation(async (args) => {
if (args[0] === "version")
return {
stdout: version,
stderr: "",
stdoutBytes: Buffer.byteLength(version),
stderrBytes: 0,
};
return { stdout: "", stderr: "", stdoutBytes: 0, stderrBytes: 0 };
});
vi.mocked(execFileBytes).mockImplementation(async (_binary, args) => {
adbDouble.device.mockImplementation(async (args) => {
if (args.includes("path"))
return {
stdout: Buffer.from(
@@ -590,7 +578,7 @@ test("resolves package-directory cleanup on the originating pull error", async (
const outputDirectory = join(f.root, "package-cleanup-output");
const packageDirectory = join(outputDirectory, "com.example.app");
let removeAttempts = 0;
vi.mocked(execFileBytes).mockImplementation(async (_binary, args) => {
adbDouble.device.mockImplementation(async (args) => {
if (args.includes("path"))
return {
stdout: Buffer.from("package:/data/app/com.example.app/base.apk\n"),
@@ -721,8 +709,8 @@ test("cancels after the input snapshot copy and before contacting the device", a
expect(primaryAnalysisError(result.error)._tag).toBe(
"AnalysisCancelledError",
);
expect(execFileOutput).toHaveBeenCalledTimes(1);
expect(execFileBytes).not.toHaveBeenCalled();
expect(adbDouble.version).toHaveBeenCalledTimes(1);
expect(adbDouble.device).not.toHaveBeenCalled();
expect(await readFile(f.source, "utf8")).toBe("immutable payload");
await f.provider.close();
});
@@ -749,7 +737,7 @@ test("reports input snapshot capacity failures before contacting the device", as
if (result.ok) throw new Error("expected snapshot capacity failure");
expect(result.error._tag).toBe("AnalysisOutputError");
expect(result.error.cause).toBe(capacityFailure);
expect(execFileOutput).toHaveBeenCalledTimes(1);
expect(execFileBytes).not.toHaveBeenCalled();
expect(adbDouble.version).toHaveBeenCalledTimes(1);
expect(adbDouble.device).not.toHaveBeenCalled();
await f.provider.close();
});
@@ -2,27 +2,25 @@ import { createHash } from "node:crypto";
import { link, lstat, open, readFile, rm } from "node:fs/promises";
import { basename, dirname, join } from "node:path";
import { afterEach, expect, onTestFinished, test, vi } from "vitest";
import { adbDouble } from "../../../support/adb/adbProcessDouble.js";
import { AdbProvider } from "../../../../src/adb/AdbProvider.js";
import { parseEvidence } from "../../../../src/domain/evidence.js";
import { primaryAnalysisError } from "../../../../src/domain/analysisErrorBase.js";
import {
execFileBytes,
execFileOutput,
} from "../../../../src/process/ExecFileOutput.js";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
import { PrivateRuntimeRoot } from "../../../../src/process/PrivateRuntimeRoot.js";
vi.mock(
"../../../../src/process/ExecFileOutput.js",
async (importOriginal) => ({
...(await importOriginal<
typeof import("../../../../src/process/ExecFileOutput.js")
>()),
execFileBytes: vi.fn(),
execFileOutput: vi.fn(),
}),
);
vi.mock("../../../../src/adb/AdbProcess.js", async (importOriginal) => ({
...(await importOriginal<
typeof import("../../../../src/adb/AdbProcess.js")
>()),
runAdbProcess: (await import("../../../support/adb/adbProcessDouble.js"))
.runAdbProcessDouble,
}));
// A running adb server makes `adb start-server` a successful no-op.
vi.mock("../../../../src/adb/AdbServer.js", () => ({
startAdbServer: async () => ({ ok: true, value: undefined }),
}));
vi.mock("node:fs/promises", async (importOriginal) => {
const actual = await importOriginal<typeof import("node:fs/promises")>();
return {
@@ -39,11 +37,9 @@ const fixture = async () => {
const root = await createTestTempDirectory("rea-adb-screen-cancel-");
const binary = join(root, "adb");
const stdout = `Android Debug Bridge version 1.0.41\nVersion 34.0.5-stub\nInstalled as ${binary}\n`;
vi.mocked(execFileOutput).mockResolvedValue({
adbDouble.version.mockResolvedValue({
stdout,
stderr: "",
stdoutBytes: Buffer.byteLength(stdout),
stderrBytes: 0,
});
const provider = new AdbProvider({ environment: { REA_ADB_PATH: binary } });
onTestFinished(() => provider.close());
@@ -61,7 +57,7 @@ test("does not publish a screen capture cancelled before the commit point", asyn
const f = await fixture();
const controller = new AbortController();
const abortReason = new Error("caller stopped after screencap");
vi.mocked(execFileBytes).mockImplementationOnce(async () => {
adbDouble.device.mockImplementationOnce(async () => {
controller.abort(abortReason);
return { stdout: f.png, stderr: Buffer.alloc(0) };
});
@@ -88,7 +84,7 @@ test("retains a committed screen capture receipt when cancellation arrives after
const f = await fixture();
const controller = new AbortController();
const abortReason = new Error("caller stopped after screen commit");
vi.mocked(execFileBytes).mockResolvedValueOnce({
adbDouble.device.mockResolvedValueOnce({
stdout: f.png,
stderr: Buffer.alloc(0),
});
@@ -149,7 +145,7 @@ test.each([1, 2])(
let rawHandle: Awaited<ReturnType<typeof actualFs.open>> | undefined;
const closeHandleIdentities: Awaited<ReturnType<typeof actualFs.open>>[] =
[];
vi.mocked(execFileBytes).mockResolvedValueOnce({
adbDouble.device.mockResolvedValueOnce({
stdout: f.png,
stderr: Buffer.alloc(0),
});
@@ -249,7 +245,7 @@ test("retains the committed receipt and cleanup observation when cancellation ra
await vi.importActual<typeof import("node:fs/promises")>(
"node:fs/promises",
);
vi.mocked(execFileBytes).mockResolvedValueOnce({
adbDouble.device.mockResolvedValueOnce({
stdout: f.png,
stderr: Buffer.alloc(0),
});
@@ -292,7 +288,7 @@ test("retains the committed receipt and cleanup observation when cancellation ra
test("publishes screen captures when the output filesystem does not support hard links", async () => {
const f = await fixture();
vi.mocked(execFileBytes).mockResolvedValueOnce({
adbDouble.device.mockResolvedValueOnce({
stdout: f.png,
stderr: Buffer.alloc(0),
});
@@ -313,7 +309,7 @@ test("publishes screen captures when the output filesystem does not support hard
test("does not replace a destination created after the initial existence check", async () => {
const f = await fixture();
vi.mocked(execFileBytes).mockResolvedValueOnce({
adbDouble.device.mockResolvedValueOnce({
stdout: f.png,
stderr: Buffer.alloc(0),
});
@@ -342,7 +338,7 @@ test("cancellation after a failed hard link but before exclusive creation does n
const f = await fixture();
const controller = new AbortController();
const abortReason = new Error("caller stopped before exclusive creation");
vi.mocked(execFileBytes).mockResolvedValueOnce({
adbDouble.device.mockResolvedValueOnce({
stdout: f.png,
stderr: Buffer.alloc(0),
});
@@ -381,7 +377,7 @@ test("retains a receipt when cancellation arrives after exclusive output creatio
);
const output = join(f.root, "captures");
const destination = join(output, "screen.png");
vi.mocked(execFileBytes).mockResolvedValueOnce({
adbDouble.device.mockResolvedValueOnce({
stdout: f.png,
stderr: Buffer.alloc(0),
});
@@ -426,7 +422,7 @@ test("closes and retains ownership when exclusive output stat fails", async () =
let statAttempts = 0;
let removeAttempts = 0;
let closeAttempts = 0;
vi.mocked(execFileBytes).mockResolvedValueOnce({
adbDouble.device.mockResolvedValueOnce({
stdout: f.png,
stderr: Buffer.alloc(0),
});
@@ -494,7 +490,7 @@ test("waits for descriptor close before rolling back an incomplete exclusive out
let handleOpen = false;
let closeAttempts = 0;
const removeWhileOpen: string[] = [];
vi.mocked(execFileBytes).mockResolvedValueOnce({
adbDouble.device.mockResolvedValueOnce({
stdout: f.png,
stderr: Buffer.alloc(0),
});
@@ -554,7 +550,7 @@ const exclusiveScreenCloseFixture = async (
const output = join(f.root, "captures");
const destination = join(output, "screen.png");
let closeAttempts = 0;
vi.mocked(execFileBytes).mockResolvedValueOnce({
adbDouble.device.mockResolvedValueOnce({
stdout: f.png,
stderr: Buffer.alloc(0),
});
@@ -717,7 +713,7 @@ test("retains incomplete cleanup on a cancelled capture while keeping cancellati
};
},
});
vi.mocked(execFileBytes).mockResolvedValueOnce({
adbDouble.device.mockResolvedValueOnce({
stdout: f.png,
stderr: Buffer.alloc(0),
});
@@ -37,6 +37,7 @@ it.each(["path", "explicit"] as const)(
printf '%s|%s|%s|%s\\n' "$1" "$ADB_SERVER_SOCKET" "$CALLER_EMPTY" "\${CALLER_ABSENT-unset}" >> "$0.calls"
if [ "$1" = version ]; then
printf 'Android Debug Bridge version 1.0.41\\nVersion 35.0.1-fixture\\nInstalled as %s\\n' "$0"
elif [ "$1" = start-server ]; then :
elif [ "$1" = devices ]; then
printf 'List of devices attached\\n%s device model:fixture transport_id:1\\n' "$ANDROID_SERIAL"
else exit 1; fi
@@ -80,7 +81,7 @@ else exit 1; fi
});
expect(JSON.stringify(result.value)).not.toContain("tcp:localhost:");
expect(await readFile(join(selectedDirectory, "adb.calls"), "utf8")).toBe(
"version|tcp:localhost:5041||unset\ndevices|tcp:localhost:5041||unset\n",
"version|tcp:localhost:5041||unset\nstart-server|tcp:localhost:5041||unset\ndevices|tcp:localhost:5041||unset\n",
);
await expect(
access(join(ambientDirectory, "adb.calls")),
@@ -103,6 +104,7 @@ const fixture = async () => {
await writeFile(
binary,
`#!/bin/sh
[ "$1" = start-server ] && exit 0
if [ "$1" = version ]; then printf 'Android Debug Bridge version 1.0.41\\nVersion 34.0.5-stub\\nInstalled as %s\\n' "$0"; exit 0; fi
if [ "$3" = shell ] && [ "$4" = pm ] && [ "$5" = path ]; then printf 'package:/data/app/fixture/base.apk\\n'; exit 0; fi
if [ "$3" = shell ]; then exit 1; fi
@@ -256,6 +258,7 @@ it.each([true, false])(
await writeFile(
binary,
`#!/bin/sh
[ "$1" = start-server ] && exit 0
if [ "$1" = version ]; then printf 'Android Debug Bridge version 1.0.41\\nVersion 34.0.5-stub\\nInstalled as %s\\n' "$0"; exit 0; fi
if [ "$3" = pull ]; then ${created ? `printf 'partial bytes' > "$5";` : ""} printf 'transfer interrupted\\n' >&2; exit 1; fi
exit 1
@@ -309,6 +312,7 @@ it.each(["file", "symlink"] as const)(
await writeFile(
binary,
`#!/bin/sh
[ "$1" = start-server ] && exit 0
if [ "$1" = version ]; then printf 'Android Debug Bridge version 1.0.41\\nVersion 34.0.5-stub\\nInstalled as %s\\n' "$0"; exit 0; fi
if [ "$3" = pull ]; then printf 'invoked' > "$0.called"; exit 1; fi
exit 1
@@ -0,0 +1,142 @@
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect, onTestFinished, test } from "vitest";
import { AdbProvider } from "../../../../src/adb/AdbProvider.js";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
import { waitFor } from "../../../support/testWait.js";
const posix = test.skipIf(process.platform === "win32");
const alive = (pid: number): boolean => {
try {
process.kill(pid, 0);
return true;
} catch {
return false;
}
};
/**
* A Node adb stand-in. `start-server` forks a detached server, as adb forks
* its daemon into a new session, and records its PID. Device commands log
* their argv, and `shell spawn-child` leaves a detached descendant behind;
* `shell hold` waits until stopped, recording the signal that stopped it.
*/
const adbFixture = async (root: string): Promise<string> => {
const adb = join(root, "adb");
await writeFile(
adb,
`#!${process.execPath}
const { appendFileSync, writeFileSync } = require("node:fs");
const { spawn } = require("node:child_process");
const args = process.argv.slice(2);
const root = ${JSON.stringify(root)};
appendFileSync(root + "/argv.log", args.join(" ") + "\\n");
const detached = (name) => {
const child = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], {
detached: true,
stdio: "ignore",
});
writeFileSync(root + "/" + name + ".pid", String(child.pid));
child.unref();
};
if (args[0] === "version")
process.stdout.write("Android Debug Bridge version 1.0.41\\nVersion 35.0.2-fixture\\n");
else if (args[0] === "start-server") detached("server");
else if (args[0] === "devices")
process.stdout.write("List of devices attached\\nemulator-5554 device transport_id:1\\n");
else if (args.includes("spawn-child")) detached("descendant");
else if (args.includes("hold")) {
process.on("SIGTERM", () => {
writeFileSync(root + "/stopped-by", "SIGTERM");
process.exit(143);
});
writeFileSync(root + "/holding", "");
setInterval(() => {}, 1000);
} else process.exitCode = 1;
`,
{ mode: 0o755 },
);
return adb;
};
const fixture = async () => {
const root = await createTestTempDirectory("rea-adb-server-lifetime-");
const adb = await adbFixture(root);
const provider = new AdbProvider({ environment: { REA_ADB_PATH: adb } });
onTestFinished(async () => {
await provider.close();
for (const name of ["server", "descendant"])
try {
process.kill(
Number(await readFile(join(root, `${name}.pid`), "utf8")),
"SIGKILL",
);
} catch {
// Not started, or already stopped.
}
});
return { root, provider };
};
posix(
"starts the adb server explicitly before device commands and never stops it",
async () => {
const { root, provider } = await fixture();
const result = await provider.execute({
operation: "list_adb_devices",
input: {},
});
if (!result.ok) throw result.error;
expect(
(await readFile(join(root, "argv.log"), "utf8")).split("\n"),
).toEqual(["version", "start-server", "devices -l", ""]);
const server = Number(await readFile(join(root, "server.pid"), "utf8"));
// The device command's owned cleanup has finished; the server REA
// started is an external shared service and keeps running.
expect(alive(server)).toBe(true);
await provider.close();
expect(alive(server)).toBe(true);
},
);
posix(
"stops a descendant a device command leaves behind with the command's cleanup",
async () => {
const { root, provider } = await fixture();
await provider.execute({
operation: "inspect_adb_package",
input: { serial: "emulator-5554", package: "spawn-child" },
});
const descendant = Number(
await readFile(join(root, "descendant.pid"), "utf8"),
);
await waitFor(() => expect(alive(descendant)).toBe(false));
},
);
posix(
"asks a cancelled device command to stop with SIGTERM before its group is killed",
async () => {
const { root, provider } = await fixture();
const controller = new AbortController();
const pending = provider.execute(
{
operation: "inspect_adb_package",
input: { serial: "emulator-5554", package: "hold" },
},
{ signal: controller.signal },
);
await waitFor(async () =>
expect(await readFile(join(root, "holding"), "utf8")).toBe(""),
);
controller.abort("caller stopped");
const result = await pending;
expect(result).toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError" },
});
expect(await readFile(join(root, "stopped-by"), "utf8")).toBe("SIGTERM");
},
);
+11 -14
View File
@@ -1,23 +1,22 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { expect, it, onTestFinished, vi } from "vitest";
import { adbDouble } from "../support/adb/adbProcessDouble.js";
import { AdbProvider } from "../../src/adb/AdbProvider.js";
import { parseEvidence } from "../../src/domain/evidence.js";
import { createServer } from "../../src/server/createServer.js";
import { createTestBinarySession } from "../fixtures/binarySession.js";
import {
execFileBytes,
execFileOutput,
} from "../../src/process/ExecFileOutput.js";
import { toolContract } from "../../src/contracts/toolContracts.js";
import { createMcpSchemaValidation } from "../fixtures/mcpSchemaValidation.js";
vi.mock("../../src/process/ExecFileOutput.js", async (importOriginal) => ({
...(await importOriginal<
typeof import("../../src/process/ExecFileOutput.js")
>()),
execFileOutput: vi.fn(),
execFileBytes: vi.fn(),
vi.mock("../../src/adb/AdbProcess.js", async (importOriginal) => ({
...(await importOriginal<typeof import("../../src/adb/AdbProcess.js")>()),
runAdbProcess: (await import("../support/adb/adbProcessDouble.js"))
.runAdbProcessDouble,
}));
// A running adb server makes `adb start-server` a successful no-op.
vi.mock("../../src/adb/AdbServer.js", () => ({
startAdbServer: async () => ({ ok: true, value: undefined }),
}));
it.each(["start_adb_app", "start_adb_activity"] as const)(
@@ -29,14 +28,12 @@ it.each(["start_adb_app", "start_adb_activity"] as const)(
let stderr = "";
const version =
"Android Debug Bridge version 1.0.41\nVersion 34.0.5-stub\n";
vi.mocked(execFileOutput).mockResolvedValue({
adbDouble.version.mockResolvedValue({
stdout: version,
stderr: "",
stdoutBytes: Buffer.byteLength(version),
stderrBytes: 0,
});
const calls: string[][] = [];
vi.mocked(execFileBytes).mockImplementation(async (_binary, args) => {
adbDouble.device.mockImplementation(async (args) => {
calls.push([...args]);
return args.includes("resolve-activity")
? {
+71
View File
@@ -0,0 +1,71 @@
import { vi } from "vitest";
import type { AdbRunOutcome } from "../../../src/adb/AdbProcess.js";
/** What a scripted adb run printed and how it exited (0 unless given). */
export interface AdbDoubleRun {
readonly stdout?: Buffer | string;
readonly stderr?: Buffer | string;
readonly exitCode?: number;
}
type AdbDoubleCommand = (
arguments_: readonly string[],
) => Promise<AdbDoubleRun>;
/**
* Scripted adb runs for provider tests that exercise publication, snapshot
* and cleanup ownership rather than process supervision. `version` answers
* the client probe; `device` answers every device command. A rejection is a
* run that failed without exiting.
*/
export const adbDouble = {
version: vi.fn<AdbDoubleCommand>(),
device: vi.fn<AdbDoubleCommand>(),
};
const bytes = (value: Buffer | string | undefined): Buffer =>
Buffer.isBuffer(value) ? value : Buffer.from(value ?? "");
/** Replaces `runAdbProcess` through `vi.mock` of `src/adb/AdbProcess.js`. */
export const runAdbProcessDouble = async (
_host: unknown,
arguments_: readonly string[],
): Promise<AdbRunOutcome> => {
const command =
arguments_[0] === "version" ? adbDouble.version : adbDouble.device;
try {
const run = await command(arguments_);
const stdout = bytes(run.stdout);
const stderr = bytes(run.stderr);
const exitCode = run.exitCode ?? 0;
return {
ok: true,
run: {
stdout,
stderr: stderr.toString("utf8"),
exitCode,
capturedOutput: {
stdout: stdout.toString("utf8"),
stderr: stderr.toString("utf8"),
stdout_bytes: stdout.byteLength,
stderr_bytes: stderr.byteLength,
exit_code: exitCode,
signal: null,
truncated: false,
},
},
};
} catch (cause: unknown) {
return {
ok: false,
failure: {
cause,
command: undefined,
launch: undefined,
capturedOutput: undefined,
exited: undefined,
},
};
}
};
@@ -171,12 +171,24 @@ export const PROVIDER_LIFECYCLE_COVERAGE: Readonly<
"src/adb/AdbProvider.test.ts",
"reports cancellation arriving during the version probe",
),
test(
"tests/boundary/providers/adb/adbServerLifetime.test.ts",
"asks a cancelled device command to stop with SIGTERM before its group is killed",
),
),
cleanup: covered(
test(
"src/adb/AdbProvider.test.ts",
"retains failed snapshot cleanup with completed push Evidence until close retries",
),
test(
"tests/boundary/providers/adb/adbServerLifetime.test.ts",
"stops a descendant a device command leaves behind with the command's cleanup",
),
test(
"tests/boundary/providers/adb/adbServerLifetime.test.ts",
"starts the adb server explicitly before device commands and never stops it",
),
),
retry: covered(
test(