Files
MikrotikManager/backend/src/db/database-source-observation.ts
T

121 lines
7.4 KiB
TypeScript

/** Internal source facts from an authenticated caller-owned RR READ ONLY lease.
* Trusted SQL must honor timeout/signal; its caller owns whole-callback bounds,
* cancellation, destruction and cleanup. This helper never abandons foreign SQL.
* Cluster system identifier + database OID do not distinguish physical clones,
* restores, or database generations. These facts never grant READY/conversion. */
import { z } from "zod"
import { McpError } from "../modules/mcp/security.js"
import type { ProbeStorageSql } from "../services/server-probe-journal-maintenance.js"
export interface DatabaseSourceObservationOptions { deadlineAt: number; signal?: AbortSignal }
export interface DatabaseSourceObservation {
readonly version: 1
readonly source: Readonly<{ systemIdentifier: string; databaseOid: number; databaseName: string; sessionUser: string;
currentUser: string; inRecovery: boolean; serverVersionNum: number }>
readonly snapshot: Readonly<{ backendPid: number; transactionTimestamp: string; snapshot: string }>
readonly ready: false
readonly generationAuthenticated: false
readonly requiresExternalSourceBinding: true
}
const refused = () => new McpError("DATABASE_SOURCE_UNAVAILABLE", "Текущий источник и снимок БД не подтверждены", 503)
const MAX_UINT64 = 18446744073709551615n
function uint64(value: string, positive = false) {
if (!/^(0|[1-9][0-9]{0,19})$/.test(value)) throw refused()
const number = BigInt(value)
if (number > MAX_UINT64 || positive && number === 0n) throw refused()
return number
}
function snapshotText(value: string) {
if (Buffer.byteLength(value, "utf8") > 65536) throw refused()
const parts = value.split(":")
if (parts.length !== 3) throw refused()
const xmin = uint64(parts[0]), xmax = uint64(parts[1])
if (xmin > xmax) throw refused()
const active = parts[2] ? parts[2].split(",") : []
if (active.length > 4096) throw refused()
let previous: bigint | undefined
for (const item of active) {
const xid = uint64(item)
if (xid < xmin || xid >= xmax || previous !== undefined && xid <= previous) throw refused()
previous = xid
}
return value
}
const text = z.string().min(1).max(200)
const rowSchema = z.object({
system_identifier: z.string().max(20), database_oid: z.string().max(10), database_name: text,
session_user: text, current_user: text, in_recovery: z.boolean(), server_version_num: z.string().regex(/^[1-9][0-9]{0,7}$/),
backend_pid: z.number().int().positive().max(2147483647),
transaction_timestamp: z.string().max(128).regex(/^[0-9]{4,6}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]{1,6})?[+-][0-9]{2}(?::[0-9]{2}(?::[0-9]{2})?)?$/),
snapshot: z.string().max(65536), isolation: z.literal("repeatable read"), read_only: z.literal("on"), explicit_transaction: z.literal(true),
}).strict()
// All executable functions and catalogs are qualified. SESSION_USER/CURRENT_USER
// are SQL keywords. No search_path-dependent user function is invoked.
const SOURCE_SQL = `/* database-source-observation:current */ SELECT
control.system_identifier::pg_catalog.text AS system_identifier,d.oid::pg_catalog.text AS database_oid,d.datname::pg_catalog.text AS database_name,
SESSION_USER::pg_catalog.text AS session_user,CURRENT_USER::pg_catalog.text AS current_user,
pg_catalog.pg_is_in_recovery() AS in_recovery,pg_catalog.current_setting('server_version_num') AS server_version_num,
pg_catalog.pg_backend_pid() AS backend_pid,pg_catalog.transaction_timestamp()::pg_catalog.text AS transaction_timestamp,
pg_catalog.pg_current_snapshot()::pg_catalog.text AS snapshot,
pg_catalog.current_setting('transaction_isolation') AS isolation,pg_catalog.current_setting('transaction_read_only') AS read_only,
pg_catalog.transaction_timestamp() OPERATOR(pg_catalog.<) pg_catalog.statement_timestamp() AS explicit_transaction
FROM pg_catalog.pg_database d CROSS JOIN pg_catalog.pg_control_system() control
WHERE d.datname OPERATOR(pg_catalog.=) pg_catalog.current_database() LIMIT 2`
const origins = new WeakMap<DatabaseSourceObservation, { sql: ProbeStorageSql; deadlineAt: number; signal?: AbortSignal }>()
function fence(options: DatabaseSourceObservationOptions) {
if (!Number.isSafeInteger(options.deadlineAt) || Date.now() >= options.deadlineAt || options.signal?.aborted) throw refused()
}
async function read(sql: ProbeStorageSql, options: DatabaseSourceObservationOptions) {
fence(options)
const timeoutMs = Math.max(1, Math.min(10000, options.deadlineAt - Date.now()))
try {
const result = await sql.query(SOURCE_SQL, [], { timeoutMs, signal: options.signal })
fence(options)
if (!result || !Array.isArray(result.rows) || result.rows.length !== 1) throw refused()
const row = rowSchema.parse(result.rows[0])
uint64(row.system_identifier, true)
if (!/^[1-9][0-9]*$/.test(row.database_oid)) throw refused()
const databaseOid = Number(row.database_oid), serverVersionNum = Number(row.server_version_num)
if (!Number.isSafeInteger(databaseOid) || databaseOid > 4294967295 || !Number.isSafeInteger(serverVersionNum)
|| serverVersionNum < 130000 || !Number.isFinite(Date.parse(row.transaction_timestamp))) throw refused()
snapshotText(row.snapshot)
return { source: { systemIdentifier: row.system_identifier, databaseOid, databaseName: row.database_name,
sessionUser: row.session_user, currentUser: row.current_user, inRecovery: row.in_recovery, serverVersionNum },
snapshot: { backendPid: row.backend_pid, transactionTimestamp: row.transaction_timestamp, snapshot: row.snapshot } }
} catch { throw refused() }
}
function equal(left: Awaited<ReturnType<typeof read>>, right: Awaited<ReturnType<typeof read>>) {
if (JSON.stringify(left) !== JSON.stringify(right)) throw refused()
}
/** Repeated genuine source metadata plus exact backend/transaction/snapshot pin.
* Caller owns authorization, checkout, transaction, cleanup and writer/DDL drain. */
export async function captureDatabaseSourceObservation(sql: ProbeStorageSql, rawOptions: DatabaseSourceObservationOptions): Promise<DatabaseSourceObservation> {
const options = { ...rawOptions }
try {
const first = await read(sql, options), second = await read(sql, options)
equal(first, second); fence(options)
const observation: DatabaseSourceObservation = Object.freeze({ version: 1,
source: Object.freeze(first.source), snapshot: Object.freeze(first.snapshot),
ready: false, generationAuthenticated: false, requiresExternalSourceBinding: true })
origins.set(observation, { sql, ...options })
return observation
} catch { throw refused() }
}
/** In-process same-lease verifier for surrounding a fixed data/archive read.
* JSON, copies and observations from another facade cannot establish a binding. */
export async function assertDatabaseSourceObservationCurrent(sql: ProbeStorageSql, expected: DatabaseSourceObservation, options: DatabaseSourceObservationOptions): Promise<void> {
try {
const origin = origins.get(expected)
if (!origin || origin.sql !== sql) throw refused()
const signal = origin.signal && options.signal ? AbortSignal.any([origin.signal, options.signal]) : origin.signal ?? options.signal
const bounded = { deadlineAt: Math.min(origin.deadlineAt, options.deadlineAt), signal }
fence(bounded)
const current = await read(sql, bounded)
equal({ source: expected.source, snapshot: expected.snapshot }, current)
fence(bounded)
} catch { throw refused() }
}