diff --git a/apps/api/src/archive/corrupt-source.test.ts b/apps/api/src/archive/corrupt-source.test.ts new file mode 100644 index 0000000..2f6c3b9 --- /dev/null +++ b/apps/api/src/archive/corrupt-source.test.ts @@ -0,0 +1,55 @@ +import { mkdtemp, writeFile, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; +import { + assertDownloadComplete, + CorruptSource, + IncompleteDownload, + isCorruptSourceMessage, +} from "./corrupt-source.js"; + +describe("corrupt / incomplete archive sources (BIT-31621)", () => { + const dirs: string[] = []; + afterEach(async () => { + await Promise.all(dirs.splice(0).map((d) => rm(d, { recursive: true, force: true }))); + }); + + it("recognises ffprobe moov / invalid-data messages as corrupt sources", () => { + expect( + isCorruptSourceMessage( + "ffprobe exited 1: [mov,mp4,m4a,3gp,3g2,mj2 @ 0x5c2e6ee11e00] moov atom not found | /tmp/x.mp4: Invalid data found when processing input", + ), + ).toBe(true); + expect(isCorruptSourceMessage("Input file has corrupt header")).toBe(true); + expect(isCorruptSourceMessage("premature end of JPEG")).toBe(true); + expect(isCorruptSourceMessage("ffmpeg exited 234: Stream map '0:v:0' matches no streams")).toBe(false); + expect(isCorruptSourceMessage("GET /a failed: 503")).toBe(false); + }); + + it("passes when downloaded size matches the walk size", async () => { + const dir = await mkdtemp(path.join(tmpdir(), "pr-corrupt-")); + dirs.push(dir); + const file = path.join(dir, "a.mp4"); + await writeFile(file, Buffer.alloc(12)); + await expect(assertDownloadComplete(file, 12n)).resolves.toBeUndefined(); + await expect(assertDownloadComplete(file, null)).resolves.toBeUndefined(); + }); + + it("throws IncompleteDownload when bytes on disk differ from the walk size", async () => { + const dir = await mkdtemp(path.join(tmpdir(), "pr-corrupt-")); + dirs.push(dir); + const file = path.join(dir, "a.mp4"); + await writeFile(file, Buffer.alloc(4)); + await expect(assertDownloadComplete(file, 100n)).rejects.toBeInstanceOf(IncompleteDownload); + await expect(assertDownloadComplete(file, 100n)).rejects.toMatchObject({ + message: "incomplete_download:4/100", + }); + }); + + it("names CorruptSource for permanent cloud damage", () => { + const err = new CorruptSource(); + expect(err.name).toBe("CorruptSource"); + expect(err.message).toBe("corrupt_source"); + }); +}); diff --git a/apps/api/src/archive/corrupt-source.ts b/apps/api/src/archive/corrupt-source.ts new file mode 100644 index 0000000..252a517 --- /dev/null +++ b/apps/api/src/archive/corrupt-source.ts @@ -0,0 +1,37 @@ +import { stat } from "node:fs/promises"; + +/** + * Damaged file in the cloud (broken JPEG/MP4, moov missing), 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"; + } +} + +/** + * Downloaded bytes do not match the size the walk stored (truncated GET / still uploading). + * Requeue and retry later; after MAX_ATTEMPTS mark FAILED as corrupt_source. + */ +export class IncompleteDownload extends Error { + constructor(got: bigint, expected: bigint) { + super(`incomplete_download:${got}/${expected}`); + this.name = "IncompleteDownload"; + } +} + +/** 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 → retry later). */ +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 IncompleteDownload(got, expected); +} diff --git a/apps/api/src/archive/nextcloud.ts b/apps/api/src/archive/nextcloud.ts index 20a418d..5c2e12a 100644 --- a/apps/api/src/archive/nextcloud.ts +++ b/apps/api/src/archive/nextcloud.ts @@ -1,4 +1,5 @@ import { createWriteStream } from "node:fs"; +import { stat } from "node:fs/promises"; import { Readable } from "node:stream"; import { pipeline } from "node:stream/promises"; import { isTransientStatus, NextcloudError } from "../delivery/nextcloud.js"; @@ -218,12 +219,20 @@ export class CloudClient { return { self, children: entries.filter((e) => e !== self) }; } - /** Streams a file into `dest`. */ + /** Streams a file into `dest`. When Content-Length is present, refuse a short body (retry as transient 502). */ async download(path: string, dest: string): Promise { await this.resolveUser(); const res = await this.call("GET", this.davUrl(path)); if (!res.ok || !res.body) throw new NextcloudError(`GET ${path} failed: ${res.status}`, res.status); + const expected = res.headers.get("content-length"); await pipeline(Readable.fromWeb(res.body as never), createWriteStream(dest)); + if (expected != null && expected !== "") { + const want = Number(expected); + if (Number.isFinite(want) && want >= 0) { + const got = (await stat(dest)).size; + if (got !== want) throw new NextcloudError(`GET ${path} truncated: got ${got} want ${want}`, 502); + } + } } /** The response of a file download, for streaming it on (the editor's 100% view). */ diff --git a/apps/api/src/archive/service.ts b/apps/api/src/archive/service.ts index 62e6691..3d5b23c 100644 --- a/apps/api/src/archive/service.ts +++ b/apps/api/src/archive/service.ts @@ -15,11 +15,24 @@ 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 { + assertDownloadComplete, + CorruptSource, + IncompleteDownload, + isCorruptSourceMessage, +} from "./corrupt-source.js"; import { makeWebCopy, VIDEO, VIDEO_FILES, VideoToolMissing, VideoUnsupported, 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"; +export { + assertDownloadComplete, + CorruptSource, + IncompleteDownload, + isCorruptSourceMessage, +} from "./corrupt-source.js"; + export const IMAGE = /\.(jpe?g)$/i; /** How long the person has to authorise in their cloud (Nextcloud keeps the flow 20 minutes). */ const LOGIN_TTL_MS = 20 * 60_000; @@ -1064,6 +1077,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 @@ -1108,13 +1122,20 @@ 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 incomplete = err instanceof IncompleteDownload; + const corrupt = err instanceof CorruptSource || (!incomplete && isCorruptSourceMessage(message)); + // Incomplete downloads retry later; confirmed corrupt sources fail once (BIT-31621). + const retry = !gone && !corrupt && (transient || file.attempts < MAX_ATTEMPTS); + const error = corrupt || (!retry && incomplete) ? "corrupt_source" : message; + await db.cloudFile.update({ where: { id: fileId }, data: { status: retry ? "PENDING" : "FAILED", error, ...(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"); + // Corrupt / incomplete sources are expected cloud damage — info only (BIT-31621), never one hub ticket per file. + if (corrupt || (!retry && incomplete)) log.info({ err, fileId, path: file.path }, "archive: image source corrupt, marked failed"); + else if (transient) log.info({ err, fileId, path: file.path }, "archive: image download blipped, requeued for a free retry"); + else if (incomplete) log.info({ err, fileId, path: file.path }, "archive: image download incomplete, requeued"); else log.warn({ err, fileId, path: file.path }, "archive: image not indexed"); } finally { await rm(dir, { recursive: true, force: true }); @@ -1160,6 +1181,8 @@ 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); + // Walk size vs bytes on disk: truncated GET / still-uploading → retry later (BIT-31621). + await assertDownloadComplete(original, video.size); } const out = path.join(dir, "out"); await mkdir(out); @@ -1190,11 +1213,18 @@ export class ArchiveService { const gone = err instanceof NextcloudError && err.status === 404; const missing = err instanceof VideoToolMissing; const unsupported = err instanceof VideoUnsupported; - // No video stream / missing tools / gone from cloud: mark FAILED once; retries cannot help. - const retry = !gone && !missing && !unsupported && (transient || video.attempts < MAX_ATTEMPTS); - await db.cloudVideo.update({ where: { id: videoId }, data: { status: retry ? "PENDING" : "FAILED", error: message, ...(transient && { attempts: { decrement: 1 } }) } }); + const incomplete = err instanceof IncompleteDownload; + // moov atom not found / Invalid data… = damaged MP4 in the cloud, not an ffmpeg bug (BIT-31621). + const corrupt = err instanceof CorruptSource || (!incomplete && isCorruptSourceMessage(message)); + // No video stream / missing tools / gone from cloud / damaged source: mark FAILED once; retries cannot help. + const retry = !gone && !missing && !unsupported && !corrupt && (transient || video.attempts < MAX_ATTEMPTS); + const error = corrupt || (!retry && incomplete) ? "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 (corrupt || (!retry && incomplete)) log.info({ err, videoId, path: video.path }, "archive: video source corrupt, marked failed"); + else if (transient) log.info({ err, videoId, path: video.path }, "archive: video download blipped, requeued for a free retry"); + else if (incomplete) log.info({ err, videoId, path: video.path }, "archive: video download incomplete, requeued"); + else log.warn({ err, videoId, path: video.path }, "archive: video not indexed"); } finally { await rm(dir, { recursive: true, force: true }); }