Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

feat(tours): read way tags and horse routes from the TREK Places layers

Maurice371083ed470d
diff --git a/server/.env.example b/server/.env.example
index 2befc2e0c..417453086 100644
--- a/server/.env.example
+++ b/server/.env.example
@@ -68,7 +68,7 @@ DEMO_MODE=false # Demo mode: resets data hourly
# OVERPASS_URL= # Custom Overpass endpoint(s) for the map POI "explore" search, comma-separated. When set, REPLACES the bundled public mirrors — point it at an internal/self-hosted Overpass instance when the public ones are unreachable from your network. Non-http(s) entries are ignored. If you don't self-host Overpass but the public mirrors throttle you, setting APP_URL also gives outbound requests a unique User-Agent the mirrors rate-limit less.
# OVERPASS_TIMEOUT_MS=25000 # Per-endpoint timeout (ms) for Overpass POI requests; slower endpoints are abandoned so a faster mirror wins. The query itself gives Overpass 20 seconds of work, so a lower value hangs up on answers that were still coming. Raise it for a slow self-hosted instance. The Tours search along a tour does not read it: it gives Overpass 10 seconds of work and waits 12. (default: 25000)
-# TREK_PLACES_ENABLED=false # Whether place search asks the TREK Places API at https://places.liketrek.com: suggestions, the full search, the category buttons on the map, the Road trip search along the route, import geocoding and offline downloads. It is on by default and has no switch in the admin panel, because whether searches leave the instance is a deployment decision. Set false to search the way it did before 4.3.0 (OpenStreetMap, or your Google/Amap key) and send nothing to that host. (default: true)
+# TREK_PLACES_ENABLED=false # Whether place search asks the TREK Places API at https://places.liketrek.com: suggestions, the full search, the category buttons on the map, the Road trip search along the route, import geocoding, offline downloads, and the OpenStreetMap ways and horse routes Tours reads. It is on by default and has no switch in the admin panel, because whether searches leave the instance is a deployment decision. Set false to search the way it did before 4.3.0 (OpenStreetMap, or your Google/Amap key) and send nothing to that host. (default: true)
# TREK_PLACES_URL=https://places.liketrek.com # Base URL of a copy of the Places API you run yourself; it has to answer the same /v1 API. Read from configuration rather than typed by a user, so an address on your LAN or Docker network works without ALLOW_INTERNAL_NETWORK. (default: https://places.liketrek.com)
# PLACES_API_KEY= # Google Maps API key (Places API (New) enabled) for place search, photos, details and Google transit. Overrides the key set in Admin > Settings > API Keys, whose field then shows this variable read-only. The value never reaches the browser.
diff --git a/server/src/nest/maps/maps.module.ts b/server/src/nest/maps/maps.module.ts
index fa7ae429d..e3ad456d8 100644
--- a/server/src/nest/maps/maps.module.ts
+++ b/server/src/nest/maps/maps.module.ts
@@ -16,6 +16,7 @@ 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';
+import { TrekPlacesLayersService } from './trek-places-layers.service';
import { MikroOrmModule } from '@mikro-orm/nestjs';
import { Module } from '@nestjs/common';
@@ -28,7 +29,9 @@ import { Module } from '@nestjs/common';
* (GooglePlacesClient, OsmClient, WikimediaClient; Amap is built per request by
* PlacesProviderSelector) and the resolvers it delegates to. The three clients
* are exported too, so the enrichment column asks Google, OpenStreetMap and
- * Wikimedia directly rather than through a MapsService facade. Nothing outside
+ * Wikimedia directly rather than through a MapsService facade, and
+ * TrekPlacesLayersService, so the tours domain reads the TREK Places ways and
+ * routes layers before it asks the Overpass mirrors. Nothing outside
* the container consumes this domain, so there is no bridge.
*
* MikroOrmModule.forFeature: AppSettings and Users for the key chain
@@ -56,7 +59,8 @@ import { Module } from '@nestjs/common';
MapsUrlResolver,
PlaceDetailsResolver,
PoisAlongResolver,
+ TrekPlacesLayersService,
],
- exports: [MapsService, GooglePlacesClient, OsmClient, WikimediaClient],
+ exports: [MapsService, GooglePlacesClient, OsmClient, WikimediaClient, TrekPlacesLayersService],
})
export class MapsModule {}
diff --git a/server/src/nest/maps/trek-places-layers.service.ts b/server/src/nest/maps/trek-places-layers.service.ts
new file mode 100644
index 000000000..2f78e2de8
--- /dev/null
+++ b/server/src/nest/maps/trek-places-layers.service.ts
@@ -0,0 +1,72 @@
+import { logInfo, logWarn } from '../audit/audit-log.logger';
+import {
+ trekPlacesMiss,
+ trekPlacesRoutes,
+ trekPlacesWays,
+ type TrekPlacesMiss,
+ type TrekPlacesRoutes,
+ type TrekPlacesRouteType,
+ type TrekWayTags,
+} from './trek-places.client';
+import { Injectable } from '@nestjs/common';
+
+/** What one of the layers answered, or why it gave nothing and the caller has to ask elsewhere. */
+type TrekPlacesLayerRead<T> = { ok: true; value: T } | { ok: false; miss: TrekPlacesMiss };
+
+type Layer = 'ways' | 'routes';
+
+const WHY: Record<TrekPlacesMiss, string> = {
+ off: 'the TREK Places API is switched off on this instance',
+ not_built: 'the service has not built this layer yet',
+ failed: 'the service did not answer',
+};
+
+/**
+ * The TREK Places service's OpenStreetMap layers for the domains that used to
+ * ask the public Overpass mirrors themselves: the tags of the ways under a tour
+ * (BIK-05, MAP-03, MAP-04, RUN-02) and the horse routes around a map view
+ * (HOR-01). A call never throws: it says what the layer answered, or why it
+ * did not, and the caller goes on to Overpass.
+ *
+ * Why a layer is not used is logged once, not on every request: a service that
+ * has not built a layer yet answers 404 for weeks, and a map being panned asks
+ * every few seconds. The line comes again when the reason changes, and after
+ * the layer has answered in between.
+ */
+@Injectable()
+export class TrekPlacesLayersService {
+ private readonly told = new Map<Layer, TrekPlacesMiss>();
+
+ wayTags(ids: readonly number[]): Promise<TrekPlacesLayerRead<TrekWayTags[]>> {
+ return this.read('ways', () => trekPlacesWays(ids));
+ }
+
+ routes(
+ bbox: { south: number; west: number; north: number; east: number },
+ type: TrekPlacesRouteType,
+ limits: { relations: number; ways: number },
+ ): Promise<TrekPlacesLayerRead<TrekPlacesRoutes>> {
+ return this.read('routes', () => trekPlacesRoutes(bbox, type, limits));
+ }
+
+ private async read<T>(layer: Layer, ask: () => Promise<T>): Promise<TrekPlacesLayerRead<T>> {
+ try {
+ const value = await ask();
+ this.told.delete(layer);
+ return { ok: true, value };
+ } catch (err: unknown) {
+ const miss = trekPlacesMiss(err);
+ this.tell(layer, miss, err);
+ return { ok: false, miss };
+ }
+ }
+
+ private tell(layer: Layer, miss: TrekPlacesMiss, err: unknown): void {
+ if (this.told.get(layer) === miss) return;
+ this.told.set(layer, miss);
+ const detail = miss === 'failed' ? ` (${err instanceof Error ? err.message : String(err)})` : '';
+ const line = `[TrekPlaces] /v1/${layer}: ${WHY[miss]}${detail}; asking the Overpass mirrors instead`;
+ if (miss === 'failed') logWarn(line);
+ else logInfo(line);
+ }
+}
diff --git a/server/src/nest/maps/trek-places.client.ts b/server/src/nest/maps/trek-places.client.ts
index aede3319e..a029b86e1 100644
--- a/server/src/nest/maps/trek-places.client.ts
+++ b/server/src/nest/maps/trek-places.client.ts
@@ -162,6 +162,22 @@ export function resetTrekPlacesBreaker(): void {
breakerOpenUntil = 0;
}
+const SWITCHED_OFF_MESSAGE = 'TREK Places API is switched off on this instance';
+
+/**
+ * Why a call to one of the service's OpenStreetMap layers gave no answer, for
+ * a caller that has another source to ask: the operator switched the index off
+ * (`off`), the service answered 404 because it has not built the layer yet
+ * (`not_built`), or anything else went wrong on the way (`failed`).
+ */
+export type TrekPlacesMiss = 'off' | 'not_built' | 'failed';
+
+export function trekPlacesMiss(err: unknown): TrekPlacesMiss {
+ if ((err as { status?: number } | null)?.status === 404) return 'not_built';
+ if (err instanceof Error && err.message === SWITCHED_OFF_MESSAGE) return 'off';
+ return 'failed';
+}
+
export function trekPlacesBaseUrl(): string {
const configured = (readEnv().maps.trekPlacesUrl || '').trim();
return (configured || DEFAULT_TREK_PLACES_URL).replace(/\/+$/, '');
@@ -177,7 +193,7 @@ async function getJson<T>(
// every request passes, so a caller that did not is still stopped here. Ahead
// of the breaker: a refusal says nothing about reachability.
if (!readEnv().maps.trekPlacesEnabled) {
- throw new Error('TREK Places API is switched off on this instance');
+ throw new Error(SWITCHED_OFF_MESSAGE);
}
const url = new URL(trekPlacesBaseUrl() + path);
@@ -631,3 +647,151 @@ export function toPlaceRecord(p: TrekPlace): Record<string, unknown> {
source: 'trek-places',
};
}
+
+/**
+ * The service's two OpenStreetMap layers TREK reads elements from: the ways
+ * layer (`/v1/ways`), the tags of the ways under a tour, and the routes layer
+ * (`/v1/routes`), the route relations around a map view with their ways. Both
+ * used to be questions to the public Overpass mirrors and are answered from
+ * the planet the service builds every month, in Overpass' own element form, so
+ * the readers TREK already had read them as they are. Both answer 404 while
+ * their layer is not built; {@link trekPlacesMiss} tells that apart, and the
+ * caller asks Overpass then.
+ *
+ * Neither is cached on the far side (`no-store`), and neither carries more than
+ * the ids of ways or the edges of a box, the same that went to Overpass.
+ */
+
+/** The most way ids one /v1/ways request takes; the service refuses more with a 400. */
+const WAYS_MAX_IDS = 500;
+/** A batch of ways is a few lookups by key; not a keystroke, but somebody is looking at the tour. */
+const WAYS_TIMEOUT_MS = 10_000;
+
+/**
+ * A routes answer carries the line of every way in the box: the service stops
+ * at 250 000 points, some 40 bytes each with the node ids beside them, so a
+ * full answer is near ten megabytes. Read once per map view and kept, so the
+ * deadline is the area download's.
+ */
+const ROUTES_TIMEOUT_MS = 20_000;
+const ROUTES_MAX_BYTES = 16 * 1024 * 1024;
+/** The service's bounds on `limitRelations` and `limitWays`. */
+const ROUTES_MAX_RELATIONS = 200;
+const ROUTES_MAX_WAYS = 4000;
+/** No way or relation of the planet has more members or points than this; a longer list is not one. */
+const ROUTES_MAX_LIST = 20_000;
+
+const osmIdSchema = z.number().int().positive().max(Number.MAX_SAFE_INTEGER);
+const osmTagsSchema = z.record(z.string(), z.string());
+
+const trekWayTagsSchema = z.object({
+ type: z.literal('way'),
+ id: osmIdSchema,
+ tags: osmTagsSchema.default({}),
+});
+/** One way of the ways layer, as `way(id:...);out tags;` answers it: only the keys the layer keeps. */
+export type TrekWayTags = z.infer<typeof trekWayTagsSchema>;
+
+const pointSchema = z.object({ lat: z.number().min(-90).max(90), lon: z.number().min(-180).max(180) });
+const memberSchema = z.object({ type: z.enum(['node', 'way', 'relation']), ref: osmIdSchema, role: z.string() });
+
+const trekRouteWayFields = z.object({
+ type: z.literal('way'),
+ id: osmIdSchema,
+ tags: osmTagsSchema.default({}),
+ nodes: z.array(osmIdSchema).max(ROUTES_MAX_LIST),
+ geometry: z.array(pointSchema).max(ROUTES_MAX_LIST),
+});
+/** A line is read node by node beside its places; one that does not pair them is no line. */
+const trekRouteWaySchema = trekRouteWayFields.refine((way) => way.nodes.length === way.geometry.length);
+const trekRouteRelationSchema = z.object({
+ type: z.literal('relation'),
+ id: osmIdSchema,
+ tags: osmTagsSchema.default({}),
+ members: z.array(memberSchema).max(ROUTES_MAX_LIST),
+});
+const trekRouteElementSchema = z.union([trekRouteRelationSchema, trekRouteWaySchema]);
+type TrekRouteElement = z.infer<typeof trekRouteElementSchema>;
+
+export interface TrekPlacesRoutes {
+ /** The relations with all their members, then their ways in the box, as Overpass answers `out body geom`. */
+ elements: TrekRouteElement[];
+ /** The service stopped at one of its caps: more relations, ways or points than one answer carries. */
+ truncated: boolean;
+}
+
+/**
+ * The route types TREK asks for. The service knows more (hiking, bicycle, mtb,
+ * piste) and answers 404 for a type it has not built.
+ */
+export type TrekPlacesRouteType = 'horse';
+
+/** The rows of an answer of the right shape that are themselves of the right shape. */
+function validRows<T>(rows: readonly unknown[], schema: z.ZodType<T>): T[] {
+ return rows.flatMap((row) => {
+ const parsed = schema.safeParse(row);
+ return parsed.success ? [parsed.data] : [];
+ });
+}
+
+const elementsAnswerSchema = z.object({ elements: z.array(z.unknown()) });
+
+/**
+ * One request of at most WAYS_MAX_IDS ids. A way the layer does not know is
+ * left out, as Overpass leaves it out; a row of another shape, or for an id
+ * that was not asked, is left out on its own. An answer without `elements`
+ * is no answer: read as an empty one, every way of the tour would be kept as
+ * having no grade.
+ */
+async function trekPlacesWaysPart(ids: readonly number[]): Promise<TrekWayTags[]> {
+ const body = await getJson<unknown>('/v1/ways', { ids: ids.join(',') }, { timeoutMs: WAYS_TIMEOUT_MS });
+ const answer = elementsAnswerSchema.safeParse(body);
+ if (!answer.success) throw new Error('TREK Places API answered /v1/ways without elements');
+ const asked = new Set(ids);
+ return validRows(answer.data.elements, trekWayTagsSchema).filter((way) => asked.has(way.id));
+}
+
+/**
+ * The tags of OpenStreetMap ways by id, from the ways layer. Asked in batches
+ * of WAYS_MAX_IDS, one after another; the first batch that fails fails the
+ * whole call, so the caller never mistakes half an answer for all of it.
+ */
+export async function trekPlacesWays(ids: readonly number[]): Promise<TrekWayTags[]> {
+ const wanted = [...new Set(ids)].filter((id) => osmIdSchema.safeParse(id).success);
+ const parts = Array.from({ length: Math.ceil(wanted.length / WAYS_MAX_IDS) }, (_, index) =>
+ wanted.slice(index * WAYS_MAX_IDS, (index + 1) * WAYS_MAX_IDS),
+ );
+ return parts.reduce<Promise<TrekWayTags[]>>(
+ async (done, part) => [...(await done), ...(await trekPlacesWaysPart(part))],
+ Promise.resolve([]),
+ );
+}
+
+/**
+ * The route relations of one type that reach into a box, with their members
+ * and those of their ways that lie in it, from the routes layer. The box is
+ * sent as it is: the service takes at most a degree a side and refuses more
+ * with a 400, which the caller reads as a failure like any other.
+ */
+export async function trekPlacesRoutes(
+ bbox: { south: number; west: number; north: number; east: number },
+ type: TrekPlacesRouteType,
+ limits: { relations: number; ways: number },
+): Promise<TrekPlacesRoutes> {
+ const body = await getJson<unknown>(
+ '/v1/routes',
+ {
+ bbox: [bbox.south, bbox.west, bbox.north, bbox.east].join(','),
+ type,
+ limitRelations: clampedInt(limits.relations, 1, ROUTES_MAX_RELATIONS),
+ limitWays: clampedInt(limits.ways, 1, ROUTES_MAX_WAYS),
+ },
+ { maxBytes: ROUTES_MAX_BYTES, timeoutMs: ROUTES_TIMEOUT_MS },
+ );
+ const answer = elementsAnswerSchema.extend({ truncated: z.unknown() }).safeParse(body);
+ if (!answer.success) throw new Error('TREK Places API answered /v1/routes without elements');
+ return {
+ elements: validRows(answer.data.elements, trekRouteElementSchema),
+ truncated: answer.data.truncated === true,
+ };
+}
diff --git a/server/src/nest/tours/tour-horse-routes.service.ts b/server/src/nest/tours/tour-horse-routes.service.ts
index fa0461164..e6452a94b 100644
--- a/server/src/nest/tours/tour-horse-routes.service.ts
+++ b/server/src/nest/tours/tour-horse-routes.service.ts
@@ -1,7 +1,9 @@
import { DomainError } from '../common/domain-error';
+import { TrekPlacesLayersService } from '../maps/trek-places-layers.service';
import { OverpassElementsClient } from '../overpass/overpass-elements.service';
import {
buildHorseRoutesQuery,
+ HORSE_ROUTE_WAYS_CAP,
horseRouteBboxKey,
snapHorseRouteBbox,
toHorseRoutes,
@@ -9,12 +11,13 @@ import {
import { Injectable } from '@nestjs/common';
import {
HORSE_ROUTES_ATTRIBUTION,
+ HORSE_ROUTES_RESULT_CAP,
HORSE_ROUTES_UNAVAILABLE_CODE,
type FerrataBbox,
type HorseRoutesResponse,
} from '@trek/shared';
-/** How long an answer is kept: signposted routes change on the scale of seasons, the mirrors are shared. */
+/** How long an answer is kept: signposted routes change on the scale of seasons, and the sources are shared. */
export const HORSE_ROUTES_KEPT_MS = 12 * 60 * 60 * 1000;
/** The most answers kept at once; the one kept longest goes first. */
@@ -32,15 +35,19 @@ export const HORSE_ROUTES_UNAVAILABLE_MESSAGE = 'Horse route data is unavailable
type Answer = Omit<HorseRoutesResponse, 'source' | 'attribution'>;
/**
- * HOR-01: the signposted horse routes around a map view, from OpenStreetMap
- * through the operator's Overpass mirrors. The view is grown to the 0.05
- * degree grid, so nearby views share one answer, and an answer is kept for
- * HORSE_ROUTES_KEPT_MS in memory, within a budget of answers and of section
- * points so a busy map cannot grow the store without end; two requests for
- * the same box at once share one query. Read only: nothing is stored, and nothing about the trip is sent.
+ * HOR-01: the signposted horse routes around a map view, from OpenStreetMap:
+ * the TREK Places routes layer first, and the operator's Overpass mirrors only
+ * when that cannot answer (switched off, not built yet, or failing). Both
+ * answer in the same element form and are read the same way. The view is
+ * grown to the 0.05 degree grid, so nearby views share one answer, and an
+ * answer is kept for HORSE_ROUTES_KEPT_MS in memory, within a budget of
+ * answers and of section points so a busy map cannot grow the store without
+ * end; two requests for the same box at once share one query. Read only:
+ * nothing is stored, and nothing about the trip is sent.
*
- * When no mirror answers, the client gets a 502 `{ error, code }` it can show,
- * and whatever it had loaded before stays as it was.
+ * When neither the layer nor any mirror answers, the client gets a 502
+ * `{ error, code }` it can show, and whatever it had loaded before stays as it
+ * was.
*/
@Injectable()
export class TourHorseRoutesService {
@@ -49,7 +56,10 @@ export class TourHorseRoutesService {
private keptPoints = 0;
private readonly pending = new Map<string, Promise<Answer>>();
- constructor(private readonly overpass: OverpassElementsClient) {}
+ constructor(
+ private readonly layers: TrekPlacesLayersService,
+ private readonly overpass: OverpassElementsClient,
+ ) {}
async list(bbox: FerrataBbox, now: number = Date.now()): Promise<HorseRoutesResponse> {
const box = snapHorseRouteBbox(bbox);
@@ -74,6 +84,15 @@ export class TourHorseRoutesService {
}
private async query(box: FerrataBbox): Promise<Answer> {
+ const layer = await this.layers.routes(box, 'horse', {
+ relations: HORSE_ROUTES_RESULT_CAP,
+ ways: HORSE_ROUTE_WAYS_CAP,
+ });
+ if (layer.ok) {
+ const read = toHorseRoutes(layer.value.elements);
+ // The layer stops at the same caps the Overpass query asks one past, and says so itself.
+ return { routes: read.routes, truncated: read.truncated || layer.value.truncated };
+ }
let elements: unknown[];
try {
elements = await this.overpass.query(buildHorseRoutesQuery(box), 'HorseRoutes');
diff --git a/server/src/nest/tours/tour-trail-grade.service.ts b/server/src/nest/tours/tour-trail-grade.service.ts
index 80010de2b..a171ad4d7 100644
--- a/server/src/nest/tours/tour-trail-grade.service.ts
+++ b/server/src/nest/tours/tour-trail-grade.service.ts
@@ -1,3 +1,4 @@
+import { TrekPlacesLayersService } from '../maps/trek-places-layers.service';
import { OverpassElementsClient } from '../overpass/overpass-elements.service';
import { Injectable } from '@nestjs/common';
import {
@@ -12,7 +13,7 @@ import { z } from 'zod';
/** Ways per Overpass question: a query names them all, and a shorter one answers sooner. */
const WAYS_PER_QUERY = 400;
-/** How long a way's grades are kept: OpenStreetMap changes slowly, the mirrors are shared. */
+/** How long a way's grades are kept: OpenStreetMap changes slowly, and the sources are shared. */
const KEPT_MS = 24 * 60 * 60 * 1000;
/** The most ways kept at once; the oldest go first. */
const MAX_KEPT = 50_000;
@@ -71,15 +72,20 @@ function gradeOf(id: number, tags: Record<string, string> = {}): TourTrailGrade
/**
* BIK-05, MAP-03 and MAP-04: what OpenStreetMap records for the ways a tour
* runs on (the mountain bike scales; the SAC hiking scale, the surface and the
- * kind of way of a hike), read through the operator's Overpass mirrors. What
- * was read is kept a day, so the same tour asked about again costs the mirrors
- * nothing; ways a mirror could not answer are said, never guessed.
+ * kind of way of a hike). Read from the TREK Places ways layer, and through the
+ * operator's Overpass mirrors only when that cannot answer: switched off, not
+ * built yet, or failing. What was read is kept a day, so the same tour asked
+ * about again costs nobody anything; ways no source could answer are said,
+ * never guessed.
*/
@Injectable()
export class TourTrailGradeService {
private readonly kept = new Map<number, { grade: TourTrailGrade | null; at: number }>();
- constructor(private readonly overpass: OverpassElementsClient) {}
+ constructor(
+ private readonly layers: TrekPlacesLayersService,
+ private readonly overpass: OverpassElementsClient,
+ ) {}
async grades(request: TourTrailGradeRequest): Promise<TourTrailGradeResponse> {
const now = Date.now();
@@ -88,14 +94,7 @@ export class TourTrailGradeService {
const known = this.kept.get(id);
return !known || now - known.at > KEPT_MS;
});
- const parts = Array.from({ length: Math.ceil(unknown.length / WAYS_PER_QUERY) }, (_, index) =>
- unknown.slice(index * WAYS_PER_QUERY, (index + 1) * WAYS_PER_QUERY),
- );
- // One question after another, so a long tour does not flood the shared mirrors.
- const unanswered = await parts.reduce<Promise<number[]>>(async (done, part) => {
- const failed = await done;
- return (await this.ask(part, now)) ? failed : [...failed, ...part];
- }, Promise.resolve([]));
+ const unanswered = unknown.length === 0 ? [] : await this.read(unknown, now);
const ways = ids.flatMap((id) => {
const grade = this.kept.get(id)?.grade;
return grade ? [grade] : [];
@@ -103,14 +102,41 @@ export class TourTrailGradeService {
return { ways, unanswered };
}
- /** Reads one part's grades into what is kept; false when no mirror answered. */
- private async ask(ids: number[], now: number): Promise<boolean> {
+ /**
+ * Reads the grades of the ways not kept yet into what is kept: from the ways
+ * layer in one go, else from the mirrors part by part. Gives back the ways
+ * no source answered.
+ */
+ private async read(ids: number[], now: number): Promise<number[]> {
+ const layer = await this.layers.wayTags(ids);
+ if (layer.ok) {
+ this.keepAll(ids, layer.value, now);
+ return [];
+ }
+ const parts = Array.from({ length: Math.ceil(ids.length / WAYS_PER_QUERY) }, (_, index) =>
+ ids.slice(index * WAYS_PER_QUERY, (index + 1) * WAYS_PER_QUERY),
+ );
+ // One question after another, so a long tour does not flood the shared mirrors.
+ return parts.reduce<Promise<number[]>>(async (done, part) => {
+ const failed = await done;
+ return (await this.askOverpass(part, now)) ? failed : [...failed, ...part];
+ }, Promise.resolve([]));
+ }
+
+ /** Reads one part's grades from the mirrors into what is kept; false when no mirror answered. */
+ private async askOverpass(ids: number[], now: number): Promise<boolean> {
let elements: unknown[];
try {
elements = await this.overpass.query(`[out:json][timeout:25];way(id:${ids.join(',')});out tags;`, 'Tours');
} catch {
return false;
}
+ this.keepAll(ids, elements, now);
+ return true;
+ }
+
+ /** Keeps a grade, or that there is none, for every way asked, out of the elements one source answered. */
+ private keepAll(ids: readonly number[], elements: readonly unknown[], now: number): void {
const tagged = new Map<number, Record<string, string> | undefined>();
for (const element of elements) {
const way = wayElementSchema.safeParse(element);
@@ -118,7 +144,6 @@ export class TourTrailGradeService {
}
// A way the answer leaves out has no tags worth naming, or no longer exists: no grade either way.
for (const id of ids) this.keep(id, gradeOf(id, tagged.get(id)), now);
- return true;
}
private keep(id: number, grade: TourTrailGrade | null, at: number): void {
diff --git a/server/tests/e2e/tours-bike.e2e.test.ts b/server/tests/e2e/tours-bike.e2e.test.ts
index ab75d8c89..947c31fc9 100644
--- a/server/tests/e2e/tours-bike.e2e.test.ts
+++ b/server/tests/e2e/tours-bike.e2e.test.ts
@@ -16,6 +16,7 @@ import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
import { JourneyDomainService } from '../../src/nest/journey/journey-domain.service';
import { MapsService } from '../../src/nest/maps/maps.service';
+import { TrekPlacesLayersService } from '../../src/nest/maps/trek-places-layers.service';
import { OverpassElementsClient } from '../../src/nest/overpass/overpass-elements.service';
import { PermissionsService } from '../../src/nest/permissions/permissions.service';
import { RealtimeModule } from '../../src/nest/realtime/realtime.module';
@@ -56,8 +57,10 @@ const { journeyHooks } = vi.hoisted(() => ({
const db = createSnapshotTestDb();
const mapsPois = vi.fn();
-// The trail grades (BIK-05) read OpenStreetMap through Overpass: no network in a test.
+// The trail grades (BIK-05) read OpenStreetMap from the TREK Places ways layer, else through
+// Overpass: no network in a test.
const overpassQuery = vi.fn();
+const placesWayTags = vi.fn();
const realtime = new FakeRealtimeService();
let orm: TestOrm;
@@ -111,6 +114,8 @@ describe('Bike tours e2e (real guards + temp SQLite)', () => {
.useValue({ pois: mapsPois })
.overrideProvider(OverpassElementsClient)
.useValue({ query: overpassQuery })
+ .overrideProvider(TrekPlacesLayersService)
+ .useValue({ wayTags: placesWayTags })
.compile();
const nest = moduleRef.createNestApplication();
nest.use(cookieParser());
@@ -155,6 +160,8 @@ describe('Bike tours e2e (real guards + temp SQLite)', () => {
);
await setAddonEnabled(orm, 'tours', true);
realtime.broadcastMock.mockClear();
+ // The ways layer not built yet unless a case says otherwise, so the grades come through Overpass.
+ placesWayTags.mockReset().mockResolvedValue({ ok: false, miss: 'not_built' });
await deleteRows(orm, DayAssignments);
await deleteRows(orm, Places);
});
@@ -314,6 +321,33 @@ describe('Bike tours e2e (real guards + temp SQLite)', () => {
});
});
+ it('reads the grades from the TREK Places ways layer when it has them, asking no mirror', async () => {
+ overpassQuery.mockReset();
+ placesWayTags.mockResolvedValueOnce({
+ ok: true,
+ value: [{ type: 'way', id: 21, tags: { 'mtb:scale': '1', surface: 'gravel', highway: 'track' } }],
+ });
+ const res = await ask({ way_ids: [21, 22] }, VIEWER);
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual({
+ ways: [
+ {
+ id: 21,
+ mtb_scale: '1',
+ mtb_scale_uphill: null,
+ mtb_scale_imba: null,
+ sac_scale: null,
+ sac_scale_unclear: null,
+ surface: 'gravel',
+ highway: 'track',
+ },
+ ],
+ unanswered: [],
+ });
+ expect(placesWayTags).toHaveBeenCalledWith([21, 22]);
+ expect(overpassQuery).not.toHaveBeenCalled();
+ });
+
it('refuses an outsider, a body it does not know, and no session', async () => {
expect((await ask({ way_ids: [1] }, OUTSIDER)).status).toBe(404);
const statuses = await [{ way_ids: [] }, { way_ids: [0] }, { way_ids: [1], extra: 1 }].reduce<Promise<number[]>>(
diff --git a/server/tests/e2e/tours-horse.e2e.test.ts b/server/tests/e2e/tours-horse.e2e.test.ts
index de5f94751..62380347c 100644
--- a/server/tests/e2e/tours-horse.e2e.test.ts
+++ b/server/tests/e2e/tours-horse.e2e.test.ts
@@ -17,6 +17,7 @@ import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
import { JourneyDomainService } from '../../src/nest/journey/journey-domain.service';
import { MapsService } from '../../src/nest/maps/maps.service';
+import { TrekPlacesLayersService } from '../../src/nest/maps/trek-places-layers.service';
import { OverpassElementsClient } from '../../src/nest/overpass/overpass-elements.service';
import { PermissionsService } from '../../src/nest/permissions/permissions.service';
import { RealtimeModule } from '../../src/nest/realtime/realtime.module';
@@ -59,8 +60,10 @@ const { journeyHooks } = vi.hoisted(() => ({
}));
const db = createSnapshotTestDb();
-// The horse routes come from OpenStreetMap through Overpass: no network in a test.
+// The horse routes come from OpenStreetMap, from the TREK Places routes layer or else through
+// Overpass: no network in a test.
const overpassQuery = vi.fn();
+const placesRoutes = vi.fn();
const realtime = new FakeRealtimeService();
let orm: TestOrm;
@@ -157,6 +160,8 @@ describe('Horse tours e2e (real guards + temp SQLite)', () => {
.useValue({ pois: vi.fn() })
.overrideProvider(OverpassElementsClient)
.useValue({ query: overpassQuery })
+ .overrideProvider(TrekPlacesLayersService)
+ .useValue({ routes: placesRoutes })
.compile();
const nest = moduleRef.createNestApplication<NestExpressApplication>();
// The ceiling bootstrap.ts gives a tour create or edit, in place of the 100kb default.
@@ -195,6 +200,8 @@ describe('Horse tours e2e (real guards + temp SQLite)', () => {
await setAddonEnabled(orm, 'tours', true);
realtime.broadcastMock.mockClear();
overpassQuery.mockReset();
+ // The routes layer not built yet unless a case says otherwise, so the routes come through Overpass.
+ placesRoutes.mockReset().mockResolvedValue({ ok: false, miss: 'not_built' });
await deleteRows(orm, DayAssignments);
await deleteRows(orm, Places);
});
@@ -360,6 +367,19 @@ describe('Horse tours e2e (real guards + temp SQLite)', () => {
});
});
+ it('reads the routes from the TREK Places routes layer when it has them, asking no mirror', async () => {
+ placesRoutes.mockResolvedValueOnce({ ok: true, value: { elements: overpassAnswer, truncated: true } });
+ const res = await ask('46.12,11.21,46.18,11.29', VIEWER);
+ expect(res.status).toBe(200);
+ expect(res.body).toMatchObject({ truncated: true, source: 'openstreetmap' });
+ expect(res.body.routes).toEqual([expect.objectContaining({ id: 'relation/42', name: 'Reitweg Isartal' })]);
+ expect(placesRoutes).toHaveBeenCalledWith({ south: 46.1, west: 11.2, north: 46.2, east: 11.3 }, 'horse', {
+ relations: 60,
+ ways: 4000,
+ });
+ expect(overpassQuery).not.toHaveBeenCalled();
+ });
+
it('says when no mirror answered, and refuses a box too large, an outsider and no session', async () => {
overpassQuery.mockRejectedValueOnce(new Error('all mirrors down'));
const failed = await ask('48.12,11.21,48.18,11.29', OWNER);
diff --git a/server/tests/unit/nest/tour-horse-routes.service.test.ts b/server/tests/unit/nest/tour-horse-routes.service.test.ts
index 6868c95f4..304e6460e 100644
--- a/server/tests/unit/nest/tour-horse-routes.service.test.ts
+++ b/server/tests/unit/nest/tour-horse-routes.service.test.ts
@@ -1,5 +1,7 @@
import { DomainError } from '../../../src/nest/common/domain-error';
+import { TrekPlacesLayersService } from '../../../src/nest/maps/trek-places-layers.service';
import { OverpassElementsClient } from '../../../src/nest/overpass/overpass-elements.service';
+import { HORSE_ROUTE_WAYS_CAP } from '../../../src/nest/tours/tour-horse-routes.helpers';
import {
HORSE_ROUTES_KEPT_MAX,
HORSE_ROUTES_KEPT_MS,
@@ -8,13 +10,19 @@ import {
TourHorseRoutesService,
} from '../../../src/nest/tours/tour-horse-routes.service';
import { Test } from '@nestjs/testing';
-import { HORSE_ROUTES_ATTRIBUTION, HORSE_ROUTES_UNAVAILABLE_CODE, horseRoutesResponseSchema } from '@trek/shared';
+import {
+ HORSE_ROUTES_ATTRIBUTION,
+ HORSE_ROUTES_RESULT_CAP,
+ HORSE_ROUTES_UNAVAILABLE_CODE,
+ horseRoutesResponseSchema,
+} from '@trek/shared';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-// HORSE-SVC-001 to HORSE-SVC-006
+// HORSE-SVC-001 to HORSE-SVC-010
const query = vi.fn<(q: string, caller: string) => Promise<unknown[]>>();
+const routes = vi.fn<TrekPlacesLayersService['routes']>();
let service: TourHorseRoutesService;
const NOW = 1_800_000_000_000;
@@ -33,10 +41,36 @@ const elements = [
},
];
+// The same routes as the layer answers them: every way of the relation's members, tags limited to its keys.
+const layerElements = [
+ {
+ type: 'relation' as const,
+ id: 7,
+ tags: { route: 'horse', name: 'Reitweg' },
+ members: [{ type: 'way' as const, ref: 1, role: '' }],
+ },
+ {
+ type: 'way' as const,
+ id: 1,
+ tags: { horse: 'designated' },
+ nodes: [1, 2],
+ geometry: [
+ { lat: 47.15, lon: 11.25 },
+ { lat: 47.16, lon: 11.25 },
+ ],
+ },
+];
+
beforeEach(async () => {
query.mockReset();
+ // The TREK Places routes layer not built yet, unless a case says otherwise: the Overpass path.
+ routes.mockReset().mockResolvedValue({ ok: false, miss: 'not_built' });
const moduleRef = await Test.createTestingModule({
- providers: [TourHorseRoutesService, { provide: OverpassElementsClient, useValue: { query } }],
+ providers: [
+ TourHorseRoutesService,
+ { provide: OverpassElementsClient, useValue: { query } },
+ { provide: TrekPlacesLayersService, useValue: { routes } },
+ ],
}).compile();
service = moduleRef.get(TourHorseRoutesService);
});
@@ -133,4 +167,51 @@ describe('TourHorseRoutesService (HOR-01)', () => {
await service.list(box, NOW);
expect(query).toHaveBeenCalledTimes(3);
});
+
+ it('HORSE-SVC-007: reads the routes from the TREK Places routes layer first, for the box grown to the grid', async () => {
+ routes.mockResolvedValue({ ok: true, value: { elements: layerElements, truncated: false } });
+ const answer = await service.list(box, NOW);
+ expect(horseRoutesResponseSchema.parse(answer)).toEqual(answer);
+ expect(answer).toMatchObject({ truncated: false, source: 'openstreetmap', attribution: HORSE_ROUTES_ATTRIBUTION });
+ expect(answer.routes.map((route) => route.id)).toEqual(['relation/7']);
+ expect(routes).toHaveBeenCalledWith({ south: 47.1, west: 11.2, north: 47.2, east: 11.3 }, 'horse', {
+ relations: HORSE_ROUTES_RESULT_CAP,
+ ways: HORSE_ROUTE_WAYS_CAP,
+ });
+ expect(query).not.toHaveBeenCalled();
+ // Kept like any answer: a nearby view asks nobody.
+ await service.list({ south: 47.11, west: 11.22, north: 47.19, east: 11.28 }, NOW + 1000);
+ expect(routes).toHaveBeenCalledTimes(1);
+ });
+
+ it('HORSE-SVC-008: says truncated when the layer stopped at one of its caps', async () => {
+ routes.mockResolvedValue({ ok: true, value: { elements: layerElements, truncated: true } });
+ const answer = await service.list(box, NOW);
+ expect(answer.truncated).toBe(true);
+ expect(answer.routes).toHaveLength(1);
+ });
+
+ it('HORSE-SVC-009: a layer not built, failing or switched off sends the box to the mirrors', async () => {
+ routes
+ .mockResolvedValueOnce({ ok: false, miss: 'not_built' })
+ .mockResolvedValueOnce({ ok: false, miss: 'failed' })
+ .mockResolvedValueOnce({ ok: false, miss: 'off' });
+ query.mockResolvedValue(elements);
+ const boxes = [box, { ...box, south: 48.12, north: 48.18 }, { ...box, south: 49.12, north: 49.18 }];
+ const answers = await boxes.reduce<Promise<number[]>>(
+ async (done, view) => [...(await done), (await service.list(view, NOW)).routes.length],
+ Promise.resolve([]),
+ );
+ expect(answers).toEqual([1, 1, 1]);
+ expect(routes).toHaveBeenCalledTimes(3);
+ expect(query).toHaveBeenCalledTimes(3);
+ });
+
+ it('HORSE-SVC-010: the layer failing and no mirror answering is the 502 the client can show', async () => {
+ routes.mockResolvedValue({ ok: false, miss: 'failed' });
+ query.mockRejectedValue(new Error('all mirrors down'));
+ const failure = await service.list(box, NOW).catch((err: unknown) => err);
+ expect(failure).toBeInstanceOf(DomainError);
+ expect((failure as DomainError).getStatus()).toBe(502);
+ });
});
diff --git a/server/tests/unit/nest/tour-trail-grade.service.test.ts b/server/tests/unit/nest/tour-trail-grade.service.test.ts
index 101ef02cc..9e47632fc 100644
--- a/server/tests/unit/nest/tour-trail-grade.service.test.ts
+++ b/server/tests/unit/nest/tour-trail-grade.service.test.ts
@@ -1,18 +1,26 @@
+import { TrekPlacesLayersService } from '../../../src/nest/maps/trek-places-layers.service';
import { OverpassElementsClient } from '../../../src/nest/overpass/overpass-elements.service';
import { TourTrailGradeService } from '../../../src/nest/tours/tour-trail-grade.service';
import { Test } from '@nestjs/testing';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-// TOUR-GRADE-001 to TOUR-GRADE-010
+// TOUR-GRADE-001 to TOUR-GRADE-016
const query = vi.fn<(q: string, caller: string) => Promise<unknown[]>>();
+const wayTags = vi.fn<TrekPlacesLayersService['wayTags']>();
let service: TourTrailGradeService;
beforeEach(async () => {
query.mockReset();
+ // The TREK Places ways layer not built yet, unless a case says otherwise: the Overpass path.
+ wayTags.mockReset().mockResolvedValue({ ok: false, miss: 'not_built' });
const moduleRef = await Test.createTestingModule({
- providers: [TourTrailGradeService, { provide: OverpassElementsClient, useValue: { query } }],
+ providers: [
+ TourTrailGradeService,
+ { provide: OverpassElementsClient, useValue: { query } },
+ { provide: TrekPlacesLayersService, useValue: { wayTags } },
+ ],
}).compile();
service = moduleRef.get(TourTrailGradeService);
});
@@ -146,4 +154,86 @@ describe('TourTrailGradeService (BIK-05)', () => {
query.mockResolvedValue([way(1, { tracktype: 'grade1', smoothness: 'good', 'surface:note': 'gravel' })]);
expect(await service.grades({ way_ids: [1] })).toEqual({ ways: [], unanswered: [] });
});
+
+ it('TOUR-GRADE-011: reads the ways from the TREK Places ways layer first and asks no mirror', async () => {
+ wayTags.mockResolvedValue({
+ ok: true,
+ value: [
+ { type: 'way', id: 1, tags: { 'mtb:scale': '2', sac_scale: 'hiking', surface: 'gravel', highway: 'path' } },
+ { type: 'way', id: 2, tags: { highway: 'track' } },
+ ],
+ });
+ const answer = await service.grades({ way_ids: [1, 2, 3, 1] });
+ expect(wayTags).toHaveBeenCalledWith([1, 2, 3]);
+ expect(query).not.toHaveBeenCalled();
+ expect(answer).toEqual({
+ ways: [
+ {
+ ...NO_MTB,
+ id: 1,
+ mtb_scale: '2',
+ sac_scale: 'hiking',
+ sac_scale_unclear: null,
+ surface: 'gravel',
+ highway: 'path',
+ },
+ { ...NO_MTB, ...NO_SAC, id: 2, surface: null, highway: 'track' },
+ ],
+ unanswered: [],
+ });
+ });
+
+ it('TOUR-GRADE-012: hands a long tour to the layer whole, which asks it in batches itself', async () => {
+ wayTags.mockResolvedValue({ ok: true, value: [{ type: 'way', id: 900, tags: { 'mtb:scale': '5' } }] });
+ const ids = Array.from({ length: 900 }, (_, index) => index + 1);
+ const answer = await service.grades({ way_ids: ids });
+ expect(wayTags).toHaveBeenCalledTimes(1);
+ expect(wayTags.mock.calls[0]?.[0]).toHaveLength(900);
+ expect(answer.ways.map((grade) => grade.id)).toEqual([900]);
+ expect(answer.unanswered).toEqual([]);
+ });
+
+ it('TOUR-GRADE-013: a layer not built yet sends the ways to the mirrors as before', async () => {
+ query.mockResolvedValue([way(1, { 'mtb:scale': '1' })]);
+ const answer = await service.grades({ way_ids: [1] });
+ expect(wayTags).toHaveBeenCalledTimes(1);
+ expect(query).toHaveBeenCalledWith('[out:json][timeout:25];way(id:1);out tags;', 'Tours');
+ expect(answer.ways.map((grade) => grade.mtb_scale)).toEqual(['1']);
+ });
+
+ it('TOUR-GRADE-014: a layer that fails or is switched off sends the ways to the mirrors, and none answering is said', async () => {
+ wayTags.mockResolvedValueOnce({ ok: false, miss: 'failed' }).mockResolvedValueOnce({ ok: false, miss: 'off' });
+ query.mockRejectedValueOnce(new Error('all mirrors down')).mockResolvedValueOnce([way(2, { surface: 'sand' })]);
+ expect(await service.grades({ way_ids: [1] })).toEqual({ ways: [], unanswered: [1] });
+ expect(await service.grades({ way_ids: [2] })).toEqual({
+ ways: [{ ...NO_MTB, ...NO_SAC, id: 2, surface: 'sand', highway: null }],
+ unanswered: [],
+ });
+ expect(query).toHaveBeenCalledTimes(2);
+ });
+
+ it('TOUR-GRADE-015: keeps what the layer answered a day, a way it left out as having no grade', async () => {
+ vi.useFakeTimers();
+ try {
+ wayTags.mockResolvedValue({ ok: true, value: [{ type: 'way', id: 1, tags: { 'mtb:scale': '3' } }] });
+ expect(await service.grades({ way_ids: [1, 2] })).toMatchObject({ unanswered: [] });
+ expect(await service.grades({ way_ids: [2, 1] })).toMatchObject({ ways: [{ id: 1 }], unanswered: [] });
+ expect(wayTags).toHaveBeenCalledTimes(1);
+ vi.advanceTimersByTime(24 * 60 * 60 * 1000 + 1);
+ await service.grades({ way_ids: [1] });
+ expect(wayTags).toHaveBeenCalledTimes(2);
+ expect(query).not.toHaveBeenCalled();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('TOUR-GRADE-016: skips what is no way in the layer answer as it does in a mirror answer', async () => {
+ wayTags.mockResolvedValue({
+ ok: true,
+ // Typed rows from the client, but read through the same check as the mirrors' answer.
+ value: [{ type: 'way', id: 0, tags: { 'mtb:scale': '1' } }],
+ });
+ expect(await service.grades({ way_ids: [1] })).toEqual({ ways: [], unanswered: [] });
+ });
});
diff --git a/server/tests/unit/nest/trek-places-layers.service.test.ts b/server/tests/unit/nest/trek-places-layers.service.test.ts
new file mode 100644
index 000000000..006aa7315
--- /dev/null
+++ b/server/tests/unit/nest/trek-places-layers.service.test.ts
@@ -0,0 +1,122 @@
+/**
+ * TrekPlacesLayersService: the TREK Places ways and routes layers for the
+ * domains that used to ask Overpass themselves. What it hands on, how it reads
+ * a failure, and that it says why a layer is not used once rather than on
+ * every request.
+ */
+import { logInfo, logWarn } from '../../../src/nest/audit/audit-log.logger';
+import { TrekPlacesLayersService } from '../../../src/nest/maps/trek-places-layers.service';
+import { trekPlacesRoutes, trekPlacesWays } from '../../../src/nest/maps/trek-places.client';
+import { Test } from '@nestjs/testing';
+
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+// TREK-LAYERS-001 to TREK-LAYERS-006
+
+vi.mock('../../../src/nest/audit/audit-log.logger', () => ({
+ LOG_LEVEL: 'error',
+ logInfo: vi.fn(),
+ logDebug: vi.fn(),
+ logError: vi.fn(),
+ logWarn: vi.fn(),
+}));
+
+// The client's requests are its own suite's subject; here only what they answer matters.
+vi.mock('../../../src/nest/maps/trek-places.client', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('../../../src/nest/maps/trek-places.client')>()),
+ trekPlacesWays: vi.fn(),
+ trekPlacesRoutes: vi.fn(),
+}));
+
+const ways = vi.mocked(trekPlacesWays);
+const routes = vi.mocked(trekPlacesRoutes);
+const info = vi.mocked(logInfo);
+const warn = vi.mocked(logWarn);
+
+const notBuilt = () => Object.assign(new Error('TREK Places API 404'), { status: 404 });
+const down = () => Object.assign(new Error('TREK Places API 503'), { status: 503 });
+// The client's own refusal when the operator switched the index off.
+const off = () => new Error('TREK Places API is switched off on this instance');
+
+const BOX = { south: 47.1, west: 11.2, north: 47.2, east: 11.3 };
+const CAPS = { relations: 60, ways: 4000 };
+
+let service: TrekPlacesLayersService;
+
+beforeEach(async () => {
+ ways.mockReset();
+ routes.mockReset();
+ info.mockClear();
+ warn.mockClear();
+ const moduleRef = await Test.createTestingModule({ providers: [TrekPlacesLayersService] }).compile();
+ service = moduleRef.get(TrekPlacesLayersService);
+});
+
+describe('TrekPlacesLayersService', () => {
+ it('TREK-LAYERS-001: hands on what a layer answered, asked as the caller asked', async () => {
+ ways.mockResolvedValue([{ type: 'way', id: 1, tags: { highway: 'path' } }]);
+ routes.mockResolvedValue({ elements: [], truncated: true });
+ expect(await service.wayTags([1, 2])).toEqual({
+ ok: true,
+ value: [{ type: 'way', id: 1, tags: { highway: 'path' } }],
+ });
+ expect(await service.routes(BOX, 'horse', CAPS)).toEqual({ ok: true, value: { elements: [], truncated: true } });
+ expect(ways).toHaveBeenCalledWith([1, 2]);
+ expect(routes).toHaveBeenCalledWith(BOX, 'horse', CAPS);
+ expect(info).not.toHaveBeenCalled();
+ expect(warn).not.toHaveBeenCalled();
+ });
+
+ it('TREK-LAYERS-002: a layer not built yet is said once, however often it is asked', async () => {
+ ways.mockRejectedValue(notBuilt());
+ expect(await service.wayTags([1])).toEqual({ ok: false, miss: 'not_built' });
+ expect(await service.wayTags([2])).toEqual({ ok: false, miss: 'not_built' });
+ expect(info).toHaveBeenCalledTimes(1);
+ expect(info.mock.calls[0]?.[0]).toContain('/v1/ways');
+ expect(info.mock.calls[0]?.[0]).toContain('not built');
+ expect(warn).not.toHaveBeenCalled();
+ });
+
+ it('TREK-LAYERS-003: a failure is a warning with its reason, once until the reason changes', async () => {
+ routes.mockRejectedValue(down());
+ expect(await service.routes(BOX, 'horse', CAPS)).toEqual({ ok: false, miss: 'failed' });
+ await service.routes(BOX, 'horse', CAPS);
+ expect(warn).toHaveBeenCalledTimes(1);
+ expect(warn.mock.calls[0]?.[0]).toContain('/v1/routes');
+ expect(warn.mock.calls[0]?.[0]).toContain('TREK Places API 503');
+ routes.mockRejectedValue(notBuilt());
+ await service.routes(BOX, 'horse', CAPS);
+ expect(info).toHaveBeenCalledTimes(1);
+ routes.mockRejectedValue('not an error');
+ expect(await service.routes(BOX, 'horse', CAPS)).toEqual({ ok: false, miss: 'failed' });
+ expect(warn).toHaveBeenCalledTimes(2);
+ expect(warn.mock.calls[1]?.[0]).toContain('not an error');
+ });
+
+ it('TREK-LAYERS-004: the off switch is said once as a note, not a warning', async () => {
+ ways.mockRejectedValue(off());
+ expect(await service.wayTags([1])).toEqual({ ok: false, miss: 'off' });
+ await service.wayTags([1]);
+ expect(info).toHaveBeenCalledTimes(1);
+ expect(info.mock.calls[0]?.[0]).toContain('switched off');
+ expect(warn).not.toHaveBeenCalled();
+ });
+
+ it('TREK-LAYERS-005: after a layer answered, the same failure is said again', async () => {
+ ways.mockRejectedValueOnce(down()).mockResolvedValueOnce([]).mockRejectedValueOnce(down());
+ await service.wayTags([1]);
+ expect(await service.wayTags([1])).toEqual({ ok: true, value: [] });
+ await service.wayTags([1]);
+ expect(warn).toHaveBeenCalledTimes(2);
+ });
+
+ it('TREK-LAYERS-006: each layer is said for itself', async () => {
+ ways.mockRejectedValue(notBuilt());
+ routes.mockRejectedValue(notBuilt());
+ await service.wayTags([1]);
+ await service.routes(BOX, 'horse', CAPS);
+ await service.wayTags([1]);
+ await service.routes(BOX, 'horse', CAPS);
+ expect(info.mock.calls.map(([line]) => line.includes('/v1/ways'))).toEqual([true, false]);
+ });
+});
diff --git a/server/tests/unit/nest/trek-places.client.test.ts b/server/tests/unit/nest/trek-places.client.test.ts
index b9505988a..5f46ee948 100644
--- a/server/tests/unit/nest/trek-places.client.test.ts
+++ b/server/tests/unit/nest/trek-places.client.test.ts
@@ -14,8 +14,11 @@ import {
trekPlacesBaseUrl,
trekPlacesById,
trekPlacesHighlights,
+ trekPlacesMiss,
trekPlacesNearby,
+ trekPlacesRoutes,
trekPlacesSearch,
+ trekPlacesWays,
resetTrekPlacesBreaker,
serviceLang,
type TrekPlace,
@@ -874,3 +877,190 @@ describe('indexRowTerm (#2663)', () => {
);
});
});
+
+// TREK-PLACES-WAYS-01 to 05, TREK-PLACES-ROUTES-01 to 05, TREK-PLACES-MISS-01
+
+/** A fetch answering each call with the next of `answers`, the last one again once they run out. */
+function stubFetchSequence(answers: { body: unknown; status?: number }[]) {
+ calls = [];
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async (url: URL | string, init?: RequestInit) => {
+ calls.push({ url: String(url), init });
+ const next = answers[Math.min(calls.length, answers.length) - 1];
+ const status = next?.status ?? 200;
+ return {
+ ok: status >= 200 && status < 300,
+ status,
+ body: null,
+ text: async () => JSON.stringify(next?.body),
+ } as unknown as Response;
+ }),
+ );
+}
+
+const askedIds = (call: { url: string }) => new URL(call.url).searchParams.get('ids');
+
+describe('trekPlacesWays', () => {
+ it('TREK-PLACES-WAYS-01: asks /v1/ways for the ids and reads the ways in Overpass form', async () => {
+ stubFetch({
+ elements: [
+ { type: 'way', id: 11, tags: { 'mtb:scale': '2', highway: 'path' } },
+ { type: 'way', id: 12 },
+ ],
+ missing: [13],
+ keys: ['highway', 'mtb:scale'],
+ });
+ const ways = await trekPlacesWays([11, 12, 13]);
+ const url = new URL(calls[0].url);
+ expect(url.pathname).toBe('/v1/ways');
+ expect(url.searchParams.get('ids')).toBe('11,12,13');
+ expect((calls[0].init?.headers as Record<string, string>)['X-TREK-Instance']).toMatch(/^trek-/);
+ expect(calls[0].init?.signal).toBeInstanceOf(AbortSignal);
+ // A way without tags reads as one without tags, never as a malformed row.
+ expect(ways).toEqual([
+ { type: 'way', id: 11, tags: { 'mtb:scale': '2', highway: 'path' } },
+ { type: 'way', id: 12, tags: {} },
+ ]);
+ });
+
+ it('TREK-PLACES-WAYS-02: asks in batches of 500, one after another, each id once, and nothing for no id', async () => {
+ stubFetch({ elements: [] });
+ const ids = Array.from({ length: 1200 }, (_, index) => index + 1);
+ await trekPlacesWays([...ids, 1, 2, 0, -3, 1.5, Number.NaN]);
+ expect(calls.map((call) => askedIds(call)?.split(',').length)).toEqual([500, 500, 200]);
+ expect(askedIds(calls[0])?.startsWith('1,2,3,')).toBe(true);
+ expect(askedIds(calls[2])?.endsWith(',1200')).toBe(true);
+ calls = [];
+ await expect(trekPlacesWays([])).resolves.toEqual([]);
+ await expect(trekPlacesWays([0, -1])).resolves.toEqual([]);
+ expect(calls).toHaveLength(0);
+ });
+
+ it('TREK-PLACES-WAYS-03: drops a row of another shape or for a way not asked, keeping the others', async () => {
+ stubFetch({
+ elements: [
+ { type: 'way', id: 1, tags: { surface: 'gravel' } },
+ { type: 'node', id: 2, tags: {} },
+ { type: 'way', id: 3, tags: { surface: 4 } },
+ { type: 'way', id: 99, tags: { surface: 'asphalt' } },
+ 'row',
+ ],
+ });
+ expect(await trekPlacesWays([1, 2, 3])).toEqual([{ type: 'way', id: 1, tags: { surface: 'gravel' } }]);
+ });
+
+ it('TREK-PLACES-WAYS-04: an answer without elements fails rather than reading as ways without tags', async () => {
+ stubFetch({ ways: [] });
+ await expect(trekPlacesWays([1])).rejects.toThrow('without elements');
+ stubFetch(null);
+ await expect(trekPlacesWays([1])).rejects.toThrow('without elements');
+ });
+
+ it('TREK-PLACES-WAYS-05: a batch that fails fails the call and asks no further, and the off switch asks nothing', async () => {
+ stubFetchSequence([{ body: { elements: [] } }, { body: {}, status: 503 }, { body: { elements: [] } }]);
+ const ids = Array.from({ length: 1400 }, (_, index) => index + 1);
+ const failure = await trekPlacesWays(ids).catch((err: unknown) => err);
+ expect(trekPlacesMiss(failure)).toBe('failed');
+ expect(calls).toHaveLength(2);
+ stubFetch({}, 404);
+ expect(trekPlacesMiss(await trekPlacesWays([1]).catch((err: unknown) => err))).toBe('not_built');
+ env.maps.trekPlacesEnabled = false;
+ calls = [];
+ expect(trekPlacesMiss(await trekPlacesWays([1]).catch((err: unknown) => err))).toBe('off');
+ expect(calls).toHaveLength(0);
+ });
+});
+
+describe('trekPlacesRoutes', () => {
+ const VIEW = { south: 47.1, west: 11.2, north: 47.2, east: 11.3 };
+ const CAPS = { relations: 60, ways: 4000 };
+ const RELATION = {
+ type: 'relation',
+ id: 7,
+ tags: { route: 'horse', name: 'Reitweg' },
+ members: [
+ { type: 'way', ref: 1, role: '' },
+ { type: 'node', ref: 5, role: 'guidepost' },
+ ],
+ };
+ const WAY = {
+ type: 'way',
+ id: 1,
+ tags: { horse: 'designated' },
+ nodes: [10, 11],
+ geometry: [
+ { lat: 47.15, lon: 11.25 },
+ { lat: 47.16, lon: 11.25 },
+ ],
+ };
+
+ it('TREK-PLACES-ROUTES-01: asks /v1/routes for the box, the type and the caps, kept inside the service bounds', async () => {
+ stubFetch({ elements: [RELATION, WAY], truncated: false });
+ const routes = await trekPlacesRoutes(VIEW, 'horse', CAPS);
+ const url = new URL(calls[0].url);
+ expect(url.pathname).toBe('/v1/routes');
+ expect(url.searchParams.get('bbox')).toBe('47.1,11.2,47.2,11.3');
+ expect(url.searchParams.get('type')).toBe('horse');
+ expect(url.searchParams.get('limitRelations')).toBe('60');
+ expect(url.searchParams.get('limitWays')).toBe('4000');
+ expect(routes).toEqual({ elements: [RELATION, WAY], truncated: false });
+ await trekPlacesRoutes(VIEW, 'horse', { relations: 999, ways: 0 });
+ const clamped = new URL(calls[1].url).searchParams;
+ expect([clamped.get('limitRelations'), clamped.get('limitWays')]).toEqual(['200', '1']);
+ });
+
+ it('TREK-PLACES-ROUTES-02: drops an element of another shape on its own, and fills the tags one left off', async () => {
+ stubFetch({
+ elements: [
+ RELATION,
+ { ...RELATION, id: 8, members: [{ type: 'area', ref: 1, role: '' }] },
+ { ...WAY, id: 2, nodes: [10] },
+ { ...WAY, id: 3, geometry: [{ lat: 95, lon: 11 }, WAY.geometry[1]] },
+ { ...WAY, id: 4, tags: undefined },
+ { type: 'node', id: 5 },
+ ],
+ truncated: true,
+ });
+ const routes = await trekPlacesRoutes(VIEW, 'horse', CAPS);
+ expect(routes.elements.map((element) => element.id)).toEqual([7, 4]);
+ expect(routes.elements[1]).toMatchObject({ id: 4, tags: {} });
+ expect(routes.truncated).toBe(true);
+ });
+
+ it('TREK-PLACES-ROUTES-03: reads truncated only when the service says true', async () => {
+ stubFetch({ elements: [], truncated: 'yes' });
+ expect(await trekPlacesRoutes(VIEW, 'horse', CAPS)).toEqual({ elements: [], truncated: false });
+ stubFetch({ elements: [] });
+ expect((await trekPlacesRoutes(VIEW, 'horse', CAPS)).truncated).toBe(false);
+ });
+
+ it('TREK-PLACES-ROUTES-04: an answer without elements fails, and a type not built is a 404', async () => {
+ stubFetch({ routes: [] });
+ await expect(trekPlacesRoutes(VIEW, 'horse', CAPS)).rejects.toThrow('without elements');
+ stubFetch({ detail: 'route type horse not built' }, 404);
+ const failure = await trekPlacesRoutes(VIEW, 'horse', CAPS).catch((err: unknown) => err);
+ expect(trekPlacesMiss(failure)).toBe('not_built');
+ });
+
+ it('TREK-PLACES-ROUTES-05: reads an answer past the search cap, since a view of routes carries their lines', async () => {
+ const payload = JSON.stringify({ elements: [RELATION, WAY], truncated: false, pad: 'x'.repeat(1_500_000) });
+ stubStreamingFetch([encoder.encode(payload)]);
+ const routes = await trekPlacesRoutes(VIEW, 'horse', CAPS);
+ expect(routes.elements).toHaveLength(2);
+ expect(streamCancelled).toBe(false);
+ });
+});
+
+describe('trekPlacesMiss', () => {
+ it('TREK-PLACES-MISS-01: tells a missing layer, the off switch and any other failure apart', async () => {
+ const notBuilt = Object.assign(new Error('TREK Places API 404'), { status: 404 });
+ expect(trekPlacesMiss(notBuilt)).toBe('not_built');
+ env.maps.trekPlacesEnabled = false;
+ expect(trekPlacesMiss(await trekPlacesSearch('x').catch((err: unknown) => err))).toBe('off');
+ expect(trekPlacesMiss(Object.assign(new Error('TREK Places API 500'), { status: 500 }))).toBe('failed');
+ expect(trekPlacesMiss(new Error('aborted'))).toBe('failed');
+ expect(trekPlacesMiss(null)).toBe('failed');
+ expect(trekPlacesMiss('nope')).toBe('failed');
+ });
+});
diff --git a/wiki/TREK-Places-API.md b/wiki/TREK-Places-API.md
index afa6137f5..c0b2c9d7c 100644
--- a/wiki/TREK-Places-API.md
+++ b/wiki/TREK-Places-API.md
@@ -35,6 +35,8 @@ Names are the ones the index has, which are the names used on the spot. The inde
| Opening a place picked from it | Address, contact details, opening hours and description | The place keeps what was saved with it |
| Category buttons on the trip map | Places of that category around the map centre | The public Overpass mirrors of OpenStreetMap |
| The [Road trip](Road-Trip#search-along-the-route) addon's search along the drive | Fuel, charging, rest areas, campsites and the other kinds it looks for | The public Overpass mirrors |
+| Tours: the trail grades, surfaces and kinds of way along a planned tour | The OpenStreetMap tags of the ways the tour runs on, from its ways layer | The public Overpass mirrors |
+| Tours: the signposted horse routes around the map view | The horse route relations in the view with their ways, from its routes layer | The public Overpass mirrors |
| Booking imports, and stops given only by name in an imported Google Maps route | The coordinate of a venue, found by its name | OpenStreetMap's search service, which also resolves street addresses |
| Preparing a trip for offline use | Up to 3000 places around the trip, in one request | Nothing is cached, and offline search has nothing to answer from |
| MCP: `search_place` and `search_pois` | The same as the full search and the category buttons | The same fallbacks |
@@ -93,11 +95,12 @@ services:
`false`, `0`, `off` and `no` in any casing switch the index off, as on every other boolean switch. A value that is not boolean-like at all aborts startup, and unset or blank leaves the index on.
-With the index off, TREK stops asking it for suggestions, searches, category buttons, the Road trip search, import geocoding and offline downloads, and place search works the way it did before 4.3.0:
+With the index off, TREK stops asking it for suggestions, searches, category buttons, the Road trip search, import geocoding, offline downloads and the ways and horse routes of Tours, and place search works the way it did before 4.3.0:
- **Full search** goes to OpenStreetMap on an install without a key. With a Google key, Google answers every search, and with Amap selected, Amap does; OpenStreetMap is then no longer asked beside them.
- **Suggestions** come from Google or Amap when one holds the keyed slot, otherwise from OpenStreetMap's public search service. That service's usage policy does not allow autocomplete, so on a keyless install consider pointing `NOMINATIM_URL` at a Nominatim of your own.
- **Category buttons** and the **Road trip search** are answered by the Overpass mirrors.
+- **Tours** read the grades of the ways under a tour and the horse routes around the map from the Overpass mirrors.
- **Imports** geocode through OpenStreetMap's search service.
- **Offline search** has nothing to answer from, because no places are downloaded.
@@ -118,7 +121,7 @@ The address is read from your own configuration and is not a URL a user can type
| `TREK_PLACES_ENABLED` | Whether the index is asked at all |
| `TREK_PLACES_URL` | Which copy of the index is asked |
| `NOMINATIM_URL` | The OpenStreetMap half of the full search, right-click reverse geocoding, OpenStreetMap place details and import geocoding |
-| `OVERPASS_URL`, `OVERPASS_TIMEOUT_MS` | The Overpass mirrors behind the category buttons and the Road trip search when the index has no answer |
+| `OVERPASS_URL`, `OVERPASS_TIMEOUT_MS` | The Overpass mirrors behind the category buttons, the Road trip search and the ways and horse routes of Tours when the index has no answer |
Defaults and details for each are on [Environment Variables](Environment-Variables).