import { createHash } from "node:crypto"; import { mkdtemp, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import sharp from "sharp"; import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest"; import { MemoryBroadcaster } from "../src/realtime.js"; import { bearer, createTestApp, login, resetDb, seedUser, type TestContext } from "./helpers.js"; describe("resumable uploads", () => { let ctx: TestContext; let dir: string; const broadcaster = new MemoryBroadcaster(); beforeAll(async () => { dir = await mkdtemp(path.join(tmpdir(), "pr-resumable-")); ctx = await createTestApp({ STORAGE_ROOT: path.join(dir, "storage"), INGEST_ROOT: path.join(dir, "ingest") }, broadcaster); }); afterAll(async () => { await ctx.app.close(); await ctx.db.$disconnect(); await rm(dir, { recursive: true, force: true }); }); beforeEach(() => resetDb(ctx.db)); it("takes a photo in chunks, survives a repeated chunk and a restart, and ingests it at the end", async () => { const { org } = await seedUser(ctx.db, "foto@fpa.pt", { org: "fpa", role: "PHOTOGRAPHER" }); const token = (await login(ctx.app, "foto@fpa.pt")).body.accessToken; const jpeg = await sharp({ create: { width: 900, height: 600, channels: 3, noise: { type: "gaussian", mean: 128, sigma: 40 } } }).jpeg({ quality: 95 }).toBuffer(); const half = Math.floor(jpeg.length / 2); const start = () => ctx.app.inject({ method: "POST", url: `/v1/orgs/${org!.id}/uploads/resumable`, headers: bearer(token), payload: { name: "IMG_0001.JPG", size: jpeg.length, fingerprint: `IMG_0001.JPG:${jpeg.length}:1760000000000` } }); const put = (id: string, offset: number, chunk: Buffer) => ctx.app.inject({ method: "PUT", url: `/v1/uploads/${id}?offset=${offset}`, headers: { ...bearer(token), "content-type": "application/offset+octet-stream" }, payload: chunk }); const first = (await start()).json() as { id: string; offset: number }; expect(first.offset).toBe(0); expect((await put(first.id, 0, jpeg.subarray(0, half))).json()).toEqual({ offset: half }); // The answer got lost and the client sends the same chunk again. expect((await put(first.id, 0, jpeg.subarray(0, half))).json()).toEqual({ error: "offset_mismatch", offset: half }); // The page reloads: the same file resumes where it stopped. const again = (await start()).json() as { id: string; offset: number }; expect(again).toMatchObject({ id: first.id, offset: half }); const done = await put(first.id, half, jpeg.subarray(half)); expect(done.statusCode).toBe(201); expect(done.json()).toMatchObject({ status: "ingested", photo: { originalName: "IMG_0001.JPG" } }); expect(await ctx.db.pendingUpload.count()).toBe(0); expect((await ctx.app.inject({ method: "GET", url: `/v1/uploads/${first.id}`, headers: bearer(token) })).statusCode).toBe(404); }); it("keeps the original on the desktop: a preview stands in for it until someone needs full resolution", async () => { const { org } = await seedUser(ctx.db, "foto@fpa.pt", { org: "fpa", role: "PHOTOGRAPHER" }); const token = (await login(ctx.app, "foto@fpa.pt")).body.accessToken; const original = await sharp({ create: { width: 1200, height: 800, channels: 3, noise: { type: "gaussian", mean: 128, sigma: 40 } } }).jpeg({ quality: 95 }).toBuffer(); const preview = await sharp(original).resize(600).jpeg().toBuffer(); const sha256 = createHash("sha256").update(original).digest("hex"); const send = async (file: Buffer, extra: object) => { const begin = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${org!.id}/uploads/resumable`, headers: bearer(token), payload: { name: "IMG_0002.JPG", size: file.length, fingerprint: `x:${file.length}`, ...extra } }); if (begin.statusCode === 200 && (begin.json() as { status?: string }).status === "duplicate") return begin; const { id } = begin.json() as { id: string }; return ctx.app.inject({ method: "PUT", url: `/v1/uploads/${id}?offset=0`, headers: { ...bearer(token), "content-type": "application/offset+octet-stream" }, payload: file }); }; const sent = await send(preview, { original: { sha256, size: original.length, width: 1200, height: 800 } }); expect(sent.statusCode).toBe(201); const photo = (sent.json() as { photo: { id: string; sha256: string; originalStored: boolean; width: number } }).photo; expect(photo).toMatchObject({ sha256, originalStored: false, width: 1200 }); // The same preview again: already here, nothing is sent. expect((await send(preview, { original: { sha256, size: original.length } })).json()).toMatchObject({ status: "duplicate" }); // 100% zoom: the original is not here; asking for it tells the desktop app over the live channel. expect((await ctx.app.inject({ method: "GET", url: `/v1/photos/${photo.id}/original`, headers: bearer(token) })).statusCode).toBe(409); const asked = await ctx.app.inject({ method: "POST", url: `/v1/photos/${photo.id}/original/request`, headers: bearer(token) }); expect(asked.statusCode).toBe(202); expect(broadcaster.sent.some((m) => m.message.type === "original.requested" && m.message.photoId === photo.id)).toBe(true); // The desktop app sends the original: it takes the preview's place. expect((await send(original, {})).statusCode).toBe(201); expect(broadcaster.sent.some((m) => m.message.type === "original.stored" && m.message.photoId === photo.id)).toBe(true); const full = await ctx.app.inject({ method: "GET", url: `/v1/photos/${photo.id}/original`, headers: bearer(token) }); expect(full.statusCode).toBe(200); expect(full.rawPayload.equals(original)).toBe(true); expect(await ctx.db.photo.count()).toBe(1); expect((await ctx.app.inject({ method: "POST", url: `/v1/photos/${photo.id}/original/request`, headers: bearer(token) })).json()).toEqual({ stored: true }); }); it("takes an original changed on the desktop since (captions written into it) as that photo's original, if it is the same photo", async () => { const { org } = await seedUser(ctx.db, "foto@fpa.pt", { org: "fpa", role: "PHOTOGRAPHER" }); const token = (await login(ctx.app, "foto@fpa.pt")).body.accessToken; const original = await sharp({ create: { width: 1200, height: 800, channels: 3, noise: { type: "gaussian", mean: 128, sigma: 40 } } }).jpeg({ quality: 95 }).toBuffer(); const sha256 = createHash("sha256").update(original).digest("hex"); const preview = await sharp(original).resize(600).jpeg().toBuffer(); const { id } = (await ctx.app.inject({ method: "POST", url: `/v1/orgs/${org!.id}/uploads/resumable`, headers: bearer(token), payload: { name: "IMG_0003.JPG", size: preview.length, fingerprint: "p", original: { sha256, size: original.length, width: 1200, height: 800 } } })).json() as { id: string }; const photo = ((await ctx.app.inject({ method: "PUT", url: `/v1/uploads/${id}?offset=0`, headers: { ...bearer(token), "content-type": "application/offset+octet-stream" }, payload: preview })).json() as { photo: { id: string } }).photo; const post = (file: Buffer) => { const boundary = "----pr-original"; const head = Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="${sha256}.jpg"\r\nContent-Type: image/jpeg\r\n\r\n`); return ctx.app.inject({ method: "POST", url: `/v1/photos/${photo.id}/original`, headers: { ...bearer(token), "content-type": `multipart/form-data; boundary=${boundary}` }, payload: Buffer.concat([head, file, Buffer.from(`\r\n--${boundary}--\r\n`)]) }); }; // Another photo (another size) is refused. const other = await sharp({ create: { width: 1000, height: 800, channels: 3, background: "#808080" } }).jpeg().toBuffer(); expect((await post(other)).statusCode).toBe(409); // The same photo with a caption written into it: a different file, the same pixel size. const captioned = await sharp(original).withMetadata({ exif: { IFD0: { ImageDescription: "SC Braga x Sporting CP" } } }).jpeg({ quality: 95 }).toBuffer(); expect(createHash("sha256").update(captioned).digest("hex")).not.toBe(sha256); expect((await post(captioned)).json()).toEqual({ stored: true }); const after = await ctx.db.photo.findUniqueOrThrow({ where: { id: photo.id } }); expect(after).toMatchObject({ originalStored: true, sha256 }); expect(await ctx.db.photo.count()).toBe(1); expect((await ctx.app.inject({ method: "GET", url: `/v1/photos/${photo.id}/original`, headers: bearer(token) })).statusCode).toBe(200); }); it("counts a full original from the desktop app's FTP as camera ingest; the autopilot edits hand uploads too", async () => { const { org } = await seedUser(ctx.db, "foto@fpa.pt", { org: "fpa", role: "PHOTOGRAPHER" }); const token = (await login(ctx.app, "foto@fpa.pt")).body.accessToken; const t = new Date("2026-10-13T15:00:00Z"); const event = await ctx.db.event.create({ data: { organizationId: org!.id, home: "ABC", away: "FCP", startsAt: t, ingestFrom: t, ingestUntil: t, iptcTemplate: {}, autopilot: { enabled: true } } }); const send = async (name: string, extra: object) => { const jpeg = await sharp({ create: { width: 900, height: 600, channels: 3, noise: { type: "gaussian", mean: 128, sigma: 40 } } }).jpeg().toBuffer(); const { id } = (await ctx.app.inject({ method: "POST", url: `/v1/orgs/${org!.id}/uploads/resumable`, headers: bearer(token), payload: { name, size: jpeg.length, fingerprint: `${name}:${jpeg.length}`, eventId: event.id, ...extra } })).json() as { id: string }; const done = await ctx.app.inject({ method: "PUT", url: `/v1/uploads/${id}?offset=0`, headers: { ...bearer(token), "content-type": "application/offset+octet-stream" }, payload: jpeg }); return ctx.db.photo.findUniqueOrThrow({ where: { id: (done.json() as { photo: { id: string } }).photo.id } }); }; expect(await send("FTP_0001.JPG", { desktop: true })).toMatchObject({ source: "DESKTOP", autopilotStatus: "PENDING" }); expect(await send("HAND_0001.JPG", {})).toMatchObject({ source: "UPLOAD", autopilotStatus: "PENDING" }); }); it("a photo that failed (a damaged file) is replaced when it is sent again", async () => { const { org } = await seedUser(ctx.db, "foto@fpa.pt", { org: "fpa", role: "PHOTOGRAPHER" }); const token = (await login(ctx.app, "foto@fpa.pt")).body.accessToken; const original = await sharp({ create: { width: 900, height: 600, channels: 3, background: "#456" } }).jpeg().toBuffer(); const sha256 = createHash("sha256").update(original).digest("hex"); const send = async (file: Buffer, extra: object) => { const begin = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${org!.id}/uploads/resumable`, headers: bearer(token), payload: { name: "PSR1.JPG", size: file.length, fingerprint: `f:${file.length}:${Math.random()}`, ...extra } }); if ((begin.json() as { status?: string }).status === "duplicate") return begin; const { id } = begin.json() as { id: string }; return ctx.app.inject({ method: "PUT", url: `/v1/uploads/${id}?offset=0`, headers: { ...bearer(token), "content-type": "application/offset+octet-stream" }, payload: file }); }; // A broken "preview" (the bytes as text, as an old bridge sent them). const broken = Buffer.from([...original.subarray(0, 300)].join(",")); const bad = await send(broken, { original: { sha256, size: original.length } }); expect((bad.json() as { photo: { status: string } }).photo.status).toBe("FAILED"); const failed = await ctx.app.inject({ method: "GET", url: `/v1/orgs/${org!.id}/photos?status=FAILED`, headers: bearer(token) }); expect((failed.json() as { total: number }).total).toBe(1); // The desktop app sends the original: it takes the failed photo's place and is processed. const good = await send(original, {}); expect(good.statusCode).toBe(201); expect((good.json() as { photo: { status: string; sha256: string; originalStored: boolean } }).photo).toMatchObject({ status: "READY", sha256, originalStored: true }); expect(await ctx.db.photo.count()).toBe(1); }); });