Files
MikrotikManager/backend/src/services/server-poll-durable-session.ts
T
DenozordecandClaude Opus 5.5 bd48368929 fix(mcp): очередь архивов POLL и проверка прав опроса раз на этап
Опрос держит исключительную блокировку записи разделов на всё время
работы, поэтому воркер успевал архивировать только один источник между
опросами. Теперь воркер разбирает очередь, пока писатель свободен
(каждый архив — прежний цикл из двух транзакций, уступает ждущему
опросу).

Права опроса проверяются свежими в начале этапа, перед каждой
отправкой на RouterOS и перед COMMIT каждой пишущей транзакции данных
или DDL; журнал и чтения используют доказательство не старше 2 с.
Холодный опрос: проверок допуска ~3700 -> 32, операция 19,9 -> 3,2 с.

Тесты: разбор очереди, уступка ждущему опросу, отзыв прав при
удержанных чтениях RouterOS, граница числа проверок; исправлено
устаревшее ожидание двух соединений в варианте с потерей ACK.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-20 02:54:37 +07:00

119 lines
8.7 KiB
TypeScript

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"
import { freshPollAuthorityScope } from "./server-poll-storage.js"
import { coalesceAuthorization } from "../modules/mcp/authorization-stage.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))
}
// Rights are proven fresh at every stage start (prepare/execute/read reset the
// stages), before every RouterOS dispatch and right before the COMMIT of every
// write that changes application data or DDL; one proof serves a whole marked
// boundary. Journal and read boundaries reuse a grant whose check began < 2 s ago;
// a refusal is never reused.
type Grant=Awaited<ReturnType<ServerPollDependencies["authorize"]>>
type Stage={signal?:AbortSignal;proof:ReturnType<typeof coalesceAuthorization<Grant>>}
let stages=new Map<string,Stage>()
const grantFor=(required:number[],signal?:AbortSignal):Promise<Grant>=>{
const key=[...required].sort((a,b)=>a-b).join(",")
let stage=stages.get(key)
if(!stage){const created={signal} as Stage;created.proof=coalesceAuthorization(()=>authorityProvider({...request},[...required],created.signal));stages.set(key,stage=created)}
stage.signal=signal
const boundary=freshPollAuthorityScope()
if(!boundary)return stage.proof.coalesced()
let proven=boundary.get(key) as Promise<Grant>|undefined
if(!proven)boundary.set(key,proven=stage.proof.fresh())
return proven
}
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.issuedAt||Date.now()>=identity.expiresAt)pollProblem("PERMISSION_DENIED","Исходная identity poll истекла")
const required=[...new Set([request.serverId,...ids])]
const grant=await grantFor(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<ServerPollDependencies,"claim"|"intent"|"acknowledge"|"complete">)=>{
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<never>=>{throw new ServerPollJournalConflict()}
const prepare=async(signal?:AbortSignal)=>{stages=new Map();return 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)=>{stages=new Map();const {journal,plan}=await journalFor(raw,"execute",signal);return build(journal).execute(plan,signal)}
const readExisting=async(raw:ServerPollPlan,signal?:AbortSignal)=>{stages=new Map();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)