All files / src server-manager.ts

100% Statements 191/191
100% Branches 69/69
100% Functions 15/15
100% Lines 191/191

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 2391x         1x 1x 1x 1x 1x 1x 1x                       1x 34x 34x 34x 34x 34x 34x 34x 34x 34x   34x 34x 34x   34x 6x 6x   34x 20x 20x   34x 505x 505x 505x   34x 273x 273x   34x 3x 253x 2x 2x 2x 2x 2x 2x 2x 251x 251x 251x 3x   34x 95x 95x 95x   34x 38x 37x 37x 37x   37x 37x 37x 37x   38x 34x 34x   37x   37x 37x 37x 37x 37x 38x 1x 1x   37x   37x 37x 37x 37x 37x   37x 37x 37x 7x 7x 7x 7x 32x 32x 32x 5x 5x 32x 32x 37x 37x   37x 20x 20x 10x 10x 10x 7x 7x 10x 10x 2x 2x 2x 37x   37x 1x 1x 37x   37x 38x 3x 38x 34x 34x 36x 28x 28x 38x 3x 3x 38x   34x 36x 502x 502x 148x 502x   354x 474x 468x 468x 36x   34x 14x 14x 3x 3x 3x 14x 5x 5x 5x   9x   14x 2x 2x 1x   1x 14x 7x 7x   9x 9x 9x 9x 9x 9x 9x 9x   14x 1x 1x   9x 9x   9x 9x 9x 9x   1x 9x 14x   34x 2x 2x 2x 2x   34x 1x 1x   34x 3x 3x 2x 2x 3x 34x  
import type { ChildProcess } from "child_process";
import type { ServerState } from "./types";
import { SERVER_STATE } from "./types";
import { node } from "./binary-manager";
 
const HEALTH_POLL_INTERVAL_MS = 1000;
const HEALTH_POLL_MAX_ATTEMPTS = 120;
const STOP_GRACE_MS = 5000;
const CRASH_RESTART_DELAY_MS = 3000;
const MAX_CRASH_RESTARTS = 3;
const PORT_FILE_POLL_INTERVAL_MS = 500;
const PORT_FILE_MAX_ATTEMPTS = 240;
 
export interface ServerManagerOptions {
    binaryPath: string;
    dataDir: string;
    port: number | null;
    ollamaUrl: string;
    systemPrompt: string;
    onStateChange?: (state: ServerState) => void;
    onRestartsExhausted?: (stderr: string) => void;
}
 
export class ServerManager {
    private opts: ServerManagerOptions;
    private child: ChildProcess | null = null;
    private _state: ServerState = SERVER_STATE.STOPPED;
    private crashCount = 0;
    private stopping = false;
    private restartTimer: ReturnType<typeof setTimeout> | null = null;
    private _actualPort: number | null = null;
    private _stderrLines: string[] = [];
    private static readonly MAX_STDERR_LINES = 20;
 
    constructor(opts: ServerManagerOptions) {
        this.opts = opts;
    }
 
    get lastStderr(): string {
        return this._stderrLines.join("\n");
    }
 
    get state(): ServerState {
        return this._state;
    }
 
    get serverUrl(): string {
        const port = this._actualPort ?? this.opts.port;
        return `http://127.0.0.1:${port}`;
    }
 
    private get portFilePath(): string {
        return `${this.opts.dataDir}/data/server.port`;
    }
 
    private async waitForPortFile(): Promise<void> {
        for (let i = 0; i < PORT_FILE_MAX_ATTEMPTS; i++) {
            if (node.existsSync(this.portFilePath)) {
                const content = node.readFileSync(this.portFilePath, "utf-8").trim();
                const port = parseInt(content, 10);
                if (!isNaN(port) && port > 0 && port <= 65535) {
                    this._actualPort = port;
                    return;
                }
            }
            await new Promise((r) => setTimeout(r, PORT_FILE_POLL_INTERVAL_MS));
        }
        throw new Error("Port file not found within timeout");
    }
 
    private setState(s: ServerState): void {
        this._state = s;
        this.opts.onStateChange?.(s);
    }
 
