import type { FastifyInstance } from "fastify" import { createScannerInboxService, type ScannerInboxService } from "./scanner-inbox.service" export function startScannerInboxWorker(server: FastifyInstance, service: Pick = createScannerInboxService(server.db)) { let stopped = false let timer: ReturnType | undefined let running: Promise | 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 }) }