From 7c67a23cb9f8a8e86c92fdcefac8df6e6d78b074 Mon Sep 17 00:00:00 2001 From: spark Date: Sat, 17 Oct 2026 15:14:55 +0000 Subject: [PATCH] Delivery: take a photo back from its destinations when it is rejected or un-picked MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A photo could be pulled off a destination only on ZeroZero, and only when an edit replaced it. Now a delivered photo that is rejected, or un-picked (PICK -> none), is taken back from every destination, and an edit that moves the file to a new folder or name removes the old one on every transport (not just ZeroZero), so no orphan is left behind. - Transport gains remove(remotePath); implemented for Nextcloud (WebDAV DELETE), SFTP, FTP and Dropbox (ZeroZero already had it). Missing-file is never an error. - delivery_items gains a `retract` flag and a RETRACTED terminal status. A rejected or un-picked photo's deliveries are queued for removal (DONE/WAITING) or cancelled outright (QUEUED, never uploaded); the worker removes them and marks them RETRACTED. - The flag PATCH triggers the retraction (REJECT for any, or the photos still PICK when they go to none, i.e. un-pick), reading the old flags first. - deliveryState() ignores RETRACTED, so a taken-back photo reads as not delivered. Destructive on the client's live destinations (it deletes delivered files, agency FTP included, by request). Not run locally — no toolchain/space on this machine; needs CI to compile and a throwaway target to try before production. Claude-Session: https://claude.ai/code/session_01RAkmwWv6L5KmpX4h9JPD2i --- .../migration.sql | 5 ++ apps/api/prisma/schema.prisma | 6 ++- apps/api/src/delivery/nextcloud.ts | 7 +++ apps/api/src/delivery/service.ts | 48 ++++++++++++++++++- apps/api/src/delivery/transports.ts | 40 ++++++++++++++++ apps/api/src/library/photos.ts | 10 ++++ packages/contracts/src/library.ts | 10 ++-- 7 files changed, 119 insertions(+), 7 deletions(-) create mode 100644 apps/api/prisma/migrations/20261017180000_delivery_retract/migration.sql diff --git a/apps/api/prisma/migrations/20261017180000_delivery_retract/migration.sql b/apps/api/prisma/migrations/20261017180000_delivery_retract/migration.sql new file mode 100644 index 0000000..4b0cbe9 --- /dev/null +++ b/apps/api/prisma/migrations/20261017180000_delivery_retract/migration.sql @@ -0,0 +1,5 @@ +-- A delivered photo that is rejected or un-picked is taken back from the destination. +-- PostgreSQL 12+ allows ADD VALUE inside a transaction as long as the new value is not used in the same one. +ALTER TYPE "DeliveryStatus" ADD VALUE IF NOT EXISTS 'RETRACTED'; + +ALTER TABLE "delivery_items" ADD COLUMN "retract" BOOLEAN NOT NULL DEFAULT false; diff --git a/apps/api/prisma/schema.prisma b/apps/api/prisma/schema.prisma index 7652b83..20de581 100644 --- a/apps/api/prisma/schema.prisma +++ b/apps/api/prisma/schema.prisma @@ -518,6 +518,8 @@ enum DeliveryStatus { WAITING DONE FAILED + /// Taken back from the destination after the photo was rejected, un-picked, or cancelled before upload. + RETRACTED } /// Where a client's photos go, and how folders and files are named there (each client has its own rules). @@ -582,8 +584,10 @@ model DeliveryItem { remotePath String? @map("remote_path") /// The photo's edit (op-log sequence) the delivered file shows: edited again after it, it is sent again. deliveredSeq Int? @map("delivered_seq") - /// Being sent again after an edit: where the previous version is (taken back on ZeroZero once the new one is up). + /// Being sent again after an edit: where the previous version is (the old file is removed once the new one lands). replacesPath String? @map("replaces_path") + /// Queued to be taken back from the destination (the photo was rejected or un-picked): the worker removes it. + retract Boolean @default(false) byteSize Int? @map("byte_size") requestedById String? @map("requested_by_id") @db.Uuid nextAttemptAt DateTime @default(now()) @map("next_attempt_at") diff --git a/apps/api/src/delivery/nextcloud.ts b/apps/api/src/delivery/nextcloud.ts index ebaf855..f3cb2fd 100644 --- a/apps/api/src/delivery/nextcloud.ts +++ b/apps/api/src/delivery/nextcloud.ts @@ -78,6 +78,13 @@ export class NextcloudClient { if (res.status !== 201 && res.status !== 204) throw new NextcloudError(`PUT ${remoteFile} failed: ${res.status}`, res.status); } + /** Removes a file (idempotent: a missing file is not an error). */ + async remove(remoteFile: string): Promise { + const res = await this.call("DELETE", this.davUrl(remoteFile)); + // 204/200 removed, 404 already gone, 423 locked (worth a retry). + if (res.status !== 204 && res.status !== 200 && res.status !== 404) throw new NextcloudError(`DELETE ${remoteFile} failed: ${res.status}`, res.status); + } + /** Public, read-only link to a folder; reuses an existing link when there is one. */ async shareLink(folder: string): Promise { const base = this.auth.baseUrl.replace(/\/+$/, ""); diff --git a/apps/api/src/delivery/service.ts b/apps/api/src/delivery/service.ts index 7f43882..357a9a6 100644 --- a/apps/api/src/delivery/service.ts +++ b/apps/api/src/delivery/service.ts @@ -58,6 +58,26 @@ export function deliveredName(photo: { originalName: string; fileName: string | /** Where a file rendered for a computer's folder waits on the server. */ export const localKey = (orgId: string, itemId: string) => `${orgId}/deliveries/${itemId}.jpg`; +/** + * Marks a photo's deliveries to be taken back (the photo was rejected or un-picked). Already on a destination + * (DONE) or waiting for a computer (WAITING): queued for the worker to remove. Not uploaded yet (QUEUED): + * cancelled outright. Returns how many are queued for removal. + */ +export async function retractPhotos(db: Db, organizationId: string, photoIds: string[]): Promise { + if (!photoIds.length) return 0; + // Not uploaded yet: cancel, there is nothing on the destination to remove. + await db.deliveryItem.updateMany({ + where: { organizationId, photoId: { in: photoIds }, status: "QUEUED", retract: false }, + data: { status: "RETRACTED", finishedAt: new Date() }, + }); + // Already delivered, or waiting for a computer to take it: the worker takes it back. + const r = await db.deliveryItem.updateMany({ + where: { organizationId, photoId: { in: photoIds }, status: { in: ["DONE", "WAITING"] }, retract: false }, + data: { status: "QUEUED", retract: true, attempts: 0, nextAttemptAt: new Date(), lastError: null, finishedAt: null }, + }); + return r.count; +} + export class DeliveryRejected extends Error { constructor(readonly code: string) { super(code); @@ -279,6 +299,28 @@ export class DeliveryService { async process(itemId: string): Promise { const { db, storage, log } = this.deps; const item = await db.deliveryItem.findUniqueOrThrow({ where: { id: itemId }, include: { target: true, photo: { include: { uploader: { select: { name: true } } } }, event: true } }); + // Taking a delivery back: the photo was rejected or un-picked. Remove it from the destination (or drop the + // copy still waiting on the server for a computer), never an upload. + if (item.retract) { + let retractUpdate: Partial; + try { + if (item.target.kind === "LOCAL") await storage.remove(localKey(item.organizationId, item.id)).catch(() => {}); + else if (item.remotePath) await this.client(item.target).remove(item.remotePath); + retractUpdate = { status: "RETRACTED", retract: false, remotePath: null, lastError: null, finishedAt: new Date() }; + log.info({ itemId, remotePath: item.remotePath }, "delivery: taken back from the destination"); + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + const retry = !(err instanceof DeliveryRejected) && isTransient(err); + retractUpdate = + retry && item.attempts < MAX_ATTEMPTS + ? { status: "QUEUED", lastError: message, nextAttemptAt: new Date(Date.now() + backoffMs(item.attempts)) } + : { status: "FAILED", retract: false, lastError: `retract: ${message}`, finishedAt: new Date() }; + log.warn({ itemId, attempt: item.attempts, error: message, final: retractUpdate.status === "FAILED" }, "delivery: retract failed"); + } + const saved = await db.deliveryItem.update({ where: { id: itemId }, data: retractUpdate }); + this.deps.broadcaster.library(saved.organizationId, { type: "delivery.updated", item: toItemSummary(saved) }); + return saved; + } let update: Partial; // An archive photo: its original is read from the cloud it lives on. let cloud: { file: string; done: () => Promise } | null = null; @@ -339,8 +381,10 @@ export class DeliveryService { // "synced-…" means the desk already had this file, so this attempt did not put a new image up. // Taking the previous one back here would remove the only copy (the new upload never landed). const alreadyThere = remotePath.includes("/synced-"); - if (!alreadyThere && item.replacesPath && item.replacesPath !== remotePath && client instanceof ZerozeroTransport) { - await client.remove(item.replacesPath).catch((err) => log.warn({ err, itemId, previous: item.replacesPath }, "delivery: previous version not taken back")); + // When the file lands at a new path (an edit changed the folder or name), remove the old one so no orphan is + // left behind; on ZeroZero `alreadyThere` means the desk already had it, so there is nothing to take back. + if (!alreadyThere && item.replacesPath && item.replacesPath !== remotePath) { + await client.remove(item.replacesPath).catch((err) => log.warn({ err, itemId, previous: item.replacesPath }, "delivery: previous file not removed")); } const storedPath = alreadyThere && item.replacesPath ? item.replacesPath : remotePath; update = { status: "DONE", remotePath: storedPath, byteSize: data.length, lastError: null, finishedAt: new Date(), deliveredSeq: item.photo.developSeq, replacesPath: null }; diff --git a/apps/api/src/delivery/transports.ts b/apps/api/src/delivery/transports.ts index 8bda1dd..05f3e87 100644 --- a/apps/api/src/delivery/transports.ts +++ b/apps/api/src/delivery/transports.ts @@ -25,6 +25,8 @@ export interface Transport { ensureFolder(folder: string): Promise; /** Returns where the photo ended up when the service names it (an id), else nothing. */ upload(remoteFile: string, data: Buffer, meta?: UploadMeta): Promise; + /** Takes a delivered file back (retraction, or replacing one at a changed path). Missing file is not an error. */ + remove(remotePath: string): Promise; /** Public read-only link to a folder; undefined when the service has none. */ shareLink?(folder: string): Promise; /** Connects and checks the credentials; SFTP also reports the host key fingerprint. */ @@ -128,6 +130,9 @@ class NextcloudTransport implements Transport { upload(remoteFile: string, data: Buffer) { return this.client.upload(remoteFile, data); } + remove(remoteFile: string) { + return this.client.remove(remoteFile); + } shareLink(folder: string) { return this.client.shareLink(folder); } @@ -251,6 +256,18 @@ export class SftpTransport implements Transport { }); } + remove(remoteFile: string): Promise { + return this.serial.run(async () => { + const client = await this.connect(); + try { + // noErrorOK: a file already gone is fine. + await client.delete(remoteFile, true); + } catch (err) { + this.fail(err, `delete ${remoteFile}`); + } + }); + } + test(): Promise<{ fingerprint?: string }> { return this.serial.run(async () => { const client = await this.connect(); @@ -329,6 +346,19 @@ export class FtpTransport implements Transport { }); } + remove(remoteFile: string): Promise { + return this.serial.run(async () => { + const client = await this.connect(); + try { + await client.remove(remoteFile); + } catch (err) { + // 550: no such file — already gone, not an error. + if ((err as { code?: number }).code === 550) return; + this.fail(err, `delete ${remoteFile}`); + } + }); + } + test(): Promise<{ account?: string }> { return this.serial.run(async () => { const client = await this.connect(); @@ -412,6 +442,16 @@ export class DropboxTransport implements Transport { }); } + async remove(remoteFile: string): Promise { + try { + await this.rpc("files/delete_v2", { path: remoteFile }); + } catch (err) { + // Already gone is not an error. + if (err instanceof TransportError && /not_found/.test(err.message)) return; + throw err; + } + } + async shareLink(folder: string): Promise { const path = folder.replace(/\/+$/, ""); try { diff --git a/apps/api/src/library/photos.ts b/apps/api/src/library/photos.ts index 2045b67..9ce9703 100644 --- a/apps/api/src/library/photos.ts +++ b/apps/api/src/library/photos.ts @@ -14,6 +14,7 @@ import type { Broadcaster } from "../realtime.js"; import type { LocalStorage, UrlSigner, Variant } from "../storage/storage.js"; import { DEFAULT_CODE_LIST, iptcForPhoto } from "./iptc.js"; import { photoInclude, toSummary } from "./serialize.js"; +import { retractPhotos } from "../delivery/service.js"; const OrgParams = z.object({ orgId: z.uuid() }); const PhotoParams = z.object({ photoId: z.uuid() }); @@ -102,8 +103,17 @@ export async function registerPhotoRoutes( if (patch.colorLabel !== undefined) data.colorLabel = patch.colorLabel; if (patch.players !== undefined) data.players = patch.players; if (patch.eventId !== undefined) data.eventId = patch.eventId; + // A rejected or un-picked photo that was already delivered is taken back from its destinations. Un-pick is a + // PICK -> NONE change, so the photos that are still PICK right now are the ones being un-picked (read first). + const retractIds = + patch.flag === "REJECT" + ? ids + : patch.flag === "NONE" + ? (await db.photo.findMany({ where: { id: { in: ids }, organizationId: orgId, flag: "PICK" }, select: { id: true } })).map((p) => p.id) + : []; const result = await db.photo.updateMany({ where: { id: { in: ids }, organizationId: orgId }, data }); if (result.count !== ids.length) throw notFound("photo_not_found"); + if (retractIds.length) await retractPhotos(db, orgId, retractIds); // Moved to another event: arrival names, faces and the autopilot follow it. if (patch.eventId) await joinedEvent(db, patch.eventId, ids); broadcaster.library(orgId, { type: "photo.updated", ids, patch }); diff --git a/packages/contracts/src/library.ts b/packages/contracts/src/library.ts index 730a98a..cf5e2b9 100644 --- a/packages/contracts/src/library.ts +++ b/packages/contracts/src/library.ts @@ -62,9 +62,11 @@ export type PhotoDelivery = "NONE" | "QUEUED" | "DONE" | "FAILED"; /** A photo's overall delivery state from the status of each of its deliveries. */ export function deliveryState(statuses: readonly string[]): PhotoDelivery { - if (statuses.includes("DONE")) return "DONE"; - if (statuses.some((x) => x === "QUEUED" || x === "RUNNING" || x === "WAITING")) return "QUEUED"; - return statuses.length ? "FAILED" : "NONE"; + // A retracted (taken-back) delivery no longer counts: a photo with only those reads as not delivered. + const live = statuses.filter((x) => x !== "RETRACTED"); + if (live.includes("DONE")) return "DONE"; + if (live.some((x) => x === "QUEUED" || x === "RUNNING" || x === "WAITING")) return "QUEUED"; + return live.length ? "FAILED" : "NONE"; } export interface PhotoSummary { @@ -104,7 +106,7 @@ export interface PhotoSummary { } /** WAITING: rendered for a folder on a computer, until that computer's desktop app takes it. */ -export type DeliveryStatus = "QUEUED" | "RUNNING" | "WAITING" | "DONE" | "FAILED"; +export type DeliveryStatus = "QUEUED" | "RUNNING" | "WAITING" | "DONE" | "FAILED" | "RETRACTED"; export interface DeliveryItemSummary { id: string;