Skip to content

7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.

TypeScript

feat(server): post-sleep wake recovery - drift detection, socket flush, immediate key re-probe (#515)

Tashfeen7c8971c3e418
diff --git a/server/src/__tests__/lib/wake-detect.test.ts b/server/src/__tests__/lib/wake-detect.test.ts
new file mode 100644
index 00000000..050508d5
--- /dev/null
+++ b/server/src/__tests__/lib/wake-detect.test.ts
@@ -0,0 +1,84 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { startWakeDetect, stopWakeDetect, _resetForTests } from '../../lib/wake-detect.js';
+
+// Ported with the module from @Naster17's fork (freellmapi-pro@4c43cf2a);
+// the drift test is ours (his suite only covered the signal path).
+
+describe('wake-detect', () => {
+ beforeEach(() => {
+ _resetForTests();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ stopWakeDetect();
+ });
+
+ it('installs idempotently (no double signal registration)', () => {
+ const before = process.listenerCount('SIGCONT');
+ startWakeDetect({ onWake: vi.fn() });
+ startWakeDetect({ onWake: vi.fn() });
+ expect(process.listenerCount('SIGCONT')).toBe(before + 1);
+ });
+
+ it('unregisters signal listeners on stop and drops the hooks reference', () => {
+ const onWake = vi.fn();
+ const before = process.listenerCount('SIGUSR2');
+ startWakeDetect({ onWake });
+ expect(process.listenerCount('SIGUSR2')).toBe(before + 1);
+ stopWakeDetect();
+ expect(process.listenerCount('SIGUSR2')).toBe(before);
+ process.emit('SIGCONT' as any);
+ expect(onWake).not.toHaveBeenCalled();
+ });
+
+ it('a signal triggers a wake event naming the signal', () => {
+ const onWake = vi.fn();
+ startWakeDetect({ onWake });
+ process.emit('SIGUSR2' as any);
+ expect(onWake).toHaveBeenCalledTimes(1);
+ expect(onWake.mock.calls[0][0]).toMatchObject({ reason: 'signal', signal: 'SIGUSR2' });
+ });
+
+ it('fires a drift wake when the wall clock jumps past the threshold (host suspend)', () => {
+ vi.useFakeTimers();
+ const onWake = vi.fn();
+ startWakeDetect({ onWake });
+
+ vi.advanceTimersByTime(5_000); // baseline tick, no drift
+ expect(onWake).not.toHaveBeenCalled();
+
+ vi.setSystemTime(Date.now() + 120_000); // the suspend: clock jumps 2 minutes
+ vi.advanceTimersByTime(5_000); // next tick observes the jump
+
+ expect(onWake).toHaveBeenCalledTimes(1);
+ const event = onWake.mock.calls[0][0];
+ expect(event.reason).toBe('drift');
+ expect(event.idleMs).toBeGreaterThanOrEqual(120_000);
+ });
+
+ it('normal ticking never fires (no false positives)', () => {
+ vi.useFakeTimers();
+ const onWake = vi.fn();
+ startWakeDetect({ onWake });
+ vi.advanceTimersByTime(60_000); // 12 ordinary ticks
+ expect(onWake).not.toHaveBeenCalled();
+ });
+
+ it('a throwing onWake handler is logged, not fatal', () => {
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ startWakeDetect({ onWake: () => { throw new Error('boom'); } });
+ process.emit('SIGCONT' as any);
+ expect(errorSpy).toHaveBeenCalled();
+ errorSpy.mockRestore();
+ });
+
+ it('a rejecting async onWake handler is logged, not fatal', async () => {
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ startWakeDetect({ onWake: async () => { throw new Error('async boom'); } });
+ process.emit('SIGCONT' as any);
+ await new Promise(r => setImmediate(r));
+ expect(errorSpy).toHaveBeenCalled();
+ errorSpy.mockRestore();
+ });
+});
diff --git a/server/src/index.ts b/server/src/index.ts
index f9dc0e9b..09593842 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -1,8 +1,9 @@
import './env.js';
import { createApp } from './app.js';
import { initDb, getDb, getSetting } from './db/index.js';
-import { startHealthChecker } from './services/health.js';
-import { applyProxyUrl, applyProxyEnabled, applyProxyBypass } from './lib/proxy.js';
+import { startHealthChecker, checkAllKeys } from './services/health.js';
+import { applyProxyUrl, applyProxyEnabled, applyProxyBypass, flushProxyCache } from './lib/proxy.js';
+import { startWakeDetect } from './lib/wake-detect.js';
import { startCatalogSync } from './services/catalog-sync.js';
import { installProcessSafetyNet } from './lib/process-safety-net.js';
import { NodeScheduler } from './lib/scheduler.js';
@@ -54,6 +55,25 @@ async function main() {
startHealthChecker(scheduler);
startCatalogSync(scheduler);
startDbBackupPump(getDb(), scheduler, config.dbPath ?? undefined);
+
+ // Post-sleep recovery: while the host was suspended (laptop lid, VM
+ // pause) timers and keep-alive sockets froze, so the first requests after
+ // wake used to hit dead pooled connections and pre-sleep key statuses
+ // until the 5-minute health cycle caught up. On a detected wake (>30s
+ // wall-clock drift, or SIGCONT/SIGUSR1/2), drop the proxy dispatcher's
+ // pooled sockets and re-probe every key immediately.
+ startWakeDetect({
+ async onWake(event) {
+ const idle = Math.round(event.idleMs / 1000);
+ console.log(`[wake] resumed after ~${idle}s (${event.reason}${event.signal ? `:${event.signal}` : ''}) — flushing stale sockets, re-probing keys`);
+ flushProxyCache();
+ try {
+ await checkAllKeys();
+ } catch (err: any) {
+ console.error(`[wake] post-wake key re-probe failed: ${err?.message ?? err}`);
+ }
+ },
+ });
};
const server = app.listen(Number(PORT), HOST, onReady(HOST));
diff --git a/server/src/lib/proxy.ts b/server/src/lib/proxy.ts
index 6c5e15e2..1011c835 100644
--- a/server/src/lib/proxy.ts
+++ b/server/src/lib/proxy.ts
@@ -399,3 +399,11 @@ export function isProxyActive(): boolean {
if (!_initialized) applyProxyUrl('');
return _proxyEnabled && !!_proxyUrl;
}
+
+/** Force-rebuild the proxy dispatcher on the next request. Called on
+ * sleep/wake recovery to drop pooled TCP connections that died while the
+ * host was suspended (undici keeps them warm and would hand a dead socket
+ * to the first post-wake request). */
+export function flushProxyCache(): void {
+ cached = null;
+}
diff --git a/server/src/lib/wake-detect.ts b/server/src/lib/wake-detect.ts
new file mode 100644
index 00000000..56b79be0
--- /dev/null
+++ b/server/src/lib/wake-detect.ts
@@ -0,0 +1,95 @@
+// Detect that the host slept (laptop lid closed, VM paused) and give the
+// server a chance to shake off stale state the moment it comes back. While
+// the process is suspended nothing runs — timers, health probes, keep-alive
+// sockets all freeze — so the first requests after wake used to hit dead
+// upstream sockets and pre-sleep key statuses until the 5-minute health cycle
+// caught up. Detection is a 5s heartbeat: when the wall clock jumped far
+// beyond the expected tick interval (>30s drift), the process was suspended.
+// SIGCONT/SIGUSR2 also trigger a wake event, so operators (and the desktop
+// wrapper) can force a recovery pass by signaling the process. SIGUSR1 is
+// deliberately NOT used: Node reserves it for the inspector — signaling it
+// opens a debugger port, which is the opposite of hardening.
+//
+// Ported from @Naster17's fork (Naster17/freellmapi-pro@4c43cf2a), trimmed to
+// what applies upstream: his inflight-slot TTL guards fork-only concurrency
+// machinery, and his SQLite ping/reconnect isn't needed for an in-process
+// better-sqlite3 handle (and would bypass connectDb's injected factory).
+
+export interface WakeHooks {
+ onWake: (event: WakeEvent) => void | Promise<void>;
+}
+
+export interface WakeEvent {
+ reason: 'drift' | 'signal';
+ idleMs: number;
+ signal?: string;
+}
+
+const TICK_MS = 5_000;
+const DRIFT_THRESHOLD_MS = 30_000;
+
+let hooks: WakeHooks | null = null;
+let timer: NodeJS.Timeout | null = null;
+let lastTickAt = 0;
+let installed = false;
+
+function tick(): void {
+ const now = Date.now();
+ if (lastTickAt > 0) {
+ const drift = now - lastTickAt - TICK_MS;
+ if (drift > DRIFT_THRESHOLD_MS) {
+ invokeHooks({ reason: 'drift', idleMs: drift });
+ }
+ }
+ lastTickAt = now;
+ timer = setTimeout(tick, TICK_MS);
+ // Never keep the process alive just for the heartbeat.
+ if (timer.unref) timer.unref();
+}
+
+function handleSignal(name: string): void {
+ const idleMs = lastTickAt > 0 ? Math.max(0, Date.now() - lastTickAt - TICK_MS) : 0;
+ invokeHooks({ reason: 'signal', idleMs, signal: name });
+ lastTickAt = Date.now();
+}
+
+// The recovery pass must never take the server down: a throwing handler is
+// logged and swallowed, sync or async.
+function invokeHooks(event: WakeEvent): void {
+ if (!hooks) return;
+ try {
+ Promise.resolve(hooks.onWake(event)).catch((err) => {
+ console.error(`[wake-detect] onWake handler error: ${err?.message ?? err}`);
+ });
+ } catch (err: any) {
+ console.error(`[wake-detect] onWake handler threw synchronously: ${err?.message ?? err}`);
+ }
+}
+
+export function startWakeDetect(h: WakeHooks): void {
+ if (installed) return; // idempotent — no double signal registration
+ installed = true;
+ hooks = h;
+ lastTickAt = Date.now();
+ timer = setTimeout(tick, TICK_MS);
+ if (timer.unref) timer.unref();
+ process.on('SIGCONT', () => handleSignal('SIGCONT'));
+ process.on('SIGUSR2', () => handleSignal('SIGUSR2'));
+}
+
+export function stopWakeDetect(): void {
+ if (!installed) return;
+ installed = false;
+ if (timer) {
+ clearTimeout(timer);
+ timer = null;
+ }
+ process.removeAllListeners('SIGCONT');
+ process.removeAllListeners('SIGUSR2');
+ hooks = null;
+ lastTickAt = 0;
+}
+
+export function _resetForTests(): void {
+ stopWakeDetect();
+}