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
+26 -4
View File
@@ -57,7 +57,7 @@ const { journeyHooks } = vi.hoisted(() => ({
const db = createSnapshotTestDb();
// The map search behind the POI search (PLN-02): no network in a test.
const mapsPois = vi.fn();
const mapsPoisAlong = vi.fn();
const realtime = new FakeRealtimeService();
let orm: TestOrm;
@@ -102,7 +102,7 @@ describe('Tours planned e2e (real guards + temp SQLite)', () => {
.overrideProvider(JourneyDomainService)
.useValue(journeyHooks)
.overrideProvider(MapsService)
.useValue({ pois: mapsPois })
.useValue({ poisAlong: mapsPoisAlong })
.compile();
const nest = moduleRef.createNestApplication();
nest.use(cookieParser());
@@ -708,7 +708,7 @@ describe('Tours planned e2e (real guards + temp SQLite)', () => {
};
it('answers the places along a draft line to anyone who sees the trip, and writes nothing', async () => {
mapsPois.mockResolvedValue({ pois: [spring], source: 'openstreetmap', truncated: false, clamped: false });
mapsPoisAlong.mockResolvedValue({ pois: [spring], failed: [], partial: false, truncated: false, capped: false });
const places = await countRows(orm, Places);
const res = await request(server)
.post('/api/trips/5/tours/poi-search')
@@ -718,11 +718,33 @@ describe('Tours planned e2e (real guards + temp SQLite)', () => {
expect(res.body.pois).toEqual([
expect.objectContaining({ id: 'node:7', name: 'Spring', category: 'drinking_water' }),
]);
expect(res.body).toMatchObject({ truncated: false, partial: false, capped: false });
expect(res.body).toMatchObject({ truncated: false, partial: false, capped: false, unavailable: [] });
expect(await countRows(orm, Places)).toBe(places);
expect(realtime.broadcastMock).not.toHaveBeenCalled();
});
it('names the kinds that could not be searched right now instead of reporting nothing found', async () => {
mapsPoisAlong.mockResolvedValue({
pois: [],
failed: ['viewpoint', 'shelter'],
partial: false,
truncated: false,
capped: false,
});
const res = await request(server)
.post('/api/trips/5/tours/poi-search')
.set('Cookie', sessionCookie(VIEWER))
.send({ ...body, categories: ['viewpoint', 'shelter', 'drinking_water'] });
expect(res.status).toBe(200);
expect(res.body).toEqual({
pois: [],
truncated: false,
partial: false,
capped: false,
unavailable: ['viewpoint', 'shelter'],
});
});
it('404 for someone outside the trip, 400 for a body it does not know, 401 without a session', async () => {
const outsider = await request(server)
.post('/api/trips/5/tours/poi-search')
+3 -1
View File
@@ -8,6 +8,7 @@ import { MapsService } from '../../src/nest/maps/maps.service';
import { PlaceDetailsResolver } from '../../src/nest/maps/place-details.resolver';
import { PlacePhotoResolver } from '../../src/nest/maps/place-photo.resolver';
import { PlacesProviderSelector } from '../../src/nest/maps/places-provider.selector';
import { PoisAlongResolver } from '../../src/nest/maps/pois-along.resolver';
import { GooglePlacesClient } from '../../src/nest/maps/providers/google-places.provider';
import { OsmClient } from '../../src/nest/maps/providers/osm.client';
import { WikimediaClient } from '../../src/nest/maps/providers/wikimedia.client';
@@ -44,7 +45,8 @@ export function buildMapsParts(
const photos = new PlacePhotoResolver(photoCache, places, google, wiki, selector);
const links = new MapsUrlResolver(osm);
const details = new PlaceDetailsResolver(placeDetailsCache, google, osm, selector);
const svc = new MapsService(photoCache, appSettings, google, osm, wiki, selector, photos, links, details);
const along = new PoisAlongResolver(osm);
const svc = new MapsService(photoCache, appSettings, google, osm, wiki, selector, photos, links, details, along);
return { svc, google, osm, wiki, selector };
}
@@ -0,0 +1,153 @@
/**
* MAPS-ALONG-001..007: the geometry of a search along a line (PLN-02). Where
* the index is asked (circles strung along the line), the stretches Overpass
* is asked in and the query near one of them, all pure.
*/
import {
OVERPASS_ALONG_QUERY_TIMEOUT_S,
alongPlan,
aroundPath,
overpassAlongQuery,
overpassStretches,
} from '../../../src/nest/maps/maps-along.helpers';
import { haversineKm, lineMetres, type LatLng } from '@trek/shared/roadtrip';
import { describe, expect, it } from 'vitest';
const ORIGIN = { lat: 47, lng: 11 };
const M_PER_DEG = 111_320;
/** A point `x` metres east and `y` metres north of the origin. */
function at(x: number, y: number): LatLng {
return {
lat: ORIGIN.lat + y / M_PER_DEG,
lng: ORIGIN.lng + x / (M_PER_DEG * Math.cos((ORIGIN.lat * Math.PI) / 180)),
};
}
const metres = (a: LatLng, b: LatLng) => haversineKm(a, b) * 1000;
describe('alongPlan', () => {
it('MAPS-ALONG-001: a straight 3 km line at 500 m takes a circle every kilometre, each reaching its stretch', () => {
const line = [at(0, 0), at(0, 3000)];
const plan = alongPlan(line, 500);
expect(plan.capped).toBe(false);
expect(plan.covered).toBe(line);
expect(plan.beads.map((bead) => Math.round(metres(line[0] as LatLng, bead)))).toEqual([
0,
1000,
2000,
Math.round(lineMetres(line)),
]);
// Half a step along and a corridor across, whichever way the line turns.
expect(plan.beads.every((bead) => bead.radiusM === 1000)).toBe(true);
});
it('MAPS-ALONG-002: on a zig-zag line every point within the corridor lies inside some circle', () => {
// Eight legs of 700 m, turning a right angle at every corner, as a walk through a street grid does.
const line = Array.from({ length: 9 }, (_, index) => at(index * 495, index % 2 === 0 ? 0 : 495));
const corridor = 500;
const plan = alongPlan(line, corridor);
const outside: LatLng[] = [];
for (let leg = 1; leg < line.length; leg++) {
const a = line[leg - 1] as LatLng;
const b = line[leg] as LatLng;
const length = metres(a, b);
// The leg's direction in metres, and the normal to it.
const dx = ((b.lng - a.lng) * M_PER_DEG * Math.cos((ORIGIN.lat * Math.PI) / 180)) / length;
const dy = ((b.lat - a.lat) * M_PER_DEG) / length;
const ax = (a.lng - ORIGIN.lng) * M_PER_DEG * Math.cos((ORIGIN.lat * Math.PI) / 180);
const ay = (a.lat - ORIGIN.lat) * M_PER_DEG;
for (let along = 0; along <= length; along += 25) {
for (const side of [-1, 1]) {
const point = at(ax + dx * along - dy * corridor * side, ay + dy * along + dx * corridor * side);
if (!plan.beads.some((bead) => metres(bead, point) <= bead.radiusM)) outside.push(point);
}
}
}
expect(outside).toEqual([]);
});
it('MAPS-ALONG-003: a 100 km line at 250 m takes 24 circles and says it covered only its start', () => {
const line = [at(0, 0), at(0, 100_000)];
const plan = alongPlan(line, 250);
expect(plan.beads).toHaveLength(24);
expect(Math.round(metres(plan.beads[0] as LatLng, plan.beads[1] as LatLng))).toBe(1500);
expect(plan.capped).toBe(true);
expect(lineMetres(plan.covered)).toBeCloseTo(34_500, -1);
});
it('MAPS-ALONG-004: two points 30 m apart take a circle at each end', () => {
const plan = alongPlan([at(0, 0), at(30, 0)], 250);
expect(plan.beads).toHaveLength(2);
expect(plan.capped).toBe(false);
});
it('MAPS-ALONG-004b: a line with no points takes no circle', () => {
expect(alongPlan([], 500).beads).toEqual([]);
});
});
describe('aroundPath and overpassAlongQuery', () => {
// A wiggly 20 km line of 2000 points, more than the query may carry.
const wiggly = Array.from({ length: 2000 }, (_, index) => at(index * 10, Math.sin(index / 3) * 40));
it('MAPS-ALONG-005: the line is simplified to at most 120 points, its reach widened by what that moved it', () => {
const path = aroundPath(wiggly, 500);
expect(path.points.length).toBeLessThanOrEqual(120);
expect(path.radiusM).toBeGreaterThanOrEqual(550);
for (const point of wiggly) {
expect(point.lat).toBeGreaterThanOrEqual(path.bbox.south);
expect(point.lat).toBeLessThanOrEqual(path.bbox.north);
expect(point.lng).toBeGreaterThanOrEqual(path.bbox.west);
expect(point.lng).toBeLessThanOrEqual(path.bbox.east);
}
// A short line keeps its points and only the corridor's tenth as slack.
const short = aroundPath([at(0, 0), at(0, 1000)], 500);
expect(short.points).toHaveLength(2);
expect(short.radiusM).toBe(550);
// The box reaches a radius past the line on every side.
expect(short.bbox.south).toBeCloseTo(ORIGIN.lat - 550 / M_PER_DEG, 8);
});
it('MAPS-ALONG-006: one query asks the box for candidates and keeps those near the line', () => {
const path = aroundPath([at(0, 0), at(0, 1000)], 500);
const query = overpassAlongQuery(['tourism=viewpoint', 'amenity=drinking_water'], path, 60);
// The deadline the client's own wait is derived from, so the two never drift apart.
expect(OVERPASS_ALONG_QUERY_TIMEOUT_S).toBe(10);
expect(query.startsWith(`[out:json][timeout:${OVERPASS_ALONG_QUERY_TIMEOUT_S}];`)).toBe(true);
expect(query).toContain('nwr["tourism"="viewpoint"](');
expect(query).toContain('nwr["amenity"="drinking_water"](');
expect(query.match(/->\.cand;/g)).toHaveLength(1);
expect(query.match(/around:/g)).toHaveLength(1);
expect(query).toContain(`nwr.cand(around:550,47.00000,11.00000,${at(0, 1000).lat.toFixed(5)},11.00000);`);
expect(query.endsWith('out center tags 85;')).toBe(true);
});
});
describe('overpassStretches', () => {
it('MAPS-ALONG-007: a line is cut into equal stretches of at most 50 km, the whole line up to 400 km', () => {
const walk = [at(0, 0), at(0, 3000)];
expect(overpassStretches(walk)).toEqual({ stretches: [walk], capped: false });
// 120 km with a bend: three stretches of 40 km, each starting where the last one ended.
const ride = [at(0, 0), at(0, 70_000), at(50_000, 70_000)];
const cut = overpassStretches(ride);
expect(cut.capped).toBe(false);
expect(cut.stretches.map((stretch) => Math.round(lineMetres(stretch) / 1000))).toEqual([40, 40, 40]);
expect(cut.stretches.map((stretch) => stretch[0])).toEqual([
ride[0],
cut.stretches[0]?.at(-1),
cut.stretches[1]?.at(-1),
]);
expect(cut.stretches[2]?.at(-1)).toBe(ride[2]);
// 450 km takes nine stretches of 50 km; the first eight are asked and the answer says so.
const long = [at(0, 0), at(0, 450_000)];
const crossing = overpassStretches(long);
expect(crossing.capped).toBe(true);
expect(crossing.stretches).toHaveLength(8);
expect(Math.round(lineMetres(crossing.stretches[0] ?? []) / 1000)).toBe(50);
expect(metres(ORIGIN, crossing.stretches[7]?.at(-1) ?? ORIGIN)).toBeCloseTo((lineMetres(long) * 8) / 9, -1);
});
});
@@ -0,0 +1,375 @@
/**
* MAPS-ALONG-010..019: places near a line (PLN-02), from the index in circles
* along it and from Overpass, in stretches of the whole line, for the kinds
* the index does not know.
*
* The index is asked through a stub here, Overpass through a spy on the OSM
* client: these cases are about who is asked for what, and how a source that
* fails is reported instead of reading as nothing found.
*/
import type { AppSettingsRepository } from '../../../src/db/repositories/AppSettings.repository';
import type { UsersRepository } from '../../../src/db/repositories/Users.repository';
import { ownedByAsked } from '../../../src/nest/maps/maps-index.helpers';
import { INDEX_MAX_CATEGORY_CHARS, INDEX_MAX_LIMIT } from '../../../src/nest/maps/trek-places.client';
import type { PlacePhotoCacheService } from '../../../src/nest/place-photos/place-photo-cache.service';
import { noGoogleQuota } from '../../helpers/google-quota';
import { buildMapsParts } from '../../helpers/maps-service';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const { mockNearby, logWarn } = vi.hoisted(() => ({
logWarn: vi.fn(),
mockNearby: vi.fn(
async (
_lat: number,
_lng: number,
_opts?: { radius?: number; limit?: number; category?: string },
): Promise<unknown[]> => [],
),
}));
// The log line is the operator's only trace of a source that failed; the logger itself writes to trek.log.
vi.mock('../../../src/nest/audit/audit-log.logger', async (importOriginal) => ({
...(await importOriginal<typeof import('../../../src/nest/audit/audit-log.logger')>()),
logWarn,
}));
vi.mock('../../../src/nest/maps/trek-places.client', async (importOriginal) => ({
...(await importOriginal<typeof import('../../../src/nest/maps/trek-places.client')>()),
trekPlacesNearby: mockNearby,
}));
const noAppSettings = { getValue: async () => null } as unknown as AppSettingsRepository;
const noUsers = { getApiKeyColumn: async () => null } as unknown as UsersRepository;
// Just under 3 km due north at 500 m: four circles about a kilometre apart, each reaching 1000 m.
const LINE = [
{ lat: 47, lng: 11 },
{ lat: 47.0269, lng: 11 },
];
/** An index row of one category path. */
function row(gers: string, name: string, categoryPath: string, over: Record<string, unknown> = {}) {
return {
gers,
name,
lat: 47.01,
lng: 11.001,
category: categoryPath.slice(categoryPath.lastIndexOf('>') + 1),
categoryPath,
confidence: 0.9,
address: null,
contact: null,
brand: null,
source: 'overture',
hours: null,
distanceMetres: 100,
...over,
};
}
const CAFE = 'food_and_drink>casual_eatery>cafe';
const MUSEUM = 'arts_and_entertainment>museum';
const SPRING = {
osm_id: 'node:7',
name: '',
lat: 47.012,
lng: 11.002,
category: 'drinking_water',
poi_type: 'amenity=drinking_water',
address: null,
website: null,
phone: null,
opening_hours: null,
cuisine: null,
brand: null,
brand_wikidata: null,
charging: null,
source: 'openstreetmap' as const,
};
const ORIGINAL_TREK_PLACES = process.env.TREK_PLACES_ENABLED;
function make(enabled = true) {
if (enabled) delete process.env.TREK_PLACES_ENABLED;
else process.env.TREK_PLACES_ENABLED = 'false';
const { svc, osm } = buildMapsParts(
{} as PlacePhotoCacheService,
noAppSettings,
noUsers,
{} as never,
{} as never,
noGoogleQuota,
);
const overpass = vi
.spyOn(osm, 'searchOverpassPoisAlong')
.mockResolvedValue({ pois: [SPRING], source: 'openstreetmap', truncated: false, clamped: false });
return { svc, overpass };
}
/** The lines logged as warnings. */
const mapsWarnings = () => logWarn.mock.calls.map((call) => String(call[0]));
/** A line due north from 47°N 11°E, `degrees` of latitude long: about 111 km each. */
const north = (degrees: number) => [
{ lat: 47, lng: 11 },
{ lat: 47 + degrees, lng: 11 },
];
/** Counts the Overpass queries in flight, each answering after a turn of the event loop. */
function inFlight(overpass: ReturnType<typeof make>['overpass']) {
const seen = { now: 0, most: 0 };
overpass.mockImplementation(async () => {
seen.now += 1;
seen.most = Math.max(seen.most, seen.now);
await new Promise((resolve) => setTimeout(resolve, 5));
seen.now -= 1;
return { pois: [SPRING], source: 'openstreetmap', truncated: false, clamped: false };
});
return seen;
}
beforeEach(() => {
mockNearby.mockReset();
mockNearby.mockResolvedValue([]);
logWarn.mockClear();
});
afterEach(() => {
if (ORIGINAL_TREK_PLACES === undefined) delete process.env.TREK_PLACES_ENABLED;
else process.env.TREK_PLACES_ENABLED = ORIGINAL_TREK_PLACES;
});
describe('MapsService.poisAlong', () => {
it('MAPS-ALONG-010: asks the index in every circle for its kinds only, and Overpass once for the rest', async () => {
const { svc, overpass } = make();
const out = await svc.poisAlong(['cafe', 'drinking_water'], LINE, 500, 'de', 30);
expect(mockNearby).toHaveBeenCalledTimes(4);
const centres = mockNearby.mock.calls.map(([lat, lng]) => [Number(lat.toFixed(3)), Number(lng.toFixed(3))]);
expect(centres).toEqual([
[47, 11],
[47.009, 11],
[47.018, 11],
[47.027, 11],
]);
for (const [, , opts] of mockNearby.mock.calls) {
expect(opts).toEqual({
radius: 1000,
limit: 30,
category: 'food_and_drink>casual_eatery>cafe,food_and_drink>non_alcoholic_beverage_venue>coffee_shop',
});
}
expect(overpass).toHaveBeenCalledTimes(1);
expect(overpass).toHaveBeenCalledWith('drinking_water', LINE, 500, 'de', 30);
// The unnamed spring stays: a tap is what a walk looks for.
expect(out).toEqual({ pois: [SPRING], failed: [], partial: false, truncated: false, capped: false });
});
it('MAPS-ALONG-011: a walk asks one request per kind when they would not fit one, each inside the limits', async () => {
const { svc, overpass } = make();
await svc.poisAlong(['sights', 'museum', 'park', 'cafe', 'restaurant', 'market'], LINE, 500, 'de', 30);
// Six kinds in four circles; none of them is asked of Overpass.
expect(mockNearby).toHaveBeenCalledTimes(24);
for (const [, , opts] of mockNearby.mock.calls) {
expect(opts?.limit).toBe(30);
expect(opts?.limit).toBeLessThanOrEqual(INDEX_MAX_LIMIT);
expect(opts?.category?.length).toBeLessThanOrEqual(INDEX_MAX_CATEGORY_CHARS);
}
expect(mockNearby.mock.calls.slice(0, 6).map(([, , opts]) => opts?.category)).toEqual([
'cultural_and_historic>historic_site,cultural_and_historic>memorial_site>monument',
'arts_and_entertainment>museum,arts_and_entertainment>arts_and_crafts_space>art_gallery,arts_and_entertainment>performing_arts_venue,arts_and_entertainment>movie_theater',
'sports_and_recreation>park,geographic_entities>built_feature>garden',
'food_and_drink>casual_eatery>cafe,food_and_drink>non_alcoholic_beverage_venue>coffee_shop',
'food_and_drink>restaurant,food_and_drink>casual_eatery',
'shopping>market',
]);
// An empty circle is an answer: Overpass is never asked for what the index knows.
expect(overpass).not.toHaveBeenCalled();
});
it('MAPS-ALONG-011b: kinds that would fit one request are still asked one by one, so a market is not crowded out', async () => {
const { svc } = make();
await svc.poisAlong(['restaurant', 'cafe', 'market'], LINE, 500, 'de', 30);
expect(mockNearby).toHaveBeenCalledTimes(12);
expect(mockNearby.mock.calls.slice(0, 3).map(([, , opts]) => [opts?.category, opts?.limit])).toEqual([
['food_and_drink>restaurant,food_and_drink>casual_eatery', 30],
['food_and_drink>casual_eatery>cafe,food_and_drink>non_alcoholic_beverage_venue>coffee_shop', 30],
['shopping>market', 30],
]);
});
it('MAPS-ALONG-012: an index that answers no circle hands its kinds to Overpass once, and says why', async () => {
mockNearby.mockRejectedValue(new Error('places api down'));
const { svc, overpass } = make();
const seen = inFlight(overpass);
const out = await svc.poisAlong(['cafe', 'drinking_water'], LINE, 500, 'de', 30);
expect(overpass).toHaveBeenCalledTimes(2);
expect(overpass).toHaveBeenLastCalledWith('cafe', LINE, 500, 'de', 30);
// The index's kinds are asked while the others still are, not one deadline after the other.
expect(seen.most).toBe(2);
expect(out.failed).toEqual([]);
// Nothing of the line was left out: Overpass searched all of it.
expect(out.partial).toBe(false);
expect(mapsWarnings()).toEqual([
expect.stringContaining('[Maps] TREK places index along a line: 4 of 4 requests failed: places api down'),
]);
});
it('MAPS-ALONG-013: one circle failing keeps the places of the others and marks the answer partial', async () => {
mockNearby.mockRejectedValueOnce('timeout').mockResolvedValue([row('c-1', 'Kaffeehaus', CAFE)]);
const { svc, overpass } = make();
const out = await svc.poisAlong(['cafe'], LINE, 500, 'de', 30);
expect(overpass).not.toHaveBeenCalled();
expect(out.partial).toBe(true);
// The same cafe in three overlapping circles is one place.
expect(out.pois.map((poi) => [poi.osm_id, poi.category])).toEqual([['gers:c-1', 'cafe']]);
expect(mapsWarnings()).toEqual([expect.stringContaining('1 of 4 requests failed: timeout')]);
});
it('MAPS-ALONG-014: Overpass failing names its kinds as failed, keeps the index places and is logged once', async () => {
mockNearby.mockResolvedValue([row('c-1', 'Kaffeehaus', CAFE)]);
const { svc, overpass } = make();
overpass.mockRejectedValue(new Error('Could not reach any Overpass endpoint'));
const out = await svc.poisAlong(['cafe', 'viewpoint', 'drinking_water'], LINE, 500, 'de', 30);
expect(out.failed).toEqual(['viewpoint', 'drinking_water']);
expect(out.pois.map((poi) => poi.name)).toEqual(['Kaffeehaus']);
expect(out.partial).toBe(false);
expect(mapsWarnings()).toEqual([
expect.stringContaining(
'[Maps] OpenStreetMap along a line: viewpoint, drinking_water: 1 of 1 requests failed: Could not reach any',
),
]);
});
it('MAPS-ALONG-015: with the index switched off every kind goes to Overpass in one query', async () => {
const { svc, overpass } = make(false);
await svc.poisAlong(['cafe', 'drinking_water'], LINE, 500);
expect(mockNearby).not.toHaveBeenCalled();
expect(overpass).toHaveBeenCalledTimes(1);
expect(overpass).toHaveBeenCalledWith('cafe,drinking_water', LINE, 500, undefined, 30);
});
it('MAPS-ALONG-016: each hit is labelled with the kind that produced it, its hours kept; a full page is cut', async () => {
const hours = { osm: 'Tu-Su 10:00-18:00', source: 'openstreetmap', sourceUrl: null };
mockNearby.mockImplementation(async (_lat, _lng, opts) =>
opts?.category?.startsWith('arts')
? [
row('m-1', 'Lenbachhaus', MUSEUM, { hours }),
...Array.from({ length: 29 }, (_, i) => row(`m-${i + 2}`, `Museum ${i}`, MUSEUM)),
]
: opts?.category?.startsWith('sports')
? [
row('p-1', 'Englischer Garten', 'sports_and_recreation>park'),
row('p-2', 'Therme Erding', 'sports_and_recreation>park>water_park'),
]
: [row('s-1', 'Siegestor', 'cultural_and_historic>memorial_site>monument')],
);
const { svc } = make();
const out = await svc.poisAlong(['sights', 'museum', 'park'], LINE, 500, 'de', 30);
expect(out.truncated).toBe(true);
const byName = new Map(out.pois.map((poi) => [poi.name, poi]));
expect(byName.get('Lenbachhaus')).toMatchObject({ category: 'museum', opening_hours: 'Tu-Su 10:00-18:00' });
expect(byName.get('Siegestor')).toMatchObject({ category: 'sights', opening_hours: null });
expect(byName.get('Englischer Garten')).toMatchObject({ category: 'park' });
// A water park lies under the parks' path, but it is the activity pill's: no park of a walk.
expect(byName.has('Therme Erding')).toBe(false);
});
it('MAPS-ALONG-016b: a row goes to the kind that names its path most closely, a row no kind knows is left as it is', () => {
const waterPark = { category: 'water_park', categoryPath: 'sports_and_recreation>park>water_park' };
expect(ownedByAsked(waterPark, ['park'])).toBe(false);
expect(ownedByAsked(waterPark, ['park', 'activity'])).toBe(true);
expect(ownedByAsked({ category: 'park', categoryPath: 'sports_and_recreation>park' }, ['park'])).toBe(true);
// Judged by its leaf where the index left the path empty.
expect(ownedByAsked({ category: 'water_park', categoryPath: null }, ['park'])).toBe(false);
expect(ownedByAsked({ category: null, categoryPath: null }, ['park'])).toBe(true);
expect(ownedByAsked({ category: 'pier', categoryPath: 'travel>pier' }, ['park'])).toBe(true);
});
it('MAPS-ALONG-017: an index and an Overpass that both fail name every kind as failed', async () => {
mockNearby.mockRejectedValue(new Error('places api down'));
const { svc, overpass } = make();
overpass.mockRejectedValue(new Error('Could not reach any Overpass endpoint'));
const out = await svc.poisAlong(['cafe', 'viewpoint'], LINE, 500, 'de', 30);
expect(out).toEqual({ pois: [], failed: ['viewpoint', 'cafe'], partial: false, truncated: false, capped: false });
expect(mapsWarnings()).toHaveLength(3);
});
it('MAPS-ALONG-018: a line longer than the circles reach has its index kinds searched along its start, and says so', async () => {
const { svc, overpass } = make();
const long = north(1);
const out = await svc.poisAlong(['cafe', 'viewpoint'], long, 250, 'de', 30);
expect(out.capped).toBe(true);
expect(mockNearby).toHaveBeenCalledTimes(24);
expect(Math.max(...mockNearby.mock.calls.map(([lat]) => lat))).toBeLessThan(47.32);
// Overpass searches the whole line in three stretches of about 37 km, the last one ending where the line does.
expect(overpass).toHaveBeenCalledTimes(3);
const stretches = overpass.mock.calls.map((call) => call[1]);
expect(stretches[0]?.[0]).toEqual(long[0]);
expect(stretches[1]?.[0]).toEqual(stretches[0]?.at(-1));
expect(stretches[2]?.[0]).toEqual(stretches[1]?.at(-1));
expect(stretches[2]?.at(-1)).toEqual(long[1]);
});
it('MAPS-ALONG-019: the kinds Overpass answers are searched along the whole line, a few stretches at a time', async () => {
const { svc, overpass } = make();
const seen = inFlight(overpass);
const ride = await svc.poisAlong(['drinking_water', 'toilets'], north(1), 500, 'de', 30);
expect(ride).toMatchObject({ capped: false, partial: false, failed: [] });
expect(overpass.mock.calls.map((call) => call[0])).toEqual([
'drinking_water,toilets',
'drinking_water,toilets',
'drinking_water,toilets',
]);
// An index that answers nothing leaves its kinds to Overpass, which reaches the whole line.
overpass.mockClear();
mockNearby.mockRejectedValue(new Error('places api down'));
const fallback = await svc.poisAlong(['cafe'], north(1), 500, 'de', 30);
expect(fallback).toMatchObject({ capped: false, failed: [] });
expect(overpass).toHaveBeenCalledTimes(3);
// Past 400 km the line is searched along its start; never more than three stretches are in flight.
overpass.mockClear();
seen.most = 0;
const crossing = await svc.poisAlong(['viewpoint'], north(4.5), 500, 'de', 30);
expect(crossing.capped).toBe(true);
expect(overpass).toHaveBeenCalledTimes(8);
expect(seen.most).toBe(3);
});
it('MAPS-ALONG-019b: one stretch failing keeps the places of the others and marks the answer partial', async () => {
const { svc, overpass } = make();
overpass.mockRejectedValueOnce(new Error('rate limited'));
const out = await svc.poisAlong(['drinking_water'], north(1), 500, 'de', 30);
expect(out).toMatchObject({ pois: [SPRING], failed: [], partial: true, capped: false });
expect(mapsWarnings()).toEqual([
expect.stringContaining(
'[Maps] OpenStreetMap along a line: drinking_water: 1 of 3 requests failed: rate limited',
),
]);
});
});
+94 -4
View File
@@ -1,5 +1,5 @@
/**
* MAPS-POIS-001..012 — the explore pill, answered from the index.
* MAPS-POIS-001..018: the explore pill, answered from the index.
*
* The pill used to be Overpass and nothing else, and the public mirrors it asks
* are regularly overloaded. The index answers first now, so the two things that
@@ -9,8 +9,16 @@
*/
import type { AppSettingsRepository } from '../../../src/db/repositories/AppSettings.repository';
import type { UsersRepository } from '../../../src/db/repositories/Users.repository';
import {
indexKnowsCategory,
indexPoiAnswer,
indexPoiPlanAround,
indexRequests,
indexRequestsPerKind,
} from '../../../src/nest/maps/maps-index.helpers';
import { MapsService } from '../../../src/nest/maps/maps.service';
import type { OsmClient } from '../../../src/nest/maps/providers/osm.client';
import { INDEX_MAX_CATEGORY_CHARS } from '../../../src/nest/maps/trek-places.client';
import type { PlacePhotoCacheService } from '../../../src/nest/place-photos/place-photo-cache.service';
import { noGoogleQuota } from '../../helpers/google-quota';
import { buildMapsParts } from '../../helpers/maps-service';
@@ -290,7 +298,7 @@ describe('MapsService.pois answered from the index', () => {
expect(out.clamped).toBe(false);
});
it('MAPS-POIS-013: a corridor search asks the index once for all its categories', async () => {
it('MAPS-POIS-013: a corridor search asks the index for all its categories, in one request while they fit', async () => {
// The corridor sends a comma-separated list. Looking the whole string up as
// one key missed every time, so every corridor query fell through to
// Overpass — on the one path where that hurts most, because a single search
@@ -314,10 +322,11 @@ describe('MapsService.pois answered from the index', () => {
const svc = make();
const overpass = stubOverpass(svc);
const out = await svc.pois('fuel,charging', BOX);
const out = await svc.pois('fuel,charging', BOX, undefined, 40);
expect(overpass).not.toHaveBeenCalled();
// One request carrying every term the two categories map to.
expect(mockNearby).toHaveBeenCalledTimes(1);
expect(mockNearby).toHaveBeenCalledWith(
0,
0,
@@ -326,13 +335,29 @@ describe('MapsService.pois answered from the index', () => {
'travel_and_transportation>fueling_station>gas_station,travel_and_transportation>fueling_station>ev_charging_station',
// Per category, so a mixed search does not spend the whole allowance on
// whichever kind happens to be densest.
limit: 120,
limit: 80,
}),
);
// Each hit carries the category that produced it, not the list that was
// asked for: the client colours and groups its markers by that field, and
// "fuel,charging" is not a category.
expect(out.pois.map((p) => p.category)).toEqual(['fuel', 'charging']);
// At the pill's own budget the two together ask for 120 rows, and the
// service refuses more than 100 with a 422: one request each, then.
mockNearby.mockClear();
const split = await svc.pois('fuel,charging', BOX);
expect(overpass).not.toHaveBeenCalled();
expect(mockNearby.mock.calls.map(([, , opts]) => opts)).toEqual([
{ radius: 7872, limit: 60, category: 'travel_and_transportation>fueling_station>gas_station' },
{ radius: 7872, limit: 60, category: 'travel_and_transportation>fueling_station>ev_charging_station' },
]);
// Both requests answered both rows here: each place is listed once.
expect(split.pois.map((p) => [p.name, p.category])).toEqual([
['Aral', 'fuel'],
['Ionity', 'charging'],
]);
});
it('MAPS-POIS-013b: a leaf category that is only a substring of a term is still labelled by it', async () => {
@@ -499,6 +524,71 @@ describe('MapsService.pois answered from the index', () => {
});
});
describe('MapsService.pois within the index service limits', () => {
it('MAPS-POIS-016: knows which categories the index answers, and narrows or widens a circle as for a viewport', () => {
expect(['nature', 'park', 'market', 'peak', 'museum_gallery'].map(indexKnowsCategory)).toEqual([
true,
true,
true,
true,
true,
]);
expect(['viewpoint', 'drinking_water', 'toilets', 'shelter'].map(indexKnowsCategory)).toEqual([
false,
false,
false,
false,
]);
const centre = { lat: 48.1, lng: 11.5 };
expect(indexPoiPlanAround('park', centre, 120, 30)).toMatchObject({ radius: 300, reach: 120, cap: 30, ...centre });
expect(indexPoiPlanAround('park', centre, 50_000, 30)?.radius).toBe(20000);
expect(indexPoiPlanAround('park,viewpoint', centre, 1000, 30)).toBeNull();
expect(indexPoiPlanAround('', centre, 1000, 30)).toBeNull();
});
it('MAPS-POIS-017: many categories are asked one by one, each its share, a full page cut and every place once', async () => {
mockNearby.mockImplementation(async (_lat, _lng, opts) =>
opts?.category?.startsWith('food_and_drink>restaurant')
? rows(48).map((r) => ({ ...r, categoryPath: 'food_and_drink>restaurant' }))
: [{ ...FULL, gers: 'shared-1' }],
);
const svc = make();
const overpass = stubOverpass(svc);
const out = await svc.pois('restaurant,cafe,bar,hotel,sights', BOX);
expect(overpass).not.toHaveBeenCalled();
expect(mockNearby).toHaveBeenCalledTimes(5);
for (const [, , opts] of mockNearby.mock.calls) {
// 240 over five categories, and never above what the service takes.
expect(opts?.limit).toBe(48);
expect(opts?.category?.length).toBeLessThanOrEqual(INDEX_MAX_CATEGORY_CHARS);
}
// The restaurants' page was full, so there are more of them.
expect(out.truncated).toBe(true);
expect(out.pois.filter((p) => p.osm_id === 'gers:shared-1')).toHaveLength(1);
expect(out.pois).toHaveLength(49);
});
it('MAPS-POIS-018: pages that together run past the cap are cut to it', () => {
const plan = indexPoiPlanAround('cafe', { lat: 0, lng: 0 }, 1000, 2);
if (!plan) throw new Error('cafe has index terms');
const answer = indexPoiAnswer(rows(3), plan, false);
expect(answer.pois).toHaveLength(2);
expect(answer.truncated).toBe(true);
expect(indexRequests(plan)).toEqual([
{
category: 'food_and_drink>casual_eatery>cafe,food_and_drink>non_alcoholic_beverage_venue>coffee_shop',
limit: 2,
},
]);
const food = indexPoiPlanAround('restaurant,cafe', { lat: 0, lng: 0 }, 1000, 30);
// Together they fit one request; one per kind gives each its own thirty.
expect(food && indexRequests(food)).toHaveLength(1);
expect(food && indexRequestsPerKind(food).map((request) => request.limit)).toEqual([30, 30]);
});
});
describe('MapsService.pois falls back to Overpass', () => {
it('MAPS-POIS-009: a pill the index has no categories for never reaches the index', async () => {
const svc = make();
@@ -0,0 +1,195 @@
/**
* MAPS-ALONG-020..026: the Overpass query near a line (PLN-02). One query for
* every kind the index does not know, the candidates of the line's box kept
* within reach of the line itself, and unnamed taps and huts kept, because
* they are what a hike looks for, while an unnamed garden or cafe is not. The
* network is a stubbed global fetch.
*/
import { OsmClient } from '../../../src/nest/maps/providers/osm.client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const osm = new OsmClient();
/** A line of two points, a little apart per case, so no case is answered from another's cache. */
const line = (n: number) => [
{ lat: 47.4 + n / 100, lng: 11.1 },
{ lat: 47.41 + n / 100, lng: 11.1 },
];
const answer = (elements: unknown[]) => ({ ok: true, json: async () => ({ elements }) });
/** The query of a fetch call, read back the way Overpass reads the form. */
const queryOf = (call: unknown[] | undefined) =>
decodeURIComponent(String((call?.[1] as RequestInit | undefined)?.body ?? '')).replace(/^data=/, '');
beforeEach(() => {
vi.spyOn(console, 'error').mockImplementation(() => {});
});
afterEach(() => {
vi.unstubAllGlobals();
vi.restoreAllMocks();
});
describe('OsmClient.searchOverpassPoisAlong', () => {
it('MAPS-ALONG-020: asks near the line once, keeps unnamed places and drops the closed ones', async () => {
const fetchMock = vi.fn().mockResolvedValue(
answer([
{ type: 'node', id: 1, lat: 47.405, lon: 11.1005, tags: { amenity: 'drinking_water' } },
{ type: 'way', id: 2, center: { lat: 47.406, lon: 11.1 }, tags: { name: 'Gamshütte', amenity: 'shelter' } },
{ type: 'node', id: 3, lat: 47.407, lon: 11.1, tags: { amenity: 'drinking_water', disused: 'yes' } },
{
type: 'node',
id: 4,
lat: 47.408,
lon: 11.1,
tags: { name: 'Alm', amenity: 'shelter', opening_hours: 'off' },
},
{ type: 'node', id: 5, tags: { name: 'Nowhere', amenity: 'shelter' } },
]),
);
vi.stubGlobal('fetch', fetchMock);
const out = await osm.searchOverpassPoisAlong('drinking_water,shelter', line(0), 500, 'de-DE');
const query = queryOf(fetchMock.mock.calls[0]);
expect(query).toContain('->.cand;');
expect(query).toContain('nwr.cand(around:550,47.40000,11.10000,47.41000,11.10000);');
expect(query).toContain('nwr["amenity"="drinking_water"](');
expect(query).toContain('nwr["tourism"="alpine_hut"](');
// Thirty of each kind, and the query's own slack.
expect(query).toContain('out center tags 85;');
expect(out.pois.map((poi) => [poi.osm_id, poi.name, poi.category])).toEqual([
['node:1', '', 'drinking_water'],
['way:2', 'Gamshütte', 'shelter'],
]);
expect(out).toMatchObject({ source: 'openstreetmap', truncated: false, clamped: false });
});
it('MAPS-ALONG-021: an unknown kind is refused before anything is asked', async () => {
const fetchMock = vi.fn();
vi.stubGlobal('fetch', fetchMock);
await expect(osm.searchOverpassPoisAlong('drinking_water,unicorns', line(1), 500)).rejects.toMatchObject({
status: 400,
});
await expect(osm.searchOverpassPoisAlong(' , ', line(1), 500)).rejects.toMatchObject({ status: 400 });
expect(fetchMock).not.toHaveBeenCalled();
});
it('MAPS-ALONG-022: the same kinds along the same line are answered from the cache, in any order', async () => {
const fetchMock = vi
.fn()
.mockResolvedValue(answer([{ type: 'node', id: 9, lat: 47.425, lon: 11.1, tags: { amenity: 'toilets' } }]));
vi.stubGlobal('fetch', fetchMock);
await osm.searchOverpassPoisAlong('toilets,picnic', line(2), 500, 'de');
const asked = fetchMock.mock.calls.length;
const again = await osm.searchOverpassPoisAlong('picnic,toilets', line(2), 500, 'de');
expect(fetchMock.mock.calls.length).toBe(asked);
expect(again.pois.map((poi) => poi.osm_id)).toEqual(['node:9']);
});
it('MAPS-ALONG-023: every mirror down throws, so the caller can name the kinds as unavailable', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: false, status: 504, json: async () => ({}) }));
await expect(osm.searchOverpassPoisAlong('viewpoint', line(3), 500)).rejects.toMatchObject({ status: 502 });
});
it('MAPS-ALONG-024b: an answer older than five minutes is asked again, and the oldest of a full cache goes', async () => {
const fetchMock = vi.fn().mockResolvedValue(answer([]));
vi.stubGlobal('fetch', fetchMock);
vi.useFakeTimers({ now: new Date('2026-10-19T10:00:00Z'), toFake: ['Date'] });
try {
await osm.searchOverpassPoisAlong('bike_repair', line(5), 500);
const asked = fetchMock.mock.calls.length;
vi.setSystemTime(new Date('2026-10-19T10:06:00Z'));
await osm.searchOverpassPoisAlong('bike_repair', line(5), 500);
expect(fetchMock.mock.calls.length).toBe(2 * asked);
// Six hundred other lines overfill the cache of five hundred: the first of them is asked again, the last is not.
const lines = Array.from({ length: 600 }, (_, i) => [
{ lat: 10 + i / 1000, lng: 20 },
{ lat: 10.0005 + i / 1000, lng: 20 },
]);
await lines.reduce<Promise<unknown>>(async (done, each) => {
await done;
return osm.searchOverpassPoisAlong('boat_rental', each, 250);
}, Promise.resolve(null));
const filled = fetchMock.mock.calls.length;
await osm.searchOverpassPoisAlong('boat_rental', lines[599] ?? [], 250);
expect(fetchMock.mock.calls.length).toBe(filled);
await osm.searchOverpassPoisAlong('boat_rental', lines[0] ?? [], 250);
expect(fetchMock.mock.calls.length).toBe(filled + asked);
} finally {
vi.useRealTimers();
}
});
it('MAPS-ALONG-026: only the kinds OSM rarely names keep their unnamed places, a city walk gets named ones', async () => {
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue(
answer([
{ type: 'node', id: 1, lat: 47.465, lon: 11.1, tags: { amenity: 'drinking_water' } },
{ type: 'way', id: 2, center: { lat: 47.466, lon: 11.1 }, tags: { leisure: 'garden' } },
{ type: 'way', id: 3, center: { lat: 47.467, lon: 11.1 }, tags: { leisure: 'garden', name: 'Hofgarten' } },
{ type: 'node', id: 4, lat: 47.468, lon: 11.1, tags: { amenity: 'cafe' } },
{ type: 'node', id: 5, lat: 47.469, lon: 11.1, tags: { historic: 'memorial' } },
{ type: 'node', id: 6, lat: 47.469, lon: 11.1, tags: { tourism: 'viewpoint' } },
]),
),
);
const out = await osm.searchOverpassPoisAlong('drinking_water,park,cafe,sights,viewpoint', line(6), 500, 'de');
expect(out.pois.map((poi) => [poi.osm_id, poi.name, poi.category])).toEqual([
['node:1', '', 'drinking_water'],
['way:3', 'Hofgarten', 'park'],
['node:6', '', 'viewpoint'],
]);
});
it('MAPS-ALONG-024: more places than the budget are cut to it and said to be', async () => {
const many = Array.from({ length: 40 }, (_, i) => ({
type: 'node',
id: 100 + i,
lat: 47.44,
lon: 11.1,
tags: { tourism: 'viewpoint' },
}));
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(answer(many)));
const out = await osm.searchOverpassPoisAlong('viewpoint', line(4), 500, undefined, 30);
expect(out.pois).toHaveLength(30);
expect(out.truncated).toBe(true);
});
});
describe('OsmClient.searchOverpassPois (the explore pill)', () => {
it('MAPS-ALONG-025: still drops unnamed places, which a plan has no use for', async () => {
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue(
answer([
{ type: 'node', id: 1, lat: 50.1, lon: 8.1, tags: { amenity: 'cafe' } },
{ type: 'node', id: 3, lat: 50.1, lon: 8.1 },
{
type: 'node',
id: 2,
lat: 50.11,
lon: 8.11,
tags: { name: 'Café Mozart', amenity: 'cafe', 'brand:wikidata': 'Q123' },
},
]),
),
);
const out = await osm.searchOverpassPois('cafe', { south: 50.05, west: 8.05, north: 50.15, east: 8.15 }, 'de');
expect(out.pois.map((poi) => [poi.name, poi.brand_wikidata])).toEqual([['Café Mozart', 'Q123']]);
});
});
@@ -1,7 +1,7 @@
/**
* TourPoiSearchService (PLN-02): places along a tour's line through the map
* search. The map search is a stub here: these tests are about which
* stretches are asked, what is kept and how the answer says what it missed.
* TourPoiSearchService (PLN-02, CW-05): places along a tour's line through
* the map search. The map search is a stub here: these tests are about what is
* asked for, what is kept and how the answer says what it missed.
*/
import { Places } from '../../../src/db/entities/Places.entity';
import type { McpContext } from '../../../src/nest-mcp';
@@ -20,17 +20,21 @@ import { createTour } from '../../helpers/tours-repos';
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
const db = createSnapshotTestDb();
const pois = vi.fn();
const poisAlong = vi.fn();
let t: TestModule;
let service: TourPoiSearchService;
beforeAll(async () => {
t = await createTestModule({ db, imports: [ToursModule], overrides: [{ provide: MapsService, useValue: { pois } }] });
t = await createTestModule({
db,
imports: [ToursModule],
overrides: [{ provide: MapsService, useValue: { poisAlong } }],
});
service = t.get(TourPoiSearchService);
});
beforeEach(() => {
resetTestDb(db);
pois.mockReset();
poisAlong.mockReset();
});
afterAll(async () => {
await t.close();
@@ -66,15 +70,16 @@ function poi(id: string, lat: number, lng: number, category = 'viewpoint', over:
const answer = (list: unknown[], over: Record<string, unknown> = {}) => ({
pois: list,
source: 'openstreetmap',
failed: [],
partial: false,
truncated: false,
clamped: false,
capped: false,
...over,
});
describe('TourPoiSearchService', () => {
it('TOUR-POI-001: keeps the places within the corridor, once each, nearest the start first, with where they lie', async () => {
pois.mockResolvedValue(
poisAlong.mockResolvedValue(
answer([
poi('node:far', 47.41, 11.2),
poi('node:late', 47.418, 11.1005),
@@ -96,7 +101,7 @@ describe('TourPoiSearchService', () => {
});
it('TOUR-POI-006: one name in one spot is one place, mapped twice as a point and an outline', async () => {
pois.mockResolvedValue(
poisAlong.mockResolvedValue(
answer([
poi('node:9', 47.41, 11.1003, 'viewpoint', { name: 'AlpspiX' }),
poi('way:9', 47.4101, 11.1004, 'viewpoint', { name: 'AlpspiX' }),
@@ -107,8 +112,8 @@ describe('TourPoiSearchService', () => {
expect(result.pois.map((found) => found.id)).toEqual(['node:9', 'node:10']);
});
it('TOUR-POI-002: asks the map search for what each category means, and names a hit by the category asked', async () => {
pois.mockResolvedValue(answer([poi('node:cafe', 47.41, 11.1, 'cafe')]));
it('TOUR-POI-002: asks the map search along the line for what each category means, and names a hit by the category asked', async () => {
poisAlong.mockResolvedValue(answer([poi('node:cafe', 47.41, 11.1, 'cafe')]));
const result = await service.search({
tour_type: 'hike',
categories: ['food', 'drinking_water'],
@@ -116,28 +121,28 @@ describe('TourPoiSearchService', () => {
line: LINE,
lang: 'de',
});
expect(pois).toHaveBeenCalledWith('restaurant,cafe,drinking_water', expect.any(Object), 'de', 60);
expect(poisAlong).toHaveBeenCalledWith(
['restaurant', 'cafe', 'drinking_water'],
[
{ lat: 47.4, lng: 11.1 },
{ lat: 47.42, lng: 11.1 },
],
250,
'de',
30,
);
expect(result.pois[0]?.category).toBe('food');
});
it('TOUR-POI-003: a stretch that fails leaves the others and marks the answer partial; a cut answer is truncated', async () => {
// A line long enough to need several stretches.
const long: Array<[number, number]> = [
[47.0, 11.0],
[48.6, 11.0],
];
pois
.mockRejectedValueOnce(new Error('overpass down'))
.mockResolvedValue(answer([poi('node:a', 47.6, 11.0005)], { truncated: true }));
const result = await service.search({ tour_type: 'hike', categories: ['viewpoint'], corridor_m: 500, line: long });
expect(pois.mock.calls.length).toBeGreaterThan(1);
expect(result.partial).toBe(true);
expect(result.truncated).toBe(true);
it('TOUR-POI-003: says when parts of the line could not be searched or more places matched than came back', async () => {
poisAlong.mockResolvedValue(answer([poi('node:a', 47.41, 11.1005)], { partial: true, truncated: true }));
const result = await service.search({ tour_type: 'hike', categories: ['viewpoint'], corridor_m: 500, line: LINE });
expect(result).toMatchObject({ partial: true, truncated: true, capped: false, unavailable: [] });
expect(result.pois.map((found) => found.id)).toEqual(['node:a']);
});
it('TOUR-POI-004: a line longer than one search covers is searched along its first stretches and says so', async () => {
pois.mockResolvedValue(answer([]));
it('TOUR-POI-004: a line longer than one search covers says it was searched along its first part', async () => {
poisAlong.mockResolvedValue(answer([], { capped: true }));
const result = await service.search({
tour_type: 'kayak',
categories: ['slipway'],
@@ -147,8 +152,84 @@ describe('TourPoiSearchService', () => {
[52.0, 14.0],
],
});
expect(pois).toHaveBeenCalledTimes(12);
expect(result.capped).toBe(true);
expect(result.truncated).toBe(false);
});
it('TOUR-POI-007: names the kinds no source could search, a kind of two only when both failed', async () => {
poisAlong.mockResolvedValue(answer([], { failed: ['viewpoint', 'cafe', 'market'] }));
const walk = await service.search({
tour_type: 'walk',
categories: ['market', 'sights', 'viewpoint'],
corridor_m: 500,
line: LINE,
});
expect(walk.unavailable).toEqual(['market', 'viewpoint']);
const hike = await service.search({ tour_type: 'hike', categories: ['food'], corridor_m: 500, line: LINE });
expect(hike.unavailable).toEqual([]);
poisAlong.mockResolvedValue(answer([], { failed: ['restaurant', 'cafe'] }));
expect(
(await service.search({ tour_type: 'hike', categories: ['food'], corridor_m: 500, line: LINE })).unavailable,
).toEqual(['food']);
});
it('TOUR-POI-008: an unnamed place is kept and never merged with another unnamed one nearby', async () => {
poisAlong.mockResolvedValue(
answer([
poi('node:1', 47.41, 11.1003, 'drinking_water', { name: '' }),
poi('node:2', 47.4101, 11.1003, 'drinking_water', { name: '' }),
// Across the line from the first: as far along, a little further off it.
poi('node:3', 47.41, 11.0995, 'drinking_water', { name: '' }),
]),
);
const result = await service.search({
tour_type: 'hike',
categories: ['drinking_water'],
corridor_m: 500,
line: LINE,
});
expect(result.pois.map((found) => [found.id, found.name])).toEqual([
['node:1', ''],
['node:3', ''],
['node:2', ''],
]);
});
it('TOUR-POI-009: of more places than an answer carries, the nearest to the line are listed from the start', async () => {
// Seventy cafes along the line, every other one a little further off it.
const many = Array.from({ length: 70 }, (_, i) =>
poi(`node:${i}`, 47.4 + (i + 1) * 0.0002, 11.1 + (i % 2 === 0 ? 0.0001 : 0.003), 'cafe'),
);
poisAlong.mockResolvedValue(answer(many));
const result = await service.search({ tour_type: 'walk', categories: ['cafe'], corridor_m: 500, line: LINE });
expect(result.pois).toHaveLength(60);
expect(result.truncated).toBe(true);
// All 35 near ones are in, from the start of the line to its end.
const ids = new Set(result.pois.map((found) => found.id));
expect(many.filter((_, i) => i % 2 === 0).every((near) => ids.has(near.osm_id))).toBe(true);
const along = result.pois.map((found) => found.along_m);
expect(along).toEqual([...along].sort((a, b) => a - b));
});
it('TOUR-POI-010: a place of a circle outside the corridor and one of a kind not asked for are left out', async () => {
poisAlong.mockResolvedValue(
answer([
poi('gers:in', 47.41, 11.101, 'park', { source: 'trek-places' }),
poi('gers:off', 47.41, 11.115, 'park', { source: 'trek-places' }),
poi('gers:other', 47.41, 11.1001, 'nature', { source: 'trek-places' }),
]),
);
const result = await service.search({
tour_type: 'walk',
categories: ['park', 'museum'],
corridor_m: 500,
line: LINE,
});
// Parks and gardens alone, museums and galleries alone: not the beaches, theatres and cinemas of the explore pill.
expect(poisAlong.mock.calls[0]?.[0]).toEqual(['park', 'museum_gallery']);
expect(result.pois.map((found) => [found.id, found.category, found.source])).toEqual([
['gers:in', 'park', 'trek-places'],
]);
});
it('TOUR-POI-005: searches along a saved tour for MCP, and a tour without a line is not found', async () => {
@@ -156,7 +237,7 @@ describe('TourPoiSearchService', () => {
const trip = createTrip(db, user.id);
const ridge = createPlace(db, trip.id, { name: 'Ridge' });
createTour(db, ridge.id);
pois.mockResolvedValue(answer([poi('node:x', 47.41, 11.1)]));
poisAlong.mockResolvedValue(answer([poi('node:x', 47.41, 11.1)]));
await expect(
service.searchSavedTour(trip.id, ridge.id, { categories: ['viewpoint'], corridor_m: 500 }),
).rejects.toThrow('Tour not found');
@@ -718,11 +718,13 @@ describe('toPlaceRecord', () => {
});
describe('POI_CATEGORY_TO_TREK', () => {
it('covers every pill the planner offers', () => {
it('covers every pill the planner offers, and the kinds of the search along a tour it holds', () => {
// The keys are the contract with the client's POI_CATEGORIES. A missing one
// silently drops that pill back to Overpass, which is the slow path — and
// for the four a drive needs that is the worst path of all, because the
// corridor search asks for them sixteen boxes at a time.
// corridor search asks for them sixteen boxes at a time. Museums and
// galleries, park, market and peak are asked along a tour (PLN-02,
// CW-05), each path checked against a live answer of the index.
expect(Object.keys(POI_CATEGORY_TO_TREK).sort()).toEqual([
'activity',
'bar',
@@ -731,8 +733,12 @@ describe('POI_CATEGORY_TO_TREK', () => {
'charging',
'fuel',
'hotel',
'market',
'museum',
'museum_gallery',
'nature',
'park',
'peak',
'rest_area',
'restaurant',
'shopping',