chat: reap orphaned per-cwd opencode serves on startup
Each pooled per-cwd server is a ~0.5GB process; across officer restarts the previous instance's servers would orphan and pile up. On module load, kill any opencode serve on a non-fixed port (the fixed OPENCODE_SERVER_URL port is preserved). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -22,6 +22,30 @@ type OpenCodeServer = { baseUrl: string; proc: Subprocess };
|
|||||||
const servers = new Map<string, OpenCodeServer>();
|
const servers = new Map<string, OpenCodeServer>();
|
||||||
const starting = new Map<string, Promise<OpenCodeServer>>();
|
const starting = new Map<string, Promise<OpenCodeServer>>();
|
||||||
|
|
||||||
|
// On startup, reap orphaned per-cwd serves left by a previous officer instance (each ~0.5GB) so they
|
||||||
|
// don't accumulate across restarts. The fixed server (OPENCODE_SERVER_URL) is preserved by port.
|
||||||
|
(function reapOrphanServers() {
|
||||||
|
const fixedPort = (() => {
|
||||||
|
try {
|
||||||
|
return new URL(OPENCODE_SERVER_URL).port || '4096';
|
||||||
|
} catch {
|
||||||
|
return '4096';
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
try {
|
||||||
|
Bun.spawnSync([
|
||||||
|
'bash',
|
||||||
|
'-c',
|
||||||
|
`ss -tlnp 2>/dev/null | grep -F opencode | grep -oP '127\\.0\\.0\\.1:\\K[0-9]+' | sort -u | while read -r p; do ` +
|
||||||
|
`[ "$p" = "${fixedPort}" ] && continue; ` +
|
||||||
|
`pid=$(ss -tlnp 2>/dev/null | grep "127.0.0.1:$p " | grep -oP 'pid=\\K[0-9]+' | head -1); ` +
|
||||||
|
`[ -n "$pid" ] && kill "$pid" 2>/dev/null; done`,
|
||||||
|
]);
|
||||||
|
} catch {
|
||||||
|
/* best effort */
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
|
||||||
async function isHealthy(baseUrl: string): Promise<boolean> {
|
async function isHealthy(baseUrl: string): Promise<boolean> {
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`${baseUrl}/api/health`, { signal: AbortSignal.timeout(3000) });
|
const res = await fetch(`${baseUrl}/api/health`, { signal: AbortSignal.timeout(3000) });
|
||||||
|
|||||||
Reference in New Issue
Block a user