diff --git a/backend/src/services/mikrotik-keepalive.test.ts b/backend/src/services/mikrotik-keepalive.test.ts new file mode 100644 index 00000000..463ae234 --- /dev/null +++ b/backend/src/services/mikrotik-keepalive.test.ts @@ -0,0 +1,22 @@ +import assert from "node:assert/strict" +import { createServer } from "node:http" +import { setTimeout as delay } from "node:timers/promises" +import { MikrotikClient, ROS_IDLE_SOCKET_MS } from "./mikrotik.js" + +let connections = 0, closedSockets = 0 +const server = createServer((_req, res) => { res.writeHead(200, { "content-type": "application/json" }); res.end("[]") }) +server.keepAliveTimeout = 30000 // RouterOS keeps idle REST connections for 30 s +server.on("connection", socket => { connections++; socket.on("close", () => closedSockets++) }) +await new Promise(resolve => server.listen(0, "127.0.0.1", resolve)) +const client = new MikrotikClient({ host: "127.0.0.1", port: (server.address() as { port: number }).port, useSsl: false, verifySsl: false, username: "fixture", password: "fixture-only" }) +try { + for (let i = 0; i < 5; i++) assert.deepEqual(await client.get("/ip/address"), []) + assert.equal(connections, 1, "a burst of sequential reads reuses one connection") + await delay(ROS_IDLE_SOCKET_MS + 500) + assert.equal(closedSockets, 1, "the client drops an idle connection long before RouterOS would") + assert.deepEqual(await client.get("/ip/address"), []) + assert.equal(connections, 2) +} finally { + server.closeAllConnections(); await new Promise(resolve => server.close(() => resolve())) +} +console.log("RouterOS REST: sequential reads share a connection; idle connection closed after", ROS_IDLE_SOCKET_MS, "ms") diff --git a/backend/src/services/mikrotik-response.test.ts b/backend/src/services/mikrotik-response.test.ts index 78bed764..7c1ba022 100644 --- a/backend/src/services/mikrotik-response.test.ts +++ b/backend/src/services/mikrotik-response.test.ts @@ -1,7 +1,7 @@ import { after, test } from "node:test" import assert from "node:assert/strict" import { createServer } from "node:http" -import { MikrotikClient, MikrotikError, routerOsAccessHint } from "./mikrotik.js" +import { MikrotikClient, MikrotikError, routerOsAccessHint, ROS_IDLE_SOCKET_MS } from "./mikrotik.js" import { pool, closePool } from "../db/index.js" import { configurationAuditTransactionFixture, emptyActiveRoutingProfilesSqlFixture } from "../test/fixtures/managed-mutation-sql.js" @@ -86,7 +86,7 @@ test("RouterOS shared REST pool bounds logins across client instances and closes try { await Promise.all(Array.from({length:12},(_,i)=>i%2?clients[i%3]!.post("/own",{},2000):clients[i%3]!.get("/own",2000))) assert.equal(requests,12);assert.equal(peak,2) - await new Promise(resolve=>setTimeout(resolve,30));assert.equal(connections.size,0) + assert.ok(connections.size<=2);await new Promise(resolve=>setTimeout(resolve,ROS_IDLE_SOCKET_MS+300));assert.equal(connections.size,0) }finally{await new Promise((resolve,reject)=>server.close(error=>error?reject(error):resolve()))} }) diff --git a/backend/src/services/mikrotik.ts b/backend/src/services/mikrotik.ts index 7ea65ecf..d35251e6 100644 --- a/backend/src/services/mikrotik.ts +++ b/backend/src/services/mikrotik.ts @@ -21,10 +21,13 @@ import type { } from "../types/server.js" const MAX_ROS_BODY_BYTES = 8 * 1024 * 1024 -// Shared pools bound concurrent REST logins across client instances. Close idle -// connections so RouterOS does not keep scarce authenticated sessions occupied. -const rosHttpAgent = new http.Agent({ keepAlive: false, maxSockets: 2 }) -const rosHttpsAgent = new https.Agent({ keepAlive: false, maxSockets: 2 }) +// Shared pools bound concurrent REST logins across client instances. Reuse a +// connection within a burst of reads (one TCP/TLS handshake instead of one per +// request), but drop it after 2 s idle so RouterOS sessions are not held; RouterOS +// itself closes idle keep-alive connections after 30 s, so a reused socket is never stale. +export const ROS_IDLE_SOCKET_MS = 2000 +const rosHttpAgent = new http.Agent({ keepAlive: true, timeout: ROS_IDLE_SOCKET_MS, maxSockets: 2 }) +const rosHttpsAgent = new https.Agent({ keepAlive: true, timeout: ROS_IDLE_SOCKET_MS, maxSockets: 2 }) function watchRosResponseFailure(res: http.IncomingMessage, reject: (error: Error) => void): void { res.once("aborted", () => reject(new Error("RouterOS response interrupted (ECONNRESET)"))) diff --git a/backend/src/services/terminal-diagnostic-client.ts b/backend/src/services/terminal-diagnostic-client.ts index 898b778c..40b3c879 100644 --- a/backend/src/services/terminal-diagnostic-client.ts +++ b/backend/src/services/terminal-diagnostic-client.ts @@ -1,6 +1,6 @@ import http from "node:http" import https from "node:https" -import { MikrotikClient } from "./mikrotik.js" +import { MikrotikClient, ROS_IDLE_SOCKET_MS } from "./mikrotik.js" import type { MikrotikConnectParams } from "./mikrotik.js" import type { TerminalDiagnosticClient } from "./terminal-diagnostics.js" import { McpError } from "../modules/mcp/security.js" @@ -17,8 +17,9 @@ export interface TerminalDiagnosticReadOptions { signal?: AbortSignal; authorize class TerminalClient extends MikrotikClient { readonly pending = new Set>() readonly cancellation = new AbortController() - private readonly httpAgent = new http.Agent({ keepAlive: false, maxSockets: 2 }) - private readonly httpsAgent = new https.Agent({ keepAlive: false, maxSockets: 2 }) + // Reuse connections within one diagnostic; close() destroys them. + private readonly httpAgent = new http.Agent({ keepAlive: true, timeout: ROS_IDLE_SOCKET_MS, maxSockets: 2 }) + private readonly httpsAgent = new https.Agent({ keepAlive: true, timeout: ROS_IDLE_SOCKET_MS, maxSockets: 2 }) private totalBytes = 0 private requests = 0 constructor(private readonly endpoint: MikrotikConnectParams, private readonly options: TerminalDiagnosticReadOptions) { super(endpoint) }