edef4d7365
* fix(images): backfill orientation for libraries that predate the fix (#1198) #1194 corrected the generators and every ingest path, but did nothing for photos already in the database. Those rows end up worse than untouched ones: before the fix a rotated photo was CONSISTENTLY wrong — a sideways image in a tile shaped to match — and afterwards the regenerated thumbnail is correct while photos.width/height still describe the raw sensor order, so masonry and justified size a portrait photo with a landscape ratio. The dimension repair cannot reach them: it only selects rows with a NULL dimension, and an affected row has both, just transposed. Its own job rather than a mode of that one. They look alike but are not the same operation: the repair FILLS missing values and touches nothing else, while this RECOMPUTES and invalidates the derived data generated against the old orientation. Sharing a lease would also mean one blocks the other. A first attempt at this was reverted from #1194 after review found five problems. All five are addressed here: - Originals are read through resolvePhotoStorageKey + withLocalCopy + withProcessableImage, so the job works on S3 installs and on RAW/DNG. The dimension repair's direct fs read does neither, which stops being an edge case in a job that walks the whole library. - The canonical preview is cleared BEFORE faces are requeued. ensurePreviewImage returns a cached preview whenever it is still a valid image, and a pre-fix unrotated one is perfectly valid — so requeueing alone made the rescan read unrotated pixels and scale those boxes by the corrected dimensions, which is worse than leaving the data alone. - Invalidation keys off the EXIF transform, not a dimension delta. Orientations 2, 3 and 4 move every pixel while leaving width and height unchanged, as does 5-8 on a square image; a delta check skips exactly those rows. - Archived events are excluded — archiving deletes the originals and keeps the rows, so every one of them would fail its read. - The dimension write and the invalidation share a transaction. Split, a failure between them leaves stale face data that no retry can fix, because the retry computes "already correct". Tier deletion stays outside the transaction on purpose: it touches storage, and a failed object delete must not roll back a correct database write. A leftover tier regenerates on next read; a rolled-back write is silent corruption. * fix(images): invalidate every stale rendition, fence the writes, and give the job a button (#1198) Three things from review, one of which mattered a lot. The invalidation was too narrow. Clearing only preview_path fixed the face data and left the gallery worse off: ensureThumbnail and ensureHeroImage return their cached file whenever it is merely VALID, and a pre-fix sideways thumbnail is perfectly valid — so a corrected row rendered the old sideways image inside a newly-corrected portrait tile. All three canonical renditions are cleared now, their stored objects deleted, and both responsive tier sets with them. The responsive tiers also needed handling rather than a hopeful catch. Their helpers swallow delete errors, and ensurePreviewImageAtWidth treats storage.stat(key) as a cache hit — so a tier that survived deletion keeps serving unrotated forever and never regenerates. The keys are re-checked after deletion and survivors are counted into the result, so a run that could not clear them does not report itself as clean. Writes are fenced on the identity that was measured, not just the id. replacePhoto swaps a new file under an existing row and rewrites path/filename, and it IS reachable — from the replace_by_name upload path in adminPhotos.js. A replacement landing while this job read the old original would otherwise have had the previous file's dimensions written over it and its fresh renditions cleared. And the job had no way to start it: the endpoint existed with no caller, so an upgrade would have left every affected library untouched unless an operator found the API themselves. It gets a Status card like its two neighbours, with strings in en/de/fr/sl. No backlog counter, because unlike the other two it cannot know how many rows need it without doing the work. * fix(images): make the backfill idempotent, and stop it lying about what it did (#1198) Six things from review round 2. The job was not idempotent, and the way it failed was expensive. Its trigger is the EXIF tag on the ORIGINAL, which correcting a photo never changes — so every re-run threw away the renditions it had just regenerated and requeued every completed face scan. On a face-enabled install, running it twice meant re-detecting the whole library for nothing. Migration 191 adds photos.orientation_checked_at, written in the same transaction as the work it records, with `force` as the escape hatch for an interrupted run. The candidate query selected preview_path but not thumbnail_path or hero_path, which the deletion loop reads — so those two pointers were cleared in the database while the objects stayed in storage, still reachable through previously issued URLs. watermark_path was missed entirely. gallery.js serves it ahead of the original when branding watermarking is on, which makes it the most visible rendition of the lot. (Its generator needed rotating too — that went into #1185, where the other three live.) storage.stat() RESOLVES with null for a missing key rather than rejecting, so counting "the promise settled" marked every deleted — and every never-created — tier as a survivor. A perfectly clean run told the operator to re-run. Now a null means gone, and a rejection counts as stuck, since a storage error is not proof the object went away. Face data is invalidated whenever the stored dimensions change, not only when the change came from rotation: boxes are scaled by photo.width at read time, so any dimension change strands them. And `corrected` now comes from the affected-row count. If the fence rejected the write because the file was replaced mid-run, the photo was not corrected and the run must not claim it was. * fix(images): stop the backfill doing unnecessary work, and make its retry advice true (#1198) Round 3, four points, all narrower than the last two rounds. It re-processed photos that were already correct. A 5-8 rotation changes the dimensions, so a tagged photo whose stored dimensions are ALREADY oriented must have been ingested after #1185 — its renditions are fine and clearing them deletes valid files and rescans a completed face detection for nothing. Those are now skipped and simply marked. Orientations 2, 3 and 4 (and 5-8 on a square image) leave the dimensions identical either way, so they carry no such evidence and are still done once. The retry advice was impossible to follow. When a responsive tier could not be deleted the row was still marked, so the ordinary re-run the UI recommends found nothing and the stale tier kept serving unrotated forever. The marker is withheld when a tier survives, which is what makes that message honest. Storage cleanup now only runs when a fenced write actually landed. If the file was replaced mid-run every update matched zero rows, but the deletion went ahead anyway and could destroy renditions belonging to the REPLACEMENT — watermarks especially, which are keyed by photo id and alias straight onto the new file. And the full-photo ETag includes the backfill's timestamp. It was built from the ORIGINAL's mtime plus the watermark settings hash, neither of which this job touches — so a guest holding a pre-fix ETag would go on getting 304 and their cached sideways image no matter how many times the backfill succeeded. --------- Co-authored-by: Paul Nothaft <paul@MacStudio-von-Paul.local>
362 lines
15 KiB
JavaScript
362 lines
15 KiB
JavaScript
/**
|
|
* Backfilling orientation for a library that predates #1185 (#1198).
|
|
*
|
|
* The orientation fix corrected the generators and every ingest path, but left
|
|
* existing rows describing the raw sensor order. Those rows end up worse than
|
|
* untouched ones: before the fix a rotated photo was consistently wrong — a
|
|
* sideways image in a matching tile — and afterwards the thumbnail is right
|
|
* while the stored aspect ratio is not.
|
|
*
|
|
* A first attempt at this was reverted from #1194 after review. These tests
|
|
* pin the five things that went wrong with it:
|
|
*
|
|
* 1. requeueing faces without clearing the cached preview, so the rescan
|
|
* re-read unrotated pixels;
|
|
* 2. reading originals in a way that cannot see S3 or RAW;
|
|
* 3. deciding "did this change" from a dimension delta, which never fires
|
|
* for orientations 2, 3 and 4;
|
|
* 4. walking archived events whose originals no longer exist;
|
|
* 5. writing dimensions and invalidation non-atomically.
|
|
*/
|
|
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
const os = require('os');
|
|
const express = require('express');
|
|
const request = require('supertest');
|
|
const sharp = require('sharp');
|
|
|
|
describe('orientation backfill (#1198)', () => {
|
|
let tmpDir; let db; let app; let storageRoot;
|
|
|
|
const status = () => request(app).get('/api/admin/photos/repair-orientation/status');
|
|
const run = () => request(app).post('/api/admin/photos/repair-orientation');
|
|
const settle = async () => {
|
|
for (let i = 0; i < 100; i++) {
|
|
await new Promise((r) => setTimeout(r, 50));
|
|
const s = await status();
|
|
if (!s.body.isRunning) return s;
|
|
}
|
|
throw new Error('backfill did not settle');
|
|
};
|
|
|
|
beforeAll(async () => {
|
|
tmpDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'picpeak-orientbf-'));
|
|
process.env.NODE_ENV = 'test';
|
|
process.env.TEST_DATABASE_PATH = path.join(tmpDir, 'data', 'db.sqlite');
|
|
await fs.promises.mkdir(path.dirname(process.env.TEST_DATABASE_PATH), { recursive: true });
|
|
process.env.JWT_SECRET = process.env.JWT_SECRET || 'orientbf-secret';
|
|
|
|
jest.resetModules();
|
|
jest.doMock('../../src/middleware/auth', () => ({
|
|
adminAuth: (req, _res, next) => { req.admin = { id: 1, username: 'tester' }; next(); },
|
|
}));
|
|
jest.doMock('../../src/middleware/permissions', () => ({
|
|
requirePermission: () => (_req, _res, next) => next(),
|
|
}));
|
|
jest.doMock('../../src/utils/logger', () => ({
|
|
debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn(),
|
|
}));
|
|
|
|
({ db } = await require('./helpers/crmDb').bootCrmDb());
|
|
// bootCrmDb owns STORAGE_PATH; fixtures must live where the app resolves.
|
|
storageRoot = process.env.STORAGE_PATH;
|
|
await fs.promises.mkdir(path.join(storageRoot, 'events/active/orientbf'), { recursive: true });
|
|
|
|
app = express();
|
|
app.use(express.json());
|
|
app.use('/api/admin/photos', require('../../src/routes/adminPhotoDimensions'));
|
|
}, 180000);
|
|
|
|
afterAll(async () => {
|
|
if (db) await db.destroy?.();
|
|
await fs.promises.rm(tmpDir, { recursive: true, force: true }).catch(() => {});
|
|
});
|
|
|
|
async function seed({
|
|
orientation, storedWidth, storedHeight, faceStatus = null,
|
|
previewPath = 'previews/prev_orientbf.jpg', archived = false, filename = 'p.jpg',
|
|
thumbnailPath = 'thumbnails/thumb_orientbf.jpg', heroPath = 'heroes/hero_orientbf.jpg',
|
|
watermarkPath = 'watermarks/wm_orientbf.jpg', checkedAt = null,
|
|
}) {
|
|
await db('photos').del();
|
|
await db('events').del();
|
|
const [e] = await db('events').insert({
|
|
slug: 'orientbf', event_type: 'wedding', event_name: 'orientbf', event_date: '2026-01-01',
|
|
host_email: 'h@example.com', admin_email: 'a@example.com', password_hash: 'x',
|
|
share_link: `orientbf-${Math.random()}`, expires_at: new Date().toISOString(),
|
|
is_archived: archived,
|
|
}).returning('id');
|
|
const eventId = typeof e === 'object' ? e.id : e;
|
|
|
|
const img = sharp({ create: { width: 400, height: 200, channels: 3, background: { r: 7, g: 7, b: 7 } } });
|
|
await (orientation ? img.withMetadata({ orientation }) : img)
|
|
.jpeg().toFile(path.join(storageRoot, 'events/active/orientbf', filename));
|
|
|
|
const [p] = await db('photos').insert({
|
|
event_id: eventId, filename, path: `orientbf/${filename}`, type: 'individual',
|
|
width: storedWidth, height: storedHeight, face_status: faceStatus,
|
|
preview_path: previewPath, thumbnail_path: thumbnailPath, hero_path: heroPath,
|
|
watermark_path: watermarkPath, orientation_checked_at: checkedAt,
|
|
uploaded_at: new Date().toISOString(),
|
|
}).returning('id');
|
|
return { eventId, photoId: typeof p === 'object' ? p.id : p };
|
|
}
|
|
|
|
it('corrects a row whose dimensions are transposed', async () => {
|
|
// The case the dimension repair can never reach: both values present,
|
|
// just in the raw sensor order.
|
|
const { photoId } = await seed({ orientation: 6, storedWidth: 400, storedHeight: 200 });
|
|
|
|
expect((await run()).body.count).toBe(1);
|
|
const done = await settle();
|
|
|
|
const row = await db('photos').where({ id: photoId }).first();
|
|
expect(row.width).toBe(200);
|
|
expect(row.height).toBe(400);
|
|
expect(done.body.lastResult.corrected).toBe(1);
|
|
});
|
|
|
|
it('clears the cached preview before requeueing, not after', async () => {
|
|
// The reverted attempt's own-goal: ensurePreviewImage hands back a cached
|
|
// preview whenever it is still a valid image, so a rescan against the
|
|
// pre-fix preview produced boxes in the old coordinate system and scaled
|
|
// them by the corrected dimensions.
|
|
const { photoId } = await seed({
|
|
orientation: 6, storedWidth: 400, storedHeight: 200, faceStatus: 'done',
|
|
});
|
|
|
|
await run();
|
|
const done = await settle();
|
|
|
|
const row = await db('photos').where({ id: photoId }).first();
|
|
expect(row.preview_path).toBeNull();
|
|
expect(row.face_status).toBe('pending');
|
|
expect(done.body.lastResult.requeuedFaces).toBe(1);
|
|
});
|
|
|
|
it('clears the thumbnail and hero too, not just the preview', async () => {
|
|
// The miss that mattered most: ensureThumbnail and ensureHeroImage return
|
|
// their cached file whenever it is merely VALID, and a pre-fix sideways
|
|
// thumbnail is perfectly valid. Clearing only the preview fixed the face
|
|
// data and left the gallery rendering the old sideways image inside a
|
|
// newly-corrected portrait tile.
|
|
const { photoId } = await seed({ orientation: 6, storedWidth: 400, storedHeight: 200 });
|
|
|
|
await run();
|
|
await settle();
|
|
|
|
const row = await db('photos').where({ id: photoId }).first();
|
|
expect(row.preview_path).toBeNull();
|
|
expect(row.thumbnail_path).toBeNull();
|
|
expect(row.hero_path).toBeNull();
|
|
});
|
|
|
|
it('leaves the renditions of an untransformed photo alone', async () => {
|
|
// Nothing moved, so nothing cached is stale — clearing them would make a
|
|
// routine run regenerate the whole library for no reason.
|
|
const { photoId } = await seed({ orientation: null, storedWidth: 400, storedHeight: 200 });
|
|
|
|
await run();
|
|
await settle();
|
|
|
|
const row = await db('photos').where({ id: photoId }).first();
|
|
expect(row.thumbnail_path).toBe('thumbnails/thumb_orientbf.jpg');
|
|
expect(row.hero_path).toBe('heroes/hero_orientbf.jpg');
|
|
expect(row.preview_path).toBe('previews/prev_orientbf.jpg');
|
|
});
|
|
|
|
it('does not touch a row whose file was replaced while it was reading', async () => {
|
|
// replacePhoto swaps a new file under an existing row and rewrites
|
|
// path/filename (reachable from replace_by_name). The writes are fenced on
|
|
// the identity that was measured, so a replacement that lands mid-run is
|
|
// left entirely alone rather than being given the previous file's
|
|
// dimensions and having its fresh renditions cleared.
|
|
const { photoId } = await seed({
|
|
orientation: 6, storedWidth: 400, storedHeight: 200, faceStatus: 'done',
|
|
});
|
|
|
|
const res = await run();
|
|
expect(res.body.count).toBe(1);
|
|
// Simulate the replacement landing before the loop writes.
|
|
await db('photos').where({ id: photoId })
|
|
.update({ path: 'orientbf/replaced.jpg', filename: 'replaced.jpg' });
|
|
await settle();
|
|
|
|
const row = await db('photos').where({ id: photoId }).first();
|
|
expect(row.width).toBe(400); // untouched
|
|
expect(row.face_status).toBe('done'); // not requeued
|
|
expect(row.thumbnail_path).toBe('thumbnails/thumb_orientbf.jpg');
|
|
});
|
|
|
|
it('is idempotent — a second run finds nothing left to do', async () => {
|
|
// The trigger is the EXIF tag on the ORIGINAL, which correcting a photo
|
|
// never changes. Without a marker every re-run would throw away the
|
|
// renditions it had just regenerated and requeue every completed face
|
|
// scan — on a face-enabled install, re-detecting the whole library.
|
|
await seed({ orientation: 6, storedWidth: 400, storedHeight: 200, faceStatus: 'done' });
|
|
|
|
expect((await run()).body.count).toBe(1);
|
|
const first = await settle();
|
|
expect(first.body.lastResult.corrected).toBe(1);
|
|
|
|
expect((await run()).body.count).toBe(0);
|
|
});
|
|
|
|
it('force revisits rows it has already checked', async () => {
|
|
await seed({
|
|
orientation: 6, storedWidth: 200, storedHeight: 400,
|
|
checkedAt: new Date().toISOString(),
|
|
});
|
|
|
|
expect((await run()).body.count).toBe(0);
|
|
const forced = await request(app).post('/api/admin/photos/repair-orientation').send({ force: true });
|
|
expect(forced.body.count).toBe(1);
|
|
await settle();
|
|
});
|
|
|
|
it('clears the watermarked rendition, which is what a guest actually sees', async () => {
|
|
// gallery.js serves watermark_path ahead of the original when branding
|
|
// watermarking is on.
|
|
const { photoId } = await seed({ orientation: 6, storedWidth: 400, storedHeight: 200 });
|
|
|
|
await run();
|
|
await settle();
|
|
|
|
expect((await db('photos').where({ id: photoId }).first()).watermark_path).toBeNull();
|
|
});
|
|
|
|
it('does not report stale tiers after a clean run', async () => {
|
|
// storage.stat() RESOLVES with null for a missing key rather than
|
|
// rejecting, so counting "the promise settled" marked every deleted and
|
|
// never-created tier as a survivor and told the operator to re-run.
|
|
await seed({ orientation: 6, storedWidth: 400, storedHeight: 200 });
|
|
|
|
await run();
|
|
const done = await settle();
|
|
|
|
expect(done.body.lastResult.staleTiers).toBe(0);
|
|
});
|
|
|
|
it('requeues faces when only the dimensions were wrong', async () => {
|
|
// No rotation involved: boxes are scaled by photo.width at read time, so
|
|
// any change to the stored dimensions invalidates them.
|
|
const { photoId } = await seed({
|
|
orientation: null, storedWidth: 999, storedHeight: 111, faceStatus: 'done',
|
|
});
|
|
|
|
await run();
|
|
const done = await settle();
|
|
|
|
const row = await db('photos').where({ id: photoId }).first();
|
|
expect(row.width).toBe(400);
|
|
expect(row.face_status).toBe('pending');
|
|
expect(done.body.lastResult.requeuedFaces).toBe(1);
|
|
});
|
|
|
|
it('requeues an orientation that moves pixels without moving dimensions', async () => {
|
|
// Orientation 3 is a 180° turn: every pixel moves, width and height do
|
|
// not. A dimension-delta check sees nothing and skips exactly this row.
|
|
const { photoId } = await seed({
|
|
orientation: 3, storedWidth: 400, storedHeight: 200, faceStatus: 'done',
|
|
});
|
|
|
|
await run();
|
|
const done = await settle();
|
|
|
|
const row = await db('photos').where({ id: photoId }).first();
|
|
expect(row.width).toBe(400); // unchanged, correctly
|
|
expect(row.face_status).toBe('pending');
|
|
expect(row.preview_path).toBeNull();
|
|
expect(done.body.lastResult.requeuedFaces).toBe(1);
|
|
expect(done.body.lastResult.corrected).toBe(0);
|
|
});
|
|
|
|
it('leaves a post-fix import alone, renditions and all', async () => {
|
|
// A 5-8 rotation changes the dimensions, so a tagged photo whose stored
|
|
// dimensions are already oriented must have been ingested after #1185.
|
|
// Re-clearing its renditions would delete valid files and rescan a
|
|
// completed face detection for nothing.
|
|
const { photoId } = await seed({
|
|
orientation: 6, storedWidth: 200, storedHeight: 400, faceStatus: 'done',
|
|
});
|
|
|
|
await run();
|
|
const done = await settle();
|
|
|
|
const row = await db('photos').where({ id: photoId }).first();
|
|
expect(row.thumbnail_path).toBe('thumbnails/thumb_orientbf.jpg');
|
|
expect(row.face_status).toBe('done');
|
|
expect(done.body.lastResult).toMatchObject({ corrected: 0, requeuedFaces: 0 });
|
|
// ...and it is marked, so it is not re-read next time either.
|
|
expect(row.orientation_checked_at).toBeTruthy();
|
|
});
|
|
|
|
it('still invalidates a 180-degree rotation, which carries no such evidence', async () => {
|
|
// Orientation 3 leaves the dimensions identical whether or not it has been
|
|
// processed, so there is nothing to infer from and it must be done once.
|
|
const { photoId } = await seed({
|
|
orientation: 3, storedWidth: 400, storedHeight: 200, faceStatus: 'done',
|
|
});
|
|
|
|
await run();
|
|
await settle();
|
|
|
|
const row = await db('photos').where({ id: photoId }).first();
|
|
expect(row.thumbnail_path).toBeNull();
|
|
expect(row.face_status).toBe('pending');
|
|
});
|
|
|
|
it('leaves an untagged photo completely alone', async () => {
|
|
const { photoId } = await seed({
|
|
orientation: null, storedWidth: 400, storedHeight: 200, faceStatus: 'done',
|
|
});
|
|
|
|
await run();
|
|
const done = await settle();
|
|
|
|
const row = await db('photos').where({ id: photoId }).first();
|
|
expect(row.width).toBe(400);
|
|
expect(row.face_status).toBe('done');
|
|
expect(row.preview_path).toBe('previews/prev_orientbf.jpg');
|
|
expect(done.body.lastResult).toMatchObject({ corrected: 0, requeuedFaces: 0, failed: 0 });
|
|
});
|
|
|
|
it('does not start face scanning on an install that never enabled it', async () => {
|
|
const { photoId } = await seed({
|
|
orientation: 6, storedWidth: 400, storedHeight: 200, faceStatus: null,
|
|
});
|
|
|
|
await run();
|
|
const done = await settle();
|
|
|
|
expect((await db('photos').where({ id: photoId }).first()).face_status).toBeNull();
|
|
expect(done.body.lastResult.requeuedFaces).toBe(0);
|
|
// ...but the dimensions are still corrected.
|
|
expect(done.body.lastResult.corrected).toBe(1);
|
|
});
|
|
|
|
it('skips archived events, whose originals were deleted on archive', async () => {
|
|
await seed({ orientation: 6, storedWidth: 400, storedHeight: 200, archived: true });
|
|
|
|
const res = await run();
|
|
expect(res.body.count).toBe(0);
|
|
});
|
|
|
|
it('refuses a second run while one is in flight', async () => {
|
|
// Shares the maintenance-lease plumbing, on its own job row so it neither
|
|
// blocks nor is blocked by the dimension repair.
|
|
const jobs = require('../../src/services/maintenanceJobState');
|
|
await seed({ orientation: 6, storedWidth: 400, storedHeight: 200 });
|
|
|
|
const claim = await jobs.claim(jobs.JOB_ORIENTATION_BACKFILL);
|
|
expect(claim).toEqual(expect.any(String));
|
|
|
|
expect((await run()).status).toBe(409);
|
|
|
|
// The dimension repair is a different job and is unaffected.
|
|
expect((await request(app).post('/api/admin/photos/repair-dimensions')).status).toBe(200);
|
|
await jobs.release(jobs.JOB_ORIENTATION_BACKFILL, claim);
|
|
});
|
|
});
|