The backlog is oldest-first, so a game someone asks to analyse now never starts. Boosted photos are claimed first, and the library says when the face worker is not running.
179 lines
9.7 KiB
TypeScript
179 lines
9.7 KiB
TypeScript
import { existsSync } from "node:fs";
|
|
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 { 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 { FacePool, FaceProcess } from "./faces/process.js";
|
|
import { AutopilotService, AutopilotWorker } from "./autopilot/service.js";
|
|
import { SportsService, SportsWorker } from "./sports/service.js";
|
|
import { ArchiveService, ArchiveWorker, localDirs } from "./archive/service.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,
|
|
delivery: config.DELIVERY_CONCURRENCY,
|
|
});
|
|
log.info(capacity, "capacity");
|
|
// Enough connections for everything running at once, within Postgres' default 100 (the API keeps its own 10).
|
|
const db = createDb(config.DATABASE_URL, Math.min(80, 10 + Math.ceil((capacity.archiveDownloads + capacity.faces + capacity.ingest) / 2)));
|
|
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 sportsService = new SportsService({ db, storage, log, fetch });
|
|
// 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 archiveService = new ArchiveService({ db, secrets, log, ingest, syncSquads: (id) => sportsService.syncEventSquads(id), ligaSeason: (season) => sportsService.importLigaSeason(season), fpaSeason: (season) => sportsService.importFpaSeason(season), storageRoot: config.STORAGE_ROOT, minFreeBytes: config.ARCHIVE_MIN_FREE_GB * 1e9, cpuSlots: capacity.archiveBurst, localDirs: localDirs(config.ARCHIVE_LOCAL_DIRS) });
|
|
const archive = new ArchiveWorker(archiveService, { concurrency: capacity.archive, burst: capacity.archiveDownloads, intervalMs: 2000, log, pressure: new Pressure() });
|
|
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 FacePool(
|
|
Array.from({ length: capacity.faces }, () => new FaceProcess({ bin: config.FACES_BIN!, modelsDir: config.FACES_MODELS_DIR!, embedder: config.FACES_EMBEDDER })),
|
|
)
|
|
: 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 faces = faceEngine
|
|
? new FaceWorker(new FaceService({ db, storage, broadcaster, log, engine: faceEngine, jersey }), {
|
|
concurrency: capacity.faces,
|
|
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), deliveries: deliveryService }),
|
|
{ concurrency: 2, intervalMs: 1000, log },
|
|
);
|
|
|
|
const sports = config.SPORTS_SYNC === "on" ? new SportsWorker(sportsService, { log }) : undefined;
|
|
|
|
scanner.start();
|
|
if (secrets) archive.start();
|
|
autopilot.start();
|
|
sports?.start();
|
|
deliveries.start();
|
|
faces?.start();
|
|
renders?.start();
|
|
fulfilment.start();
|
|
invoices.start();
|
|
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.
|
|
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"));
|