maps, routing, i18n: settle what the checks found

- The lead is Photon's own row first; a row of its name inside the lead
  only stands in where Photon's row went as the same place. Rows without a
  line below the name are never folded as reading the same.
- A miss of Photon where it is the geocoder no longer asks it a second time
  on the way to an empty answer.
- The transport words of the identity match use a Unicode word boundary
  (straße, estación) and match 駅 anywhere.
- Opening an OSM place reads the coordinate it was placed at explicitly.
- The ferry spans of a Valhalla leg move to valhallaFerries.ts, and a day
  cut into pieces is asked with one options object.
- "Limit" on the allowance tiles is "Daily limit", which no locale left
  as an English copy.
- Tests follow the new behaviour: no Nominatim behind Photon, zoom 13,
  and the expectations of the merge and edit-distance cases.
This commit is contained in:
Maurice
2026-10-30 16:36:22 +01:00
parent b98e530ffc
commit 1e5314d847
19 changed files with 111 additions and 88 deletions
@@ -0,0 +1,45 @@
import type { FerrySpan } from './valhallaRoute';
/** One step of a Valhalla leg, with the fields the ferry spans are read from. */
export interface ValhallaManeuver {
type?: number;
ferry?: boolean;
begin_shape_index?: number;
end_shape_index?: number;
time?: number;
length?: number;
}
/** Valhalla's maneuver type for boarding a ferry; the maneuver also carries `ferry: true` for its crossing. */
const FERRY_ENTER = 28;
/**
* CW-12: the stretches of a leg the router takes by boat, read off its
* maneuvers: a crossing is the maneuver that boards the ferry, from the point
* it starts at to the one it ends at, with its own length and time. Measured
* on Venice, the San Tomà to Ca' Rezzonico line came back as one maneuver of
* type 28, ferry true, 1.236 km and 745 s over shape points 24 to 46, then the
* walk off it. Crossings that touch are one. A leg the summary says has a
* ferry but whose maneuvers do not say where is taken whole, without a time:
* the crossing is somewhere on it, and none of it is counted as walked.
*/
export function ferrySpansOf(maneuvers: ValhallaManeuver[] | undefined, points: number): FerrySpan[] {
const spans: FerrySpan[] = [];
for (const maneuver of maneuvers ?? []) {
if (maneuver.ferry !== true && maneuver.type !== FERRY_ENTER) continue;
const from = Number(maneuver.begin_shape_index);
const to = Number(maneuver.end_shape_index);
if (!Number.isInteger(from) || !Number.isInteger(to) || from < 0 || to <= from || to >= points) continue;
const metres = Number.isFinite(maneuver.length) ? Number(maneuver.length) * 1000 : 0;
const seconds = Number.isFinite(maneuver.time) ? Number(maneuver.time) : null;
const previous = spans[spans.length - 1];
if (previous && previous.to === from) {
previous.to = to;
previous.metres += metres;
previous.seconds = previous.seconds === null || seconds === null ? null : previous.seconds + seconds;
} else {
spans.push({ from, to, metres, seconds });
}
}
return spans.length || points < 2 ? spans : [{ from: 0, to: points - 1, metres: 0, seconds: null }];
}
+12 -48
View File
@@ -9,6 +9,7 @@ import {
import { valhallaRelayRepo } from '../../repo/valhallaRelayRepo'
import { useSettingsStore } from '../../store/settingsStore'
import { decodePolyline } from './transitGeometry'
import { ferrySpansOf, type ValhallaManeuver } from './valhallaFerries'
import { haversineKm } from '../../utils/geo'
import type { Waypoint, SnappedWaypoint, RouteAvoidClass } from '../../types'
@@ -390,7 +391,7 @@ async function chainRun(
const base = valhallaBase()
if (!mayAsk(base, ask.publicFallback) || waypoints.length < 2) return null
const size = locationsPerRequest(base)
const run = await chainRunSized(base, waypoints, size, profile, avoid, signal, ask)
const run = await chainRunSized(base, waypoints, { size, profile, avoid, signal, ask })
// The relay fell over during a day cut for it. It rests now, so the base reads as FOSSGIS
// and the day is asked again there in pieces of ten.
const recut = run === null && base === TREK_VALHALLA && ask.publicFallback && waypoints.length > MAX_LOCATIONS
@@ -400,14 +401,19 @@ async function chainRun(
return run
}
/** How one day is asked: in pieces of `size`, for this profile and these avoidances. */
interface SizedRun {
size: number
profile: 'driving' | 'walking' | 'cycling'
avoid: readonly AvoidClass[]
signal: AbortSignal | undefined
ask: RunAsk
}
async function chainRunSized(
base: string,
waypoints: Waypoint[],
size: number,
profile: 'driving' | 'walking' | 'cycling',
avoid: readonly AvoidClass[],
signal: AbortSignal | undefined,
ask: RunAsk,
{ size, profile, avoid, signal, ask }: SizedRun,
): Promise<ValhallaRun | ValhallaNoPath | null> {
const legs: ValhallaLeg[] = []
// No pause between the pieces: a question that reaches FOSSGIS waits its turn in
@@ -926,14 +932,6 @@ export function runFrom(data: unknown): Omit<ValhallaRun, 'snapped'> | null {
interface ValhallaSummary { [key: string]: number | boolean | undefined }
interface ValhallaManeuver {
type?: number
ferry?: boolean
begin_shape_index?: number
end_shape_index?: number
time?: number
length?: number
}
function tripOf(data: unknown) {
return (data as {
@@ -944,40 +942,6 @@ function tripOf(data: unknown) {
})?.trip
}
/** Valhalla's maneuver type for boarding a ferry; the maneuver also carries `ferry: true` for its crossing. */
const FERRY_ENTER = 28
/**
* CW-12: the stretches of a leg the router takes by boat, read off its
* maneuvers: a crossing is the maneuver that boards the ferry, from the point
* it starts at to the one it ends at, with its own length and time. Measured
* on Venice, the San Tomà to Ca' Rezzonico line came back as one maneuver of
* type 28, ferry true, 1.236 km and 745 s over shape points 24 to 46, then the
* walk off it. Crossings that touch are one. A leg the summary says has a
* ferry but whose maneuvers do not say where is taken whole, without a time:
* the crossing is somewhere on it, and none of it is counted as walked.
*/
function ferrySpansOf(maneuvers: ValhallaManeuver[] | undefined, points: number): FerrySpan[] {
const spans: FerrySpan[] = []
for (const maneuver of maneuvers ?? []) {
if (maneuver.ferry !== true && maneuver.type !== FERRY_ENTER) continue
const from = Number(maneuver.begin_shape_index)
const to = Number(maneuver.end_shape_index)
if (!Number.isInteger(from) || !Number.isInteger(to) || from < 0 || to <= from || to >= points) continue
const metres = Number.isFinite(maneuver.length) ? Number(maneuver.length) * 1000 : 0
const seconds = Number.isFinite(maneuver.time) ? Number(maneuver.time) : null
const previous = spans[spans.length - 1]
if (previous && previous.to === from) {
previous.to = to
previous.metres += metres
previous.seconds = previous.seconds === null || seconds === null ? null : previous.seconds + seconds
} else {
spans.push({ from, to, metres, seconds })
}
}
return spans.length || points < 2 ? spans : [{ from: 0, to: points - 1, metres: 0, seconds: null }]
}
/** A summary and a shape as a leg, or null when the summary carries no numbers. */
function measured(summary: ValhallaSummary, coordinates: [number, number][]): ValhallaLeg | null {
if (!coordinates.length) return null
+9 -2
View File
@@ -145,7 +145,8 @@ const recordView = (r: Record<string, unknown>): RowView => ({
* Then Photon's lead (`pickLead`) goes first, and rows of its name inside it
* go: "Berlin" no longer opens on a business filed as Berlin above the city.
* Rows that read the same twice, two branches of a chain with the same town
* below them, are one row: nobody can tell them apart in the list.
* below them, are one row: nobody can tell them apart in the list. A row
* without a line below its name is never folded that way.
*/
export function mergeRanked<T>(
first: T[],
@@ -163,12 +164,18 @@ export function mergeRanked<T>(
return !first.some((i) => (id !== null && view(i).id === id) || samePlace(asPlace(i), asPlace(o)));
});
const merged = interleave(first, extra, Number.POSITIVE_INFINITY);
const top = lead && leadsHere(lead, bias) ? merged.find((row) => standsFor(view(row), lead)) : undefined;
// Photon's own row first; a row of its name inside it only where that row went as the same place.
const top =
lead && leadsHere(lead, bias)
? (merged.find((row) => view(row).id === lead.placeId) ?? merged.find((row) => standsFor(view(row), lead)))
: undefined;
const ordered = top && lead ? [top, ...merged.filter((row) => row !== top && !standsFor(view(row), lead))] : merged;
const shown = new Set<string>();
return ordered
.filter((row) => {
const v = view(row);
// Without a line below the name two rows of one name are told apart by nothing but where they are.
if (!v.line.trim()) return true;
const reads = `${foldName(v.name)}\n${foldName(v.line)}`;
if (shown.has(reads)) return false;
shown.add(reads);
+7 -8
View File
@@ -405,14 +405,13 @@ export class MapsService {
}),
this.osm
.searchPhoton(query, lang, locationBias)
// Nominatim only for an installation Photon does not answer.
.then(
async (photon) =>
photon ?? {
records: await this.osm.searchNominatim(query, lang, 'interactive', locationBias),
lead: null,
},
)
// Nominatim only for an installation without Photon; where Photon is
// the geocoder its miss is an empty half, not a question for another.
.then(async (photon) => {
if (photon) return photon;
if (this.osm.photonIsGeocoder()) return { records: [] as Record<string, unknown>[], lead: null };
return { records: await this.osm.searchNominatim(query, lang, 'interactive', locationBias), lead: null };
})
.catch((err: unknown) => {
console.warn('OpenStreetMap search failed, index only:', (err as Error).message);
return { records: [] as Record<string, unknown>[], lead: null };
+12 -6
View File
@@ -205,7 +205,7 @@ const IDENTITY_TIMEOUT_MS = 2500;
// asked for one ("Hauptbahnhof", "Tor station").
const TRANSPORT_KEYS = new Set(['railway', 'public_transport', 'highway']);
const TRANSPORT_WORDS =
/(station|bahnhof|hbf|bhf|halt|haltestelle|stop|street|straße|strasse|road|weg|gare|estación|stazione|駅)/iu;
/(?:^|[^\p{L}])(?:station|bahnhof|hbf|bhf|halt|haltestelle|stop|street|straße|strasse|road|weg|gare|estación|stazione)(?:$|[^\p{L}])|駅/iu;
// How far a reverse lookup that found nothing next to the point looks again.
const WIDE_REVERSE_KM = 50;
@@ -544,6 +544,11 @@ export class OsmClient {
* next Nominatim slot each time, so somebody typing in the place search waits
* behind the whole import.
*/
/** Whether Photon is this installation's geocoder, so a miss of it is not handed to Nominatim. */
photonIsGeocoder(): boolean {
return this.photon.inUse();
}
async searchNominatim(
query: string,
lang?: string,
@@ -930,9 +935,10 @@ export class OsmClient {
placeId: string,
lang?: string,
): Promise<Record<string, unknown> | null> {
const at = element.center ?? (element.lat !== undefined && element.lon !== undefined ? element : null);
if (!at) return null;
const near = await this.photon.reverse(at.lat, at.lon, lang, undefined, { limit: 10, radius: 0.3 });
const lat = element.center?.lat ?? element.lat;
const lng = element.center?.lon ?? element.lon;
if (lat === undefined || lng === undefined) return null;
const near = await this.photon.reverse(lat, lng, lang, undefined, { limit: 10, radius: 0.3 });
const self = near?.find((f) => asNominatimHit(f)?.osm_type === osmType && String(f.properties.osm_id) === osmId);
const base = lang ? toApiLang(lang).split('-')[0] : '';
const extra = self ? (asNominatimHit(self)?.extratags ?? {}) : {};
@@ -940,8 +946,8 @@ export class OsmClient {
...buildOsmDetails({ ...extra, ...(element.tags ?? {}) }, osmType, osmId),
name: (base && element.tags?.[`name:${base}`]) || self?.properties.name || element.tags?.name || '',
address: self ? photonDisplayName(self.properties) : near?.[0] ? photonDisplayName(near[0].properties) : '',
lat: at.lat,
lng: at.lon,
lat,
lng,
osm_id: placeId,
};
}
@@ -334,7 +334,7 @@ export function nameLike(query: string, name: string): boolean {
/**
* Edits between two strings, a swap of neighbours counting as one: the
* optimal string alignment distance. "Paramraibo" is two from "Paramaribo".
* optimal string alignment distance. "Paramraibo" is one from "Paramaribo".
*/
export function editDistance(a: string, b: string): number {
if (Math.abs(a.length - b.length) > 2) return 3;
+8 -7
View File
@@ -1,5 +1,6 @@
/**
* /api/maps search and reverse e2e with Photon in front of Nominatim: the real
* /api/maps search and reverse e2e with Photon as the geocoder of an
* installation with a key, Nominatim of one without: the real
* JwtAuthGuard, Zod pipe and response contracts over MapsModule on a migrated
* temp database, the TREK Places index switched off so the OpenStreetMap half
* answers alone.
@@ -127,12 +128,12 @@ describe('POST /api/maps/search', () => {
expect(identity.observed).toEqual([{ host: 'photon.liketrek.com', status: 200 }]);
});
it('MAPS-PHOTON-E2E-002: falls back to Nominatim when Photon refuses, and the answer reads the same', async () => {
it('MAPS-PHOTON-E2E-002: a Photon that refuses is an empty answer, Nominatim is not asked in its place', async () => {
photonReply = () => photonAnswer([], 429);
const res = await request(app.getHttpServer()).post('/api/maps/search').set(as(USER)).send({ query: 'Café' });
expect(res.status).toBe(200);
expect(res.body.places[0]).toMatchObject({ osm_id: 'node:42', name: 'Café Nominatim', category: 'cafe' });
expect(hostsAsked()).toEqual(['photon.liketrek.com', 'nominatim.openstreetmap.org']);
expect(res.body.places).toEqual([]);
expect(hostsAsked()).toEqual(['photon.liketrek.com']);
});
it('MAPS-PHOTON-E2E-003: never asks Photon without a key', async () => {
@@ -164,14 +165,14 @@ describe('GET /api/maps/reverse', () => {
expect(asked[0].pathname).toBe('/reverse');
});
it('MAPS-PHOTON-E2E-006: asks Nominatim when Photon is down', async () => {
it('MAPS-PHOTON-E2E-006: a Photon that is down names nothing, Nominatim is not asked in its place', async () => {
photonReply = () => photonAnswer([], 503);
const res = await request(app.getHttpServer())
.get('/api/maps/reverse')
.set(as(USER))
.query({ lat: '52.5163', lng: '13.3777' });
expect(res.body).toEqual({ name: 'Café Nominatim', address: NOMINATIM_HIT.display_name });
expect(hostsAsked()).toEqual(['photon.liketrek.com', 'nominatim.openstreetmap.org']);
expect(res.body).toEqual({ name: null, address: null });
expect(hostsAsked()).toEqual(['photon.liketrek.com']);
});
it('MAPS-PHOTON-E2E-007: answers 401 without a session and asks nobody', async () => {
@@ -238,7 +238,7 @@ describe('MapsService.autocompletePlaces', () => {
});
it('MAPS-AUTO-009: index and layer hits keep their own id form in one list', async () => {
mockSearch.mockResolvedValue([hit(), osmHit(), hit({ gers: 'def-456' })]);
mockSearch.mockResolvedValue([hit(), osmHit(), hit({ gers: 'def-456', name: 'Kirby Cafe Tenjin' })]);
const { suggestions } = await make().autocompletePlaces(1, INPUT);
@@ -85,8 +85,8 @@ describe('mergeSuggestions', () => {
it('MAPS-SUGMERGE-005: opens on the lead and drops the rows of its name inside it', () => {
const list = mergeSuggestions(berlinIndex, berlinPhoton, 8, { lead: berlin });
// The "Berlin" in Kleinmachnow lies outside the city, so it stays.
expect(list.map((s) => s.placeId)).toEqual(['relation:62422', 'node:484323', 'node:21302157', 'relation:170184']);
// The "Berlin" in Kleinmachnow lies inside the city's box, so it goes too.
expect(list.map((s) => s.placeId)).toEqual(['relation:62422', 'relation:170184', 'node:21302157']);
});
it('MAPS-SUGMERGE-006: a town leads only near where the traveller looks', () => {
+2 -2
View File
@@ -213,7 +213,7 @@ describe('search', () => {
(aerodrome.geometry as { coordinates: number[] }).coordinates = [-73.7781, 40.6413];
photonReply = () => photonAnswer([aerodrome]);
const fetchStub = globalThis.fetch as unknown as ReturnType<typeof vi.fn>;
const inner = fetchStub.getMockImplementation()!;
const inner = fetchStub.getMockImplementation() as (input: string | URL) => Promise<Response>;
fetchStub.mockImplementation(async (input: string | URL) => {
asked.push(new URL(String(input)).searchParams);
return inner(input);
@@ -256,7 +256,7 @@ describe('reverse', () => {
const asked: string[] = [];
photonReply = () => photonAnswer([]);
const fetchStub = globalThis.fetch as unknown as ReturnType<typeof vi.fn>;
const inner = fetchStub.getMockImplementation()!;
const inner = fetchStub.getMockImplementation() as (input: string | URL) => Promise<Response>;
fetchStub.mockImplementation(async (input: string | URL) => {
asked.push(new URL(String(input)).searchParams.get('radius') ?? '');
return inner(input);
+1 -1
View File
@@ -84,7 +84,7 @@ describe('what Photon is asked', () => {
lang: 'pt',
lat: '35.31',
lon: '139.53',
zoom: '10',
zoom: '13',
});
});
@@ -252,7 +252,7 @@ describe('rankFeatures', () => {
extra: undefined,
name: 'Neuschwanstein Souvenirs',
});
expect(rankFeatures([art, street, castle, shop]).map((f) => f.properties.osm_id)).toEqual([2, 1, 4, 3]);
expect(rankFeatures([art, street, castle, shop]).map((f) => f.properties.osm_id)).toEqual([2, 1, 3, 4]);
expect(rankFeatures([castle, art]).map((f) => f.properties.osm_id)).toEqual([2, 1]);
});
});
@@ -295,7 +295,7 @@ describe('pickLead', () => {
expect(pickLead([town({ name: 'FRA' })], 'FRA')).toBeNull();
const municipality = town({ osm_value: 'municipality', name: 'Sagrada Família' });
expect(pickLead([municipality], 'Sagrada Familia')).toBeNull();
expect(pickLead([municipality], 'Sagrada Familia', { lat: -20, lng: -44 })).not.toBeNull();
expect(pickLead([municipality], 'Sagrada Familia', { lat: 52.5, lng: 13.4 })).not.toBeNull();
});
});
@@ -338,7 +338,7 @@ describe('pickLead, namesakes', () => {
describe('nameLike and editDistance', () => {
it('PHOTON-MAP-025: counts a swap of neighbours as one edit', () => {
expect(editDistance('paramraibo', 'paramaribo')).toBe(2);
expect(editDistance('paramraibo', 'paramaribo')).toBe(1);
expect(editDistance('tokio', 'tokyo')).toBe(1);
expect(editDistance('ab', 'ba')).toBe(1);
expect(editDistance('berlin', 'berlin')).toBe(0);
@@ -755,7 +755,8 @@ describe('server Roadtrip router through the TREK services (routing relay)', ()
await oneByOne([...slow.entries()], async ([userId, timedOut]) => {
vi.mocked(safeFetchAdminConfigured).mockClear();
relay.ask.mockReset().mockImplementationOnce(timedOut);
const route = await settled(setup().router.route(userId, 1, 1, points.slice(0, 2), 'driving', ['toll']));
// All three points: the stubbed OSRM day has a leg for each pair of them.
const route = await settled(setup().router.route(userId, 1, 1, points, 'driving', ['toll']));
expect(route.avoidMissed).toEqual(['toll']);
const asked = vi.mocked(safeFetchAdminConfigured).mock.calls.map(([url]) => String(url));
expect(asked).toHaveLength(1);
+1 -1
View File
@@ -190,7 +190,7 @@ const admin: TranslationStrings = {
'admin.trekApi.quota.used': 'İstifadə edilib',
'admin.trekApi.quota.remaining': 'Qalıb',
'admin.trekApi.quota.resets': 'Sıfırlanma vaxtı',
'admin.trekApi.quota.limit': 'Limit',
'admin.trekApi.quota.limit': 'Gündəlik limit',
'admin.trekApi.quota.key': 'Açar',
'admin.trekApi.quota.state.connected': 'Qoşulub',
'admin.trekApi.quota.state.registering': 'Qurulur',
+1 -1
View File
@@ -135,7 +135,7 @@ const admin: TranslationStrings = {
'admin.trekApi.quota.used': 'Využito',
'admin.trekApi.quota.remaining': 'Zbývá',
'admin.trekApi.quota.resets': 'Obnoví se v',
'admin.trekApi.quota.limit': 'Limit',
'admin.trekApi.quota.limit': 'Denní limit',
'admin.trekApi.quota.key': 'Klíč',
'admin.trekApi.quota.state.connected': 'Připojeno',
'admin.trekApi.quota.state.registering': 'Nastavuje se',
+1 -1
View File
@@ -135,7 +135,7 @@ const admin: TranslationStrings = {
'admin.trekApi.quota.used': 'Verbraucht',
'admin.trekApi.quota.remaining': 'Verbleibend',
'admin.trekApi.quota.resets': 'Zurückgesetzt um',
'admin.trekApi.quota.limit': 'Limit',
'admin.trekApi.quota.limit': 'Tageslimit',
'admin.trekApi.quota.key': 'Schlüssel',
'admin.trekApi.quota.state.connected': 'Verbunden',
'admin.trekApi.quota.state.registering': 'Wird eingerichtet',
+1 -1
View File
@@ -185,7 +185,7 @@ const admin: TranslationStrings = {
'admin.trekApi.quota.used': 'Used',
'admin.trekApi.quota.remaining': 'Remaining',
'admin.trekApi.quota.resets': 'Resets at',
'admin.trekApi.quota.limit': 'Limit',
'admin.trekApi.quota.limit': 'Daily limit',
'admin.trekApi.quota.key': 'Key',
'admin.trekApi.quota.state.connected': 'Connected',
'admin.trekApi.quota.state.registering': 'Setting up',
+1 -1
View File
@@ -133,7 +133,7 @@ const admin: TranslationStrings = {
'admin.trekApi.quota.used': 'Wykorzystano',
'admin.trekApi.quota.remaining': 'Pozostało',
'admin.trekApi.quota.resets': 'Reset o',
'admin.trekApi.quota.limit': 'Limit',
'admin.trekApi.quota.limit': 'Limit dzienny',
'admin.trekApi.quota.key': 'Klucz',
'admin.trekApi.quota.state.connected': 'Połączono',
'admin.trekApi.quota.state.registering': 'Konfigurowanie',
+1 -1
View File
@@ -188,7 +188,7 @@ const admin: TranslationStrings = {
'admin.trekApi.quota.used': 'Využité',
'admin.trekApi.quota.remaining': 'Zostáva',
'admin.trekApi.quota.resets': 'Obnoví sa o',
'admin.trekApi.quota.limit': 'Limit',
'admin.trekApi.quota.limit': 'Denný limit',
'admin.trekApi.quota.key': 'Kľúč',
'admin.trekApi.quota.state.connected': 'Pripojené',
'admin.trekApi.quota.state.registering': 'Nastavuje sa',