import { SERVER_POLL_WALL_BUDGET_MS } from "./server-poll-limits.js" import { createServerPollProductionExecution, createServerPollProductionIo } from "./server-poll-production.js" import { createAtomicServerPollProductionExecution } from "./server-poll-atomic-production.js" import { createServerPartitionMaintenanceLease } from "./server-partition-maintenance-lease.js" import { createSqlServerPollJournal, parseServerPollJournalIdentity, ServerPollJournalConflict, type ServerPollJournalIdentity } from "./server-poll-journal.js" import { pollProblem } from "./server-poll-execution-model.js" import type { ServerPollDependencies, ServerPollPlan, ServerPollRequest } from "./server-poll-execution.js" import { createHolderBoundServerPollStorageJournal, createServerPollStorageJournal } from "./server-poll-storage-journal.js" import { createServerPollBoundaryCoordinator } from "./server-poll-boundary.js" export interface DurableServerPollSessionInput { request:ServerPollRequest /** Accepted trusted REST identity or the actual MCP operation identity. * This private API does not authenticate HTTP, approve a plan or issue grants. */ identity:ServerPollJournalIdentity /** Caller must validate current owner/permissions/global full-server scope, * original credential/generation, protections and cancellation. Required; * it is never replaced by a permissive or process-memory default. */ authorize:ServerPollDependencies["authorize"] } /** Private, unregistered complete assembly. ONE factory owns the maintenance * exclusion AND every production SQL transaction. No caller-supplied pool, * transaction, native transport, journal, signer or lease can split ownership. * Construction/import performs no SQL, native requests or schema provisioning. * The journal/trigger migration must already exist or execution fails closed. */ function durableSession(input:DurableServerPollSessionInput,storageBound:boolean,atomicMaintenance=false) { const request=structuredClone(input.request),identity=parseServerPollJournalIdentity(structuredClone(input.identity)),authorityProvider=input.authorize if(!request||!Number.isSafeInteger(request.serverId)||request.serverId<=0||!/^[a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12}$/i.test(request.receiptId)||typeof input.authorize!=="function"||identity.expiresAt<=identity.issuedAt)pollProblem("INVALID_INPUT","Нужны доверенные request, identity и authority полного poll") // Derive the purpose key once for this private batch. Current access and // generation are still checked at every authority boundary; no admission // decision is cached. The server-owned signer is never serialized/exposed. let signer:Promise<(value:string)=>string>|undefined const proof:ServerPollDependencies["proof"]=async value=>{ const security=await import("../modules/mcp/security.js") signer??=security.privateFingerprinter("server-poll-production-v1") return (await signer)(security.fingerprint(value)) } const authorize:ServerPollDependencies["authorize"]=async(candidate,ids,signal)=>{ if(candidate.serverId!==request.serverId||candidate.receiptId!==request.receiptId)pollProblem("STATE_CONFLICT","Запрос не принадлежит durable poll session") signal?.throwIfAborted() if(Date.now()=identity.expiresAt)pollProblem("PERMISSION_DENIED","Исходная identity poll истекла") const required=[...new Set([request.serverId,...ids])] const grant=await authorityProvider({...request},required,signal) if(!grant.global||required.some(id=>!grant.serverIds.includes(id))||!/^[a-f0-9]{64}$/.test(grant.authorityProof))pollProblem("PERMISSION_DENIED","Требуется полный живой global допуск poll") signal?.throwIfAborted() if(Date.now()>=identity.expiresAt)pollProblem("PERMISSION_DENIED","Исходная identity poll истекла") return grant } const productionIo=createServerPollProductionIo() const boundary=createServerPollBoundaryCoordinator(authorize,request) const lease=createServerPartitionMaintenanceLease({ boundary, connect:productionIo.connect, assertAuthority:async options=>{await authorize(request,options.serverIds,options.signal)}, }) const io={...productionIo,transaction:lease.transaction} const build=(journal:Pick)=>{ const dependencies={...(storageBound?{approvalProtocol:"configuration-epoch-v3" as const}:{}),request,authorize,proof,boundary,io,maintenanceLease:lease.withLease,journal} if(atomicMaintenance){if(!storageBound)pollProblem("STATE_UNAVAILABLE","Atomic maintenance requires durable quota-bound storage");return createAtomicServerPollProductionExecution(dependencies)} return createServerPollProductionExecution(dependencies) } // Preparation has no journal effects. These throwing boundaries make an // accidental unbound execution impossible; they never invent an ACK/claim. const unavailable=async():Promise=>{throw new ServerPollJournalConflict()} const prepare=async(signal?:AbortSignal)=>build({claim:unavailable,intent:unavailable,acknowledge:unavailable,complete:unavailable}).prepare(request,signal) const journalFor=async(raw:ServerPollPlan,mode:"execute"|"read",signal?:AbortSignal)=>{ const plan=structuredClone(raw) if(plan.request.serverId!==request.serverId||plan.request.receiptId!==request.receiptId)pollProblem("STATE_CONFLICT","План не принадлежит durable poll session") const deadlineAt=Math.min(identity.expiresAt,Date.now()+SERVER_POLL_WALL_BUDGET_MS) const assertAuthority=async(context:{plan:ServerPollPlan})=>{ signal?.throwIfAborted() const grant=await authorize(request,context.plan.affectedServerIds,signal) if(grant.authorityProof!==context.plan.authorityProof)pollProblem("STATE_CONFLICT","Полномочия durable poll изменились") } const context={identity,plan} const storageOptions={assertAuthority,deadlineAt,signal} const storage=storageBound?await (mode==="execute" ?createHolderBoundServerPollStorageJournal(context,storageOptions,lease.journalOwner) :createServerPollStorageJournal(context,storageOptions)):undefined const journal=createSqlServerPollJournal(context,{ executionProof:proof,deadlineAt,assertAuthority,storage, }) return {journal,plan} } const execute=async(raw:ServerPollPlan,signal?:AbortSignal)=>{const {journal,plan}=await journalFor(raw,"execute",signal);return build(journal).execute(plan,signal)} const readExisting=async(raw:ServerPollPlan,signal?:AbortSignal)=>{const {journal}=await journalFor(raw,"read",signal);return journal.readExisting()} return {prepare,execute,readExisting} } /** Historical private assembly for the enrolled 0038 fixture; public adapters * must use the quota-bound constructor below after storage enrollment. */ export const createDurableServerPollSession=(input:DurableServerPollSessionInput)=>durableSession(input,false) /** Opt-in quota-bound assembly. Missing storage schema fails closed. */ export const createStorageDurableServerPollSession=(input:DurableServerPollSessionInput)=>durableSession(input,true) /** Fixed quota-bound v4 issuer for public adapters. Legacy constructors retain * their original protocol; existing plans are never grouped automatically. */ export const createAtomicStorageDurableServerPollSession=(input:DurableServerPollSessionInput)=>durableSession(input,true,true)