mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-05 10:24:05 +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:
@@ -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