28 lines
1.1 KiB
TypeScript
28 lines
1.1 KiB
TypeScript
import type { FastifyInstance } from "fastify"
|
|
import { createScannerInboxService, type ScannerInboxService } from "./scanner-inbox.service"
|
|
|
|
export function startScannerInboxWorker(server: FastifyInstance, service: Pick<ScannerInboxService, "processNextSuggestion"> = createScannerInboxService(server.db)) {
|
|
let stopped = false
|
|
let timer: ReturnType<typeof setTimeout> | undefined
|
|
let running: Promise<void> | undefined
|
|
const run = async () => {
|
|
try {
|
|
// One analysis per process; database claims coordinate multiple backend instances.
|
|
while (!stopped && await service.processNextSuggestion()) { /* drain the durable queue */ }
|
|
} catch {
|
|
server.log.error("KI-Vorbereitung der Dokumentenablage unterbrochen; erneuter Versuch folgt.")
|
|
} finally {
|
|
if (!stopped) {
|
|
timer = setTimeout(() => { running = run() }, 2000)
|
|
timer.unref()
|
|
}
|
|
}
|
|
}
|
|
server.addHook("onReady", async () => { running = run() })
|
|
server.addHook("onClose", async () => {
|
|
stopped = true
|
|
clearTimeout(timer)
|
|
await running
|
|
})
|
|
}
|