Graceful shutdown: close all sessions, the engine, and clean up the lock.
(reason: string = 'stop')
| 461 | |
| 462 | /** Graceful shutdown: close all sessions, the engine, and clean up the lock. */ |
| 463 | async stop(reason: string = 'stop'): Promise<void> { |
| 464 | if (this.stopping) return; |
| 465 | this.stopping = true; |
| 466 | if (this.idleTimer) { |
| 467 | clearTimeout(this.idleTimer); |
| 468 | this.idleTimer = null; |
| 469 | } |
| 470 | if (this.maxIdleTimer) { |
| 471 | clearInterval(this.maxIdleTimer); |
| 472 | this.maxIdleTimer = null; |
| 473 | } |
| 474 | if (this.clientSweepTimer) { |
| 475 | clearInterval(this.clientSweepTimer); |
| 476 | this.clientSweepTimer = null; |
| 477 | } |
| 478 | if (this.installCheckTimer) { |
| 479 | clearInterval(this.installCheckTimer); |
| 480 | this.installCheckTimer = null; |
| 481 | } |
| 482 | if (this.rootCheckTimer) { |
| 483 | clearInterval(this.rootCheckTimer); |
| 484 | this.rootCheckTimer = null; |
| 485 | } |
| 486 | process.stderr.write(`[CodeGraph daemon] Shutting down (${reason}; clients=${this.clients.size}).\n`); |
| 487 | for (const session of [...this.clients]) { |
| 488 | try { session.stop(); } catch { /* best-effort */ } |
| 489 | } |
| 490 | this.clients.clear(); |
| 491 | for (const socket of this.acceptedSockets) socket.destroy(); |
| 492 | this.acceptedSockets.clear(); |
| 493 | if (this.server) { |
| 494 | await new Promise<void>((resolve) => this.server!.close(() => resolve())); |
| 495 | this.server = null; |
| 496 | } |
| 497 | await this.engine.stop(); |
| 498 | this.cleanupLockfile(); |
| 499 | // Only this daemon's record: one that found another daemon serving its |
| 500 | // project leaves that one's record in place (#3245). |
| 501 | deregisterDaemon(this.projectRoot, process.pid); |
| 502 | if (process.platform !== 'win32') { |
| 503 | try { fs.unlinkSync(this.socketPath); } catch { /* may already be gone */ } |
| 504 | } |
| 505 | // POSIX exits here; Windows drains first (engine.stop() above began closing |
| 506 | // the file watcher, and exiting mid-teardown aborts the process). See |
| 507 | // finalizeDaemonExit / DAEMON_SHUTDOWN_BACKSTOP_MS. |
| 508 | finalizeDaemonExit(process.platform, (code) => process.exit(code)); |
| 509 | } |
| 510 | |
| 511 | private handleConnection(socket: net.Socket): void { |
| 512 | if (this.stopping) { socket.destroy(); return; } |
no test coverage detected