fix(journey): keep place names between photo previews and count unreadable capture times

The reverse lookup behind MapsService keeps no cache, so every preview
(each gap change, each reopen) took the shared Nominatim slot again for
the same towns. Keep the names found, by rounded point and language,
bounded; failed or empty lookups are asked again. A capture time that
does not parse now counts in withoutCaptureTime instead of vanishing.
This commit is contained in:
Maurice
2026-11-30 14:40:26 +01:00
parent c36aae1022
commit a7b36fef62
3 changed files with 86 additions and 10 deletions
@@ -34,6 +34,31 @@ export const FROM_PHOTOS_MAX_GEOCODED = 25;
const FROM_PHOTOS_GEOCODE_BUDGET_MS = 20_000;
/** The deadline of one place lookup, after the geocoder's own rate-limit wait. */
const GEOCODE_TIMEOUT_MS = 8_000;
/** The most place names kept between previews; the oldest goes first. */
const PLACE_NAME_CACHE_MAX = 5_000;
/**
* Place names already found, by rounded point and language. The geocoder's
* reverse lookup keeps no cache of its own, and a traveller who changes the
* gap or opens the dialog again asks for the same towns: they come from here
* instead of taking the shared Nominatim slot again. Only names are kept: a
* lookup that failed or came back empty (Nominatim answers a refusal with no
* name) is asked again by the next preview.
*/
const placeNameCache = new Map<string, string>();
/** Test seam: the suites start every case without names found by an earlier one. */
export function forgetFromPhotosPlaceNames(): void {
placeNameCache.clear();
}
function rememberPlaceName(key: string, name: string): void {
if (placeNameCache.size >= PLACE_NAME_CACHE_MAX) {
const oldest = placeNameCache.keys().next().value;
if (oldest !== undefined) placeNameCache.delete(oldest);
}
placeNameCache.set(key, name);
}
type CreatedEntry = NonNullable<Awaited<ReturnType<JourneyDomainService['createEntry']>>>;
@@ -47,7 +72,7 @@ function countryOf(lat: number | null, lng: number | null): string | null {
}
}
/** The photos of the gallery on no entry, as the clustering reads them; the ones without a capture time apart. */
/** The photos of the gallery on no entry, as the clustering reads them; those without a capture time counted apart. */
function capturedOf(rows: readonly JourneyPhotoOffEntryRow[]): { captured: FromPhotosPhoto[]; withoutTime: number } {
const captured: FromPhotosPhoto[] = [];
let withoutTime = 0;
@@ -112,9 +137,10 @@ export class JourneyEntriesFromPhotosService {
maxDistanceKm: request.maxDistanceKm ?? JOURNEY_FROM_PHOTOS_DEFAULT_DISTANCE_KM,
};
const { captured, withoutTime } = capturedOf(await this.photosRepo.listOffEntries(journeyId));
const summaries = clusterCaptures(localCaptures(captured, request.timezone ?? null), thresholds).map(
summarizeCluster,
);
const captures = localCaptures(captured, request.timezone ?? null);
// A capture time that does not read as one leaves the photo out of every group like a missing one.
const withoutCaptureTime = withoutTime + captured.length - captures.length;
const summaries = clusterCaptures(captures, thresholds).map(summarizeCluster);
const names = await this.placeNames(summaries, request.lang);
const clusters = summaries.map((summary, index): JourneyEntriesFromPhotosCluster => {
const countryCode = countryOf(summary.lat, summary.lng);
@@ -136,12 +162,12 @@ export class JourneyEntriesFromPhotosService {
coverPhotoId: summary.coverPhotoId,
};
});
return { clusters, withoutCaptureTime: withoutTime, ...thresholds };
return { clusters, withoutCaptureTime, ...thresholds };
}
/**
* A place name for every group with a middle, from the geocoder, one point
* asked once. Best effort: at most {@link FROM_PHOTOS_MAX_GEOCODED} points
* asked once (and not again while it is in the cache). Best effort: at most {@link FROM_PHOTOS_MAX_GEOCODED} points
* and {@link FROM_PHOTOS_GEOCODE_BUDGET_MS} per preview, one after the other
* so the geocoder's own rate limit is kept; a point it did not name (no
* answer, an error, past the budget) gets null, and its group is named by
@@ -151,6 +177,7 @@ export class JourneyEntriesFromPhotosService {
const started = Date.now();
const byPoint = new Map<string, string | null>();
const names: (string | null)[] = [];
let asked = 0;
for (const summary of summaries) {
if (summary.lat === null || summary.lng === null) {
names.push(null);
@@ -158,10 +185,15 @@ export class JourneyEntriesFromPhotosService {
}
// About a kilometre: two groups of the same town share one lookup.
const key = `${summary.lat.toFixed(2)},${summary.lng.toFixed(2)}`;
const cacheKey = `${key}|${lang ?? ''}`;
const cached = placeNameCache.get(cacheKey);
if (!byPoint.has(key) && cached !== undefined) byPoint.set(key, cached);
if (!byPoint.has(key)) {
const withinBudget =
byPoint.size < FROM_PHOTOS_MAX_GEOCODED && Date.now() - started < FROM_PHOTOS_GEOCODE_BUDGET_MS;
byPoint.set(key, withinBudget ? await this.placeName(summary.lat, summary.lng, lang) : null);
const withinBudget = asked < FROM_PHOTOS_MAX_GEOCODED && Date.now() - started < FROM_PHOTOS_GEOCODE_BUDGET_MS;
if (withinBudget) asked++;
const found = withinBudget ? await this.placeName(summary.lat, summary.lng, lang) : null;
if (found) rememberPlaceName(cacheKey, found);
byPoint.set(key, found);
}
names.push(byPoint.get(key) ?? null);
}
@@ -14,7 +14,10 @@ import { AddonsModule } from '../../../../src/nest/addons/addons.module';
import { AddonsService } from '../../../../src/nest/addons/addons.service';
import { JourneyDomainModule } from '../../../../src/nest/journey/journey-domain.module';
import { JourneyEntriesFromPhotosMcp } from '../../../../src/nest/journey/journey-entries-from-photos.mcp';
import { JourneyEntriesFromPhotosService } from '../../../../src/nest/journey/journey-entries-from-photos.service';
import {
forgetFromPhotosPlaceNames,
JourneyEntriesFromPhotosService,
} from '../../../../src/nest/journey/journey-entries-from-photos.service';
import { MapsService } from '../../../../src/nest/maps/maps.service';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { addJourneyContributor, makeJourney } from '../../../helpers/factories/journeys';
@@ -59,6 +62,7 @@ beforeEach(() => {
orm.clear();
t.realtime.reset();
vi.restoreAllMocks();
forgetFromPhotosPlaceNames();
reverseGeocode.mockReset().mockResolvedValue({ name: 'Venezia', address: null });
});
afterAll(async () => {
@@ -20,6 +20,7 @@ import { DomainError } from '../../../../src/nest/common/domain-error';
import { JourneyDomainModule } from '../../../../src/nest/journey/journey-domain.module';
import { JourneyDomainService } from '../../../../src/nest/journey/journey-domain.service';
import {
forgetFromPhotosPlaceNames,
FROM_PHOTOS_MAX_GEOCODED,
JourneyEntriesFromPhotosService,
} from '../../../../src/nest/journey/journey-entries-from-photos.service';
@@ -55,6 +56,7 @@ beforeEach(() => {
orm.clear();
t.realtime.reset();
vi.restoreAllMocks();
forgetFromPhotosPlaceNames();
reverseGeocode.mockReset().mockResolvedValue({ name: 'Venezia', address: 'Venezia, Veneto, Italia' });
});
afterAll(async () => {
@@ -231,6 +233,44 @@ describe('JourneyEntriesFromPhotosService.preview', () => {
expect(await refusal(svc.preview(outsider.id, 999_999, {}))).toEqual({ status: 404, error: 'Journey not found' });
expect(reverseGeocode).not.toHaveBeenCalled();
});
it('JRNPHOTOS-SVC-010: a place name found once is not asked again; a failed or empty lookup is', async () => {
const { owner, journey } = await fixture();
await galleryPhoto(journey.id, owner.id, '2026-05-14T07:00:00Z');
await galleryPhoto(journey.id, owner.id, '2026-05-16T07:00:00Z', VERONA);
reverseGeocode.mockImplementation(async (lat) =>
Number(lat) < 45.436 ? { name: 'Venezia', address: null } : { name: null, address: null },
);
await svc.preview(owner.id, journey.id, { lang: 'it' });
expect(reverseGeocode).toHaveBeenCalledTimes(2);
// The gap changed: Venice comes from the cache, Verona (no name the first time) is asked again.
const again = await svc.preview(owner.id, journey.id, { lang: 'it', maxGapMinutes: 60 });
expect(reverseGeocode).toHaveBeenCalledTimes(3);
expect(reverseGeocode).toHaveBeenLastCalledWith(String(VERONA.lat), String(VERONA.lng), 'it', expect.anything());
expect(again.clusters[0]).toMatchObject({ locationName: 'Venezia', titleSource: 'place' });
// Another language is another name.
await svc.preview(owner.id, journey.id, { lang: 'de' });
expect(reverseGeocode).toHaveBeenCalledTimes(5);
reverseGeocode.mockClear().mockRejectedValue(new Error('down'));
forgetFromPhotosPlaceNames();
await svc.preview(owner.id, journey.id, {});
await svc.preview(owner.id, journey.id, {});
expect(reverseGeocode).toHaveBeenCalledTimes(4);
});
it('JRNPHOTOS-SVC-011: a capture time that does not read as one counts with the photos that have none', async () => {
const { owner, journey } = await fixture();
await galleryPhoto(journey.id, owner.id, 'sometime in May');
await galleryPhoto(journey.id, owner.id, '');
const kept = await galleryPhoto(journey.id, owner.id, '2026-05-14 07:00:00', null);
const preview = await svc.preview(owner.id, journey.id, {});
expect(preview.withoutCaptureTime).toBe(2);
expect(preview.clusters).toEqual([expect.objectContaining({ photoIds: [kept], startTime: '07:00' })]);
});
});
describe('JourneyEntriesFromPhotosService.create', () => {