Files
MikrotikManager/backend/src/services/traffic-flow-settings-store.ts
T

87 lines
6.3 KiB
TypeScript

import { isDeepStrictEqual } from "node:util"
import type { Pool, PoolClient } from "pg"
import type { FlowSettingsConfiguration, FlowSettingsPhase } from "./traffic-flow-settings-execution.js"
const aliases = {
collector_ip: "collectorIp", flow_listen_port: "flowListenPort", wg_listen_port: "wgListenPort",
public_endpoint: "publicEndpoint", host_public_key: "hostPublicKey", host_private_key: "hostPrivateKey",
hub_server_id: "hubServerId", retention_hours: "retentionHours", top_n: "topN",
map_service_min_share_pct: "mapServiceMinSharePct", peers_json: "peersJson", created_at: "createdAt",
} as const
const telemetry = ["last_datagram_at", "last_exporter_ip", "last_error", "packets_received", "updated_at"]
const mutable = new Map(Object.entries({ enabled: "enabled", prefix: "prefix", ...aliases }).filter(([key]) => key !== "created_at").map(([column, field]) => [field, column]))
export function flowSettingsConfiguration(raw: Record<string, unknown>): FlowSettingsConfiguration {
const value: Record<string, unknown> = {}
for (const [key, item] of Object.entries(raw)) {
if (!telemetry.includes(key)) {
const target = Object.hasOwn(aliases, key) ? aliases[key as keyof typeof aliases] : key
if (Object.hasOwn(value, target)) throw new Error("Ambiguous NetFlow configuration columns")
Object.defineProperty(value, target, { value: structuredClone(item), writable: true, enumerable: true, configurable: true })
}
}
if (value.id !== 1 || typeof value.hostPublicKey !== "string" || typeof value.hostPrivateKey !== "string") throw new Error("NetFlow configuration is missing or invalid")
return value as FlowSettingsConfiguration
}
function rawConfiguration(value: FlowSettingsConfiguration) {
const reverse = new Map(Object.entries(aliases).map(([column, field]) => [field as string, column]))
return Object.fromEntries(Object.entries(value).map(([field, item]) => [reverse.get(field) ?? field, item]))
}
const projection = `to_jsonb(s) - ARRAY['last_datagram_at','last_exporter_ip','last_error','packets_received','updated_at']::text[]`
const conflict = () => Object.assign(new Error("Настройки NetFlow или квитанция изменились; повтор запрещён"), { statusCode: 409 })
type Database = Pick<Pool, "connect" | "query">
/** This store never creates settings on a read, never retries a write and keeps
* unknown future columns in the complete CAS comparison. A receipt claim is a
* permanent tombstone even if COMMIT or listener acknowledgement is lost. */
export function createFlowSettingsStore(database: Database, authorize: () => Promise<unknown>, invalidate: () => void) {
const read = async (client: Pick<PoolClient, "query"> = database): Promise<FlowSettingsConfiguration> => {
await authorize()
const rows = (await client.query(`SELECT CASE WHEN octet_length((${projection})::text)<=262144 THEN ${projection} ELSE NULL END AS configuration FROM traffic_flow_settings s WHERE id=1`)).rows
await authorize()
if (rows.length !== 1 || !rows[0].configuration) throw conflict()
return flowSettingsConfiguration(rows[0].configuration)
}
const claim = async (receiptId: string, phase: FlowSettingsPhase, proof: string) => {
await authorize()
const result = await database.query("INSERT INTO flow_settings_intents(receipt_id,phase,request_proof) VALUES($1,$2,$3) ON CONFLICT DO NOTHING RETURNING phase", [receiptId, phase, proof])
if (result.rows.length !== 1) throw conflict()
await authorize()
}
const compareAndSet = async (receiptId: string, proof: string, expected: FlowSettingsConfiguration, desired: FlowSettingsConfiguration) => {
const changes = Object.keys(desired).filter(key => !isDeepStrictEqual(expected[key], desired[key]))
if (Object.keys(expected).some(key => !(key in desired)) || changes.some(key => !mutable.has(key))) throw conflict()
// jsonb_populate_record decodes each known column using its actual SQL type.
const desiredRaw = rawConfiguration(desired)
const values = [JSON.stringify(desiredRaw), JSON.stringify(rawConfiguration(expected))]
const assignments = changes.map(key => `${mutable.get(key)}=d.${mutable.get(key)}`)
assignments.push("updated_at=now()")
const client = await database.connect()
let begun = false, committing = false, unsafe = false
try {
await authorize(); await client.query("BEGIN"); begun = true
const intent = (await client.query("SELECT state FROM flow_settings_intents WHERE receipt_id=$1 AND phase='configuration' AND request_proof=$2 FOR UPDATE", [receiptId, proof])).rows
if (intent.length !== 1 || intent[0].state !== "claimed") throw conflict()
await authorize()
const result = await client.query(`UPDATE traffic_flow_settings s SET ${assignments.join(",")} FROM jsonb_populate_record(NULL::traffic_flow_settings,$1::jsonb) d WHERE s.id=1 AND ${projection}=$2::jsonb RETURNING s.id`, values)
if (result.rows.length !== 1) { await client.query("ROLLBACK"); begun = false; return false }
if (!isDeepStrictEqual(await read(client), desired)) throw conflict()
await authorize()
await client.query("UPDATE flow_settings_intents SET state='completed' WHERE receipt_id=$1 AND phase='configuration' AND request_proof=$2 AND state='claimed'", [receiptId, proof])
await authorize(); committing = true; await client.query("COMMIT"); begun = false
invalidate(); await authorize(); return true
} catch (error) {
// A rejected COMMIT acknowledgement is ambiguous. Destroy the connection;
// the permanent claim blocks a second execution in either outcome.
if (committing) unsafe = true
else if (begun) try { await client.query("ROLLBACK") } catch { unsafe = true }
invalidate(); throw error
} finally { client.release(unsafe) }
}
const complete = async (receiptId: string, phase: FlowSettingsPhase, proof: string, result: unknown) => {
await authorize()
const saved = await database.query("UPDATE flow_settings_intents SET state='completed',result=$4::jsonb WHERE receipt_id=$1 AND phase=$2 AND request_proof=$3 AND (state='claimed' OR (state='completed' AND result IS NULL)) RETURNING phase", [receiptId, phase, proof, JSON.stringify(result)])
if (saved.rows.length !== 1) throw conflict()
await authorize()
}
return { read, claim, compareAndSet, complete }
}