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 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 | 50x 45x 2x 1x 1x 1x 4x 4x 7x 7x 6x 6x 6x 3x 2x 392x 392x 392x 392x 389x 389x 389x 76x 312x 35x 35x 16x 16x 12x 4x 82x 82x 81x 1x 44x 44x 39x 38x 38x 36x 5x 5x 5x 4x 9x 6x 10x 10x 9x 9x 56x 56x 6x 50x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 101x 47x 47x 41x 41x 74x 35x 58x 213x 208x 1x 1x 4x 6x 688x 28x 138x 28x 28x 300x 300x 248x 573x 574x 570x 564x 96x 370x 370x 85x 85x 85x 83x 83x 276x 275x 97x 97x 97x 3x 97x 3x 97x 28x 97x 97x 97x 97x 2x 2x 96x 51x 48x 48x 29x 3x 3x 3x 3x 26x 51x 51x 2x 2x 2x 24x 24x 24x 24x 96x 5x 3x 3x 2x 2x 2x 2x 2x 2x 26x 26x 26x 26x 23x 23x 23x 23x 19x 23x 3x 3x 3x 3x 19x 19x 2x 97x 97x 97x 97x 97x 97x 96x 96x 96x 96x 119x 118x 118x 118x 118x 118x 118x 118x 118x 118x 21x 21x 21x 97x 97x 97x 97x 97x 83x 82x 82x 13x 9x 8x 8x 8x 118x 118x 27x 27x 22x 21x 21x 21x 21x 21x 22x 22x 22x 3x 3x 2x 2x 21x 14x 19x 10x 10x 16x 15x 15x 16x 3x 2x 2x 2x 2x 2x 2x 2x 2x 83x 204x 204x 122x 122x 17x 15x 15x 15x 15x 130x 114x 114x 28x 27x 27x 27x 28x 28x 1x 1x 28x 6x 6x 6x 6x 6x 6x 22x 22x 2x 2x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 10x 3x 3x 3x 2x 7x 7x 7x 6x 6x 10x 20x 10x 10x 1x 1x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 7x 3x 3x 2x 3x 4x 3x 2x 6x 6x 3x 3x 3x 3x 3x 4x 4x 4x | import type { ChildProcess } from "child_process";
import type { ServerState } from "./types";
import { LOG_FILE, LOGS_DIR, PLATFORM, SERVER_STATE, bearerHeaders } from "./types";
import { node } from "./node";
import { appendCapped } from "./utils/capped-log";
/** Human-readable cause for a child that went away: signal beats exit code. */
function describeExit(code: number | null, signal: NodeJS.Signals | null): string {
if (signal) return `signal ${signal}`;
if (code !== null) return `exit code ${code}`;
return "unknown cause";
}
const SERVER_MANAGER_CONFIG = {
HEALTH_POLL_INTERVAL_MS: 1000,
HEALTH_POLL_MAX_ATTEMPTS: 120,
ADOPT_PROBE_TIMEOUT_MS: 2000,
ADOPTED_WATCH_INTERVAL_MS: 5000,
SHUTDOWN_REQUEST_TIMEOUT_MS: 3000,
// Must exceed the server's own worst-case fleet teardown (bounded ~10s
// server-side) so a graceful stop is never cut short by an escalation.
STOP_GRACE_MS: 12_000,
KILL_GRACE_MS: 5000,
CRASH_RESTART_DELAY_MS: 3000,
MAX_CRASH_RESTARTS: 3,
// A run that served this long counts as healthy, so its failure starts a
// fresh budget. Shorter runs are a flap and keep spending the old one.
STABLE_UPTIME_MS: 60_000,
PORT_FILE_POLL_INTERVAL_MS: 500,
PORT_FILE_MAX_ATTEMPTS: 240,
SPAWN_CRASH_LOG_MAX_BYTES: 262_144,
} as const;
/** Exit code a refused `lilbee serve` uses when another server holds its lock. */
export const LOCK_REFUSAL_EXIT_CODE = 3;
/** Sidecar the server writes next to its scope lock, naming the holder. */
const SCOPE_OWNER_FILE = "server.scope.owner.json";
/** Identity of the server holding the shared root, read from its sidecar. */
export interface ScopeOwner {
dataDir: string;
pid: number;
}
/** The server refused to start: another vault's server owns the shared root. */
export class ScopeHeldError extends Error {
constructor(serverOutput: string) {
super(serverOutput || "another lilbee server owns the shared root");
this.name = "ScopeHeldError";
}
}
export function readScopeOwner(sharedRoot: string): ScopeOwner | null {
const path = node.join(sharedRoot, SCOPE_OWNER_FILE);
if (!node.existsSync(path)) return null;
try {
const parsed = JSON.parse(node.readFileSync(path, "utf-8")) as {
data_dir?: unknown;
pid?: unknown;
};
if (typeof parsed.data_dir !== "string" || typeof parsed.pid !== "number") return null;
return { dataDir: parsed.data_dir, pid: parsed.pid };
} catch {
return null;
}
}
/** A running server's port and the bearer token it mints at boot. */
export interface ServerSession {
port: number;
token: string;
}
/** Port + bearer token of the server serving *dataDir*, from its session files. */
export function readServerSession(dataDir: string): ServerSession | null {
try {
const portRaw = node.readFileSync(node.join(dataDir, "data", "server.port"), "utf-8");
const port = parseInt(portRaw.trim(), 10);
if (isNaN(port) || port <= 0 || port > 65535) return null;
const sessionRaw = node.readFileSync(node.join(dataDir, "data", "server.json"), "utf-8");
const parsed = JSON.parse(sessionRaw) as { token?: unknown };
if (typeof parsed.token !== "string") return null;
return { port, token: parsed.token };
} catch {
return null;
}
}
/**
* Ask the server serving *dataDir* to stop, via its own API. True when the
* request was accepted. Talks fetch directly rather than through LilbeeClient:
* the target is reached during lifecycle negotiation (possibly another vault's
* server, with its own token and port) before any client for it exists.
*/
export async function requestServerShutdown(dataDir: string): Promise<boolean> {
const session = readServerSession(dataDir);
if (session === null) return false;
try {
const res = await node.fetch(`http://127.0.0.1:${session.port}/api/shutdown`, {
method: "POST",
headers: bearerHeaders(session.token),
signal: AbortSignal.timeout(SERVER_MANAGER_CONFIG.SHUTDOWN_REQUEST_TIMEOUT_MS),
});
return res.ok;
} catch {
return false;
}
}
/** Version out of a health response; empty when absent or unparseable — never blocks readiness. */
async function reportedVersion(res: Response): Promise<string> {
try {
const body = (await res.json()) as { version?: unknown };
return typeof body.version === "string" ? body.version : "";
} catch {
return "";
}
}
/** lilbee's health report for *session*, or null when it is dead or answers with a foreign shape. */
async function probeLilbeeHealth(session: ServerSession): Promise<{ version: string } | null> {
try {
const res = await node.fetch(`http://127.0.0.1:${session.port}/api/health`, {
headers: bearerHeaders(session.token),
signal: AbortSignal.timeout(SERVER_MANAGER_CONFIG.ADOPT_PROBE_TIMEOUT_MS),
});
if (!res.ok) return null;
// The port file can outlive a SIGKILLed server, and the port can be
// reused by anything. Only lilbee's health shape counts as live.
const body = (await res.json()) as { status?: unknown; version?: unknown };
if (body.status !== "ok") return null;
return { version: typeof body.version === "string" ? body.version : "" };
} catch {
return null;
}
}
/** True when a lilbee server is live for *dataDir* (session files present and health answers). */
export async function serverIsLive(dataDir: string): Promise<boolean> {
const session = readServerSession(dataDir);
if (session === null) return false;
return (await probeLilbeeHealth(session)) !== null;
}
/** Ask the server serving *dataDir* to exit and wait until it is gone; false when it will not go. */
export async function askServerToExit(dataDir: string, timeoutMs: number): Promise<boolean> {
if (!(await requestServerShutdown(dataDir))) return false;
return awaitServerGone(dataDir, timeoutMs);
}
/** Poll until the server serving *dataDir* stops answering; false on timeout. */
export async function awaitServerGone(dataDir: string, timeoutMs: number): Promise<boolean> {
const session = readServerSession(dataDir);
if (session === null) return true;
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
try {
await node.fetch(`http://127.0.0.1:${session.port}/api/health`, {
headers: bearerHeaders(session.token),
signal: AbortSignal.timeout(SERVER_MANAGER_CONFIG.ADOPT_PROBE_TIMEOUT_MS),
});
} catch {
return true;
}
await new Promise((r) => window.setTimeout(r, SERVER_MANAGER_CONFIG.PORT_FILE_POLL_INTERVAL_MS));
}
return false;
}
/** The system prompts a spawned server starts with, empty when the server's own default applies. */
export interface SystemPrompts {
rag: string;
general: string;
}
export interface ServerManagerOptions {
binaryPath: string;
dataDir: string;
/**
* The shared root every vault's server competes for. Passed to the server
* as its exclusive scope, so the one-managed-server-ever invariant is
* enforced by an OS lock the server holds, not by plugin bookkeeping.
*/
sharedRoot: string;
/**
* HuggingFace cache and GGUF storage. Set via `LILBEE_MODELS_DIR` so the
* server uses the same path across all vaults — without it, lilbee would
* scope models to each per-vault data-dir and re-download per vault.
*/
modelsDir: string;
/** Read once per spawn, never captured at construction. */
systemPrompts: () => SystemPrompts;
/**
* Version of the installed binary, i.e. what a spawn would launch. May
* carry the release tag's leading "v", which the server's health report
* omits. Empty when unknown; adoption then skips the version check.
*/
installedVersion: string;
onStateChange?: (state: ServerState) => void;
onRestartsExhausted?: (output: string) => void;
/** Another vault took the shared root while this server was down. */
onScopeHeld?: (error: ScopeHeldError) => void;
onShutdownFailure?: (error: Error) => void;
/** Receives one line per lifecycle decision (spawn, adopt, stop, crash-restart). */
onJournal?: (message: string) => void;
}
const DESIRED = {
RUNNING: "running",
STOPPED: "stopped",
} as const;
type Desired = (typeof DESIRED)[keyof typeof DESIRED];
/**
* Supervises the one managed server for this vault's data dir.
*
* The supervisor never hunts processes: a healthy server found at start is
* adopted, a server it must replace is asked to exit over its API, and only
* its own spawned child is ever signalled — with the exit awaited, so
* "stopped" always means the process is gone and its exit event consumed.
* Mutual exclusion lives in the server's own OS locks (data dir + scope);
* a refused spawn surfaces as ScopeHeldError instead of a crash loop.
*/
export class ServerManager {
private opts: ServerManagerOptions;
private child: ChildProcess | null = null;
/** Resolves when the current child's exit event fires; created at spawn. */
private childExit: Promise<void> | null = null;
private desired: Desired = DESIRED.STOPPED;
private adopted = false;
private adoptedWatch: number | null = null;
private _state: ServerState = SERVER_STATE.STOPPED;
private crashCount = 0;
/** When the current run reached READY; null while it is not up. */
private readyAt: number | null = null;
private restartTimer: number | null = null;
private _actualPort: number | null = null;
private _spawnedVersion = "";
/** This supervisor's own notes about the child (exit cause, launch failure). */
private _outputLines: string[] = [];
/** True while the current child writes its stdout and stderr to the stdio log. */
private stdioLogged = false;
/** Set when the child can no longer come up (spawn error, refusal, restarts exhausted); aborts discovery. */
private fatalStartError: Error | null = null;
/** Bumped per start(); a superseded attempt's discovery loop steps aside. */
private startGeneration = 0;
private static readonly MAX_OUTPUT_LINES = 20;
constructor(opts: ServerManagerOptions) {
this.opts = opts;
}
/** Newest lines the server wrote to its stdio log, followed by this supervisor's notes. */
get lastOutput(): string {
return [...this.stdioTail(), ...this._outputLines].join("\n");
}
private stdioTail(): string[] {
if (!this.stdioLogged) return [];
try {
const lines = node.readFileSync(this.stdioLogPath, "utf-8").split(/\r?\n/);
return lines.filter((line) => line.length > 0).slice(-ServerManager.MAX_OUTPUT_LINES);
} catch {
return [];
}
}
get state(): ServerState {
return this._state;
}
get serverUrl(): string {
if (this._actualPort === null) return "";
return `http://127.0.0.1:${this._actualPort}`;
}
get dataDir(): string {
return this.opts.dataDir;
}
/** The resolved binary this supervisor spawns. */
get binaryPath(): string {
return this.opts.binaryPath;
}
/** Version the spawned child reported on its ready probe; empty when adopted or unknown. */
get spawnedVersion(): string {
return this._spawnedVersion;
}
get isAdopted(): boolean {
return this.adopted;
}
private get portFilePath(): string {
return `${this.opts.dataDir}/data/server.port`;
}
private get crashLogPath(): string {
return `${this.opts.dataDir}/${LOGS_DIR}/${LOG_FILE.SPAWN_CRASH}`;
}
private get stdioLogPath(): string {
return `${this.opts.dataDir}/${LOGS_DIR}/${LOG_FILE.SERVER_STDIO}`;
}
/** Persist the output ring buffer so a crash survives an Obsidian restart. */
private snapshotCrashOutput(): void {
const header = `=== crash ${new Date().toISOString()} ===\n`;
appendCapped(
this.crashLogPath,
`${header}${this.lastOutput}\n`,
SERVER_MANAGER_CONFIG.SPAWN_CRASH_LOG_MAX_BYTES,
);
}
private setState(s: ServerState): void {
this._state = s;
this.opts.onStateChange?.(s);
}
private journal(message: string): void {
this.opts.onJournal?.(message);
}
/** True when stop() has been requested; a method so TS narrowing can't fold it away. */
private stopRequested(): boolean {
return this.desired === DESIRED.STOPPED;
}
/** Throws when waiting any longer is pointless: superseded, unrecoverable, or stopped. */
private assertStartupViable(generation: number): void {
if (this.startGeneration !== generation) throw new Error("Superseded by a newer start");
if (this.fatalStartError) throw this.fatalStartError;
if (this.stopRequested()) throw new Error("Server was stopped during startup");
}
private async waitForPortFile(generation: number): Promise<void> {
for (let i = 0; i < SERVER_MANAGER_CONFIG.PORT_FILE_MAX_ATTEMPTS; i++) {
this.assertStartupViable(generation);
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) => window.setTimeout(r, SERVER_MANAGER_CONFIG.PORT_FILE_POLL_INTERVAL_MS));
}
throw new Error("Port file not found within timeout");
}
private buildSpawnEnv(): Record<string, string | undefined> {
const env: Record<string, string | undefined> = {
...process.env,
// Force UTF-8 locale/stdio: GUI-spawned children inherit no locale,
// so the server defaults to ASCII and crashes crawling non-ASCII output.
LANG: "en_US.UTF-8",
LC_ALL: "en_US.UTF-8",
PYTHONIOENCODING: "utf-8",
PYTHONUTF8: "1",
LILBEE_CORS_ORIGINS: "app://obsidian.md",
LILBEE_PARENT_PID: String(process.pid),
LILBEE_MODELS_DIR: this.opts.modelsDir,
LILBEE_EXCLUSIVE_SCOPE: this.opts.sharedRoot,
};
const prompts = this.opts.systemPrompts();
if (prompts.rag) {
env.LILBEE_RAG_SYSTEM_PROMPT = prompts.rag;
}
if (prompts.general) {
env.LILBEE_GENERAL_SYSTEM_PROMPT = prompts.general;
}
return env;
}
private pushOutputLine(line: string): void {
this._outputLines.push(line);
}
/** Descriptor for the child's stdout/stderr; a file it owns outlives a plugin reload, a pipe into this renderer does not. */
private openStdioLog(): number | null {
try {
const dir = `${this.opts.dataDir}/${LOGS_DIR}`;
if (!node.existsSync(dir)) node.mkdirSync(dir, { recursive: true });
return node.openSync(this.stdioLogPath, "w");
} catch (err) {
this.journal(`server output not captured: ${err instanceof Error ? err.message : String(err)}`);
return null;
}
}
private attachLifecycleHandlers(child: ChildProcess): void {
child.on("exit", (code: number | null, signal: NodeJS.Signals | null) => {
// A process this manager no longer tracks has no say in its state.
if (child !== this.child) return;
this.child = null;
if (this.desired === DESIRED.STOPPED) return;
if (code === LOCK_REFUSAL_EXIT_CODE) {
// Another server owns the lock; the server's refusal message is
// already in the output capture. Not a crash: no restart loop.
this.journal(`spawned server pid ${child.pid} refused to start: another server owns the shared root`);
this.fatalStartError = new ScopeHeldError(this.lastOutput);
this.setState(SERVER_STATE.ERROR);
return;
}
// A clean exit (code 0 or SIGTERM) while we still wanted the server
// running means another vault asked it to stop via a take-over. Not
// a crash: do not restart. The scope sidecar now names the winner,
// and main.ts surfaces that as STATUS_LOCKED_BY_OTHER. Without a
// foreign owner on record this is an ordinary clean shutdown, so it
// keeps the crash path instead of claiming a take-over.
const exitedCleanly = code === 0 || signal === "SIGTERM";
const owner = exitedCleanly ? readScopeOwner(this.opts.sharedRoot) : null;
if (owner && owner.dataDir !== this.opts.dataDir) {
this.journal(
`server pid ${child.pid} exited (${describeExit(code, signal)}): another vault took over the shared root`,
);
this.setState(SERVER_STATE.ERROR);
return;
}
this.pushOutputLine(`server exited (${describeExit(code, signal)})`);
this.journal(`server pid ${child.pid} exited (${describeExit(code, signal)})`);
this.snapshotCrashOutput();
this.scheduleCrashRestart();
});
child.on("error", (err: Error) => {
if (child !== this.child) return;
this.child = null;
if (this.desired === DESIRED.STOPPED) return;
const line = `failed to launch server: ${err.message}`;
this.journal(line);
this.pushOutputLine(line);
this.snapshotCrashOutput();
this.fatalStartError = new Error(`Failed to launch server: ${err.message}`);
this.setState(SERVER_STATE.ERROR);
});
}
private scheduleCrashRestart(): void {
// Reaching READY is not evidence the server works; staying there is.
// Resetting on the start itself let an adopt-fail-adopt cycle spend
// attempt 1 forever, so the budget never ran out and nothing was said.
const uptime = this.readyAt === null ? 0 : Date.now() - this.readyAt;
if (uptime >= SERVER_MANAGER_CONFIG.STABLE_UPTIME_MS) this.crashCount = 0;
this.readyAt = null;
if (this.crashCount < SERVER_MANAGER_CONFIG.MAX_CRASH_RESTARTS) {
this.crashCount++;
this.journal(
`restarting in ${SERVER_MANAGER_CONFIG.CRASH_RESTART_DELAY_MS}ms ` +
`(attempt ${this.crashCount}/${SERVER_MANAGER_CONFIG.MAX_CRASH_RESTARTS})`,
);
this.setState(SERVER_STATE.ERROR);
this.restartTimer = window.setTimeout(() => {
this.restartTimer = null;
/* v8 ignore next -- stop() flips desired and clears this timer in one synchronous block, so the false branch is unreachable */
if (this.desired === DESIRED.RUNNING) void this.startForRestart();
}, SERVER_MANAGER_CONFIG.CRASH_RESTART_DELAY_MS);
return;
}
this.journal(`server did not stay up after ${SERVER_MANAGER_CONFIG.MAX_CRASH_RESTARTS} restarts; giving up`);
this.fatalStartError = new Error(
`Server kept exiting and did not come back after ${SERVER_MANAGER_CONFIG.MAX_CRASH_RESTARTS} restarts`,
);
this.setState(SERVER_STATE.ERROR);
this.opts.onRestartsExhausted?.(this.lastOutput);
}
/** Crash-loop restart: failures surface via state + onRestartsExhausted, so
* don't rethrow. A lock refusal is not a crash and has its own recovery,
* so it is handed to the caller instead of being dropped here. */
private async startForRestart(): Promise<void> {
try {
await this.start();
} catch (err) {
if (err instanceof ScopeHeldError) this.opts.onScopeHeld?.(err);
}
}
private spawnChild(): ChildProcess {
// No --port: the server binds 0, the kernel picks a free port, and
// the chosen value is written to data/server.port for us to read.
const args = ["serve", "--host", "127.0.0.1", "--data-dir", this.opts.dataDir];
const fd = this.openStdioLog();
const out = fd ?? "ignore";
let child: ChildProcess;
try {
child = node.spawn(this.opts.binaryPath, args, {
env: this.buildSpawnEnv(),
stdio: ["ignore", out, out],
// POSIX: own process group so stop() can signal the server *and* its
// worker forks as a unit. Windows uses taskkill /t for the tree.
detached: process.platform !== PLATFORM.WIN32,
});
} finally {
// The child holds its own copy of the descriptor from here on.
if (fd !== null) node.closeSync(fd);
}
this.stdioLogged = fd !== null;
this.childExit = new Promise((resolve) => child.once("exit", () => resolve()));
this.attachLifecycleHandlers(child);
return child;
}
async start(): Promise<void> {
if (this.child || this.adopted) return;
const generation = ++this.startGeneration;
this.desired = DESIRED.RUNNING;
this._actualPort = null;
this._spawnedVersion = "";
this.fatalStartError = null;
this.setState(SERVER_STATE.STARTING);
this._outputLines = [];
this.stdioLogged = false;
// Adopt-first: a healthy server already serving this data dir is the
// singleton, not garbage. A plugin reload re-attaches instead of
// replacing it; a server whose Obsidian died exits on its own via the
// parent monitor and simply fails this probe. One exception: a server
// running a different version than the installed binary is asked to
// exit, so a binary update takes effect on the next reload.
if (await this.tryAdopt()) {
this.readyAt = Date.now();
this.setState(SERVER_STATE.READY);
return;
}
// A leftover server.port from a previous run would be adopted as this
// child's port, so it must be gone before the spawn. The probe above
// already established nothing live is behind it.
this.cleanupPortFile();
this.child = this.spawnChild();
this.journal(`spawned server pid ${this.child.pid}`);
try {
await this.waitForPortFile(generation);
await this.waitForReady(generation);
this.readyAt = Date.now();
this.setState(SERVER_STATE.READY);
} catch (err) {
// A crash-restart superseded this attempt; the newer start owns the state.
if (this.startGeneration !== generation) return;
// A stop() mid-startup aborted the discovery on purpose; not a failure.
if (this.stopRequested()) return;
if (this.child) await this.stop();
this.setState(SERVER_STATE.ERROR);
throw err;
}
}
private async tryAdopt(): Promise<boolean> {
const session = readServerSession(this.opts.dataDir);
if (session === null) return false;
const health = await probeLilbeeHealth(session);
if (health === null) return false;
if (this.versionDiffers(health.version) && (await this.replaceMismatched(health.version))) return false;
this._actualPort = session.port;
this.adopted = true;
this.watchAdopted();
this.journal(`adopted running server on port ${session.port}`);
return true;
}
/** True when running and installed versions differ; "v"-prefixed and bare forms compare equal, unknown never differs. */
private versionDiffers(running: string): boolean {
const installed = this.opts.installedVersion.replace(/^v/, "");
const current = running.replace(/^v/, "");
return installed !== "" && current !== "" && installed !== current;
}
/** Ask a version-mismatched server to exit; false when it will not go (the caller then adopts it anyway). */
private async replaceMismatched(running: string): Promise<boolean> {
this.journal(
`running server version ${running} differs from installed ${this.opts.installedVersion}; asking it to exit`,
);
if (await askServerToExit(this.opts.dataDir, SERVER_MANAGER_CONFIG.STOP_GRACE_MS)) return true;
this.journal("outdated server did not stop when asked; adopting it anyway");
return false;
}
/** Health-poll an adopted server; there is no child process to emit exit events. */
private watchAdopted(): void {
this.adoptedWatch = window.setInterval(() => {
void this.checkAdopted();
}, SERVER_MANAGER_CONFIG.ADOPTED_WATCH_INTERVAL_MS);
}
private stopAdoptedWatch(): void {
if (this.adoptedWatch !== null) {
window.clearInterval(this.adoptedWatch);
this.adoptedWatch = null;
}
}
private async checkAdopted(): Promise<void> {
if (!this.adopted || this._actualPort === null) return;
// Read the session per tick rather than caching what adoption saw: the
// server deletes server.json on shutdown and mints a fresh token on
// every boot, so a cached one goes stale the moment it restarts and
// would report a live server as dead. The port stays the adopted
// server's own, so a rewritten port file cannot silently re-point the
// watch at somebody else.
const session = readServerSession(this.opts.dataDir);
const live =
session !== null && (await probeLilbeeHealth({ port: this._actualPort, token: session.token })) !== null;
if (live) return;
if (!this.adopted || this.desired === DESIRED.STOPPED) return;
this.stopAdoptedWatch();
this.adopted = false;
this._actualPort = null;
const line = "adopted server became unreachable";
this.journal(line);
this.pushOutputLine(line);
this.snapshotCrashOutput();
this.scheduleCrashRestart();
}
private async waitForReady(generation: number): Promise<void> {
for (let i = 0; i < SERVER_MANAGER_CONFIG.HEALTH_POLL_MAX_ATTEMPTS; i++) {
this.assertStartupViable(generation);
const url = this.serverUrl;
/* v8 ignore next -- waitForReady runs only after waitForPortFile sets the port, so url is always non-empty */
if (url) {
try {
// Bootstrap probe via the injectable node abstraction: runs during
// spawn before any LilbeeClient exists, and stays test-swappable.
// The server writes server.json during lifespan startup and the
// port file only once it is listening, so by the time this loop
// runs the token is there. Read per attempt rather than hoisted,
// and probe bare if it is somehow missing: a 401 just retries,
// whereas skipping the request would stall the loop outright.
const session = readServerSession(this.opts.dataDir);
const res = await node.fetch(
`${url}/api/health`,
session === null ? undefined : { headers: bearerHeaders(session.token) },
);
if (res.ok) {
this._spawnedVersion = await reportedVersion(res);
return;
}
} catch {
// not ready yet
}
}
await new Promise((r) => window.setTimeout(r, SERVER_MANAGER_CONFIG.HEALTH_POLL_INTERVAL_MS));
}
throw new Error("Server did not become ready within timeout");
}
/**
* Signal the child's whole process group (server + worker forks). The child
* leads its own group because it was spawned detached; fall back to the bare
* child if the group send fails (e.g. it already exited).
*/
private signalGroup(child: ChildProcess, signal: NodeJS.Signals): void {
if (child.pid) {
try {
node.processKill(-child.pid, signal);
return;
} catch {
// group gone; fall through to the direct kill
}
}
child.kill(signal);
}
private cleanupPortFile(): void {
if (!node.existsSync(this.portFilePath)) return;
try {
node.unlinkSync(this.portFilePath);
} catch {
// ignore cleanup errors
}
}
/** Resolves true when the child's exit fires within *ms*; false on timeout. */
private async exitedWithin(ms: number): Promise<boolean> {
if (this.childExit === null) return true;
return Promise.race([
this.childExit.then(() => true),
new Promise<boolean>((resolve) => window.setTimeout(() => resolve(false), ms)),
]);
}
/**
* Stop the server and return only once its process is observably gone.
*
* Escalation: ask over the API, then SIGTERM the group, then SIGKILL it —
* and await the exit event at the end regardless, so no exit can land
* after stop() returns and be mistaken for a crash.
*/
async stop(): Promise<void> {
this.desired = DESIRED.STOPPED;
if (this.restartTimer) {
window.clearTimeout(this.restartTimer);
this.restartTimer = null;
}
if (this.adopted) {
this.stopAdoptedWatch();
await this.stopAdopted();
this.adopted = false;
this._actualPort = null;
this.setState(SERVER_STATE.STOPPED);
return;
}
const child = this.child;
if (!child) {
this.setState(SERVER_STATE.STOPPED);
return;
}
await this.terminateChild(child);
this.child = null;
this.childExit = null;
this._actualPort = null;
this.setState(SERVER_STATE.STOPPED);
this.cleanupPortFile();
}
/** Ask the child to exit, escalate on timeout, and await the observed exit. */
private async terminateChild(child: ChildProcess): Promise<void> {
const stopStartedAt = Date.now();
const accepted = await requestServerShutdown(this.opts.dataDir);
this.journal(`stopping server pid ${child.pid}: shutdown request ${accepted ? "accepted" : "not accepted"}`);
if (!(await this.exitedWithin(SERVER_MANAGER_CONFIG.STOP_GRACE_MS))) {
if (process.platform === PLATFORM.WIN32) {
// taskkill /f /t is the tree kill; Windows has no group signal.
this.journal(`sent taskkill /f /t to pid ${child.pid}`);
try {
await node.execFile("taskkill", ["/pid", String(child.pid), "/f", "/t"]);
} catch (err) {
this.opts.onShutdownFailure?.(err instanceof Error ? err : new Error(String(err)));
}
} else {
this.journal(`sent SIGTERM to pid ${child.pid} group`);
this.signalGroup(child, "SIGTERM");
if (!(await this.exitedWithin(SERVER_MANAGER_CONFIG.KILL_GRACE_MS))) {
this.journal(`sent SIGKILL to pid ${child.pid} group`);
this.signalGroup(child, "SIGKILL");
}
}
// SIGKILL (and taskkill /f) cannot be ignored; the exit event is
// guaranteed, so this await is what makes "stopped" mean stopped.
await this.childExit;
}
this.journal(`server pid ${child.pid} exit observed after ${Date.now() - stopStartedAt}ms`);
}
/**
* Synchronously signal the spawned child's process group to die and remove
* its port file. For use in synchronous teardown (onunload) only: it does
* not await the process exit. The OS reaps the child; the next plugin
* instance finds no stale port and no lock holder, so it spawns fresh.
*/
killChildSync(): void {
this.desired = DESIRED.STOPPED;
if (this.restartTimer !== null) {
window.clearTimeout(this.restartTimer);
this.restartTimer = null;
}
const wasAdopted = this.adopted;
this.stopAdoptedWatch();
const child = this.child;
this.child = null;
this.childExit = null;
this.adopted = false;
this._actualPort = null;
this.cleanupPortFile();
this.setState(SERVER_STATE.STOPPED);
if (child) {
if (process.platform === PLATFORM.WIN32) {
this.journal(`sent taskkill /f /t to pid ${child.pid}`);
void node.execFile("taskkill", ["/pid", String(child.pid), "/f", "/t"]).catch((err: unknown) => {
this.opts.onShutdownFailure?.(err instanceof Error ? err : new Error(String(err)));
});
child.kill("SIGKILL");
} else {
this.signalGroup(child, "SIGKILL");
}
} else if (wasAdopted) {
void requestServerShutdown(this.opts.dataDir);
}
}
/** Ask an adopted server to exit; report when it will not go. */
private async stopAdopted(): Promise<void> {
const gone = await askServerToExit(this.opts.dataDir, SERVER_MANAGER_CONFIG.STOP_GRACE_MS);
if (gone) {
this.journal("adopted server stopped when asked");
this.cleanupPortFile();
return;
}
// Not our child: there is no process handle to signal. Its own
// supervisor (parent monitor, OS locks) bounds how long it lingers.
this.journal("adopted server did not stop when asked");
this.opts.onShutdownFailure?.(new Error("the running server did not stop when asked"));
}
async restart(): Promise<void> {
await this.stop();
this.crashCount = 0;
await this.start();
}
}
|