refactor(place-photos): route place-photo cache through storage

This commit is contained in:
jubnl
2026-08-17 05:20:09 +02:00
parent d27e54952a
commit 4eca78b53e
28 changed files with 430 additions and 365 deletions
+1 -1
View File
@@ -171,7 +171,7 @@ export class MapsController {
@Get('place-photo/:placeId/bytes')
async placePhotoBytes(@Param('placeId') placeId: string, @Res() res: Response): Promise<void> {
const key = this.maps.photoBytesKey(placeId);
const key = await this.maps.photoBytesKey(placeId);
if (!key) {
// Same reasoning as the JSON endpoint above, and the bigger half of #1727:
// places keep this URL in image_url, so a trip render asks for one photo per
+7 -7
View File
@@ -529,7 +529,7 @@ export class MapsService {
return this.getPlacePhoto(userId, placeId, lat, lng, name) as Promise<MapsPlacePhotoResult>;
}
photoBytesKey(placeId: string): string | null {
photoBytesKey(placeId: string): Promise<string | null> {
return this.photoCache.serveKey(placeId);
}
@@ -1802,7 +1802,7 @@ export class MapsService {
name?: string,
): Promise<{ photoUrl: string | null; attribution: string | null }> {
// Disk cache hit — serve immediately, no Google call
const diskHit = this.photoCache.get(placeId);
const diskHit = await 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
@@ -1828,7 +1828,7 @@ export class MapsService {
// or timed out only for a few minutes.
let providerFailed = false;
const fetchPromise = (async (): Promise<{ filePath: string; attribution: string | null } | null> => {
const fetchPromise = (async (): Promise<{ attribution: string | null } | null> => {
await acquirePhotoFetchSlot();
try {
const apiKey = this.getMapsKey(userId);
@@ -1837,7 +1837,7 @@ export class MapsService {
// (right-click) places and as a fallback when a Google place yields no photo,
// so a place added via search still gets a marker image when Google returns
// nothing. Returns null (without marking an error) so the caller decides.
const fetchWikimediaFallback = async (): Promise<{ filePath: string; attribution: string | null } | null> => {
const fetchWikimediaFallback = async (): Promise<{ attribution: string | null } | null> => {
if (isNaN(lat) || isNaN(lng)) return null;
try {
const wiki = await this.fetchWikimediaPhoto(lat, lng, name);
@@ -1851,7 +1851,7 @@ export class MapsService {
}
const bytes = Buffer.from(await imgRes.arrayBuffer());
const cached = await this.photoCache.put(placeId, bytes, wiki.attribution);
return { filePath: cached.filePath, attribution: cached.attribution };
return { attribution: cached.attribution };
} catch {
providerFailed = true;
return null;
@@ -1862,7 +1862,7 @@ export class MapsService {
// key, request rejected, no photos, or a failed media download — so the
// caller can fall back to Wikimedia; the misses that were Google's fault
// flag providerFailed on the way out.
const fetchGooglePhoto = async (): Promise<{ filePath: string; attribution: string | null } | null> => {
const fetchGooglePhoto = async (): Promise<{ attribution: string | null } | null> => {
if (!apiKey) return null;
// Fetch details to get the photo name
@@ -1926,7 +1926,7 @@ export class MapsService {
console.error('Failed to persist photo URL to database:', dbErr);
}
return { filePath: cached.filePath, attribution };
return { attribution };
};
// Prefer the Google photo (higher quality); if Google yields nothing, fall
@@ -60,7 +60,7 @@ export class PlaceEnrichmentController {
* local — no provider is contacted, so it needs no rate limit.
*/
@Get('credit/:key')
credit(@Param('key') key: string): { credit: string | null } {
credit(@Param('key') key: string): Promise<{ credit: string | null }> {
return this.enrichment.credit(key);
}
}
@@ -269,7 +269,7 @@ export class PlaceEnrichmentService {
const placeId = req.placeId?.trim() || `coords:${req.lat}:${req.lng}`;
const lang = req.lang;
const cached = this.readCache(placeId, lang);
const cached = await this.readCache(placeId, lang);
if (cached) return cached;
// One details lookup feeds all three halves: the pictures need its Commons
@@ -318,8 +318,8 @@ export class PlaceEnrichmentService {
* obligation does not end there — the place inspector reads this so a picture
* that was chosen weeks ago still names whoever made it.
*/
credit(key: string): { credit: string | null } {
return { credit: this.photoCache.get(key)?.attribution ?? null };
async credit(key: string): Promise<{ credit: string | null }> {
return { credit: (await this.photoCache.get(key))?.attribution ?? null };
}
/**
@@ -492,7 +492,7 @@ export class PlaceEnrichmentService {
credit: string | null,
fetchBytes: () => Promise<Buffer | null>,
): Promise<string | null> {
const hit = this.photoCache.get(key);
const hit = await this.photoCache.get(key);
if (hit) return hit.photoUrl;
const bytes = await withPhotoFetchSlot(fetchBytes);
@@ -662,7 +662,7 @@ export class PlaceEnrichmentService {
// ── Result cache ───────────────────────────────────────────────────────────
private readCache(placeId: string, lang: string | undefined): CachedEnrichment | null {
private async readCache(placeId: string, lang: string | undefined): Promise<CachedEnrichment | null> {
try {
const row = this.database.get<{ payload_json: string; fetched_at: number }>(
'SELECT payload_json, fetched_at FROM place_details_cache WHERE place_id = ? AND lang = ? AND expanded = ?',
@@ -679,7 +679,8 @@ export class PlaceEnrichmentService {
// them. Treat any loss as a stale entry and rebuild, rather than serving
// the survivors: filtering alone would leave the column empty for the rest
// of the week for a place that has pictures perfectly available.
const photos = parsed.photos.filter((photo) => this.photoCache.get(photo.key));
const checks = await Promise.all(parsed.photos.map((photo) => this.photoCache.get(photo.key)));
const photos = parsed.photos.filter((_, i) => checks[i]);
if (photos.length !== parsed.photos.length) return null;
const value: CachedEnrichment = {
@@ -20,13 +20,15 @@ export class PlacePhotoCacheJob implements OnApplicationBootstrap {
onApplicationBootstrap(): void {
if (!this.registrar.isEnabled()) return;
// Run once on startup to reclaim orphans left over from before this sweeper existed.
this.sweep();
this.registrar.register('place-photo-cache', '30 3 * * *', () => this.sweep());
void this.sweep();
this.registrar.register('place-photo-cache', '30 3 * * *', () => {
void this.sweep();
});
}
sweep(): void {
async sweep(): Promise<void> {
try {
const removed = this.cache.sweepOrphans();
const removed = await this.cache.sweepOrphans();
if (removed > 0) logInfo(`Place-photo cache cleanup: removed ${removed} orphaned file(s)/row(s)`);
} catch (err: unknown) {
logError(`Place-photo cache cleanup: ${err instanceof Error ? err.message : err}`);
@@ -1,11 +1,9 @@
import { Injectable, OnModuleInit } from '@nestjs/common';
import { Injectable } from '@nestjs/common';
import { Jimp, JimpMime } from 'jimp';
import crypto from 'node:crypto';
import fs from 'node:fs';
import fsPromises from 'node:fs/promises';
import path from 'node:path';
import { Readable } from 'node:stream';
import { DatabaseService } from '../database/database.service';
import { RuntimeEnvService } from '../app-config/runtime-env.service';
import { StorageService } from '../storage/storage.service';
// How long a "no photo for this place" answer stays remembered. Nothing about it
// changes until a photo appears upstream, so it is worth keeping: without it every
@@ -31,7 +29,6 @@ const JPEG_QUALITY = 80;
interface CachedPhoto {
photoUrl: string;
filePath: string;
attribution: string | null;
}
@@ -44,39 +41,26 @@ interface CachedPhoto {
* simultaneous requests for the same uncached place would both call the
* provider. That is the reason the nightly sweep (PlacePhotoCacheJob) injects
* this container singleton rather than constructing its own.
*
* Bytes live in the 'photos-google' storage category as '<sha1>.jpg' names.
* The registry's mode-aware prefix reproduces both TREK_PLACE_PHOTO_DIR
* layouts (unset: uploads/photos/google; set: that dir, bare keys), so the
* cache itself is mode-agnostic.
*/
@Injectable()
export class PlacePhotoCacheService implements OnModuleInit {
export class PlacePhotoCacheService {
/** Provider calls that failed recently — in memory only, so a restart retries. */
private readonly recentFailures = new Map<string, number>();
/** In-flight dedup: stops a stampede when several requests miss the same placeId at once. */
private readonly inFlight = new Map<string, Promise<{ filePath: string; attribution: string | null } | null>>();
/** placeIds whose file was confirmed on disk this session — saves an existsSync per hit. */
private readonly inFlight = new Map<string, Promise<{ attribution: string | null } | null>>();
/** placeIds whose object was confirmed in storage this session — saves a stat per hit. */
private readonly knownOnDisk = new Set<string>();
constructor(
private readonly db: DatabaseService,
private readonly env: RuntimeEnvService,
private readonly storage: StorageService,
) {}
/**
* Overridable for tests (mirrors the TREK_DB_FILE seam) so the suite never
* touches the real uploads tree. Read per call rather than frozen at import:
* the tests that set TREK_PLACE_PHOTO_DIR do so after this module loads.
*/
private get photoDir(): string {
return this.env.env().paths.placePhotoDir || path.join(__dirname, '../../../uploads/photos/google');
}
/** Ensure the upload dir exists once at startup, so put() never needs a sync FS call. */
onModuleInit(): void {
try {
fs.mkdirSync(this.photoDir, { recursive: true });
} catch {
/* already exists */
}
}
private fileName(placeId: string): string {
// Hash to avoid filename collisions — coords:lat:lng pseudo-IDs contain characters that
// collapse identically under sanitization (e.g. ':' and '.' both → '_')
@@ -84,15 +68,11 @@ export class PlacePhotoCacheService implements OnModuleInit {
return `${hash}.jpg`;
}
private filePath(placeId: string): string {
return path.join(this.photoDir, this.fileName(placeId));
}
private proxyUrl(placeId: string): string {
return `/api/maps/place-photo/${encodeURIComponent(placeId)}/bytes`;
}
get(placeId: string): CachedPhoto | null {
async get(placeId: string): Promise<CachedPhoto | null> {
const row = this.db.get<{ attribution: string | null }>(
'SELECT attribution FROM google_place_photo_meta WHERE place_id = ? AND error_at IS NULL',
placeId,
@@ -100,19 +80,17 @@ export class PlacePhotoCacheService implements OnModuleInit {
if (!row) return null;
const fp = this.filePath(placeId);
if (!this.knownOnDisk.has(placeId)) {
// First time this placeId is checked this session — verify the file exists on disk.
// First time this placeId is checked this session — verify the object exists.
// (Guards against volume wipes or manual deletion between server restarts.)
if (!fs.existsSync(fp)) {
if (!(await this.storage.exists('photos-google', this.fileName(placeId)))) {
this.db.run('DELETE FROM google_place_photo_meta WHERE place_id = ?', placeId);
return null;
}
this.knownOnDisk.add(placeId);
}
return { photoUrl: this.proxyUrl(placeId), filePath: fp, attribution: row.attribution };
return { photoUrl: this.proxyUrl(placeId), attribution: row.attribution };
}
getErrored(placeId: string): boolean {
@@ -174,12 +152,8 @@ export class PlacePhotoCacheService implements OnModuleInit {
}
async put(placeId: string, bytes: Buffer, attribution: string | null): Promise<CachedPhoto> {
const fp = this.filePath(placeId);
const tmp = fp + '.tmp';
const resized = await this.downscale(bytes);
await fsPromises.writeFile(tmp, resized);
await fsPromises.rename(tmp, fp);
await this.storage.put('photos-google', this.fileName(placeId), Readable.from(resized));
this.knownOnDisk.add(placeId);
this.recentFailures.delete(placeId);
@@ -189,19 +163,14 @@ export class PlacePhotoCacheService implements OnModuleInit {
placeId, attribution, Date.now(),
);
return { photoUrl: this.proxyUrl(placeId), filePath: fp, attribution };
return { photoUrl: this.proxyUrl(placeId), attribution };
}
getInFlight(
placeId: string,
): Promise<{ filePath: string; attribution: string | null } | null> | undefined {
getInFlight(placeId: string): Promise<{ attribution: string | null } | null> | undefined {
return this.inFlight.get(placeId);
}
setInFlight(
placeId: string,
promise: Promise<{ filePath: string; attribution: string | null } | null>,
): void {
setInFlight(placeId: string, promise: Promise<{ attribution: string | null } | null>): void {
this.inFlight.set(placeId, promise);
promise
.finally(() => this.inFlight.delete(placeId))
@@ -210,22 +179,16 @@ export class PlacePhotoCacheService implements OnModuleInit {
});
}
serveFilePath(placeId: string): string | null {
if (this.knownOnDisk.has(placeId)) return this.filePath(placeId);
const fp = this.filePath(placeId);
if (!fs.existsSync(fp)) return null;
this.knownOnDisk.add(placeId);
return fp;
}
/**
* Storage name (category 'photos-google') for a cached photo, or null when
* not on disk. The registry's mode-aware prefix reproduces photoDir in both
* TREK_PLACE_PHOTO_DIR modes; the cache's own disk internals move onto
* storage in slice 4.
* the object is missing.
*/
serveKey(placeId: string): string | null {
return this.serveFilePath(placeId) ? this.fileName(placeId) : null;
async serveKey(placeId: string): Promise<string | null> {
const name = this.fileName(placeId);
if (this.knownOnDisk.has(placeId)) return name;
if (!(await this.storage.exists('photos-google', name))) return null;
this.knownOnDisk.add(placeId);
return name;
}
/**
@@ -249,12 +212,10 @@ export class PlacePhotoCacheService implements OnModuleInit {
return !!row;
}
private deleteEntry(placeId: string): void {
try {
fs.unlinkSync(this.filePath(placeId));
} catch {
private async deleteEntry(placeId: string): Promise<void> {
await this.storage.delete('photos-google', this.fileName(placeId)).catch(() => {
/* already gone */
}
});
this.db.run('DELETE FROM google_place_photo_meta WHERE place_id = ?', placeId);
this.knownOnDisk.delete(placeId);
}
@@ -263,41 +224,37 @@ export class PlacePhotoCacheService implements OnModuleInit {
* Drop a cache entry if no place references it anymore. Called after a place delete
* for prompt reclamation; the nightly sweep is the catch-all for every other path.
*/
removeIfUnreferenced(placeId: string): void {
async removeIfUnreferenced(placeId: string): Promise<void> {
if (this.isReferenced(placeId)) return;
this.deleteEntry(placeId);
await this.deleteEntry(placeId);
}
/**
* Reclaim orphaned cache files + meta rows. Runs on startup and nightly (scheduler).
* Two passes: (1) meta rows no place references; (2) stray .jpg files with no meta row.
* Two passes: (1) meta rows no place references; (2) stray .jpg objects with no meta row.
*/
sweepOrphans(): number {
async sweepOrphans(): Promise<number> {
let removed = 0;
const rows = this.db.all<{ place_id: string }>('SELECT place_id FROM google_place_photo_meta');
const keepFiles = new Set<string>();
for (const { place_id } of rows) {
if (this.isReferenced(place_id)) {
keepFiles.add(`${crypto.createHash('sha1').update(place_id).digest('hex')}.jpg`);
keepFiles.add(this.fileName(place_id));
} else {
this.deleteEntry(place_id);
await this.deleteEntry(place_id);
removed++;
}
}
// Pass 2: files on disk that no surviving meta row maps to (e.g. left over from a
// crash between writeFile and the DB upsert, or a meta row deleted out-of-band).
let entries: string[];
try {
entries = fs.readdirSync(this.photoDir);
} catch {
entries = [];
}
for (const entry of entries) {
if (!entry.endsWith('.jpg') || keepFiles.has(entry)) continue;
// Pass 2: objects that no surviving meta row maps to (e.g. left over from a
// crash between the object write and the DB upsert, or a meta row deleted
// out-of-band). list() recurses where the old readdirSync didn't — skip
// nested keys so a subdirectory of a relocated cache dir is never swept.
for await (const stat of this.storage.list('photos-google')) {
if (stat.key.includes('/') || !stat.key.endsWith('.jpg') || keepFiles.has(stat.key)) continue;
try {
fs.unlinkSync(path.join(this.photoDir, entry));
await this.storage.delete('photos-google', stat.key);
removed++;
} catch {
/* race */
@@ -3,6 +3,7 @@ import { PlacePhotoCacheService } from './place-photo-cache.service';
import { PlacePhotoCacheJob } from './place-photo-cache.job';
import { AppConfigModule } from '../app-config/app-config.module';
import { SchedulingModule } from '../scheduling/scheduling.module';
import { StorageModule } from '../storage/storage.module';
/** The marker-photo cache. No controller of its own — maps serves the bytes,
* places and share read through it, and PlacePhotoCacheJob sweeps it nightly.
@@ -11,7 +12,7 @@ import { SchedulingModule } from '../scheduling/scheduling.module';
* imported explicitly because @Global only reaches modules that are in the
* graph — which a single-domain e2e TestingModule is not. */
@Module({
imports: [AppConfigModule, SchedulingModule],
imports: [AppConfigModule, SchedulingModule, StorageModule],
providers: [PlacePhotoCacheService, PlacePhotoCacheJob],
exports: [PlacePhotoCacheService],
})
+4 -4
View File
@@ -272,7 +272,7 @@ export class PlacesController {
@Post('bulk-delete')
@HttpCode(200) // Express answers bulk-delete with res.json (200), unlike the 201 imports.
bulkDelete(
async bulkDelete(
@CurrentUser() user: User,
@Param('tripId') tripId: string,
@Body() body: PlaceBulkDeleteDto,
@@ -293,7 +293,7 @@ export class PlacesController {
for (const id of scoped) this.places.onDeleted(id);
// Read the linked expenses before the delete — afterwards the link is gone (#1298).
const expenseIds = this.places.linkedExpenseIds(tripId, scoped);
const deleted = this.places.removeMany(tripId, ids);
const deleted = await this.places.removeMany(tripId, ids);
for (const id of deleted) {
this.places.broadcast(tripId, 'place:deleted', { placeId: id }, socketId);
}
@@ -452,7 +452,7 @@ export class PlacesController {
@Delete(':id')
@UseGuards(TripAccessGuard)
@RequirePermission('place_edit')
remove(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string, @Headers('x-socket-id') socketId?: string) {
async remove(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string, @Headers('x-socket-id') socketId?: string) {
// Scope the id to the trip before the hook (see bulkDelete), then sync the
// journey ahead of the actual delete.
if (!this.places.get(tripId, id)) {
@@ -460,7 +460,7 @@ export class PlacesController {
}
this.places.onDeleted(Number(id));
const expenseIds = this.places.linkedExpenseIds(tripId, [id]);
if (!this.places.remove(tripId, id)) {
if (!(await this.places.remove(tripId, id))) {
throw new HttpException({ error: 'Place not found' }, 404);
}
this.places.broadcast(tripId, 'place:deleted', { placeId: Number(id) }, socketId);
+2 -2
View File
@@ -101,13 +101,13 @@ export interface KmlImportOptions {
// Reclaim a deleted place's cached marker photo if nothing else references it.
// The cache key is the Google place_id, or — for coordinate-only places — the
// pseudo-id embedded in the stored proxy URL (/api/maps/place-photo/{id}/bytes).
export function reclaimPhotoCache(cache: PlacePhotoCacheService, googlePlaceId: string | null, imageUrl: string | null): void {
export async function reclaimPhotoCache(cache: PlacePhotoCacheService, googlePlaceId: string | null, imageUrl: string | null): Promise<void> {
const candidates = new Set<string>();
if (googlePlaceId) candidates.add(googlePlaceId);
const m = imageUrl?.match(/^\/api\/maps\/place-photo\/(.+)\/bytes$/);
if (m) { try { candidates.add(decodeURIComponent(m[1])); } catch { /* malformed url */ } }
for (const id of candidates) {
try { cache.removeIfUnreferenced(id); } catch { /* best-effort */ }
try { await cache.removeIfUnreferenced(id); } catch { /* best-effort */ }
}
}
+2 -2
View File
@@ -234,7 +234,7 @@ export class PlacesMcp {
try { this.journey.onPlaceDeleted(placeId); } catch { /* non-fatal */ } // sync journeys before the row is gone
// The link is gone once the place is, so read it first (#1298).
const expenseIds = this.places.linkedExpenseIds(tripId, [placeId]);
const deleted = this.places.remove(String(tripId), String(placeId));
const deleted = await this.places.remove(String(tripId), String(placeId));
if (!deleted) return { content: [{ type: 'text' as const, text: 'Place not found.' }], isError: true };
this.guards.safeBroadcast(tripId, 'place:deleted', { placeId });
for (const itemId of expenseIds) this.guards.safeBroadcast(tripId, 'budget:deleted', { itemId });
@@ -346,7 +346,7 @@ export class PlacesMcp {
}
// The link is gone once the places are, so read it first (#1298).
const expenseIds = this.places.linkedExpenseIds(tripId, scoped);
const deleted = this.places.removeMany(String(tripId), placeIds);
const deleted = await this.places.removeMany(String(tripId), placeIds);
for (const id of deleted) this.guards.safeBroadcast(tripId, 'place:deleted', { placeId: id });
for (const itemId of expenseIds) this.guards.safeBroadcast(tripId, 'budget:deleted', { itemId });
return ok({ deleted, count: deleted.length });
+4 -4
View File
@@ -357,7 +357,7 @@ export class PlacesService {
return rows.map(r => r.id);
}
remove(tripId: string, placeId: string): boolean {
async remove(tripId: string, placeId: string): Promise<boolean> {
const place = this.dbs.get<{ google_place_id: string | null; image_url: string | null }>(
'SELECT google_place_id, image_url FROM places WHERE id = ? AND trip_id = ?', placeId, tripId,
);
@@ -369,12 +369,12 @@ export class PlacesService {
this.dbs.run('DELETE FROM budget_items WHERE trip_id = ? AND place_id = ?', tripId, placeId);
this.dbs.run('DELETE FROM places WHERE id = ?', placeId);
});
reclaimPhotoCache(this.photoCache, place.google_place_id, place.image_url);
await reclaimPhotoCache(this.photoCache, place.google_place_id, place.image_url);
reclaimPlaceImage(place.image_url);
return true;
}
removeMany(tripId: string, ids: number[]): number[] {
async removeMany(tripId: string, ids: number[]): Promise<number[]> {
if (ids.length === 0) return [];
const selectStmt = this.dbs.prepare('SELECT google_place_id, image_url FROM places WHERE id = ? AND trip_id = ?');
const deleteStmt = this.dbs.prepare('DELETE FROM places WHERE id = ?');
@@ -393,7 +393,7 @@ export class PlacesService {
});
// Reclaim after the transaction commits so isReferenced() sees the final place set.
for (const row of reclaimable) {
reclaimPhotoCache(this.photoCache, row.google_place_id, row.image_url);
await reclaimPhotoCache(this.photoCache, row.google_place_id, row.image_url);
reclaimPlaceImage(row.image_url);
}
return deleted;
+1 -1
View File
@@ -97,7 +97,7 @@ export class SharedController {
*/
@Get(':token/place-photo/:placeId/bytes')
async placePhotoBytes(@Param('token') token: string, @Param('placeId') placeId: string, @Res() res: Response): Promise<void> {
const key = this.share.getSharedPlacePhotoKey(token, placeId);
const key = await this.share.getSharedPlacePhotoKey(token, placeId);
if (!key) {
this.emptyPhoto(res);
return;
+1 -1
View File
@@ -305,7 +305,7 @@ export class ShareService {
* Returns null — never throws — so the caller answers a plain miss,
* mirroring the authenticated bytes endpoint.
*/
getSharedPlacePhotoKey(token: string, placeId: string): string | null {
async getSharedPlacePhotoKey(token: string, placeId: string): Promise<string | null> {
const shareRow = this.dbs.get<{ trip_id: string; share_map: number }>(
"SELECT trip_id, share_map FROM share_tokens WHERE token = ? AND (expires_at IS NULL OR expires_at > datetime('now'))",
token,