    async start(): Promise<void> {
        if (this.child) return;
        this.stopping = false;
        this._actualPort = null;
        this.setState(SERVER_STATE.STARTING);
 
        const args = [
            "serve",
            "--host", "127.0.0.1",
        ];
 
        if (this.opts.port !== null) {
            args.push("--port", String(this.opts.port));
        }
 
        args.push("--data-dir", this.opts.dataDir);
 
        const env: Record<string, string | undefined> = {
            ...process.env,
            OLLAMA_HOST: this.opts.ollamaUrl,
            LILBEE_CORS_ORIGINS: "app://obsidian.md",
        };
        if (this.opts.systemPrompt) {
            env.LILBEE_SYSTEM_PROMPT = this.opts.systemPrompt;
        }
 
        this._stderrLines = [];
 
        this.child = node.spawn(this.opts.binaryPath, args, {
            env,
            stdio: ["ignore", "ignore", "pipe"],
            detached: false,
        });
 
        if (this.child.stderr) {
            let partial = "";
            this.child.stderr.on("data", (chunk: Buffer) => {
                partial += chunk.toString();
                const lines = partial.split("\n");
                partial = lines.pop()!;
                for (const line of lines) {
                    if (line.length > 0) {
                        this._stderrLines.push(line);
                        if (this._stderrLines.length > ServerManager.MAX_STDERR_LINES) {
                            this._stderrLines.shift();
                        }
                    }
                }
            });
        }
 
        this.child.on("exit", (_code, _signal) => {
            this.child = null;
            if (!this.stopping && this.crashCount < MAX_CRASH_RESTARTS) {
                this.crashCount++;
                this.setState(SERVER_STATE.ERROR);
                this.restartTimer = setTimeout(() => {
                    this.restartTimer = null;
                    if (!this.stopping) void this.start();
                }, CRASH_RESTART_DELAY_MS);
            } else if (!this.stopping) {
                this.setState(SERVER_STATE.ERROR);
                this.opts.onRestartsExhausted?.(this.lastStderr);
            }
        });
 
        this.child.on("error", () => {
            this.child = null;
            this.setState(SERVER_STATE.ERROR);
        });
 
        try {
            if (this.opts.port === null) {
                await this.waitForPortFile();
            } else {
                this._actualPort = this.opts.port;
            }
            await this.waitForReady();
            this.crashCount = 0;
            this.setState(SERVER_STATE.READY);
        } catch {
            this.setState(SERVER_STATE.ERROR);
        }
    }
 
    private async waitForReady(): Promise<void> {
        for (let i = 0; i < HEALTH_POLL_MAX_ATTEMPTS; i++) {
            try {
                const res = await node.fetch(`${this.serverUrl}/api/health`);
                if (res.ok) return;
            } catch {
                // not ready yet
            }
            await new Promise((r) => setTimeout(r, HEALTH_POLL_INTERVAL_MS));
        }
        throw new Error("Server did not become ready within timeout");
    }
 
    async stop(): Promise<void> {
        this.stopping = true;
        if (this.restartTimer) {
            clearTimeout(this.restartTimer);
            this.restartTimer = null;
        }
        if (!this.child) {
            this.setState(SERVER_STATE.STOPPED);
            return;
        }
 
        const child = this.child;
 
        if (process.platform === "win32") {
            try {
                await node.execFile("taskkill", ["/pid", String(child.pid), "/f", "/t"]);
            } catch {
                // process may already be gone
            }
        } else {
            child.kill("SIGTERM");
        }
 
        const exited = await Promise.race([
            new Promise<boolean>((resolve) => {
                child.on("exit", () => resolve(true));
            }),
            new Promise<boolean>((resolve) => {
                setTimeout(() => resolve(false), STOP_GRACE_MS);
            }),
        ]);
 
        if (!exited && this.child) {
            this.child.kill("SIGKILL");
        }
 
        this.child = null;
        this.setState(SERVER_STATE.STOPPED);
 
        if (node.existsSync(this.portFilePath)) {
            try {
                node.unlinkSync(this.portFilePath);
            } catch {
                // ignore cleanup errors
            }
        }
    }
 
    async restart(): Promise<void> {
        await this.stop();
        this.crashCount = 0;
        await this.start();
    }
 
    updateOllamaUrl(url: string): void {
        this.opts.ollamaUrl = url;
    }
 
    updatePort(port: number | null): void {
        this.opts.port = port;
        if (port !== null) {
            this._actualPort = port;
        }
    }
}