The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.
TypeScript budget-trackercollaborativedockeritinerarymcp-serveroffline-firstopen-sourceopenstreetmappacking-listpwareal-timeself-hostedselfhostedtraveltravel-apptravel-journaltravel-plannertripitwanderlog
/**
* Unit tests for PlacePhotoCacheService — PPC-001 through PPC-014.
* Covers the downscale guard in put(), removeIfUnreferenced(), sweepOrphans(),
* the two negative-cache windows, and the serveKey/get miss handling.
*
* Slice 4: the cache is fully async and addresses storage as
* ('photos-google', '<sha1>.jpg'). The whole suite runs in BOTH registry
* modes — mode A (TREK_PLACE_PHOTO_DIR unset: uploads-local backend,
* 'photos/google/' prefix) and mode B (dir set: place-photos-local backend,
* bare keys) — via the shared stub-registry fixture. The real mode flip is
* pinned by the storage-registry tests; here the two prefixes prove the cache
* itself is mode-agnostic.
*
* Rebuilt on GooglePlacePhotoMetaRepository/PlacesRepository (Plan 3c Task 1)
* and, since Plan 3h Task 6, CollectionPlacesRepository too (PP6's
* `collection_places` half, closing out the Plan 3h carve-out): the legacy
* version cast a hand-rolled 3-table SQLite fixture to `DatabaseService`;
* that cannot survive the service now calling three repositories for its
* owned reads/writes. The suite runs on the migrated snapshot
* (`createSnapshotTestDb()`), wired through `createTestOrm()`, and seeds the
* referencing places and saved places through the ORM factories, which need
* the full rows a hand-rolled table could not give them.
* Plan 4 Task 4 dropped the now-unused `DatabaseService` injection entirely.
*/
import { db as testDb } from '../../../../src/db/database';
import { CollectionPlaces } from '../../../../src/db/entities/CollectionPlaces.entity';
import { GooglePlacePhotoMeta } from '../../../../src/db/entities/GooglePlacePhotoMeta.entity';
import { Places } from '../../../../src/db/entities/Places.entity';
import type { CollectionPlacesRepository } from '../../../../src/db/repositories/CollectionPlaces.repository';
import type { GooglePlacePhotoMetaRepository } from '../../../../src/db/repositories/GooglePlacePhotoMeta.repository';
import type { PlacesRepository } from '../../../../src/db/repositories/Places.repository';
import { PlacePhotoCacheService } from '../../../../src/nest/place-photos/place-photo-cache.service';
import { makeCollection, makeCollectionPlace } from '../../../helpers/factories/collections';
import { makePlace } from '../../../helpers/factories/places';
import { deleteRows, findRow, insertRow, updateRows } from '../../../helpers/factories/rows';
import { makeTrip } from '../../../helpers/factories/trips';
import { makeUser } from '../../../helpers/factories/users';
import { makeStorageFixture, type StorageFixture } from '../../../helpers/storage-fixture';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { Jimp, JimpMime } from 'jimp';
import crypto from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import { describe, it, expect, beforeAll, beforeEach, afterAll, vi } from 'vitest';
vi.mock('../../../../src/db/database', async () => {
const { createSnapshotTestDb, buildDbMock } = await import('../../../helpers/db-mock');
return buildDbMock(createSnapshotTestDb());
});
async function makeJpeg(width: number, height: number): Promise<Buffer> {
const img = new Jimp({ width, height, color: 0xff0000ff });
return img.getBuffer(JimpMime.jpeg, { quality: 80 });
}
function nameFor(placeId: string): string {
return `${crypto.createHash('sha1').update(placeId).digest('hex')}.jpg`;
}
let t: TestOrm;
let metaRepo: GooglePlacePhotoMetaRepository;
let placesRepo: PlacesRepository;
let collectionPlacesRepo: CollectionPlacesRepository;
/** The trip and the collection the referencing rows hang off; the per-case reset leaves both alone. */
let ownerId: number;
let tripId: number;
let collectionId: number;
const referenceByPlace = (overrides: { google_place_id?: string; image_url?: string }) =>
makePlace(t, tripId, overrides);
const referenceByCollectionPlace = (googlePlaceId: string) =>
makeCollectionPlace(t, collectionId, ownerId, { google_place_id: googlePlaceId });
const insertMeta = (placeId: string, attribution: string | null, fetchedAt: number) =>
insertRow(t, GooglePlacePhotoMeta, { place_id: placeId, attribution, fetched_at: fetchedAt });
// Task 1 fix review L3: this is the one suite in this commit that opts out of
// the request-context ratchet (`allowGlobalContext: true`, disabling
// `TrekRepository.validateRequestContext()` for the whole file). Justified,
// not converted: `PlacePhotoCacheService` is constructed directly below
// (`new PlacePhotoCacheService(...)`), never through Nest DI or an HTTP
// request, and every one of its ~20 cases would otherwise need its own
// `withRequestContext(t.orm, ...)` wrapper around a repository call it makes
// several layers deep inside the service (`get`/`put`/`sweepOrphans`/…) — a
// mechanical, high-diff, low-value change to a file this task does not
// otherwise own. The production ratchet (a service booted outside a request
// context throws) is covered elsewhere, by the seams tests
// (`cron-registrar.service.test.ts`, `tests/unit/nest/database/
// request-context.test.ts`) and by `PlacePhotoCacheJob`'s own suite
// (`place-photo-cache.job.test.ts`), which DOES use `allowGlobalContext:
// false` + `CronRegistrarService.runOnBoot`'s `withRequestContext` wrapper
// for the one real entrypoint that reaches this service outside a request.
// Recorded so Tasks 4–8 do not copy this suite's `allowGlobalContext: true`
// into a suite that boots a real app.
beforeAll(async () => {
t = await createTestOrm(testDb, { allowGlobalContext: true });
metaRepo = t.repo(GooglePlacePhotoMeta);
placesRepo = t.repo(Places);
collectionPlacesRepo = t.repo(CollectionPlaces);
ownerId = (await makeUser(t)).user.id;
tripId = (await makeTrip(t, ownerId)).id;
collectionId = (await makeCollection(t, ownerId)).id;
});
afterAll(async () => {
await t.close();
testDb.close();
});
describe.each([
['mode A (photos/google/ prefix)', 'photos/google/'],
['mode B (bare keys)', ''],
])('PlacePhotoCacheService — %s', (_label, keyPrefix) => {
let fx: StorageFixture;
let cache: PlacePhotoCacheService;
const prefixDir = () => path.join(fx.root, ...keyPrefix.split('/').filter(Boolean));
const filePathFor = (placeId: string) => path.join(prefixDir(), nameFor(placeId));
const writeObject = (placeId: string, bytes: Buffer | string) => {
fs.mkdirSync(prefixDir(), { recursive: true });
fs.writeFileSync(filePathFor(placeId), bytes);
};
beforeAll(() => {
fx = makeStorageFixture(keyPrefix);
cache = new PlacePhotoCacheService(fx.storage, metaRepo, placesRepo, collectionPlacesRepo);
});
beforeEach(async () => {
await deleteRows(t, Places);
await deleteRows(t, CollectionPlaces);
await deleteRows(t, GooglePlacePhotoMeta);
t.clear();
for (const f of fs.readdirSync(fx.root)) {
if (f === '.tmp') continue;
fs.rmSync(path.join(fx.root, f), { recursive: true, force: true });
}
});
afterAll(() => {
fx.cleanup();
});
describe('put() downscale guard', () => {
it('PPC-001: downscales an oversized image to <= 800px', async () => {
const big = await makeJpeg(1600, 1200);
await cache.put('big-place', big, 'Alice');
const written = fs.readFileSync(filePathFor('big-place'));
const decoded = await Jimp.read(written);
expect(Math.max(decoded.bitmap.width, decoded.bitmap.height)).toBeLessThanOrEqual(800);
expect(written.length).toBeLessThan(big.length);
});
it('PPC-002: passes a small image through unchanged', async () => {
const small = await makeJpeg(100, 100);
await cache.put('small-place', small, null);
const written = fs.readFileSync(filePathFor('small-place'));
expect(written.equals(small)).toBe(true);
});
it('PPC-003: falls back to original bytes when the input is not a decodable image', async () => {
const garbage = Buffer.from('definitely not an image');
await cache.put('garbage-place', garbage, null);
const written = fs.readFileSync(filePathFor('garbage-place'));
expect(written.equals(garbage)).toBe(true);
});
});
describe('serveKey()', () => {
it('returns the bare <sha1>.jpg storage name when the photo object exists', async () => {
writeObject('p-key', await makeJpeg(10, 10));
expect(await cache.serveKey('p-key')).toBe(nameFor('p-key'));
});
it('returns null when nothing is cached', async () => {
expect(await cache.serveKey('p-missing')).toBeNull();
});
});
describe('get()', () => {
it('PPC-013: purges the meta row and returns null when the object vanished', async () => {
await insertMeta('gone-place', 'Bob', Date.now());
expect(await cache.get('gone-place')).toBeNull();
expect(await findRow(t, GooglePlacePhotoMeta, { place_id: 'gone-place' })).toBeNull();
});
it('PPC-014: returns the proxy URL + attribution for a cached photo', async () => {
await cache.put('hit-place', await makeJpeg(20, 20), 'Carol');
const hit = await cache.get('hit-place');
expect(hit).toEqual({
photoUrl: `/api/maps/place-photo/${encodeURIComponent('hit-place')}/bytes`,
attribution: 'Carol',
});
});
// Task 1 fix review M3 (Plan 3c inventory §18.4, program rule 11):
// PP1 (`this.meta.findLive`) → `await storage.exists(...)` → PP2
// (`this.meta.deleteByPlaceId`) is a non-transactional check-then-act with
// a real `await` in the window — flagged, not fixed. This pins today's
// outcome on a genuine race: two concurrent `get()` calls for a
// never-checked placeId whose storage object is missing.
it("PPC-017 (§18.4 concurrency): two concurrent gets on a row whose storage object is missing both resolve null; the loser's delete is a harmless no-op", async () => {
await insertMeta('race-place', 'Dana', Date.now());
const deleteSpy = vi.spyOn(metaRepo, 'deleteByPlaceId');
try {
const [a, b] = await Promise.all([cache.get('race-place'), cache.get('race-place')]);
// Both requests read the row, both find the storage object missing
// (neither had it in `knownOnDisk` yet), so both resolve null and
// both call deleteByPlaceId — the second is a 0-row DELETE, which
// GPPMREPO-008 already proves does not throw.
expect(a).toBeNull();
expect(b).toBeNull();
expect(deleteSpy).toHaveBeenCalledTimes(2);
expect(deleteSpy).toHaveBeenCalledWith('race-place');
// Exactly one row existed to begin with — gone either way, not double-deleted into an error.
expect(await findRow(t, GooglePlacePhotoMeta, { place_id: 'race-place' })).toBeNull();
} finally {
deleteSpy.mockRestore();
}
});
});
describe('removeIfUnreferenced()', () => {
it('PPC-004: removes a cache entry that no place references', async () => {
await cache.put('orphan', await makeJpeg(50, 50), null);
expect(fs.existsSync(filePathFor('orphan'))).toBe(true);
await cache.removeIfUnreferenced('orphan');
expect(fs.existsSync(filePathFor('orphan'))).toBe(false);
expect(await findRow(t, GooglePlacePhotoMeta, { place_id: 'orphan' })).toBeNull();
});
it('PPC-005: keeps an entry still referenced by google_place_id', async () => {
await cache.put('gid-1', await makeJpeg(50, 50), null);
await referenceByPlace({ google_place_id: 'gid-1' });
await cache.removeIfUnreferenced('gid-1');
expect(fs.existsSync(filePathFor('gid-1'))).toBe(true);
});
it('PPC-006: keeps an entry referenced by a coords proxy URL in image_url', async () => {
const id = 'coords:48.8:2.3';
await cache.put(id, await makeJpeg(50, 50), null);
const proxy = `/api/maps/place-photo/${encodeURIComponent(id)}/bytes`;
await referenceByPlace({ image_url: proxy });
await cache.removeIfUnreferenced(id);
expect(fs.existsSync(filePathFor(id))).toBe(true);
});
// Plan 3c Task 1 PP6 ruling, converted onto CollectionPlacesRepository by
// Plan 3h Task 6: the `collection_places` half only runs when the
// `places` half comes back false — this is the direct proof that half
// is still wired, through the SAME `isReferenced` call as the two above.
it('PPC-016: keeps an entry referenced only through collection_places, proving the repository-backed fallback still fires', async () => {
const id = 'coll-only';
await cache.put(id, await makeJpeg(50, 50), null);
await referenceByCollectionPlace(id);
await cache.removeIfUnreferenced(id);
expect(fs.existsSync(filePathFor(id))).toBe(true);
});
});
describe('sweepOrphans()', () => {
it('PPC-007: removes orphaned meta rows + files, keeps referenced ones, deletes stray files', async () => {
await cache.put('keep-gid', await makeJpeg(50, 50), null);
await cache.put('drop-me', await makeJpeg(50, 50), null);
await referenceByPlace({ google_place_id: 'keep-gid' });
// A stray .jpg on disk with no meta row (e.g. a crash between write and upsert).
const strayPath = path.join(prefixDir(), 'deadbeef'.padEnd(40, '0') + '.jpg');
fs.writeFileSync(strayPath, 'stray');
const removed = await cache.sweepOrphans();
expect(fs.existsSync(filePathFor('keep-gid'))).toBe(true);
expect(fs.existsSync(filePathFor('drop-me'))).toBe(false);
expect(fs.existsSync(strayPath)).toBe(false);
expect(await findRow(t, GooglePlacePhotoMeta, { place_id: 'drop-me' })).toBeNull();
expect(await findRow(t, GooglePlacePhotoMeta, { place_id: 'keep-gid' })).not.toBeNull();
expect(removed).toBe(2); // drop-me (orphan meta+file) + stray file
});
it('PPC-008: returns 0 when every entry is referenced', async () => {
await cache.put('ref-a', await makeJpeg(50, 50), null);
await referenceByPlace({ google_place_id: 'ref-a' });
expect(await cache.sweepOrphans()).toBe(0);
expect(fs.existsSync(filePathFor('ref-a'))).toBe(true);
});
it('PPC-015: never touches nested entries or non-jpg files (readdir parity — list() recurses)', async () => {
const nestedDir = path.join(prefixDir(), 'sub');
fs.mkdirSync(nestedDir, { recursive: true });
const nested = path.join(nestedDir, 'nested.jpg');
fs.writeFileSync(nested, 'nested');
const note = path.join(prefixDir(), 'note.txt');
fs.writeFileSync(note, 'not a photo');
const removed = await cache.sweepOrphans();
expect(fs.existsSync(nested)).toBe(true);
expect(fs.existsSync(note)).toBe(true);
expect(removed).toBe(0);
});
});
describe('negative cache', () => {
async function ageError(placeId: string, ms: number): Promise<void> {
await updateRows(t, GooglePlacePhotoMeta, { place_id: placeId }, { error_at: Date.now() - ms });
}
it('PPC-009: a place with no photo stays remembered well past the old five-minute window', async () => {
await cache.markError('photo-less');
await ageError('photo-less', 30 * 60 * 1000);
expect(await cache.getErrored('photo-less')).toBe(true);
await ageError('photo-less', 5 * 60 * 60 * 1000);
expect(await cache.getErrored('photo-less')).toBe(true);
});
it('PPC-010: the miss expires once it is a day old', async () => {
await cache.markError('stale-miss');
await ageError('stale-miss', 24 * 60 * 60 * 1000);
expect(await cache.getErrored('stale-miss')).toBe(false);
});
// A failed provider call says nothing about the place, so it must not inherit the
// long window a real "this place has no photo" answer gets.
it('PPC-011: a failed provider call is forgotten after minutes and never persisted', async () => {
vi.useFakeTimers();
try {
await cache.markError('flaky', 'provider-error');
expect(await cache.getErrored('flaky')).toBe(true);
// Nothing on disk — a restart retries instead of inheriting someone's outage.
expect(await findRow(t, GooglePlacePhotoMeta, { place_id: 'flaky' })).toBeNull();
vi.advanceTimersByTime(5 * 60 * 1000);
expect(await cache.getErrored('flaky')).toBe(false);
// The long window belongs to the other case: same age, still remembered.
await cache.markError('photo-less-too');
await ageError('photo-less-too', 5 * 60 * 1000);
expect(await cache.getErrored('photo-less-too')).toBe(true);
} finally {
vi.useRealTimers();
}
});
it('PPC-012: a cached photo clears an earlier failed attempt', async () => {
await cache.markError('recovered', 'provider-error');
expect(await cache.getErrored('recovered')).toBe(true);
await cache.put('recovered', await makeJpeg(40, 40), null);
expect(await cache.getErrored('recovered')).toBe(false);
});
});
});