@luxorai/sandbox
Version:
TypeScript SDK for Luxor Sandbox: cloud sandboxes (microVMs) for AI agents on Luxor Agent Cloud
259 lines • 10.7 kB
JavaScript
import { timestampDate } from "@bufbuild/protobuf/wkt";
import { Code, ConnectError, createClient } from "@connectrpc/connect";
import { createGrpcTransport } from "@connectrpc/connect-node";
import { setSdkIdentityHeaders } from "./auth.js";
import { setClientMetadataHeaders } from "./client-metadata.js";
import { pollBackoffMs } from "./constants.js";
import { DataPlaneNotReadyError, InvalidStateError, isPausedSessionStateError } from "./errors.js";
import { DATA_PLANE_SESSION_OPTIONS, DrainingHttp2SessionManager, KEEPALIVE_PING_OPTIONS } from "./http2-drain.js";
import { SandboxSessionDataPlaneService, } from "./internal/proto/tenki/sandbox/v1/sandbox_pb.js";
import { refusedStreamRetry } from "./refused-stream.js";
export const dataPlaneCredentialHeader = "x-tenki-session-cert";
const sharedDataPlaneSessionManagers = new Map();
const dataPlaneSessionManagers = new WeakMap();
export class DataPlaneEndpointHints {
endpoint = "";
resolving;
current() {
return this.endpoint;
}
remember(endpoint) {
const resolved = endpoint.trim();
if (resolved)
this.endpoint = resolved;
}
clear() {
this.endpoint = "";
}
async resolve(resolveEndpoint) {
for (;;) {
if (this.endpoint)
return this.endpoint;
const owner = !this.resolving;
if (owner) {
this.resolving = resolveEndpoint().then((endpoint) => {
this.remember(endpoint);
return endpoint;
});
}
const resolving = this.resolving;
if (!resolving)
continue;
try {
return await resolving;
}
catch (err) {
if (owner)
throw err;
}
finally {
if (this.resolving === resolving)
this.resolving = undefined;
}
}
}
}
export class DataPlaneCredentialManager {
session;
#credential = "";
// #endpoint is the endpoint #credential was minted for. A data-plane
// credential authorizes one session on one node, so it is only ever handed
// to a client aimed at that endpoint. An empty value means the engine
// returned a credential before the endpoint was known, and the first
// endpoint the session resolves to adopts it.
#endpoint = "";
expiresAt;
timer;
stopped = false;
constructor(session, initial, endpoint = "") {
this.session = session;
this.set(initial, endpoint);
}
current() {
return this.#credential;
}
/** The credential, but only for the endpoint it was minted for. */
currentFor(endpoint) {
if (!this.#credential)
return { credential: "", bound: true };
if (this.#endpoint !== endpoint)
return { bound: false };
return { credential: this.#credential, bound: true };
}
/** Bind an unbound credential to the first endpoint the session resolves to. */
adoptEndpoint(endpoint) {
if (this.#credential && !this.#endpoint)
this.#endpoint = endpoint;
}
set(credential, endpoint = "") {
if (!credential?.credential || this.stopped)
return;
this.#credential = credential.credential;
this.#endpoint = endpoint;
this.expiresAt = credential.expiresAt ? timestampDate(credential.expiresAt) : undefined;
this.schedule();
}
stop() {
this.stopped = true;
if (this.timer)
clearTimeout(this.timer);
}
schedule() {
if (this.stopped || !this.expiresAt)
return;
if (this.timer)
clearTimeout(this.timer);
const remainingMs = this.expiresAt.getTime() - Date.now();
const delayMs = Math.max(1_000, Math.floor(remainingMs / 2));
this.timer = setTimeout(() => void this.renewLoop(), delayMs);
this.timer.unref?.();
}
async renewLoop() {
let attempt = 0;
while (!this.stopped) {
try {
if (await this.session.renewDataPlaneCredential())
return;
}
catch (err) {
// Retry only transient readiness errors; stop on terminal route failure or fatal errors (auth/not-found) instead of spinning forever, and never rethrow out of this fire-and-forget loop.
const retryable = (err instanceof DataPlaneNotReadyError && !err.terminal) ||
(err instanceof InvalidStateError && !isPausedSessionStateError(err));
if (!retryable) {
this.stopped = true;
return;
}
}
const delayMs = Math.max(1_000, pollBackoffMs(attempt));
await new Promise((resolve) => setTimeout(resolve, delayMs));
attempt++;
}
}
}
export function createDataPlaneClient(endpoint, credentials, sessionId, lane) {
// The interceptor is bound to the session and endpoint this client targets.
// A credential minted for another node, or a request naming another session,
// is refused here rather than sent to the wrong destination.
const credentialInterceptor = (next) => async (req) => {
if (!req.stream)
validateRequestSession(req.message, sessionId);
const current = credentials.currentFor(endpoint);
if (!current.bound) {
throw new ConnectError(`sandbox: refusing to send a data-plane credential to the wrong destination: credential was minted for another endpoint, not ${endpoint}`, Code.PermissionDenied);
}
if (current.credential)
req.header.set(dataPlaneCredentialHeader, current.credential);
setSdkIdentityHeaders(req.header);
setClientMetadataHeaders(req.header);
return req.stream ? next({ ...req, message: validateStreamRequests(req.message, sessionId) }) : next(req);
};
// refusedStreamRetry is outermost so a retried attempt re-runs the credential
// interceptor (fresh connection re-applies auth).
const origin = new URL(endpoint).origin;
// Lane 0 is the connection every session on this host shares; higher lanes are extra connections
// that parallel transfers spread one file over, since a single TCP connection caps far clients.
const key = lane === 0 ? origin : `${origin}#lane${lane}`;
let sharedSessionManager = sharedDataPlaneSessionManagers.get(key);
if (!sharedSessionManager) {
sharedSessionManager = {
manager: new DrainingHttp2SessionManager(origin, KEEPALIVE_PING_OPTIONS, DATA_PLANE_SESSION_OPTIONS),
key,
references: 0,
};
sharedDataPlaneSessionManagers.set(key, sharedSessionManager);
}
sharedSessionManager.references++;
const transport = createGrpcTransport({
baseUrl: endpoint,
interceptors: [refusedStreamRetry, credentialInterceptor],
sessionManager: sharedSessionManager.manager,
});
const client = createClient(SandboxSessionDataPlaneService, transport);
dataPlaneSessionManagers.set(client, sharedSessionManager);
return client;
}
function validateRequestSession(message, sessionId) {
const requested = requestSessionId(message);
if (requested && requested !== sessionId) {
throw new ConnectError(`sandbox: refusing to send a data-plane credential to the wrong destination: request targets session ${requested} on a client credentialed for session ${sessionId}`, Code.PermissionDenied);
}
}
async function* validateStreamRequests(messages, sessionId) {
for await (const message of messages) {
validateRequestSession(message, sessionId);
yield message;
}
}
function requestSessionId(message, depth = 3) {
if (typeof message !== "object" || message === null || ArrayBuffer.isView(message))
return undefined;
const direct = message.sessionId;
if (typeof direct === "string" && direct)
return direct;
if (depth <= 0)
return undefined;
for (const value of Object.values(message)) {
if (Array.isArray(value))
continue;
const nested = requestSessionId(value, depth - 1);
if (nested)
return nested;
}
return undefined;
}
export async function warmDataPlaneConnection(client) {
await dataPlaneSessionManagers.get(client)?.manager.connect();
}
const DATA_PLANE_WARM_MAX_ENDPOINTS = 8;
const DATA_PLANE_WARM_HOLD_MS = 30_000;
// Opens the shared connections a session on any of these hosts will reuse; nothing is sent on them.
export function warmDataPlaneEndpoints(endpoints) {
for (const endpoint of endpoints.slice(0, DATA_PLANE_WARM_MAX_ENDPOINTS)) {
let origin;
try {
const url = new URL(endpoint);
if (url.protocol !== "https:")
continue;
origin = url.origin;
}
catch {
continue;
}
let sharedSessionManager = sharedDataPlaneSessionManagers.get(origin);
if (!sharedSessionManager) {
sharedSessionManager = {
manager: new DrainingHttp2SessionManager(origin, KEEPALIVE_PING_OPTIONS, DATA_PLANE_SESSION_OPTIONS),
key: origin,
references: 0,
};
sharedDataPlaneSessionManagers.set(origin, sharedSessionManager);
const warmed = sharedSessionManager;
// Drop a warmed connection no session claimed, as the Go and Python SDKs do.
const timer = setTimeout(() => {
if (warmed.references > 0)
return;
if (sharedDataPlaneSessionManagers.get(origin) === warmed)
sharedDataPlaneSessionManagers.delete(origin);
warmed.manager.abort();
}, DATA_PLANE_WARM_HOLD_MS);
timer.unref?.();
}
void sharedSessionManager.manager.connect().catch(() => { });
}
}
export function closeDataPlaneConnection(client) {
if (!client)
return;
const sharedSessionManager = dataPlaneSessionManagers.get(client);
if (!sharedSessionManager)
return;
dataPlaneSessionManagers.delete(client);
sharedSessionManager.references--;
if (sharedSessionManager.references > 0)
return;
if (sharedDataPlaneSessionManagers.get(sharedSessionManager.key) === sharedSessionManager) {
sharedDataPlaneSessionManagers.delete(sharedSessionManager.key);
}
sharedSessionManager.manager.abort();
}
//# sourceMappingURL=data-plane.js.map