mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 17:41:51 +00:00
fix(journey): select all takes every photo in the range and imports keep their order
The photo picker's Select all took only the pages already loaded, 50 at a time, and replaced whatever had been picked on another tab. It now loads the rest of a day, trip or date-range search before selecting (cancelled by closing the picker or switching tab), adds to earlier picks, and Deselect all only clears what is in view. Add stays disabled until that loading is done. The whole-library tab keeps selecting what is loaded and shows the count as "N+". A date-filtered Immich search stopped at 1,000 photos without a word, because its page budget was absolute; it is now relative to the page asked for, with an absolute ceiling of 270 raw pages sized so the picker's deepest page still gets a full answer. Adds go out in batches of 500 ids, under the JSON body limit, and each batch is sent oldest first, so photos land in an entry in the order they were taken. When a later batch fails, the photos already saved are counted and the journey reloads while the error still shows, through one hook for desktop and phone. After a provider add, the capture-time lookup runs at most four at a time per user, shared by all of that user's batches. When it fills a row, a journey:photos:updated event reloads open journeys once per batch, from the REST routes and the MCP add tool alike. Device uploads, which arrive one file per request, get the same lookup without the event. Addresses discussion #1587.
This commit is contained in:
@@ -1,9 +1,9 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { AllowedFileTypesModule } from '../files/allowed-file-types.module';
|
||||
import { MemoriesModule } from '../memories/memories.module';
|
||||
import { PluginGuardsModule } from '../plugins/host/plugin-guards.module';
|
||||
import { StorageModule } from '../storage/storage.module';
|
||||
import { JourneyDomainModule } from './journey-domain.module';
|
||||
import { JourneyPhotoCaptureModule } from './journey-photo-capture.module';
|
||||
import { JournalRpc } from './journal.rpc';
|
||||
|
||||
/**
|
||||
@@ -11,17 +11,17 @@ import { JournalRpc } from './journal.rpc';
|
||||
*
|
||||
* JournalRpc used to sit in JourneyDomainModule, and it cannot stay there now
|
||||
* that it writes photo bytes: that needs StorageService and, for the EXIF
|
||||
* backfill, PhotoCaptureBackfillService out of MemoriesModule. JourneyDomainModule
|
||||
* exists precisely so places, assignments and the plugin host can reach a few
|
||||
* journey functions WITHOUT dragging MemoriesModule and both photo providers into
|
||||
* their graphs (see the comment there), so the dependency goes here instead and
|
||||
* only the plugin host pays for it.
|
||||
* backfill, JourneyPhotoCaptureModule, which brings MemoriesModule with it.
|
||||
* JourneyDomainModule exists precisely so places, assignments and the plugin
|
||||
* host can reach a few journey functions WITHOUT dragging MemoriesModule and
|
||||
* both photo providers into their graphs (see the comment there), so the
|
||||
* dependency goes here instead and only the plugin host pays for it.
|
||||
*
|
||||
* JourneyDomainModule is re-exported so importing this one is a superset of
|
||||
* importing that one, and nothing that already depended on it has to change.
|
||||
*/
|
||||
@Module({
|
||||
imports: [JourneyDomainModule, StorageModule, AllowedFileTypesModule, MemoriesModule, PluginGuardsModule],
|
||||
imports: [JourneyDomainModule, StorageModule, AllowedFileTypesModule, JourneyPhotoCaptureModule, PluginGuardsModule],
|
||||
providers: [JournalRpc],
|
||||
exports: [JourneyDomainModule],
|
||||
})
|
||||
|
||||
@@ -11,10 +11,10 @@ import { ADDON_IDS } from '../../addons';
|
||||
import { readEnv } from '../../app-config';
|
||||
import { isDemoEmail } from '../common/demo';
|
||||
import { AllowedFileTypesService } from '../files/allowed-file-types.service';
|
||||
import { PhotoCaptureBackfillService } from '../memories/photo-capture-backfill.service';
|
||||
import { DatabaseService } from '../database/database.service';
|
||||
import { StorageService } from '../storage/storage.service';
|
||||
import { JourneyDomainService } from './journey-domain.service';
|
||||
import { JourneyPhotoCaptureService } from './journey-photo-capture.service';
|
||||
|
||||
/** 10MB decoded, the same cap the file surface applies to plugin uploads. */
|
||||
const PHOTO_CONTENT_MAX = 10 * 1024 * 1024;
|
||||
@@ -45,7 +45,7 @@ export class JournalRpc {
|
||||
private readonly guards: PluginGuards,
|
||||
private readonly storage: StorageService,
|
||||
private readonly allowedTypes: AllowedFileTypesService,
|
||||
private readonly captureBackfill: PhotoCaptureBackfillService,
|
||||
private readonly photoCapture: JourneyPhotoCaptureService,
|
||||
private readonly db: DatabaseService,
|
||||
) {}
|
||||
|
||||
@@ -181,9 +181,10 @@ export class JournalRpc {
|
||||
await this.storage.delete('journey', filename).catch(() => {});
|
||||
throw new ForbiddenResource(`no editable journal entry ${entryId} for this user`);
|
||||
}
|
||||
// Best-effort, exactly as the REST route does it: reads EXIF so the photo
|
||||
// carries its capture date.
|
||||
this.captureBackfill.schedule([photo.photo_id].filter((id): id is number => typeof id === 'number'), userId);
|
||||
// Best-effort, exactly as the REST upload does it: reads EXIF so the photo
|
||||
// carries its capture date. One photo per call, so no journey refresh, or a
|
||||
// plugin importing a folder would reload every open client once per photo.
|
||||
this.photoCapture.scheduleUpload([photo], userId);
|
||||
return photo;
|
||||
}
|
||||
|
||||
|
||||
@@ -1500,6 +1500,19 @@ export class JourneyDomainService {
|
||||
|
||||
// ── Photos ───────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* The journey an entry belongs to, or null when there is no such entry.
|
||||
*
|
||||
* No access check: it answers for a caller that has already added photos to
|
||||
* the entry, and only decides which journey hears about their capture times.
|
||||
*/
|
||||
journeyIdOfEntry(entryId: number): number | null {
|
||||
const row = this.db.prepare('SELECT journey_id FROM journey_entries WHERE id = ?').get(entryId) as
|
||||
| { journey_id: number }
|
||||
| undefined;
|
||||
return row?.journey_id ?? null;
|
||||
}
|
||||
|
||||
// Promote a skeleton suggestion to a concrete entry. Called whenever the user
|
||||
// adds content (photo upload, provider photo, gallery link) — a suggestion
|
||||
// with photos is no longer just a suggestion.
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { MemoriesModule } from '../memories/memories.module';
|
||||
import { JourneyDomainModule } from './journey-domain.module';
|
||||
import { JourneyPhotoCaptureService } from './journey-photo-capture.service';
|
||||
|
||||
/**
|
||||
* The capture-time backfill as the journey surfaces use it: fill taken_at, then,
|
||||
* for a batch of provider photos, tell the journey (#1587).
|
||||
*
|
||||
* Its own module because two containers need the same instance of the rule:
|
||||
* JourneyModule (REST routes and the MCP tool) and JournalRpcModule (the plugin
|
||||
* RPC). Neither JourneyDomainModule nor MemoriesModule can own it, the first
|
||||
* because it stays free of the photo providers on purpose and the second
|
||||
* because the memories domain knows nothing about journeys.
|
||||
*/
|
||||
@Module({
|
||||
imports: [JourneyDomainModule, MemoriesModule],
|
||||
providers: [JourneyPhotoCaptureService],
|
||||
exports: [JourneyPhotoCaptureService],
|
||||
})
|
||||
export class JourneyPhotoCaptureModule {}
|
||||
@@ -0,0 +1,85 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { PhotoCaptureBackfillService } from '../memories/photo-capture-backfill.service';
|
||||
import { JourneyDomainService } from './journey-domain.service';
|
||||
|
||||
/** The trek_photos ids of freshly added journey photo rows, whatever shape the add answered with. */
|
||||
function trekPhotoIdsOf(photos: readonly unknown[]): number[] {
|
||||
return photos
|
||||
.map(p => (p as { photo_id?: unknown } | null)?.photo_id)
|
||||
.filter((id): id is number => typeof id === 'number');
|
||||
}
|
||||
|
||||
/**
|
||||
* Capture times for photos that just landed on a journey, and the refresh that
|
||||
* has to follow them (#1587).
|
||||
*
|
||||
* The add answers before anyone has asked the provider when each photo was
|
||||
* taken (#1614 keeps that on the server rather than trusting the client). So
|
||||
* the reload a client does straight after the add still sees the new photos
|
||||
* without taken_at, and the gallery files them at the end by import time. Once
|
||||
* the backfill has written something, everyone on the journey is told, the
|
||||
* importer included: its own reload came too early, which is why the event
|
||||
* excludes no socket.
|
||||
*
|
||||
* One place for the REST routes, the MCP tool and the plugin RPC, so no surface
|
||||
* can add provider photos that stay out of order until somebody reloads.
|
||||
*
|
||||
* Uploads from a device fill their capture times here too, but tell nobody (see
|
||||
* scheduleUpload): one upload request carries one file, so a refresh per request
|
||||
* would reload every open client once per photo of a bulk upload.
|
||||
*/
|
||||
@Injectable()
|
||||
export class JourneyPhotoCaptureService {
|
||||
constructor(
|
||||
private readonly backfill: PhotoCaptureBackfillService,
|
||||
private readonly journey: JourneyDomainService,
|
||||
) {}
|
||||
|
||||
/** Provider photos just added to a journey, to its gallery or to one of its entries. Detached. */
|
||||
scheduleForJourney(journeyId: number, photos: readonly unknown[], userId: number): void {
|
||||
const ids = trekPhotoIdsOf(photos);
|
||||
if (!ids.length) return;
|
||||
void this.fill(journeyId, ids, userId);
|
||||
}
|
||||
|
||||
/** Provider photos just added to an entry, for a caller that only knows the entry. Detached. */
|
||||
scheduleForEntry(entryId: number, photos: readonly unknown[], userId: number): void {
|
||||
const ids = trekPhotoIdsOf(photos);
|
||||
if (!ids.length) return;
|
||||
void this.fill(this.journey.journeyIdOfEntry(entryId), ids, userId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Photos uploaded from a device: read their capture times, and nothing more.
|
||||
* Detached.
|
||||
*
|
||||
* No refresh on purpose. The client sends one file per upload request and
|
||||
* reloads the journey itself once the last one is in, so an event per request
|
||||
* would only make every other open client reload once per uploaded photo. The
|
||||
* refresh belongs to the provider adds, where one request carries the batch.
|
||||
*/
|
||||
scheduleUpload(photos: readonly unknown[], userId: number): void {
|
||||
const ids = trekPhotoIdsOf(photos);
|
||||
if (!ids.length) return;
|
||||
this.backfill.schedule(ids, userId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Awaitable form, so tests do not have to chase a floating promise. Answers
|
||||
* whether the batch changed anything. Never rejects: it runs detached, and a
|
||||
* refresh that could not be sent is a gallery that sorts right on the next
|
||||
* reload, not a failed add.
|
||||
*/
|
||||
async fill(journeyId: number | null, trekPhotoIds: number[], userId: number): Promise<boolean> {
|
||||
let changed = false;
|
||||
try {
|
||||
changed = await this.backfill.run(trekPhotoIds, userId);
|
||||
if (changed && journeyId != null) {
|
||||
this.journey.broadcastJourneyEvent(journeyId, 'journey:photos:updated', {});
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`[Journey] capture refresh failed for journey ${journeyId}:`, err instanceof Error ? err.message : err);
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
}
|
||||
@@ -26,7 +26,7 @@ import { StorageService } from '../storage/storage.service';
|
||||
import { journeyThumbName } from '../memories/thumbnail.service';
|
||||
import { JourneyService } from './journey.service';
|
||||
import { JourneyBookService } from './journey-book.service';
|
||||
import { PhotoCaptureBackfillService } from '../memories/photo-capture-backfill.service';
|
||||
import { JourneyPhotoCaptureService } from './journey-photo-capture.service';
|
||||
import { AddonGuard } from '../addons/addon.guard';
|
||||
import { RequireAddon } from '../addons/require-addon.decorator';
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
@@ -130,7 +130,7 @@ export class JourneyController {
|
||||
private readonly journey: JourneyService,
|
||||
private readonly storage: StorageService,
|
||||
private readonly books: JourneyBookService,
|
||||
private readonly captureBackfill: PhotoCaptureBackfillService,
|
||||
private readonly photoCapture: JourneyPhotoCaptureService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
@@ -166,16 +166,6 @@ export class JourneyController {
|
||||
}
|
||||
}
|
||||
|
||||
// The add call carries only an asset id, so when and where the picture was taken
|
||||
// are fetched from the provider afterwards rather than trusted from the client
|
||||
// (#1614). Detached: a slow or unreachable provider must not hold up the add.
|
||||
private backfillCapture(photos: unknown[], userId: number): void {
|
||||
const ids = photos
|
||||
.map(p => (p as { photo_id?: number } | null)?.photo_id)
|
||||
.filter((id): id is number => typeof id === 'number');
|
||||
this.captureBackfill.schedule(ids, userId);
|
||||
}
|
||||
|
||||
// ── Static prefix routes (before /:id) ──────────────────────────────────
|
||||
@Get()
|
||||
list(@CurrentUser() user: User) {
|
||||
@@ -263,7 +253,11 @@ export class JourneyController {
|
||||
if (!results.length) {
|
||||
throw new HttpException({ error: 'Not allowed' }, 403);
|
||||
}
|
||||
this.backfillCapture(results, user.id);
|
||||
// When and where the picture was taken is read from the file afterwards
|
||||
// (#1614). Detached, so the add never waits for it, and without the journey
|
||||
// refresh the provider adds send (#1587): the client uploads one file per
|
||||
// request and reloads once after the last.
|
||||
this.photoCapture.scheduleUpload(results, user.id);
|
||||
return { photos: results };
|
||||
}
|
||||
|
||||
@@ -327,7 +321,7 @@ export class JourneyController {
|
||||
const photo = this.journey.addProviderPhoto(Number(entryId), user.id, String(body.provider), String(id), body.caption as string | undefined, pp, mt);
|
||||
if (photo) added.push(photo);
|
||||
});
|
||||
this.backfillCapture(added, user.id);
|
||||
this.photoCapture.scheduleForEntry(Number(entryId), added, user.id);
|
||||
return { photos: added, added: added.length };
|
||||
}
|
||||
if (!body.provider || !body.asset_id) {
|
||||
@@ -337,7 +331,7 @@ export class JourneyController {
|
||||
if (!photo) {
|
||||
throw new HttpException({ error: 'Not allowed or duplicate' }, 403);
|
||||
}
|
||||
this.backfillCapture([photo], user.id);
|
||||
this.photoCapture.scheduleForEntry(Number(entryId), [photo], user.id);
|
||||
return photo;
|
||||
}
|
||||
|
||||
@@ -424,8 +418,9 @@ export class JourneyController {
|
||||
throw new HttpException({ error: 'Not allowed' }, 403);
|
||||
}
|
||||
// An uploaded file carries its own EXIF; reading it is what puts the photo on
|
||||
// the map later. Detached, like the provider branch.
|
||||
this.backfillCapture(photos, user.id);
|
||||
// the map later. Detached, like the provider branch, but without its journey
|
||||
// refresh: one file per request would mean one reload per photo (#1587).
|
||||
this.photoCapture.scheduleUpload(photos, user.id);
|
||||
return { photos };
|
||||
}
|
||||
|
||||
@@ -484,7 +479,7 @@ export class JourneyController {
|
||||
const photo = this.journey.addProviderPhotoToGallery(Number(id), user.id, String(body.provider), String(aid), undefined, pp, mt);
|
||||
if (photo) added.push(photo);
|
||||
});
|
||||
this.backfillCapture(added, user.id);
|
||||
this.photoCapture.scheduleForJourney(Number(id), added, user.id);
|
||||
return { photos: added, added: added.length };
|
||||
}
|
||||
if (!body.provider || !body.asset_id) {
|
||||
@@ -494,7 +489,7 @@ export class JourneyController {
|
||||
if (!photo) {
|
||||
throw new HttpException({ error: 'Not allowed or duplicate' }, 403);
|
||||
}
|
||||
this.backfillCapture([photo], user.id);
|
||||
this.photoCapture.scheduleForJourney(Number(id), [photo], user.id);
|
||||
return photo;
|
||||
}
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ import type { JourneyContributor } from '../../types';
|
||||
import { addonGate } from '../addons/addon-gate';
|
||||
import { AddonsService } from '../addons/addons.service';
|
||||
import { AuthService } from '../auth/auth.service';
|
||||
import { PhotoCaptureBackfillService } from '../memories/photo-capture-backfill.service';
|
||||
import { JourneyPhotoCaptureService } from './journey-photo-capture.service';
|
||||
|
||||
/** Legacy registrar gate: the whole journey surface rode the journey addon. */
|
||||
const journeyAddonOn = addonGate(ADDON_IDS.JOURNEY);
|
||||
@@ -110,7 +110,7 @@ export class JourneyMcp {
|
||||
private readonly share: JourneyShareService,
|
||||
readonly addons: AddonsService,
|
||||
private readonly auth: AuthService,
|
||||
private readonly captureBackfill: PhotoCaptureBackfillService,
|
||||
private readonly photoCapture: JourneyPhotoCaptureService,
|
||||
) {}
|
||||
|
||||
// ── Read ────────────────────────────────────────────────────────────────
|
||||
@@ -572,11 +572,9 @@ export class JourneyMcp {
|
||||
|
||||
// Detached, exactly as the REST routes schedule it: the provider is asked
|
||||
// when and where each photo was taken, and without that answer an attached
|
||||
// photo can never appear on the journey map (#1614).
|
||||
this.captureBackfill.schedule(
|
||||
photos.map(p => (p as { photo_id?: number }).photo_id).filter((id): id is number => typeof id === 'number'),
|
||||
ctx.userId,
|
||||
);
|
||||
// photo can never appear on the journey map (#1614). Open clients are told
|
||||
// once it lands, so the gallery re-sorts without a reload (#1587).
|
||||
this.photoCapture.scheduleForJourney(journeyId, photos, ctx.userId);
|
||||
// `skipped` is what tells a caller that a shortfall was duplicates rather
|
||||
// than a failure; the REST body carries only photos and added.
|
||||
return ok({ photos, added: photos.length, skipped: asset_ids.length - photos.length });
|
||||
|
||||
@@ -6,6 +6,7 @@ import { JourneyBookService } from './journey-book.service';
|
||||
import { AddonsModule } from '../addons/addons.module';
|
||||
import { MemoriesModule } from '../memories/memories.module';
|
||||
import { JourneyDomainModule } from './journey-domain.module';
|
||||
import { JourneyPhotoCaptureModule } from './journey-photo-capture.module';
|
||||
import { JourneyMcp } from './journey.mcp';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
import { MulterModule } from '@nestjs/platform-express';
|
||||
@@ -33,7 +34,7 @@ import { journeyImageFileFilter, journeyUploadFilename } from './journey.control
|
||||
}),
|
||||
}),
|
||||
StorageModule,
|
||||
AuthModule, AddonsModule, MemoriesModule, JourneyDomainModule],
|
||||
AuthModule, AddonsModule, MemoriesModule, JourneyDomainModule, JourneyPhotoCaptureModule],
|
||||
controllers: [JourneyController, JourneyPublicController],
|
||||
providers: [JourneyService, JourneyBookService, JourneyMcp],
|
||||
})
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { PROVIDER_SELECT_ALL_MAX_PAGES } from '@trek/shared';
|
||||
import type { Response } from 'express';
|
||||
import { maybe_encrypt_api_key, decrypt_api_key } from '../common/crypto/apiKeyCrypto';
|
||||
import { checkSsrf, safeFetch, type SafeFetchOptions } from '../../utils/ssrfGuard';
|
||||
@@ -13,7 +14,7 @@ import { describeFetchFailure, fail, handleServiceResult, isWithinLocalDayRange,
|
||||
const ALBUM_PAGE_SIZE = 1000;
|
||||
const ALBUM_MAX_PAGES = 20;
|
||||
/**
|
||||
* How many upstream pages one search may read while filling one answered page.
|
||||
* How many upstream pages one search may spend on rows the day filter drops.
|
||||
*
|
||||
* The day filter runs after the fetch, so the number of raw pages an answered
|
||||
* page costs depends on how much of the padding days sits in front of it. This
|
||||
@@ -21,8 +22,29 @@ const ALBUM_MAX_PAGES = 20;
|
||||
* would otherwise keep a single request fetching, so the scan stops here and
|
||||
* answers `hasMore: false` rather than spinning or handing back the same
|
||||
* partial page for every page the caller asks for.
|
||||
*
|
||||
* It is an allowance on top of the pages the answered ones need, not a ceiling
|
||||
* on the scan. Every call restarts at raw page 1, so page N reads at least N-1
|
||||
* raw pages before it reaches its own, and a flat budget of 20 ended every
|
||||
* date-filtered search at 20 answered pages: 1,000 photos at the picker's old
|
||||
* page size, with no word to the user (#1587).
|
||||
*/
|
||||
const SEARCH_MAX_RAW_PAGES = 20;
|
||||
/**
|
||||
* The hard stop behind that allowance: no single search reads more raw pages
|
||||
* than this, whatever page it asks for. `page` comes from the caller unbounded,
|
||||
* and a purely relative budget would walk 100,000 raw pages to answer page
|
||||
* 100,000.
|
||||
*
|
||||
* Sized for the journey picker, which never asks a date-bounded search for a
|
||||
* page past PROVIDER_SELECT_ALL_MAX_PAGES + 1 (251), whether "Select all" loads
|
||||
* it, a second press does, or it is scrolled into view: photos 50,001 to 50,200
|
||||
* at its 200 a page. Page N may read N - 1 + SEARCH_MAX_RAW_PAGES raw pages, so
|
||||
* page 251 needs 250 + 20 = 270, and that is the ceiling. A deeper page, which
|
||||
* only another caller such as the MCP tool asks for, gets a smaller allowance,
|
||||
* and one past the ceiling can only come back empty with `hasMore: false`.
|
||||
*/
|
||||
const SEARCH_ABSOLUTE_MAX_RAW_PAGES = PROVIDER_SELECT_ALL_MAX_PAGES + SEARCH_MAX_RAW_PAGES;
|
||||
/** A mirrored journey upload is one photo; a server that sits on it this long is not coming back. */
|
||||
const UPLOAD_TIMEOUT_MS = 60_000;
|
||||
|
||||
@@ -331,7 +353,10 @@ export class ImmichService {
|
||||
const narrowed = Boolean(from || to);
|
||||
const skip = narrowed ? (page - 1) * size : 0;
|
||||
const wanted = skip + size;
|
||||
const maxRawPages = narrowed ? SEARCH_MAX_RAW_PAGES : 1;
|
||||
// The pages before this one, read even when every row on them is kept, plus
|
||||
// the allowance for rows the filter drops. Page 1 keeps its budget of 20, and
|
||||
// no page reads past the absolute ceiling.
|
||||
const maxRawPages = narrowed ? Math.min(page - 1 + SEARCH_MAX_RAW_PAGES, SEARCH_ABSOLUTE_MAX_RAW_PAGES) : 1;
|
||||
|
||||
const kept: any[] = [];
|
||||
let rawPage = narrowed ? 1 : page;
|
||||
|
||||
@@ -4,6 +4,26 @@ import { PhotoResolverService } from './photo-resolver.service';
|
||||
import { StorageService } from '../storage/storage.service';
|
||||
import { TrekPhotosRepository } from '../photos/trek-photos.repository';
|
||||
|
||||
/**
|
||||
* Provider lookups one user keeps in flight at once, across every run of theirs.
|
||||
*
|
||||
* Per user rather than per run: the picker sends a large import in batches of
|
||||
* 500, every batch starts its own detached run, and a per-run cap let those runs
|
||||
* add up to several times this against the same NAS. Per user rather than for
|
||||
* the whole server: each lookup goes to the importer's own Immich or Synology,
|
||||
* so a NAS that has stopped answering must not hold up the capture times of
|
||||
* everybody else on the instance. The service is a singleton of MemoriesModule,
|
||||
* so a user's imports queue for the same slots whichever surface sent them.
|
||||
*/
|
||||
const BACKFILL_CONCURRENCY = 4;
|
||||
|
||||
/** One user's lookup slots: how many are open, and who waits for the next. */
|
||||
interface LookupSlots {
|
||||
active: number;
|
||||
/** First come first served. */
|
||||
waiting: Array<() => void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ask the provider when and where a photo was taken, and record it (#1614).
|
||||
*
|
||||
@@ -19,6 +39,13 @@ import { TrekPhotosRepository } from '../photos/trek-photos.repository';
|
||||
*/
|
||||
@Injectable()
|
||||
export class PhotoCaptureBackfillService {
|
||||
/**
|
||||
* Open lookups per user, never above BACKFILL_CONCURRENCY for any of them. An
|
||||
* entry lives only while its user has a lookup open or waiting, so the map
|
||||
* does not grow with every user who ever imported a photo.
|
||||
*/
|
||||
private readonly slots = new Map<number, LookupSlots>();
|
||||
|
||||
constructor(
|
||||
private readonly resolver: PhotoResolverService,
|
||||
private readonly photos: TrekPhotosRepository,
|
||||
@@ -31,34 +58,104 @@ export class PhotoCaptureBackfillService {
|
||||
void this.run(trekPhotoIds, userId);
|
||||
}
|
||||
|
||||
/** Awaitable form, so tests do not have to chase a floating promise. */
|
||||
async run(trekPhotoIds: number[], userId: number): Promise<void> {
|
||||
for (const id of trekPhotoIds) {
|
||||
try {
|
||||
const photo = this.photos.resolve(id);
|
||||
// A row that already knows both has nothing to gain, and a provider call
|
||||
// per photo is the expensive part of an album import.
|
||||
if (!photo || (photo.taken_at && photo.lat != null && photo.lng != null)) continue;
|
||||
|
||||
// A local file has no provider to ask — the answer is in its own EXIF, and
|
||||
// getPhotoInfo would only hand back what the DB row already says.
|
||||
if (photo.provider === 'local') {
|
||||
const meta = await this.readLocalExif(photo.file_path);
|
||||
if (meta) this.photos.recordCaptureMetadata(id, meta);
|
||||
continue;
|
||||
}
|
||||
|
||||
const info = await this.resolver.getPhotoInfo(userId, id);
|
||||
if (!info.success) continue;
|
||||
|
||||
this.photos.recordCaptureMetadata(id, {
|
||||
takenAt: info.data.takenAt ?? null,
|
||||
lat: info.data.lat ?? null,
|
||||
lng: info.data.lng ?? null,
|
||||
});
|
||||
} catch (err) {
|
||||
console.error(`[Photos] capture backfill failed for ${id}:`, err instanceof Error ? err.message : err);
|
||||
/**
|
||||
* Awaitable form: resolves once every photo of the batch has been tried, with
|
||||
* whether any of them learned something. The journey refresh hangs off that
|
||||
* answer (#1587).
|
||||
*
|
||||
* A few photos at a time rather than one after the other: every provider call
|
||||
* can take seconds, and a strictly sequential walk kept a large import out of
|
||||
* order for minutes. The cap is shared by every run of the same user, so a
|
||||
* thousand-photo import, however many batches it arrives in, never has more
|
||||
* than BACKFILL_CONCURRENCY lookups open against that user's NAS.
|
||||
*/
|
||||
async run(trekPhotoIds: number[], userId: number): Promise<boolean> {
|
||||
let next = 0;
|
||||
let changed = false;
|
||||
const worker = async (): Promise<void> => {
|
||||
while (next < trekPhotoIds.length) {
|
||||
const id = trekPhotoIds[next++];
|
||||
if (await this.fillOne(id, userId)) changed = true;
|
||||
}
|
||||
};
|
||||
const workers = Math.min(BACKFILL_CONCURRENCY, trekPhotoIds.length);
|
||||
await Promise.all(Array.from({ length: workers }, worker));
|
||||
return changed;
|
||||
}
|
||||
|
||||
/**
|
||||
* One provider lookup inside the user's cap. The slot is given back whatever
|
||||
* the lookup does: a slot lost to a throw would stay lost, and four of them
|
||||
* would stall every later import of that user for good.
|
||||
*/
|
||||
private async withLookupSlot<T>(userId: number, lookup: () => Promise<T>): Promise<T> {
|
||||
const slots = await this.acquireSlot(userId);
|
||||
try {
|
||||
return await lookup();
|
||||
} finally {
|
||||
this.releaseSlot(userId, slots);
|
||||
}
|
||||
}
|
||||
|
||||
/** Wait for one of the user's lookup slots, and answer the entry it came from. */
|
||||
private async acquireSlot(userId: number): Promise<LookupSlots> {
|
||||
let slots = this.slots.get(userId);
|
||||
if (!slots) {
|
||||
slots = { active: 0, waiting: [] };
|
||||
this.slots.set(userId, slots);
|
||||
}
|
||||
if (slots.active < BACKFILL_CONCURRENCY) {
|
||||
slots.active++;
|
||||
return slots;
|
||||
}
|
||||
// releaseSlot hands its slot straight to the first waiter, so the count
|
||||
// stays where it is and nobody can slip in between.
|
||||
const { waiting } = slots;
|
||||
await new Promise<void>(resolve => {
|
||||
waiting.push(resolve);
|
||||
});
|
||||
return slots;
|
||||
}
|
||||
|
||||
/** Give a slot back: to the user's longest waiter, or, once nobody holds one, drop the entry. */
|
||||
private releaseSlot(userId: number, slots: LookupSlots): void {
|
||||
const next = slots.waiting.shift();
|
||||
if (next) {
|
||||
next();
|
||||
return;
|
||||
}
|
||||
slots.active--;
|
||||
if (slots.active === 0) this.slots.delete(userId);
|
||||
}
|
||||
|
||||
/** One photo; answers whether its row changed. */
|
||||
private async fillOne(id: number, userId: number): Promise<boolean> {
|
||||
try {
|
||||
const photo = this.photos.resolve(id);
|
||||
// A row that already knows both has nothing to gain, and a provider call
|
||||
// per photo is the expensive part of an album import.
|
||||
if (!photo || (photo.taken_at && photo.lat != null && photo.lng != null)) return false;
|
||||
|
||||
// A local file has no provider to ask: the answer is in its own EXIF, and
|
||||
// getPhotoInfo would only hand back what the DB row already says. Nor does
|
||||
// it take a lookup slot, which exists to spare a NAS: a device upload must
|
||||
// not wait behind the same user's provider import.
|
||||
if (photo.provider === 'local') {
|
||||
const meta = await this.readLocalExif(photo.file_path);
|
||||
return meta ? this.photos.recordCaptureMetadata(id, meta) : false;
|
||||
}
|
||||
|
||||
const info = await this.withLookupSlot(userId, () => this.resolver.getPhotoInfo(userId, id));
|
||||
if (!info.success) return false;
|
||||
|
||||
return this.photos.recordCaptureMetadata(id, {
|
||||
takenAt: info.data.takenAt ?? null,
|
||||
lat: info.data.lat ?? null,
|
||||
lng: info.data.lng ?? null,
|
||||
});
|
||||
} catch (err) {
|
||||
console.error(`[Photos] capture backfill failed for ${id}:`, err instanceof Error ? err.message : err);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -99,24 +99,35 @@ export class TrekPhotosRepository {
|
||||
* and a later, emptier answer must not blank what is already there.
|
||||
*
|
||||
* A photo with neither is the normal case, not a failure.
|
||||
*
|
||||
* Answers whether the row learned anything. The guard in the WHERE clause is
|
||||
* what makes that answer mean something: SQLite counts a matched row as changed
|
||||
* even when every COALESCE kept the old value, and the caller broadcasts a
|
||||
* journey refresh on it (#1587).
|
||||
*/
|
||||
recordCaptureMetadata(
|
||||
photoId: number,
|
||||
meta: { takenAt?: string | null; lat?: number | null; lng?: number | null },
|
||||
): void {
|
||||
): boolean {
|
||||
const { takenAt = null, lat = null, lng = null } = meta;
|
||||
if (takenAt == null && lat == null && lng == null) return;
|
||||
if (takenAt == null && lat == null && lng == null) return false;
|
||||
// Coordinates are stored as a pair or not at all — a lone latitude is not a
|
||||
// place, and half a pair would put the photo on the null island.
|
||||
const hasPair = Number.isFinite(lat) && Number.isFinite(lng);
|
||||
this.db.run(
|
||||
const pairLat = hasPair ? lat : null;
|
||||
const pairLng = hasPair ? lng : null;
|
||||
const result = this.db.run(
|
||||
`UPDATE trek_photos
|
||||
SET taken_at = COALESCE(taken_at, ?),
|
||||
lat = COALESCE(lat, ?),
|
||||
lng = COALESCE(lng, ?)
|
||||
WHERE id = ?`,
|
||||
takenAt, hasPair ? lat : null, hasPair ? lng : null, photoId,
|
||||
WHERE id = ?
|
||||
AND ((taken_at IS NULL AND ? IS NOT NULL)
|
||||
OR (lat IS NULL AND ? IS NOT NULL)
|
||||
OR (lng IS NULL AND ? IS NOT NULL))`,
|
||||
takenAt, pairLat, pairLng, photoId, takenAt, pairLat, pairLng,
|
||||
);
|
||||
return result.changes > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -9,6 +9,7 @@ import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vites
|
||||
import request from 'supertest';
|
||||
import cookieParser from 'cookie-parser';
|
||||
import type { Server } from 'http';
|
||||
import path from 'node:path';
|
||||
import { DatabaseModule } from '../../src/nest/database/database.module';
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { seedUser, sessionCookie } from './harness';
|
||||
@@ -50,10 +51,18 @@ const { jsvc } = vi.hoisted(() => ({
|
||||
jsvc: {
|
||||
listJourneys: vi.fn(), createJourney: vi.fn(), getJourneyFull: vi.fn(),
|
||||
journeyStats: vi.fn(), updateEntry: vi.fn(), restoreDismissedSuggestions: vi.fn(),
|
||||
addProviderPhoto: vi.fn(), addProviderPhotoToGallery: vi.fn(), uploadGalleryPhotos: vi.fn(),
|
||||
broadcastJourneyEvent: vi.fn(), journeyIdOfEntry: vi.fn(),
|
||||
},
|
||||
}));
|
||||
import { JourneyDomainService } from '../../src/nest/journey/journey-domain.service';
|
||||
|
||||
// The capture-time lookup itself asks a real provider; what these cases pin is
|
||||
// the wiring around it: the route answers, the backfill runs detached, and the
|
||||
// journey hears about it after a provider add, never after an upload (#1587).
|
||||
const { backfillRun, backfillSchedule } = vi.hoisted(() => ({ backfillRun: vi.fn(), backfillSchedule: vi.fn() }));
|
||||
import { PhotoCaptureBackfillService } from '../../src/nest/memories/photo-capture-backfill.service';
|
||||
|
||||
const { sharesvc } = vi.hoisted(() => ({ sharesvc: { getPublicJourney: vi.fn() } }));
|
||||
import { JourneyShareService } from '../../src/nest/journey/journey-share.service';
|
||||
|
||||
@@ -67,6 +76,7 @@ import { JourneyBookService } from '../../src/nest/journey/journey-book.service'
|
||||
import { MAX_SPREAD_ELEMENTS } from '@trek/shared';
|
||||
|
||||
import { JourneyModule } from '../../src/nest/journey/journey.module';
|
||||
import { StorageService } from '../../src/nest/storage/storage.service';
|
||||
import { AddonsService } from '../../src/nest/addons/addons.service';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
|
||||
@@ -85,6 +95,8 @@ describe('Journey e2e (real auth guard + temp SQLite)', () => {
|
||||
.useValue(booksvc)
|
||||
.overrideProvider(AddonsService)
|
||||
.useValue({ isAddonEnabled })
|
||||
.overrideProvider(PhotoCaptureBackfillService)
|
||||
.useValue({ run: backfillRun, schedule: backfillSchedule })
|
||||
.compile();
|
||||
const nest = moduleRef.createNestApplication();
|
||||
nest.use(cookieParser());
|
||||
@@ -415,6 +427,80 @@ describe('Journey e2e (real auth guard + temp SQLite)', () => {
|
||||
expect(res.body).toEqual({ error: 'Not allowed' });
|
||||
});
|
||||
|
||||
it('a gallery provider-photo add answers at once, then tells the journey when the capture times land (#1587)', async () => {
|
||||
jsvc.broadcastJourneyEvent.mockReset();
|
||||
jsvc.addProviderPhotoToGallery.mockReturnValue({ id: 5, journey_id: 9, photo_id: 77 });
|
||||
backfillRun.mockReset().mockResolvedValue(true);
|
||||
|
||||
const res = await request(server)
|
||||
.post('/api/journeys/9/gallery/provider-photos')
|
||||
.set('Cookie', sessionCookie(1))
|
||||
.send({ provider: 'immich', asset_ids: ['a1'], media_types: ['image'] });
|
||||
|
||||
expect(res.status).toBe(201);
|
||||
expect(res.body).toEqual({ photos: [{ id: 5, journey_id: 9, photo_id: 77 }], added: 1 });
|
||||
await vi.waitFor(() => expect(jsvc.broadcastJourneyEvent).toHaveBeenCalledWith(9, 'journey:photos:updated', {}));
|
||||
expect(backfillRun).toHaveBeenCalledWith([77], 1);
|
||||
});
|
||||
|
||||
it('an entry provider-photo add is told to the journey of that entry, and only when something was learned', async () => {
|
||||
jsvc.broadcastJourneyEvent.mockReset();
|
||||
jsvc.addProviderPhoto.mockReturnValue({ id: 6, entry_id: 3, photo_id: 78 });
|
||||
jsvc.journeyIdOfEntry.mockReturnValue(9);
|
||||
backfillRun.mockReset().mockResolvedValue(true);
|
||||
|
||||
const res = await request(server)
|
||||
.post('/api/journeys/entries/3/provider-photos')
|
||||
.set('Cookie', sessionCookie(1))
|
||||
.send({ provider: 'immich', asset_ids: ['a2'] });
|
||||
|
||||
expect(res.status).toBe(201);
|
||||
expect(res.body).toEqual({ photos: [{ id: 6, entry_id: 3, photo_id: 78 }], added: 1 });
|
||||
await vi.waitFor(() => expect(jsvc.broadcastJourneyEvent).toHaveBeenCalledWith(9, 'journey:photos:updated', {}));
|
||||
expect(jsvc.journeyIdOfEntry).toHaveBeenCalledWith(3);
|
||||
|
||||
// Nothing learned: the photos are where they already were, so no refresh.
|
||||
jsvc.broadcastJourneyEvent.mockReset();
|
||||
backfillRun.mockReset().mockResolvedValue(false);
|
||||
await request(server)
|
||||
.post('/api/journeys/entries/3/provider-photos')
|
||||
.set('Cookie', sessionCookie(1))
|
||||
.send({ provider: 'immich', asset_ids: ['a3'] });
|
||||
await vi.waitFor(() => expect(backfillRun).toHaveBeenCalled());
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
expect(jsvc.broadcastJourneyEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('a gallery upload gets its capture time read, and no journey refresh: the client sends one file per request (#1587)', async () => {
|
||||
jsvc.broadcastJourneyEvent.mockReset();
|
||||
backfillRun.mockReset().mockResolvedValue(true);
|
||||
backfillSchedule.mockReset();
|
||||
jsvc.uploadGalleryPhotos.mockImplementation((_id: number, _userId: number, files: Array<{ path: string }>) =>
|
||||
files.map((f, i) => ({ id: 30 + i, journey_id: 9, photo_id: 90 + i, file_path: f.path })));
|
||||
|
||||
const res = await request(server)
|
||||
.post('/api/journeys/9/gallery/photos')
|
||||
.set('Cookie', sessionCookie(1))
|
||||
.attach('photos', path.join(__dirname, '../fixtures/small-image.jpg'));
|
||||
|
||||
try {
|
||||
expect(res.status).toBe(201);
|
||||
expect(res.body.photos).toHaveLength(1);
|
||||
// The plain backfill, the same one the provider adds run...
|
||||
expect(backfillSchedule).toHaveBeenCalledWith([90], 1);
|
||||
// ...but not the refreshing run behind it: a bulk upload would otherwise
|
||||
// reload every open client once per photo.
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
expect(backfillRun).not.toHaveBeenCalled();
|
||||
expect(jsvc.broadcastJourneyEvent).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
const storage = app.get(StorageService);
|
||||
for (const photo of (res.body.photos ?? []) as Array<{ file_path: string }>) {
|
||||
await storage.delete('journey', photo.file_path.slice('journey/'.length));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('public journey 404 for an unknown token', async () => {
|
||||
sharesvc.getPublicJourney.mockReturnValueOnce(null);
|
||||
const res = await request(server).get('/api/public/journey/bad');
|
||||
|
||||
@@ -95,6 +95,7 @@ import { ImmichService } from '../../src/nest/memories/immich.service';
|
||||
import { SynologyService } from '../../src/nest/memories/synology.service';
|
||||
import { MemoriesAccessService } from '../../src/nest/memories/memories-access.service';
|
||||
import { PhotoCaptureBackfillService } from '../../src/nest/memories/photo-capture-backfill.service';
|
||||
import { JourneyPhotoCaptureService } from '../../src/nest/journey/journey-photo-capture.service';
|
||||
import { PhotoResolverService } from '../../src/nest/memories/photo-resolver.service';
|
||||
import { ThumbnailService } from '../../src/nest/memories/thumbnail.service';
|
||||
import { TrekPhotoCacheService } from '../../src/nest/memories/trek-photo-cache.service';
|
||||
@@ -245,7 +246,7 @@ export function createMcpTestRegistry(): McpRegistry {
|
||||
new CollectionsMcp(new CollectionsService(dbService, permissionsService, realtimeService, notificationsStub(), generalStorage), dbService, authService, addonsService),
|
||||
new TransitMcp(new TransitService(new GoogleTransitProvider(dbService)), daysService, reservationsService, dbService, authService, guards),
|
||||
new AtlasMcp(new AtlasService(dbService), addonsService, authService),
|
||||
new JourneyMcp(journeyDomain, new JourneyShareService(dbService, journeyDomain, new SettingsService(dbService)), addonsService, authService, captureBackfill),
|
||||
new JourneyMcp(journeyDomain, new JourneyShareService(dbService, journeyDomain, new SettingsService(dbService)), addonsService, authService, new JourneyPhotoCaptureService(captureBackfill, journeyDomain)),
|
||||
new MemoriesMcp(immichService, synologyService, dbService, addonsService),
|
||||
new NotificationsMcp(makeNotificationsService(dbService, realtimeService), authService),
|
||||
new AirtrailMcp(new AirtrailService(dbService, new AuditService(dbService), new AirtrailClient()), addonsService),
|
||||
|
||||
@@ -139,7 +139,7 @@ export function createPluginRpcHostFactory(dbs: DatabaseService): PluginRpcHostF
|
||||
new VacayRpc(vacay, guards),
|
||||
// The photo half needs storage plus the allowed-types setting and the EXIF
|
||||
// backfill; none of the tests on this harness write bytes, so they are stubs.
|
||||
new JournalRpc(journey, guards, generalStorage, { get: () => '*' } as never, { schedule: () => {} } as never, dbs),
|
||||
new JournalRpc(journey, guards, generalStorage, { get: () => '*' } as never, { scheduleUpload: () => {} } as never, dbs),
|
||||
new CollectionsRpc(collections, guards),
|
||||
new DbRpc(new PluginUserSettingsService(dbs)),
|
||||
new MetaRpc(dbs, guards),
|
||||
|
||||
@@ -982,6 +982,52 @@ describe('Immich searchPhotos pagination pass-through', () => {
|
||||
expect(res.body.hasMore).toBe(false);
|
||||
});
|
||||
|
||||
it('IMMICH-094: POST /search reaches a date-filtered page past the twentieth at the picker page size (#1587)', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
setImmichCredentials(testDb, user.id, 'https://immich.example.com', 'test-api-key');
|
||||
|
||||
// Every raw page is 200 photos of the searched day, so answered page 21
|
||||
// needs raw pages 1 to 21. The old flat budget of 20 answered it empty with
|
||||
// hasMore false, which is where a trip stopped without a word.
|
||||
const previous = vi.mocked(safeFetch).getMockImplementation();
|
||||
vi.mocked(safeFetch).mockClear();
|
||||
vi.mocked(safeFetch).mockImplementation(async (_url: unknown, init?: { body?: unknown }) => {
|
||||
const rawPage = JSON.parse(String(init?.body ?? '{}')).page as number;
|
||||
return {
|
||||
ok: true, status: 200,
|
||||
headers: { get: () => null },
|
||||
json: () => Promise.resolve({
|
||||
assets: {
|
||||
items: Array.from({ length: 200 }, (_, i) => ({
|
||||
id: `deep-${rawPage}-${i}`,
|
||||
fileCreatedAt: '2024-06-01T10:00:00.000Z',
|
||||
localDateTime: '2024-06-01T12:00:00.000Z',
|
||||
})),
|
||||
},
|
||||
}),
|
||||
body: null,
|
||||
} as never;
|
||||
});
|
||||
|
||||
let res: request.Response;
|
||||
try {
|
||||
res = await request(app)
|
||||
.post(`${IMMICH}/search`)
|
||||
.set('Cookie', authCookie(user.id))
|
||||
.send({ from: '2024-06-01', to: '2024-06-01', page: 21, size: 200 });
|
||||
} finally {
|
||||
if (previous) vi.mocked(safeFetch).mockImplementation(previous);
|
||||
}
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.assets).toHaveLength(200);
|
||||
expect(res.body.assets[0].id).toMatch(/^deep-21-/);
|
||||
expect(res.body.hasMore).toBe(true);
|
||||
expect(vi.mocked(safeFetch)).toHaveBeenCalledTimes(21);
|
||||
const sizes = vi.mocked(safeFetch).mock.calls.map(c => JSON.parse(String((c[1] as { body?: unknown }).body)).size);
|
||||
expect(new Set(sizes)).toEqual(new Set([200]));
|
||||
});
|
||||
|
||||
it('IMMICH-093 — POST /search requests timeline visibility so Immich v3 never returns hidden assets (#1474)', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
setImmichCredentials(testDb, user.id, 'https://immich.example.com', 'test-api-key');
|
||||
|
||||
@@ -55,8 +55,9 @@ const synologySearch = vi.spyOn(SynologyService.prototype, 'searchSynologyPhotos
|
||||
const synologyAlbums = vi.spyOn(SynologyService.prototype, 'listSynologyAlbums');
|
||||
const synologyAlbumPhotos = vi.spyOn(SynologyService.prototype, 'getSynologyAlbumPhotos');
|
||||
// Detached in production; held still here so a case can assert what was queued
|
||||
// without the provider lookup it would otherwise fire.
|
||||
const backfillSchedule = vi.spyOn(PhotoCaptureBackfillService.prototype, 'schedule').mockImplementation(() => {});
|
||||
// without the provider lookup it would otherwise fire. It answers "a row learned
|
||||
// its capture time", which is what makes the journey refresh go out.
|
||||
const backfillRun = vi.spyOn(PhotoCaptureBackfillService.prototype, 'run').mockResolvedValue(true);
|
||||
|
||||
const IMMICH_ASSET = { id: 'a1', takenAt: '2026-07-01T10:00:00.000Z', city: 'Rome', country: 'IT', lat: 41.9, lng: 12.5, mediaType: 'image' };
|
||||
const SYNOLOGY_ASSET = { id: 's1', takenAt: '2026-07-02T10:00:00.000Z', lat: 48.1, lng: 11.6 };
|
||||
@@ -94,7 +95,7 @@ beforeEach(() => {
|
||||
synologySearch.mockReset().mockResolvedValue({ success: true, data: { assets: [SYNOLOGY_ASSET], total: 1, hasMore: false } });
|
||||
synologyAlbums.mockReset().mockResolvedValue({ success: true, data: { albums: [{ id: '7', albumName: 'Munich', assetCount: 3, passphrase: 'pp' }] } });
|
||||
synologyAlbumPhotos.mockReset().mockResolvedValue({ success: true, data: { assets: [SYNOLOGY_ASSET], total: 1, hasMore: false } });
|
||||
backfillSchedule.mockClear();
|
||||
backfillRun.mockClear();
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
@@ -466,7 +467,25 @@ describe('Tool: add_journey_provider_photos', () => {
|
||||
arguments: { journeyId: journey.id, entryId: entry.id, provider: 'immich', asset_ids: ['bf-1'] },
|
||||
});
|
||||
const photoId = (testDb.prepare('SELECT id FROM trek_photos WHERE asset_id = ? AND owner_id = ?').get('bf-1', user.id) as { id: number }).id;
|
||||
expect(backfillSchedule).toHaveBeenCalledWith([photoId], user.id);
|
||||
expect(backfillRun).toHaveBeenCalledWith([photoId], user.id);
|
||||
});
|
||||
});
|
||||
|
||||
it('tells the journey once the capture times have landed, exactly as the REST routes do', async () => {
|
||||
// Same shared rule as POST /api/journeys/:id/gallery/provider-photos: the
|
||||
// gallery re-sorts on the event instead of waiting for a reload (#1587).
|
||||
const { user } = createUser(testDb);
|
||||
const journey = createJourney(testDb, user.id);
|
||||
await withHarness(user.id, async (h) => {
|
||||
await h.client.callTool({
|
||||
name: 'add_journey_provider_photos',
|
||||
arguments: { journeyId: journey.id, provider: 'immich', asset_ids: ['bf-2'] },
|
||||
});
|
||||
await vi.waitFor(() => expect(broadcastMock).toHaveBeenCalledWith(
|
||||
user.id,
|
||||
expect.objectContaining({ type: 'journey:photos:updated', journeyId: journey.id }),
|
||||
undefined,
|
||||
));
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -49,6 +49,7 @@ import type { MemoriesAccessService } from '../../../src/nest/memories/memories-
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { makeStorageFixture } from '../../helpers/storage-fixture';
|
||||
import { PROVIDER_SELECT_ALL_MAX_PAGES } from '@trek/shared';
|
||||
|
||||
const audit = { writeAudit: vi.fn() };
|
||||
const access = { getAlbumIdFromLink: vi.fn() };
|
||||
@@ -453,6 +454,91 @@ describe('searchPhotos', () => {
|
||||
expect(safeFetch).toHaveBeenCalledTimes(20);
|
||||
});
|
||||
|
||||
it('IMMICH-050e: a page past the twentieth still answers on a window full of the searched day', async () => {
|
||||
// The budget used to be 20 raw pages whatever page was asked for, and every
|
||||
// call restarts at raw page 1, so answered page 21 onwards was always empty
|
||||
// with hasMore false: a trip stopped at 1,000 photos without a word (#1587).
|
||||
safeFetch.mockImplementation(async (_url: string, init: { body: string }) => {
|
||||
const rawPage = JSON.parse(init.body).page as number;
|
||||
return upstream({ json: { assets: { items: [
|
||||
{ id: `d-${rawPage}-1`, fileCreatedAt: '2026-03-15T09:00:00.000Z', localDateTime: '2026-03-15T20:00:00.000Z' },
|
||||
{ id: `d-${rawPage}-2`, fileCreatedAt: '2026-03-15T08:00:00.000Z', localDateTime: '2026-03-15T19:00:00.000Z' },
|
||||
] } } });
|
||||
});
|
||||
|
||||
const result = await svc.searchPhotos(USER, '2026-03-15', '2026-03-15', 25, 2);
|
||||
|
||||
expect(result.assets!.map(a => a.id)).toEqual(['d-25-1', 'd-25-2']);
|
||||
expect(result.hasMore).toBe(true);
|
||||
expect(safeFetch).toHaveBeenCalledTimes(25);
|
||||
});
|
||||
|
||||
it('IMMICH-050f: a deep page still stops once its own allowance of padding pages is spent', async () => {
|
||||
// Page 3 needs the two pages in front of it plus the same allowance page 1
|
||||
// gets, and a window of nothing but the neighbouring day never fills it.
|
||||
safeFetch.mockResolvedValue(upstream({ json: { assets: { items: NEXT_DAY } } }));
|
||||
|
||||
const result = await svc.searchPhotos(USER, '2026-03-15', '2026-03-15', 3, 2);
|
||||
|
||||
expect(result.assets).toEqual([]);
|
||||
expect(result.hasMore).toBe(false);
|
||||
expect(safeFetch).toHaveBeenCalledTimes(22);
|
||||
});
|
||||
|
||||
it('IMMICH-050g: a huge page stops at the absolute ceiling instead of walking the whole library', async () => {
|
||||
// page is not bounded by the routes, and the relative allowance alone would
|
||||
// have read a million raw pages here before answering.
|
||||
safeFetch.mockImplementation(async (_url: string, init: { body: string }) => {
|
||||
const rawPage = JSON.parse(init.body).page as number;
|
||||
return upstream({ json: { assets: { items: [
|
||||
{ id: `h-${rawPage}-1`, fileCreatedAt: '2026-03-15T09:00:00.000Z', localDateTime: '2026-03-15T20:00:00.000Z' },
|
||||
{ id: `h-${rawPage}-2`, fileCreatedAt: '2026-03-15T08:00:00.000Z', localDateTime: '2026-03-15T19:00:00.000Z' },
|
||||
] } } });
|
||||
});
|
||||
|
||||
const result = await svc.searchPhotos(USER, '2026-03-15', '2026-03-15', 1_000_000, 2);
|
||||
|
||||
expect(result.assets).toEqual([]);
|
||||
expect(result.hasMore).toBe(false);
|
||||
// The ceiling: the pages in front of the picker's deepest page plus its
|
||||
// allowance, 250 + 20.
|
||||
expect(safeFetch).toHaveBeenCalledTimes(270);
|
||||
});
|
||||
|
||||
it('IMMICH-050h: the deepest page the picker asks for still gets its full allowance under the ceiling', async () => {
|
||||
// The picker never asks a date-bounded search past page 251, by Select all
|
||||
// or by scrolling: 250 pages in front of it plus the allowance of 20.
|
||||
safeFetch.mockResolvedValue(upstream({ json: { assets: { items: NEXT_DAY } } }));
|
||||
|
||||
const deepest = await svc.searchPhotos(USER, '2026-03-15', '2026-03-15', PROVIDER_SELECT_ALL_MAX_PAGES + 1, 2);
|
||||
|
||||
expect(deepest.hasMore).toBe(false);
|
||||
expect(safeFetch).toHaveBeenCalledTimes(270);
|
||||
|
||||
// One page further the ceiling already bites: the allowance shrinks by one.
|
||||
safeFetch.mockClear();
|
||||
await svc.searchPhotos(USER, '2026-03-15', '2026-03-15', PROVIDER_SELECT_ALL_MAX_PAGES + 2, 2);
|
||||
expect(safeFetch).toHaveBeenCalledTimes(270);
|
||||
});
|
||||
|
||||
it('IMMICH-050i: at the picker page size of 200 the deepest page it asks for answers in full', async () => {
|
||||
// A trip of more than 50,000 photos, every raw page full of the searched
|
||||
// day: page 251 is photos 50,001 to 50,200, read off raw page 251.
|
||||
safeFetch.mockImplementation(async (_url: string, init: { body: string }) => {
|
||||
const { page, size } = JSON.parse(init.body) as { page: number; size: number };
|
||||
return upstream({ json: { assets: { items: Array.from({ length: size }, (_, i) => ({
|
||||
id: `p-${page}-${i}`, fileCreatedAt: '2026-03-15T09:00:00.000Z', localDateTime: '2026-03-15T20:00:00.000Z',
|
||||
})) } } });
|
||||
});
|
||||
|
||||
const result = await svc.searchPhotos(USER, '2026-03-15', '2026-03-15', PROVIDER_SELECT_ALL_MAX_PAGES + 1, 200);
|
||||
|
||||
expect(result.assets).toHaveLength(200);
|
||||
expect(result.assets!.every(a => a.id.startsWith('p-251-'))).toBe(true);
|
||||
expect(result.hasMore).toBe(true);
|
||||
expect(safeFetch).toHaveBeenCalledTimes(251);
|
||||
});
|
||||
|
||||
it('IMMICH-050d: an unfiltered browse still costs one round trip, at the page it was asked for', async () => {
|
||||
// Nothing narrows those pages, so a raw page and an answered page are the
|
||||
// same page and the scan must not start over at page 1.
|
||||
|
||||
@@ -2721,3 +2721,16 @@ describe('entry field switches', () => {
|
||||
expect(svc.updateJourney(journey.id, editor.id, { show_mood: false })).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('journeyIdOfEntry', () => {
|
||||
it('JOURNEY-SVC-ENTRY-JOURNEY-001: names the journey an entry sits in, and null for an entry that does not exist', () => {
|
||||
// The capture refresh (#1587) only knows the entry the photos went to and has
|
||||
// to tell the journey they belong to.
|
||||
const { user } = createUser(testDb);
|
||||
const journey = createJourney(testDb, user.id);
|
||||
const entry = createJourneyEntry(testDb, journey.id, user.id);
|
||||
|
||||
expect(svc.journeyIdOfEntry(entry.id)).toBe(journey.id);
|
||||
expect(svc.journeyIdOfEntry(999999)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
/**
|
||||
* JourneyPhotoCaptureService (#1587): the capture-time backfill as every journey
|
||||
* surface runs it, and the refresh that has to follow it so the gallery re-sorts
|
||||
* without anyone reloading.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { JourneyPhotoCaptureService } from '../../../src/nest/journey/journey-photo-capture.service';
|
||||
import { PhotoCaptureBackfillService } from '../../../src/nest/memories/photo-capture-backfill.service';
|
||||
import type { JourneyDomainService } from '../../../src/nest/journey/journey-domain.service';
|
||||
import type { PhotoResolverService } from '../../../src/nest/memories/photo-resolver.service';
|
||||
import type { TrekPhotosRepository } from '../../../src/nest/photos/trek-photos.repository';
|
||||
import type { StorageService } from '../../../src/nest/storage/storage.service';
|
||||
|
||||
function build(changed: boolean | Error = true) {
|
||||
const run = vi.fn(async () => {
|
||||
if (changed instanceof Error) throw changed;
|
||||
return changed;
|
||||
});
|
||||
const schedule = vi.fn();
|
||||
const broadcastJourneyEvent = vi.fn();
|
||||
const journeyIdOfEntry = vi.fn((entryId: number) => (entryId === 4 ? 9 : null));
|
||||
const svc = new JourneyPhotoCaptureService(
|
||||
{ run, schedule } as unknown as PhotoCaptureBackfillService,
|
||||
{ broadcastJourneyEvent, journeyIdOfEntry } as unknown as JourneyDomainService,
|
||||
);
|
||||
return { svc, run, schedule, broadcastJourneyEvent, journeyIdOfEntry };
|
||||
}
|
||||
|
||||
beforeEach(() => vi.restoreAllMocks());
|
||||
|
||||
describe('JourneyPhotoCaptureService', () => {
|
||||
it('JPCAP-001: fills the added photos, then tells everyone on the journey, the importer included', async () => {
|
||||
const { svc, run, broadcastJourneyEvent } = build(true);
|
||||
|
||||
svc.scheduleForJourney(9, [{ id: 1, photo_id: 11 }, { id: 2, photo_id: 12 }], 3);
|
||||
|
||||
await vi.waitFor(() => expect(broadcastJourneyEvent).toHaveBeenCalled());
|
||||
expect(run).toHaveBeenCalledWith([11, 12], 3);
|
||||
// No socket is excluded: the importer's own reload came before the backfill.
|
||||
expect(broadcastJourneyEvent).toHaveBeenCalledWith(9, 'journey:photos:updated', {});
|
||||
});
|
||||
|
||||
it('JPCAP-002: says nothing when the backfill learned nothing', async () => {
|
||||
const { svc, broadcastJourneyEvent } = build(false);
|
||||
|
||||
await expect(svc.fill(9, [11], 3)).resolves.toBe(false);
|
||||
expect(broadcastJourneyEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('JPCAP-003: an entry add is reported against the journey that entry belongs to', async () => {
|
||||
const { svc, journeyIdOfEntry, broadcastJourneyEvent } = build(true);
|
||||
|
||||
svc.scheduleForEntry(4, [{ id: 1, photo_id: 11 }], 3);
|
||||
|
||||
await vi.waitFor(() => expect(broadcastJourneyEvent).toHaveBeenCalledWith(9, 'journey:photos:updated', {}));
|
||||
expect(journeyIdOfEntry).toHaveBeenCalledWith(4);
|
||||
});
|
||||
|
||||
it('JPCAP-004: an entry that has gone still gets its photos filled, with no one to tell', async () => {
|
||||
const { svc, run, broadcastJourneyEvent } = build(true);
|
||||
|
||||
await expect(svc.fill(null, [11], 3)).resolves.toBe(true);
|
||||
expect(run).toHaveBeenCalledWith([11], 3);
|
||||
expect(broadcastJourneyEvent).not.toHaveBeenCalled();
|
||||
|
||||
svc.scheduleForEntry(5, [{ id: 1, photo_id: 12 }], 3);
|
||||
await vi.waitFor(() => expect(run).toHaveBeenCalledWith([12], 3));
|
||||
expect(broadcastJourneyEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('JPCAP-005: rows without a trek photo id are skipped, and an empty batch never starts a run', () => {
|
||||
const { svc, run, journeyIdOfEntry } = build(true);
|
||||
|
||||
svc.scheduleForJourney(9, [null, { id: 1 }, { photo_id: 'x' }], 3);
|
||||
svc.scheduleForEntry(4, [], 3);
|
||||
|
||||
expect(run).not.toHaveBeenCalled();
|
||||
expect(journeyIdOfEntry).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('JPCAP-006: a refresh that could not be sent is logged, never thrown at a detached caller', async () => {
|
||||
const { svc, broadcastJourneyEvent } = build(true);
|
||||
broadcastJourneyEvent.mockImplementation(() => { throw new Error('socket gone'); });
|
||||
const error = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
|
||||
await expect(svc.fill(9, [11], 3)).resolves.toBe(true);
|
||||
expect(error).toHaveBeenCalledWith('[Journey] capture refresh failed for journey 9:', 'socket gone');
|
||||
});
|
||||
|
||||
it('JPCAP-007: a backfill that rejects is caught too', async () => {
|
||||
const { svc, run, broadcastJourneyEvent } = build(new Error('boom'));
|
||||
const error = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
|
||||
await expect(svc.fill(9, [11], 3)).resolves.toBe(false);
|
||||
expect(broadcastJourneyEvent).not.toHaveBeenCalled();
|
||||
expect(error).toHaveBeenCalledWith('[Journey] capture refresh failed for journey 9:', 'boom');
|
||||
|
||||
// Something thrown that is not an Error is logged as it is.
|
||||
run.mockRejectedValueOnce('gone');
|
||||
await expect(svc.fill(null, [11], 3)).resolves.toBe(false);
|
||||
expect(error).toHaveBeenLastCalledWith('[Journey] capture refresh failed for journey null:', 'gone');
|
||||
});
|
||||
|
||||
it('JPCAP-008: an upload gets the plain backfill and no refresh, since one request is one file', async () => {
|
||||
const { svc, run, schedule, broadcastJourneyEvent, journeyIdOfEntry } = build(true);
|
||||
|
||||
svc.scheduleUpload([{ id: 1, photo_id: 11 }, null, { id: 2 }], 3);
|
||||
await new Promise(resolve => setTimeout(resolve, 5));
|
||||
|
||||
expect(schedule).toHaveBeenCalledWith([11], 3);
|
||||
expect(run).not.toHaveBeenCalled();
|
||||
expect(journeyIdOfEntry).not.toHaveBeenCalled();
|
||||
expect(broadcastJourneyEvent).not.toHaveBeenCalled();
|
||||
|
||||
// Nothing with a trek photo id: nothing to schedule.
|
||||
schedule.mockClear();
|
||||
svc.scheduleUpload([{ id: 3 }], 3);
|
||||
expect(schedule).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('JPCAP-009: provider adds from every surface share the user\'s four lookup slots, uploads read their own files, and only the provider adds refresh', async () => {
|
||||
// A gallery add (REST or MCP), an entry add and a device upload (REST or
|
||||
// plugin RPC) landing together: three detached runs on the one backfill.
|
||||
const load = { inFlight: 0, peak: 0 };
|
||||
const getPhotoInfo = vi.fn(async () => {
|
||||
load.inFlight++;
|
||||
load.peak = Math.max(load.peak, load.inFlight);
|
||||
await new Promise(resolve => setTimeout(resolve, 5));
|
||||
load.inFlight--;
|
||||
return { success: true, data: { takenAt: '2026-03-15T08:00:00Z' } };
|
||||
});
|
||||
const recordCaptureMetadata = vi.fn(() => true);
|
||||
// Ids from 30 up are the uploaded files; their EXIF says when they were taken.
|
||||
const resolve = (id: number) =>
|
||||
id >= 30 ? { id, provider: 'local', file_path: `journey/${id}.jpg` } : { id, provider: 'immich' };
|
||||
const withLocalFile = vi.fn(async () => ({ DateTimeOriginal: new Date('2026-03-15T09:00:00Z') }));
|
||||
const backfill = new PhotoCaptureBackfillService(
|
||||
{ getPhotoInfo } as unknown as PhotoResolverService,
|
||||
{ resolve, recordCaptureMetadata } as unknown as TrekPhotosRepository,
|
||||
{ withLocalFile } as unknown as StorageService,
|
||||
);
|
||||
const broadcastJourneyEvent = vi.fn();
|
||||
const svc = new JourneyPhotoCaptureService(
|
||||
backfill,
|
||||
{ broadcastJourneyEvent, journeyIdOfEntry: () => 9 } as unknown as JourneyDomainService,
|
||||
);
|
||||
const rows = (from: number) => Array.from({ length: 5 }, (_, i) => ({ photo_id: from + i }));
|
||||
|
||||
svc.scheduleForJourney(9, rows(10), 3);
|
||||
svc.scheduleForEntry(4, rows(20), 3);
|
||||
svc.scheduleUpload(rows(30), 3);
|
||||
|
||||
await vi.waitFor(() => expect(recordCaptureMetadata).toHaveBeenCalledTimes(15));
|
||||
// Ten provider lookups, never more than four at once; the five uploads never asked a provider.
|
||||
expect(getPhotoInfo).toHaveBeenCalledTimes(10);
|
||||
expect(load.peak).toBe(4);
|
||||
expect(withLocalFile).toHaveBeenCalledTimes(5);
|
||||
expect(recordCaptureMetadata).toHaveBeenCalledWith(30, { takenAt: '2026-03-15T09:00:00.000Z', lat: null, lng: null });
|
||||
// One event per provider batch, none for the upload.
|
||||
await vi.waitFor(() => expect(broadcastJourneyEvent).toHaveBeenCalledTimes(2));
|
||||
expect(broadcastJourneyEvent).toHaveBeenCalledWith(9, 'journey:photos:updated', {});
|
||||
});
|
||||
});
|
||||
@@ -4,7 +4,7 @@ import type { Response } from 'express';
|
||||
|
||||
import { JourneyController } from '../../../src/nest/journey/journey.controller';
|
||||
import { journeyThumbName } from '../../../src/nest/memories/thumbnail.service';
|
||||
import type { PhotoCaptureBackfillService } from '../../../src/nest/memories/photo-capture-backfill.service';
|
||||
import type { JourneyPhotoCaptureService } from '../../../src/nest/journey/journey-photo-capture.service';
|
||||
import { JourneyPublicController } from '../../../src/nest/journey/journey-public.controller';
|
||||
import { AddonGuard } from '../../../src/nest/addons/addon.guard';
|
||||
import { REQUIRE_ADDON } from '../../../src/nest/addons/require-addon.decorator';
|
||||
@@ -28,9 +28,14 @@ const storageStub = {
|
||||
exists: storageExists,
|
||||
sendToResponse: storageSendToResponse,
|
||||
} as unknown as StorageService;
|
||||
// The capture backfill is detached and irrelevant to every case here — it only has
|
||||
// to exist so the constructor can call it.
|
||||
const captureBackfillStub = { schedule: vi.fn(), run: vi.fn() } as unknown as PhotoCaptureBackfillService;
|
||||
// The capture backfill is detached; most cases here only need it to exist so the
|
||||
// constructor can call it. The spies are read by the cases that pin which journey
|
||||
// (or entry) a provider batch is reported against, and that uploads get the
|
||||
// backfill without the refresh (#1587).
|
||||
const scheduleForEntry = vi.fn();
|
||||
const scheduleForJourney = vi.fn();
|
||||
const scheduleUpload = vi.fn();
|
||||
const captureBackfillStub = { scheduleForEntry, scheduleForJourney, scheduleUpload } as unknown as JourneyPhotoCaptureService;
|
||||
|
||||
/**
|
||||
* Build the controller.
|
||||
@@ -93,6 +98,42 @@ describe('JourneyController', () => {
|
||||
expect(thrown(() => ctl(svc({ addProviderPhoto: vi.fn().mockReturnValue(null) } as Partial<JourneyService>)).providerPhotos(user, '3', { provider: 'immich', asset_id: 'a' }))).toEqual({ status: 403, body: { error: 'Not allowed or duplicate' } });
|
||||
});
|
||||
|
||||
it('provider-photos hand what they added to the shared capture refresh, by entry or by journey; uploads only backfill (#1587)', async () => {
|
||||
const entryPhoto = { id: 1, photo_id: 11 };
|
||||
const galleryPhoto = { id: 2, photo_id: 12 };
|
||||
const withAdds = svc({
|
||||
addProviderPhoto: vi.fn().mockReturnValue(entryPhoto),
|
||||
addProviderPhotoToGallery: vi.fn().mockReturnValue(galleryPhoto),
|
||||
addPhoto: vi.fn().mockReturnValue(entryPhoto),
|
||||
uploadGalleryPhotos: vi.fn().mockReturnValue([galleryPhoto]),
|
||||
immichAutoUploadEnabled: vi.fn().mockReturnValue(false),
|
||||
} as Partial<JourneyService>);
|
||||
const c = ctl(withAdds);
|
||||
|
||||
c.providerPhotos(user, '3', { provider: 'immich', asset_ids: ['a'] });
|
||||
c.providerPhotos(user, '3', { provider: 'immich', asset_id: 'b' });
|
||||
await c.uploadEntryPhotos(user, '3', [{ filename: 'a.jpg', originalname: 'a.jpg' } as Express.Multer.File], {});
|
||||
expect(scheduleForEntry.mock.calls).toEqual([
|
||||
[3, [entryPhoto], 1],
|
||||
[3, [entryPhoto], 1],
|
||||
]);
|
||||
|
||||
c.galleryProviderPhotos(user, '9', { provider: 'immich', asset_ids: ['a'] });
|
||||
c.galleryProviderPhotos(user, '9', { provider: 'immich', asset_id: 'b' });
|
||||
await c.uploadGalleryPhotos(user, '9', [{ filename: 'g.jpg' } as Express.Multer.File]);
|
||||
expect(scheduleForJourney.mock.calls).toEqual([
|
||||
[9, [galleryPhoto], 1],
|
||||
[9, [galleryPhoto], 1],
|
||||
]);
|
||||
|
||||
// The client uploads one file per request, so a refresh per upload would
|
||||
// reload every open client once per photo: uploads backfill and stay quiet.
|
||||
expect(scheduleUpload.mock.calls).toEqual([
|
||||
[[entryPhoto], 1],
|
||||
[[galleryPhoto], 1],
|
||||
]);
|
||||
});
|
||||
|
||||
it('link-photo: 400 without id (accepts legacy photo_id), 403, success', () => {
|
||||
expect(thrown(() => ctl(svc()).linkPhoto(user, '3', {}))).toEqual({ status: 400, body: { error: 'journey_photo_id required' } });
|
||||
const linkPhotoToEntry = vi.fn().mockReturnValue({ id: 5 });
|
||||
|
||||
@@ -37,6 +37,39 @@ function build(rows: Row[], info: Record<number, unknown>) {
|
||||
return { svc: new PhotoCaptureBackfillService(resolver, photos, storageStub), recordCaptureMetadata, getPhotoInfo };
|
||||
}
|
||||
|
||||
/**
|
||||
* A service whose provider stops answering user 1 until `recover` is called, the
|
||||
* way a NAS that has gone away holds a lookup until its timeout, and answers
|
||||
* every other user at once.
|
||||
*/
|
||||
function buildHung(rows: Row[]) {
|
||||
const nas = { up: false, pending: [] as Array<() => void> };
|
||||
const getPhotoInfo = vi.fn(async (userId: number, _id: number) => {
|
||||
if (userId === 1 && !nas.up) {
|
||||
await new Promise<void>(resolve => {
|
||||
nas.pending.push(resolve);
|
||||
});
|
||||
}
|
||||
return { success: true, data: { takenAt: '2026-03-15T08:00:00Z' } };
|
||||
});
|
||||
const recordCaptureMetadata = vi.fn(() => true);
|
||||
const photos = {
|
||||
resolve: (id: number) => rows.find(r => r.id === id) ?? null,
|
||||
recordCaptureMetadata,
|
||||
} as unknown as TrekPhotosRepository;
|
||||
const svc = new PhotoCaptureBackfillService({ getPhotoInfo } as unknown as PhotoResolverService, photos, storageStub);
|
||||
const recover = () => {
|
||||
nas.up = true;
|
||||
for (const answer of nas.pending.splice(0)) answer();
|
||||
};
|
||||
return { svc, getPhotoInfo, recordCaptureMetadata, recover };
|
||||
}
|
||||
|
||||
/** How many users the service is holding lookup slots for right now. */
|
||||
function usersWithSlots(svc: PhotoCaptureBackfillService): number {
|
||||
return (svc as unknown as { slots: Map<number, unknown> }).slots.size;
|
||||
}
|
||||
|
||||
describe('PhotoCaptureBackfillService', () => {
|
||||
it('CAPTURE-001: records what the provider knows', async () => {
|
||||
const { svc, recordCaptureMetadata } = build(
|
||||
@@ -76,7 +109,7 @@ describe('PhotoCaptureBackfillService', () => {
|
||||
it('CAPTURE-004: a provider that refuses leaves the row alone and does not throw', async () => {
|
||||
const { svc, recordCaptureMetadata } = build([{ id: 7 }], {});
|
||||
|
||||
await expect(svc.run([7], 1)).resolves.toBeUndefined();
|
||||
await expect(svc.run([7], 1)).resolves.toBe(false);
|
||||
expect(recordCaptureMetadata).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -108,6 +141,172 @@ describe('PhotoCaptureBackfillService', () => {
|
||||
svc.schedule([], 1);
|
||||
expect(getPhotoInfo).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('CAPTURE-016: answers whether any row learned something, which is what the journey refresh hangs off', async () => {
|
||||
const { svc, recordCaptureMetadata } = build(
|
||||
[{ id: 7 }, { id: 8 }],
|
||||
{ 7: { takenAt: '2026-03-15T10:20:00Z' }, 8: { takenAt: '2026-03-16T08:00:00Z' } },
|
||||
);
|
||||
// The repository reports no change for 7 (it already knew) and news for 8.
|
||||
recordCaptureMetadata.mockImplementation((id: number) => id === 8);
|
||||
|
||||
await expect(svc.run([7, 8], 1)).resolves.toBe(true);
|
||||
|
||||
recordCaptureMetadata.mockReturnValue(false);
|
||||
await expect(svc.run([7, 8], 1)).resolves.toBe(false);
|
||||
});
|
||||
|
||||
/** A service whose provider takes a moment per photo and counts how many lookups overlap. */
|
||||
function buildSlow(count: number) {
|
||||
const rows = Array.from({ length: count }, (_, i) => ({ id: i + 1 }));
|
||||
const recordCaptureMetadata = vi.fn(() => true);
|
||||
const load = { inFlight: 0, peak: 0 };
|
||||
const getPhotoInfo = vi.fn(async (_userId: number, id: number) => {
|
||||
load.inFlight++;
|
||||
load.peak = Math.max(load.peak, load.inFlight);
|
||||
await new Promise(resolve => setTimeout(resolve, 5));
|
||||
load.inFlight--;
|
||||
return { success: true, data: { takenAt: `2026-03-${String((id % 28) + 1).padStart(2, '0')}T08:00:00Z` } };
|
||||
});
|
||||
const photos = {
|
||||
resolve: (id: number) => rows.find(r => r.id === id) ?? null,
|
||||
recordCaptureMetadata,
|
||||
} as unknown as TrekPhotosRepository;
|
||||
const svc = new PhotoCaptureBackfillService({ getPhotoInfo } as unknown as PhotoResolverService, photos, storageStub);
|
||||
return { svc, rows, recordCaptureMetadata, getPhotoInfo, load };
|
||||
}
|
||||
|
||||
it('CAPTURE-017: one run asks about a few photos at a time instead of one after the other, never more than four', async () => {
|
||||
const { svc, rows, recordCaptureMetadata, getPhotoInfo, load } = buildSlow(10);
|
||||
|
||||
await expect(svc.run(rows.map(r => r.id), 1)).resolves.toBe(true);
|
||||
|
||||
expect(load.peak).toBe(4);
|
||||
expect(getPhotoInfo).toHaveBeenCalledTimes(10);
|
||||
expect(recordCaptureMetadata.mock.calls.map(c => (c as unknown[])[0]).sort((a, b) => (a as number) - (b as number)))
|
||||
.toEqual(rows.map(r => r.id));
|
||||
});
|
||||
|
||||
it('CAPTURE-018: the four slots are shared by every run of one user, so batches that start together still keep four in flight', async () => {
|
||||
// A 1,500-photo import arrives as three batches of 500, each its own detached
|
||||
// run; a cap per run would have let them open twelve lookups at once.
|
||||
const { svc, rows, getPhotoInfo, load } = buildSlow(15);
|
||||
const ids = rows.map(r => r.id);
|
||||
|
||||
const results = await Promise.all([svc.run(ids.slice(0, 5), 1), svc.run(ids.slice(5, 10), 1), svc.run(ids.slice(10), 1)]);
|
||||
|
||||
expect(results).toEqual([true, true, true]);
|
||||
expect(load.peak).toBe(4);
|
||||
expect(getPhotoInfo).toHaveBeenCalledTimes(15);
|
||||
|
||||
// Every slot came back: a later run gets the full four again.
|
||||
load.peak = 0;
|
||||
await svc.run(ids.slice(0, 8), 1);
|
||||
expect(load.peak).toBe(4);
|
||||
});
|
||||
|
||||
it('CAPTURE-019: two overlapping runs of one user together never have more than four lookups open', async () => {
|
||||
// Say a gallery import and an entry import landing at the same moment: each
|
||||
// run starts four workers of its own, and only four of the eight may ask.
|
||||
const { svc, rows, getPhotoInfo, load } = buildSlow(12);
|
||||
const ids = rows.map(r => r.id);
|
||||
|
||||
const first = svc.run(ids.slice(0, 6), 1);
|
||||
const second = svc.run(ids.slice(6), 1);
|
||||
|
||||
await expect(Promise.all([first, second])).resolves.toEqual([true, true]);
|
||||
expect(load.peak).toBe(4);
|
||||
expect(getPhotoInfo).toHaveBeenCalledTimes(12);
|
||||
});
|
||||
|
||||
it('CAPTURE-020: a lookup that throws gives its slot back', async () => {
|
||||
const { svc, rows, getPhotoInfo, load } = buildSlow(8);
|
||||
const ids = rows.map(r => r.id);
|
||||
// The first four lookups take every slot and then throw. Had they kept their
|
||||
// slots, the other four photos would wait for ever and the run never end.
|
||||
const slowAnswer = getPhotoInfo.getMockImplementation()!;
|
||||
getPhotoInfo.mockImplementation(async (userId: number, id: number) => {
|
||||
if (id > 4) return slowAnswer(userId, id);
|
||||
load.inFlight++;
|
||||
load.peak = Math.max(load.peak, load.inFlight);
|
||||
await new Promise(resolve => setTimeout(resolve, 5));
|
||||
load.inFlight--;
|
||||
throw new Error('NAS gone');
|
||||
});
|
||||
const error = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
|
||||
try {
|
||||
await expect(svc.run(ids, 1)).resolves.toBe(true);
|
||||
expect(getPhotoInfo).toHaveBeenCalledTimes(8);
|
||||
expect(error).toHaveBeenCalledWith('[Photos] capture backfill failed for 1:', 'NAS gone');
|
||||
|
||||
// All four slots are free again for the next import.
|
||||
load.peak = 0;
|
||||
getPhotoInfo.mockImplementation(slowAnswer);
|
||||
await svc.run(ids, 1);
|
||||
expect(load.peak).toBe(4);
|
||||
expect(usersWithSlots(svc)).toBe(0);
|
||||
} finally {
|
||||
error.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('CAPTURE-021: a provider that knows only the place records the place, and the time stays unknown', async () => {
|
||||
const { svc, recordCaptureMetadata } = build([{ id: 7 }], { 7: { lat: 48.8584, lng: 2.2945 } });
|
||||
|
||||
await svc.run([7], 1);
|
||||
|
||||
expect(recordCaptureMetadata).toHaveBeenCalledWith(7, { takenAt: null, lat: 48.8584, lng: 2.2945 });
|
||||
});
|
||||
|
||||
it('CAPTURE-022: a lookup that throws something other than an Error is logged as it is', async () => {
|
||||
const { svc, getPhotoInfo } = build([{ id: 7 }], {});
|
||||
getPhotoInfo.mockImplementation(async () => { throw 'socket hang up'; });
|
||||
const error = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
|
||||
try {
|
||||
await expect(svc.run([7], 1)).resolves.toBe(false);
|
||||
expect(error).toHaveBeenCalledWith('[Photos] capture backfill failed for 7:', 'socket hang up');
|
||||
} finally {
|
||||
error.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('CAPTURE-023: a NAS that stopped answering one user holds up nobody else', async () => {
|
||||
const { svc, getPhotoInfo, recordCaptureMetadata, recover } = buildHung(
|
||||
Array.from({ length: 10 }, (_, i) => ({ id: i + 1 })),
|
||||
);
|
||||
|
||||
// User 1 imports eight photos: the first four lookups take every slot of
|
||||
// theirs and hang, the other four wait behind them.
|
||||
const stuck = svc.run([1, 2, 3, 4, 5, 6, 7, 8], 1);
|
||||
await vi.waitFor(() => expect(getPhotoInfo).toHaveBeenCalledTimes(4));
|
||||
|
||||
// User 2's import is not queued behind them.
|
||||
await expect(svc.run([9, 10], 2)).resolves.toBe(true);
|
||||
expect(getPhotoInfo).toHaveBeenCalledWith(2, 9);
|
||||
expect(getPhotoInfo).toHaveBeenCalledWith(2, 10);
|
||||
expect(recordCaptureMetadata).toHaveBeenCalledWith(10, { takenAt: '2026-03-15T08:00:00Z', lat: null, lng: null });
|
||||
expect(getPhotoInfo).toHaveBeenCalledTimes(6);
|
||||
expect(usersWithSlots(svc)).toBe(1);
|
||||
|
||||
// Once the NAS is back, user 1's run finishes and leaves no slots behind.
|
||||
recover();
|
||||
await expect(stuck).resolves.toBe(true);
|
||||
expect(getPhotoInfo).toHaveBeenCalledTimes(10);
|
||||
expect(usersWithSlots(svc)).toBe(0);
|
||||
});
|
||||
|
||||
it('CAPTURE-024: every user has four slots of their own, so two importers may have eight lookups open', async () => {
|
||||
const { svc, rows, getPhotoInfo, load } = buildSlow(12);
|
||||
const ids = rows.map(r => r.id);
|
||||
|
||||
await expect(Promise.all([svc.run(ids.slice(0, 6), 1), svc.run(ids.slice(6), 2)])).resolves.toEqual([true, true]);
|
||||
|
||||
expect(load.peak).toBe(8);
|
||||
expect(getPhotoInfo).toHaveBeenCalledTimes(12);
|
||||
expect(usersWithSlots(svc)).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('PhotoCaptureBackfillService — local files', () => {
|
||||
@@ -181,7 +380,7 @@ describe('PhotoCaptureBackfillService — local files', () => {
|
||||
{ id: 7, provider: 'local', file_path: 'journey/a.jpg' },
|
||||
]);
|
||||
|
||||
await expect(svc.run([7], 1)).resolves.toBeUndefined();
|
||||
await expect(svc.run([7], 1)).resolves.toBe(false);
|
||||
expect(recordCaptureMetadata).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -219,7 +418,7 @@ describe('PhotoCaptureBackfillService — local files', () => {
|
||||
} as unknown as TrekPhotosRepository;
|
||||
const svc = new PhotoCaptureBackfillService({} as PhotoResolverService, photos, storageStub);
|
||||
|
||||
await expect(svc.run([7], 1)).resolves.toBeUndefined();
|
||||
await expect(svc.run([7], 1)).resolves.toBe(false);
|
||||
expect(recordCaptureMetadata).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -232,4 +431,25 @@ describe('PhotoCaptureBackfillService — local files', () => {
|
||||
svc.schedule([7], 1);
|
||||
await vi.waitFor(() => expect(recordCaptureMetadata).toHaveBeenCalled());
|
||||
});
|
||||
|
||||
it('CAPTURE-025: a device upload reads its EXIF while the same user\'s provider lookups hang', async () => {
|
||||
vi.mocked(exifr.parse).mockResolvedValue({ DateTimeOriginal: new Date('2026-03-15T10:20:00Z') });
|
||||
const { svc, getPhotoInfo, recordCaptureMetadata, recover } = buildHung([
|
||||
{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 },
|
||||
{ id: 5, provider: 'local', file_path: 'journey/upload.jpg' },
|
||||
]);
|
||||
|
||||
// The user's own import has every lookup slot taken by a NAS that hangs.
|
||||
const stuck = svc.run([1, 2, 3, 4], 1);
|
||||
await vi.waitFor(() => expect(getPhotoInfo).toHaveBeenCalledTimes(4));
|
||||
|
||||
// A file on TREK's own storage needs no slot, so the upload is not queued.
|
||||
await expect(svc.run([5], 1)).resolves.toBe(true);
|
||||
expect(storageStub.withLocalFile).toHaveBeenCalledWith('journey', 'upload.jpg', expect.any(Function));
|
||||
expect(recordCaptureMetadata).toHaveBeenCalledWith(5, { takenAt: '2026-03-15T10:20:00.000Z', lat: null, lng: null });
|
||||
expect(getPhotoInfo).toHaveBeenCalledTimes(4);
|
||||
|
||||
recover();
|
||||
await expect(stuck).resolves.toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -92,4 +92,17 @@ describe('TrekPhotosRepository.recordCaptureMetadata', () => {
|
||||
|
||||
expect(read(id)).toEqual({ taken_at: '2026-03-15T10:20:00Z', lat: 48.8584, lng: 2.2945 });
|
||||
});
|
||||
|
||||
it('TREKPHOTO-006: says whether the row learned anything, so a refresh is only sent for news', () => {
|
||||
const id = makePhoto();
|
||||
|
||||
expect(repo.recordCaptureMetadata(id, { takenAt: '2026-03-15T10:20:00Z' })).toBe(true);
|
||||
// Same answer again: every COALESCE keeps what is there.
|
||||
expect(repo.recordCaptureMetadata(id, { takenAt: '2020-01-01T00:00:00Z' })).toBe(false);
|
||||
// Half a pair is dropped, so there is nothing new in it either.
|
||||
expect(repo.recordCaptureMetadata(id, { lat: 48.8584, lng: null })).toBe(false);
|
||||
expect(repo.recordCaptureMetadata(id, { lat: 48.8584, lng: 2.2945 })).toBe(true);
|
||||
expect(repo.recordCaptureMetadata(id, {})).toBe(false);
|
||||
expect(repo.recordCaptureMetadata(999999, { takenAt: '2026-03-15T10:20:00Z' })).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -73,7 +73,7 @@ function build(addonOn: boolean) {
|
||||
new JournalRpc(spyService(calls, 'journey'), guards,
|
||||
{ put: async () => undefined, delete: async () => undefined } as never,
|
||||
{ get: () => '*' } as never,
|
||||
{ schedule: () => undefined } as never,
|
||||
{ scheduleUpload: () => undefined } as never,
|
||||
{ prepare: () => ({ get: () => ({ email: 'u@example.test' }) }) } as never),
|
||||
new CollectionsRpc(spyService(calls, 'collections'), guards),
|
||||
new CostsRpc(spyService(calls, 'budget'), db, { broadcast: vi.fn() } as never, guards, spyService(calls, 'membership')),
|
||||
|
||||
@@ -31,7 +31,7 @@ function build(overrides: {
|
||||
// Typed parameters so the assertions below can index mock.calls.
|
||||
const put = vi.fn(async (_category: string, _filename: string, _body?: unknown, _opts?: unknown) => undefined);
|
||||
const del = vi.fn(async (_category: string, _filename: string) => undefined);
|
||||
const schedule = vi.fn();
|
||||
const scheduleUpload = vi.fn();
|
||||
const addPhoto = vi.fn(overrides.addPhoto === undefined
|
||||
? () => ({ id: 5, photo_id: 42 })
|
||||
: () => overrides.addPhoto);
|
||||
@@ -43,10 +43,10 @@ function build(overrides: {
|
||||
{ requireAddon: vi.fn() } as never,
|
||||
{ put, delete: del } as never,
|
||||
{ get: () => overrides.allowed ?? '*' } as never,
|
||||
{ schedule } as never,
|
||||
{ scheduleUpload } as never,
|
||||
{ prepare: () => ({ get: () => ({ email: overrides.email ?? 'user@example.test' }) }) } as never,
|
||||
);
|
||||
return { rpc, put, del, schedule, addPhoto };
|
||||
return { rpc, put, del, scheduleUpload, addPhoto };
|
||||
}
|
||||
|
||||
const input = (over: Record<string, unknown> = {}) => ({ name: 'photo.jpg', content_base64: PNG, ...over });
|
||||
@@ -57,7 +57,7 @@ beforeEach(() => {
|
||||
|
||||
describe('journal.addEntryPhoto', () => {
|
||||
it('JPHOTO-001: stores the bytes under a name of its own, then links the photo', async () => {
|
||||
const { rpc, put, schedule, addPhoto } = build();
|
||||
const { rpc, put, scheduleUpload, addPhoto } = build();
|
||||
|
||||
const photo = await rpc.addEntryPhoto({ entryId: 3, input: input({ caption: 'Tokyo' }) }, ACTOR);
|
||||
|
||||
@@ -69,7 +69,9 @@ describe('journal.addEntryPhoto', () => {
|
||||
expect(category).toBe('journey');
|
||||
expect(filename).toMatch(/^[0-9a-f-]{36}\.jpg$/);
|
||||
expect(addPhoto).toHaveBeenCalledWith(3, 7, `journey/${filename}`, undefined, 'Tokyo');
|
||||
expect(schedule).toHaveBeenCalledWith([42], 7);
|
||||
// An upload's capture time is backfilled like the REST upload's, without the
|
||||
// journey refresh: one photo per call would be one reload per photo (#1587).
|
||||
expect(scheduleUpload).toHaveBeenCalledWith([{ id: 5, photo_id: 42 }], 7);
|
||||
});
|
||||
|
||||
it('JPHOTO-002: refuses an entry the acting user cannot edit, and removes the object it just wrote', async () => {
|
||||
|
||||
Reference in New Issue
Block a user