diff --git a/src/server/routes/events.ts b/src/server/routes/events.ts index 6a72c63..c63b945 100644 --- a/src/server/routes/events.ts +++ b/src/server/routes/events.ts @@ -66,6 +66,7 @@ const eventsRoutes: FastifyPluginAsyncTypebox = async (fastify) => { // Set up file watcher for live updates let fileWatcher: FSWatcher | null = null + let closed = false const repoPath = fastify.config.repositoryPath // Debounced broadcast to avoid flooding on rapid file changes @@ -82,6 +83,9 @@ const eventsRoutes: FastifyPluginAsyncTypebox = async (fastify) => { // Load gitignore patterns for filtering const ig = await loadGitignore(repoPath, fastify.log) + // Server may have shut down while we were scanning + if (closed) return + fileWatcher = chokidar.watch(repoPath, { ignored: (filePath: string) => { // Get path relative to repo root for gitignore matching @@ -121,11 +125,15 @@ const eventsRoutes: FastifyPluginAsyncTypebox = async (fastify) => { } } - // Start watching immediately (could optimize to start only when clients connect) - await startWatching() + // Start watching in the background to avoid blocking plugin registration. + // On large repos, loadGitignore can exceed Fastify's default plugin timeout. + startWatching().catch((err) => { + fastify.log.warn({ err }, 'Unexpected error starting file watcher') + }) // Clean up on server close fastify.addHook('onClose', async () => { + closed = true // Close all active SSE connections fastify.log.info({ clients: activeConnections.size }, 'Closing active SSE connections') for (const connection of activeConnections) { diff --git a/src/server/utils/gitignore.ts b/src/server/utils/gitignore.ts index db52f93..6e0de43 100644 --- a/src/server/utils/gitignore.ts +++ b/src/server/utils/gitignore.ts @@ -2,7 +2,7 @@ * Utilities for loading and parsing .gitignore files */ import ignore, { type Ignore } from 'ignore' -import { readdir, readFile, stat } from 'node:fs/promises' +import { readdir, readFile } from 'node:fs/promises' import { dirname, join, relative, sep } from 'node:path' import type { FastifyBaseLogger } from 'fastify' @@ -22,33 +22,24 @@ export async function findGitignoreFiles (dir: string, log?: Logger): Promise