Skip to content
16 changes: 16 additions & 0 deletions docs/HTTP-API.md
Original file line number Diff line number Diff line change
Expand Up @@ -1554,6 +1554,22 @@ agent-device session with an agent on a worker's own tokens. Through a gateway:
agent ended through `close` or `disconnect` answers agent-device's own
`LEASE_NOT_FOUND`, so `close` then `open` works. A heartbeat Simlock cannot
renew for another reason answers `COMMAND_FAILED` with Simlock's message.
- **An unreachable worker answers "try again".** Through a gateway, when the
worker holding the agent's device is not connected, or has reconnected and
the gateway has not read it yet, every request for that device (a command,
heartbeat, `close`, an upload naming the lease, and `devices`) answers
`agent-device is not available on this simlock: the worker holding this
device is not connected to the gateway; try again` with status 503. A
`/rpc` answer carries `details.reason` `WORKER_UNREACHABLE`. Nothing is sent
to the worker and the Simlock lease is untouched; once the worker is back and
read, before the lease ran out, the next request works. A command running
when the connection drops answers the same. The same answer covers a lease
the gateway does not know yet in the first 60 seconds after it starts.
- **A gateway restart keeps the agent's device.** Once the worker reconnects,
the agent's next request of any kind works on the same device, with no
`open`. A lease the agent did not make through this front (another token's,
or one made under another requester) is not picked up. On a worker, a
restart of Simlock still ends the agent-device lease.

What `open` asks Simlock for:

Expand Down
13 changes: 13 additions & 0 deletions src/agent-device/edge.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2037,6 +2037,19 @@ describe("the agent-device front, through the whole worker daemon", () => {
expect(await listed(rig)).toEqual([]);
});

it("on a worker, after a simlock restart, a command for the old lease is not adopted and the next heartbeat answers `LEASE_ENDED_BY_HOST`, as today", async () => {
const first = await setUp();
await granted(first, 1);
const rig = await first.restart();
expect(await listed(rig)).toEqual([hex(1)]);

const answer = await envelopeOf(await runCommand(rig, "snapshot", 1));
// why: a worker has no map entry for the old lease and adopts nothing, so the command is forwarded as before and the heartbeat still ends the lease.
expect(answer.error).toBeUndefined();
expectEndedBySimlock(await envelopeOf(await heartbeat(rig, 1)));
expect(await listed(rig)).toEqual([]);
});

