import { SERVER_POLL_WALL_BUDGET_MS } from "./server-poll-limits.js" /** Fixed internal REST host. Route/auth middleware integration is separate. */ import { randomUUID } from "node:crypto" import { z } from "zod" import type { AuthUser } from "../lib/permissions.js" import { McpError } from "../modules/mcp/security.js" import { createAtomicStorageDurableServerPollSession as createDurableServerPollSession } from "./server-poll-durable-session.js" import { createRestServerPollAuthority, type ServerPollRestAuthorityContext } from "./server-poll-authority.js" import { ServerPollProblem } from "./server-poll-execution-model.js" export interface ServerPollRestContext extends ServerPollRestAuthorityContext { actor?: AuthUser } type Dependencies = { session: typeof createDurableServerPollSession; authority: typeof createRestServerPollAuthority } const snapshotSchema = z.object({ id: z.number().int().positive().safe(), serverId: z.number().int().positive().safe(), polledAt: z.string().datetime(), status: z.enum(["online", "offline"]), latencyMs: z.number().nonnegative().nullable().optional(), rosVersion: z.string().nullable().optional(), boardName: z.string().nullable().optional(), uptime: z.string().nullable().optional(), cpuLoad: z.number().nullable().optional(), freeMemory: z.number().nonnegative().nullable().optional(), totalMemory: z.number().nonnegative().nullable().optional(), identityName: z.string().nullable().optional() }).strict() export type ServerPollRestReply = { statusCode: number; body: Record } function failure(error: unknown): ServerPollRestReply { const code = error instanceof McpError || error instanceof ServerPollProblem ? error.code : "STATE_UNAVAILABLE" const errors: Record = { INVALID_INPUT: [400, "Некорректный запрос полного опроса"], NOT_FOUND: [404, "Server not found"], PERMISSION_DENIED: [403, "Нет актуального права полного опроса"], PROTECTED_OBJECT: [409, "Полный опрос заблокирован защитой"], APPROVAL_REQUIRED: [409, "Полный опрос требует подтверждённого допуска"], STATE_CONFLICT: [409, "Источники или допуск полного опроса изменились"], READ_CANCELLED: [409, "Полный опрос отменён или истёк"], ABORTED: [409, "Полный опрос отменён или истёк"], MUTATION_OUTCOME_UNKNOWN: [502, "Полный опрос завершён не полностью; автоматический повтор запрещён"], VERIFICATION_FAILED: [502, "Результат полного опроса не подтверждён; автоматический повтор запрещён"] } const [statusCode, message] = errors[code] ?? [503, "Состояние полного опроса недоступно; автоматический повтор запрещён"] return { statusCode, body: { error: message } } } function host(deps: Dependencies) { return async (rawServerId: string, rawContext: ServerPollRestContext): Promise => { let timer: ReturnType | undefined, onAbort: (() => void) | undefined const controller = new AbortController() try { const serverId = /^[1-9][0-9]*$/.test(rawServerId) ? Number(rawServerId) : NaN if (!Number.isSafeInteger(serverId)) throw new McpError("INVALID_INPUT", "Некорректный server id", 400) // Freeze the accepted request and JWT before the first async boundary. const actor = rawContext.actor ? structuredClone(rawContext.actor) : undefined if (actor) { Object.freeze(actor.apps); Object.freeze(actor.permissions); Object.freeze(actor) } const context = { authRequired: rawContext.authRequired, acceptedAt: rawContext.acceptedAt, requestId: rawContext.requestId, deadlineAt: rawContext.deadlineAt, signal: rawContext.signal, assertRequestActive: rawContext.assertRequestActive } const signal = context.signal ? AbortSignal.any([context.signal, controller.signal]) : controller.signal const originalAuthority = deps.authority(actor, { ...context, signal }) const authorize: typeof originalAuthority = async (...args) => { context.assertRequestActive?.() const grant = await originalAuthority(...args) context.assertRequestActive?.() return grant } const deadlineAt = Math.min(Date.now() + SERVER_POLL_WALL_BUDGET_MS, context.acceptedAt + SERVER_POLL_WALL_BUDGET_MS, context.deadlineAt ?? Infinity, actor?.expiresAt ?? Infinity) if (!Number.isSafeInteger(deadlineAt) || deadlineAt <= Date.now() || context.deadlineAt !== undefined && !Number.isSafeInteger(context.deadlineAt)) throw new McpError("READ_CANCELLED", "Полный опрос истёк", 409) const request = Object.freeze({ serverId, receiptId: randomUUID() }) const identity = Object.freeze({ kind: "rest" as const, authentication: actor ? "jwt" as const : "local" as const, ownerId: actor?.id ?? "local-operator", executionId: randomUUID(), requestId: context.requestId, issuedAt: actor?.issuedAt ?? context.acceptedAt, expiresAt: deadlineAt }) const stopped = new Promise((_yes, reject) => { onAbort = () => { controller.abort(); reject(new McpError("READ_CANCELLED", "Полный опрос отменён или истёк", 409)) } }) timer = setTimeout(onAbort!, Math.max(1, deadlineAt - Date.now())) context.signal?.addEventListener("abort", onAbort!, { once: true }) const work = Promise.resolve().then(async () => { signal.throwIfAborted() // Metadata-only authorization and 404 precede construction of a session // capable of reading private endpoints or publishing any durable effect. await authorize(request, [serverId], signal); signal.throwIfAborted() const session = deps.session({ request, identity, authorize }) const plan = await session.prepare(signal); signal.throwIfAborted() const receipt = await session.execute(plan, signal); signal.throwIfAborted() if (!receipt.complete || !receipt.maintenanceComplete || !receipt.configurationVerified) throw new McpError("VERIFICATION_FAILED", "Неполный poll receipt", 502) await authorize(request, plan.affectedServerIds, signal); signal.throwIfAborted() const snapshot = snapshotSchema.parse(receipt.snapshot) if (snapshot.serverId !== serverId) throw new McpError("VERIFICATION_FAILED", "Poll snapshot identity drift", 502) // Exact legacy SnapshotRead shape, including nullable offline fields. return { statusCode: 200, body: { id: snapshot.id, serverId: snapshot.serverId, polledAt: snapshot.polledAt, status: snapshot.status, latencyMs: snapshot.latencyMs ?? null, rosVersion: snapshot.rosVersion ?? null, boardName: snapshot.boardName ?? null, uptime: snapshot.uptime ?? null, cpuLoad: snapshot.cpuLoad ?? null, freeMemory: snapshot.freeMemory ?? null, totalMemory: snapshot.totalMemory ?? null, identityName: snapshot.identityName ?? null } } }) if (context.signal?.aborted) onAbort!() return await Promise.race([work, stopped]) } catch (error) { return failure(error) } finally { clearTimeout(timer); if (onAbort) rawContext.signal?.removeEventListener("abort", onAbort); controller.abort() } } } export const executeDurableServerPollRest = host({ session: createDurableServerPollSession, authority: createRestServerPollAuthority }) /** Explicit unit-only trusted composition; never populated from request JSON. */ export const createDurableServerPollRestForTests = (dependencies: Dependencies) => host(dependencies)