fix(routeros): переиспользовать REST-соединение внутри серии чтений

Клиент RouterOS открывал новое TCP-соединение на каждый запрос, а одна
запись MCP делает 100–470 запросов. Замер на CHR: последовательный GET
105 -> 54 мс (CHR1) и 215 -> 114 мс (CHR2). Свободное соединение
закрывается через 2 с простоя (RouterOS держит его 30 с), предел
2 сессии на роутер сохранён.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
DenozordecandClaude Opus 5.5 committed 2026-11-19 09:35:44 +07:00
1 parent 1efc265e36
commit 4e4c871761
4 files changed
+35 -9

No files matched your search

@@ -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<void>(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<void>(resolve => server.close(() => resolve()))
}
console.log("RouterOS REST: sequential reads share a connection; idle connection closed after", ROS_IDLE_SOCKET_MS, "ms")
@@ -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<void>(resolve=>setTimeout(resolve,30));assert.equal(connections.size,0)
assert.ok(connections.size<=2);await new Promise<void>(resolve=>setTimeout(resolve,ROS_IDLE_SOCKET_MS+300));assert.equal(connections.size,0)
}finally{await new Promise<void>((resolve,reject)=>server.close(error=>error?reject(error):resolve()))}
})
+7 -4
View File
@@ -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)")))
@@ -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<Promise<unknown>>()
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) }