From 5c4b4e5195aa0f90cb136cd765967520e26c40cd Mon Sep 17 00:00:00 2001 From: spark Date: Sat, 17 Oct 2026 15:40:08 +0100 Subject: [PATCH] Faces: a requested event jumps the analysis queue. 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. --- .../migration.sql | 6 ++ apps/api/prisma/schema.prisma | 4 ++ apps/api/src/app.ts | 9 ++- apps/api/src/archive/service.ts | 3 +- apps/api/src/faces/heartbeat.ts | 27 ++++++++ apps/api/src/faces/routes.ts | 24 +++++-- apps/api/src/faces/service.ts | 51 +++++++++++++-- apps/api/src/ingest/service.ts | 11 +++- apps/api/src/library/adopt.ts | 7 +- apps/api/src/worker.ts | 8 ++- apps/api/test/face-heartbeat.test.ts | 25 ++++++++ apps/api/test/faces.test.ts | 64 +++++++++++++++++++ apps/api/test/helpers.ts | 4 +- apps/app/src/i18n.ts | 1 + apps/app/src/library/FacesView.tsx | 10 ++- packages/sdk/src/client.ts | 2 +- 16 files changed, 232 insertions(+), 24 deletions(-) create mode 100644 apps/api/prisma/migrations/20261017130000_face_queue_boost/migration.sql create mode 100644 apps/api/src/faces/heartbeat.ts create mode 100644 apps/api/test/face-heartbeat.test.ts diff --git a/apps/api/prisma/migrations/20261017130000_face_queue_boost/migration.sql b/apps/api/prisma/migrations/20261017130000_face_queue_boost/migration.sql new file mode 100644 index 0000000..08a785d --- /dev/null +++ b/apps/api/prisma/migrations/20261017130000_face_queue_boost/migration.sql @@ -0,0 +1,6 @@ +-- Someone asking to analyse one event jumps its photos ahead of the oldest-first backlog. +ALTER TABLE "events" ADD COLUMN "face_boosted_at" TIMESTAMP(3); +ALTER TABLE "photos" ADD COLUMN "faces_boosted_at" TIMESTAMP(3); + +DROP INDEX "photos_faces_pending_idx"; +CREATE INDEX "photos_faces_pending_idx" ON "photos" ("faces_boosted_at" DESC NULLS LAST, "created_at") WHERE "faces_status" = 'PENDING'; diff --git a/apps/api/prisma/schema.prisma b/apps/api/prisma/schema.prisma index c8c5d3a..7652b83 100644 --- a/apps/api/prisma/schema.prisma +++ b/apps/api/prisma/schema.prisma @@ -254,6 +254,8 @@ model Event { iptcTemplate Json @map("iptc_template") /// Autopilot settings (contracts AutopilotSettings); null: off. autopilot Json? + /// Set when someone asks to analyse this event now: its photos jump the face queue (the backlog is oldest-first). + faceBoostedAt DateTime? @map("face_boosted_at") /// The official match this event covers, and its teams (squads, names for codes, faces and numbers). fixtureId String? @map("fixture_id") @db.Uuid homeTeamId String? @map("home_team_id") @db.Uuid @@ -393,6 +395,8 @@ model Photo { embeddedIptc Json? @map("embedded_iptc") /// Face analysis: NONE (organization without biometrics), PENDING, DONE or FAILED. facesStatus FacesStatus @default(NONE) @map("faces_status") + /// When the event was asked to the front of the face queue. Null waits behind every boosted photo. + facesBoostedAt DateTime? @map("faces_boosted_at") /// Autopilot queue (docs/photo-editing-rules.md): NONE unless the event's autopilot took this photo. autopilotStatus FacesStatus @default(NONE) @map("autopilot_status") /// What the autopilot saw and did: subject, crop, angle, frame score, burst decision. diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index 4b43021..24a5b88 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -32,6 +32,7 @@ import { registerFaceRoutes } from "./faces/routes.js"; import { FaceLookup, IdleEngine } from "./faces/lookup.js"; import { registerLookupRoutes } from "./faces/lookupRoutes.js"; import { type FaceEngine, FaceProcess } from "./faces/process.js"; +import { faceWorkerLive } from "./faces/heartbeat.js"; import { faceEnginePaths } from "./lib/engines.js"; import { registerJerseyRoutes } from "./jersey/routes.js"; import { JerseyService } from "./jersey/service.js"; @@ -73,13 +74,15 @@ export interface AppDeps { reporter?: ErrorReporter; /** The face engine for search by photo (tests pass a fake; otherwise the built engine, started on demand). */ faceEngine?: FaceEngine; + /** Whether the worker is running face analysis. Tests set this; otherwise a heartbeat file next to storage. */ + engineOnline?: () => boolean; } /** * Builds the API. Modules (ingest, library, oplog, galleries, sales, events, print, delivery) register here as * they are built. */ -export async function buildApp({ config, db, realtime, fetchImpl, reporter: given, faceEngine }: AppDeps): Promise { +export async function buildApp({ config, db, realtime, fetchImpl, reporter: given, faceEngine, engineOnline }: AppDeps): Promise { const reporter = given ?? reporterFor(config); const app = Fastify({ // Error lines (and warnings carrying an error) also go to errors.bitreport.pt. @@ -143,7 +146,9 @@ export async function buildApp({ config, db, realtime, fetchImpl, reporter: give await registerUploadRoutes(app, { db, sessions, ingest, storage, signer }); // The API never runs the face engine: it confirms and merges groups; the worker detects and groups. const faces = new FaceService({ db, storage, broadcaster, log: app.log }); - await registerFaceRoutes(app, { db, sessions, faces, signer, storage }); + // The worker writes the heartbeat. Tests have no worker, so they say the engine is on unless a case says otherwise. + const facesOnline = engineOnline ?? (() => (config.NODE_ENV === "test" ? true : faceEnginePaths(config) !== null && faceWorkerLive(config.STORAGE_ROOT))); + await registerFaceRoutes(app, { db, sessions, faces, signer, storage, engineOnline: facesOnline }); // Search by photo (library and "Encontra-te" on the sites): the API's own face engine, started on demand. const facePaths = faceEnginePaths(config); const lookupEngine = new IdleEngine( diff --git a/apps/api/src/archive/service.ts b/apps/api/src/archive/service.ts index 6deb57b..3647e49 100644 --- a/apps/api/src/archive/service.ts +++ b/apps/api/src/archive/service.ts @@ -754,7 +754,8 @@ export class ArchiveService { await db.photo.findMany({ where: { id: { in: ids }, source: "CLOUD", NOT: { eventId }, ...(previous ? { OR: [{ eventId: previous }, { eventId: null }] } : {}) }, select: { id: true } }) ).map((p) => p.id); if (moving.length) { - await db.photo.updateMany({ where: { id: { in: moving } }, data: { eventId } }); + const faceBoostedAt = (await db.event.findUnique({ where: { id: eventId }, select: { faceBoostedAt: true } }))?.faceBoostedAt ?? null; + await db.photo.updateMany({ where: { id: { in: moving } }, data: { eventId, facesBoostedAt: faceBoostedAt } }); // Their faces belonged to the other event's groups: taken out of them, and found again in the new event. await db.face.deleteMany({ where: { photoId: { in: moving } } }); await db.photo.updateMany({ where: { id: { in: moving }, facesStatus: { in: ["DONE", "FAILED", "RUNNING"] } }, data: { facesStatus: "PENDING" } }); diff --git a/apps/api/src/faces/heartbeat.ts b/apps/api/src/faces/heartbeat.ts new file mode 100644 index 0000000..d0e58f9 --- /dev/null +++ b/apps/api/src/faces/heartbeat.ts @@ -0,0 +1,27 @@ +import { mkdirSync, renameSync, statSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; + +/** No beat for this long means the worker is not running face analysis. */ +export const FACE_HEARTBEAT_STALE_MS = 90_000; + +/** Written by the face worker, read by the API. Both share the storage directory. */ +export function faceHeartbeatPath(storageRoot: string): string { + return join(storageRoot, ".photoreport", "faces-heartbeat"); +} + +export function touchFaceHeartbeat(storageRoot: string, now = new Date()): void { + const path = faceHeartbeatPath(storageRoot); + mkdirSync(join(storageRoot, ".photoreport"), { recursive: true }); + const tmp = `${path}.${process.pid}.tmp`; + writeFileSync(tmp, now.toISOString()); + renameSync(tmp, path); +} + +/** True when the worker has written a beat recently. A missing file means face analysis never started. */ +export function faceWorkerLive(storageRoot: string, now = Date.now(), staleMs = FACE_HEARTBEAT_STALE_MS): boolean { + try { + return now - statSync(faceHeartbeatPath(storageRoot)).mtimeMs < staleMs; + } catch { + return false; + } +} diff --git a/apps/api/src/faces/routes.ts b/apps/api/src/faces/routes.ts index 1152ec9..e02aef5 100644 --- a/apps/api/src/faces/routes.ts +++ b/apps/api/src/faces/routes.ts @@ -35,7 +35,10 @@ const FileQuery = z.object({ exp: z.coerce.number().int(), sig: z.string().min(1 const personOut = (p: { id: string; name: string; club: string | null; number: string | null } | null) => p ? { id: p.id, name: p.name, club: p.club, number: p.number } : null; -export async function registerFaceRoutes(app: FastifyInstance, deps: { db: Db; sessions: SessionService; faces: FaceService; signer: UrlSigner; storage: LocalStorage }) { +export async function registerFaceRoutes( + app: FastifyInstance, + deps: { db: Db; sessions: SessionService; faces: FaceService; signer: UrlSigner; storage: LocalStorage; engineOnline?: () => boolean }, +) { const { db, faces, signer, storage } = deps; const authenticate = requireAuth(deps.sessions); const fail = (err: unknown): never => { @@ -103,7 +106,7 @@ export async function registerFaceRoutes(app: FastifyInstance, deps: { db: Db; s preview: signer.url(f.photoId, "preview"), })), })); - return { groups: out, pending, unclear }; + return { groups: out, pending, unclear, available: deps.engineOnline ? deps.engineOnline() : true }; }); app.post("/v1/face-groups/:groupId/confirm", { preHandler: authenticate }, async (req) => { @@ -258,18 +261,27 @@ export async function registerFaceRoutes(app: FastifyInstance, deps: { db: Db; s data: { biometricsEnabled: body.enabled, ...(body.legalBasis !== undefined && { biometricsLegalBasis: body.legalBasis }) }, }); // Switched on: the photos already here are analysed too, not only the ones that arrive from now on. - if (org.biometricsEnabled) await db.photo.updateMany({ where: { organizationId: orgId, status: "READY", facesStatus: "NONE" }, data: { facesStatus: "PENDING" } }); + if (org.biometricsEnabled) { + await db.$executeRaw` + UPDATE photos AS p + SET faces_status = 'PENDING', + faces_boosted_at = (SELECT e.face_boosted_at FROM events e WHERE e.id = p.event_id), + updated_at = now() + WHERE p.organization_id = ${orgId}::uuid AND p.status = 'READY' AND p.faces_status = 'NONE'`; + } return { enabled: org.biometricsEnabled, legalBasis: org.biometricsLegalBasis }; }); - /** Analyse (again) the photos of an event, e.g. after switching face analysis on. */ + /** + * Analyse this event ahead of the backlog. Photos already waiting jump the queue; a RUNNING photo is queued + * again only when the worker has left it (it is not the one being analysed right now). + */ app.post("/v1/events/:eventId/faces/analyse", { preHandler: authenticate }, async (req) => { const { eventId } = EventParams.parse(req.params); const event = await db.event.findUnique({ where: { id: eventId }, include: { organization: { select: { biometricsEnabled: true } } } }); if (!event) throw notFound("event_not_found"); await requireMembership(db, req, event.organizationId, "EDITOR"); if (!event.organization.biometricsEnabled) throw conflict("biometrics_disabled"); - const r = await db.photo.updateMany({ where: { eventId, status: "READY", facesStatus: { in: ["NONE", "FAILED"] } }, data: { facesStatus: "PENDING" } }); - return { queued: r.count }; + return { queued: await faces.boostEvent(eventId) }; }); } diff --git a/apps/api/src/faces/service.ts b/apps/api/src/faces/service.ts index 619fb12..1f17e41 100644 --- a/apps/api/src/faces/service.ts +++ b/apps/api/src/faces/service.ts @@ -22,7 +22,8 @@ import type { FaceEngine } from "./process.js"; /** Faces this small (fraction of the photo's longer side) are crowd, not subjects. */ const MIN_FACE_SIDE = 0.012; -const STALE_RUNNING_MS = 10 * 60_000; +/** A photo left RUNNING this long is no longer being analysed (the worker stopped mid-photo). */ +export const STALE_RUNNING_MS = 10 * 60_000; export class FaceRejected extends Error { constructor(readonly code: string) { @@ -58,7 +59,7 @@ export class FaceService { UPDATE photos SET faces_status = 'RUNNING', updated_at = now() WHERE id IN ( SELECT id FROM photos WHERE faces_status = 'PENDING' AND status = 'READY' - ORDER BY created_at LIMIT ${limit} FOR UPDATE SKIP LOCKED + ORDER BY faces_boosted_at DESC NULLS LAST, created_at LIMIT ${limit} FOR UPDATE SKIP LOCKED ) RETURNING id`; return rows.map((r) => r.id); @@ -82,9 +83,33 @@ export class FaceService { * while a toggle raced their ingest): queue them. Cheap; the worker runs it at start and every minute. */ async queueMissed(): Promise { + // A boosted event keeps that place in the queue for photos that were missed, not only the ones already pending. + return Number( + await this.deps.db.$executeRaw` + UPDATE photos AS p + SET faces_status = 'PENDING', + faces_boosted_at = (SELECT e.face_boosted_at FROM events e WHERE e.id = p.event_id), + updated_at = now() + FROM organizations o + WHERE p.organization_id = o.id AND o.biometrics_enabled AND p.faces_status = 'NONE' AND p.status = 'READY'`, + ); + } + + /** + * The "Analisar caras" button: this event's photos go ahead of the oldest-first backlog, including ones already + * pending. A photo the worker is analysing right now (RUNNING, recently touched) is left alone; one it abandoned + * is queued again. + */ + async boostEvent(eventId: string, now = new Date()): Promise { + const staleBefore = new Date(now.getTime() - STALE_RUNNING_MS); + await this.deps.db.event.update({ where: { id: eventId }, data: { faceBoostedAt: now } }); const r = await this.deps.db.photo.updateMany({ - where: { facesStatus: "NONE", status: "READY", organization: { biometricsEnabled: true } }, - data: { facesStatus: "PENDING" }, + where: { + eventId, + status: "READY", + OR: [{ facesStatus: { in: ["NONE", "FAILED", "PENDING"] } }, { facesStatus: "RUNNING", updatedAt: { lt: staleBefore } }], + }, + data: { facesStatus: "PENDING", facesBoostedAt: now }, }); return r.count; } @@ -602,17 +627,33 @@ export class FaceWorker { private stopped = false; private ticking = false; + private lastBeat = 0; + constructor( private readonly service: FaceService, - private readonly opts: { concurrency: number; intervalMs: number; log: IngestLogger }, + private readonly opts: { concurrency: number; intervalMs: number; log: IngestLogger; heartbeat?: () => void }, ) {} + /** Lets the API tell a dead worker from a long queue. Throttled: the tick itself is every second. */ + private beat(): void { + if (!this.opts.heartbeat) return; + const now = Date.now(); + if (now - this.lastBeat < 15_000) return; + this.lastBeat = now; + try { + this.opts.heartbeat(); + } catch (err) { + this.opts.log.warn({ err }, "faces: heartbeat not written"); + } + } + start(): void { void this.service.requeueStale(); let missedAt = 0; const tick = async () => { this.ticking = true; try { + this.beat(); if (Date.now() - missedAt > 60_000) { missedAt = Date.now(); const n = await this.service.queueMissed(); diff --git a/apps/api/src/ingest/service.ts b/apps/api/src/ingest/service.ts index 2844c4c..95c53e7 100644 --- a/apps/api/src/ingest/service.ts +++ b/apps/api/src/ingest/service.ts @@ -193,11 +193,18 @@ export class IngestService { const { width, height } = origin.original?.width && origin.original.height ? { width: origin.original.width, height: origin.original.height } : made; const org = await db.organization.findUnique({ where: { id: orgId }, select: { biometricsEnabled: true } }); // The event's autopilot edits what arrives by FTP or the desktop app's ingest; hand uploads stay as sent. - const event = eventId ? await db.event.findUnique({ where: { id: eventId }, select: { autopilot: true } }) : null; + const event = eventId ? await db.event.findUnique({ where: { id: eventId }, select: { autopilot: true, faceBoostedAt: true } }) : null; const autopilot = origin.source !== "UPLOAD" && origin.source !== "CLOUD" && (event?.autopilot as { enabled?: boolean } | null)?.enabled === true; photo = await db.photo.update({ where: { id: photo.id }, - data: { status: "READY", width, height, facesStatus: org?.biometricsEnabled ? "PENDING" : "NONE", ...(autopilot && { autopilotStatus: "PENDING" }) }, + data: { + status: "READY", + width, + height, + facesStatus: org?.biometricsEnabled ? "PENDING" : "NONE", + ...(org?.biometricsEnabled && event?.faceBoostedAt && { facesBoostedAt: event.faceBoostedAt }), + ...(autopilot && { autopilotStatus: "PENDING" }), + }, }); // Photo Mechanic's "Rename as" on Live Ingest: the arrival name (camera name kept in originalName). if (origin.source !== "UPLOAD" && origin.source !== "CLOUD") await applyRename(db, photo.id).catch((err) => log.warn({ err, photoId: photo!.id }, "ingest: rename failed")); diff --git a/apps/api/src/library/adopt.ts b/apps/api/src/library/adopt.ts index d078738..d2a9560 100644 --- a/apps/api/src/library/adopt.ts +++ b/apps/api/src/library/adopt.ts @@ -8,10 +8,13 @@ import { applyRename } from "./rename.js"; */ export async function joinedEvent(db: Db, eventId: string, ids: string[]): Promise { if (!ids.length) return; - const event = await db.event.findUnique({ where: { id: eventId }, select: { autopilot: true, organization: { select: { biometricsEnabled: true } } } }); + const event = await db.event.findUnique({ where: { id: eventId }, select: { autopilot: true, faceBoostedAt: true, organization: { select: { biometricsEnabled: true } } } }); if (!event) return; if (event.organization.biometricsEnabled) { - await db.photo.updateMany({ where: { id: { in: ids }, status: "READY", facesStatus: { in: ["DONE", "FAILED"] } }, data: { facesStatus: "PENDING" } }); + await db.photo.updateMany({ + where: { id: { in: ids }, status: "READY", facesStatus: { in: ["DONE", "FAILED", "PENDING"] } }, + data: { facesStatus: "PENDING", facesBoostedAt: event.faceBoostedAt }, + }); } if ((event.autopilot as { enabled?: boolean } | null)?.enabled === true) { await db.photo.updateMany({ where: { id: { in: ids }, status: "READY", source: { not: "UPLOAD" }, autopilotStatus: "NONE" }, data: { autopilotStatus: "PENDING" } }); diff --git a/apps/api/src/worker.ts b/apps/api/src/worker.ts index 05da02e..5a2de12 100644 --- a/apps/api/src/worker.ts +++ b/apps/api/src/worker.ts @@ -20,6 +20,7 @@ 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"; @@ -117,7 +118,12 @@ const faceEngine = 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 }) + ? 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"); diff --git a/apps/api/test/face-heartbeat.test.ts b/apps/api/test/face-heartbeat.test.ts new file mode 100644 index 0000000..424ea39 --- /dev/null +++ b/apps/api/test/face-heartbeat.test.ts @@ -0,0 +1,25 @@ +import { mkdtemp, stat, utimes } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; +import { FACE_HEARTBEAT_STALE_MS, faceHeartbeatPath, faceWorkerLive, touchFaceHeartbeat } from "../src/faces/heartbeat.js"; + +describe("face worker heartbeat", () => { + const dirs: string[] = []; + afterEach(async () => { + const { rm } = await import("node:fs/promises"); + await Promise.all(dirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true }))); + }); + + it("is live just after a beat and not once the beat is old or missing", async () => { + const root = await mkdtemp(path.join(tmpdir(), "pr-face-beat-")); + dirs.push(root); + expect(faceWorkerLive(root)).toBe(false); + touchFaceHeartbeat(root, new Date("2026-10-17T12:00:00Z")); + const beat = await stat(faceHeartbeatPath(root)); + expect(faceWorkerLive(root, beat.mtimeMs + 1_000)).toBe(true); + const old = new Date(beat.mtimeMs - FACE_HEARTBEAT_STALE_MS - 1_000); + await utimes(faceHeartbeatPath(root), old, old); + expect(faceWorkerLive(root, beat.mtimeMs)).toBe(false); + }); +}); \ No newline at end of file diff --git a/apps/api/test/faces.test.ts b/apps/api/test/faces.test.ts index 7921688..e76283d 100644 --- a/apps/api/test/faces.test.ts +++ b/apps/api/test/faces.test.ts @@ -466,4 +466,68 @@ describe("faces", () => { expect(both.score).toBeGreaterThan(byFace.score); expect(both.score).toBeLessThanOrEqual(0.99); }); + + it("claims a boosted photo ahead of an older one", async () => { + const { orgId, day1 } = await setup(); + await ctx.db.photo.create({ + data: { organizationId: orgId, eventId: day1.id, source: "UPLOAD", originalName: "old.jpg", sha256: "a".repeat(64), byteSize: 1, storageKey: "old", status: "READY", facesStatus: "PENDING", createdAt: new Date("2026-10-01T00:00:00Z") }, + }); + const newer = await ctx.db.photo.create({ + data: { + organizationId: orgId, + eventId: day1.id, + source: "UPLOAD", + originalName: "new.jpg", + sha256: "b".repeat(64), + byteSize: 1, + storageKey: "new", + status: "READY", + facesStatus: "PENDING", + facesBoostedAt: new Date(), + createdAt: new Date("2026-10-02T00:00:00Z"), + }, + }); + expect(await faces.claim(1)).toEqual([newer.id]); + }); + + it("puts the event at the front of the queue and requeues a face the worker abandoned", async () => { + const { orgId, token, day1 } = await setup(); + const photoOf = (name: string, facesStatus: "PENDING" | "FAILED" | "RUNNING") => + ctx.db.photo.create({ + data: { organizationId: orgId, eventId: day1.id, source: "UPLOAD", originalName: name, sha256: name.padEnd(64, "0"), byteSize: 1, storageKey: name, status: "READY", facesStatus }, + }); + const pending = await photoOf("pending.jpg", "PENDING"); + const failed = await photoOf("failed.jpg", "FAILED"); + const fresh = await photoOf("fresh.jpg", "RUNNING"); + const stale = await photoOf("stale.jpg", "RUNNING"); + const aged = await ctx.db.$executeRaw`UPDATE photos SET updated_at = ${new Date(Date.now() - 60 * 60_000)} WHERE id = ${stale.id}::uuid`; + expect(aged).toBe(1); + const res = await ctx.app.inject({ method: "POST", url: `/v1/events/${day1.id}/faces/analyse`, headers: bearer(token) }); + expect(res.statusCode).toBe(200); + expect(res.json()).toEqual({ queued: 3 }); + const statusOf = async (id: string) => ctx.db.photo.findUniqueOrThrow({ where: { id }, select: { facesStatus: true, facesBoostedAt: true } }); + expect(await statusOf(pending.id)).toMatchObject({ facesStatus: "PENDING" }); + expect((await statusOf(pending.id)).facesBoostedAt).not.toBeNull(); + expect((await statusOf(failed.id)).facesStatus).toBe("PENDING"); + expect((await statusOf(stale.id)).facesStatus).toBe("PENDING"); + expect((await statusOf(fresh.id)).facesStatus).toBe("RUNNING"); + expect((await statusOf(fresh.id)).facesBoostedAt).toBeNull(); + const event = await ctx.db.event.findUniqueOrThrow({ where: { id: day1.id }, select: { faceBoostedAt: true } }); + expect(event.faceBoostedAt).not.toBeNull(); + const listed = await ctx.app.inject({ method: "GET", url: `/v1/events/${day1.id}/face-groups`, headers: bearer(token) }); + expect(listed.json()).toMatchObject({ available: true, pending: 4 }); + }); + + it("says face analysis is unavailable when the worker engine is not running", async () => { + const off = await createTestApp({ STORAGE_ROOT: ctx.config.STORAGE_ROOT, INGEST_ROOT: ingestRoot }, broadcaster, undefined, () => false); + try { + const { token, day1 } = await setup(); + const res = await off.app.inject({ method: "GET", url: `/v1/events/${day1.id}/face-groups`, headers: bearer(token) }); + expect(res.statusCode).toBe(200); + expect(res.json()).toMatchObject({ available: false, groups: [] }); + } finally { + await off.app.close(); + await off.db.$disconnect(); + } + }); }); diff --git a/apps/api/test/helpers.ts b/apps/api/test/helpers.ts index dfa1216..875ec43 100644 --- a/apps/api/test/helpers.ts +++ b/apps/api/test/helpers.ts @@ -13,7 +13,7 @@ export interface TestContext { config: Config; } -export async function createTestApp(overrides: Record = {}, realtime?: Broadcaster, fetchImpl?: typeof fetch): Promise { +export async function createTestApp(overrides: Record = {}, realtime?: Broadcaster, fetchImpl?: typeof fetch, engineOnline?: () => boolean): Promise { const config = loadConfig({ NODE_ENV: "test", DATABASE_URL: assertTestDatabase(process.env.DATABASE_URL_TEST), @@ -23,7 +23,7 @@ export async function createTestApp(overrides: Record = {}, real ...overrides, }); const db = createDb(config.DATABASE_URL); - const app = await buildApp({ config, db, ...(realtime && { realtime }), ...(fetchImpl && { fetchImpl }) }); + const app = await buildApp({ config, db, ...(realtime && { realtime }), ...(fetchImpl && { fetchImpl }), ...(engineOnline && { engineOnline }) }); return { app, db, config }; } diff --git a/apps/app/src/i18n.ts b/apps/app/src/i18n.ts index ca70931..2c63f1f 100644 --- a/apps/app/src/i18n.ts +++ b/apps/app/src/i18n.ts @@ -186,6 +186,7 @@ export const t = { queued: (n: number) => (n ? `${n} fotos em fila para análise` : "Não há fotos por analisar"), disabled: "O reconhecimento de caras está desligado nesta organização.", working: "A analisar as fotos…", + unavailable: (n: number) => (n > 0 ? `Análise de caras indisponível (${n} ${n === 1 ? "foto por analisar" : "fotos por analisar"}).` : "Análise de caras indisponível."), showSingles: (n: number) => `Mostrar ${n} ${n === 1 ? "cara que aparece" : "caras que aparecem"} só numa foto`, hideSingles: "Esconder caras que aparecem só numa foto", unclear: (n: number) => `${n} ${n === 1 ? "cara desfocada ficou" : "caras desfocadas ficaram"} de fora (público, fundo)`, diff --git a/apps/app/src/library/FacesView.tsx b/apps/app/src/library/FacesView.tsx index 729fe37..d3fadd0 100644 --- a/apps/app/src/library/FacesView.tsx +++ b/apps/app/src/library/FacesView.tsx @@ -204,6 +204,7 @@ function GroupCard(props: { export function FacesView({ api, orgId, eventId, canAnalyse, refreshKey }: { api: ApiClient; orgId: string; eventId: string; canAnalyse: boolean; refreshKey: number }) { const [groups, setGroups] = useState(null); const [pending, setPending] = useState(0); + const [engineOn, setEngineOn] = useState(true); const [unclear, setUnclear] = useState(0); const [showSingles, setShowSingles] = useState(false); const [people, setPeople] = useState([]); @@ -217,6 +218,7 @@ export function FacesView({ api, orgId, eventId, canAnalyse, refreshKey }: { api setGroups(r.groups); setPending(r.pending); setUnclear(r.unclear ?? 0); + setEngineOn(r.available !== false); }, () => setGroups([]), ); @@ -243,12 +245,16 @@ export function FacesView({ api, orgId, eventId, canAnalyse, refreshKey }: { api const isSingle = (g: FaceGroupSummary) => g.size === 1 && !g.person && !g.suggestion; const singles = (groups ?? []).filter(isSingle).length; const shown = (groups ?? []).filter((g) => showSingles || !isSingle(g)); + let empty: string = t.faces.none; + if (!engineOn) empty = t.faces.unavailable(pending); + else if (pending > 0) empty = t.faces.working; return (
{t.faces.summary(groups?.length ?? 0, open)} - {pending > 0 && {t.faces.pending(pending)}} + {pending > 0 && engineOn && {t.faces.pending(pending)}} + {!engineOn && {t.faces.unavailable(pending)}} {unclear > 0 && {t.faces.unclear(unclear)}} {t.numbers.title} @@ -293,7 +299,7 @@ export function FacesView({ api, orgId, eventId, canAnalyse, refreshKey }: { api {groups === null ? (

…

) : groups.length === 0 ? ( -

{pending ? t.faces.working : t.faces.none}

+

{empty}

) : (
{shown.map((g) => ( diff --git a/packages/sdk/src/client.ts b/packages/sdk/src/client.ts index 86b0b98..e3e8543 100644 --- a/packages/sdk/src/client.ts +++ b/packages/sdk/src/client.ts @@ -685,7 +685,7 @@ export class ApiClient { // ---- faces ------------------------------------------------------------------------------------------ faceGroups(eventId: string) { - return this.request<{ groups: FaceGroupSummary[]; pending: number; unclear: number }>("GET", `/v1/events/${eventId}/face-groups`); + return this.request<{ groups: FaceGroupSummary[]; pending: number; unclear: number; available?: boolean }>("GET", `/v1/events/${eventId}/face-groups`); } confirmFaceGroup(groupId: string, who: ConfirmFaceGroup) { -- 2.47.3