0b886ed942
* fix(faces): defer on unreachable storage, and commit the import path first The two follow-ups left open by #1091, both consequences of external photos becoming scannable at all. **A dropped mount no longer burns the gallery.** ensurePreviewImage returns null for "this JPEG is corrupt" and "the NFS share is gone" alike, and faceProcessor marked both 'failed'. Nothing re-queues a failure automatically and the queue only ever claims 'pending', so a mount that blinked mid-scan cost the whole event a manual Re-scan — on external libraries, where network storage drops far more often than local disk, that is the common case rather than the corner one. faceProcessor now probes the containing DIRECTORY before failing, and throws TransientSourceError when it cannot be reached; faceQueue treats that exactly like SidecarUnavailableError — release to pending, back off, retry — with the warning rate-limited to one per five minutes, since an outage hits every photo in the event. The directory rather than the file is the whole point: a missing file inside a healthy directory is a broken photo and should still fail, and it still does. Anything that goes wrong deciding which case it is falls through to 'failed', because guessing 'transient' on an unknown condition would retry forever. **The import commits its path before inserting rows.** enqueueEvent accepts processing_status NULL (faceProcessor.js:243-246), which these inserts leave unset, so an admin hitting the toggle or Re-scan during a long import could queue partial rows while the event still resolved against the old directory — and burn them to 'failed'. Moving events.external_path ahead of the loop closes that, and fixes a pre-existing bug on the same line: an import that died at photo 500 of 1000 used to leave those 500 rows pointing into the new tree while the event still resolved against the old one, making every one of them unreadable. Safe to do first because the path is already validated above, and existing photos are unaffected — photo.source_origin takes precedence over event.source_mode in both resolvers and is NOT NULL defaulting to 'managed'. The #1090 test that asserted a missing source fails needed its setup corrected rather than its intent: it created no directory at all, which is now (correctly) a dropped mount. It now creates one, so it tests the case it always meant to — healthy storage, dead photo. Verified both fixes discriminate: removing the probe fails the defer test, and moving the event update back after the loop fails the ordering test. Face suite 59 passed across 8 suites; the full backend suite fails the same 10 pre-existing suites as unmodified main, no more. * fix(faces): stop a dead mount stalling the whole queue External review, and the first finding is one my own change created. Deferring by returning the row to 'pending' was a trap: claimNextPhoto orders by id ascending and the queue defaults to a single worker, so the same unreachable row becomes the oldest pending one after every backoff and the worker never reaches a higher id. One dead mount would have stalled face scanning for the entire install — unrelated events, fresh uploads, everything. Strictly worse than the permanent 'failed' this set out to replace. The row is now left parked in 'processing' with face_started_at intact. It is not claimable, so the worker moves straight on; the janitor that already exists returns it to 'pending' past STUCK_TIMEOUT_MS, which is the retry. No new column and no new timer. The sidecar branch still releases, because a down sidecar blocks every photo anyway — there is no other work to get on with. Second: probing existence was not enough. Unmounting an NFS or SMB share usually leaves the mountpoint behind as an ordinary empty directory, so fs.access succeeded on storage that was entirely gone and the photo was failed anyway — the exact case this was written for. An empty directory where the photo should live now counts as unreachable. The trade is deliberate and documented: a directory an admin genuinely emptied is retried rather than failed, which now costs one attempt per janitor sweep and nothing else. Third: a comment in adminExternalMedia claimed source_origin isolates existing photos from the early external_path update. That is true of managed rows and false of external ones — resolveExternalPath prefixes every external row with event.external_path, so importing folder B into an event referencing folder A rebases the A rows. Pre-existing rather than introduced here (the update always did this, just later), but the comment asserted otherwise, so it now says what actually happens and names the underlying single-base-path limitation. The deferral test initially passed against the blocking version too — database state alone cannot tell the fix from the bug. It now inspects the branch directly, the way the #596 contract tests do, and fails when releaseToPending is put back or the two branches are merged. * fix(faces): back off per event, and stop clobbering concurrent scans Round two of external review. Parking a row in 'processing' fixed the head-of-line block but not the cost: every janitor sweep handed the whole dead gallery back, and the worker walked all of it again — one stat per photo against storage that may be hard-mounted and slow to time out — before reaching any healthy event. Every one of those attempts also went through generatePreviewImage first, which logs an error per photo, so a down mount produced a recurring flood that the rate-limited warning did nothing about. So the backoff is now per EVENT and separate from the janitor: TransientSourceError carries the event id, the queue records a cooldown, and claimNextPhoto excludes those events while it lasts. The janitor keeps doing its own job, which is rescuing rows a crashed worker abandoned. Cooldown is in memory on purpose — a restart is usually what follows fixing a mount, so it should retry at once. Second: committing the event path before the loop means a toggle or Re-scan firing mid-import can now genuinely queue and finish some of those rows. The final bulk update was unconditional, so it dragged 'done' rows back to 'pending' for a duplicate sidecar scan and knocked 'processing' rows out from under the worker. It is now whereNull — only rows nothing has touched are ours to queue. Also corrected a comment of mine that had gone stale in the same file: it still described the enqueue as happening after the event path was written "below", which stopped being true when that update moved above the loop. * fix(faces): judge the mount, the path and the file separately Round three of external review. The probe was too coarse in both directions. It read any ENOENT on the photo's own directory as a mount-wide outage, so a deleted or renamed subfolder — individual/ gone while collages/ is healthy — deferred the entire event and starved every sibling folder, renewing the cooldown on each retry. It now judges the EVENT ROOT for that verdict: root missing, or present-but-empty, is an outage; anything below a populated root is a broken path and fails. And it read a listable directory as proof the photo was at fault, so EACCES on a reconnected share, EIO, or the classic NFS ESTALE handle were burnt as permanent failures. Only ENOENT now means genuinely gone; any other error opening the file defers. The event-wide backoff was also too broad. A reference event can hold managed uploads alongside imported external ones, and those live in local storage that is fine — excluding the whole event id left them unscanned for as long as external rows kept renewing the cooldown, which during a real outage is indefinitely. The exclusion is now scoped to external and reference rows. One of my own tests had modelled the unmount wrongly: it emptied the photo's subdirectory rather than the event root, which under the corrected logic is a populated mount with a missing folder — a failure, not an outage. It now empties the root, which is what an unmount actually leaves behind. Dropped the path require the first version of this probe needed; the event-root form does not. All three fixes mutation-checked: reverting each one fails the test written for it. Face suite 69 passed across 9 suites; full backend suite fails the same 10 pre-existing suites as main, no more. --------- Co-authored-by: Paul Nothaft <paul@MacStudio-von-Paul.local>
210 lines
8.8 KiB
JavaScript
210 lines
8.8 KiB
JavaScript
/**
|
|
* A dropped mount defers a scan; a dead photo fails it.
|
|
*
|
|
* ensurePreviewImage returns null for both "this JPEG is corrupt" and "the
|
|
* NFS share is gone", and #1090 made that distinction matter: external
|
|
* libraries now reach this path, and network mounts drop far more often than
|
|
* local disks. Failing on an outage strands the photo — faceQueue only ever
|
|
* claims 'pending', and nothing re-queues a failure automatically, so a mount
|
|
* that blinked mid-scan would cost an entire gallery a manual Re-scan.
|
|
*
|
|
* The probe checks the containing DIRECTORY rather than the file, because that
|
|
* is what separates the two cases: a missing file inside a healthy directory
|
|
* is a broken photo, an unreachable directory is broken storage.
|
|
*/
|
|
|
|
const path = require('path');
|
|
const fs = require('fs');
|
|
const os = require('os');
|
|
|
|
process.env.NODE_ENV = 'test';
|
|
const tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'picpeak-transient-'));
|
|
process.env.TEST_DATABASE_PATH = path.join(tmpRoot, 'db.sqlite');
|
|
process.env.JWT_SECRET = process.env.JWT_SECRET || 'transient-test-secret';
|
|
// Created BEFORE anything requires externalMediaService: getExternalMediaRoot
|
|
// only honours the env var if the directory already exists, and caches the
|
|
// result on first call — set it later and every path silently resolves
|
|
// against a fallback root instead.
|
|
process.env.EXTERNAL_MEDIA_ROOT = path.join(tmpRoot, 'media');
|
|
fs.mkdirSync(process.env.EXTERNAL_MEDIA_ROOT, { recursive: true });
|
|
|
|
let previewKeyResult = null;
|
|
const mockEnsurePreviewImage = jest.fn(async () => previewKeyResult);
|
|
|
|
jest.mock('../../src/services/imageProcessor', () => ({
|
|
...jest.requireActual('../../src/services/imageProcessor'),
|
|
ensurePreviewImage: (...args) => mockEnsurePreviewImage(...args),
|
|
}));
|
|
|
|
jest.mock('../../src/services/faceClient', () => ({
|
|
detectFaces: jest.fn(async () => ({ model_version: 'test-v1', faces: [] })),
|
|
SidecarUnavailableError: class extends Error {},
|
|
}));
|
|
|
|
const { bootCrmDb } = require('./helpers/crmDb');
|
|
|
|
let db; let cleanup; let faceProcessor;
|
|
|
|
async function seedExternalPhoto({ externalPath, relpath = 'individual/a.jpg' }) {
|
|
const [e] = await db('events').insert({
|
|
slug: `tr-${Math.random().toString(36).slice(2, 8)}`,
|
|
event_type: 'wedding',
|
|
event_name: 'tr',
|
|
event_date: '2026-01-01',
|
|
host_email: 'h@example.com',
|
|
admin_email: 'a@example.com',
|
|
password_hash: 'x',
|
|
share_link: `tr-${Math.random()}`,
|
|
expires_at: new Date().toISOString(),
|
|
face_recognition_enabled: true,
|
|
source_mode: 'reference',
|
|
external_path: externalPath,
|
|
}).returning('id');
|
|
const eventId = typeof e === 'object' ? e.id : e;
|
|
|
|
const [p] = await db('photos').insert({
|
|
event_id: eventId,
|
|
filename: 'a.jpg',
|
|
path: 'tr/a.jpg',
|
|
type: 'individual',
|
|
width: 4000,
|
|
height: 3000,
|
|
processing_status: 'complete',
|
|
face_status: 'processing',
|
|
source_origin: 'external',
|
|
external_relpath: relpath,
|
|
}).returning('id');
|
|
return { eventId, photoId: typeof p === 'object' ? p.id : p };
|
|
}
|
|
|
|
describe('transient source vs dead photo', () => {
|
|
beforeAll(async () => {
|
|
({ db, cleanup } = await bootCrmDb());
|
|
await db('feature_flags').insert({ key: 'faces', value: true })
|
|
.onConflict('key').merge()
|
|
.catch(async () => { await db('feature_flags').where({ key: 'faces' }).update({ value: true }); });
|
|
faceProcessor = require('../../src/services/faceProcessor');
|
|
}, 120000);
|
|
|
|
afterAll(async () => {
|
|
if (cleanup) await cleanup();
|
|
await fs.promises.rm(tmpRoot, { recursive: true, force: true }).catch(() => {});
|
|
});
|
|
|
|
beforeEach(() => {
|
|
previewKeyResult = null; // i.e. ensurePreviewImage could not build one
|
|
mockEnsurePreviewImage.mockClear();
|
|
});
|
|
|
|
it('defers, not fails, when the source directory is unreachable', async () => {
|
|
// Nothing was ever created under EXTERNAL_MEDIA_ROOT for this path, so the
|
|
// directory does not resolve — the shape a dropped mount presents.
|
|
const { photoId } = await seedExternalPhoto({ externalPath: 'vanished-share' });
|
|
|
|
await expect(faceProcessor.processPhotoFaces(photoId))
|
|
.rejects.toBeInstanceOf(faceProcessor.TransientSourceError);
|
|
|
|
// Critically: still claimable. A 'failed' here is what stranded the photo.
|
|
const photo = await db('photos').where({ id: photoId }).first();
|
|
expect(photo.face_status).not.toBe('failed');
|
|
});
|
|
|
|
it('defers when the event root survives an unmount but is empty', async () => {
|
|
// The common NFS/SMB shape: unmounting leaves the mountpoint behind as an
|
|
// ordinary empty directory, so fs.access succeeds on storage that is
|
|
// entirely gone. The EVENT ROOT is the thing that goes empty — the photo's
|
|
// own subdirectory vanishes with it.
|
|
const emptyRoot = path.join(process.env.EXTERNAL_MEDIA_ROOT, 'unmounted');
|
|
await fs.promises.mkdir(emptyRoot, { recursive: true });
|
|
const { photoId } = await seedExternalPhoto({ externalPath: 'unmounted' });
|
|
|
|
await expect(faceProcessor.processPhotoFaces(photoId))
|
|
.rejects.toBeInstanceOf(faceProcessor.TransientSourceError);
|
|
|
|
const photo = await db('photos').where({ id: photoId }).first();
|
|
expect(photo.face_status).not.toBe('failed');
|
|
});
|
|
|
|
it('fails when the directory is healthy but the file is gone', async () => {
|
|
// Directory exists, file does not — a genuinely broken photo, which should
|
|
// surface as a failure the admin can see rather than retry forever.
|
|
const live = path.join(process.env.EXTERNAL_MEDIA_ROOT, 'live-share', 'individual');
|
|
await fs.promises.mkdir(live, { recursive: true });
|
|
// Non-empty: an empty directory is now read as an unmounted share, so the
|
|
// "healthy storage, dead photo" case needs a sibling file present.
|
|
await fs.promises.writeFile(path.join(live, 'sibling.jpg'), 'x');
|
|
const { photoId } = await seedExternalPhoto({ externalPath: 'live-share' });
|
|
|
|
const result = await faceProcessor.processPhotoFaces(photoId);
|
|
|
|
expect(result.status).toBe('failed');
|
|
const photo = await db('photos').where({ id: photoId }).first();
|
|
expect(photo.face_status).toBe('failed');
|
|
expect(photo.face_error).toMatch(/preview/i);
|
|
});
|
|
|
|
it('fails a missing subdirectory rather than deferring the whole event', async () => {
|
|
// individual/ deleted while collages/ is fine. Probing only the photo's own
|
|
// directory reports ENOENT and would read as a mount-wide outage, deferring
|
|
// the event and starving every healthy sibling folder. The root is
|
|
// populated, so the mount is up and this is a broken path.
|
|
const root = path.join(process.env.EXTERNAL_MEDIA_ROOT, 'partial');
|
|
await fs.promises.mkdir(path.join(root, 'collages'), { recursive: true });
|
|
await fs.promises.writeFile(path.join(root, 'collages', 'kept.jpg'), 'x');
|
|
const { photoId } = await seedExternalPhoto({ externalPath: 'partial' });
|
|
|
|
const result = await faceProcessor.processPhotoFaces(photoId);
|
|
expect(result.status).toBe('failed');
|
|
});
|
|
|
|
it('defers a file that exists but cannot be read', async () => {
|
|
// EACCES / EIO / ESTALE on the file itself, with the mount up: a transient
|
|
// condition wearing a per-file disguise. Only ENOENT means genuinely gone.
|
|
const root = path.join(process.env.EXTERNAL_MEDIA_ROOT, 'locked');
|
|
const dir = path.join(root, 'individual');
|
|
await fs.promises.mkdir(dir, { recursive: true });
|
|
const file = path.join(dir, 'a.jpg');
|
|
await fs.promises.writeFile(file, 'x');
|
|
await fs.promises.chmod(file, 0o000);
|
|
|
|
const { photoId } = await seedExternalPhoto({ externalPath: 'locked' });
|
|
try {
|
|
await expect(faceProcessor.processPhotoFaces(photoId))
|
|
.rejects.toBeInstanceOf(faceProcessor.TransientSourceError);
|
|
} finally {
|
|
await fs.promises.chmod(file, 0o644).catch(() => {});
|
|
}
|
|
});
|
|
|
|
it('still fails managed photos without probing the mount', async () => {
|
|
// The probe is scoped to external/reference rows: a managed photo with no
|
|
// preview is broken, and there is no mount to blame.
|
|
const [e] = await db('events').insert({
|
|
slug: `tr-m-${Math.random().toString(36).slice(2, 8)}`,
|
|
event_type: 'wedding',
|
|
event_name: 'trm',
|
|
event_date: '2026-01-01',
|
|
host_email: 'h@example.com',
|
|
admin_email: 'a@example.com',
|
|
password_hash: 'x',
|
|
share_link: `tr-m-${Math.random()}`,
|
|
expires_at: new Date().toISOString(),
|
|
face_recognition_enabled: true,
|
|
}).returning('id');
|
|
const [p] = await db('photos').insert({
|
|
event_id: typeof e === 'object' ? e.id : e,
|
|
filename: 'm.jpg',
|
|
path: 'trm/m.jpg',
|
|
type: 'individual',
|
|
width: 100,
|
|
height: 100,
|
|
processing_status: 'complete',
|
|
face_status: 'processing',
|
|
source_origin: 'managed',
|
|
}).returning('id');
|
|
|
|
const result = await faceProcessor.processPhotoFaces(typeof p === 'object' ? p.id : p);
|
|
expect(result.status).toBe('failed');
|
|
});
|
|
});
|