diff --git a/apps/api/src/archive/corrupt.test.ts b/apps/api/src/archive/corrupt.test.ts new file mode 100644 index 0000000..414d466 --- /dev/null +++ b/apps/api/src/archive/corrupt.test.ts @@ -0,0 +1,59 @@ +import { describe, expect, it } from "vitest"; +import { writeFile, mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { isTransientStatus } from "../delivery/nextcloud.js"; +import { assertDownloadComplete, CorruptSource, isCorruptSourceMessage } from "./corrupt.js"; +import { CloudClient } from "./nextcloud.js"; + +describe("isTransientStatus (BIT-31658 / BIT-31513)", () => { + it("covers lock, rate-limit and all 5xx including 502/504", () => { + for (const s of [0, 408, 423, 429, 500, 502, 503, 504]) expect(isTransientStatus(s)).toBe(true); + for (const s of [400, 401, 403, 404, 422]) expect(isTransientStatus(s)).toBe(false); + }); +}); + +describe("corrupt source classification (BIT-31658)", () => { + it("recognises ffprobe/sharp damage messages", () => { + expect(isCorruptSourceMessage("ffprobe exited 1: moov atom not found")).toBe(true); + expect(isCorruptSourceMessage("VipsJpeg: premature end of JPEG file")).toBe(true); + expect(isCorruptSourceMessage("VipsForeignLoad: not a known file format")).toBe(true); + expect(isCorruptSourceMessage("Input file has corrupt header")).toBe(true); + expect(isCorruptSourceMessage("ffmpeg exited 234: Failed to set value")).toBe(false); + }); + + it("rejects a truncated download whose size does not match WebDAV getcontentlength", async () => { + const dir = await mkdtemp(path.join(tmpdir(), "pr-corrupt-")); + try { + const file = path.join(dir, "a.jpg"); + await writeFile(file, Buffer.from("short")); + await expect(assertDownloadComplete(file, 1000n)).rejects.toBeInstanceOf(CorruptSource); + await expect(assertDownloadComplete(file, 5n)).resolves.toBeUndefined(); + await expect(assertDownloadComplete(file, null)).resolves.toBeUndefined(); + } finally { + await rm(dir, { recursive: true, force: true }); + } + }); +}); + +describe("CloudClient 502 retry then success (BIT-31658)", () => { + it("retries a 502 blip on a download and succeeds", async () => { + let calls = 0; + const whoami = (url: URL) => (url.pathname.endsWith("/ocs/v2.php/cloud/user") ? Response.json({ ocs: { data: { id: "peter" } } }) : null); + const fetchImpl: typeof fetch = async (input) => { + const url = new URL(String(input)); + const who = whoami(url); + if (who) return who; + calls++; + return calls <= 2 ? new Response(null, { status: 502 }) : new Response(new Uint8Array(Buffer.from("hello")), { status: 200 }); + }; + const client = new CloudClient({ baseUrl: "https://cloud.test", username: "peter", password: "pw" }, fetchImpl); + const dir = await mkdtemp(path.join(tmpdir(), "pr-502-")); + try { + await client.download("/a.jpg", path.join(dir, "out.jpg")); + expect(calls).toBe(3); + } finally { + await rm(dir, { recursive: true, force: true }); + } + }); +}); diff --git a/apps/api/src/archive/corrupt.ts b/apps/api/src/archive/corrupt.ts new file mode 100644 index 0000000..71419a0 --- /dev/null +++ b/apps/api/src/archive/corrupt.ts @@ -0,0 +1,26 @@ +import { stat } from "node:fs/promises"; + +/** + * Damaged file in the cloud (truncated download, incomplete sync, broken JPEG/MP4), not a codec/tool bug. + * Mark FAILED with no retry until the walk sees a new etag; log at info — never the error hub. + */ +export class CorruptSource extends Error { + constructor(reason = "corrupt_source") { + super(reason); + this.name = "CorruptSource"; + } +} + +/** ffprobe/ffmpeg/sharp messages that mean the cloud file itself is damaged, not our pipeline. */ +export function isCorruptSourceMessage(message: string): boolean { + return /moov atom not found|premature end|not a known file format|corrupt (?:jpeg )?header|Corrupt JPEG|Input file has corrupt header|Invalid data found when processing input/i.test( + message, + ); +} + +/** Downloaded bytes must match the WebDAV size the walk stored (truncated GET → corrupt_source). */ +export async function assertDownloadComplete(file: string, expected: bigint | null): Promise { + if (expected === null) return; + const got = BigInt((await stat(file)).size); + if (got !== expected) throw new CorruptSource("corrupt_source"); +} diff --git a/apps/api/src/archive/routes.ts b/apps/api/src/archive/routes.ts index f32559a..b07c037 100644 --- a/apps/api/src/archive/routes.ts +++ b/apps/api/src/archive/routes.ts @@ -67,7 +67,7 @@ export async function registerArchiveRoutes(app: FastifyInstance, deps: { db: Db // The pace: images indexed in the last 15 minutes, per hour. const recent = await db.cloudFile.groupBy({ by: ["sourceId"], where: { sourceId: { in: sourceIds }, status: "DONE", updatedAt: { gte: new Date(Date.now() - 15 * 60_000) } }, _count: { _all: true } }); const out = new Map>(); - const get = (id: string) => out.get(id) ?? out.set(id, { pending: 0, done: 0, failed: 0, galleries: 0, games: 0, named: 0, unmatched: 0, perHour: 0, videos: 0, videosPending: 0, videosFailed: 0, videoFacesPending: 0, videoFacesDone: 0, videoFacesFailed: 0 }).get(id)!; + const get = (id: string) => out.get(id) ?? out.set(id, { pending: 0, done: 0, failed: 0, failedCorrupt: 0, galleries: 0, games: 0, named: 0, unmatched: 0, perHour: 0, videos: 0, videosPending: 0, videosFailed: 0, videoFacesPending: 0, videoFacesDone: 0, videoFacesFailed: 0 }).get(id)!; for (const v of videos) { const c = get(v.sourceId); if (v.status === "DONE") c.videos! += v._count._all; @@ -87,6 +87,19 @@ export async function registerArchiveRoutes(app: FastifyInstance, deps: { db: Db else if (f.status === "FAILED") c.failed! += f._count._all; else c.pending! += f._count._all; } + // Damaged cloud files (BIT-31658): shown as "corrompido" in the archive UI, not as a tool bug. + const corruptFiles = await db.cloudFile.groupBy({ + by: ["sourceId"], + where: { sourceId: { in: sourceIds }, status: "FAILED", error: { in: ["corrupt_source", "no_video_stream"] } }, + _count: { _all: true }, + }); + const corruptVideos = await db.cloudVideo.groupBy({ + by: ["sourceId"], + where: { sourceId: { in: sourceIds }, status: "FAILED", error: { in: ["corrupt_source", "no_video_stream"] } }, + _count: { _all: true }, + }); + for (const r of corruptFiles) get(r.sourceId).failedCorrupt! += r._count._all; + for (const r of corruptVideos) get(r.sourceId).failedCorrupt! += r._count._all; for (const f of folders) { const c = get(f.sourceId); c.galleries! += f._count._all; @@ -110,7 +123,7 @@ export async function registerArchiveRoutes(app: FastifyInstance, deps: { db: Db nextScanAt: s.nextScanAt, lastError: s.lastError, loginUrl: loginUrl ?? archive.pendingLoginUrl(s), - counts: { pending: 0, done: 0, failed: 0, galleries: 0, games: 0, named: 0, unmatched: 0, perHour: 0, videos: 0, videosPending: 0, videosFailed: 0, videoFacesPending: 0, videoFacesDone: 0, videoFacesFailed: 0, ...c }, + counts: { pending: 0, done: 0, failed: 0, failedCorrupt: 0, galleries: 0, games: 0, named: 0, unmatched: 0, perHour: 0, videos: 0, videosPending: 0, videosFailed: 0, videoFacesPending: 0, videoFacesDone: 0, videoFacesFailed: 0, ...c }, }); const loadSource = async (req: Parameters[1], sourceId: string, role: "EDITOR" | "ADMIN") => { diff --git a/apps/api/src/archive/service.ts b/apps/api/src/archive/service.ts index 5e9e802..382f7fa 100644 --- a/apps/api/src/archive/service.ts +++ b/apps/api/src/archive/service.ts @@ -5,7 +5,7 @@ import { mkdir, mkdtemp, readdir, rm, stat, statfs } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { NEWSROOM_TEMPLATE, GENERAL_TEMPLATE } from "@photoreport/metadata"; -import sharp from "sharp"; +import sharp, { type Metadata } from "sharp"; import type { Db } from "../db.js"; import { NextcloudError } from "../delivery/nextcloud.js"; import type { SecretBox } from "../delivery/secrets.js"; @@ -15,7 +15,7 @@ import { ingestWindow } from "../library/events.js"; import { waitUntil } from "../lib/idle.js"; import type { LocalStorage } from "../storage/storage.js"; import { CloudClient, cleanBase, pollLogin, startLogin, type CloudEntry } from "./nextcloud.js"; -import { makeWebCopy, VIDEO, VIDEO_FILES, VideoToolMissing, type VideoTools } from "./video.js"; +import { makeWebCopy, NotAVideo, VIDEO, VIDEO_FILES, VideoToolMissing, type VideoTools } from "./video.js"; import { teamSideRows } from "./directory.js"; import { galleryAssignments } from "./gallery.js"; import { canonicalTeam, competitionLabel, describeFolder, exhibitionName, type FolderGame, isExhibition, isInitials, isTeamName, knownVersus, lisbonDay, parseFolder, pastOrToday, pickFixture, seasonOf, slashSides, teamMatcher } from "./match.js"; @@ -39,6 +39,9 @@ const seasonOfDay = (day: Date) => { export class ArchiveRejected extends Error {} +import { assertDownloadComplete, CorruptSource, isCorruptSourceMessage } from "./corrupt.js"; +export { assertDownloadComplete, CorruptSource, isCorruptSourceMessage }; + /** What a check did: galleries looked at, the ones that changed (from/to how they were matched), the ones it could not check. */ export interface RematchReport { checked: number; @@ -152,11 +155,36 @@ interface LoginState { */ export class ArchiveService { private readonly cpu: Slots; + /** Permanent index failures coalesced so the hub gets one ticket per burst, not one per photo (BIT-31658). */ + private failBatch = { count: 0, sample: null as Error | null, paths: [] as string[] }; + private failFlush: ReturnType | null = null; constructor(private readonly deps: ArchiveDeps) { this.cpu = new Slots(Math.max(1, deps.cpuSlots ?? Number.MAX_SAFE_INTEGER)); } + /** Remember a permanent index failure; flushed shortly after the burst settles (or on the next poll). */ + noteIndexFailure(err: Error, filePath: string): void { + this.failBatch.count++; + this.failBatch.sample ??= err; + if (this.failBatch.paths.length < 5) this.failBatch.paths.push(filePath); + if (this.failFlush) clearTimeout(this.failFlush); + this.failFlush = setTimeout(() => this.flushIndexFailures(), 5_000); + this.failFlush.unref?.(); + } + + /** One aggregated warn for the error hub after retries are exhausted (BIT-31658). */ + flushIndexFailures(): void { + if (this.failFlush) { + clearTimeout(this.failFlush); + this.failFlush = null; + } + const { count, sample, paths } = this.failBatch; + if (!count) return; + this.failBatch = { count: 0, sample: null, paths: [] }; + this.deps.log.warn({ err: sample, count, paths }, `archive: ${count} files failed indexing after retries`); + } + private get fetchImpl(): typeof fetch { return this.deps.fetchImpl ?? fetch; } @@ -1045,6 +1073,7 @@ export class ArchiveService { if (!original) { original = path.join(dir, "original.jpg"); await this.client(file.source).download(file.path, original); + await assertDownloadComplete(original, file.size); } const from = original; // The official game's day against the day the photos were taken: a folder matched to the wrong game is @@ -1063,13 +1092,24 @@ export class ArchiveService { const outcome = await this.cpu.run(async () => { const size = (await stat(from)).size; const sha256 = await hashFile(from); - const meta = await sharp(from).metadata(); + let meta: Metadata; + try { + meta = await sharp(from).metadata(); + } catch (err) { + if (isCorruptSourceMessage((err as Error).message)) throw new CorruptSource(); + throw err; + } const turned = (meta.orientation ?? 1) >= 5; const width = turned ? meta.height : meta.width; const height = turned ? meta.width : meta.height; const preview = path.join(dir, "preview.jpg"); // Pixels as stored and the orientation tag kept, like the desktop app's previews. - await sharp(from).resize(2048, 2048, { fit: "inside", withoutEnlargement: true }).keepMetadata().jpeg({ quality: 90 }).toFile(preview); + try { + await sharp(from).resize(2048, 2048, { fit: "inside", withoutEnlargement: true }).keepMetadata().jpeg({ quality: 90 }).toFile(preview); + } catch (err) { + if (isCorruptSourceMessage((err as Error).message)) throw new CorruptSource(); + throw err; + } return ingest.ingest(preview, { organizationId: file.source.organizationId, userId: ownerId, @@ -1080,7 +1120,13 @@ export class ArchiveService { }); }); if (outcome.status === "failed") { - await db.cloudFile.update({ where: { id: fileId }, data: { status: "FAILED", error: outcome.error, photoId: outcome.photoId } }); + const corrupt = outcome.error && isCorruptSourceMessage(outcome.error); + await db.cloudFile.update({ + where: { id: fileId }, + data: { status: "FAILED", error: corrupt ? "corrupt_source" : outcome.error, photoId: outcome.photoId }, + }); + if (corrupt) log.info({ fileId, path: file.path }, "archive: image corrupt in cloud, marked failed"); + else this.noteIndexFailure(new Error(outcome.error ?? "ingest_failed"), file.path); return; } await db.cloudFile.update({ where: { id: fileId }, data: { status: "DONE", photoId: outcome.photoId, error: null } }); @@ -1089,14 +1135,21 @@ export class ArchiveService { const message = (err as Error).message; const transient = err instanceof NextcloudError && err.transient; const gone = err instanceof NextcloudError && err.status === 404; - const retry = !gone && (transient || file.attempts < MAX_ATTEMPTS); - await db.cloudFile.update({ where: { id: fileId }, data: { status: retry ? "PENDING" : "FAILED", error: message, ...(transient && { attempts: { decrement: 1 } }) } }); + const corrupt = + err instanceof CorruptSource || (err instanceof ArchiveRejected && err.message === "corrupt_source") || isCorruptSourceMessage(message); + const retry = !gone && !corrupt && (transient || file.attempts < MAX_ATTEMPTS); + await db.cloudFile.update({ + where: { id: fileId }, + data: { status: retry ? "PENDING" : "FAILED", error: corrupt ? "corrupt_source" : message, ...(transient && { attempts: { decrement: 1 } }) }, + }); // A file moved since the walk: read its folder again next time. if (gone) await db.cloudFolder.update({ where: { id: file.folderId }, data: { etag: null } }); // A transient blip is given a free retry and costs nothing (BIT-31513): logged at info so it never reaches // the error hub as a warning, unlike a real decoding/matching failure or one burning the attempt budget. if (transient) log.info({ err, fileId, path: file.path }, "archive: image download blipped, requeued for a free retry"); - else log.warn({ err, fileId, path: file.path }, "archive: image not indexed"); + else if (corrupt) log.info({ fileId, path: file.path }, "archive: image corrupt in cloud, marked failed"); + else if (!retry) this.noteIndexFailure(err instanceof Error ? err : new Error(message), file.path); + else log.info({ err, fileId, path: file.path, attempts: file.attempts }, "archive: image not indexed, will retry"); } finally { await rm(dir, { recursive: true, force: true }); } @@ -1141,6 +1194,7 @@ export class ArchiveService { if (!original) { original = path.join(dir, `original${path.posix.extname(video.path).toLowerCase()}`); await this.client(video.source).download(video.path, original); + await assertDownloadComplete(original, video.size); } const out = path.join(dir, "out"); await mkdir(out); @@ -1170,10 +1224,21 @@ export class ArchiveService { const transient = err instanceof NextcloudError && err.transient; const gone = err instanceof NextcloudError && err.status === 404; const missing = err instanceof VideoToolMissing; - const retry = !gone && !missing && (transient || video.attempts < MAX_ATTEMPTS); - await db.cloudVideo.update({ where: { id: videoId }, data: { status: retry ? "PENDING" : "FAILED", error: message, ...(transient && { attempts: { decrement: 1 } }) } }); + const unsupported = err instanceof NotAVideo; + const corrupt = err instanceof CorruptSource || isCorruptSourceMessage(message); + const retry = !gone && !missing && !unsupported && !corrupt && (transient || video.attempts < MAX_ATTEMPTS); + const error = unsupported ? "no_video_stream" : corrupt ? "corrupt_source" : message; + await db.cloudVideo.update({ + where: { id: videoId }, + data: { status: retry ? "PENDING" : "FAILED", error, ...(transient && { attempts: { decrement: 1 } }) }, + }); if (gone) await db.cloudFolder.update({ where: { id: video.folderId }, data: { etag: null } }); - log.warn({ err, videoId, path: video.path }, "archive: video not indexed"); + if (transient) log.info({ err, videoId, path: video.path }, "archive: video download blipped, requeued for a free retry"); + else if (unsupported) log.info({ videoId, path: video.path }, "archive: not a video stream, marked failed"); + else if (corrupt) log.info({ videoId, path: video.path }, "archive: video corrupt in cloud, marked failed"); + else if (missing) log.info({ err, videoId, path: video.path }, "archive: ffmpeg missing, video waits"); + else if (!retry) this.noteIndexFailure(err instanceof Error ? err : new Error(message), video.path); + else log.info({ err, videoId, path: video.path, attempts: video.attempts }, "archive: video not indexed, will retry"); } finally { await rm(dir, { recursive: true, force: true }); } @@ -1378,6 +1443,8 @@ export class ArchiveWorker { try { await ready; try { + // Failures from the previous burst (indexes finish after claim); coalesce hub noise (BIT-31658). + this.service.flushIndexFailures(); if (!this.scanning) { this.scanning = true; // Walking runs beside the indexing (a big first walk should not hold the queue back). @@ -1444,6 +1511,7 @@ export class ArchiveWorker { this.stopped = true; if (this.timer) clearTimeout(this.timer); const drained = await waitUntil(() => !this.ticking && !this.scanning && !this.directories && this.inFlight === 0 && this.videosInFlight === 0, { timeoutMs }); + this.service.flushIndexFailures(); if (!drained) this.opts.log.warn({ inFlight: this.inFlight, videos: this.videosInFlight, scanning: this.scanning }, "archive: stop timed out with work still running"); } } diff --git a/apps/api/src/archive/video.test.ts b/apps/api/src/archive/video.test.ts index 2799bf5..f2a1119 100644 --- a/apps/api/src/archive/video.test.ts +++ b/apps/api/src/archive/video.test.ts @@ -4,7 +4,7 @@ import { tmpdir } from "node:os"; import path from "node:path"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; import { UrlSigner } from "../storage/storage.js"; -import { findVideoTools, makeWebCopy, parseRange, posterAt, readProbe, VIDEO, VideoToolMissing, webCopyArgs, probe } from "./video.js"; +import { findVideoTools, makeWebCopy, parseRange, posterAt, readProbe, requireVideoStream, VIDEO, VideoToolMissing, NotAVideo, webCopyArgs, probe } from "./video.js"; describe("archive videos", () => { it("knows a video by its name", () => { @@ -35,19 +35,39 @@ describe("archive videos", () => { { codec_type: "audio" }, ], }); - expect(info).toEqual({ durationMs: 12480, width: 1920, height: 1080, capturedAt: new Date("2025-09-13T18:42:10.000Z"), hasAudio: true }); + expect(info).toEqual({ + durationMs: 12480, + width: 1920, + height: 1080, + capturedAt: new Date("2025-09-13T18:42:10.000Z"), + hasAudio: true, + hasVideo: true, + }); // A camera that never had its clock set. expect(readProbe({ format: { tags: { creation_time: "1970-01-01T00:00:00Z" } }, streams: [{ codec_type: "video" }] }).capturedAt).toBeNull(); - expect(readProbe({ streams: [] })).toMatchObject({ durationMs: null, width: null, hasAudio: false }); + expect(readProbe({ streams: [] })).toMatchObject({ durationMs: null, width: null, hasAudio: false, hasVideo: false }); + expect(readProbe({ format: { duration: "3.0" }, streams: [{ codec_type: "audio" }] })).toMatchObject({ + hasAudio: true, + hasVideo: false, + width: null, + height: null, + }); + }); + + it("refuses indexing when there is no video stream (BIT-31658)", () => { + expect(() => requireVideoStream({ hasVideo: true })).not.toThrow(); + expect(() => requireVideoStream({ hasVideo: false })).toThrow(NotAVideo); + expect(() => requireVideoStream({ hasVideo: false })).toThrow("no_video_stream"); }); it("makes an H.264 web copy that starts at once, with or without sound", () => { const withSound = webCopyArgs("in.mov", "out.mp4", { audio: true }); - expect(withSound).toEqual(expect.arrayContaining(["libx264", "+faststart", "aac", "0:a:0"])); + expect(withSound).toEqual(expect.arrayContaining(["libx264", "+faststart", "aac", "0:a:0?"])); + expect(withSound).toContain("0:v:0?"); expect(withSound.at(-1)).toBe("out.mp4"); const silent = webCopyArgs("in.mov", "out.mp4", { audio: false }); expect(silent).toContain("-an"); - expect(silent).not.toContain("0:a:0"); + expect(silent).not.toContain("0:a:0?"); }); it("takes the poster a second in, sooner in a short clip", () => { @@ -139,4 +159,18 @@ describe.skipIf(!hasFfmpeg)("archive videos with ffmpeg", () => { expect(await makeWebCopy(tools, clip("tall.mp4", "1440x2560", false), portrait)).toMatchObject({ width: 1080, height: 1920, hasAudio: false }); expect(await makeWebCopy(tools, clip("small.mp4", "640x360", false), small)).toMatchObject({ width: 640, height: 360 }); }, 60_000); + + it("marks audio-only files unsupported instead of failing on -map 0:v:0 (BIT-31658)", async () => { + const audioOnly = path.join(dir, "sound.mp4"); + execFileSync("ffmpeg", [ + "-hide_banner", "-loglevel", "error", "-y", + "-f", "lavfi", "-i", "sine=frequency=440:duration=1", + "-c:a", "aac", + audioOnly, + ]); + const out = path.join(dir, "audio-only-out"); + await import("node:fs/promises").then((fs) => fs.mkdir(out)); + await expect(makeWebCopy(tools, audioOnly, out)).rejects.toBeInstanceOf(NotAVideo); + await expect(makeWebCopy(tools, audioOnly, out)).rejects.toThrow("no_video_stream"); + }, 30_000); }); diff --git a/apps/api/src/archive/video.ts b/apps/api/src/archive/video.ts index 8798d78..d259384 100644 --- a/apps/api/src/archive/video.ts +++ b/apps/api/src/archive/video.ts @@ -29,6 +29,17 @@ export class VideoToolMissing extends Error { } } +/** + * Source has no usable video stream (audio-only, data-only, or a container that ffprobe can open but + * ffmpeg cannot `-map 0:v:0`). Indexing marks FAILED without retry — never report to the error hub. + */ +export class NotAVideo extends Error { + constructor(reason = "no_video_stream") { + super(reason); + this.name = "NotAVideo"; + } +} + export interface VideoTools { ffmpeg: string; ffprobe: string; @@ -40,6 +51,7 @@ export interface VideoInfo { height: number | null; capturedAt: Date | null; hasAudio: boolean; + hasVideo: boolean; } /** @@ -69,8 +81,8 @@ export function webCopyArgs(input: string, output: string, opts: { audio: boolea "-i", input, "-map", - "0:v:0", - ...(opts.audio ? ["-map", "0:a:0"] : []), + "0:v:0?", + ...(opts.audio ? ["-map", "0:a:0?"] : []), "-vf", `${scale},format=yuv420p`, "-c:v", @@ -137,15 +149,22 @@ export function readProbe(json: ProbeJson): VideoInfo { height: video?.height ?? null, capturedAt, hasAudio: streams.some((s) => s.codec_type === "audio"), + hasVideo: !!video, }; } +/** Refuse sources with no video stream before ffmpeg `-map 0:v:0` (cryptic exit 234). */ +export function requireVideoStream(info: Pick): void { + if (!info.hasVideo) throw new NotAVideo(); +} + /** * The web copy, poster and thumbnail of `input`, written into `dir`. What it answers is read from the copy (its * size is the one shown, upright), with the original's camera time. */ export async function makeWebCopy(tools: VideoTools, input: string, dir: string): Promise { const original = await probe(tools, input); + requireVideoStream(original); const web = path.join(dir, VIDEO_FILES.web); await run(tools.ffmpeg, webCopyArgs(input, web, { audio: original.hasAudio }), "ffmpeg"); const copy = await probe(tools, web); diff --git a/apps/api/vitest.unit.config.ts b/apps/api/vitest.unit.config.ts index 49ea637..dab3482 100644 --- a/apps/api/vitest.unit.config.ts +++ b/apps/api/vitest.unit.config.ts @@ -1,9 +1,9 @@ import { defineConfig } from "vitest/config"; -/** Pure tests. The default config migrates a database, which these do not need. */ +/** Pure unit tests that do not need Postgres (BIT-31658). */ export default defineConfig({ test: { - include: ["src/**/*.test.ts"], - fileParallelism: false, + include: ["src/archive/video.test.ts", "src/archive/corrupt.test.ts"], + testTimeout: 60_000, }, }); diff --git a/apps/app/src/i18n.ts b/apps/app/src/i18n.ts index 63268d6..311650e 100644 --- a/apps/app/src/i18n.ts +++ b/apps/app/src/i18n.ts @@ -605,6 +605,8 @@ export const t = { never: "ainda não", progress: (done: number, total: number) => `${done.toLocaleString("pt-PT")} de ${total.toLocaleString("pt-PT")} fotos indexadas`, failed: (n: number) => `${n} com erro`, + failedCorrupt: "ficheiro corrompido na cloud", + failedNoVideo: "ficheiro sem vídeo utilizável", pace: (perHour: number, left: number) => { if (!perHour) return left ? "à espera do worker" : ""; const hours = left / perHour; @@ -620,6 +622,8 @@ export const t = { cloud_unreachable: "Não foi possível chegar à cloud. Confirma o endereço.", cloud_not_found: "Isto não parece uma Nextcloud (o login não respondeu).", cloud_error: "A cloud respondeu com um erro.", + corrupt_source: "Ficheiro corrompido na cloud.", + no_video_stream: "Ficheiro sem stream de vídeo utilizável.", invalid_url: "Endereço inválido.", secrets_not_configured: "O servidor não tem a chave de segredos configurada.", } as Record, diff --git a/apps/app/src/pages/ArchivePage.tsx b/apps/app/src/pages/ArchivePage.tsx index 61372a6..7894656 100644 --- a/apps/app/src/pages/ArchivePage.tsx +++ b/apps/app/src/pages/ArchivePage.tsx @@ -177,7 +177,13 @@ function SourceCard({ api, source, isAdmin, active, onSelect, onChange, onRemove
{A.progress(c.done, total)} - {c.failed > 0 && · {A.failed(c.failed)}} + {c.failed > 0 && ( + + {" "} + · {A.failed(c.failed)} + {(c.failedCorrupt ?? 0) > 0 && <> · {A.failedCorrupt}} + + )} {(c.pending > 0 || (c.perHour ?? 0) > 0) && · {A.pace(c.perHour ?? 0, c.pending)}} {A.galleriesLine(c.galleries, c.games, c.named, c.unmatched)} diff --git a/docs/archive.md b/docs/archive.md index deea32a..94ce3a6 100644 --- a/docs/archive.md +++ b/docs/archive.md @@ -184,6 +184,14 @@ appears and when (`people`, with each moment), and a person's page lists the vid each moment. A folder moved to another event has its videos' faces looked for again there. The app's archive counts show how many videos are waiting for their faces (`videoFacesPending`), done and failed. +**Damaged / non-video sources (BIT-31658):** before `-map 0:v:0`, `probe` must see a `codec_type=video` stream +(`NotAVideo` / `no_video_stream`); otherwise the row is `FAILED` with no retry and no error-hub report. Truncated +downloads (size ≠ WebDAV `getcontentlength`) and ffprobe/sharp messages like `moov atom not found` / JPEG +`premature end` are `corrupt_source` — same treatment; the walk requeues only when the file's etag changes. The +Arquivo UI shows these under `failedCorrupt` (“ficheiro corrompido na cloud”). Transient Nextcloud GET +423/429/5xx (incl. 502/504) still retry inside `CloudClient.call`; permanent index failures after the attempt +budget are coalesced into **one** hub warn per burst (`flushIndexFailures`), not one ticket per photo. + ### Downloads Every viewer downloads at web size: 2048 px on the long side, with the photo's metadata (credits, caption, names); diff --git a/packages/sdk/src/types.ts b/packages/sdk/src/types.ts index e2d7fc4..8e9c42e 100644 --- a/packages/sdk/src/types.ts +++ b/packages/sdk/src/types.ts @@ -441,6 +441,8 @@ export interface CloudSourceCounts { pending: number; done: number; failed: number; + /** FAILED with corrupt_source / no_video_stream — damaged file in the cloud, not a tool bug. */ + failedCorrupt?: number; galleries: number; /** Galleries matched to the official game (or chosen by hand). */ games: number;