UNPKG

@luxorai/sandbox

Version:

TypeScript SDK for Luxor Sandbox: cloud sandboxes (microVMs) for AI agents on Luxor Agent Cloud

268 lines • 11.4 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.DataPlaneCredentialManager = exports.DataPlaneEndpointHints = exports.dataPlaneCredentialHeader = void 0; exports.createDataPlaneClient = createDataPlaneClient; exports.warmDataPlaneConnection = warmDataPlaneConnection; exports.warmDataPlaneEndpoints = warmDataPlaneEndpoints; exports.closeDataPlaneConnection = closeDataPlaneConnection; const wkt_1 = require("@bufbuild/protobuf/wkt"); const connect_1 = require("@connectrpc/connect"); const connect_node_1 = require("@connectrpc/connect-node"); const auth_js_1 = require("./auth.js"); const client_metadata_js_1 = require("./client-metadata.js"); const constants_js_1 = require("./constants.js"); const errors_js_1 = require("./errors.js"); const http2_drain_js_1 = require("./http2-drain.js"); const sandbox_pb_js_1 = require("./internal/proto/tenki/sandbox/v1/sandbox_pb.js"); const refused_stream_js_1 = require("./refused-stream.js"); exports.dataPlaneCredentialHeader = "x-tenki-session-cert"; const sharedDataPlaneSessionManagers = new Map(); const dataPlaneSessionManagers = new WeakMap(); 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; } } } } exports.DataPlaneEndpointHints = DataPlaneEndpointHints; 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 ? (0, wkt_1.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 errors_js_1.DataPlaneNotReadyError && !err.terminal) || (err instanceof errors_js_1.InvalidStateError && !(0, errors_js_1.isPausedSessionStateError)(err)); if (!retryable) { this.stopped = true; return; } } const delayMs = Math.max(1_000, (0, constants_js_1.pollBackoffMs)(attempt)); await new Promise((resolve) => setTimeout(resolve, delayMs)); attempt++; } } } exports.DataPlaneCredentialManager = DataPlaneCredentialManager; 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 connect_1.ConnectError(`sandbox: refusing to send a data-plane credential to the wrong destination: credential was minted for another endpoint, not ${endpoint}`, connect_1.Code.PermissionDenied); } if (current.credential) req.header.set(exports.dataPlaneCredentialHeader, current.credential); (0, auth_js_1.setSdkIdentityHeaders)(req.header); (0, client_metadata_js_1.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 http2_drain_js_1.DrainingHttp2SessionManager(origin, http2_drain_js_1.KEEPALIVE_PING_OPTIONS, http2_drain_js_1.DATA_PLANE_SESSION_OPTIONS), key, references: 0, }; sharedDataPlaneSessionManagers.set(key, sharedSessionManager); } sharedSessionManager.references++; const transport = (0, connect_node_1.createGrpcTransport)({ baseUrl: endpoint, interceptors: [refused_stream_js_1.refusedStreamRetry, credentialInterceptor], sessionManager: sharedSessionManager.manager, }); const client = (0, connect_1.createClient)(sandbox_pb_js_1.SandboxSessionDataPlaneService, transport); dataPlaneSessionManagers.set(client, sharedSessionManager); return client; } function validateRequestSession(message, sessionId) { const requested = requestSessionId(message); if (requested && requested !== sessionId) { throw new connect_1.ConnectError(`sandbox: refusing to send a data-plane credential to the wrong destination: request targets session ${requested} on a client credentialed for session ${sessionId}`, connect_1.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; } 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. 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 http2_drain_js_1.DrainingHttp2SessionManager(origin, http2_drain_js_1.KEEPALIVE_PING_OPTIONS, http2_drain_js_1.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(() => { }); } } 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