fix(tours): search along a tour through the places index along the line, and name what could not be searched (PLN-02, CW-05)

The search along a tour found nothing. It asked the places index for all
kinds of a stretch at once, above the 100 rows and 200 characters of terms
the index takes, so the index refused and every stretch went to the public
Overpass mirrors, which do not answer from this server. Now the index is
asked in small circles strung along the line, one request per kind and
circle within its limits, and an empty circle counts as an answer, so a
city walk lists its sights, museums, parks, cafes, restaurants and markets
in well under a second. The kinds the index does not know (viewpoints,
huts, drinking water, toilets and the like) are asked of Overpass along the
whole line at the same time, one query per stretch of up to 50 km, three at
a time, each with a short deadline of its own; a line past 400 km is
searched along its start and says so. When the index answers no circle at
all, its kinds go to Overpass beside the others instead of after them. A
kind no source could be searched for is named in a calm notice above the
list instead of reporting nothing found, and the reason is written to the
log. Unnamed taps, toilets, shelters, picnic spots, viewpoints, summits,
slipways and repair stands stay in the list and on the map under the name
of their kind; an unnamed garden, cafe or memorial is left out. The places
nearest the line are kept when there are more than sixty, listed from the
start, with the opening hours the source has.

A walk's parks are parks and gardens only, and its museums are museums
and galleries only, no longer the beaches, summits, theatres and cinemas of
the map's explore buttons; a water park the index files under parks is not
one of them. The index also answers markets and summits. The explore
buttons keep their single request, and a search of several kinds that
would exceed the index limits is asked one kind at a time instead of being
refused. The MCP tool search_tour_pois and its wiki row describe the walk
kinds and the new unavailable list, and the OVERPASS_TIMEOUT_MS row says
the search along a tour keeps its own shorter deadline.
This commit is contained in:
Maurice
2026-10-19 22:34:10 +00:00
parent 9ed944c1e6
commit 3c823e07f4
55 changed files with 1841 additions and 236 deletions
+156
View File
@@ -0,0 +1,156 @@
/**
* The geometry of a search along a line (PLN-02): where the index is asked,
* the stretches Overpass is asked in, and the query that asks for every kind
* near one stretch at once. Pure: PoisAlongResolver makes the calls.
*/
import { lineMetres, pointAtMeters, simplifyLine, sliceAtMeters, type LatLng } from '@trek/shared/roadtrip';
/**
* The most circles one line is asked in. The index answers each in a fraction
* of a second, so this bounds the requests one search sends rather than its
* time; a longer line is searched along its first part and the answer says so.
*/
const MAX_BEADS = 24;
/** The most points the Overpass query carries; the line is simplified until it fits. */
const MAX_AROUND_POINTS = 120;
const METRES_PER_DEGREE = 111_320;
/**
* The longest stretch of a line one Overpass query covers, so the box it asks
* for candidates stays close to its part of the line however the line runs.
*/
const OVERPASS_STRETCH_M = 50_000;
/** The most stretches one line is asked in; a longer line is searched along its first 400 km and the answer says so. */
const MAX_OVERPASS_STRETCHES = 8;
/**
* How long Overpass may spend on the query near a line, in seconds, sent as
* its `[timeout:N]`. Shorter than the explore pill's, because a person waits
* for the search beside the index. The client waits a little longer than this
* (osm.client), never less, or it would hang up on an answer still coming.
*/
export const OVERPASS_ALONG_QUERY_TIMEOUT_S = 10;
/** One circle the index is asked in. */
interface AlongBead {
lat: number;
lng: number;
radiusM: number;
}
export interface AlongPlan {
beads: AlongBead[];
/** The part of the line the beads cover: all of it, unless the line was too long. */
covered: LatLng[];
capped: boolean;
}
/**
* Circles strung along the line like beads, so together they hold every point
* within the corridor of it. They lie a step apart, at least two and at most
* six corridor widths. Each reaches half a step and a corridor width: a place
* near the line is at most a corridor from the line, and that point of the
* line at most half a step from a bead, however the line turns at a street
* corner. The index answers nearest first, so the wider reach costs nothing
* close to the line. A line longer than the beads reach is covered along its
* start.
*/
export function alongPlan(line: LatLng[], corridorM: number): AlongPlan {
const total = lineMetres(line);
const step = Math.min(6 * corridorM, Math.max(2 * corridorM, total / (MAX_BEADS - 1)));
const coveredM = Math.min(total, step * (MAX_BEADS - 1));
// A hair of slack, so a line exactly a whole number of steps long takes no bead twice.
const steps = Math.max(0, Math.ceil(coveredM / step - 1e-9));
const radiusM = Math.ceil(step / 2 + corridorM);
const beads = Array.from({ length: steps + 1 }, (_, index) => pointAtMeters(line, Math.min(coveredM, index * step)))
.filter((at): at is LatLng => at !== null)
.map((at) => ({ lat: at.lat, lng: at.lng, radiusM }));
const capped = coveredM < total;
return { beads, covered: capped ? sliceAtMeters(line, 0, coveredM) : line, capped };
}
interface AlongStretches {
stretches: LatLng[][];
/** The line was longer than the stretches reach; only its start is asked. */
capped: boolean;
}
/**
* The line cut into stretches of equal length, none longer than one Overpass
* query covers, together the whole line unless it runs past what one search
* asks. A line that fits one stretch is asked as it is.
*/
export function overpassStretches(line: LatLng[]): AlongStretches {
const total = lineMetres(line);
// A hair of slack, so a line exactly a whole number of stretches long takes no extra one.
const needed = Math.max(1, Math.ceil(total / OVERPASS_STRETCH_M - 1e-9));
if (needed === 1) return { stretches: [line], capped: false };
const length = total / needed;
// The last stretch ends at the line's own end, not where adding up the lengths lands.
const end = (index: number) => (index + 1 === needed ? total : (index + 1) * length);
const stretches = Array.from({ length: Math.min(needed, MAX_OVERPASS_STRETCHES) }, (_, index) =>
sliceAtMeters(line, index * length, end(index)),
);
return { stretches, capped: needed > MAX_OVERPASS_STRETCHES };
}
interface AroundPath {
points: LatLng[];
/** How far from the simplified line a place may lie and still be near the real one. */
radiusM: number;
bbox: { south: number; west: number; north: number; east: number };
}
/**
* The line as Overpass' `around` filter takes it: simplified until it has at
* most a hundred and twenty points, the reach widened by what the
* simplification moved it, and the box that holds it all, so the query looks
* at the candidates of that box only.
*/
export function aroundPath(line: LatLng[], corridorM: number): AroundPath {
let toleranceM = Math.max(10, corridorM / 10);
let points = simplifyLine(line, toleranceM / 1000);
while (points.length > MAX_AROUND_POINTS) {
toleranceM *= 2;
points = simplifyLine(line, toleranceM / 1000);
}
const radiusM = Math.ceil(corridorM + toleranceM);
const lats = points.map((point) => point.lat);
const lngs = points.map((point) => point.lng);
const padLat = radiusM / METRES_PER_DEGREE;
const widest = Math.max(...lats.map((lat) => Math.abs(lat)));
const padLng = radiusM / (METRES_PER_DEGREE * Math.max(0.01, Math.cos((widest * Math.PI) / 180)));
return {
points,
radiusM,
bbox: {
south: Math.min(...lats) - padLat,
west: Math.min(...lngs) - padLng,
north: Math.max(...lats) + padLat,
east: Math.max(...lngs) + padLng,
},
};
}
const coordinate = (value: number) => value.toFixed(5);
/**
* One Overpass query for every kind near the line: the candidates of the box,
* then those of them within reach of the line itself, with the short deadline
* of its own above.
*/
export function overpassAlongQuery(filters: readonly string[], path: AroundPath, cap: number): string {
const { south, west, north, east } = path.bbox;
const box = `(${[south, west, north, east].map(coordinate).join(',')})`;
const selectors = filters
.map((filter) => {
const [key, value] = filter.split('=');
return ` nwr["${key}"="${value}"]${box};`;
})
.join('\n');
const line = path.points.map((point) => `${coordinate(point.lat)},${coordinate(point.lng)}`).join(',');
return `[out:json][timeout:${OVERPASS_ALONG_QUERY_TIMEOUT_S}];\n(\n${selectors}\n)->.cand;\nnwr.cand(around:${path.radiusM},${line});\nout center tags ${cap + 25};`;
}
+122 -26
View File
@@ -8,6 +8,8 @@ import { getCountryFromCoords } from '../../utils/country-borders';
import { buildOsmDetails, parsePoiCategories, samePlace, toApiLang } from './maps.helpers';
import { POI_RESULT_CAP, type PoiSearchResult } from './providers/osm.client';
import {
INDEX_MAX_CATEGORY_CHARS,
INDEX_MAX_LIMIT,
POI_CATEGORY_TO_TREK,
indexRowTerm,
isOsmHit,
@@ -25,6 +27,8 @@ type PoiBbox = { south: number; west: number; north: number; east: number };
export interface IndexPoiPlan {
wanted: string[];
terms: string[];
/** The category each term answers for, so a request can be cut per category. */
kindOfTerm: ReadonlyMap<string, string>;
lat: number;
lng: number;
radius: number;
@@ -34,6 +38,11 @@ export interface IndexPoiPlan {
labelFor: (leaf: string | null, path: string | null) => string | undefined;
}
/** Whether the index has terms for a category, so it can answer it at all. */
export function indexKnowsCategory(key: string): boolean {
return (POI_CATEGORY_TO_TREK[key]?.length ?? 0) > 0;
}
/**
* The index query for a POI request, or null when the index cannot answer it.
*
@@ -44,28 +53,6 @@ export interface IndexPoiPlan {
* sixteen boxes, and each of those races four public mirrors.
*/
export function indexPoiPlan(category: string, bbox: PoiBbox, limit: number): IndexPoiPlan | null {
const wanted = parsePoiCategories(category);
// Which category each Overture term belongs to, so a hit can be labelled
// with the category that actually produced it rather than with the whole
// list. The client colours and groups its markers by that field.
const categoryOfTerm = new Map<string, string>();
for (const key of wanted) {
for (const term of POI_CATEGORY_TO_TREK[key] ?? []) categoryOfTerm.set(term, key);
}
// All or nothing: a category the index has no terms for has to be answered
// by Overpass, and a mixed answer would silently drop it.
const indexKnowsAll = wanted.length > 0 && wanted.every((key) => POI_CATEGORY_TO_TREK[key]?.length);
if (!indexKnowsAll) return null;
// A row belongs to the term whose path it lies under, not to one it is merely
// spelled like: the leaf alone is rarely a term (`italian_restaurant` sits
// under `food_and_drink>restaurant`), and falling through to wanted[0] then
// labelled it with whichever pill the user tapped first, so a trattoria came
// back as a petrol station. The most specific term wins, so a water park
// answers the activity pill rather than the park it sits under.
const labelFor = (leaf: string | null, path: string | null): string | undefined => {
const term = indexRowTerm(categoryOfTerm.keys(), leaf, path);
return term === undefined ? undefined : categoryOfTerm.get(term);
};
const lat = (bbox.south + bbox.north) / 2;
const lng = (bbox.west + bbox.east) / 2;
// Half the diagonal, so the circle covers the viewport corners rather
@@ -76,12 +63,117 @@ export function indexPoiPlan(category: string, bbox: PoiBbox, limit: number): In
(bbox.east - bbox.west) * 111_320 * Math.cos((lat * Math.PI) / 180),
) / 2,
);
return indexPoiPlanAround(category, { lat, lng }, reach, limit);
}
/** The same plan for a circle the caller chose: a viewport's, or one bead of a line searched along. */
export function indexPoiPlanAround(
category: string,
centre: { lat: number; lng: number },
reach: number,
limit: number,
): IndexPoiPlan | null {
const wanted = parsePoiCategories(category);
// Which category each Overture term belongs to, so a hit can be labelled
// with the category that actually produced it rather than with the whole
// list. The client colours and groups its markers by that field.
const categoryOfTerm = new Map<string, string>();
for (const key of wanted) {
for (const term of POI_CATEGORY_TO_TREK[key] ?? []) categoryOfTerm.set(term, key);
}
// All or nothing: a category the index has no terms for has to be answered
// by Overpass, and a mixed answer would silently drop it.
if (wanted.length === 0 || !wanted.every(indexKnowsCategory)) return null;
// A row belongs to the term whose path it lies under, not to one it is merely
// spelled like: the leaf alone is rarely a term (`italian_restaurant` sits
// under `food_and_drink>restaurant`), and falling through to wanted[0] then
// labelled it with whichever pill the user tapped first, so a trattoria came
// back as a petrol station. The most specific term wins, so a water park
// answers the activity pill rather than the park it sits under.
const labelFor = (leaf: string | null, path: string | null): string | undefined => {
const term = indexRowTerm(categoryOfTerm.keys(), leaf, path);
return term === undefined ? undefined : categoryOfTerm.get(term);
};
const radius = Math.min(20000, Math.max(300, reach));
// The same budget the Overpass path spends: per category, capped, so a
// mixed search does not spend the whole allowance on whichever kind
// happens to be densest.
const cap = Math.min(limit * wanted.length, POI_RESULT_CAP);
return { wanted, terms: [...categoryOfTerm.keys()], lat, lng, radius, reach, cap, labelFor };
const terms = [...categoryOfTerm.keys()];
return { wanted, terms, kindOfTerm: categoryOfTerm, lat: centre.lat, lng: centre.lng, radius, reach, cap, labelFor };
}
/** One request to the index: the comma-joined terms it asks for and how many rows. */
interface IndexRequest {
category: string;
limit: number;
}
/** Terms joined with commas into as few lists as the service takes, none longer than its limit. */
function packTerms(terms: readonly string[]): string[] {
return terms.reduce<string[]>((lists, term) => {
const last = lists.at(-1);
if (last !== undefined && last.length + 1 + term.length <= INDEX_MAX_CATEGORY_CHARS) {
lists[lists.length - 1] = `${last},${term}`;
} else lists.push(term);
return lists;
}, []);
}
/**
* The requests that answer a plan within the service's limits. One request,
* exactly as before, while the whole plan fits; otherwise one per category
* (its terms packed into lists the service takes), each with that category's
* share of the budget. A plan of several categories used to ask for their
* budgets together, and above 100 rows the service refused the request.
*/
export function indexRequests(plan: IndexPoiPlan): IndexRequest[] {
const all = plan.terms.join(',');
if (plan.cap <= INDEX_MAX_LIMIT && all.length <= INDEX_MAX_CATEGORY_CHARS) {
return [{ category: all, limit: plan.cap }];
}
return indexRequestsPerKind(plan);
}
/**
* One request per category, each with its share of the budget and its terms
* packed into lists the service takes. The search along a tour always asks
* this way, so the restaurants of a city centre cannot take the place of its
* one market among the nearest rows.
*/
export function indexRequestsPerKind(plan: IndexPoiPlan): IndexRequest[] {
const share = Math.max(1, Math.min(INDEX_MAX_LIMIT, Math.floor(plan.cap / plan.wanted.length)));
return plan.wanted.flatMap((key) =>
packTerms(plan.terms.filter((term) => plan.kindOfTerm.get(term) === key)).map((category) => ({
category,
limit: share,
})),
);
}
/** Every term the index is asked by, whichever kind asks for it. */
const EVERY_TERM = Object.values(POI_CATEGORY_TO_TREK).flat();
/**
* Whether a row's most specific known term is one an asked kind asks for. A
* water park lies under the parks' path, but `activity` names its own path for
* it, so a search for parks alone does not list it; a row no term knows is
* left to {@link belonging}. The search along a tour asks this; the explore
* pill keeps every row its pills' paths hold.
*/
export function ownedByAsked(
row: { category: string | null; categoryPath: string | null },
asked: readonly string[],
): boolean {
const term = indexRowTerm(EVERY_TERM, row.category, row.categoryPath);
return term === undefined || asked.some((kind) => POI_CATEGORY_TO_TREK[kind]?.includes(term));
}
/** The rows of several pages as one list, each place once, in the order they came. */
export function mergeIndexPages<T extends { gers: string }>(pages: readonly T[][]): T[] {
const byId = new Map<string, T>();
for (const row of pages.flat()) if (!byId.has(row.gers)) byId.set(row.gers, row);
return [...byId.values()];
}
/**
@@ -100,10 +192,13 @@ export function indexPoiPlan(category: string, bbox: PoiBbox, limit: number): In
export function indexPoiAnswer(
found: (TrekPlace & { categoryPath?: string | null })[],
plan: IndexPoiPlan,
pageFull: boolean,
): PoiSearchResult {
const { wanted, labelFor, cap, radius, reach } = plan;
// Pages asked per category can together run past the cap.
const kept = belonging(found, plan).slice(0, cap);
return {
pois: belonging(found, plan).map((p) => ({
pois: kept.map((p) => ({
osm_id: `gers:${p.gers}`,
name: p.name,
lat: p.lat,
@@ -133,8 +228,9 @@ export function indexPoiAnswer(
})),
source: 'trek-places' as const,
// The page the index sent, not what was left of it: a full page means more
// places, however many of them this one had to leave out.
truncated: found.length >= cap,
// places, however many of them this one had to leave out. Pages asked per
// category say so for themselves, and their sum may run past the cap.
truncated: pageFull || found.length > cap,
// A wide viewport is narrowed here too, and the caller is told so
// for the same reason the Overpass path tells it.
clamped: radius < reach,
+4
View File
@@ -380,6 +380,10 @@ export const CATEGORY_OSM_FILTERS: Record<string, string[]> = {
bike_repair: ['amenity=bicycle_repair_station', 'shop=bicycle'],
// A city walk's market (CW-05): the square itself, not the shops of a mall as `shopping` has them.
market: ['amenity=marketplace'],
// A city walk's museums and galleries (CW-05), without the theatres and public art of `museum`.
museum_gallery: ['tourism=museum', 'tourism=gallery'],
// A city walk's parks and gardens (CW-05), without the beaches and summits of `nature`.
park: ['leisure=park', 'leisure=garden'],
};
export const POI_CATEGORY_KEYS = Object.keys(CATEGORY_OSM_FILTERS);
+2
View File
@@ -12,6 +12,7 @@ import { MapsService } from './maps.service';
import { PlaceDetailsResolver } from './place-details.resolver';
import { PlacePhotoResolver } from './place-photo.resolver';
import { PlacesProviderSelector } from './places-provider.selector';
import { PoisAlongResolver } from './pois-along.resolver';
import { GooglePlacesClient } from './providers/google-places.provider';
import { OsmClient } from './providers/osm.client';
import { WikimediaClient } from './providers/wikimedia.client';
@@ -54,6 +55,7 @@ import { Module } from '@nestjs/common';
PlacePhotoResolver,
MapsUrlResolver,
PlaceDetailsResolver,
PoisAlongResolver,
],
exports: [MapsService, GooglePlacesClient, OsmClient, WikimediaClient],
})
+36 -7
View File
@@ -4,13 +4,21 @@ import type { AppSettingsRepository } from '../../db/repositories/AppSettings.re
import type { GeoLane } from '../geo/nominatim.client';
import { PlacePhotoCacheService } from '../place-photos/place-photo-cache.service';
import type { ApiKeySource } from '../settings/instance-api-keys';
import { belonging, indexPoiAnswer, indexPoiPlan, indexSuggestions } from './maps-index.helpers';
import {
belonging,
indexPoiAnswer,
indexPoiPlan,
indexRequests,
indexSuggestions,
mergeIndexPages,
} from './maps-index.helpers';
import { NEARBY_DEFAULT_LIMIT, NEARBY_DEFAULT_RADIUS_M, nearbyCacheKey, nearestFirst } from './maps-nearby.helpers';
import { MapsUrlResolver, type ResolvedMapsUrl } from './maps-url.resolver';
import { toApiLang, mergeSearchResults } from './maps.helpers';
import { PlaceDetailsResolver } from './place-details.resolver';
import { PlacePhotoResolver } from './place-photo.resolver';
import { PlacesProviderSelector, type KeyedProvider } from './places-provider.selector';
import { PoisAlongResolver, type PoisAlongResult } from './pois-along.resolver';
import type { AmapPlacesProvider } from './providers/amap.provider';
import { GooglePlacesClient } from './providers/google-places.provider';
import { OsmClient, type PoiSearchResult } from './providers/osm.client';
@@ -75,6 +83,7 @@ export class MapsService {
private readonly photos: PlacePhotoResolver,
private readonly links: MapsUrlResolver,
private readonly placeDetails: PlaceDetailsResolver,
private readonly along: PoisAlongResolver,
) {}
private async isSettingDisabled(key: string): Promise<boolean> {
@@ -209,13 +218,17 @@ export class MapsService {
const plan = indexPoiPlan(category, bbox, limit);
if (this.trekPlacesEnabled() && plan) {
try {
const found = await trekPlacesNearby(plan.lat, plan.lng, {
radius: plan.radius,
limit: plan.cap,
category: plan.terms.join(','),
});
// One request while the plan fits the service's limits, one per category beyond them.
const pages = await Promise.all(
indexRequests(plan).map(async ({ category: terms, limit: rows }) => ({
rows,
found: await trekPlacesNearby(plan.lat, plan.lng, { radius: plan.radius, limit: rows, category: terms }),
})),
);
const found = mergeIndexPages(pages.map((page) => page.found));
const pageFull = pages.some((page) => page.found.length >= page.rows);
// A page of near misses only is a miss too, not an empty answer.
if (belonging(found, plan).length > 0) return indexPoiAnswer(found, plan);
if (belonging(found, plan).length > 0) return indexPoiAnswer(found, plan, pageFull);
} catch (err: unknown) {
console.warn('TREK Places nearby failed, falling back:', (err as Error).message);
}
@@ -223,6 +236,22 @@ export class MapsService {
return this.osm.searchOverpassPois(category, bbox, lang, limit);
}
/**
* Places of some kinds near a line (PLN-02): the index in circles along it,
* Overpass for the kinds the index does not know, side by side. Never calls
* Google. `limit` is each kind's budget per source; `failed` names the kinds
* no source could be asked for.
*/
poisAlong(
categories: string[],
line: { lat: number; lng: number }[],
corridorM: number,
lang?: string,
limit = 30,
): Promise<PoisAlongResult> {
return this.along.search({ categories, line, corridorM, lang, limit }, this.trekPlacesEnabled());
}
// ── Keys and the keyed provider (resolved by PlacesProviderSelector) ─────
/** The Places credential for this request and where it came from (#1939). */
+182
View File
@@ -0,0 +1,182 @@
/**
* Places of some kinds near a line (PLN-02, CW-05), from the TREK index and
* OpenStreetMap side by side.
*
* The kinds the index knows are asked in circles strung along the line, the way
* the explore pill asks it for a viewport: one small request per kind and
* circle, each inside the service's limits, a few at a time. An empty
* circle is an answer, so those kinds never wait on Overpass while the index
* answers. The kinds it does not know (a viewpoint, a tap, a hut) go to
* Overpass at the same time, one query near each stretch of the whole line,
* with a short deadline. A source that fails is logged and its kinds named in
* `failed`, so the caller can say what could not be searched instead of
* reporting nothing found.
*
* MapsService.poisAlong delegates here and hands in whether the index is
* switched on, which is a deployment property it owns.
*/
import { logWarn } from '../audit/audit-log.logger';
import { alongPlan, overpassStretches, type AlongPlan } from './maps-along.helpers';
import {
indexKnowsCategory,
indexPoiAnswer,
indexPoiPlanAround,
indexRequestsPerKind,
ownedByAsked,
} from './maps-index.helpers';
import type { OverpassPoi } from './maps.helpers';
import { OsmClient } from './providers/osm.client';
import { trekPlacesNearby } from './trek-places.client';
import { Injectable } from '@nestjs/common';
import type { LatLng } from '@trek/shared/roadtrip';
/** How many index requests are in flight at once, so one search never floods the service. */
const PARALLEL_INDEX_REQUESTS = 8;
/** How many stretches one source asks Overpass for at once, so the public mirrors are not flooded. */
const PARALLEL_OVERPASS_STRETCHES = 3;
/** What is searched for along which line: the kinds, how far from it, and each kind's budget per source. */
interface PoisAlongQuery {
categories: string[];
line: LatLng[];
corridorM: number;
lang?: string;
limit: number;
}
export interface PoisAlongResult {
pois: OverpassPoi[];
/** The kinds no source could be asked for right now: their places are missing, not absent. */
failed: string[];
/** Some circles or stretches of the line could not be searched; the places of the others are there. */
partial: boolean;
/** A source had more places than it answered with. */
truncated: boolean;
/** The line was longer than one search covers; only its first part was searched. */
capped: boolean;
}
/** What one request of a source brings back. */
interface Page {
pois: OverpassPoi[];
truncated: boolean;
}
interface Batched extends Page {
/** How many of the source's requests answered, and how many failed. */
answered: number;
missed: number;
/** Why requests failed, or null when every one answered. */
error: string | null;
}
interface SourceAnswer extends Batched {
/** The source was asked along the start of the line only. */
capped: boolean;
}
const NOTHING: SourceAnswer = { pois: [], truncated: false, answered: 0, missed: 0, error: null, capped: false };
const reason = (err: unknown) => (err instanceof Error ? err.message : String(err));
/** Each place once, as the first circle or source that found it has it: neighbouring circles overlap. */
function oncePerPlace(pois: OverpassPoi[]): OverpassPoi[] {
const seen = new Map<string, OverpassPoi>();
for (const poi of pois) if (!seen.has(poi.osm_id)) seen.set(poi.osm_id, poi);
return [...seen.values()];
}
/**
* Requests a few at a time, each batch after the last, so no more than a
* batch is ever in flight; a failed one leaves the others.
*/
async function inBatches(requests: Array<() => Promise<Page>>, parallel: number): Promise<Batched> {
const batches = Array.from({ length: Math.ceil(requests.length / parallel) }, (_, index) =>
requests.slice(index * parallel, (index + 1) * parallel),
);
const settled = await batches.reduce<Promise<PromiseSettledResult<Page>[]>>(
async (done, batch) => [...(await done), ...(await Promise.allSettled(batch.map((ask) => ask())))],
Promise.resolve([]),
);
const pages = settled.flatMap((entry) => (entry.status === 'fulfilled' ? [entry.value] : []));
const misses = settled.flatMap((entry) => (entry.status === 'rejected' ? [reason(entry.reason)] : []));
return {
pois: pages.flatMap((page) => page.pois),
truncated: pages.some((page) => page.truncated),
answered: pages.length,
missed: misses.length,
error: misses.length ? `${misses.length} of ${settled.length} requests failed: ${misses[0]}` : null,
};
}
/** A source asked that answered none of its requests: its kinds could not be searched. */
const unanswered = (answer: SourceAnswer) => answer.missed > 0 && answer.answered === 0;
@Injectable()
export class PoisAlongResolver {
constructor(private readonly osm: OsmClient) {}
async search(query: PoisAlongQuery, indexEnabled: boolean): Promise<PoisAlongResult> {
const plan = alongPlan(query.line, query.corridorM);
const indexed = indexEnabled ? query.categories.filter(indexKnowsCategory) : [];
const rest = query.categories.filter((key) => !indexed.includes(key));
// Only an index that answered no circle at all hands its kinds to Overpass,
// once, while the other kinds are still being asked there rather than after.
const indexPart = this.askIndex(indexed, plan, query.limit).then(async (index) => ({
index,
fallback: indexed.length > 0 && index.answered === 0 ? await this.askOverpass(indexed, query) : NOTHING,
}));
const [{ index, fallback }, overpass] = await Promise.all([indexPart, this.askOverpass(rest, query)]);
if (index.error) logWarn(`[Maps] TREK places index along a line: ${index.error}`);
for (const answer of [overpass, fallback]) {
if (answer.error) logWarn(`[Maps] OpenStreetMap along a line: ${answer.error}`);
}
const sources = [index, overpass, fallback];
return {
pois: oncePerPlace([...index.pois, ...overpass.pois, ...fallback.pois]),
failed: [...(unanswered(overpass) ? rest : []), ...(unanswered(fallback) ? indexed : [])],
partial: sources.some((answer) => answer.answered > 0 && answer.missed > 0),
truncated: sources.some((answer) => answer.truncated),
// A source that answered nothing searched nothing: its kinds are failed or asked of Overpass instead.
capped: sources.some((answer) => answer.answered > 0 && answer.capped),
};
}
/** The index kinds in every circle, a few requests at a time; a failed request leaves the others. */
private async askIndex(kinds: string[], plan: AlongPlan, limit: number): Promise<SourceAnswer> {
// No kinds make no plan, and so no request.
const requests = plan.beads.flatMap((bead) => {
const circle = indexPoiPlanAround(kinds.join(','), bead, bead.radiusM, limit);
return circle
? indexRequestsPerKind(circle).map((request) => async (): Promise<Page> => {
const found = await trekPlacesNearby(circle.lat, circle.lng, {
radius: circle.radius,
limit: request.limit,
category: request.category,
});
// A row goes to the kind that names its path most closely: a water park is no park.
const own = found.filter((row) => ownedByAsked(row, kinds));
const answer = indexPoiAnswer(own, circle, found.length >= request.limit);
return { pois: answer.pois, truncated: answer.truncated };
})
: [];
});
return { ...(await inBatches(requests, PARALLEL_INDEX_REQUESTS)), capped: plan.capped };
}
/**
* The other kinds near each stretch of the whole line, one Overpass query
* per stretch; nothing to ask is nothing found.
*/
private async askOverpass(kinds: string[], query: PoisAlongQuery): Promise<SourceAnswer> {
if (!kinds.length) return NOTHING;
const along = overpassStretches(query.line);
const asked = kinds.join(',');
const requests = along.stretches.map(
(stretch) => () => this.osm.searchOverpassPoisAlong(asked, stretch, query.corridorM, query.lang, query.limit),
);
const answer = await inBatches(requests, PARALLEL_OVERPASS_STRETCHES);
return { ...answer, error: answer.error && `${kinds.join(', ')}: ${answer.error}`, capped: along.capped };
}
}
+175 -71
View File
@@ -17,6 +17,7 @@
* (lint:boundaries holds that).
*/
import { nominatimFetch, type GeoLane } from '../../geo/nominatim.client';
import { OVERPASS_ALONG_QUERY_TIMEOUT_S, aroundPath, overpassAlongQuery } from '../maps-along.helpers';
import { nearbyOverpassQuery, overpassNearbyRecords } from '../maps-nearby.helpers';
import {
UA,
@@ -37,6 +38,7 @@ import {
import { readWikiIdentity } from './wiki-identity';
import { Injectable } from '@nestjs/common';
import { normalizePlaceWebsite } from '@trek/shared';
import type { LatLng } from '@trek/shared/roadtrip';
function nominatimCategory(item: { class?: string; type?: string }): string | null {
if (!item.class || !item.type || item.type === 'yes') return null;
@@ -130,14 +132,14 @@ export const POI_RESULT_CAP = 240;
// valid JSON. Throws {status:502} only if every mirror fails. Racing (rather than
// trying one-by-one) keeps latency at the fastest reachable mirror instead of the
// sum of every dead mirror's timeout.
async function overpassFetch(query: string): Promise<OverpassPoiElement[]> {
async function overpassFetch(query: string, timeoutMs = OVERPASS_TIMEOUT_MS): Promise<OverpassPoiElement[]> {
const body = `data=${encodeURIComponent(query)}`;
const controllers: AbortController[] = [];
const attempt = async (url: string): Promise<OverpassPoiElement[]> => {
const ctrl = new AbortController();
controllers.push(ctrl);
const timer = setTimeout(() => ctrl.abort(), OVERPASS_TIMEOUT_MS);
const timer = setTimeout(() => ctrl.abort(), timeoutMs);
try {
const res = await fetch(url, {
method: 'POST',
@@ -188,6 +190,133 @@ async function overpassFetch(query: string): Promise<OverpassPoiElement[]> {
}
}
/** The kinds of a POI request and the OSM selectors that answer each, every selector labelled with its kind. */
interface PoiFilters {
categories: string[];
filters: string[];
categoryOfFilter: Map<string, string>;
}
/** One or several categories as Overpass selectors; an unknown one refuses the whole request. */
function poiFilters(category: string): PoiFilters {
// Each OSM selector belongs to exactly one category, so a hit can still be
// labelled with the category it answered.
const categories = parsePoiCategories(category);
if (!categories.length) throw Object.assign(new Error('Unknown POI category'), { status: 400 });
const categoryOfFilter = new Map<string, string>();
for (const key of categories) {
const own = CATEGORY_OSM_FILTERS[key];
if (!own) throw Object.assign(new Error('Unknown POI category'), { status: 400 });
for (const f of own) categoryOfFilter.set(f, key);
}
return { categories, filters: [...categoryOfFilter.keys()], categoryOfFilter };
}
/** Keeps an answer in the POI cache, dropping the oldest entry once the cache is full. */
function cachePoiAnswer(cacheKey: string, value: PoiSearchResult): void {
// FIFO eviction: a Map preserves insertion order, so the first key is the oldest.
if (POI_CACHE.size >= POI_CACHE_MAX) POI_CACHE.delete(POI_CACHE.keys().next().value as string);
POI_CACHE.set(cacheKey, { at: Date.now(), value });
}
/** A fresh cached answer, or undefined; an expired one is dropped on the way. */
function cachedPoiAnswer(cacheKey: string): PoiSearchResult | undefined {
const cached = POI_CACHE.get(cacheKey);
if (cached && Date.now() - cached.at < POI_CACHE_TTL_MS) return cached.value;
if (cached) POI_CACHE.delete(cacheKey); // expired: drop it before refetching
return undefined;
}
/**
* The kinds whose places OSM rarely names, kept unnamed by the search along a
* tour: a tap, a hut, a bench with a view. An unnamed garden or memorial
* plaque is no place to suggest, so every other kind still needs a name.
*/
const KEPT_UNNAMED_ALONG: ReadonlySet<string> = new Set([
'drinking_water',
'toilets',
'shelter',
'picnic',
'viewpoint',
'peak',
'slipway',
'bike_repair',
]);
/**
* Overpass elements as POI rows, each labelled with the category its selector
* belongs to. An unnamed element is dropped unless its category is one of
* `keptUnnamed`; a shut-down place never comes back.
*/
function readPois(
elements: OverpassPoiElement[],
match: PoiFilters,
osmLang: string,
keptUnnamed: ReadonlySet<string>,
): OverpassPoi[] {
const { filters, categoryOfFilter, categories } = match;
const pois: OverpassPoi[] = [];
for (const el of elements) {
const tags = el.tags || {};
const matched =
filters.find((f) => {
const [k, v] = f.split('=');
return tags[k] === v;
}) || filters[0];
const category = categoryOfFilter.get(matched) ?? categories[0];
// `operator` comes last but matters for the road categories: petrol stations,
// charging points and service areas are routinely mapped with an operator and no
// name, and dropping those would empty the road trip corridor over long stretches.
const name = tags[`name:${osmLang}`] || tags['int_name'] || tags.name || tags.brand || tags.operator || null;
if (!name && !keptUnnamed.has(category)) continue; // unnamed POIs aren't useful to add to a plan
// A shut-down place is not somewhere to plan a visit (#1341). OSM usually
// re-tags one with a `disused:`/`abandoned:` prefix, and those never match
// the selectors above, but plenty keep their original tag and gain a marker
// instead, and those do come back. `opening_hours=closed`/`off` is the same
// statement in the hours field.
if (tags.disused === 'yes' || tags.abandoned === 'yes') continue;
if (tags.opening_hours === 'closed' || tags.opening_hours === 'off') continue;
const lat = el.lat ?? el.center?.lat;
const lng = el.lon ?? el.center?.lon;
if (lat == null || lng == null) continue;
const addr =
[tags['addr:street'], tags['addr:housenumber'], tags['addr:postcode'], tags['addr:city']]
.filter(Boolean)
.join(' ') || null;
pois.push({
osm_id: `${el.type}:${el.id}`,
name: name ?? '',
lat,
lng,
category,
poi_type: matched,
address: addr,
website: normalizePlaceWebsite(tags.website) ?? normalizePlaceWebsite(tags['contact:website']),
phone: tags.phone || tags['contact:phone'] || null,
opening_hours: tags.opening_hours || null,
cuisine: tags.cuisine || null,
brand: tags.brand || tags.operator || null,
// Only the plain Q-id form is passed on; anything else would be a lookup we
// would have to guess at.
brand_wikidata: /^Q[0-9]+$/.test(tags['brand:wikidata'] || '') ? tags['brand:wikidata'] : null,
// Only where it means something. Every POI carries `capacity` and `fee` for its
// own reasons (a restaurant's capacity is seats), so reading them as charging
// data anywhere else would be wrong on most of the map.
charging: category === 'charging' ? readChargingInfo(tags) : null,
source: 'openstreetmap',
});
}
return pois;
}
/**
* How long the search along a line waits for Overpass: the query's own
* deadline and two seconds to hand the answer back. It sits inside one request
* a person is waiting on, beside the index, so it gives up well before the
* explore pill's budget, and OVERPASS_TIMEOUT_MS does not apply to it.
*/
const OVERPASS_ALONG_TIMEOUT_MS = (OVERPASS_ALONG_QUERY_TIMEOUT_S + 2) * 1000;
@Injectable()
export class OsmClient {
// ── Nominatim search ───────────────────────────────────────────────────────
@@ -542,17 +671,9 @@ export class OsmClient {
lang?: string,
limit = 60,
): Promise<PoiSearchResult> {
// One or several categories in one query. Each OSM selector belongs to exactly one
// category, so a hit can still be labelled with the category it answered.
const categories = parsePoiCategories(category);
if (!categories.length) throw Object.assign(new Error('Unknown POI category'), { status: 400 });
const categoryOfFilter = new Map<string, string>();
for (const key of categories) {
const own = CATEGORY_OSM_FILTERS[key];
if (!own) throw Object.assign(new Error('Unknown POI category'), { status: 400 });
for (const f of own) categoryOfFilter.set(f, key);
}
const filters = [...categoryOfFilter.keys()];
// One or several categories in one query.
const match = poiFilters(category);
const { categories, filters } = match;
// Each category gets its own share of the cap, or a mixed search would spend the
// whole budget on whichever kind happens to be densest.
const cap = Math.min(limit * categories.length, POI_RESULT_CAP);
@@ -572,9 +693,8 @@ export class OsmClient {
// Serve repeat pans/toggles of the same area straight from the cache.
const cacheKey = `${[...categories].sort((a, b) => a.localeCompare(b)).join('+')}|${osmLang}|${south.toFixed(2)},${west.toFixed(2)},${north.toFixed(2)},${east.toFixed(2)}|${cap}`;
const cached = POI_CACHE.get(cacheKey);
if (cached && Date.now() - cached.at < POI_CACHE_TTL_MS) return cached.value;
if (cached) POI_CACHE.delete(cacheKey); // expired — drop it before refetching
const cached = cachedPoiAnswer(cacheKey);
if (cached) return cached;
// Overpass wants the box as (south,west,north,east) = (minLat,minLng,maxLat,maxLng).
const box = `(${south},${west},${north},${east})`;
@@ -588,63 +708,47 @@ export class OsmClient {
// the result count in one round-trip.
const query = `[out:json][timeout:${OVERPASS_QUERY_TIMEOUT_S}];\n(\n${selectors}\n);\nout center tags ${cap + 25};`;
const elements = await overpassFetch(query);
const pois: OverpassPoi[] = [];
for (const el of elements) {
const tags = el.tags || {};
// `operator` comes last but matters for the road categories: petrol stations,
// charging points and service areas are routinely mapped with an operator and no
// name, and dropping those would empty the road trip corridor over long stretches.
const name = tags[`name:${osmLang}`] || tags['int_name'] || tags.name || tags.brand || tags.operator || null;
if (!name) continue; // unnamed POIs aren't useful to add to a plan
// A shut-down place is not somewhere to plan a visit (#1341). OSM usually
// re-tags one with a `disused:`/`abandoned:` prefix, and those never match
// the selectors above — but plenty keep their original tag and gain a marker
// instead, and those do come back. `opening_hours=closed`/`off` is the same
// statement in the hours field.
if (tags.disused === 'yes' || tags.abandoned === 'yes') continue;
if (tags.opening_hours === 'closed' || tags.opening_hours === 'off') continue;
const lat = el.lat ?? el.center?.lat;
const lng = el.lon ?? el.center?.lon;
if (lat == null || lng == null) continue;
const matched =
filters.find((f) => {
const [k, v] = f.split('=');
return tags[k] === v;
}) || filters[0];
const addr =
[tags['addr:street'], tags['addr:housenumber'], tags['addr:postcode'], tags['addr:city']]
.filter(Boolean)
.join(' ') || null;
pois.push({
osm_id: `${el.type}:${el.id}`,
name,
lat,
lng,
category: categoryOfFilter.get(matched) ?? categories[0],
poi_type: matched,
address: addr,
website: normalizePlaceWebsite(tags.website) ?? normalizePlaceWebsite(tags['contact:website']),
phone: tags.phone || tags['contact:phone'] || null,
opening_hours: tags.opening_hours || null,
cuisine: tags.cuisine || null,
brand: tags.brand || tags.operator || null,
// Only the plain Q-id form is passed on; anything else would be a lookup we
// would have to guess at.
brand_wikidata: /^Q[0-9]+$/.test(tags['brand:wikidata'] || '') ? tags['brand:wikidata'] : null,
// Only where it means something. Every POI carries `capacity` and `fee` for its
// own reasons — a restaurant's capacity is seats — so reading them as charging
// data anywhere else would be wrong on most of the map.
charging: categoryOfFilter.get(matched) === 'charging' ? readChargingInfo(tags) : null,
source: 'openstreetmap',
});
}
const pois = readPois(await overpassFetch(query), match, osmLang, new Set());
const truncated = pois.length > cap;
const value: PoiSearchResult = { pois: pois.slice(0, cap), source: 'openstreetmap', truncated, clamped };
// FIFO eviction: a Map preserves insertion order, so the first key is the oldest.
if (POI_CACHE.size >= POI_CACHE_MAX) POI_CACHE.delete(POI_CACHE.keys().next().value as string);
POI_CACHE.set(cacheKey, { at: Date.now(), value });
cachePoiAnswer(cacheKey, value);
return value;
}
/**
* POIs of one or several categories near a line (PLN-02): one Overpass query
* for the candidates of the line's box within reach of the line itself, so
* the cap is spent on the corridor rather than on the box. Unnamed taps,
* huts and the like stay, because they are what a hike looks for, while an
* unnamed garden or cafe is dropped as on the explore pill. A short deadline
* of its own; failing throws as the explore pill's search does.
*/
async searchOverpassPoisAlong(
category: string,
line: LatLng[],
corridorM: number,
lang?: string,
limit = 30,
): Promise<PoiSearchResult> {
const match = poiFilters(category);
const cap = Math.min(limit * match.categories.length, POI_RESULT_CAP);
const path = aroundPath(line, corridorM);
const osmLang = toApiLang(lang).split('-')[0].toLowerCase();
const kinds = [...match.categories].sort((a, b) => a.localeCompare(b)).join('+');
const points = path.points.map((point) => `${point.lat.toFixed(5)},${point.lng.toFixed(5)}`).join(';');
const cacheKey = `along|${kinds}|${osmLang}|${path.radiusM}|${points}|${cap}`;
const cached = cachedPoiAnswer(cacheKey);
if (cached) return cached;
const elements = await overpassFetch(overpassAlongQuery(match.filters, path, cap), OVERPASS_ALONG_TIMEOUT_MS);
const pois = readPois(elements, match, osmLang, KEPT_UNNAMED_ALONG);
const value: PoiSearchResult = {
pois: pois.slice(0, cap),
source: 'openstreetmap',
truncated: pois.length > cap,
clamped: false,
};
cachePoiAnswer(cacheKey, value);
return value;
}
}
@@ -28,6 +28,15 @@ const TIMEOUT_MS = 3500;
/** A search answer is a few kB. A megabyte means something is wrong upstream. */
const MAX_BYTES = 1_000_000;
/**
* The service's own limits on one /v1/nearby request: it refuses a `limit`
* above the first and a `category` list longer than the second with a 422.
* A refused request reads like a failure to the caller, so a request is cut to
* fit them before it leaves (maps-index.helpers' indexRequests).
*/
export const INDEX_MAX_LIMIT = 100;
export const INDEX_MAX_CATEGORY_CHARS = 200;
/**
* The area download is the one call that is neither short nor interactive.
*
@@ -391,6 +400,15 @@ export const POI_CATEGORY_TO_TREK: Record<string, string[]> = {
charging: ['travel_and_transportation>fueling_station>ev_charging_station'],
rest_area: ['travel_and_transportation>ground_transport_facility_or_service>road_structures_and_service>rest_stop'],
campsite: ['lodging>campground', 'lodging>rv_park'],
// What the search along a tour asks for (PLN-02, CW-05), each path checked
// against a live answer of the index: museums and galleries alone, without
// the theatres and cinemas of `museum`; parks and gardens alone, without the
// beaches and mountains `nature` brings; the market square and its farmers'
// and night markets; a summit.
museum_gallery: ['arts_and_entertainment>museum', 'arts_and_entertainment>arts_and_crafts_space>art_gallery'],
park: ['sports_and_recreation>park', 'geographic_entities>built_feature>garden'],
market: ['shopping>market'],
peak: ['geographic_entities>land_feature>mountain'],
};
/**
@@ -16,7 +16,6 @@ import {
type TourPoiSearchRequest,
type TourPoiSearchResponse,
} from '@trek/shared';
import { corridorTiles, simplifyLine } from '@trek/shared/roadtrip';
/** The map search's own categories each Tours category asks for. */
const MAPS_CATEGORIES: Record<TourPoiCategory, readonly string[]> = {
@@ -32,28 +31,24 @@ const MAPS_CATEGORIES: Record<TourPoiCategory, readonly string[]> = {
slipway: ['slipway'],
boat_rental: ['boat_rental'],
bike_repair: ['bike_repair'],
museum: ['museum'],
park: ['nature'],
// Museums and galleries alone, parks and gardens alone: the explore pill's
// `museum` also brings theatres and cinemas, its `nature` beaches and summits.
museum: ['museum_gallery'],
park: ['park'],
cafe: ['cafe'],
restaurant: ['restaurant'],
market: ['market'],
};
/**
* How many stretches of the line one search covers, each at most about half a
* degree, so a long tour is searched along its first stretches and the answer
* says so. Three are asked at a time, so the public mirrors are not flooded.
*/
const MAX_TILES = 12;
const PARALLEL_TILES = 3;
/** The most places one stretch is asked for. */
const PER_TILE_LIMIT = 60;
/** The most places of one kind the map search answers from each source. */
const PER_KIND_LIMIT = 30;
/** Within this many metres, two places of one name are one place mapped twice. */
const SAME_PLACE_M = 60;
function sameSpot(a: Pick<TourPoi, 'name' | 'lat' | 'lng'>, b: { name: string; lat: number; lng: number }): boolean {
if (a.name.trim().toLocaleLowerCase() !== b.name.trim().toLocaleLowerCase()) return false;
type MapsPoi = Awaited<ReturnType<MapsService['poisAlong']>>['pois'][number];
function withinSamePlace(a: Pick<TourPoi, 'lat' | 'lng'>, b: { lat: number; lng: number }): boolean {
const metresPerDegree = 111_320;
const dLat = (a.lat - b.lat) * metresPerDegree;
const dLng = (a.lng - b.lng) * metresPerDegree * Math.cos((a.lat * Math.PI) / 180);
@@ -65,13 +60,51 @@ function tourCategoryOf(mapsCategory: string, asked: readonly TourPoiCategory[])
}
/**
* PLN-02: places along a tour, searched on purpose. The line is cut into
* stretches as the road trip's corridor search does, each searched through
* the map search (the TREK places index first, OpenStreetMap after), the
* places kept that lie within the corridor of the line itself, nearest the
* start first. Nothing is written. A stretch that fails leaves the others'
* places and marks the answer partial; the distance is measured straight
* across to the line, never a way someone walked or paddled.
* The places found, each once and within the corridor, with where they lie.
* OpenStreetMap often maps one place twice, as a point and as its outline, and
* the index may hold it beside OpenStreetMap: one name in one spot is one
* place. An unnamed place (a tap, a bench) is never merged with another.
*/
function placesWithin(found: MapsPoi[], body: TourPoiSearchRequest, line: Array<[number, number]>): TourPoi[] {
const kept = new Map<string, TourPoi>();
const byName = new Map<string, TourPoi[]>();
for (const poi of found) {
const category = tourCategoryOf(poi.category, body.categories);
const near = nearnessToLine({ lat: poi.lat, lng: poi.lng }, line);
if (!category || !near || near.distanceM > body.corridor_m || kept.has(poi.osm_id)) continue;
const name = poi.name.trim().toLocaleLowerCase();
const namesakes = name ? (byName.get(name) ?? []) : [];
if (namesakes.some((other) => withinSamePlace(other, poi))) continue;
const place: TourPoi = {
id: poi.osm_id,
name: poi.name,
lat: poi.lat,
lng: poi.lng,
category,
kind: poi.poi_type,
source: poi.source,
address: poi.address,
website: poi.website,
phone: poi.phone,
opening_hours: poi.opening_hours,
distance_m: Math.round(near.distanceM),
along_m: Math.round(near.alongM),
};
kept.set(poi.osm_id, place);
if (name) byName.set(name, [...namesakes, place]);
}
return [...kept.values()];
}
/**
* PLN-02: places along a tour, searched on purpose. The map search asks the
* TREK places index in circles along the line and OpenStreetMap near it for
* the kinds the index does not know; the places kept are those within the
* corridor of the line itself, the nearest to it when there are more than one
* answer carries, listed from the start. Nothing is written. A kind no source
* could be asked for is named as unavailable, so a failed source never reads
* as nothing found; the distance is measured straight across to the line,
* never a way someone walked or paddled.
*/
@Injectable()
export class TourPoiSearchService {
@@ -82,65 +115,27 @@ export class TourPoiSearchService {
) {}
async search(body: TourPoiSearchRequest): Promise<TourPoiSearchResponse> {
const corridorKm = body.corridor_m / 1000;
// The contract's tuples, spelled out as pairs once for the measures below.
const line = body.line.map((point): [number, number] => [Number(point[0]), Number(point[1])]);
const simplified = simplifyLine(
const asked = [...new Set(body.categories.flatMap((category) => MAPS_CATEGORIES[category]))];
const along = await this.maps.poisAlong(
asked,
line.map(([lat, lng]) => ({ lat, lng })),
Math.max(0.05, corridorKm / 4),
body.corridor_m,
body.lang,
PER_KIND_LIMIT,
);
const tiles = corridorTiles(simplified, corridorKm);
const searched = tiles.slice(0, MAX_TILES);
const asked = [...new Set(body.categories.flatMap((category) => MAPS_CATEGORIES[category]))].join(',');
// Three stretches at a time, each batch after the last, so no more than three are ever in flight.
const batches = Array.from({ length: Math.ceil(searched.length / PARALLEL_TILES) }, (_, index) =>
searched.slice(index * PARALLEL_TILES, (index + 1) * PARALLEL_TILES),
);
const answers = await batches.reduce<
Promise<Array<PromiseSettledResult<Awaited<ReturnType<MapsService['pois']>>>>>
>(
async (done, batch) => [
...(await done),
...(await Promise.allSettled(batch.map((tile) => this.maps.pois(asked, tile, body.lang, PER_TILE_LIMIT)))),
],
Promise.resolve([]),
);
const found = new Map<string, TourPoi>();
let truncated = false;
for (const answer of answers) {
if (answer.status !== 'fulfilled') continue;
truncated ||= answer.value.truncated || answer.value.clamped;
for (const poi of answer.value.pois) {
const category = tourCategoryOf(poi.category, body.categories);
const near = nearnessToLine({ lat: poi.lat, lng: poi.lng }, line);
if (!category || !near || near.distanceM > body.corridor_m || found.has(poi.osm_id)) continue;
// OpenStreetMap often maps one place twice, as a point and as its outline: one name in one spot is one place.
if (poi.name && [...found.values()].some((other) => sameSpot(other, poi))) continue;
found.set(poi.osm_id, {
id: poi.osm_id,
name: poi.name,
lat: poi.lat,
lng: poi.lng,
category,
kind: poi.poi_type,
source: poi.source ?? 'openstreetmap',
address: poi.address,
website: poi.website,
phone: poi.phone,
opening_hours: poi.opening_hours,
distance_m: Math.round(near.distanceM),
along_m: Math.round(near.alongM),
});
}
}
const pois = [...found.values()].sort((a, b) => a.along_m - b.along_m || a.distance_m - b.distance_m);
const places = placesWithin(along.pois, body, line);
// The nearest to the line when there are too many, then in the order the tour meets them.
const nearest = [...places].sort((a, b) => a.distance_m - b.distance_m).slice(0, TOUR_POI_LIMIT);
return {
pois: pois.slice(0, TOUR_POI_LIMIT),
truncated: truncated || pois.length > TOUR_POI_LIMIT,
partial: answers.some((answer) => answer.status === 'rejected'),
capped: tiles.length > MAX_TILES,
pois: nearest.sort((a, b) => a.along_m - b.along_m || a.distance_m - b.distance_m),
truncated: along.truncated || places.length > TOUR_POI_LIMIT,
partial: along.partial,
capped: along.capped,
unavailable: body.categories.filter((category) =>
MAPS_CATEGORIES[category].every((mapsCategory) => along.failed.includes(mapsCategory)),
),
};
}
+1 -1
View File
@@ -158,7 +158,7 @@ export class ToursMcp {
@Tool({
name: 'search_tour_pois',
description:
'Search places along the saved line of a tour: what a hike, a bike tour or a paddle tour stops for (viewpoint, peak, shelter, drinking_water, food, toilets, picnic, campsite, sights, slipway, boat_rental, bike_repair for repair stations and bike shops), within corridor_m metres of the line. Answers each place with its source, kind, address, website and phone where known, opening hours as the source has them (a hint to check, never a promise), distance_m (straight across to the line, not a detour) and along_m (from the start along the line), nearest the start first, up to 60. partial says some stretches could not be searched, capped that only the first part of a long line was. Nothing is added to the tour or the trip.',
'Search places along the saved line of a tour: what a hike, a bike tour, a paddle tour or a city walk stops for (viewpoint, peak, shelter, drinking_water, food, toilets, picnic, campsite, sights, slipway, boat_rental, bike_repair for repair stations and bike shops, and for a city walk museum for museums and galleries, park for parks and gardens, cafe, restaurant and market), within corridor_m metres of the line. Answers each place with its source (TREK places index or OpenStreetMap), kind, address, website and phone where known, opening hours as the source has them (a hint to check, never a promise), distance_m (straight across to the line, not a detour) and along_m (from the start along the line); up to 60, the nearest to the line when more match, listed from the start. A place OpenStreetMap has no name for (a tap, a bench) comes with an empty name. unavailable lists the categories no source could be searched for right now: their places are missing, not absent, so ask again later rather than reporting none. partial says some stretches could not be searched, capped that only the first part of a long line was, truncated that more places matched. Nothing is added to the tour or the trip.',
inputSchema: {
tripId: idSchema,
placeId: idSchema.describe('The place id of the tour, as list_tours gives it'),