mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-05 02:14:05 +00:00
fix(maps): stop the photo endpoint answering 404 for photo-less places (#1727)
Opening one trip fires a 404 per place without a photo, 30 to 60 of them from one IP in seconds. CrowdSec and fail2ban read that as scanning; the reporter had three users banned within five minutes. A place having no photo is not an error and no longer answers as one. OSM places were also sent to Google as node:/way:/relation: ids, which can only return 400 INVALID_ARGUMENT — a billed round-trip and about 1.3s per place. getPlacePhoto already guarded coords: this way; the OSM prefixes now get the same treatment, as does getPlaceDetailsExpanded, which had no guard. The negative cache separates a place having no photo from a failed provider call instead of expiring both after five minutes and replaying the storm.
This commit is contained in:
@@ -265,17 +265,45 @@ describe('Maps happy paths (mocked service)', () => {
|
||||
it('MAPS-004 — getPlacePhoto error with status returns that status', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
vi.mocked(mapsService.getPlacePhoto).mockRejectedValueOnce(
|
||||
Object.assign(new Error('Photo not found'), { status: 404 })
|
||||
Object.assign(new Error('Photo provider unavailable'), { status: 503 })
|
||||
);
|
||||
|
||||
const res = await request(app)
|
||||
.get('/api/maps/place-photo/some-place-id?lat=48.8&lng=2.3')
|
||||
.set('Cookie', authCookie(user.id));
|
||||
|
||||
expect(res.status).toBe(404);
|
||||
expect(res.status).toBe(503);
|
||||
expect(res.body).toHaveProperty('error');
|
||||
});
|
||||
|
||||
// A photo-less place must answer 200 { photoUrl: null }: one 404 per place turns
|
||||
// a normal itinerary render into a 404 storm that fail2ban/CrowdSec bans (#1727).
|
||||
it('MAPS-004b — a place with no photo answers 200 with photoUrl null', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
vi.mocked(mapsService.getPlacePhoto).mockResolvedValueOnce({ photoUrl: null, attribution: null });
|
||||
|
||||
const res = await request(app)
|
||||
.get('/api/maps/place-photo/node%3A5255005321?lat=36.76&lng=-3.84&name=Nerja')
|
||||
.set('Cookie', authCookie(user.id));
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ photoUrl: null, attribution: null });
|
||||
});
|
||||
|
||||
// Places keep the bytes URL in image_url, so an evicted cache entry means one
|
||||
// request per place on the next trip render — the second half of the same ban
|
||||
// vector. Nothing to serve is an empty 204, not a 404.
|
||||
it('MAPS-004c — the bytes proxy answers 204 for a photo that is not cached', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
|
||||
const res = await request(app)
|
||||
.get('/api/maps/place-photo/ChIJnot-cached/bytes')
|
||||
.set('Cookie', authCookie(user.id));
|
||||
|
||||
expect(res.status).toBe(204);
|
||||
expect(res.text).toBeFalsy();
|
||||
});
|
||||
|
||||
it('MAPS-005 — reverseGeocode error returns null values', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
vi.mocked(mapsService.reverseGeocode).mockRejectedValueOnce(new Error('Geocode failed'));
|
||||
|
||||
@@ -210,12 +210,20 @@ describe('MapsController (parity with the legacy /api/maps route)', () => {
|
||||
});
|
||||
|
||||
it('maps a 4xx service error', async () => {
|
||||
const photo = vi.fn().mockRejectedValue(withError(404, 'No photo available'));
|
||||
const photo = vi.fn().mockRejectedValue(withError(429, 'Rate limited'));
|
||||
expect(await thrown(() => makeController({ photosDisabled: () => false, photo }).placePhoto(user, 'p1', '1', '2'))).toEqual({
|
||||
status: 404, body: { error: 'No photo available' },
|
||||
status: 429, body: { error: 'Rate limited' },
|
||||
});
|
||||
});
|
||||
|
||||
// A place without a photo is an empty result, not a 404 — one 404 per photo-less
|
||||
// place gets the user banned by any 404-rate IPS in front of TREK (#1727).
|
||||
it('passes a photo-less place through as a 200 with photoUrl null', async () => {
|
||||
const photo = vi.fn().mockResolvedValue({ photoUrl: null, attribution: null });
|
||||
const res = await makeController({ photosDisabled: () => false, photo }).placePhoto(user, 'node:123', '1', '2');
|
||||
expect(res).toEqual({ photoUrl: null, attribution: null });
|
||||
});
|
||||
|
||||
it('logs and maps a 5xx service error', async () => {
|
||||
const photo = vi.fn().mockRejectedValue(withError(502, 'Upstream failed'));
|
||||
expect(await thrown(() => makeController({ photosDisabled: () => false, photo }).placePhoto(user, 'p1', '1', '2'))).toEqual({
|
||||
@@ -244,17 +252,22 @@ describe('MapsController (parity with the legacy /api/maps route)', () => {
|
||||
json: vi.fn(),
|
||||
set: vi.fn(),
|
||||
type: vi.fn(),
|
||||
end: vi.fn(),
|
||||
};
|
||||
return res as unknown as Response & { status: ReturnType<typeof vi.fn>; json: ReturnType<typeof vi.fn>; set: ReturnType<typeof vi.fn>; type: ReturnType<typeof vi.fn> };
|
||||
return res as unknown as Response & { status: ReturnType<typeof vi.fn>; json: ReturnType<typeof vi.fn>; set: ReturnType<typeof vi.fn>; type: ReturnType<typeof vi.fn>; end: ReturnType<typeof vi.fn> };
|
||||
}
|
||||
|
||||
beforeEach(() => createReadStream.mockReset());
|
||||
|
||||
it('404 when the photo is not cached', () => {
|
||||
// Places persist this URL in image_url, so an evicted cache entry means one
|
||||
// request per place on a trip render. 404 for each of them is the ban vector
|
||||
// from #1727 — an uncached photo answers 204 with an empty body instead.
|
||||
it('204 without a body when the photo is not cached', () => {
|
||||
const res = makeRes();
|
||||
makeController({ photoBytesPath: () => null }).placePhotoBytes('p1', res);
|
||||
expect(res.status).toHaveBeenCalledWith(404);
|
||||
expect(res.json).toHaveBeenCalledWith({ error: 'Photo not cached' });
|
||||
expect(res.status).toHaveBeenCalledWith(204);
|
||||
expect(res.end).toHaveBeenCalled();
|
||||
expect(res.json).not.toHaveBeenCalled();
|
||||
expect(createReadStream).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -269,18 +282,22 @@ describe('MapsController (parity with the legacy /api/maps route)', () => {
|
||||
expect(stream.pipe).toHaveBeenCalledWith(res);
|
||||
});
|
||||
|
||||
it('falls back to 404 when the read stream errors', () => {
|
||||
it('falls back to an empty 204 when the read stream errors', () => {
|
||||
let onError: () => void = () => {};
|
||||
const stream = { on: vi.fn((ev: string, cb: () => void) => { if (ev === 'error') onError = cb; return stream; }), pipe: vi.fn() };
|
||||
createReadStream.mockReturnValue(stream);
|
||||
const res = makeRes();
|
||||
makeController({ photoBytesPath: () => '/cache/p1.jpg' }).placePhotoBytes('p1', res);
|
||||
onError();
|
||||
expect(res.status).toHaveBeenCalledWith(404);
|
||||
expect(res.json).toHaveBeenCalledWith({ error: 'Photo not cached' });
|
||||
expect(res.status).toHaveBeenCalledWith(204);
|
||||
expect(res.end).toHaveBeenCalled();
|
||||
// The hit path already asked for a month of immutable caching — that header
|
||||
// must not survive onto the empty answer, or the photo stays hidden once it
|
||||
// is back in the cache.
|
||||
expect(res.set).toHaveBeenLastCalledWith('Cache-Control', 'no-store');
|
||||
});
|
||||
|
||||
it('does not re-send a 404 when the stream errors after headers were flushed', () => {
|
||||
it('does not re-send a 204 when the stream errors after headers were flushed', () => {
|
||||
let onError: () => void = () => {};
|
||||
const stream = { on: vi.fn((ev: string, cb: () => void) => { if (ev === 'error') onError = cb; return stream; }), pipe: vi.fn() };
|
||||
createReadStream.mockReturnValue(stream);
|
||||
@@ -289,7 +306,7 @@ describe('MapsController (parity with the legacy /api/maps route)', () => {
|
||||
makeController({ photoBytesPath: () => '/cache/p1.jpg' }).placePhotoBytes('p1', res);
|
||||
onError();
|
||||
expect(res.status).not.toHaveBeenCalled();
|
||||
expect(res.json).not.toHaveBeenCalled();
|
||||
expect(res.end).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -8,9 +8,12 @@
|
||||
*/
|
||||
import {
|
||||
parseOpeningHours,
|
||||
normalizeOpeningPeriods,
|
||||
normalizeSpecialDays,
|
||||
buildOsmDetails,
|
||||
getMapsKey,
|
||||
googleFtidFromMapsUrl,
|
||||
isGooglePlaceId,
|
||||
buildUserAgent,
|
||||
resolveOverpassEndpoints,
|
||||
resolveOverpassTimeoutMs,
|
||||
@@ -25,6 +28,7 @@ const {
|
||||
mockCheckSsrf,
|
||||
mockCacheGet,
|
||||
mockCacheGetErrored,
|
||||
mockCacheMarkError,
|
||||
mockCachePut,
|
||||
mockCacheGetInFlight,
|
||||
mockCacheSetInFlight,
|
||||
@@ -34,6 +38,7 @@ const {
|
||||
mockCheckSsrf: vi.fn(async () => ({ allowed: true })),
|
||||
mockCacheGet: vi.fn(() => null as any),
|
||||
mockCacheGetErrored: vi.fn(() => false),
|
||||
mockCacheMarkError: vi.fn(),
|
||||
mockCachePut: vi.fn(async (placeId: string, _bytes: Buffer, attribution: string | null) => ({
|
||||
photoUrl: `/api/maps/place-photo/${encodeURIComponent(placeId)}/bytes`,
|
||||
filePath: `/tmp/${placeId}.jpg`,
|
||||
@@ -83,7 +88,7 @@ vi.mock('../../../src/services/placePhotoCache', () => ({
|
||||
get: (placeId: string) => mockCacheGet(placeId),
|
||||
getErrored: (placeId: string) => mockCacheGetErrored(placeId),
|
||||
put: (placeId: string, bytes: Buffer, attribution: string | null) => mockCachePut(placeId, bytes, attribution),
|
||||
markError: vi.fn(),
|
||||
markError: (placeId: string, kind?: string) => mockCacheMarkError(placeId, kind),
|
||||
getInFlight: (placeId: string) => mockCacheGetInFlight(placeId),
|
||||
setInFlight: (placeId: string, p: Promise<any>) => mockCacheSetInFlight(placeId, p),
|
||||
serveFilePath: vi.fn(() => null),
|
||||
@@ -100,6 +105,7 @@ afterEach(() => {
|
||||
mockCacheGet.mockReturnValue(null);
|
||||
mockCacheGetErrored.mockReset();
|
||||
mockCacheGetErrored.mockReturnValue(false);
|
||||
mockCacheMarkError.mockReset();
|
||||
mockCachePut.mockReset();
|
||||
mockCachePut.mockImplementation(async (placeId: string, _bytes: Buffer, attribution: string | null) => ({
|
||||
photoUrl: `/api/maps/place-photo/${encodeURIComponent(placeId)}/bytes`,
|
||||
@@ -157,6 +163,84 @@ describe('parseOpeningHours', () => {
|
||||
const elapsed = Date.now() - start;
|
||||
expect(elapsed).toBeLessThan(100);
|
||||
});
|
||||
|
||||
it('MAPS-007b: emits machine-readable periods in Google day numbering (Sunday = 0)', () => {
|
||||
const result = parseOpeningHours('Mo 09:00-18:00; Su 10:00-14:00');
|
||||
expect(result.periods).toEqual([
|
||||
{ open: { day: 1, hour: 9, minute: 0 }, close: { day: 1, hour: 18, minute: 0 } },
|
||||
{ open: { day: 0, hour: 10, minute: 0 }, close: { day: 0, hour: 14, minute: 0 } },
|
||||
]);
|
||||
});
|
||||
|
||||
it('MAPS-007c: a period past midnight closes on the following day', () => {
|
||||
const result = parseOpeningHours('Sa 20:00-02:00');
|
||||
expect(result.periods).toEqual([
|
||||
{ open: { day: 6, hour: 20, minute: 0 }, close: { day: 0, hour: 2, minute: 0 } },
|
||||
]);
|
||||
});
|
||||
|
||||
it('MAPS-007d: the OSM 24:00 spelling becomes midnight of the next day', () => {
|
||||
// Google's clock has no hour 24, so "00:00-24:00" is a full day, not a rejected range.
|
||||
const result = parseOpeningHours('Mo 00:00-24:00');
|
||||
expect(result.periods).toEqual([
|
||||
{ open: { day: 1, hour: 0, minute: 0 }, close: { day: 2, hour: 0, minute: 0 } },
|
||||
]);
|
||||
});
|
||||
|
||||
it('MAPS-007e: unusable clock values produce no period', () => {
|
||||
expect(parseOpeningHours('Mo 09:75-18:00').periods).toEqual([]);
|
||||
expect(parseOpeningHours('Mo 09:00-24:30').periods).toEqual([]);
|
||||
expect(parseOpeningHours('Mo closed').periods).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
// ── normalizeOpeningPeriods / normalizeSpecialDays ────────────────────────────
|
||||
|
||||
describe('normalizeOpeningPeriods', () => {
|
||||
it('MAPS-007f: keeps well-formed periods and fills the zeroes proto3 JSON omits', () => {
|
||||
expect(
|
||||
normalizeOpeningPeriods([{ open: { day: 3, hour: 9, minute: 30 }, close: { day: 3, hour: 17 } }]),
|
||||
).toEqual([{ open: { day: 3, hour: 9, minute: 30 }, close: { day: 3, hour: 17, minute: 0 } }]);
|
||||
// Sunday midnight arrives as an empty object.
|
||||
expect(normalizeOpeningPeriods([{ open: {} }])).toEqual([{ open: { day: 0, hour: 0, minute: 0 }, close: null }]);
|
||||
});
|
||||
|
||||
it('MAPS-007g: a period without a close survives as the round-the-clock marker', () => {
|
||||
expect(normalizeOpeningPeriods([{ open: { day: 0, hour: 0, minute: 0 } }])).toEqual([
|
||||
{ open: { day: 0, hour: 0, minute: 0 }, close: null },
|
||||
]);
|
||||
});
|
||||
|
||||
it('MAPS-007h: drops out-of-range points and periods with an unusable close', () => {
|
||||
expect(normalizeOpeningPeriods([{ open: { day: 7, hour: 9, minute: 0 } }])).toBeNull();
|
||||
expect(normalizeOpeningPeriods([{ open: { day: 1, hour: 24, minute: 0 } }])).toBeNull();
|
||||
// A broken close must not be mistaken for "never closes".
|
||||
expect(
|
||||
normalizeOpeningPeriods([{ open: { day: 1, hour: 9, minute: 0 }, close: { day: 1, hour: 9, minute: 90 } }]),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it('MAPS-007i: returns null when there is nothing to normalise', () => {
|
||||
expect(normalizeOpeningPeriods(undefined)).toBeNull();
|
||||
expect(normalizeOpeningPeriods([])).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('normalizeSpecialDays', () => {
|
||||
it('MAPS-007j: turns Google date parts into ISO dates without duplicates', () => {
|
||||
expect(
|
||||
normalizeSpecialDays([
|
||||
{ date: { year: 2026, month: 12, day: 25 } },
|
||||
{ date: { year: 2026, month: 1, day: 1 } },
|
||||
{ date: { year: 2026, month: 12, day: 25 } },
|
||||
]),
|
||||
).toEqual(['2026-12-25', '2026-01-01']);
|
||||
});
|
||||
|
||||
it('MAPS-007k: skips incomplete or impossible dates and returns null when none are left', () => {
|
||||
expect(normalizeSpecialDays([{}, { date: { year: 2026, month: 13, day: 1 } }, { date: { year: 2026, day: 5 } }])).toBeNull();
|
||||
expect(normalizeSpecialDays(undefined)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// ── buildOsmDetails ───────────────────────────────────────────────────────────
|
||||
@@ -202,6 +286,19 @@ describe('buildOsmDetails', () => {
|
||||
expect(buildOsmDetails({}, 'node', '1').source).toBe('openstreetmap');
|
||||
});
|
||||
|
||||
it('MAPS-012b: carries the structured periods next to the weekday lines', () => {
|
||||
const result = buildOsmDetails({ opening_hours: 'Mo-Tu 09:00-18:00' }, 'node', '1');
|
||||
expect(result.opening_periods).toEqual([
|
||||
{ open: { day: 1, hour: 9, minute: 0 }, close: { day: 1, hour: 18, minute: 0 } },
|
||||
{ open: { day: 2, hour: 9, minute: 0 }, close: { day: 2, hour: 18, minute: 0 } },
|
||||
]);
|
||||
});
|
||||
|
||||
it('MAPS-012c: opening_periods is null when the day lines carry no usable times', () => {
|
||||
expect(buildOsmDetails({}, 'node', '1').opening_periods).toBeNull();
|
||||
expect(buildOsmDetails({ opening_hours: 'Mo closed' }, 'node', '1').opening_periods).toBeNull();
|
||||
});
|
||||
|
||||
it('MAPS-014b: opening_hours is null when all days have unknown times (all "?")', () => {
|
||||
// "closed" does not match the day+time pattern so all days remain "?"
|
||||
const result = buildOsmDetails({ opening_hours: 'closed' }, 'node', '1');
|
||||
@@ -1488,6 +1585,71 @@ describe('getPlaceDetails (fetch stubbed)', () => {
|
||||
expect((result.place as any).open_now).toBe(false);
|
||||
});
|
||||
|
||||
it('MAPS-041f2: hands the structured opening periods and special days to the client', async () => {
|
||||
mockDbGet.mockReturnValueOnce({ maps_api_key: 'gkey' });
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
id: 'ChIJPeriods',
|
||||
regularOpeningHours: {
|
||||
// Localised display text — the client shows it but must not parse it.
|
||||
weekdayDescriptions: ['月曜日: 9:00~18:00'],
|
||||
openNow: true,
|
||||
periods: [{ open: { day: 1, hour: 9, minute: 0 }, close: { day: 1, hour: 18, minute: 0 } }],
|
||||
specialDays: [{ date: { year: 2026, month: 12, day: 25 } }],
|
||||
},
|
||||
}),
|
||||
}),
|
||||
);
|
||||
const { getPlaceDetails } = await import('../../../src/services/mapsService');
|
||||
const place = (await getPlaceDetails(1, 'ChIJPeriods')).place as any;
|
||||
expect(place.opening_periods).toEqual([
|
||||
{ open: { day: 1, hour: 9, minute: 0 }, close: { day: 1, hour: 18, minute: 0 } },
|
||||
]);
|
||||
expect(place.opening_special_days).toEqual(['2026-12-25']);
|
||||
expect(place.opening_hours).toEqual(['月曜日: 9:00~18:00']);
|
||||
});
|
||||
|
||||
it('MAPS-041f3: opening_periods is null when Google sends no periods', async () => {
|
||||
mockDbGet.mockReturnValueOnce({ maps_api_key: 'gkey' });
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
id: 'ChIJNoPeriods',
|
||||
regularOpeningHours: { weekdayDescriptions: ['Monday: 9:00 AM – 5:00 PM'], openNow: false },
|
||||
}),
|
||||
}),
|
||||
);
|
||||
const { getPlaceDetails } = await import('../../../src/services/mapsService');
|
||||
const place = (await getPlaceDetails(1, 'ChIJNoPeriods')).place as any;
|
||||
expect(place.opening_periods).toBeNull();
|
||||
expect(place.opening_special_days).toBeNull();
|
||||
});
|
||||
|
||||
it('MAPS-041f4: getPlaceDetailsExpanded carries the periods too', async () => {
|
||||
mockDbGet.mockReturnValueOnce({ maps_api_key: 'gkey' });
|
||||
// expanded=1 cache miss
|
||||
mockDbGet.mockReturnValueOnce(undefined);
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
id: 'ChIJExpandedPeriods',
|
||||
// A place that never closes: one period, no close point.
|
||||
regularOpeningHours: { openNow: true, periods: [{ open: { day: 0, hour: 0, minute: 0 } }] },
|
||||
}),
|
||||
}),
|
||||
);
|
||||
const { getPlaceDetailsExpanded } = await import('../../../src/services/mapsService');
|
||||
const place = (await getPlaceDetailsExpanded(1, 'ChIJExpandedPeriods')).place as any;
|
||||
expect(place.opening_periods).toEqual([{ open: { day: 0, hour: 0, minute: 0 }, close: null }]);
|
||||
});
|
||||
|
||||
it('MAPS-041g: getPlaceDetailsExpanded truncates reviews to first 5 entries', async () => {
|
||||
mockDbGet.mockReturnValueOnce({ maps_api_key: 'gkey' });
|
||||
// expanded=1 cache miss
|
||||
@@ -1509,6 +1671,33 @@ describe('getPlaceDetails (fetch stubbed)', () => {
|
||||
const result = await getPlaceDetailsExpanded(1, 'ChIJMany');
|
||||
expect((result.place as any).reviews).toHaveLength(5);
|
||||
});
|
||||
|
||||
// The client sends whatever id the place carries, and the expanded lookup used to
|
||||
// forward all of them — including OSM ids — to Google, which bills the 400
|
||||
// INVALID_ARGUMENT it answers with (#1727).
|
||||
it('MAPS-041h: getPlaceDetailsExpanded serves an OSM id from Overpass instead of Google', async () => {
|
||||
mockDbGet.mockReturnValue({ maps_api_key: 'gkey' });
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ elements: [{ tags: { website: 'https://nerja.example' } }] }),
|
||||
});
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
const { getPlaceDetailsExpanded } = await import('../../../src/services/mapsService');
|
||||
const result = await getPlaceDetailsExpanded(1, 'node:5255005321');
|
||||
expect((result.place as any).source).toBe('openstreetmap');
|
||||
expect((result.place as any).website).toBe('https://nerja.example');
|
||||
expect(fetchMock.mock.calls.map((call) => String(call[0])).some((url) => url.includes('places.googleapis.com')))
|
||||
.toBe(false);
|
||||
});
|
||||
|
||||
it('MAPS-041i: getPlaceDetailsExpanded answers a coordinate pseudo-id with no place at all', async () => {
|
||||
mockDbGet.mockReturnValue({ maps_api_key: 'gkey' });
|
||||
const fetchMock = vi.fn();
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
const { getPlaceDetailsExpanded } = await import('../../../src/services/mapsService');
|
||||
await expect(getPlaceDetailsExpanded(1, 'coords:48.8,2.3')).resolves.toEqual({ place: null });
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
// ── getPlacePhoto (fetch stubbed) ────────────────────────────────────────────
|
||||
@@ -1539,7 +1728,7 @@ describe('getPlacePhoto (fetch stubbed)', () => {
|
||||
expect(mockCachePut).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('MAPS-043: throws 404 when Wikimedia returns nothing and no API key', async () => {
|
||||
it('MAPS-043: resolves with photoUrl null when Wikimedia returns nothing and no API key', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue({
|
||||
@@ -1548,7 +1737,10 @@ describe('getPlacePhoto (fetch stubbed)', () => {
|
||||
}),
|
||||
);
|
||||
const { getPlacePhoto } = await import('../../../src/services/mapsService');
|
||||
await expect(getPlacePhoto(999, 'coords:0.0,0.0', 0, 0)).rejects.toMatchObject({ status: 404 });
|
||||
await expect(getPlacePhoto(999, 'coords:0.0,0.0', 0, 0)).resolves.toEqual({
|
||||
photoUrl: null,
|
||||
attribution: null,
|
||||
});
|
||||
});
|
||||
|
||||
it('MAPS-043b: returns cached photo when disk cache returns a hit', async () => {
|
||||
@@ -1567,27 +1759,42 @@ describe('getPlacePhoto (fetch stubbed)', () => {
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('MAPS-043c: throws 404 from error cache without making a network request', async () => {
|
||||
it('MAPS-043c: serves the negative cache with photoUrl null and no network request', async () => {
|
||||
mockCacheGetErrored.mockReturnValue(true);
|
||||
const fetchMock = vi.fn();
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
const { getPlacePhoto } = await import('../../../src/services/mapsService');
|
||||
const errorId = `coords:error-cache-${Date.now()}`;
|
||||
await expect(getPlacePhoto(999, errorId, 0, 0)).rejects.toMatchObject({ status: 404 });
|
||||
await expect(getPlacePhoto(999, errorId, 0, 0)).resolves.toEqual({ photoUrl: null, attribution: null });
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('MAPS-043d: throws 404 when lat/lng are NaN and no API key', async () => {
|
||||
it('MAPS-043d: resolves with photoUrl null when lat/lng are NaN and no API key', async () => {
|
||||
const { getPlacePhoto } = await import('../../../src/services/mapsService');
|
||||
const nanId = `coords:nan-test-${Date.now()}`;
|
||||
await expect(getPlacePhoto(999, nanId, NaN, NaN)).rejects.toMatchObject({ status: 404 });
|
||||
await expect(getPlacePhoto(999, nanId, NaN, NaN)).resolves.toEqual({ photoUrl: null, attribution: null });
|
||||
});
|
||||
|
||||
it('MAPS-043e: falls through and throws 404 when Wikimedia fetch throws', async () => {
|
||||
it('MAPS-043e: falls through to photoUrl null when the Wikimedia fetch throws', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('network fail')));
|
||||
const { getPlacePhoto } = await import('../../../src/services/mapsService');
|
||||
const throwId = `coords:throw-test-${Date.now()}`;
|
||||
await expect(getPlacePhoto(999, throwId, 48.8, 2.3, 'Place')).rejects.toMatchObject({ status: 404 });
|
||||
await expect(getPlacePhoto(999, throwId, 48.8, 2.3, 'Place')).resolves.toEqual({
|
||||
photoUrl: null,
|
||||
attribution: null,
|
||||
});
|
||||
});
|
||||
|
||||
it('MAPS-043f: an in-flight lookup that found nothing resolves the waiter with photoUrl null', async () => {
|
||||
mockCacheGetInFlight.mockReturnValue(Promise.resolve(null) as any);
|
||||
const fetchMock = vi.fn();
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
const { getPlacePhoto } = await import('../../../src/services/mapsService');
|
||||
await expect(getPlacePhoto(999, 'ChIJInFlight', 48.8, 2.3)).resolves.toEqual({
|
||||
photoUrl: null,
|
||||
attribution: null,
|
||||
});
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('MAPS-044: returns proxy URL via Google path when API key present and photos exist', async () => {
|
||||
@@ -1616,7 +1823,7 @@ describe('getPlacePhoto (fetch stubbed)', () => {
|
||||
expect(mockCachePut).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('MAPS-044b: throws 404 when Google details fetch returns non-ok', async () => {
|
||||
it('MAPS-044b: resolves with photoUrl null when Google details fetch returns non-ok', async () => {
|
||||
mockDbGet.mockReturnValueOnce({ maps_api_key: 'gkey' });
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
@@ -1628,10 +1835,50 @@ describe('getPlacePhoto (fetch stubbed)', () => {
|
||||
);
|
||||
const { getPlacePhoto } = await import('../../../src/services/mapsService');
|
||||
const errId = `ChIJErr-${Date.now()}`;
|
||||
await expect(getPlacePhoto(1, errId, 48.8, 2.3)).rejects.toMatchObject({ status: 404 });
|
||||
await expect(getPlacePhoto(1, errId, 48.8, 2.3)).resolves.toEqual({ photoUrl: null, attribution: null });
|
||||
// A rejected provider call says nothing about the place — remember it as a
|
||||
// failed attempt (minutes), not as "this place has no photo" (a day).
|
||||
expect(mockCacheMarkError).toHaveBeenCalledWith(errId, 'provider-error');
|
||||
});
|
||||
|
||||
it('MAPS-044c: throws 404 when Google place has no photos', async () => {
|
||||
it('MAPS-044b2: remembers a place both providers came up empty for as a lasting miss', async () => {
|
||||
mockDbGet.mockReturnValueOnce({ maps_api_key: 'gkey' });
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi
|
||||
.fn()
|
||||
// Google answers, the place simply has no photos.
|
||||
.mockResolvedValueOnce({ ok: true, text: async () => JSON.stringify({ photos: [] }) })
|
||||
// Wikimedia has no article near the coordinates either.
|
||||
.mockResolvedValueOnce({ ok: true, json: async () => ({ query: { pages: {} } }) }),
|
||||
);
|
||||
const { getPlacePhoto } = await import('../../../src/services/mapsService');
|
||||
const emptyId = `ChIJEmpty-${Date.now()}`;
|
||||
await expect(getPlacePhoto(1, emptyId, 48.8, 2.3)).resolves.toEqual({ photoUrl: null, attribution: null });
|
||||
expect(mockCacheMarkError).toHaveBeenCalledWith(emptyId, 'no-photo');
|
||||
});
|
||||
|
||||
it('MAPS-044b3: a failed Wikimedia image download counts as a failed attempt', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({ query: { pages: { '1': { thumbnail: { source: 'https://wiki.org/photo.jpg' } } } } }),
|
||||
})
|
||||
.mockResolvedValueOnce({ ok: false, status: 503, arrayBuffer: async () => new ArrayBuffer(0) }),
|
||||
);
|
||||
const { getPlacePhoto } = await import('../../../src/services/mapsService');
|
||||
const downId = `coords:down-${Date.now()}`;
|
||||
await expect(getPlacePhoto(999, downId, 48.8, 2.3, 'Place')).resolves.toEqual({
|
||||
photoUrl: null,
|
||||
attribution: null,
|
||||
});
|
||||
expect(mockCacheMarkError).toHaveBeenCalledWith(downId, 'provider-error');
|
||||
});
|
||||
|
||||
it('MAPS-044c: resolves with photoUrl null when the Google place has no photos', async () => {
|
||||
mockDbGet.mockReturnValueOnce({ maps_api_key: 'gkey' });
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
@@ -1642,10 +1889,10 @@ describe('getPlacePhoto (fetch stubbed)', () => {
|
||||
);
|
||||
const { getPlacePhoto } = await import('../../../src/services/mapsService');
|
||||
const noPhotoId = `ChIJNone-${Date.now()}`;
|
||||
await expect(getPlacePhoto(1, noPhotoId, 48.8, 2.3)).rejects.toMatchObject({ status: 404 });
|
||||
await expect(getPlacePhoto(1, noPhotoId, 48.8, 2.3)).resolves.toEqual({ photoUrl: null, attribution: null });
|
||||
});
|
||||
|
||||
it('MAPS-044d: throws 404 when media endpoint returns non-ok status', async () => {
|
||||
it('MAPS-044d: resolves with photoUrl null when the media endpoint returns non-ok status', async () => {
|
||||
mockDbGet.mockReturnValueOnce({ maps_api_key: 'gkey' });
|
||||
const fetchMock = vi
|
||||
.fn()
|
||||
@@ -1664,7 +1911,7 @@ describe('getPlacePhoto (fetch stubbed)', () => {
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
const { getPlacePhoto } = await import('../../../src/services/mapsService');
|
||||
const noUriId = `ChIJXYZ-${Date.now()}`;
|
||||
await expect(getPlacePhoto(1, noUriId, 48.8, 2.3)).rejects.toMatchObject({ status: 404 });
|
||||
await expect(getPlacePhoto(1, noUriId, 48.8, 2.3)).resolves.toEqual({ photoUrl: null, attribution: null });
|
||||
});
|
||||
|
||||
it('MAPS-044e: returns proxy URL with null attribution when authorAttributions is empty', async () => {
|
||||
@@ -1748,6 +1995,58 @@ describe('getPlacePhoto (fetch stubbed)', () => {
|
||||
expect(result.attribution).toBe('Wikipedia');
|
||||
expect(mockCachePut).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
// OSM ids are what the client sends whenever a place has no google_place_id.
|
||||
// Google rejects them with a billable 400 INVALID_ARGUMENT, so they must go
|
||||
// straight to the Wikimedia fallback like coords: ids already do.
|
||||
it.each(['node:5255005321', 'way:84527326', 'relation:345407'])(
|
||||
'MAPS-044h: skips Google for the OSM id %s even when an API key is configured',
|
||||
async (osmId) => {
|
||||
mockDbGet.mockReturnValueOnce({ maps_api_key: 'gkey' });
|
||||
const fetchMock = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({ query: { pages: { '1': { thumbnail: { source: 'https://wiki.org/osm.jpg' } } } } }),
|
||||
})
|
||||
.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
arrayBuffer: async () => new ArrayBuffer(90),
|
||||
});
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
const { getPlacePhoto } = await import('../../../src/services/mapsService');
|
||||
const result = await getPlacePhoto(1, osmId, 36.7617, -3.8448, 'Cueva de Nerja');
|
||||
expect(result.photoUrl).toBe(`/api/maps/place-photo/${encodeURIComponent(osmId)}/bytes`);
|
||||
const requested = fetchMock.mock.calls.map((call) => String(call[0]));
|
||||
expect(requested.some((url) => url.includes('places.googleapis.com'))).toBe(false);
|
||||
},
|
||||
);
|
||||
|
||||
it('MAPS-044i: an OSM id with no Wikimedia hit resolves with photoUrl null instead of a 404', async () => {
|
||||
mockDbGet.mockReturnValueOnce({ maps_api_key: 'gkey' });
|
||||
const fetchMock = vi.fn().mockResolvedValue({ ok: true, json: async () => ({ query: { pages: {} } }) });
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
const { getPlacePhoto } = await import('../../../src/services/mapsService');
|
||||
await expect(getPlacePhoto(1, 'node:2481346642', 36.76, -3.84, 'Nerja')).resolves.toEqual({
|
||||
photoUrl: null,
|
||||
attribution: null,
|
||||
});
|
||||
expect(fetchMock.mock.calls.map((call) => String(call[0])).some((url) => url.includes('places.googleapis.com')))
|
||||
.toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isGooglePlaceId', () => {
|
||||
it('MAPS-045: accepts Google place ids and rejects the ids Google cannot resolve', () => {
|
||||
expect(isGooglePlaceId('ChIJLU7jZClu5kcR4PcOOO6p3I0')).toBe(true);
|
||||
expect(isGooglePlaceId('coords:48.8,2.3')).toBe(false);
|
||||
expect(isGooglePlaceId('node:5255005321')).toBe(false);
|
||||
expect(isGooglePlaceId('way:84527326')).toBe(false);
|
||||
expect(isGooglePlaceId('relation:345407')).toBe(false);
|
||||
expect(isGooglePlaceId('https://lh3.googleusercontent.com/photo.jpg')).toBe(false);
|
||||
// The collection views send the bare coordinate pair when a place has no ids.
|
||||
expect(isGooglePlaceId('36.7617499,-3.8448432')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('googleFtidFromMapsUrl', () => {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/**
|
||||
* Unit tests for placePhotoCache — PPC-001 through PPC-010.
|
||||
* Covers the downscale guard in put(), removeIfUnreferenced(), and sweepOrphans().
|
||||
* Unit tests for placePhotoCache — PPC-001 through PPC-012.
|
||||
* Covers the downscale guard in put(), removeIfUnreferenced(), sweepOrphans(),
|
||||
* and the two negative-cache windows.
|
||||
* Uses a real in-memory SQLite DB and a throwaway temp upload dir
|
||||
* (TREK_PLACE_PHOTO_DIR) so the real uploads tree is never touched.
|
||||
*/
|
||||
@@ -156,3 +157,58 @@ describe('placePhotoCache.sweepOrphans()', () => {
|
||||
expect(fs.existsSync(filePathFor('ref-a'))).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('placePhotoCache negative cache', () => {
|
||||
function ageError(placeId: string, ms: number): void {
|
||||
testDb
|
||||
.prepare('UPDATE google_place_photo_meta SET error_at = ? WHERE place_id = ?')
|
||||
.run(Date.now() - ms, placeId);
|
||||
}
|
||||
|
||||
it('PPC-009: a place with no photo stays remembered well past the old five-minute window', () => {
|
||||
cache.markError('photo-less');
|
||||
|
||||
ageError('photo-less', 30 * 60 * 1000);
|
||||
expect(cache.getErrored('photo-less')).toBe(true);
|
||||
|
||||
ageError('photo-less', 5 * 60 * 60 * 1000);
|
||||
expect(cache.getErrored('photo-less')).toBe(true);
|
||||
});
|
||||
|
||||
it('PPC-010: the miss expires once it is a day old', () => {
|
||||
cache.markError('stale-miss');
|
||||
ageError('stale-miss', 24 * 60 * 60 * 1000);
|
||||
|
||||
expect(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', () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
cache.markError('flaky', 'provider-error');
|
||||
expect(cache.getErrored('flaky')).toBe(true);
|
||||
// Nothing on disk — a restart retries instead of inheriting someone's outage.
|
||||
expect(testDb.prepare('SELECT 1 FROM google_place_photo_meta WHERE place_id = ?').get('flaky')).toBeUndefined();
|
||||
|
||||
vi.advanceTimersByTime(5 * 60 * 1000);
|
||||
expect(cache.getErrored('flaky')).toBe(false);
|
||||
|
||||
// The long window belongs to the other case: same age, still remembered.
|
||||
cache.markError('photo-less-too');
|
||||
ageError('photo-less-too', 5 * 60 * 1000);
|
||||
expect(cache.getErrored('photo-less-too')).toBe(true);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('PPC-012: a cached photo clears an earlier failed attempt', async () => {
|
||||
cache.markError('recovered', 'provider-error');
|
||||
expect(cache.getErrored('recovered')).toBe(true);
|
||||
|
||||
await cache.put('recovered', await makeJpeg(40, 40), null);
|
||||
expect(cache.getErrored('recovered')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user