import { pool } from "../db/index.js" import { planRecursiveIdentities, type RecursiveIdentityRow, type RecursiveIdentityMode } from "./recursive-route-identity.js" const columns = `id::text AS id, dst_address AS "dstAddress", gateway, distance, scope, target_scope AS "targetScope", routing_table AS "routingTable", check_gateway AS "checkGateway", country, comment, disabled` /** Validation is also run before sending any native mutation. Persistence repeats * it under table/row locks so a late filter binding cannot be silently orphaned. */ export async function storeRecursiveRoutes(serverId: number, desired: RecursiveIdentityRow[], mode: RecursiveIdentityMode, validateOnly = false) { const client = await pool.connect() try { await client.query("BEGIN") await client.query("LOCK TABLE filter_rules IN SHARE ROW EXCLUSIVE MODE") const current = (await client.query(`SELECT ${columns} FROM recursive_routes WHERE server_id=$1 ORDER BY sort_order,id FOR UPDATE`, [serverId])).rows const references = (await client.query<{ id: string }>(`SELECT r.id::text AS id FROM recursive_routes r JOIN filter_rules f ON f.server_id=r.server_id AND f.gateway_tunnel_id='rec:'||r.id::text WHERE r.server_id=$1`, [serverId])).rows const plan = planRecursiveIdentities(current, desired, new Set(references.map(row => row.id)), mode) if (!validateOnly) { for (const [index, row] of plan.rows.entries()) { const values = [serverId, index, row.dstAddress, row.gateway, row.distance, row.scope, row.targetScope, row.routingTable, row.checkGateway, row.country, row.comment, row.disabled] if (row.id) await client.query(`UPDATE recursive_routes SET sort_order=$2,dst_address=$3,gateway=$4,distance=$5,scope=$6,target_scope=$7, routing_table=$8,check_gateway=$9,country=$10,comment=$11,disabled=$12,updated_at=now() WHERE server_id=$1 AND id=$13 AND ROW(sort_order,dst_address,gateway,distance,scope,target_scope,routing_table,check_gateway,country,comment,disabled) IS DISTINCT FROM ROW($2::integer,$3::text,$4::text,$5::integer,$6::integer,$7::integer,$8::text,$9::text,$10::text,$11::text,$12::boolean)`, [...values, row.id]) else row.id = String((await client.query(`INSERT INTO recursive_routes (server_id,sort_order,dst_address,gateway,distance,scope,target_scope,routing_table,check_gateway,country,comment,disabled) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12) RETURNING id`, values)).rows[0].id) } if (plan.deletedIds.length) await client.query("DELETE FROM recursive_routes WHERE server_id=$1 AND id=ANY($2::bigint[])", [serverId, plan.deletedIds]) } await client.query("COMMIT") return plan.rows } catch (error) { await client.query("ROLLBACK") throw error } finally { client.release() } }