/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @format * @oncall memory_lab */ import {spawn} from 'child_process'; import fs from 'fs'; import os from 'os'; import path from 'path'; /** * Runs the upload command for session records after a report-type record is * written, so rounds reach the records store without depending on a hook of * the client or on how the server was launched. * * The command is `MEMLAB_RECORD_UPLOAD_CMD` when a wrapper names one, else * `meta memlab.run upload` on the records directory when that CLI is on the * PATH. With neither, uploads are off. There is no switch that turns them off * where an uploader exists. Runs are debounced (`MEMLAB_RECORD_UPLOAD_DEBOUNCE_MS`, * default 30 s, and at most 5 windows after the first pending report so a * steady stream of reports still uploads), one at a time, detached from the * server. A run that exits * non-zero is retried after each delay of `MEMLAB_RECORD_UPLOAD_BACKOFF_MS` * (comma-separated, default 1, 5 and 15 minutes), then left until the next * record. A run still going after `MEMLAB_RECORD_UPLOAD_TIMEOUT_MS` (default * 15 minutes) is stopped (SIGTERM to its process group, SIGKILL 10 s later) * and counts as failed once the group is gone, so one hung upload cannot * block every later one and none runs beside it. An * upload still owed or in flight when the server exits (SIGTERM, SIGINT, * stdin closed, or an empty event loop) is attempted once more, detached, * after the one in flight ends or reaches that limit. */ const DEFAULT_DEBOUNCE_MS = 30_000; const DEFAULT_BACKOFF_MS = [60_000, 300_000, 900_000]; const DEFAULT_TIMEOUT_MS = 900_000; const KILL_GRACE_MS = 10_000; let killGraceMs = KILL_GRACE_MS; export interface RecordUploadState { command: string; runs: number; running: boolean; last: {at: number; exit: number | null; error: string | null} | null; /** Retries already made after the last failure. */ retries: number; /** When the next run is due, while one is scheduled. */ next_at: number | null; /** Gave up after the last retry; the next record schedules again. */ gave_up: boolean; } let timer: NodeJS.Timeout | null = null; let nextAt: number | null = null; let running = false; let rerun = false; let runs = 0; let retries = 0; let gaveUp = false; let last: RecordUploadState['last'] = null; let shutdownInstalled = false; let finalSent = false; /** When the first report still waiting on the debounce was written. */ let pendingSince: number | null = null; let current: ReturnType | null = null; /** When the run in flight started. */ let currentSince: number | null = null; const UPLOADER_BIN = 'meta'; /** Where session records are kept: `MEMLAB_RECORDS_DIR`, else `~/.memlab-mcp/records`. */ export function recordsDir(): string { const dir = process.env.MEMLAB_RECORDS_DIR; if (dir == null || dir.trim() === '') { return path.join(os.homedir(), '.memlab-mcp', 'records'); } if (dir === '~') return os.homedir(); return dir.startsWith('~/') ? path.join(os.homedir(), dir.slice(2)) : path.resolve(dir); } let uploaderCache: {path: string; found: boolean} | null = null; /** An executable regular file: what `sh` would run for a PATH entry. */ function isExecutableFile(file: string): boolean { try { if (!fs.statSync(file).isFile()) return false; fs.accessSync(file, fs.constants.X_OK); return true; } catch { return false; } } /** * A script run by Node, which is what an npm package's `meta` bin is: a * `#!…node` script, or the `#!/bin/sh` shim some package managers (pnpm, * cmd-shim) write, which execs node on a file under `node_modules`. */ function isNodeScript(file: string): boolean { try { const fd = fs.openSync(file, 'r'); try { const head = Buffer.alloc(4096); const n = fs.readSync(fd, head, 0, head.length, 0); const text = head.subarray(0, n).toString('latin1'); const first = text.split('\n')[0]; if (/^#!.*[/\s]node(?:js)?(?:\s|$)/.test(first)) return true; return ( /^#!.*[/\s](?:ba|da)?sh(?:\s|$)/.test(first) && /\bexec\s+(?:"\$basedir\/node(?:\.exe)?"|node)\s/.test(text) && /node_modules|\$basedir\//.test(text) ); } finally { fs.closeSync(fd); } } catch { return false; } } /** * Whether the records uploader CLI is on the PATH (looked up once per PATH): * the `meta` that `sh` would run, unless it is a Node script. The CLI is not * run to tell, so any other `meta` is trusted: a Meta CLI taken for * something else would stop recording on that host. */ export function uploaderOnPath(): boolean { const searchPath = process.env.PATH ?? ''; if (uploaderCache?.path === searchPath) return uploaderCache.found; let found = false; for (const dir of searchPath.split(path.delimiter)) { if (dir === '') continue; const file = path.join(dir, UPLOADER_BIN); if (!isExecutableFile(file)) continue; found = !isNodeScript(file); break; } uploaderCache = {path: searchPath, found}; return found; } const shellQuote = (s: string): string => `'${s.replace(/'/g, "'\\''")}'`; /** The upload command, or null when this host has no uploader. */ export function recordUploadCommand(): string | null { const cmd = process.env.MEMLAB_RECORD_UPLOAD_CMD; if (cmd != null && cmd.trim() !== '') return cmd; return uploaderOnPath() ? `${UPLOADER_BIN} memlab.run upload --dir=${shellQuote(recordsDir())} -o json` : null; } function debounceMs(): number { const n = Number(process.env.MEMLAB_RECORD_UPLOAD_DEBOUNCE_MS); return Number.isFinite(n) && n >= 0 ? n : DEFAULT_DEBOUNCE_MS; } function backoffMs(): number[] { const raw = process.env.MEMLAB_RECORD_UPLOAD_BACKOFF_MS; if (raw == null || raw.trim() === '') return DEFAULT_BACKOFF_MS; const list = raw.split(',').map(s => Number(s.trim())); return list.every(n => Number.isFinite(n) && n >= 0) ? list : DEFAULT_BACKOFF_MS; } function timeoutMs(): number { const n = Number(process.env.MEMLAB_RECORD_UPLOAD_TIMEOUT_MS); return Number.isFinite(n) && n > 0 ? n : DEFAULT_TIMEOUT_MS; } function killGroup(pid: number | undefined, signal: NodeJS.Signals): void { if (pid == null) return; try { process.kill(-pid, signal); } catch { // Already gone. } } function groupAlive(pid: number | undefined): boolean { if (pid == null) return false; try { process.kill(-pid, 0); return true; } catch { return false; } } function arm(delay: number): void { if (timer != null) clearTimeout(timer); nextAt = Date.now() + delay; timer = setTimeout(fire, delay); // A pending upload never keeps the server alive; the exit hook sends it. timer.unref(); } function launch(cmd: string): ReturnType | null { try { const child = spawn('sh', ['-c', cmd], {detached: true, stdio: 'ignore'}); child.unref(); return child; } catch (err) { last = { at: Date.now(), exit: null, error: err instanceof Error ? err.message : String(err), }; return null; } } /** The longest a report waits while newer ones keep re-arming the debounce. */ function maxWaitMs(): number { return 5 * debounceMs(); } function fire(): void { timer = null; pendingSince = null; nextAt = null; const cmd = recordUploadCommand(); if (cmd == null) return; if (running) { rerun = true; return; } running = true; runs++; const child = launch(cmd); if (child == null) { running = false; failed(); return; } current = child; currentSince = Date.now(); let settled = false; let timedOut = false; const limit = timeoutMs(); const timeoutError = `timed out after ${inMinutes(limit)}`; // The run stays in flight until its whole process group is gone, so no // other run, the final attempt included, starts beside it. const watchdog = setTimeout(() => { timedOut = true; killGroup(child.pid, 'SIGTERM'); const termAt = Date.now(); const poll = setInterval(() => { const late = Date.now() - termAt >= killGraceMs; if (late) killGroup(child.pid, 'SIGKILL'); if (late || !groupAlive(child.pid)) { clearInterval(poll); done(null, timeoutError); } }, 50); poll.unref(); }, limit); watchdog.unref(); const done = (exit: number | null, error: string | null): void => { if (settled) return; settled = true; clearTimeout(watchdog); running = false; current = null; currentSince = null; last = {at: Date.now(), exit, error}; if (exit === 0 && error == null) { retries = 0; gaveUp = false; if (rerun) { rerun = false; arm(debounceMs()); } return; } failed(); }; child.once('error', err => done(null, err.message)); child.once('exit', (code, signal) => { if (!timedOut) done(code, signal != null ? `killed by ${signal}` : null); }); } function failed(): void { const delays = backoffMs(); if (rerun) { // A newer record is waiting: send it on the normal schedule. rerun = false; retries = 0; arm(debounceMs()); } else if (retries < delays.length) { arm(delays[retries++]); } else { gaveUp = true; } } /** * Whether an upload is scheduled, waiting on a retry, or in flight: a run in * flight may still fail after the server is gone, with no one to retry it, * so shutdown queues one more run after it. */ function owed(): boolean { return timer != null || rerun || running; } function finalAttempt(): void { if (finalSent || !owed()) return; const cmd = recordUploadCommand(); if (cmd == null) return; finalSent = true; if (timer != null) clearTimeout(timer); timer = null; nextAt = null; pendingSince = null; rerun = false; runs++; // One run at a time: after the one in flight's process group is gone, not // beside it, and not past its time limit plus the kill grace. const pid = running ? current?.pid : undefined; const left = Math.max( 0, Math.ceil(((currentSince ?? Date.now()) + timeoutMs() - Date.now()) / 1000), ); const grace = Math.ceil(killGraceMs / 1000); const waitGroup = (secs: number) => `n=0; while kill -0 -- -${pid} 2>/dev/null && [ "$n" -lt ${secs} ]; do sleep 1; n=$((n + 1)); done`; const child = launch( pid != null ? `${waitGroup(left)}; kill -s TERM -- -${pid} 2>/dev/null; ${waitGroup(grace)}; kill -s KILL -- -${pid} 2>/dev/null; ${cmd}` : cmd, ); // An asynchronous spawn failure must not turn a clean exit into a crash. child?.once('error', err => { last = {at: Date.now(), exit: null, error: err.message}; }); } function installShutdown(): void { if (shutdownInstalled) return; shutdownInstalled = true; for (const sig of ['SIGTERM', 'SIGINT'] as const) { process.once(sig, () => { finalAttempt(); // Keep the default behaviour of a signal nobody else handles. if (process.listenerCount(sig) === 0) process.kill(process.pid, sig); }); } process.once('beforeExit', finalAttempt); process.stdin.once('end', finalAttempt); } /** * Schedule an upload after a report-type record. Does nothing when no * command is configured. */ export function scheduleRecordUpload(): void { if (recordUploadCommand() == null) return; installShutdown(); finalSent = false; retries = 0; gaveUp = false; if (running) { rerun = true; return; } const now = Date.now(); if (timer == null || pendingSince == null) pendingSince = now; arm(Math.max(0, Math.min(debounceMs(), pendingSince + maxWaitMs() - now))); } export function recordUploadState(): RecordUploadState | null { const command = recordUploadCommand(); if (command == null) return null; return { command, runs, running, last, retries, next_at: nextAt, gave_up: gaveUp, }; } function inMinutes(ms: number): string { const s = Math.max(0, Math.round(ms / 1000)); return s < 120 ? `${s} s` : `${Math.round(s / 60)} min`; } /** One line for `memlab_server_status`, or null when no command is set. */ export function recordUploadLine( state: RecordUploadState | null = recordUploadState(), now: number = Date.now(), ): string | null { if (state == null) return null; const parts: string[] = []; if (state.last == null) { parts.push(state.running ? 'running' : 'not run yet in this process'); } else { const how = state.last.error != null ? `failed: ${state.last.error}` : state.last.exit === 0 ? 'exit 0' : `exit ${state.last.exit}`; parts.push( `${state.runs} run(s), last ${inMinutes(now - state.last.at)} ago (${how})`, ); if (state.running) parts.push('running now'); } if (state.next_at != null) { parts.push( state.retries > 0 ? `retry ${state.retries} in ${inMinutes(state.next_at - now)}` : `next run in ${inMinutes(state.next_at - now)}`, ); } if (state.gave_up) { parts.push('gave up after the last retry; the next report tries again'); } return parts.join('; '); } /** For tests: forget all state and cancel a pending run. */ export function resetRecordUploadForTests( opts: {killGraceMs?: number} = {}, ): void { killGraceMs = opts.killGraceMs ?? KILL_GRACE_MS; uploaderCache = null; if (timer != null) clearTimeout(timer); timer = null; nextAt = null; running = false; rerun = false; pendingSince = null; current = null; currentSince = null; runs = 0; retries = 0; gaveUp = false; last = null; finalSent = false; }