weakset for sockets

This commit is contained in:
Alex Holliday committed 2025-12-18 21:37:09 +00:00
1 parent 4d7c5ca885
commit e76fc05f8d
1 file changed
+12 -9
@@ -16,6 +16,8 @@ import ApiError from "@/utils/ApiError.js";
import { config } from "@/config/index.js"; import { config } from "@/config/index.js";
import CacheableLookup from "cacheable-lookup"; import CacheableLookup from "cacheable-lookup";
import { getChildLogger } from "@/logger/Logger.js"; import { getChildLogger } from "@/logger/Logger.js";
// Track sockets we've already attached a secureConnect listener to avoid leaks on keep-alive reuse
const tlsCaptureAttached: WeakSet<any> = new WeakSet();
const SERVICE_NAME = "NetworkService"; const SERVICE_NAME = "NetworkService";
const logger = getChildLogger(SERVICE_NAME); const logger = getChildLogger(SERVICE_NAME);
export interface INetworkService { export interface INetworkService {
@@ -159,16 +161,17 @@ class NetworkService implements INetworkService {
} }
}; };
// Attempt immediate capture; for reused TLS sockets this is sufficient. const isTLS = typeof (socket as any).getPeerCertificate === "function";
capture(); if (!isTLS) return;
// Only add a one-time listener if TLS handshake hasn't completed. // If socket already encrypted (keep-alive reuse), capture immediately
const isTLS = if ((socket as any).encrypted === true) {
typeof (socket as any).getPeerCertificate === "function"; capture();
const isEncrypted = isTLS && (socket as any).encrypted === true; }
const connectPending =
isTLS && !isEncrypted && (socket as any).connecting === true; // Add at most one secureConnect listener per socket
if (connectPending && typeof socket.once === "function") { if (!tlsCaptureAttached.has(socket) && typeof socket.once === "function") {
tlsCaptureAttached.add(socket);
socket.once("secureConnect", capture); socket.once("secureConnect", capture);
} }
}); });