mirror of
https://github.com/Dasemu/remote-mcp-manager.git
synced 2026-11-26 23:36:31 +00:00
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 <noreply@anthropic.com>
This commit is contained in:
1 parent
05ad174f90
commit
eb24e21df7
14 files changed
+371
-12
No files matched your search
@@ -3,9 +3,12 @@ import { spawn } from "node:child_process";
|
|||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import { config } from "../config/env.js";
|
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 }> {
|
function run(cmd: string, args: string[], cwd?: string): Promise<{ code: number; output: string }> {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
const child = spawn(cmd, args, { cwd });
|
const child = spawn(cmd, args, { cwd, timeout: GIT_TIMEOUT_MS });
|
||||||
let output = "";
|
let output = "";
|
||||||
child.stdout.on("data", (d) => (output += d.toString()));
|
child.stdout.on("data", (d) => (output += d.toString()));
|
||||||
child.stderr.on("data", (d) => (output += d.toString()));
|
child.stderr.on("data", (d) => (output += d.toString()));
|
||||||
|
|||||||
@@ -7,6 +7,9 @@ export function buildLogPath(slug: string, buildId: string): string {
|
|||||||
return path.join(config.logsDir, slug, `${buildId}.log`);
|
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 {
|
export interface BuildResult {
|
||||||
success: boolean;
|
success: boolean;
|
||||||
logPath: string;
|
logPath: string;
|
||||||
@@ -83,7 +86,7 @@ export function runNixpacksBuild(
|
|||||||
logStream.write(`[remote-mcp-manager] pinning NIXPACKS_NODE_VERSION=${nodeVersion}\n`);
|
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.stdout.pipe(logStream, { end: false });
|
||||||
child.stderr.pipe(logStream, { end: false });
|
child.stderr.pipe(logStream, { end: false });
|
||||||
|
|
||||||
|
|||||||
@@ -17,4 +17,12 @@ export const config = {
|
|||||||
// Per-container resource caps, applied to every installation (no per-installation override in V1).
|
// Per-container resource caps, applied to every installation (no per-installation override in V1).
|
||||||
containerMemoryMb: Number(process.env.CONTAINER_MEMORY_MB ?? 512),
|
containerMemoryMb: Number(process.env.CONTAINER_MEMORY_MB ?? 512),
|
||||||
containerCpus: Number(process.env.CONTAINER_CPUS ?? 1),
|
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),
|
||||||
};
|
};
|
||||||
@@ -2,6 +2,7 @@ import net from "node:net";
|
|||||||
import Docker from "dockerode";
|
import Docker from "dockerode";
|
||||||
import { config } from "../config/env.js";
|
import { config } from "../config/env.js";
|
||||||
import type { Installation } from "../db/installations.js";
|
import type { Installation } from "../db/installations.js";
|
||||||
|
import { withTimeout } from "../util/withTimeout.js";
|
||||||
|
|
||||||
const docker = new Docker({ socketPath: config.dockerSocketPath });
|
const docker = new Docker({ socketPath: config.dockerSocketPath });
|
||||||
|
|
||||||
@@ -12,7 +13,15 @@ export async function ensureNetwork(name: string): Promise<void> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 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<string, { ip: Promise<string>; expires: number }>();
|
||||||
|
|
||||||
export async function removeContainerIfExists(containerName: string): Promise<void> {
|
export async function removeContainerIfExists(containerName: string): Promise<void> {
|
||||||
|
ipCache.delete(containerName);
|
||||||
try {
|
try {
|
||||||
await docker.getContainer(containerName).remove({ force: true });
|
await docker.getContainer(containerName).remove({ force: true });
|
||||||
} catch {
|
} catch {
|
||||||
@@ -25,6 +34,7 @@ export async function runInstallationContainer(installation: Installation): Prom
|
|||||||
|
|
||||||
await ensureNetwork(config.mcpNetworkName);
|
await ensureNetwork(config.mcpNetworkName);
|
||||||
await removeContainerIfExists(installation.containerName);
|
await removeContainerIfExists(installation.containerName);
|
||||||
|
ipCache.delete(installation.containerName);
|
||||||
|
|
||||||
const env = {
|
const env = {
|
||||||
...installation.env,
|
...installation.env,
|
||||||
@@ -89,9 +99,12 @@ export async function stopInstallationContainer(containerName: string): Promise<
|
|||||||
await removeContainerIfExists(containerName);
|
await removeContainerIfExists(containerName);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getContainerIp(containerName: string): Promise<string> {
|
async function lookupContainerIp(containerName: string): Promise<string> {
|
||||||
const container = docker.getContainer(containerName);
|
const info = await withTimeout(
|
||||||
const info = await container.inspect();
|
docker.getContainer(containerName).inspect(),
|
||||||
|
DOCKER_CALL_TIMEOUT_MS,
|
||||||
|
`docker inspect ${containerName}`,
|
||||||
|
);
|
||||||
const network = info.NetworkSettings.Networks[config.mcpNetworkName];
|
const network = info.NetworkSettings.Networks[config.mcpNetworkName];
|
||||||
if (!network?.IPAddress) {
|
if (!network?.IPAddress) {
|
||||||
throw new Error(`Container ${containerName} has no IP on network ${config.mcpNetworkName}`);
|
throw new Error(`Container ${containerName} has no IP on network ${config.mcpNetworkName}`);
|
||||||
@@ -99,6 +112,19 @@ export async function getContainerIp(containerName: string): Promise<string> {
|
|||||||
return network.IPAddress;
|
return network.IPAddress;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function getContainerIp(containerName: string): Promise<string> {
|
||||||
|
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(
|
export async function waitForContainerHealth(
|
||||||
installation: Installation,
|
installation: Installation,
|
||||||
timeoutMs = 20_000,
|
timeoutMs = 20_000,
|
||||||
|
|||||||
@@ -2,11 +2,13 @@ import path from "node:path";
|
|||||||
import express from "express";
|
import express from "express";
|
||||||
import session from "express-session";
|
import session from "express-session";
|
||||||
import { config } from "./config/env.js";
|
import { config } from "./config/env.js";
|
||||||
import "./db/index.js";
|
import { db } from "./db/index.js";
|
||||||
import { handleMcpProxyRequest } from "./proxy/mcpProxy.js";
|
import { getActiveProxyRequests, handleMcpProxyRequest } from "./proxy/mcpProxy.js";
|
||||||
import { authRouter } from "./api/auth.js";
|
import { authRouter } from "./api/auth.js";
|
||||||
import { installationsRouter } from "./api/installations.js";
|
import { installationsRouter } from "./api/installations.js";
|
||||||
import { requireAuth } from "./middleware/requireAuth.js";
|
import { requireAuth } from "./middleware/requireAuth.js";
|
||||||
|
import { SqliteSessionStore } from "./session/sqliteStore.js";
|
||||||
|
import { startMemoryGuard } from "./service/memoryGuard.js";
|
||||||
|
|
||||||
if (!config.sessionSecret) {
|
if (!config.sessionSecret) {
|
||||||
throw new Error("SESSION_SECRET env var must be set");
|
throw new Error("SESSION_SECRET env var must be set");
|
||||||
@@ -16,6 +18,7 @@ const app = express();
|
|||||||
app.set("trust proxy", 1);
|
app.set("trust proxy", 1);
|
||||||
app.use(
|
app.use(
|
||||||
session({
|
session({
|
||||||
|
store: new SqliteSessionStore(db),
|
||||||
secret: config.sessionSecret,
|
secret: config.sessionSecret,
|
||||||
resave: false,
|
resave: false,
|
||||||
saveUninitialized: 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).
|
// Bearer-token-gated MCP reverse proxy, public (auth handled per-installation).
|
||||||
app.all("/mcp/:slug", handleMcpProxyRequest);
|
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}`);
|
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);
|
||||||
|
},
|
||||||
|
});
|
||||||
@@ -3,8 +3,17 @@ import type { Request, Response } from "express";
|
|||||||
import httpProxy from "http-proxy";
|
import httpProxy from "http-proxy";
|
||||||
import { getInstallationBySlug, type Installation } from "../db/installations.js";
|
import { getInstallationBySlug, type Installation } from "../db/installations.js";
|
||||||
import { getContainerIp } from "../docker/containers.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) => {
|
proxy.on("error", (err, _req, res) => {
|
||||||
if (!(res as Response).headersSent) {
|
if (!(res as Response).headersSent) {
|
||||||
(res as Response).status(502).json({ error: "proxy error", detail: err.message });
|
(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;
|
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;
|
let targetIp: string;
|
||||||
try {
|
try {
|
||||||
targetIp = await getContainerIp(installation.containerName);
|
targetIp = await getContainerIp(installation.containerName);
|
||||||
|
|||||||
@@ -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();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -17,6 +17,11 @@ import {
|
|||||||
removeImageIfUnused,
|
removeImageIfUnused,
|
||||||
} from "../docker/containers.js";
|
} from "../docker/containers.js";
|
||||||
import { generateBearerToken } from "../crypto/secrets.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 {
|
export interface DraftResult {
|
||||||
installation: Installation;
|
installation: Installation;
|
||||||
@@ -64,7 +69,11 @@ export function configureInstallation(
|
|||||||
return updateInstallation(id, patch);
|
return updateInstallation(id, patch);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function buildInstallation(id: string): Promise<Installation> {
|
export function buildInstallation(id: string): Promise<Installation> {
|
||||||
|
return enqueueBuild(() => runBuild(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runBuild(id: string): Promise<Installation> {
|
||||||
const installation = getInstallationById(id);
|
const installation = getInstallationById(id);
|
||||||
if (!installation) throw new Error("installation not found");
|
if (!installation) throw new Error("installation not found");
|
||||||
|
|
||||||
@@ -127,7 +136,10 @@ export async function deployInstallation(id: string): Promise<Installation> {
|
|||||||
|
|
||||||
export async function redeployInstallation(id: string, opts: { rebuild?: boolean } = {}): Promise<Installation> {
|
export async function redeployInstallation(id: string, opts: { rebuild?: boolean } = {}): Promise<Installation> {
|
||||||
if (opts.rebuild) {
|
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);
|
return deployInstallation(id);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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<SessionData | null | undefined>((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<void>((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" }]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
/** Runs async tasks strictly one after another, whether the previous one succeeded or failed. */
|
||||||
|
export function createSerialQueue() {
|
||||||
|
let tail: Promise<unknown> = Promise.resolve();
|
||||||
|
return function enqueue<T>(task: () => Promise<T>): Promise<T> {
|
||||||
|
const run = tail.then(task, task);
|
||||||
|
tail = run.catch(() => {});
|
||||||
|
return run;
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -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"]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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<T>(promise: Promise<T>, ms: number, what: string): Promise<T> {
|
||||||
|
return new Promise<T>((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);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
Reference in new issue
Block a user