refactor(server): make the place-photo cache a provider (#1833)

The last file in be-places-helpers-fold, and the one that had to be a provider
rather than a move: it carries three in-memory structures that only do their job
if the process has exactly one of them.

  recentFailures  stops a screenful of markers hammering an API that is down
  inFlight        stops a stampede when several requests miss the same placeId
  knownOnDisk     saves an existsSync per cache hit

A second instance gives the stampede guard its own inFlight map, so two
simultaneous requests for the same uncached place both call the provider. That
is why the scheduler takes this one from the container instead of constructing
it: SchedulerDeps gains a placePhotos entry alongside backups, filled from
app.get() in index.ts — the shape PR #1827 was built for.

The module-scope mkdirSync becomes onModuleInit, and GOOGLE_PHOTO_DIR is read
per call through RuntimeEnvService rather than frozen at import. That is not
cosmetic: TREK_PLACE_PHOTO_DIR is the seam the tests use to keep off the real
uploads tree, and its own test used to have to import the module dynamically to
set the variable in time. The __dirname fallback moved a level with the file and
is corrected accordingly.

Consumers: maps, places and share inject it; places.helpers.reclaimPhotoCache
takes it as a parameter, since it is a free function.

Six test seams follow. Four path mocks become injected stubs with the same mock
functions behind them; the collections case keeps the REAL implementation,
because what it asserts is that removeIfUnreferenced counts collection_places as
a reference (#1081) — a stub there would assert nothing. The share e2e overrides
the provider in its container.

services/ is down to 14 top-level files, from 44 when this started.
This commit is contained in:
Maurice
2026-08-07 20:27:19 +02:00
committed by GitHub
parent 4e6b45016a
commit c7fed4b1f8
20 changed files with 419 additions and 309 deletions
+2
View File
@@ -2,6 +2,7 @@ import { Module } from '@nestjs/common';
import { MapsController } from './maps.controller';
import { MapsService } from './maps.service';
import { MapsMcp } from './maps.mcp';
import { PlacePhotosModule } from '../place-photos/place-photos.module';
/**
* Maps / geo domain (L3 leaf module). Registered in AppModule. Exports
@@ -10,6 +11,7 @@ import { MapsMcp } from './maps.mcp';
* Nothing outside the container consumes this domain, so there is no bridge.
*/
@Module({
imports: [PlacePhotosModule],
controllers: [MapsController],
providers: [MapsService, MapsMcp],
exports: [MapsService],
+13 -10
View File
@@ -11,7 +11,7 @@ import { readEnv, getAppUrl } from '../../app-config';
import { safeFetchFollow, SsrfBlockedError } from '../../utils/ssrfGuard';
import { decrypt_api_key } from '../common/crypto/apiKeyCrypto';
// ── Photo cache (disk-backed) ────────────────────────────────────────────────
import * as placePhotoCache from '../../services/placePhotoCache';
import { PlacePhotoCacheService } from '../place-photos/place-photo-cache.service';
import { DatabaseService } from '../database/database.service';
import {
UA,
@@ -238,7 +238,10 @@ type LocationBias = { low: { lat: number; lng: number }; high: { lat: number; ln
*/
@Injectable()
export class MapsService {
constructor(private readonly database: DatabaseService) {}
constructor(
private readonly database: DatabaseService,
private readonly photoCache: PlacePhotoCacheService,
) {}
private isSettingDisabled(key: string): boolean {
const row = this.database.get<{ value: string }>(
@@ -283,7 +286,7 @@ export class MapsService {
}
photoBytesPath(placeId: string): string | null {
return placePhotoCache.serveFilePath(placeId);
return this.photoCache.serveFilePath(placeId);
}
reverse(lat: string, lng: string, lang?: string): Promise<MapsReverseResult> {
@@ -949,7 +952,7 @@ export class MapsService {
name?: string,
): Promise<{ photoUrl: string | null; attribution: string | null }> {
// Disk cache hit — serve immediately, no Google call
const diskHit = placePhotoCache.get(placeId);
const diskHit = this.photoCache.get(placeId);
if (diskHit) return { photoUrl: diskHit.photoUrl, attribution: diskHit.attribution };
// "No photo for this place" is an empty result, not a missing resource: a trip
@@ -960,10 +963,10 @@ export class MapsService {
const noPhoto = { photoUrl: null, attribution: null };
// Recent miss — don't hammer the API
if (placePhotoCache.getErrored(placeId)) return noPhoto;
if (this.photoCache.getErrored(placeId)) return noPhoto;
// Deduplicate concurrent requests for the same placeId
const existing = placePhotoCache.getInFlight(placeId);
const existing = this.photoCache.getInFlight(placeId);
if (existing) {
const result = await existing;
if (!result) return noPhoto;
@@ -997,7 +1000,7 @@ export class MapsService {
return null;
}
const bytes = Buffer.from(await imgRes.arrayBuffer());
const cached = await placePhotoCache.put(placeId, bytes, wiki.attribution);
const cached = await this.photoCache.put(placeId, bytes, wiki.attribution);
return { filePath: cached.filePath, attribution: cached.attribution };
} catch {
providerFailed = true;
@@ -1060,7 +1063,7 @@ export class MapsService {
return null;
}
const cached = await placePhotoCache.put(placeId, bytes, attribution);
const cached = await this.photoCache.put(placeId, bytes, attribution);
// Persist stable proxy URL to database
try {
@@ -1087,14 +1090,14 @@ export class MapsService {
const fallback = await fetchWikimediaFallback();
if (fallback) return fallback;
placePhotoCache.markError(placeId, providerFailed ? 'provider-error' : 'no-photo');
this.photoCache.markError(placeId, providerFailed ? 'provider-error' : 'no-photo');
return null;
} finally {
releasePhotoFetchSlot();
}
})();
placePhotoCache.setInFlight(placeId, fetchPromise);
this.photoCache.setInFlight(placeId, fetchPromise);
const result = await fetchPromise;
if (!result) return noPhoto;