From eb24e21df79e0e645ff5d7d8702bcc9d4fd7bb62 Mon Sep 17 00:00:00 2001 From: Dasemu Date: Mon, 19 Oct 2026 05:23:18 +0200 Subject: [PATCH] fix: bound memory and sockets in the manager to prevent host-wide OOM - proxy: inactivity timeouts and a cap on concurrent requests (503 beyond it) - docker: cache/coalesce container IP lookups and time out inspect calls - sessions: SQLite-backed store instead of the leaking MemoryStore - memory guard: exit when heap+external passes MANAGER_MEMORY_LIMIT_MB so the restart policy replaces the process before the host swaps - builds: serialize them and time out hung git/nixpacks processes - redeploy with rebuild no longer deploys the old image after a failed build - /health reports memory and in-flight proxy requests; handle SIGTERM Co-Authored-By: Claude Sonnet 5.5 --- apps/server/src/build/git.ts | 5 +- apps/server/src/build/nixpacks.ts | 5 +- apps/server/src/config/env.ts | 8 +++ apps/server/src/docker/containers.ts | 32 ++++++++- apps/server/src/index.ts | 41 +++++++++-- apps/server/src/proxy/mcpProxy.ts | 21 +++++- apps/server/src/service/memoryGuard.test.ts | 34 +++++++++ apps/server/src/service/memoryGuard.ts | 40 +++++++++++ apps/server/src/service/orchestrator.ts | 16 ++++- apps/server/src/session/sqliteStore.test.ts | 43 ++++++++++++ apps/server/src/session/sqliteStore.ts | 77 +++++++++++++++++++++ apps/server/src/util/serialQueue.ts | 9 +++ apps/server/src/util/withTimeout.test.ts | 36 ++++++++++ apps/server/src/util/withTimeout.ts | 16 +++++ 14 files changed, 371 insertions(+), 12 deletions(-) create mode 100644 apps/server/src/service/memoryGuard.test.ts create mode 100644 apps/server/src/service/memoryGuard.ts create mode 100644 apps/server/src/session/sqliteStore.test.ts create mode 100644 apps/server/src/session/sqliteStore.ts create mode 100644 apps/server/src/util/serialQueue.ts create mode 100644 apps/server/src/util/withTimeout.test.ts create mode 100644 apps/server/src/util/withTimeout.ts diff --git a/apps/server/src/build/git.ts b/apps/server/src/build/git.ts index 46acbde..378f9eb 100644 --- a/apps/server/src/build/git.ts +++ b/apps/server/src/build/git.ts @@ -3,9 +3,12 @@ import { spawn } from "node:child_process"; import path from "node:path"; import { config } from "../config/env.js"; +// A clone that never finishes (e.g. ssh waiting on a prompt) would otherwise hang forever. +const GIT_TIMEOUT_MS = 5 * 60 * 1000; + function run(cmd: string, args: string[], cwd?: string): Promise<{ code: number; output: string }> { return new Promise((resolve, reject) => { - const child = spawn(cmd, args, { cwd }); + const child = spawn(cmd, args, { cwd, timeout: GIT_TIMEOUT_MS }); let output = ""; child.stdout.on("data", (d) => (output += d.toString())); child.stderr.on("data", (d) => (output += d.toString())); diff --git a/apps/server/src/build/nixpacks.ts b/apps/server/src/build/nixpacks.ts index f71121e..0a7d9a5 100644 --- a/apps/server/src/build/nixpacks.ts +++ b/apps/server/src/build/nixpacks.ts @@ -7,6 +7,9 @@ export function buildLogPath(slug: string, buildId: string): string { return path.join(config.logsDir, slug, `${buildId}.log`); } +// A hung build would hold the (serialized) build queue forever. +const BUILD_TIMEOUT_MS = 30 * 60 * 1000; + export interface BuildResult { success: boolean; logPath: string; @@ -83,7 +86,7 @@ export function runNixpacksBuild( logStream.write(`[remote-mcp-manager] pinning NIXPACKS_NODE_VERSION=${nodeVersion}\n`); } - const child = spawn("nixpacks", args); + const child = spawn("nixpacks", args, { timeout: BUILD_TIMEOUT_MS }); child.stdout.pipe(logStream, { end: false }); child.stderr.pipe(logStream, { end: false }); diff --git a/apps/server/src/config/env.ts b/apps/server/src/config/env.ts index cc95ba5..e7589ee 100644 --- a/apps/server/src/config/env.ts +++ b/apps/server/src/config/env.ts @@ -17,4 +17,12 @@ export const config = { // Per-container resource caps, applied to every installation (no per-installation override in V1). containerMemoryMb: Number(process.env.CONTAINER_MEMORY_MB ?? 512), containerCpus: Number(process.env.CONTAINER_CPUS ?? 1), + // Safeguards so one stuck upstream or a runaway heap can't take the whole host down. + // Inactivity timeout for proxied MCP requests/streams; a stalled upstream is cut after this. + proxyTimeoutMs: Number(process.env.PROXY_TIMEOUT_MS ?? 300_000), + // Max simultaneous proxied requests; beyond this the proxy answers 503 instead of piling up. + maxProxyRequests: Number(process.env.MAX_PROXY_REQUESTS ?? 100), + // The manager exits (and the container restart policy brings it back) once its own + // heap + external memory exceeds this. 0 disables the guard. + memoryLimitMb: Number(process.env.MANAGER_MEMORY_LIMIT_MB ?? 512), }; diff --git a/apps/server/src/docker/containers.ts b/apps/server/src/docker/containers.ts index 45da4cf..4683de6 100644 --- a/apps/server/src/docker/containers.ts +++ b/apps/server/src/docker/containers.ts @@ -2,6 +2,7 @@ import net from "node:net"; import Docker from "dockerode"; import { config } from "../config/env.js"; import type { Installation } from "../db/installations.js"; +import { withTimeout } from "../util/withTimeout.js"; const docker = new Docker({ socketPath: config.dockerSocketPath }); @@ -12,7 +13,15 @@ export async function ensureNetwork(name: string): Promise { } } +// Every proxied MCP request needs the container's IP. Asking Docker each time meant a slow +// daemon stalled every request at once (and each one held its socket while waiting); a short +// cache plus a call timeout keeps one wedged Docker daemon from snowballing into the proxy. +const IP_CACHE_TTL_MS = 5_000; +const DOCKER_CALL_TIMEOUT_MS = 10_000; +const ipCache = new Map; expires: number }>(); + export async function removeContainerIfExists(containerName: string): Promise { + ipCache.delete(containerName); try { await docker.getContainer(containerName).remove({ force: true }); } catch { @@ -25,6 +34,7 @@ export async function runInstallationContainer(installation: Installation): Prom await ensureNetwork(config.mcpNetworkName); await removeContainerIfExists(installation.containerName); + ipCache.delete(installation.containerName); const env = { ...installation.env, @@ -89,9 +99,12 @@ export async function stopInstallationContainer(containerName: string): Promise< await removeContainerIfExists(containerName); } -export async function getContainerIp(containerName: string): Promise { - const container = docker.getContainer(containerName); - const info = await container.inspect(); +async function lookupContainerIp(containerName: string): Promise { + const info = await withTimeout( + docker.getContainer(containerName).inspect(), + DOCKER_CALL_TIMEOUT_MS, + `docker inspect ${containerName}`, + ); const network = info.NetworkSettings.Networks[config.mcpNetworkName]; if (!network?.IPAddress) { throw new Error(`Container ${containerName} has no IP on network ${config.mcpNetworkName}`); @@ -99,6 +112,19 @@ export async function getContainerIp(containerName: string): Promise { return network.IPAddress; } +export function getContainerIp(containerName: string): Promise { + const cached = ipCache.get(containerName); + if (cached && cached.expires > Date.now()) return cached.ip; + + // Concurrent callers share one in-flight lookup; failures aren't cached. + const ip = lookupContainerIp(containerName); + ipCache.set(containerName, { ip, expires: Date.now() + IP_CACHE_TTL_MS }); + ip.catch(() => { + if (ipCache.get(containerName)?.ip === ip) ipCache.delete(containerName); + }); + return ip; +} + export async function waitForContainerHealth( installation: Installation, timeoutMs = 20_000, diff --git a/apps/server/src/index.ts b/apps/server/src/index.ts index baca1ae..2d548fa 100644 --- a/apps/server/src/index.ts +++ b/apps/server/src/index.ts @@ -2,11 +2,13 @@ import path from "node:path"; import express from "express"; import session from "express-session"; import { config } from "./config/env.js"; -import "./db/index.js"; -import { handleMcpProxyRequest } from "./proxy/mcpProxy.js"; +import { db } from "./db/index.js"; +import { getActiveProxyRequests, handleMcpProxyRequest } from "./proxy/mcpProxy.js"; import { authRouter } from "./api/auth.js"; import { installationsRouter } from "./api/installations.js"; import { requireAuth } from "./middleware/requireAuth.js"; +import { SqliteSessionStore } from "./session/sqliteStore.js"; +import { startMemoryGuard } from "./service/memoryGuard.js"; if (!config.sessionSecret) { throw new Error("SESSION_SECRET env var must be set"); @@ -16,6 +18,7 @@ const app = express(); app.set("trust proxy", 1); app.use( session({ + store: new SqliteSessionStore(db), secret: config.sessionSecret, resave: false, saveUninitialized: false, @@ -32,7 +35,16 @@ app.use( }), ); -app.get("/health", (_req, res) => res.json({ ok: true })); +app.get("/health", (_req, res) => { + const mem = process.memoryUsage(); + res.json({ + ok: true, + uptimeSec: Math.round(process.uptime()), + rssMb: Math.round(mem.rss / 1048576), + heapUsedMb: Math.round(mem.heapUsed / 1048576), + activeProxyRequests: getActiveProxyRequests(), + }); +}); // Bearer-token-gated MCP reverse proxy, public (auth handled per-installation). app.all("/mcp/:slug", handleMcpProxyRequest); @@ -53,6 +65,27 @@ app.get(/^\/(?!api|mcp|health).*/, (_req, res) => { }); }); -app.listen(config.port, () => { +const server = app.listen(config.port, () => { console.log(`remote-mcp-manager listening on http://localhost:${config.port}`); }); + +function shutdown(code: number): void { + server.close(() => process.exit(code)); + server.closeAllConnections(); + setTimeout(() => process.exit(code), 5_000).unref(); +} + +process.on("SIGTERM", () => shutdown(0)); +process.on("SIGINT", () => shutdown(0)); + +// Exit before a leak drags the whole host into swap; the container's restart policy +// (`unless-stopped`) starts a fresh process. +startMemoryGuard({ + limitMb: config.memoryLimitMb, + onExceeded: (usedMb) => { + console.error( + `memory guard: heap+external at ${Math.round(usedMb)} MB exceeds MANAGER_MEMORY_LIMIT_MB=${config.memoryLimitMb}, restarting`, + ); + shutdown(1); + }, +}); diff --git a/apps/server/src/proxy/mcpProxy.ts b/apps/server/src/proxy/mcpProxy.ts index 142f481..22467c6 100644 --- a/apps/server/src/proxy/mcpProxy.ts +++ b/apps/server/src/proxy/mcpProxy.ts @@ -3,8 +3,17 @@ import type { Request, Response } from "express"; import httpProxy from "http-proxy"; import { getInstallationBySlug, type Installation } from "../db/installations.js"; import { getContainerIp } from "../docker/containers.js"; +import { config } from "../config/env.js"; -const proxy = httpProxy.createProxyServer(); +// proxyTimeout: inactivity timeout on the upstream socket; timeout: same on the client socket. +// Without them a stalled MCP container (or a client that vanished mid-stream) holds its +// sockets and buffers forever, and those pile up until the host runs out of memory. +const proxy = httpProxy.createProxyServer({ proxyTimeout: config.proxyTimeoutMs, timeout: config.proxyTimeoutMs }); +let activeProxyRequests = 0; + +export function getActiveProxyRequests(): number { + return activeProxyRequests; +} proxy.on("error", (err, _req, res) => { if (!(res as Response).headersSent) { (res as Response).status(502).json({ error: "proxy error", detail: err.message }); @@ -51,6 +60,16 @@ export async function handleMcpProxyRequest(req: Request, res: Response): Promis return; } + // Bounded concurrency: when upstreams or Docker stall, shed load rather than queue unboundedly. + if (activeProxyRequests >= config.maxProxyRequests) { + res.set("Retry-After", "5").status(503).json({ error: "too many concurrent requests" }); + return; + } + activeProxyRequests += 1; + res.once("close", () => { + activeProxyRequests -= 1; + }); + let targetIp: string; try { targetIp = await getContainerIp(installation.containerName); diff --git a/apps/server/src/service/memoryGuard.test.ts b/apps/server/src/service/memoryGuard.test.ts new file mode 100644 index 0000000..bd0ac7b --- /dev/null +++ b/apps/server/src/service/memoryGuard.test.ts @@ -0,0 +1,34 @@ +import { describe, expect, it, vi } from "vitest"; +import { isOverLimit, startMemoryGuard } from "./memoryGuard.js"; + +const MB = 1024 * 1024; + +describe("isOverLimit", () => { + it("counts heap + external against the limit", () => { + expect(isOverLimit({ heapUsed: 300 * MB, external: 250 * MB }, 512)).toBe(true); + expect(isOverLimit({ heapUsed: 300 * MB, external: 100 * MB }, 512)).toBe(false); + }); + + it("is disabled when the limit is 0", () => { + expect(isOverLimit({ heapUsed: 9999 * MB, external: 0 }, 0)).toBe(false); + }); +}); + +describe("startMemoryGuard", () => { + it("fires onExceeded exactly once after the limit is passed", async () => { + const onExceeded = vi.fn(); + const timer = startMemoryGuard({ + limitMb: 100, + intervalMs: 5, + sample: () => ({ heapUsed: 200 * MB, external: 0 }), + onExceeded, + }); + await new Promise((r) => setTimeout(r, 40)); + clearInterval(timer); + expect(onExceeded).toHaveBeenCalledTimes(1); + }); + + it("does not start when disabled", () => { + expect(startMemoryGuard({ limitMb: 0, onExceeded: () => {} })).toBeUndefined(); + }); +}); diff --git a/apps/server/src/service/memoryGuard.ts b/apps/server/src/service/memoryGuard.ts new file mode 100644 index 0000000..271ce41 --- /dev/null +++ b/apps/server/src/service/memoryGuard.ts @@ -0,0 +1,40 @@ +const MB = 1024 * 1024; + +export interface MemorySample { + heapUsed: number; + external: number; +} + +/** Heap + external, not RSS: RSS drops when the kernel swaps pages out, which hides a leak on a swapping host. */ +export function usedMb(sample: MemorySample): number { + return (sample.heapUsed + sample.external) / MB; +} + +export function isOverLimit(sample: MemorySample, limitMb: number): boolean { + return limitMb > 0 && usedMb(sample) > limitMb; +} + +/** + * Polls the process's own memory and calls `onExceeded` once it passes `limitMb`. The caller is + * expected to exit so the container restart policy replaces a bloated process with a fresh one + * *before* the host starts swapping and every other container on it degrades. + */ +export function startMemoryGuard(opts: { + limitMb: number; + intervalMs?: number; + sample?: () => MemorySample; + onExceeded: (usedMb: number) => void; +}): NodeJS.Timeout | undefined { + if (opts.limitMb <= 0) return undefined; + const sample = opts.sample ?? (() => process.memoryUsage()); + let fired = false; + const timer = setInterval(() => { + const current = sample(); + if (!fired && isOverLimit(current, opts.limitMb)) { + fired = true; + opts.onExceeded(usedMb(current)); + } + }, opts.intervalMs ?? 30_000); + timer.unref(); + return timer; +} diff --git a/apps/server/src/service/orchestrator.ts b/apps/server/src/service/orchestrator.ts index 04c1f55..2cee38e 100644 --- a/apps/server/src/service/orchestrator.ts +++ b/apps/server/src/service/orchestrator.ts @@ -17,6 +17,11 @@ import { removeImageIfUnused, } from "../docker/containers.js"; import { generateBearerToken } from "../crypto/secrets.js"; +import { createSerialQueue } from "../util/serialQueue.js"; + +// Builds are the heaviest thing the host does (nixpacks + docker build); running several at +// once on a small host is what pushes it into swap. Serialize them. +const enqueueBuild = createSerialQueue(); export interface DraftResult { installation: Installation; @@ -64,7 +69,11 @@ export function configureInstallation( return updateInstallation(id, patch); } -export async function buildInstallation(id: string): Promise { +export function buildInstallation(id: string): Promise { + return enqueueBuild(() => runBuild(id)); +} + +async function runBuild(id: string): Promise { const installation = getInstallationById(id); if (!installation) throw new Error("installation not found"); @@ -127,7 +136,10 @@ export async function deployInstallation(id: string): Promise { export async function redeployInstallation(id: string, opts: { rebuild?: boolean } = {}): Promise { if (opts.rebuild) { - await buildInstallation(id); + // A failed build must stop here: deploying anyway would silently run the previous image + // and flip the status back to "running", hiding the failure. + const built = await buildInstallation(id); + if (built.status === "error") return built; } return deployInstallation(id); } diff --git a/apps/server/src/session/sqliteStore.test.ts b/apps/server/src/session/sqliteStore.test.ts new file mode 100644 index 0000000..929dbeb --- /dev/null +++ b/apps/server/src/session/sqliteStore.test.ts @@ -0,0 +1,43 @@ +import { describe, expect, it } from "vitest"; +import Database from "better-sqlite3"; +import type { SessionData } from "express-session"; +import { SqliteSessionStore } from "./sqliteStore.js"; + +function makeStore() { + return new SqliteSessionStore(new Database(":memory:"), 60_000); +} + +function sessionExpiringIn(ms: number): SessionData { + return { cookie: { expires: new Date(Date.now() + ms), originalMaxAge: ms }, authenticated: true } as SessionData; +} + +const get = (store: SqliteSessionStore, sid: string) => + new Promise((resolve, reject) => + store.get(sid, (err, sess) => (err ? reject(err) : resolve(sess))), + ); + +describe("SqliteSessionStore", () => { + it("round-trips a session and destroys it", async () => { + const store = makeStore(); + store.set("a", sessionExpiringIn(60_000)); + expect((await get(store, "a"))?.authenticated).toBe(true); + + await new Promise((resolve) => store.destroy("a", () => resolve())); + expect(await get(store, "a")).toBeNull(); + }); + + it("treats an expired session as missing", async () => { + const store = makeStore(); + store.set("old", sessionExpiringIn(-1_000)); + expect(await get(store, "old")).toBeNull(); + }); + + it("purges expired sessions that are never read again", () => { + const db = new Database(":memory:"); + const store = new SqliteSessionStore(db, 60_000); + store.set("old", sessionExpiringIn(-1_000)); + store.set("live", sessionExpiringIn(60_000)); + store.purgeExpired(); + expect(db.prepare("SELECT sid FROM sessions").all()).toEqual([{ sid: "live" }]); + }); +}); diff --git a/apps/server/src/session/sqliteStore.ts b/apps/server/src/session/sqliteStore.ts new file mode 100644 index 0000000..084f23b --- /dev/null +++ b/apps/server/src/session/sqliteStore.ts @@ -0,0 +1,77 @@ +import session from "express-session"; +import type { Database } from "better-sqlite3"; + +const DEFAULT_TTL_MS = 12 * 60 * 60 * 1000; + +/** + * Session store backed by the manager's own SQLite DB. Replaces express-session's MemoryStore, + * which never evicts sessions that aren't read again (it warns it "will leak memory" in + * production) and loses every login on restart. + */ +export class SqliteSessionStore extends session.Store { + constructor(private readonly db: Database, purgeIntervalMs = 10 * 60 * 1000) { + super(); + db.exec( + "CREATE TABLE IF NOT EXISTS sessions (sid TEXT PRIMARY KEY, sess TEXT NOT NULL, expires INTEGER NOT NULL)", + ); + db.exec("CREATE INDEX IF NOT EXISTS sessions_expires ON sessions (expires)"); + const timer = setInterval(() => this.purgeExpired(), purgeIntervalMs); + timer.unref(); + } + + purgeExpired(): void { + this.db.prepare("DELETE FROM sessions WHERE expires <= ?").run(Date.now()); + } + + private expiryOf(sess: session.SessionData): number { + const expires = sess.cookie?.expires; + return expires ? new Date(expires).getTime() : Date.now() + DEFAULT_TTL_MS; + } + + get(sid: string, cb: (err?: unknown, sess?: session.SessionData | null) => void): void { + try { + const row = this.db.prepare("SELECT sess, expires FROM sessions WHERE sid = ?").get(sid) as + | { sess: string; expires: number } + | undefined; + if (!row || row.expires <= Date.now()) { + if (row) this.db.prepare("DELETE FROM sessions WHERE sid = ?").run(sid); + cb(null, null); + return; + } + cb(null, JSON.parse(row.sess) as session.SessionData); + } catch (err) { + cb(err); + } + } + + set(sid: string, sess: session.SessionData, cb?: (err?: unknown) => void): void { + try { + this.db + .prepare( + "INSERT INTO sessions (sid, sess, expires) VALUES (?, ?, ?) " + + "ON CONFLICT(sid) DO UPDATE SET sess = excluded.sess, expires = excluded.expires", + ) + .run(sid, JSON.stringify(sess), this.expiryOf(sess)); + cb?.(); + } catch (err) { + cb?.(err); + } + } + + touch(sid: string, sess: session.SessionData, cb?: () => void): void { + try { + this.db.prepare("UPDATE sessions SET expires = ? WHERE sid = ?").run(this.expiryOf(sess), sid); + } finally { + cb?.(); + } + } + + destroy(sid: string, cb?: (err?: unknown) => void): void { + try { + this.db.prepare("DELETE FROM sessions WHERE sid = ?").run(sid); + cb?.(); + } catch (err) { + cb?.(err); + } + } +} diff --git a/apps/server/src/util/serialQueue.ts b/apps/server/src/util/serialQueue.ts new file mode 100644 index 0000000..087c7cb --- /dev/null +++ b/apps/server/src/util/serialQueue.ts @@ -0,0 +1,9 @@ +/** Runs async tasks strictly one after another, whether the previous one succeeded or failed. */ +export function createSerialQueue() { + let tail: Promise = Promise.resolve(); + return function enqueue(task: () => Promise): Promise { + const run = tail.then(task, task); + tail = run.catch(() => {}); + return run; + }; +} diff --git a/apps/server/src/util/withTimeout.test.ts b/apps/server/src/util/withTimeout.test.ts new file mode 100644 index 0000000..f3f7107 --- /dev/null +++ b/apps/server/src/util/withTimeout.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, it } from "vitest"; +import { withTimeout } from "./withTimeout.js"; +import { createSerialQueue } from "./serialQueue.js"; + +describe("withTimeout", () => { + it("resolves with the value when the promise settles in time", async () => { + await expect(withTimeout(Promise.resolve(42), 100, "x")).resolves.toBe(42); + }); + + it("rejects when the promise never settles", async () => { + await expect(withTimeout(new Promise(() => {}), 10, "docker inspect")).rejects.toThrow( + "docker inspect timed out after 10ms", + ); + }); +}); + +describe("createSerialQueue", () => { + it("never runs two tasks at once and keeps going after a failure", async () => { + const enqueue = createSerialQueue(); + let running = 0; + let maxRunning = 0; + const task = (fail = false) => async () => { + running += 1; + maxRunning = Math.max(maxRunning, running); + await new Promise((r) => setTimeout(r, 5)); + running -= 1; + if (fail) throw new Error("boom"); + return "ok"; + }; + + const results = await Promise.allSettled([enqueue(task()), enqueue(task(true)), enqueue(task())]); + + expect(maxRunning).toBe(1); + expect(results.map((r) => r.status)).toEqual(["fulfilled", "rejected", "fulfilled"]); + }); +}); diff --git a/apps/server/src/util/withTimeout.ts b/apps/server/src/util/withTimeout.ts new file mode 100644 index 0000000..7692c1a --- /dev/null +++ b/apps/server/src/util/withTimeout.ts @@ -0,0 +1,16 @@ +/** Rejects if `promise` hasn't settled within `ms` — for calls that can hang forever (e.g. a wedged Docker daemon). */ +export function withTimeout(promise: Promise, ms: number, what: string): Promise { + return new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new Error(`${what} timed out after ${ms}ms`)), ms); + promise.then( + (value) => { + clearTimeout(timer); + resolve(value); + }, + (err) => { + clearTimeout(timer); + reject(err); + }, + ); + }); +}