45 lines
1.4 KiB
TypeScript
45 lines
1.4 KiB
TypeScript
import chokidar from 'chokidar'
|
|
import { openSessionsDb } from './db.js'
|
|
import { indexFile, PROJECTS_ROOT } from './indexer.js'
|
|
|
|
export async function startWatcher(dbPath: string): Promise<void> {
|
|
const db = openSessionsDb(dbPath)
|
|
const watcher = chokidar.watch(`${PROJECTS_ROOT}/**/*.jsonl`, {
|
|
persistent: true,
|
|
ignoreInitial: true,
|
|
awaitWriteFinish: { stabilityThreshold: 2000, pollInterval: 500 },
|
|
})
|
|
|
|
async function reindex(path: string): Promise<void> {
|
|
try {
|
|
await indexFile(db, path)
|
|
console.log(`[watcher] indexed ${path}`)
|
|
} catch (err) {
|
|
console.error(`[watcher] erro ${path}:`, err)
|
|
}
|
|
}
|
|
|
|
watcher
|
|
.on('add', reindex)
|
|
.on('change', reindex)
|
|
.on('unlink', (path) => {
|
|
db.deleteByJsonlPath(path)
|
|
console.log(`[watcher] removed ${path}`)
|
|
})
|
|
.on('error', (err) => console.error('[watcher] error:', err))
|
|
|
|
console.log('[watcher] pronto')
|
|
|
|
// Registar handler SIGTERM/SIGINT para fechar DB limpa (evita WAL corruption em Task 9 systemd restart)
|
|
const cleanup = async (): Promise<void> => {
|
|
console.log('[watcher] SIGTERM/SIGINT — a fechar watcher e DB')
|
|
await watcher.close()
|
|
db.close()
|
|
process.exit(0)
|
|
}
|
|
process.on('SIGTERM', () => { void cleanup() })
|
|
process.on('SIGINT', () => { void cleanup() })
|
|
|
|
return new Promise(() => {}) // nunca resolve — processo mantém-se vivo
|
|
}
|