fix(server): ask Nominatim when Photon finds nothing and keep bulk lookups off Photon

An empty Photon search, or one without a hit that has an OpenStreetMap id, is asked again at Nominatim as the reverse lookup already was. The background lane goes to Nominatim alone, a reverse lookup leaves Nominatim half of the caller's deadline, and a 429 with Retry-After pauses Photon for that long.
This commit is contained in:
Maurice
2026-10-29 11:05:45 +01:00
committed by Maurice
parent 45727b3d3b
commit 8c11833fb1
5 changed files with 120 additions and 14 deletions
+18 -6
View File
@@ -451,7 +451,12 @@ export class OsmClient {
* to thirty sequential calls. On the interactive lane those thirty take the
* next slot each time, so somebody typing in the place search waits behind the
* whole import. Yielding does not make the import faster, it stops it from
* being the only thing the process will do for half a minute.
* being the only thing the process will do for half a minute. That loop
* asks Nominatim alone, so an import does not spend the Photon allowance
* the people typing need.
*
* Photon matches differently and can find nothing where Nominatim finds the
* place, so an answer without a usable hit is asked again there.
*/
async searchNominatim(
query: string,
@@ -459,8 +464,9 @@ export class OsmClient {
lane: GeoLane = 'interactive',
bias?: { lat: number; lng: number },
) {
const photon = await this.photon.search(query, { lang, bias });
if (photon) return photon.map(asNominatimHit).filter(isHit).map(searchRecord);
const photon = lane === 'background' ? null : await this.photon.search(query, { lang, bias });
const hits = photon?.map(asNominatimHit).filter(isHit);
if (hits?.length) return hits.map(searchRecord);
const params = new URLSearchParams({
q: query,
format: 'json',
@@ -656,7 +662,8 @@ export class OsmClient {
lang?: string,
opts?: { lane?: GeoLane; timeoutMs?: number; locality?: boolean },
): Promise<{ name: string | null; address: string | null }> {
const data = (await this.reversePhoton(lat, lng, lang)) ?? (await this.reverseNominatim(lat, lng, lang, opts));
const photon = opts?.lane === 'background' ? null : await this.reversePhoton(lat, lng, lang, opts?.timeoutMs);
const data = photon ?? (await this.reverseNominatim(lat, lng, lang, opts));
if (!data) return { name: null, address: null };
const addr = data.address || {};
const name = opts?.locality
@@ -670,8 +677,13 @@ export class OsmClient {
* within a radius and can find nothing at all, where Nominatim names the
* nearest object at any distance, so an empty answer is asked again there.
*/
private async reversePhoton(lat: string, lng: string, lang?: string): Promise<NominatimReverse | null> {
const found = await this.photon.reverse(Number.parseFloat(lat), Number.parseFloat(lng), lang);
private async reversePhoton(
lat: string,
lng: string,
lang?: string,
timeoutMs?: number,
): Promise<NominatimReverse | null> {
const found = await this.photon.reverse(Number.parseFloat(lat), Number.parseFloat(lng), lang, timeoutMs);
return found?.[0] ? asNominatimReverse(found[0]) : null;
}
@@ -11,6 +11,13 @@
* read to the traveller as the search they had before. After a few misses in
* a row it stops asking for a minute, as the Places client does, so an
* installation that cannot reach it does not pay the deadline on every search.
* A spent allowance says itself how long to wait (Retry-After), and that wait
* is kept instead.
*
* The key comes from serviceIdentitySlot, as it does for the Places request
* (trek-places.fetch.ts), so the maps domain reads the installation identity
* one way and needs no import of ServiceIdentityModule; the slot holds the
* port that module resolved.
*
* Never imports MapsService: providers sit below the orchestrator.
*/
@@ -19,6 +26,7 @@ import { capResponse } from '../../../utils/ssrfGuard';
import { servicesConfig } from '../../app-config/tokens';
import { logDebug, logWarn } from '../../audit/audit-log.logger';
import { serviceIdentitySlot } from '../../service-identity/service-identity.interface';
import { retryAfterMs } from '../overpass-hedge.helpers';
import { photonAnswerSchema, photonLang, type PhotonFeature } from './photon.mapping';
import { Inject, Injectable } from '@nestjs/common';
import type { ConfigType } from '@nestjs/config';
@@ -35,6 +43,8 @@ const SEARCH_LIMIT = 10;
const BIAS_ZOOM = 10;
const MISSES_BEFORE_PAUSE = 4;
const PAUSE_MS = 60_000;
/** The longest Retry-After followed; the first question after it finds out whether the allowance is back. */
const MAX_PAUSE_MS = 60 * 60_000;
interface PhotonSearchOptions {
lang?: string;
@@ -59,14 +69,21 @@ export class PhotonClient {
return this.ask('api', params);
}
/** What lies at a point, nearest first, or null when Nominatim has to answer. */
reverse(lat: number, lng: number, lang?: string): Promise<PhotonFeature[] | null> {
/**
* What lies at a point, nearest first, or null when Nominatim has to answer.
* A caller's own deadline leaves Nominatim at least half of it.
*/
reverse(lat: number, lng: number, lang?: string, timeoutMs?: number): Promise<PhotonFeature[] | null> {
if (!Number.isFinite(lat) || !Number.isFinite(lng)) return Promise.resolve(null);
const params = new URLSearchParams({ lat: String(lat), lon: String(lng), limit: '1', lang: photonLang(lang) });
return this.ask('reverse', params);
return this.ask('reverse', params, timeoutMs ? Math.min(TIMEOUT_MS, timeoutMs / 2) : TIMEOUT_MS);
}
private async ask(path: 'api' | 'reverse', params: URLSearchParams): Promise<PhotonFeature[] | null> {
private async ask(
path: 'api' | 'reverse',
params: URLSearchParams,
timeoutMs = TIMEOUT_MS,
): Promise<PhotonFeature[] | null> {
if (!this.mayAsk()) return null;
const url = new URL(`${this.config.photonUrl}/${path}`);
url.search = params.toString();
@@ -78,9 +95,15 @@ export class PhotonClient {
headers: { Accept: 'application/json', ...headers },
// The key goes to this host alone, never on to wherever it points.
redirect: 'error',
signal: AbortSignal.timeout(TIMEOUT_MS),
signal: AbortSignal.timeout(timeoutMs),
});
identity.observe(url, res);
const wait = res.status === 429 ? retryAfterMs(res.headers.get('retry-after')) : null;
if (wait !== null) {
await res.body?.cancel();
this.pauseFor(wait);
return null;
}
if (!res.ok) {
await res.body?.cancel();
throw new Error(`answered ${res.status}`);
@@ -112,4 +135,11 @@ export class PhotonClient {
this.misses = MISSES_BEFORE_PAUSE - 1;
logWarn(`[Photon] ${reason}; asking Nominatim alone for a minute`);
}
private pauseFor(ms: number): void {
const wait = Math.min(ms, MAX_PAUSE_MS);
this.pausedUntil = Date.now() + wait;
this.misses = MISSES_BEFORE_PAUSE - 1;
logWarn(`[Photon] allowance spent; asking Nominatim alone for ${Math.ceil(wait / 1000)} s`);
}
}
+31 -1
View File
@@ -1,5 +1,5 @@
/**
* OSM-PHOTON-001..009: the OpenStreetMap search and reverse lookup ask Photon
* OSM-PHOTON-001..012: the OpenStreetMap search and reverse lookup ask Photon
* first where the installation holds a key, answer in the shape Nominatim's
* answers always had, and fall back to Nominatim whenever Photon gives none.
* Lookups by id stay on Nominatim. The network is a stubbed global fetch
@@ -95,6 +95,36 @@ describe('search', () => {
expect(places.map((p) => p.osm_id)).toEqual(['node:7']);
});
it('OSM-PHOTON-010: asks Nominatim when Photon finds nothing usable, without holding it against Photon', async () => {
photonReply = () => photonAnswer([]);
expect((await osm.searchNominatim('Brandenburger Tor', 'de'))[0]).toMatchObject({ osm_id: 'way:518071791' });
photonReply = () => photonAnswer([gateFeature({ osm_type: undefined })]);
expect((await osm.searchNominatim('Brandenburger Tor', 'de'))[0]).toMatchObject({ wikidata: 'Q82425' });
photonReply = () => photonAnswer([gateFeature()]);
await osm.searchNominatim('Brandenburger Tor', 'de');
expect(hosts).toEqual([
'photon.liketrek.com',
'nominatim.openstreetmap.org',
'photon.liketrek.com',
'nominatim.openstreetmap.org',
'photon.liketrek.com',
]);
});
it('OSM-PHOTON-011: a bulk import on the background lane asks Nominatim alone', async () => {
await osm.searchNominatim('Brandenburger Tor', 'de', 'background');
await osm.reverse('52.5', '13.4', 'de', { lane: 'background' });
expect(hosts).toEqual(['nominatim.openstreetmap.org', 'nominatim.openstreetmap.org']);
});
it('OSM-PHOTON-012: carries the wiki tags of a Photon hit into the record', async () => {
photonReply = () =>
photonAnswer([gateFeature({ extra: { wikidata: 'Q82425', wikimedia_commons: 'Category:Brandenburger Tor' } })]);
const [place] = await osm.searchNominatim('Brandenburger Tor', 'de');
expect(hosts).toEqual(['photon.liketrek.com']);
expect(place).toMatchObject({ wikidata: 'Q82425', wikimedia_commons: 'Category:Brandenburger Tor' });
});
it('OSM-PHOTON-004: the suggestions of a keyless install come out of Photon too', async () => {
const { suggestions } = await osm.autocompleteNominatim('Brandenb', 'de');
expect(hosts).toEqual(['photon.liketrek.com']);
+35 -1
View File
@@ -1,5 +1,5 @@
/**
* PHOTON-001..014: when Photon is asked, what it is asked, and every way it
* PHOTON-001..016: when Photon is asked, what it is asked, and every way it
* hands the question back to Nominatim. The network is a stubbed global fetch,
* the installation identity a fake in the slot the service-identity module fills.
*/
@@ -162,3 +162,37 @@ describe('the pause after misses in a row', () => {
expect(fetchMock).toHaveBeenCalledTimes(9);
});
});
describe('a spent allowance and a short deadline', () => {
it('PHOTON-015: a refusal with Retry-After pauses for that long, an hour at most', async () => {
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(new Date('2026-10-29T10:00:00Z'));
const photon = client();
const spent = (retryAfter: string) =>
new Response('{}', { status: 429, headers: { 'content-type': 'application/json', 'retry-after': retryAfter } });
fetchMock.mockResolvedValueOnce(spent('30'));
expect(await photon.search('Rostock')).toBeNull();
expect(await photon.reverse(52.5, 13.4)).toBeNull();
expect(fetchMock).toHaveBeenCalledTimes(1);
vi.setSystemTime(new Date('2026-10-29T10:00:31Z'));
fetchMock.mockResolvedValueOnce(spent('50400'));
expect(await photon.search('Rostock')).toBeNull();
vi.setSystemTime(new Date('2026-10-29T10:59:00Z'));
expect(await photon.search('Rostock')).toBeNull();
expect(fetchMock).toHaveBeenCalledTimes(2);
vi.setSystemTime(new Date('2026-10-29T11:00:32Z'));
expect(await photon.search('Rostock')).toHaveLength(1);
expect(fetchMock).toHaveBeenCalledTimes(3);
});
it("PHOTON-016: a reverse lookup leaves Nominatim at least half of the caller's deadline", async () => {
const timeout = vi.spyOn(AbortSignal, 'timeout');
await client().reverse(52.5, 13.4, 'de', 3000);
await client().reverse(52.5, 13.4, 'de', 8000);
await client().reverse(52.5, 13.4, 'de');
expect(timeout.mock.calls.map(([ms]) => ms)).toEqual([1500, 2500, 2500]);
timeout.mockRestore();
});
});
+1 -1
View File
@@ -81,7 +81,7 @@ An installation pointed at its own copy with `TREK_PLACES_URL`, or with `TREK_PL
## Address search
Where the installation holds a key, the OpenStreetMap half of the search, the suggestions of an install without the index or a key, the right-click on the map, the name of a pasted map link and the geocoding of imports ask the address search of the TREK services first: a [Photon](https://github.com/komoot/photon) instance at `photon.liketrek.com` with a planet-wide import of OpenStreetMap. Nominatim stays behind it. A refused key, a spent allowance, an error, no answer within 2.5 seconds, or nothing found at a right-clicked point all go to Nominatim, so the result reads the same either way. After four misses in a row TREK asks Nominatim alone for a minute.
Where the installation holds a key, the OpenStreetMap half of the search, the suggestions of an install without the index or a key, the right-click on the map and the name of a pasted map link ask the address search of the TREK services first: a [Photon](https://github.com/komoot/photon) instance at `photon.liketrek.com` with a planet-wide import of OpenStreetMap. Nominatim stays behind it. A refused key, a spent allowance, an error, no answer within 2.5 seconds, or nothing found all go to Nominatim, so the result reads the same either way. After four misses in a row TREK asks Nominatim alone for a minute; a spent allowance that says when it comes back is waited out instead, for an hour at most. Imports that look up many points in a row (the venues of a booking, the stops of a route link, the addresses of imported places) go to Nominatim alone and leave the allowance to the people searching.
It is asked in the language TREK is set to, without its region (`pt-BR` asks in Portuguese, `zh-TW` in Chinese), where the import holds names in that language: Arabic, Azerbaijani, Catalan, Chinese, Czech, Dutch, English, Estonian, French, German, Greek, Hungarian, Indonesian, Italian, Japanese, Korean, Polish, Portuguese, Russian, Slovak, Spanish, Swedish, Thai, Turkish, Ukrainian and Vietnamese. Any other language gets the names used on the spot. Opening a place and matching a Google place to its OpenStreetMap record stay on Nominatim.