Files
MikrotikManager/backend/src/modules/mcp/routing-controller-overlap.ts
T

19 lines
1.6 KiB
TypeScript

import { pool } from "../../db/index.js"
import { routeAiProfileSchema } from "@mmapp/contracts/mcp-routing"
import { McpError } from "./security.js"
/** The common native guard supports only one enrolled profile per role server.
* Preparation reports overlap early; execute rechecks under its existing
* application+role-server locks immediately before profile CAS. No JSON payload
* is hydrated and no caller reader/authority provider is accepted. */
export async function assertNoActiveRoutingProfileOverlap(profileId: string, rawProfile: unknown) {
const profile = routeAiProfileSchema.parse(rawProfile)
const ids = [...new Set([profile.serverId, ...profile.candidates.flatMap(candidate => [candidate.jumpHostId, candidate.exitNodeId])])].sort((a, b) => a - b).map(String)
const found = (await pool.query(`SELECT id FROM mcp_routing_profiles WHERE enabled AND id<>$1::uuid AND (
config IS NULL OR jsonb_typeof(config) IS DISTINCT FROM 'object' OR jsonb_typeof(config->'candidates') IS DISTINCT FROM 'array'
OR config->>'serverId'=ANY($2::text[]) OR EXISTS(
SELECT 1 FROM jsonb_array_elements(CASE WHEN jsonb_typeof(config->'candidates')='array' THEN config->'candidates' ELSE '[]'::jsonb END) candidate
WHERE candidate->>'jumpHostId'=ANY($2::text[]) OR candidate->>'exitNodeId'=ANY($2::text[]))) LIMIT 1`, [profileId, ids])).rows
if (found.length) throw new McpError("STATE_CONFLICT", "Устройства пути уже заняты активным профилем маршрутизации; приостановите пересекающийся профиль", 409)
}