it("after the same restart (same `FakeDriver`, lease still listed), a release for a lease made before the restart answers the agent-device daemon's reply as a success and releases that simlock lease", async () => {
const first = await setUp();
await granted(first, 1);
Expand Down
22 changes: 16 additions & 6 deletions src/agent-device/front/allocate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,14 @@ import { buildHttpSession } from "../../http/dispatcher-session.js";
import { mapError } from "../../http/errors.js";
import type { TokenIdentity } from "../../http/token-store.js";
import type { Clock } from "../../ports/index.js";
import { frontReply, failure, notAvailable, refusal, type FrontReply } from "../shared/replies.js";
import {
frontReply,
failure,
notAvailable,
refusal,
workerUnreachable,
type FrontReply,
} from "../shared/replies.js";
import { validDeviceKey } from "../shared/release-scope.js";
import { leaseCallFields, leaseIdOf, replyData, type RpcRead } from "../shared/rpc.js";
import { addressField, asRecord } from "../shared/selectors.js";
Expand Down Expand Up @@ -91,6 +98,11 @@ function refusalFor(params: Record<string, unknown>): FrontReply | undefined {
return undefined;
}

function holderReply(holder: Awaited<ReturnType<FrontContext["link"]["status"]>>): FrontReply {
if (holder.state === "unreachable") return workerUnreachable();
return notAvailable(holder.state === "unavailable" ? holder.reason : NO_CEILING);
}

function planOf(params: Record<string, unknown>, cap: number | undefined): Plan {
const fields = leaseCallFields(params);
const device =
Expand Down Expand Up @@ -184,6 +196,7 @@ async function requestLease(
};
signal.addEventListener("abort", onAbort, { once: true });
context.map.startWaiting(plan.leaseId);
context.link.asked?.(plan.leaseId);
try {
const grant = await context.dispatch(
"lease.request",
Expand Down Expand Up @@ -275,12 +288,9 @@ export async function allocate(
: frontReply(failure("simlock granted a device with no address; nothing was leased"), call);
}
const holder = await context.link.status(plan.leaseId, identity);
if (holder.state === "unavailable" || holder.leaseMaxTtlMs === undefined) {
if (holder.state !== "running" || holder.leaseMaxTtlMs === undefined) {
await releaseSimlock(context, identity, plan.leaseId);
return frontReply(
notAvailable(holder.state === "unavailable" ? holder.reason : NO_CEILING),
call,
);
return frontReply(holderReply(holder), call);
}
const forwarded = new Request(request.url, {
body: JSON.stringify(forwardedBody(call, plan, address, holder.leaseMaxTtlMs)),
Expand Down
15 changes: 14 additions & 1 deletion src/agent-device/front/devices-filter.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { TokenIdentity } from "../../http/token-store.js";
import { failure, frontReply } from "../shared/replies.js";
import { failure, frontReply, workerUnreachable } from "../shared/replies.js";
import { readBounded, readReply } from "../shared/rpc.js";
import { asRecord } from "../shared/selectors.js";
import { relay, type FrontContext } from "./context.js";
Expand Down Expand Up @@ -41,6 +41,18 @@ export async function filterDevices(
return relay({ response, text: JSON.stringify(body) });
}

// why: one lease the gateway cannot reach makes the whole list unknown, so `devices` answers it rather than a list missing that device.
export async function anyUnreachable(
context: FrontContext,
identity: TokenIdentity,
leases: readonly { readonly leaseId: string }[],
): Promise<boolean> {
for (const lease of leases) {
if ((await context.link.status(lease.leaseId, identity)).state === "unreachable") return true;
}
return false;
}

interface GatewayDevices {
readonly request: Request;
readonly identity: TokenIdentity;
Expand Down Expand Up @@ -101,6 +113,7 @@ export async function devicesThroughGateway(
return frontReply(failure(error.message), read);
}
if (held.length === 0) return emptyList(read);
if (await anyUnreachable(context, identity, held)) return frontReply(workerUnreachable(), read);
const cancel = new AbortController();
const signal = AbortSignal.any([request.signal, cancel.signal]);
const pieces = await Promise.all(
Expand Down
10 changes: 9 additions & 1 deletion src/agent-device/front/front-map.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ interface DeviceFacts {
readonly name?: string;
readonly target?: string;
readonly deviceKey?: string;
// why: an adopted entry was rebuilt after a gateway restart and has no device key until a call names one.
readonly adopted?: boolean;
}

export interface FrontMapEntry extends DeviceFacts {
Expand All @@ -33,7 +35,8 @@ export interface ListedLease {
readonly ttlDeadline: number;
}

interface Held extends DeviceFacts {
interface Held extends Omit<DeviceFacts, "deviceKey"> {
deviceKey?: string;
readonly identity: TokenIdentity;
readonly address: string;
ttlMs: number;
Expand Down Expand Up @@ -80,6 +83,11 @@ export class FrontMap {
.map(([leaseId, held]) => ({ ...held, leaseId }));
}

setDeviceKey(leaseId: string, deviceKey: string): void {
const held = this.#held.get(leaseId);
if (held !== undefined && held.deviceKey === undefined) held.deviceKey = deviceKey;
}

setTtl(leaseId: string, ttlMs: number): void {
const held = this.#held.get(leaseId);
if (held !== undefined) held.ttlMs = ttlMs;
Expand Down
75 changes: 67 additions & 8 deletions src/agent-device/front/front.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
import type { HttpMount } from "../../http/app.js";
import type { TokenIdentity } from "../../http/token-store.js";
import { FRONT_MOUNT, FRONT_PREFIX, LEASE_HEADER } from "../shared/paths.js";
import { failure, frontReply, notAvailable, refusal } from "../shared/replies.js";
import {
failure,
frontReply,
isUnreachableAnswer,
notAvailable,
refusal,
workerUnreachable,
} from "../shared/replies.js";
import { isKnownRoute } from "../shared/routes.js";
import { commandName, asRecord } from "../shared/selectors.js";
import {
Expand All @@ -16,8 +23,9 @@ import {
} from "../shared/rpc.js";
import { allocate } from "./allocate.js";
import { relay, type FrontContext } from "./context.js";
import { devicesThroughGateway, filterDevices } from "./devices-filter.js";
import { anyUnreachable, devicesThroughGateway, filterDevices } from "./devices-filter.js";
import { heartbeat } from "./heartbeat.js";
import type { LinkStatus } from "./host-link.js";
import { release } from "./release.js";
import { checkRequest } from "./request-rules.js";

Expand Down Expand Up @@ -70,6 +78,26 @@ function untilHangUp(signal: AbortSignal, work: Promise<Response | undefined>):

const FAILED_BODY_LOG_CHARS = 500;

// why: `devices` names no lease, so a gateway with no capable worker still answers "try again" when one of the token's own leases is only unreachable.
async function notRunning(
context: FrontContext,
identity: TokenIdentity,
read: RpcRequest,
status: Exclude<LinkStatus, { state: "running" }>,
): Promise<Response> {
if (
status.state === "unavailable" &&
!(
isDevicesCall(read) &&
context.link.readsLeaseHeader &&
(await anyUnreachable(context, identity, context.map.liveOf(identity.requesterId)))
)
) {
return frontReply(notAvailable(status.reason), read);
}
return frontReply(workerUnreachable(), read);
}

async function handleRpc(
context: FrontContext,
request: Request,
Expand All @@ -84,7 +112,7 @@ async function handleRpc(
}
const kind = classifyCall(read.method, read.params);
const status = await context.link.status(leaseOf(kind, read), identity);
if (status.state === "unavailable") return frontReply(notAvailable(status.reason), read);
if (status.state !== "running") return notRunning(context, identity, read, status);
if (kind === "wrapped-lease") {
return frontReply(refusal("refused: send lease calls as lease RPCs"), read);
}
Expand Down Expand Up @@ -138,7 +166,7 @@ async function runCommand(
end();
throw error;
}
return untilBodyEnds(response, end);
return isUnreachableAnswer(response) ? response : untilBodyEnds(response, end);
}

// why: a command counts as running until its body has gone out, since the stream is what the CLI waits on.
Expand Down Expand Up @@ -173,6 +201,13 @@ function untilBodyEnds(response: Response, end: () => void): Response {
});
}

function isDevicesCall(read: RpcRequest): boolean {
return (
methodName(read.method) === "command" &&
commandName(asRecord(read.params)?.["command"]) === "devices"
);
}

// why: agent-device answers `devices` with everything its daemon sees, so the answer is cut down before the CLI gets it.
async function forwardCommand(
context: FrontContext,
Expand All @@ -181,9 +216,7 @@ async function forwardCommand(
read: RpcRequest,
leaseId: string | undefined,
): Promise<Response> {
const isDevices =
methodName(read.method) === "command" &&
commandName(asRecord(read.params)?.["command"]) === "devices";
const isDevices = isDevicesCall(read);
if (isDevices && context.link.readsLeaseHeader) {
return devicesThroughGateway(context, {
forward: (forwarded, held) => passThrough(context, forwarded, identity, read, held),
Expand Down Expand Up @@ -287,12 +320,20 @@ async function routeByHeader(
if (leaseId === undefined) return passThrough(context, request, identity, undefined);
const status = await context.link.status(leaseId, identity);
if (status.state === "unavailable") return frontReply(notAvailable(status.reason), undefined);
if (status.state === "unreachable") return frontReply(workerUnreachable(), undefined);
const response = await passThrough(context, request, identity, undefined, leaseId);
const path = new URL(request.url).pathname.slice(FRONT_PREFIX.length);
const preflight = request.method === "POST" && path === "/upload/preflight";
return preflight && response.ok ? withCallerCredentials(request, response) : response;
}

// why: a request naming a lease is judged by that lease's worker, which may be the one that is gone.
function namesLease(context: FrontContext, request: Request, probe: boolean): boolean {
return (
context.link.readsLeaseHeader && !probe && (request.headers.get(LEASE_HEADER) ?? "") !== ""
);
}

async function handlePlain(
context: FrontContext,
request: Request,
Expand All @@ -301,7 +342,7 @@ async function handlePlain(
const status = await context.link.status();
const path = new URL(request.url).pathname.slice(FRONT_PREFIX.length);
const probe = request.method === "GET" && path === "/health";
if (status.state === "unavailable") {
if (status.state === "unavailable" && !namesLease(context, request, probe)) {
const reply = notAvailable(status.reason);
return frontReply(probe ? { ...reply, status: HEALTH_STATUS } : reply, undefined);
}
Expand All @@ -314,6 +355,23 @@ async function handlePlain(
return routeByHeader(context, request, identity);
}

// why: after a gateway restart the map is empty, so the token's leases are rebuilt from what the gateway knows before any rule reads the map.
function adoptLeases(context: FrontContext, identity: TokenIdentity): void {
for (const lease of context.link.adoptable?.(identity) ?? []) {
if (context.map.get(lease.leaseId) !== undefined) continue;
context.map.add(lease.leaseId, {
address: lease.address,
adopted: true,
deadline: lease.ttlDeadline,
identity,
model: lease.model,
platform: lease.platform,
target: lease.target,
ttlMs: lease.ttlMs,
});
}
}

export function createFront(context: FrontContext): HttpMount {
return {
handle: async (request, identity) => {
Expand All @@ -322,6 +380,7 @@ export function createFront(context: FrontContext): HttpMount {
if (identity.role !== "agent") {
return frontReply(refusal(AGENT_TOKEN_ONLY, 403), isRpc ? { id: null } : undefined);
}
adoptLeases(context, identity);
if (isRpc) return handleRpc(context, request, identity);
return handlePlain(context, request, identity);
},
Expand Down
19 changes: 18 additions & 1 deletion src/agent-device/front/host-link.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,20 @@ export type LinkStatus =
readonly leaseMaxTtlMs?: number;
readonly platforms: readonly AgentDevicePlatform[];
}
| { readonly state: "unavailable"; readonly reason: string };
| { readonly state: "unavailable"; readonly reason: string }
// why: the lease may still exist, but only its worker can say, and the worker is not connected or not yet read.
| { readonly state: "unreachable" };

// why: a lease the front may rebuild an entry for after a gateway restart, with what the entry needs.
export interface AdoptableLease {
readonly leaseId: string;
readonly address: string;
readonly platform: "ios" | "android";
readonly model: string;
readonly target: string;
readonly ttlMs: number;
readonly ttlDeadline: number;
}

export interface HostLink {
// why: only a link that serves many hosts routes non-RPC requests by the lease header and fans out `devices`; a worker never reads the header.
Expand All @@ -18,6 +31,10 @@ export interface HostLink {
readonly leaseRequires?: readonly string[];
status(leaseId?: string, identity?: TokenIdentity): Promise<LinkStatus>;
forward(request: Request, identity: TokenIdentity, leaseId?: string): Promise<Response>;
// why: only a link that serves many hosts adopts leases made before the front's map was empty; a worker's map is in memory and has no entry for a lease it made before a restart, but that lease is ended, not adopted.
adoptable?(identity: TokenIdentity): readonly AdoptableLease[];
// why: a lease the front asked for in this process is its allocate's to keep or release, never to adopt.
asked?(leaseId: string): void;
dispose?(): void;
}

Expand Down
Loading
Loading