Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 13 additions & 4 deletions packages/daemon-client/src/__tests__/index-lease-admission.test.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,20 @@
import http from 'node:http';
import path from 'node:path';
import { expect, test } from 'vitest';
import { closeLoopbackServer, listenOnLoopback, mkdtempForTestSync } from '@agent-device/test-kit';
import {
closeLoopbackServer,
createTestHostEnvironment,
listenOnLoopback,
mkdtempForTestSync,
} from '@agent-device/test-kit';
import { DAEMON_HTTP_INSTANCE_MISMATCH_HEADER } from '@agent-device/contracts/daemon-http';
import { sendToDaemon } from '../index.ts';
import { LeaseAdmissionUnsupportedError } from '@agent-device/daemon-contracts/daemon-resolution';
import { createEnsuredDaemonTransport } from '../index.ts';

// A request whose reused lease no heartbeat checked reads `lease-admission` from the `/health` gate
// it already passes, so it costs `/health` and `/rpc` and nothing more. Without the capability it is
// refused before the send, so the caller can fall back to its heartbeat.
// refused before the send. The CLI falls back to its heartbeat on that refusal's class alone, so
// these requests go through the CLI's transport.

const LEASE_ADMISSION = ['script-artifacts', 'lease-admission'];

Expand All @@ -29,7 +36,7 @@ async function sendAdmissionChecked(
});
const root = mkdtempForTestSync('lease-admission-');
try {
const result = await sendToDaemon(
const result = await createEnsuredDaemonTransport({ host: createTestHostEnvironment() })(
{
command: 'snapshot',
session: 'remote',
Expand Down Expand Up @@ -88,6 +95,7 @@ test.each([
])('a $name is refused before the send', async ({ health }) => {
const { result, routes } = await sendAdmissionChecked(() => health);

expect(result).toBeInstanceOf(LeaseAdmissionUnsupportedError);
expect(result).toMatchObject({
code: 'UNSUPPORTED_OPERATION',
details: { reason: 'lease_admission_unsupported', daemonRequestSent: false, dispatched: 'no' },
Expand Down Expand Up @@ -116,6 +124,7 @@ test.each([
},
);

expect(result).toBeInstanceOf(LeaseAdmissionUnsupportedError);
expect(result).toMatchObject({
details: { reason: 'lease_admission_unsupported', daemonRequestSent: false, dispatched: 'no' },
});
Expand Down
212 changes: 46 additions & 166 deletions src/__tests__/cli-lease-admission-proxy.test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import assert from 'node:assert/strict';
import fs from 'node:fs';
import http from 'node:http';
import path from 'node:path';
import { test } from 'vitest';
import { createDaemonProxyServer } from '@agent-device/proxy';
import { DAEMON_HTTP_INSTANCE_MISMATCH_HEADER } from '@agent-device/contracts/daemon-http';
import {
closeLoopbackServer,
listenOnLoopback,
Expand Down Expand Up @@ -36,42 +34,18 @@ const LEASE_SCOPE = {

test('a lease the daemon dropped is reallocated through the proxy without a heartbeat', async (t) => {
if (await skipWhenLoopbackUnavailable(t)) return;
const { root, home, project } = makeTempWorkspace();
const daemon = await startPublicDaemonRuntime({
serverMode: 'http',
env: { AGENT_DEVICE_ANDROID_DEVICE_ALLOWLIST: 'emulator-9999' },
});
const upstream: string[] = [];
const proxy = createDaemonProxyServer({
upstreamBaseUrl: daemon.baseUrl,
upstreamToken: daemon.runtime.token,
clientToken: 'client-secret',
upstreamFetch: async (request) => {
upstream.push(await describe(request));
return await fetch(request);
},
});
try {
const baseUrl = `http://127.0.0.1:${await listenOnLoopback(proxy)}/agent-device`;
await withProxiedDaemon(async ({ baseUrl, project, stateDir, upstream, cli }) => {
const client = createAgentDeviceClient({
daemonBaseUrl: baseUrl,
daemonAuthToken: 'client-secret',
daemonTransport: 'http',
});
const lease = await client.leases.allocate({ ...LEASE_SCOPE, leaseId: 'b'.repeat(32) });
const stateDir = path.join(root, 'state');
writeConnection(stateDir, project, baseUrl, lease.leaseId);
await client.leases.release({ ...LEASE_SCOPE, leaseId: lease.leaseId });
upstream.length = 0;

const result = await runCliCapture(
['snapshot', '--session', 'agent', '--state-dir', stateDir, '--json'],
{
cwd: project,
env: { HOME: home, AGENT_DEVICE_DAEMON_AUTH_TOKEN: 'client-secret' },
useRealDaemonClient: true,
},
);
const result = await cli(['snapshot']);

const reallocated = readRemoteConnectionState({ stateDir, session: 'agent' })?.leaseId;
assert.ok(reallocated && reallocated !== lease.leaseId, result.stdout);
Expand All @@ -84,35 +58,13 @@ test('a lease the daemon dropped is reallocated through the proxy without a hear
if (result.code !== null) {
assert.notEqual(JSON.parse(result.stdout).error.details?.reason, 'LEASE_NOT_FOUND');
}
} finally {
await closeLoopbackServer(proxy);
await daemon.close();
fs.rmSync(root, { recursive: true, force: true });
}
});
});

// A checked connection keeps the one checked request for a command that checks no lease. A command on
// the connection's reused lease reads `lease-admission` from `/health`, so it goes on `/rpc`.
test('a checked connection sends a reused-lease command health-first and without a heartbeat', async (t) => {
// A reused lease on the connection does not move a command that checks no lease off the checked route.
test('a checked connection sends a command that checks no lease as its one checked request', async (t) => {
if (await skipWhenLoopbackUnavailable(t)) return;
const { root, home, project } = makeTempWorkspace();
const daemon = await startPublicDaemonRuntime({
serverMode: 'http',
env: { AGENT_DEVICE_ANDROID_DEVICE_ALLOWLIST: 'emulator-9999' },
});
const upstream: string[] = [];
const proxy = createDaemonProxyServer({
upstreamBaseUrl: daemon.baseUrl,
upstreamToken: daemon.runtime.token,
clientToken: 'client-secret',
upstreamFetch: async (request) => {
upstream.push(await describe(request));
return await fetch(request);
},
});
try {
const baseUrl = `http://127.0.0.1:${await listenOnLoopback(proxy)}/agent-device`;
const stateDir = path.join(root, 'state');
await withProxiedDaemon(async ({ baseUrl, project, stateDir, upstream, cli }) => {
const remoteConfigPath = path.join(project, 'checked.remote.json');
fs.writeFileSync(
remoteConfigPath,
Expand All @@ -127,136 +79,64 @@ test('a checked connection sends a reused-lease command health-first and without
platform: 'android',
}),
);
const cli = async (argv: string[]) =>
await runCliCapture([...argv, '--session', 'agent', '--state-dir', stateDir, '--json'], {
cwd: project,
env: { HOME: home, AGENT_DEVICE_DAEMON_AUTH_TOKEN: 'client-secret' },
useRealDaemonClient: true,
});
const connected = await cli(['connect', '--remote-config', remoteConfigPath]);
assert.equal(connected.code, null, connected.stdout);
const state = readRemoteConnectionState({ stateDir, session: 'agent' });
assert.ok(state?.daemon?.checkedRpcTarget, connected.stdout);

// The lease comes from the daemon directly, so this process holds no `/health` for the proxy.
const direct = createAgentDeviceClient({
daemonBaseUrl: daemon.baseUrl,
daemonAuthToken: daemon.runtime.token,
daemonTransport: 'http',
});
const lease = await direct.leases.allocate({ ...LEASE_SCOPE, leaseId: 'c'.repeat(32) });
writeRemoteConnectionState({
stateDir,
state: { ...state, leaseId: lease.leaseId, deviceKey: LEASE_SCOPE.deviceKey },
state: { ...state, leaseId: 'c'.repeat(32), deviceKey: LEASE_SCOPE.deviceKey },
});

upstream.length = 0;
const listed = await cli(['session', 'list']);
assert.equal(listed.code, null, listed.stdout);
assert.deepEqual(upstream, ['/rpc/checked session_list']);
});
});

upstream.length = 0;
await cli(['snapshot']);
// No device answers, so the failed command also reads its diagnostics record.
assert.deepEqual(
upstream.filter((route) => !route.startsWith('/sessions/')),
['/health', '/rpc snapshot'],
);
type ProxiedDaemon = Readonly<{
/** The proxy's base URL, which the CLI and the SDK client reach with `client-secret`. */
baseUrl: string;
project: string;
stateDir: string;
/** What the proxy forwarded to the daemon: the path, and for an RPC its method or command. */
upstream: string[];
cli: (argv: string[]) => ReturnType<typeof runCliCapture>;
}>;

/** Runs `run` against a real daemon behind a real proxy, with an empty CLI workspace. */
async function withProxiedDaemon(run: (proxied: ProxiedDaemon) => Promise<void>) {
const { root, home, project } = makeTempWorkspace();
const daemon = await startPublicDaemonRuntime({
serverMode: 'http',
env: { AGENT_DEVICE_ANDROID_DEVICE_ALLOWLIST: 'emulator-9999' },
});
const upstream: string[] = [];
const proxy = createDaemonProxyServer({
upstreamBaseUrl: daemon.baseUrl,
upstreamToken: daemon.runtime.token,
clientToken: 'client-secret',
upstreamFetch: async (request) => {
upstream.push(await describe(request));
return await fetch(request);
},
});
try {
const baseUrl = `http://127.0.0.1:${await listenOnLoopback(proxy)}/agent-device`;
const stateDir = path.join(root, 'state');
const cli = async (argv: string[]) =>
await runCliCapture([...argv, '--session', 'agent', '--state-dir', stateDir, '--json'], {
cwd: project,
env: { HOME: home, AGENT_DEVICE_DAEMON_AUTH_TOKEN: 'client-secret' },
useRealDaemonClient: true,
});
await run({ baseUrl, project, stateDir, upstream, cli });
} finally {
await closeLoopbackServer(proxy);
await daemon.close();
fs.rmSync(root, { recursive: true, force: true });
}
});

// A proxy that names no upstream daemon cannot say whose admission would check the lease: the next
// request carries only the proxy's own instance fence.
test.for([
{ path: 'the first health check', replaced: false, rpcs: ['heartbeat', 'snapshot'] },
// The first send is refused before dispatch for its stale instance, so only the second one runs.
{
path: 'the refresh after an instance mismatch',
replaced: true,
rpcs: ['snapshot', 'heartbeat', 'snapshot'],
},
])(
'a proxy answer with no upstream on $path gets the heartbeat before the command',
async ({ replaced, rpcs }, context) => {
if (await skipWhenLoopbackUnavailable(context)) return;
const { root, home, project } = makeTempWorkspace();
const proxy = await proxyWithoutUpstream(replaced);
try {
const stateDir = path.join(root, 'state');
writeConnection(stateDir, project, proxy.baseUrl, 'd'.repeat(32));

const result = await runCliCapture(
['snapshot', '--session', 'agent', '--state-dir', stateDir, '--json'],
{
cwd: project,
env: { HOME: home, AGENT_DEVICE_DAEMON_AUTH_TOKEN: 'client-secret' },
useRealDaemonClient: true,
},
);

assert.equal(result.code, null, result.stdout);
assert.deepEqual(proxy.rpcs, rpcs);
} finally {
await proxy.close();
fs.rmSync(root, { recursive: true, force: true });
}
},
);

/**
* A remote whose `/health` is a proxy's with a top-level `lease-admission` and no upstream. With
* `replaced`, it first names an upstream daemon and refuses the first RPC for its stale instance.
*/
async function proxyWithoutUpstream(replaced: boolean) {
const capabilities = ['script-artifacts', 'lease-admission'];
let named = replaced;
const rpcs: string[] = [];
const server = http.createServer((req, res) => {
res.setHeader('content-type', 'application/json');
if (req.url === '/health') {
const link = named
? { upstream: { service: 'agent-device-daemon', instanceId: 'daemon-1', capabilities } }
: { capabilities };
res.end(
JSON.stringify({
ok: true,
service: 'agent-device-proxy',
instanceId: named ? 'proxy-1' : 'proxy-2',
...link,
}),
);
return;
}
let body = '';
req.on('data', (chunk) => (body += chunk));
req.on('end', () => {
const { id, method, params } = JSON.parse(body);
rpcs.push(method === 'agent_device.lease.heartbeat' ? 'heartbeat' : params.command);
if (named) {
named = false;
res.statusCode = 409;
res.setHeader(DAEMON_HTTP_INSTANCE_MISMATCH_HEADER, 'true');
const error = { code: -32000, message: 'stale instance' };
res.end(JSON.stringify({ jsonrpc: '2.0', id, error }));
return;
}
const lease = {
leaseId: params.leaseId,
tenantId: LEASE_SCOPE.tenant,
runId: LEASE_SCOPE.runId,
backend: LEASE_SCOPE.leaseBackend,
};
const data =
method === 'agent_device.lease.heartbeat' ? { lease } : { nodes: [], truncated: false };
res.end(JSON.stringify({ jsonrpc: '2.0', id, result: { ok: true, data } }));
});
});
const baseUrl = `http://127.0.0.1:${await listenOnLoopback(server)}`;
return { baseUrl, rpcs, close: () => closeLoopbackServer(server) };
}

async function describe(request: Request): Promise<string> {
Expand Down
Loading
Loading