93 lines
6.1 KiB
TypeScript
93 lines
6.1 KiB
TypeScript
import { pool } from "../../db/index.js"
|
|
import { captureVerifiedMcpServiceExecution, inspectVerifiedMcpServiceExecution } from "../../services/config-mutation-policy.js"
|
|
import { executeReservedScopedRecovery, validateReservedInverseVerified } from "./routing-community-scoped-recovery.js"
|
|
import { createRoutingReservationStore } from "./routing-reservation-store.js"
|
|
import { fingerprint, McpError } from "./security.js"
|
|
import type { McpPrincipal } from "./store.js"
|
|
import type { RoutingReservedNetworkSession } from "./service-registry.js"
|
|
|
|
export type ReservedRoutingStepOutcome<T> =
|
|
| { kind: "forwardPassed"; forwardResult: T }
|
|
| { kind: "recovered"; forwardResult: T; recoveryResult: Awaited<ReturnType<typeof executeReservedScopedRecovery>> }
|
|
|
|
/** Private runner progress, never serialize this error or its forward result.
|
|
* A confirmed forward configuration does not prove a verified network outcome.
|
|
* An unconfirmed handoff must not re-enter forward or reconstruct a capability. */
|
|
const unconfirmed = new WeakMap<object, { forwardResult: unknown; originalError: unknown }>()
|
|
class ReservedRoutingHandoffUnknown extends McpError {
|
|
constructor(forwardResult: unknown, originalError: unknown) {
|
|
super("MUTATION_OUTCOME_UNKNOWN", "Результат зарезервированного восстановления не подтверждён; повтор запрещён", 409)
|
|
unconfirmed.set(this, { forwardResult, originalError })
|
|
}
|
|
}
|
|
/** Process-local progress only; public JSON and matching error codes confer none. */
|
|
export function hasConfirmedReservedRoutingForward(error: unknown): boolean {
|
|
return typeof error === "object" && error !== null && unconfirmed.has(error)
|
|
}
|
|
|
|
/** Internal composition only; call INSIDE the original runner's active
|
|
* withVerifiedConfigurationChange callback, before changing generic intent.
|
|
* This does not activate applyPlan's reserved dispatch gate or close RT-1. */
|
|
export async function executeReservedRoutingStep<T>(input: {
|
|
reservationId: string; sourceOperationId: string; principal: McpPrincipal;
|
|
forward: (retainNetworkSession: (session: RoutingReservedNetworkSession) => void) => Promise<T>
|
|
}): Promise<ReservedRoutingStepOutcome<T>> {
|
|
const origin = await captureVerifiedMcpServiceExecution()
|
|
const inspect = async () => {
|
|
const metadata = await inspectVerifiedMcpServiceExecution(origin)
|
|
if (metadata.operationId !== input.sourceOperationId || metadata.operationName !== "routing.community.switch" || metadata.operationVersion !== 7 ||
|
|
metadata.serviceName !== "routing.community.scoped" || metadata.stepIndex !== 0 || metadata.phase !== "forward" ||
|
|
fingerprint(metadata.principal) !== fingerprint(input.principal)) throw new McpError("STATE_CONFLICT", "Исходный service step восстановления изменился", 409)
|
|
return metadata
|
|
}
|
|
await inspect()
|
|
const retained: { session?: RoutingReservedNetworkSession } = {}
|
|
let acceptingSession = true
|
|
try {
|
|
let forwardResult: T
|
|
try {
|
|
forwardResult = await input.forward(session => {
|
|
if (!acceptingSession || retained.session || session.readBudget().closed) {
|
|
throw new McpError("STATE_CONFLICT", "Исходный сетевой сеанс уже передан или закрыт", 409)
|
|
}
|
|
retained.session = session
|
|
})
|
|
} catch (error) {
|
|
if (error instanceof McpError && error.code === "MUTATION_OUTCOME_UNKNOWN") {
|
|
// Preserve the spent attempt even if quarantine itself cannot be confirmed.
|
|
await createRoutingReservationStore().markUnknown(input.reservationId, "forward").catch(() => {})
|
|
}
|
|
throw error
|
|
} finally { acceptingSession = false }
|
|
try {
|
|
await inspect()
|
|
const store = createRoutingReservationStore()
|
|
const published = await store.recordForwardOutcome(input.reservationId)
|
|
await inspect()
|
|
if (!published.allocation) return { kind: "forwardPassed", forwardResult }
|
|
if (!retained.session) throw new McpError("STATE_CONFLICT", "Исходный сетевой сеанс возврата недоступен", 409)
|
|
const recoveryResult = await executeReservedScopedRecovery(published.allocation, {
|
|
sourceOperationId: input.sourceOperationId, principal: input.principal, networkSession: retained.session,
|
|
})
|
|
const metadata = await inspect()
|
|
// A returned object alone cannot promote recovery to verified. Re-read the
|
|
// signed ledger and authenticate all three receipts in the same source slot.
|
|
const record = await store.read(input.reservationId, input.principal)
|
|
const row = (await pool.query("SELECT * FROM mcp_scoped_recovery_intents WHERE source_operation_id=$1 AND source_step_index=0 AND reservation_id=$2 AND mode='reserved'", [input.sourceOperationId, input.reservationId])).rows
|
|
if (record.sourceOperationId !== input.sourceOperationId || record.state.forward !== "spent" || record.state.inverse !== "spent" || record.state.outcome?.status !== "failed" || record.sharedSlotQuarantined ||
|
|
row.length !== 1 || row[0].state !== "verified" || row[0].verified_proof !== recoveryResult.recoveryCheckpointProof ||
|
|
recoveryResult.outcome !== "recovered" || recoveryResult.configurationVerified !== true || recoveryResult.controlProbeVerified !== true || recoveryResult.nativeWrites !== 1 ||
|
|
!await validateReservedInverseVerified(row[0], { reservationId: input.reservationId, sourceOperationId: input.sourceOperationId,
|
|
sourceReceiptId: String(metadata.serviceInput.receiptId), inverseReceiptId: String(recoveryResult.receiptId), deadline: record.deadline,
|
|
configurationProof: record.state.outcome.configurationProof, networkProof: record.state.outcome.networkProof })) {
|
|
throw new McpError("MUTATION_OUTCOME_UNKNOWN", "Подписанная квитанция inverse не подтверждена", 409)
|
|
}
|
|
await inspect()
|
|
return { kind: "recovered", forwardResult, recoveryResult }
|
|
} catch (error) {
|
|
// No retry, refund, replacement allocation or synthetic source checkpoint.
|
|
throw new ReservedRoutingHandoffUnknown(forwardResult, error)
|
|
}
|
|
} finally { retained.session?.close() }
|
|
}
|