import { existsSync } from "node:fs"; import { homedir } from "node:os"; import { dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { preferIpv4 } from "./lib/prefer-ipv4.js"; import { reporterFor } from "./lib/reporter.js"; import pino from "pino"; import { loadConfig } from "./config.js"; import { dbConnectionBudget, planCapacity, Pressure } from "./lib/capacity.js"; import { modelsDir } from "./lib/models.js"; import { createDb } from "./db.js"; import { closeRenderer } from "./delivery/render.js"; import { SecretBox } from "./delivery/secrets.js"; import { DeliveryService, DeliveryWorker } from "./delivery/service.js"; import { RenderPool, RenderProcess } from "./develop/engine.js"; import { DevelopService, RenderWorker } from "./develop/service.js"; import { FaceProcess, GrowingFacePool } from "./faces/process.js"; import { AutopilotService, AutopilotWorker } from "./autopilot/service.js"; import { ensureCloudM19Target, ensureCloudW17Target } from "./delivery/fpa-m19.js"; import { jogaClientFromConfig } from "./sports/joga.js"; import { SportsService, SportsWorker } from "./sports/service.js"; import { ArchiveService, ArchiveWorker, localDirs } from "./archive/service.js"; import { findVideoTools } from "./archive/video.js"; import { lazyDetector } from "./composition/detect.js"; import { smtpMailer } from "./lib/mailer.js"; import { FulfilmentWorker, ShopService } from "./shop/service.js"; import { touchFaceHeartbeat } from "./faces/heartbeat.js"; import { FaceService, FaceWorker } from "./faces/service.js"; import { JerseyModel } from "./jersey/model.js"; import { IngestScanner } from "./ingest/scanner.js"; import { IngestService } from "./ingest/service.js"; import { createRemoteBroadcaster } from "./realtime.js"; import { LocalStorage, UrlSigner } from "./storage/storage.js"; import { Notifications } from "./notifications/service.js"; import { InvoicingService, InvoicingWorker } from "./invoicing/service.js"; /** * Background worker: FTP ingest and the delivery queue. One per installation, next to the SFTPGo drop folder * and the storage (PM2 app `photoreport-worker`, never clustered: it owns the drop folder). */ preferIpv4(); const config = loadConfig(); // Error lines (and warnings carrying an error) also go to errors.bitreport.pt, as do crashes. const reporter = reporterFor(config); reporter.watchProcess("worker"); const log = pino({ level: config.LOG_LEVEL, name: "worker", hooks: reporter.logHooks("worker") }); /** * The engines the deploy builds (target/release) and the models it downloads (next to the storage) are used when * apps/api/.env doesn't name them, so a fresh install analyses faces and renders edits without hand editing. */ const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../../.."); const built = (name: string) => [join(repoRoot, "target/release", name)].find((f) => existsSync(f)); const models = modelsDir(config.STORAGE_ROOT); const faceModels = models && existsSync(join(models, "face_detection_yunet_2023mar.onnx")) ? models : undefined; config.FACES_BIN ??= built("photoreport-faces"); config.FACES_MODELS_DIR ??= faceModels; config.RENDER_BIN ??= built("photoreport-render"); if (!config.JERSEY_MODEL_DIR && models && existsSync(join(models, "jersey", "jersey.onnx"))) config.JERSEY_MODEL_DIR = join(models, "jersey"); log.info({ faces: config.FACES_BIN ?? null, models: config.FACES_MODELS_DIR ?? null, render: config.RENDER_BIN ?? null, jersey: config.JERSEY_MODEL_DIR ?? null }, "engines"); // How much runs at once, from this container's CPUs and memory (a value in the environment wins). const capacity = planCapacity({ ingest: config.INGEST_CONCURRENCY, archive: config.ARCHIVE_CONCURRENCY, faces: config.FACES_PROCESSES, render: config.RENDER_PROCESSES, autopilot: config.AUTOPILOT_CONCURRENCY, delivery: config.DELIVERY_CONCURRENCY, }); log.info(capacity, "capacity"); // Enough connections for everything running at once, within what's left of Postgres' max_connections once the // API's cluster (Prisma pool and realtime connections), the superuser-reserved slots, the realtime broadcaster // and ad hoc connections (migrations, scripts, psql) have theirs. const wanted = 10 + Math.ceil((capacity.archiveDownloads + capacity.faces + capacity.ingest + capacity.autopilot + capacity.render) / 2); const db = createDb( config.DATABASE_URL, dbConnectionBudget(wanted, { max: config.DB_MAX_CONNECTIONS, apiInstances: config.API_INSTANCES, apiPoolSize: config.API_DB_POOL_SIZE, superuserReserved: config.DB_SUPERUSER_RESERVED_CONNECTIONS, }), ); const storage = new LocalStorage(config.STORAGE_ROOT); const broadcaster = createRemoteBroadcaster(config.DATABASE_URL, (err) => log.error({ err }, "realtime publish failed")); const ingest = new IngestService({ db, storage, signer: new UrlSigner(config.JWT_SECRET, config.FILE_URL_TTL_SEC), broadcaster, ingestRoot: config.INGEST_ROOT, log, }); const scanner = new IngestScanner(ingest, config.INGEST_ROOT, { intervalMs: config.INGEST_SCAN_INTERVAL_MS, concurrency: capacity.ingest, log }); const secrets = config.DELIVERY_SECRET_KEY ? new SecretBox(config.DELIVERY_SECRET_KEY) : undefined; if (!secrets) log.warn("DELIVERY_SECRET_KEY is not set: deliveries will fail until it is"); const signer = new UrlSigner(config.JWT_SECRET, config.FILE_URL_TTL_SEC); const renderEngine = config.RENDER_BIN ? new RenderPool(Array.from({ length: capacity.render }, () => new RenderProcess({ bin: config.RENDER_BIN! }))) : undefined; if (!renderEngine) log.warn("RENDER_BIN not set: edited photos get no new thumbnails and cannot be delivered"); const develop = new DevelopService({ db, storage, signer, broadcaster, log, engine: renderEngine }); const renders = renderEngine ? new RenderWorker(develop, { concurrency: capacity.render, intervalMs: 500, log }) : undefined; const joga = jogaClientFromConfig(config); if (!joga) log.info("joga: no credentials, FPF squads stay on the HTML site"); const sportsService = new SportsService({ db, storage, signer, log, fetch, joga }); // Archive clouds: walked for new galleries, each image indexed as a preview whose original stays in the cloud. // A big backlog: many downloads from the cloud in flight, previews made by as many as the machine's share. const videoTools = findVideoTools({ ffmpeg: config.FFMPEG_BIN, ffprobe: config.FFPROBE_BIN }, homedir()); const archiveService = new ArchiveService({ db, secrets, log, ingest, syncSquads: (id) => sportsService.syncEventSquads(id), ligaSeason: (season) => sportsService.importLigaSeason(season), fpaSeason: (season) => sportsService.importFpaSeason(season), ehfSeason: (season) => sportsService.importEhfSeason(season), storageRoot: config.STORAGE_ROOT, minFreeBytes: config.ARCHIVE_MIN_FREE_GB * 1e9, cpuSlots: capacity.archiveBurst, localDirs: localDirs(config.ARCHIVE_LOCAL_DIRS), storage, videoTools }); const archive = new ArchiveWorker(archiveService, { concurrency: capacity.archive, burst: capacity.archiveDownloads, intervalMs: 2000, log, pressure: new Pressure(), videos: config.ARCHIVE_VIDEO_CONCURRENCY }); const deliveryService = new DeliveryService({ db, storage, secrets, broadcaster, log, develop, originals: archiveService, notifications: new Notifications(db, (err) => log.warn({ err }, "notifications: not written")) }); // Every arrival goes on to the destinations that take all of them (one's own backup of the originals). ingest.arrivals = (photo) => deliveryService.queueArrival(photo); const deliveries = new DeliveryWorker(deliveryService, { concurrency: capacity.delivery, intervalMs: 1000, log, }); const mailer = config.SMTP_URL ? smtpMailer(config.SMTP_URL, config.MAIL_FROM) : undefined; if (!mailer) log.warn("SMTP_URL not set: buyers get no email when their photos are ready"); const shop = new ShopService({ db, storage, signer, secrets, log, secret: config.JWT_SECRET, develop, mailer }); const fulfilment = new FulfilmentWorker(shop, { concurrency: 2, intervalMs: 1000, log }); // Certified invoices for paid orders (the API queues them when the order is paid). const invoices = new InvoicingWorker(new InvoicingService({ db, secrets, log, notifications: new Notifications(db, (err) => log.warn({ err }, "notifications: not written")) }), { intervalMs: 5000, log }); const faceEngine = config.FACES_BIN && config.FACES_MODELS_DIR ? new GrowingFacePool( () => new FaceProcess({ bin: config.FACES_BIN!, modelsDir: config.FACES_MODELS_DIR!, embedder: config.FACES_EMBEDDER }), capacity.faces, ) : undefined; const jersey = faceEngine && config.JERSEY_MODEL_DIR ? await JerseyModel.load(config.JERSEY_MODEL_DIR) : undefined; if (jersey) log.info({ dir: config.JERSEY_MODEL_DIR }, "shirt-number model loaded"); const faceService = faceEngine ? new FaceService({ db, storage, broadcaster, log, engine: faceEngine, jersey, videoTools, videoFps: config.ARCHIVE_VIDEO_FACE_FPS, resend: (orgId, ids) => deliveryService.resendPhotos(orgId, ids), }) : undefined; const faces = faceService ? new FaceWorker(faceService, { concurrency: () => faceEngine?.size ?? 1, intervalMs: 1000, log, heartbeat: () => touchFaceHeartbeat(config.STORAGE_ROOT), }) : undefined; if (!faces) log.warn("FACES_BIN/FACES_MODELS_DIR not set: face analysis is off in this worker"); // Autopilot: edits and picks what arrives at events that have it switched on (docs/photo-editing-rules.md). const autopilot = new AutopilotWorker( new AutopilotService({ db, storage, broadcaster, log, develop, engine: renderEngine, detector: lazyDetector(config.STORAGE_ROOT, capacity.autopilot), deliveries: deliveryService }), { concurrency: capacity.autopilot, intervalMs: 200, log }, ); const sports = config.SPORTS_SYNC === "on" ? new SportsWorker(sportsService, { log, afterRegister: async () => { const n = await faceService?.requeueForSquad(); if (n) log.info({ photos: n }, "faces: read photographs queued again, newest first"); }, }) : undefined; ensureCloudM19Target(db).catch((err) => log.warn({ err }, "delivery: Cloud M19 profile not created")); ensureCloudW17Target(db).catch((err) => log.warn({ err }, "delivery: Cloud W17 profile not created")); scanner.start(); if (secrets) archive.start(); autopilot.start(); sports?.start(); deliveries.start(); faces?.start(); renders?.start(); fulfilment.start(); invoices.start(); // Photos that arrived before on-camera stars were read: apply Rating from the original in storage. const ratingBackfill = setInterval(() => { void ingest.backfillCameraRatings(25).catch((err) => log.warn({ err }, "ingest: camera rating backfill failed")); void ingest.backfillCaptureClock(100).catch((err) => log.warn({ err }, "ingest: capture clock repair failed")); void ingest.recurateAfterClockRepair(200).catch((err) => log.warn({ err }, "ingest: gallery reopen after clock repair failed")); }, 60_000); void ingest.backfillCameraRatings(25).catch((err) => log.warn({ err }, "ingest: camera rating backfill failed")); void ingest.backfillCaptureClock(100).catch((err) => log.warn({ err }, "ingest: capture clock repair failed")); void ingest.recurateAfterClockRepair(200).catch((err) => log.warn({ err }, "ingest: gallery reopen after clock repair failed")); log.info({ ingestRoot: config.INGEST_ROOT, storage: config.STORAGE_ROOT }, "worker started"); /** Drain in-flight jobs before ending the Prisma/pg pool (BIT-31189). Leave headroom under PM2 kill_timeout. */ const DRAIN_MS = 25_000; let shuttingDown = false; const shutdown = async (signal: string) => { if (shuttingDown) return; shuttingDown = true; log.info({ signal }, "worker stopping"); // Stop claiming first, then wait for ticks/in-flight work so `$disconnect` does not race Prisma queries. clearInterval(ratingBackfill); await Promise.all([ scanner.stop(DRAIN_MS), archive.stop(DRAIN_MS), autopilot.stop(DRAIN_MS), sports?.stop(DRAIN_MS) ?? Promise.resolve(), deliveries.stop(DRAIN_MS), faces?.stop(DRAIN_MS) ?? Promise.resolve(), renders?.stop(DRAIN_MS) ?? Promise.resolve(), fulfilment.stop(DRAIN_MS), invoices.stop(DRAIN_MS), ]); await faceEngine?.close(); await deliveryService.close(); await renderEngine?.close(); await closeRenderer(); await broadcaster.close(); await db.$disconnect(); await reporter.flush(); process.exit(0); }; process.on("SIGTERM", () => void shutdown("SIGTERM")); process.on("SIGINT", () => void shutdown("SIGINT"));