import { type DevelopState, type EditCommand, type EditLogEntry, type PostEdits, getControl } from "@photoreport/contracts"; import type { Db } from "../db.js"; import { Prisma, type PhotoEdit } from "../generated/prisma/client.js"; import type { IngestLogger } from "../ingest/service.js"; import { waitUntil } from "../lib/idle.js"; import { photoUrls } from "../library/serialize.js"; import type { Broadcaster } from "../realtime.js"; import { type LocalStorage, type UrlSigner, VARIANT_SIZE } from "../storage/storage.js"; import type { RenderEngine, Settings } from "./engine.js"; /** Edits pause this long before the worker renders new thumbnails (a slider drag sends many). */ export const RENDER_QUIET_MS = 2000; const STALE_RUNNING_MS = 5 * 60_000; export class EditRejected extends Error { constructor(readonly code: string) { super(code); } } function toEntry(e: PhotoEdit): EditLogEntry { return { seq: e.seq, opId: e.opId, clientId: e.clientId, command: e.command as EditCommand, userId: e.userId, at: e.createdAt.toISOString() }; } /** Commands are checked against the controls of the pinned engine, so a stale client cannot fill the log with junk. */ function validate(command: EditCommand): void { if (command.command !== "develop.set") return; for (const [id, value] of Object.entries(command.params.values)) { const control = getControl(id); if (!control) throw new EditRejected("unknown_control"); if (value < control.min || value > control.max) throw new EditRejected("value_out_of_range"); } } /** * The develop op log. Clients send commands (never pixels); the server orders them per photo, stores them and * fans them out, so every open window (web or desktop) replays the same sequence with its own engine. The * worker keeps a settings snapshot, renders edited thumbnails once edits pause, and deliveries render from it. */ export class DevelopService { constructor( private readonly deps: { db: Db; storage: LocalStorage; signer: UrlSigner; broadcaster: Broadcaster; log: IngestLogger; engine?: RenderEngine | undefined; /** A person (not the autopilot) changed this photo: the autopilot learns from it. */ onHumanEdit?: ((photoId: string) => void) | undefined; }, ) {} get engine(): RenderEngine | undefined { return this.deps.engine; } async state(photoId: string, since?: number): Promise { const photo = await this.deps.db.photo.findUniqueOrThrow({ where: { id: photoId }, select: { developSeq: true, developSnapshot: true, snapshotSeq: true } }); const useSnapshot = since === undefined || since < photo.snapshotSeq; const from = useSnapshot ? photo.snapshotSeq : since; const ops = await this.deps.db.photoEdit.findMany({ where: { photoId, seq: { gt: from } }, orderBy: { seq: "asc" } }); return { photoId, developSeq: photo.developSeq, snapshotSeq: from, snapshot: useSnapshot ? ((photo.developSnapshot as Settings | null) ?? null) : null, ops: ops.map(toEntry), }; } /** Appends ops in order. A repeated `opId` (a retry) returns the stored entry and is not broadcast again. */ async append(photoId: string, userId: string | null, body: PostEdits): Promise<{ developSeq: number; ops: EditLogEntry[] }> { for (const op of body.ops) validate(op.command); const { db, broadcaster } = this.deps; // Many photos are edited at once. Waiting for a connection must not drop the edit. const result = await db.$transaction(async (tx) => { const [locked] = await tx.$queryRaw<{ develop_seq: number; organization_id: string; event_id: string | null }[]>` SELECT develop_seq, organization_id, event_id FROM photos WHERE id = ${photoId}::uuid FOR UPDATE`; if (!locked) throw new EditRejected("photo_not_found"); let seq = locked.develop_seq; const existing = new Map( (await tx.photoEdit.findMany({ where: { photoId, opId: { in: body.ops.map((o) => o.opId) } } })).map((e) => [e.opId, e]), ); const out: EditLogEntry[] = []; const fresh: EditLogEntry[] = []; for (const op of body.ops) { const known = existing.get(op.opId); if (known) { out.push(toEntry(known)); continue; } seq++; const row = await tx.photoEdit.create({ data: { photoId, seq, opId: op.opId, clientId: body.clientId, command: op.command as Prisma.InputJsonValue, userId }, }); existing.set(op.opId, row); const entry = toEntry(row); out.push(entry); fresh.push(entry); } if (fresh.length) await tx.photo.update({ where: { id: photoId }, data: { developSeq: seq, editedAt: new Date(), renderStatus: "PENDING" } }); return { organizationId: locked.organization_id, eventId: locked.event_id, developSeq: seq, out, fresh }; }, { maxWait: 20_000, timeout: 20_000 }); if (result.fresh.length && body.clientId !== "autopilot") this.deps.onHumanEdit?.(photoId); if (result.fresh.length) { broadcaster.library(result.organizationId, { type: "photo.edited", photoId, eventId: result.eventId, clientId: body.clientId, developSeq: result.developSeq, ops: result.fresh, }); } return { developSeq: result.developSeq, ops: result.out }; } /** * Settings at the photo's current op-log position (null: never edited, or edited back to defaults), refreshing * the stored snapshot when ops came after it. Needs the engine. */ async settings(photoId: string): Promise<{ settings: Settings | null; seq: number }> { const { db, engine } = this.deps; const photo = await db.photo.findUniqueOrThrow({ where: { id: photoId }, select: { developSeq: true, developSnapshot: true, snapshotSeq: true } }); if (photo.developSeq === 0) return { settings: null, seq: 0 }; if (photo.snapshotSeq === photo.developSeq) return { settings: (photo.developSnapshot as Settings | null) ?? null, seq: photo.developSeq }; if (!engine) throw new Error("render worker not configured (RENDER_BIN)"); const ops = await db.photoEdit.findMany({ where: { photoId, seq: { gt: photo.snapshotSeq, lte: photo.developSeq } }, orderBy: { seq: "asc" } }); const replayed = await engine.replay((photo.developSnapshot as Settings | null) ?? null, ops.map((o) => o.command)); if (replayed.skipped.length) this.deps.log.warn({ photoId, skipped: replayed.skipped.map((i) => ops[i]?.seq) }, "develop: commands refused by the engine"); const settings = replayed.unedited ? null : replayed.settings; // Only move forward: a concurrent replay may already have stored a later snapshot. await db.photo.updateMany({ where: { id: photoId, snapshotSeq: { lt: photo.developSeq } }, data: { developSnapshot: (settings as Prisma.InputJsonValue | null) ?? Prisma.DbNull, snapshotSeq: photo.developSeq }, }); return { settings, seq: photo.developSeq }; } async claimRenders(limit: number, now = new Date()): Promise { if (limit <= 0) return []; const quiet = new Date(now.getTime() - RENDER_QUIET_MS); const rows = await this.deps.db.$queryRaw<{ id: string }[]>` UPDATE photos SET render_status = 'RUNNING', updated_at = now() WHERE id IN ( SELECT id FROM photos WHERE render_status = 'PENDING' AND edited_at <= ${quiet} ORDER BY edited_at LIMIT ${limit} FOR UPDATE SKIP LOCKED ) RETURNING id`; return rows.map((r) => r.id); } async requeueStale(now = new Date()): Promise { const r = await this.deps.db.photo.updateMany({ where: { renderStatus: "RUNNING", updatedAt: { lt: new Date(now.getTime() - STALE_RUNNING_MS) } }, data: { renderStatus: "PENDING" }, }); return r.count; } /** Renders the edited thumb and preview of one claimed photo. Never throws. */ async render(photoId: string): Promise { const { db, storage, signer, broadcaster, log, engine } = this.deps; try { if (!engine) throw new Error("render worker not configured (RENDER_BIN)"); const { settings, seq } = await this.settings(photoId); const photo = await db.photo.findUniqueOrThrow({ where: { id: photoId } }); const renderedSeq = settings ? seq : 0; if (settings) { for (const variant of ["preview", "thumb"] as const) { await engine.render({ input: storage.resolve(photo.storageKey), output: storage.resolve(storage.editedKey(photo.organizationId, photo.sha256, seq, variant)), settings, maxEdge: VARIANT_SIZE[variant], quality: variant === "thumb" ? 80 : 88, }); } } // Edits that arrived while rendering leave the photo pending for the next round. const updated = await db.photo.update({ where: { id: photoId }, data: { renderedSeq, renderStatus: (await db.photo.count({ where: { id: photoId, developSeq: seq } })) ? "DONE" : "PENDING" }, }); if (photo.renderedSeq && photo.renderedSeq !== renderedSeq) { for (const variant of ["preview", "thumb"] as const) await storage.remove(storage.editedKey(photo.organizationId, photo.sha256, photo.renderedSeq, variant)); } const urls = photoUrls(updated, signer); broadcaster.library(photo.organizationId, { type: "photo.rendered", photoId, renderedSeq, urls: { thumb: urls.thumb, preview: urls.preview } }); log.info({ photoId, seq: renderedSeq }, "develop: edit rendered"); } catch (err) { log.warn({ photoId, err: (err as Error).message }, "develop: render failed"); await db.photo.update({ where: { id: photoId }, data: { renderStatus: "FAILED" } }).catch(() => {}); } } } export class RenderWorker { private inFlight = 0; private timer: NodeJS.Timeout | undefined; private stopped = false; private ticking = false; constructor( private readonly service: DevelopService, private readonly opts: { concurrency: number; intervalMs: number; log: IngestLogger }, ) {} start(): void { void this.service.requeueStale(); const tick = async () => { this.ticking = true; try { for (const id of await this.service.claimRenders(this.opts.concurrency - this.inFlight)) { this.inFlight++; void this.service.render(id).finally(() => { this.inFlight--; }); } } catch (err) { this.opts.log.warn({ err }, "develop: poll failed"); } finally { this.ticking = false; if (!this.stopped) this.timer = setTimeout(tick, this.opts.intervalMs); } }; this.timer = setTimeout(tick, 0); } async stop(timeoutMs = 25_000): Promise { this.stopped = true; if (this.timer) clearTimeout(this.timer); const drained = await waitUntil(() => !this.ticking && this.inFlight === 0, { timeoutMs }); if (!drained) this.opts.log.warn({ inFlight: this.inFlight }, "develop: stop timed out with work still running"); } }