feat(tours): plan rides on horseback from signposted horse routes

A tour can now be a ride (HOR-01). The planner offers "Horse ride" as a
tour type with its own horseshoe, and a Horse routes card beside the
waypoints looks, when asked, for the route=horse relations OpenStreetMap
knows in the map view. A route opens in a dialog that shows it on a map in
the sections it is made of, split at forks, gaps and crossings, so nothing
is ever joined across a gap. The rider picks a section and its direction,
sees what the horse=* tags along it say (open, limited, closed, or unknown
where untagged) and whether it is signposted the other way, and takes it as
one undoable step. A section that does not start where the ride ends is
only joined by a straight manual stretch once the rider switched that on.

Nothing of a ride is routed: every leg follows a section or is drawn by
hand, and the waypoint list and the map say which (a section as a solid
line with its route, a manual stretch dashed and marked unchecked). A point
at a section stays where the route has it, a ride works out no riding time,
and distance, heights, day assignment, GPX import and export, the 3D view
and the reversed ride keep working with each leg's origin saved and opened
again. A failed lookup leaves the ride and the routes already found as they
were.

The server reads the routes through the shared Overpass client
(GET /api/trips/:tripId/tours/horse-routes, Tours addon, trip access),
keeps an answer twelve hours per grid-aligned view, and the tour contract
refuses a routed leg, a via ferrata or a riding time on a ride and a horse
route section on any other type. A migration enables the horse tour type.
This commit is contained in:
Maurice
2026-10-20 12:48:41 +02:00
parent dfe11e9c4c
commit 0331d9950f
103 changed files with 5470 additions and 82 deletions
+2 -2
View File
@@ -146,8 +146,8 @@ export const FERRATA_TILE_PAYLOAD: JsonColumn<FerrataTilePayload | null> = {
};
/**
* A tour leg taken as a fixed line (a via ferrata's own line from OSM) rather
* than routed. A row that does not decode reads as a routed leg, which the
* A tour leg taken as a fixed line (a via ferrata's own line from OSM, a
* section of a horse route, a stretch drawn by hand) rather than routed. A row that does not decode reads as a routed leg, which the
* editor then plans again.
*/
export const TOUR_WAYPOINT_FIXED_LEG: JsonColumn<TourFixedLeg | null> = {
@@ -0,0 +1,21 @@
import { Migration } from '@mikro-orm/migrations';
/**
* HOR-01: a tour can be a ride on horseback. `horse` is a key of its own in
* `tour_types`, enabled, with no routing profile: a ride is never routed, it
* is made of sections of signposted horse routes and stretches the rider
* draws by hand. Those live in `tour_waypoints.fixed_leg` like every other
* fixed leg, so no column is added and no existing tour changes its meaning.
* An instance that already defined the key keeps its own row.
*/
export class Migration20200101045600_a_tour_can_be_ridden_on_horseback extends Migration {
override name = 'Migration20200101045600_a_tour_can_be_ridden_on_horseback';
override up(): void {
this.addSql(`
INSERT INTO tour_types (key, label_key, icon, color, routing_profile, is_sport, enabled, sort_order)
VALUES ('horse', 'tourTypes.horse', 'Horseshoe', '#a16207', NULL, 1, 1, 7)
ON CONFLICT (key) DO NOTHING
`);
}
}
@@ -0,0 +1,151 @@
import {
HORSE_ROUTE_SECTION_MAX_POINTS,
haversineMetres,
type HorseAccess,
type HorseAccessShare,
type HorseSignposted,
} from '@trek/shared';
/**
* HOR-01: a horse route's ways cut into the sections a rider can take whole.
*
* The member ways are read as a graph of their nodes: a section runs from a
* node where the route ends, forks or meets itself to the next such node, so
* a gap in the route ends a section and a fork starts new ones. Nothing is
* joined across a gap, nothing is guessed about which branch is the "main"
* one, and a section keeps the line of its ways point for point. Pure, so the
* service and its tests share it.
*/
/** One step of a member way between two of its nodes. */
export interface RouteEdge {
from: number;
to: number;
/** The `horse=*` value of the way the step is on. */
access: HorseAccess;
/** The way the route is signposted along the step: 1 from `from` to `to`, -1 the other way, 0 both or unsaid. */
signed: 1 | -1 | 0;
/** The place of its way among the route's members, which orders the sections. */
order: number;
}
/** A section as the route answer carries it, before it is numbered. */
interface SectionLine {
geometry: [number, number][];
lengthM: number;
access: HorseAccessShare[];
signposted: HorseSignposted | null;
order: number;
}
interface Step {
edge: RouteEdge;
/** Walked from `from` to `to`. */
forward: boolean;
}
interface Chain {
nodes: number[];
steps: Step[];
}
/** The edges at every node, by index. */
function incidence(edges: readonly RouteEdge[]): Map<number, number[]> {
const at = new Map<number, number[]>();
const add = (node: number, index: number) => {
const list = at.get(node);
if (list) list.push(index);
else at.set(node, [index]);
};
edges.forEach((edge, index) => {
add(edge.from, index);
add(edge.to, index);
});
return at;
}
/**
* Every edge in exactly one chain. A chain starts at a node that is no plain
* through point (an end, a fork, a crossing) and goes on through nodes with
* two edges until it reaches the next such node; what is left after that are
* closed rings without any, each walked once round from where it is entered.
*/
function chainsOf(edges: readonly RouteEdge[]): Chain[] {
const at = incidence(edges);
const used = new Set<number>();
const chains: Chain[] = [];
const through = (node: number) => at.get(node)?.length === 2;
const walk = (start: number, first: number) => {
const chain: Chain = { nodes: [start], steps: [] };
let node = start;
let index: number | undefined = first;
while (index !== undefined) {
used.add(index);
const edge = edges[index] as RouteEdge;
const forward = edge.from === node;
node = forward ? edge.to : edge.from;
chain.steps.push({ edge, forward });
chain.nodes.push(node);
index = through(node) && node !== start ? at.get(node)?.find((next) => !used.has(next)) : undefined;
}
chains.push(chain);
};
for (const [node, list] of at) {
if (through(node)) continue;
for (const index of list) if (!used.has(index)) walk(node, index);
}
edges.forEach((edge, index) => {
if (!used.has(index)) walk(edge.from, index);
});
return chains;
}
/** The direction a run of steps is signposted in: one way along all of it, or null. */
function signpostedOf(steps: readonly Step[]): HorseSignposted | null {
const signs = new Set(steps.map(({ edge, forward }) => edge.signed * (forward ? 1 : -1)));
if (signs.size !== 1 || signs.has(0)) return null;
return signs.has(1) ? 'with' : 'against';
}
/** A run of steps as a section: its line, its length, the access along it and its direction. */
function toSection(nodes: readonly number[], steps: readonly Step[], coords: ReadonlyMap<number, [number, number]>) {
const geometry = nodes.map((node) => coords.get(node) as [number, number]);
const byValue = new Map<HorseAccess, number>();
let lengthM = 0;
steps.forEach(({ edge }, index) => {
const [aLat, aLng] = geometry[index] as [number, number];
const [bLat, bLng] = geometry[index + 1] as [number, number];
const metres = haversineMetres(aLat, aLng, bLat, bLng);
lengthM += metres;
byValue.set(edge.access, (byValue.get(edge.access) ?? 0) + metres);
});
const access = [...byValue].map(([value, metres]) => ({ value, length_m: Math.round(metres) }));
return {
geometry,
lengthM: Math.round(lengthM),
access: access.sort((a, b) => b.length_m - a.length_m),
signposted: signpostedOf(steps),
order: Math.min(...steps.map(({ edge }) => edge.order)),
};
}
/**
* The sections of a route out of its edges, in the order its ways are listed,
* each at most HORSE_ROUTE_SECTION_MAX_POINTS points long: a longer chain is
* cut into pieces that meet end to end. A section of no length is left out.
* Every node an edge names must have its place in `coords`.
*/
export function routeSections(
edges: readonly RouteEdge[],
coords: ReadonlyMap<number, [number, number]>,
): SectionLine[] {
const perPiece = HORSE_ROUTE_SECTION_MAX_POINTS - 1;
const sections: SectionLine[] = [];
for (const { nodes, steps } of chainsOf(edges)) {
for (let start = 0; start < steps.length; start += perPiece) {
const piece = steps.slice(start, start + perPiece);
sections.push(toSection(nodes.slice(start, start + piece.length + 1), piece, coords));
}
}
return sections.filter((section) => section.lengthM > 0).sort((a, b) => a.order - b.order);
}
@@ -30,11 +30,14 @@ const SKI_ACTIVITY: Record<SkiDiscipline, string> = {
touring: 'backcountry_skiing',
};
/** The activity a ride names in GPX (HOR-01), in the words Garmin reads. */
const HORSE_ACTIVITY = 'horseback_riding';
/**
* The activity a tour's track names in GPX: a paddle tour its boat, a bike
* tour and a run their profile, a ski track its discipline (SKI-02), a hike on
* snowshoes snowshoeing (HIK-01) and any other hike hiking; whatever is
* missing falls back to the plainest.
* tour and a run their profile, a ski track its discipline (SKI-02), a ride
* horseback riding (HOR-01), a hike on snowshoes snowshoeing (HIK-01) and any
* other hike hiking; whatever is missing falls back to the plainest.
*/
export function gpxActivityOf(tour: {
tour_type: string;
@@ -49,6 +52,7 @@ export function gpxActivityOf(tour: {
if (type === 'bike') return BIKE_ACTIVITY[(bike ?? 'touring') as BikeProfile] ?? BIKE_ACTIVITY.touring;
if (type === 'run') return RUN_ACTIVITY[(tour.run_profile ?? 'running') as RunProfile] ?? RUN_ACTIVITY.running;
if (type === 'ski') return SKI_ACTIVITY[tour.ski_discipline as SkiDiscipline] ?? 'skiing';
if (type === 'horse') return HORSE_ACTIVITY;
if (type !== 'hike') return type;
// A winter hike is walked as any hike is; only snowshoes make it an activity of its own.
return tour.winter_activity === 'snowshoe' ? 'snowshoeing' : 'hiking';
@@ -0,0 +1,50 @@
import { ADDON_IDS } from '../../addons';
import { AddonGuard } from '../addons/addon.guard';
import { RequireAddon } from '../addons/require-addon.decorator';
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
import { badRequest } from '../common/domain-error';
import { ResponseContract } from '../common/response-contract';
import { TripAccessGuard } from '../permissions/trip-access.guard';
import { TourHorseRoutesService } from './tour-horse-routes.service';
import { Controller, Get, Query, UseGuards } from '@nestjs/common';
import {
FERRATA_BBOX_INVALID_MESSAGE,
FERRATA_BBOX_TOO_LARGE_MESSAGE,
horseRoutesQuerySchema,
horseRoutesResponseSchema,
type HorseRoutesQuery,
type HorseRoutesResponse,
} from '@trek/shared';
/**
* The query through the shared contract, answered with one of two messages:
* a box that is too large is a different fix for the client (zoom in) than
* one that is malformed.
*/
export function parseHorseRoutesQuery(raw: Record<string, unknown>): HorseRoutesQuery {
const parsed = horseRoutesQuerySchema.safeParse(raw);
if (parsed.success) return parsed.data;
const tooLarge = parsed.error.issues.some((issue) => issue.message === FERRATA_BBOX_TOO_LARGE_MESSAGE);
throw badRequest(tooLarge ? FERRATA_BBOX_TOO_LARGE_MESSAGE : FERRATA_BBOX_INVALID_MESSAGE);
}
/**
* HOR-01 GET /api/trips/:tripId/tours/horse-routes?bbox=south,west,north,east:
* the signposted horse routes OpenStreetMap knows inside a map view, cut into
* the sections a horse tour can take. A read, so anyone who sees the trip may
* ask; the box is the caller's view and nothing about the trip goes out.
* Declared before the tours' `:placeId` routes, which would read the path as
* a tour.
*/
@Controller('api/trips/:tripId/tours')
@UseGuards(AddonGuard, JwtAuthGuard, TripAccessGuard)
@RequireAddon(ADDON_IDS.TOURS, 'Tours')
export class TourHorseRoutesController {
constructor(private readonly horseRoutes: TourHorseRoutesService) {}
@Get('horse-routes')
@ResponseContract(horseRoutesResponseSchema)
async list(@Query() raw: Record<string, unknown>): Promise<HorseRoutesResponse> {
return await this.horseRoutes.list(parseHorseRoutesQuery(raw).bbox);
}
}
@@ -0,0 +1,201 @@
import { routeSections, type RouteEdge } from './horse-route-sections';
import {
HORSE_ROUTE_SECTIONS_CAP,
HORSE_ROUTES_RESULT_CAP,
type FerrataBbox,
type HorseAccess,
type HorseRoute,
} from '@trek/shared';
import { z } from 'zod';
/**
* HOR-01, the pure half of the horse route lookup: the Overpass query, the
* box it asks for, and the routes read out of the elements it answers with.
* Kept free of I/O so the service and its tests share it.
*/
/** How long Overpass itself may work on one query, in seconds (`[timeout:N]`). */
const HORSE_ROUTES_QUERY_TIMEOUT_S = 25;
/** The most member ways one query asks for; one more is asked, which is how a cut answer is told. */
export const HORSE_ROUTE_WAYS_CAP = 4000;
/** The grid a box is grown outwards to, so nearby views share one answer. */
const GRID_DEG = 0.05;
const NAME_MAX = 255;
const REF_MAX = 64;
const snapDown = (v: number) => Math.floor(v / GRID_DEG + 1e-9) * GRID_DEG;
const snapUp = (v: number) => Math.ceil(v / GRID_DEG - 1e-9) * GRID_DEG;
const fixed = (v: number) => Number(v.toFixed(2));
/** The box grown outwards to the 0.05 degree grid and clamped to the globe. */
export function snapHorseRouteBbox(bbox: FerrataBbox): FerrataBbox {
return {
south: fixed(Math.max(-90, snapDown(bbox.south))),
west: fixed(Math.max(-180, snapDown(bbox.west))),
north: fixed(Math.min(90, snapUp(bbox.north))),
east: fixed(Math.min(180, snapUp(bbox.east))),
};
}
/** The key a box is remembered under: its snapped edges. */
export function horseRouteBboxKey(bbox: FerrataBbox): string {
return [bbox.south, bbox.west, bbox.north, bbox.east].join(',');
}
/**
* The `route=horse` relations that reach into the box, with their members,
* and those of their ways that lie in it, with their tags, nodes and line. A
* way crossing the edge comes whole; a member way outside the box is left out
* and the route is said to go on.
*/
export function buildHorseRoutesQuery(bbox: FerrataBbox): string {
const box = `(${bbox.south},${bbox.west},${bbox.north},${bbox.east})`;
return [
`[out:json][timeout:${HORSE_ROUTES_QUERY_TIMEOUT_S}];`,
`rel["route"="horse"]${box}->.routes;`,
`way(r.routes)${box}->.ways;`,
`.routes out body qt ${HORSE_ROUTES_RESULT_CAP + 1};`,
`.ways out body geom qt ${HORSE_ROUTE_WAYS_CAP + 1};`,
].join('\n');
}
const osmId = z.number().int().positive();
const tags = z.record(z.string(), z.string()).optional();
const point = z.object({ lat: z.number().min(-90).max(90), lon: z.number().min(-180).max(180) });
const wayElementSchema = z.object({
type: z.literal('way'),
id: osmId,
tags,
nodes: z.array(osmId).max(20000),
// A point Overpass could not place comes back as null; its steps are left out.
geometry: z.array(point.nullable()).max(20000),
});
const relationElementSchema = z.object({
type: z.literal('relation'),
id: osmId,
tags,
members: z.array(z.object({ type: z.string(), ref: z.number().int(), role: z.string().optional() })).max(20000),
});
const elementSchema = z.discriminatedUnion('type', [wayElementSchema, relationElementSchema]);
type WayElement = z.infer<typeof wayElementSchema>;
type RelationElement = z.infer<typeof relationElementSchema>;
const KNOWN_ACCESS = new Set<HorseAccess>([
'designated',
'yes',
'permissive',
'destination',
'discouraged',
'private',
'no',
]);
/** `horse=*` as tagged: a common value as it is, any other `other`, none `unknown`. */
export function horseAccessOf(tag: string | undefined): HorseAccess {
const value = tag?.trim().toLowerCase() ?? '';
if (value === '') return 'unknown';
return KNOWN_ACCESS.has(value as HorseAccess) ? (value as HorseAccess) : 'other';
}
/** A member's role as the direction the route is signposted along its way: 1 with it, -1 against, 0 both. */
function signOfRole(role: string | undefined): 1 | -1 | 0 {
if (role === 'forward') return 1;
if (role === 'backward') return -1;
return 0;
}
function cleanText(value: string | undefined, max: number): string | null {
const text = value?.trim() ?? '';
return text === '' ? null : text.slice(0, max);
}
/** The steps of one member way, each between two placed nodes, and the places of its nodes. */
function wayEdges(way: WayElement, role: string | undefined, order: number, coords: Map<number, [number, number]>) {
const access = horseAccessOf(way.tags?.horse);
const signed = signOfRole(role);
const edges: RouteEdge[] = [];
way.nodes.forEach((node, index) => {
const place = way.geometry[index];
if (place) coords.set(node, [place.lat, place.lon]);
const next = way.nodes[index + 1];
const nextPlace = way.geometry[index + 1];
if (next === undefined || !place || !nextPlace || next === node) return;
edges.push({ from: node, to: next, access, signed, order });
});
return edges;
}
/**
* One relation as a route: its sections out of the member ways the answer
* holds, each way once (the first time the route lists it), and whether it
* has member ways the answer does not hold. Null when none of its ways is in
* the box, so there is nothing of it to take; `cut` when it had more sections
* than one answer carries.
*/
function toRoute(
relation: RelationElement,
ways: ReadonlyMap<number, WayElement>,
): { route: HorseRoute; cut: boolean } | null {
const coords = new Map<number, [number, number]>();
const edges: RouteEdge[] = [];
const seen = new Set<number>();
let continues = false;
relation.members.forEach((member, order) => {
if (member.type !== 'way' || seen.has(member.ref)) return;
seen.add(member.ref);
const way = ways.get(member.ref);
if (!way) {
continues = true;
return;
}
edges.push(...wayEdges(way, member.role, order, coords));
});
const sections = routeSections(edges, coords);
if (sections.length === 0) return null;
const route: HorseRoute = {
id: `relation/${relation.id}`,
name: cleanText(relation.tags?.name, NAME_MAX),
ref: cleanText(relation.tags?.ref, REF_MAX),
osmUrl: `https://www.openstreetmap.org/relation/${relation.id}`,
continues,
sections: sections.slice(0, HORSE_ROUTE_SECTIONS_CAP).map((section, index) => ({
number: index + 1,
geometry: section.geometry,
length_m: section.lengthM,
access: section.access,
signposted: section.signposted,
})),
};
return { route, cut: sections.length > HORSE_ROUTE_SECTIONS_CAP };
}
/**
* The routes out of the raw elements. An element of another shape is left
* out rather than failing the whole answer. `truncated` says the answer was
* cut: more relations or ways than were asked for, or a route with more
* sections than one answer carries.
*/
export function toHorseRoutes(elements: unknown[]): { routes: HorseRoute[]; truncated: boolean } {
const ways = new Map<number, WayElement>();
const relations: RelationElement[] = [];
for (const raw of elements) {
const parsed = elementSchema.safeParse(raw);
if (!parsed.success) continue;
if (parsed.data.type === 'way') ways.set(parsed.data.id, parsed.data);
else relations.push(parsed.data);
}
const cut = relations.length > HORSE_ROUTES_RESULT_CAP || ways.size > HORSE_ROUTE_WAYS_CAP;
const routes: HorseRoute[] = [];
let sectionsCut = false;
for (const relation of relations.slice(0, HORSE_ROUTES_RESULT_CAP)) {
const read = toRoute(relation, ways);
if (!read) continue;
sectionsCut ||= read.cut;
routes.push(read.route);
}
return { routes, truncated: cut || sectionsCut };
}
@@ -0,0 +1,86 @@
import { DomainError } from '../common/domain-error';
import { OverpassElementsClient } from '../overpass/overpass-elements.service';
import {
buildHorseRoutesQuery,
horseRouteBboxKey,
snapHorseRouteBbox,
toHorseRoutes,
} from './tour-horse-routes.helpers';
import { Injectable } from '@nestjs/common';
import {
HORSE_ROUTES_ATTRIBUTION,
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. */
export const HORSE_ROUTES_KEPT_MS = 12 * 60 * 60 * 1000;
/** The most answers kept at once; the one kept longest goes first. */
const HORSE_ROUTES_KEPT_MAX = 200;
export const HORSE_ROUTES_UNAVAILABLE_MESSAGE = 'Horse route data is unavailable right now';
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; 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.
*/
@Injectable()
export class TourHorseRoutesService {
private readonly kept = new Map<string, { at: number; answer: Answer }>();
private readonly pending = new Map<string, Promise<Answer>>();
constructor(private readonly overpass: OverpassElementsClient) {}
async list(bbox: FerrataBbox, now: number = Date.now()): Promise<HorseRoutesResponse> {
const box = snapHorseRouteBbox(bbox);
const key = horseRouteBboxKey(box);
const known = this.kept.get(key);
const answer = known && now - known.at < HORSE_ROUTES_KEPT_MS ? known.answer : await this.fetch(key, box, now);
return { ...answer, source: 'openstreetmap', attribution: HORSE_ROUTES_ATTRIBUTION };
}
/** One query for the box, shared with every request for it until it settles. */
private fetch(key: string, box: FerrataBbox, now: number): Promise<Answer> {
const running = this.pending.get(key);
if (running) return running;
const run = this.query(box).then((answer) => {
this.keep(key, answer, now);
return answer;
});
this.pending.set(key, run);
const settle = () => this.pending.delete(key);
void run.then(settle, settle);
return run;
}
private async query(box: FerrataBbox): Promise<Answer> {
let elements: unknown[];
try {
elements = await this.overpass.query(buildHorseRoutesQuery(box), 'HorseRoutes');
} catch {
// The client already logged why each mirror failed.
throw new DomainError(502, HORSE_ROUTES_UNAVAILABLE_MESSAGE, {
code: HORSE_ROUTES_UNAVAILABLE_CODE,
details: { code: HORSE_ROUTES_UNAVAILABLE_CODE },
});
}
return toHorseRoutes(elements);
}
private keep(key: string, answer: Answer, at: number): void {
this.kept.delete(key);
this.kept.set(key, { at, answer });
// A map keeps its insertion order: the first key is the one kept longest.
if (this.kept.size > HORSE_ROUTES_KEPT_MAX) this.kept.delete(this.kept.keys().next().value as string);
}
}
+2 -2
View File
@@ -85,7 +85,7 @@ export class ToursMcp {
@Tool({
name: 'list_tours',
description:
'List the saved tours of a trip (hikes, city walks, runs, bike tours, paddle tours and ski tracks planned or imported in the Tours addon): name, type (hike, walk for a city walk, run, bike, kayak for a paddle tour, or ski for a ski track), where it came from (origin: trek, gpx or wanderer), distance in km, ascent and descent in metres, the stored routing limit of a hike (max_hiking_difficulty, SAC T1 to T6) and its route choices (hiking_preferences: avoid_climbs for gentler ways, avoid_steps, avoid_ferries; weightings, never a grade of the path), the profile a bike tour is routed for (bike_profile: touring for paved cycle paths and quiet roads, road for asphalt, gravel for gravel and farm tracks, mtb for rough tracks; a routing preference, never a statement that a way is rideable or safe), the winter label of a hike (winter_activity: winter_hike or snowshoe, null for none; a label the travellers chose, while the route and its time are planned as for any hike, never a statement that a way can be walked in winter or anything about snow or avalanches), the profile and pace of a run (run_profile: running for runnable, mostly paved ways in towns and parks, trail for forest tracks and natural paths up to mountain paths (T2); a routing preference, never a statement that a way can be run; run_pace_seconds_per_km, the pace the runners planned with, null while they entered none; its duration is the distance at that pace and nothing else, no climb, descent or difficulty is in it, and it is a plan, never a recorded time), the classification of a ski track (ski_discipline: alpine, snowboard, cross_country or touring for ski touring; ski_technique for cross-country only: classic, skating or unknown when the travellers did not know; a ski track is imported from a GPX file and kept as recorded, never routed, its distance and heights come from the file, it has no ski time worked out, and nothing in it says anything about snow, avalanches or whether a run or trail is open), the boat, water and chosen speed of a paddle tour (boat_type, water_context, paddle_speed_kmh in km/h, null while the suggested speed of the boat applies), the check bench of a paddle tour (paddle_check: how far the OpenStreetMap obstacle data covers its line and how many obstacles are open, to check again or decided by the travellers; a planning status, never a safety or legal clearance), for a city walk the number of its stations (station_count: its points without the shaping points and the way back of a loop), their stays as far as entered (station_stay_minutes) and how many have none (station_stays_unknown), whether a tour still waits for its way to be planned (route_pending: saved with its points only, so its distance and walking time stay null until someone opens it in the planner and saves it), the revision (raised by every saved change of the tour), and the days of the trip each tour is on.',
'List the saved tours of a trip (hikes, city walks, runs, bike tours, paddle tours, rides on horseback and ski tracks planned or imported in the Tours addon): name, type (hike, walk for a city walk, run, bike, kayak for a paddle tour, horse for a ride, or ski for a ski track; a ride has no riding time worked out, so its duration is null), where it came from (origin: trek, gpx or wanderer), distance in km, ascent and descent in metres, the stored routing limit of a hike (max_hiking_difficulty, SAC T1 to T6) and its route choices (hiking_preferences: avoid_climbs for gentler ways, avoid_steps, avoid_ferries; weightings, never a grade of the path), the profile a bike tour is routed for (bike_profile: touring for paved cycle paths and quiet roads, road for asphalt, gravel for gravel and farm tracks, mtb for rough tracks; a routing preference, never a statement that a way is rideable or safe), the winter label of a hike (winter_activity: winter_hike or snowshoe, null for none; a label the travellers chose, while the route and its time are planned as for any hike, never a statement that a way can be walked in winter or anything about snow or avalanches), the profile and pace of a run (run_profile: running for runnable, mostly paved ways in towns and parks, trail for forest tracks and natural paths up to mountain paths (T2); a routing preference, never a statement that a way can be run; run_pace_seconds_per_km, the pace the runners planned with, null while they entered none; its duration is the distance at that pace and nothing else, no climb, descent or difficulty is in it, and it is a plan, never a recorded time), the classification of a ski track (ski_discipline: alpine, snowboard, cross_country or touring for ski touring; ski_technique for cross-country only: classic, skating or unknown when the travellers did not know; a ski track is imported from a GPX file and kept as recorded, never routed, its distance and heights come from the file, it has no ski time worked out, and nothing in it says anything about snow, avalanches or whether a run or trail is open), the boat, water and chosen speed of a paddle tour (boat_type, water_context, paddle_speed_kmh in km/h, null while the suggested speed of the boat applies), the check bench of a paddle tour (paddle_check: how far the OpenStreetMap obstacle data covers its line and how many obstacles are open, to check again or decided by the travellers; a planning status, never a safety or legal clearance), for a city walk the number of its stations (station_count: its points without the shaping points and the way back of a loop), their stays as far as entered (station_stay_minutes) and how many have none (station_stays_unknown), whether a tour still waits for its way to be planned (route_pending: saved with its points only, so its distance and walking time stay null until someone opens it in the planner and saves it), the revision (raised by every saved change of the tour), and the days of the trip each tour is on.',
inputSchema: { tripId: idSchema },
annotations: TOOL_ANNOTATIONS_READONLY,
when: addonGate(ADDON_IDS.TOURS),
@@ -100,7 +100,7 @@ export class ToursMcp {
@Tool({
name: 'get_tour_plan',
description:
'Read one saved tour of a trip: its facts, its ordered control points (start, via and end; an import without its own shows the two ends of its track), where it came from (provenance) and the days it is on. A control point with linked_place_id stands for that place of the trip (linked_place_name names it); it keeps its own coordinates. A control point whose fixed_leg is set leads to the next one along a line the router did not plan: kind ferrata follows a via ferrata, kind free is drawn by hand and was checked by nothing. A paddle tour also carries its obstacle checklist (obstacle_check): the obstacles of the OpenStreetMap data along its line, the decisions the travellers made about them and their own portages and locks; a planning aid, never a safety or legal clearance. A city walk (tour_type walk) has stations for control points, shaping points and the way back of a loop aside, each with every field spelled out: key (its own id, the same across saves; the visits of a day are kept by it), name, stay_minutes (the stay in minutes; 0 for a point only passed through, null when not known), importance (optional or must; null for a normal station), protected (true for a station any change you propose has to keep where it is: neither removed, replaced nor moved; the travellers can still edit it themselves in the app) and opening_hours (as OpenStreetMap writes them; a hint to check, never a promise; null when none is known). How far a walk got on a day is get_city_walk_progress. The full track geometry is not included.',
'Read one saved tour of a trip: its facts, its ordered control points (start, via and end; an import without its own shows the two ends of its track), where it came from (provenance) and the days it is on. A control point with linked_place_id stands for that place of the trip (linked_place_name names it); it keeps its own coordinates. A control point whose fixed_leg is set leads to the next one along a line the router did not plan: kind ferrata follows a via ferrata, kind free is drawn by hand and was checked by nothing, kind horse_route (a ride only) follows a section of a signposted horse route from OpenStreetMap in the direction the rider chose (signposted: with or against the direction the route is signposted in, null where it is not signposted one way; access: the metres of each horse=* value its ways carried when it was taken, unknown where untagged). Being on a horse route is no permission to ride it. A paddle tour also carries its obstacle checklist (obstacle_check): the obstacles of the OpenStreetMap data along its line, the decisions the travellers made about them and their own portages and locks; a planning aid, never a safety or legal clearance. A city walk (tour_type walk) has stations for control points, shaping points and the way back of a loop aside, each with every field spelled out: key (its own id, the same across saves; the visits of a day are kept by it), name, stay_minutes (the stay in minutes; 0 for a point only passed through, null when not known), importance (optional or must; null for a normal station), protected (true for a station any change you propose has to keep where it is: neither removed, replaced nor moved; the travellers can still edit it themselves in the app) and opening_hours (as OpenStreetMap writes them; a hint to check, never a promise; null when none is known). How far a walk got on a day is get_city_walk_progress. The full track geometry is not included.',
inputSchema: { tripId: idSchema, placeId: idSchema.describe('The place id of the tour, as list_tours gives it') },
annotations: TOOL_ANNOTATIONS_READONLY,
when: addonGate(ADDON_IDS.TOURS),
+6 -1
View File
@@ -19,6 +19,8 @@ import { WandererModule } from '../wanderer/wanderer.module';
import { CityWalkBriefingService } from './city-walk-briefing.service';
import { CityWalkMcp } from './city-walk.mcp';
import { TourGpxExportService } from './tour-gpx-export.service';
import { TourHorseRoutesController } from './tour-horse-routes.controller';
import { TourHorseRoutesService } from './tour-horse-routes.service';
import { TourLibraryController, TourTakeOverController } from './tour-library.controller';
import { TourLibraryMcp } from './tour-library.mcp';
import { TourLibraryService } from './tour-library.service';
@@ -68,7 +70,8 @@ import { Module } from '@nestjs/common';
McpSharedModule,
// PLN-02 searches places along a tour through the map search.
MapsModule,
// BIK-05 reads the trail grades along a mountain bike tour from OpenStreetMap.
// BIK-05 reads the trail grades along a mountain bike tour from OpenStreetMap,
// HOR-01 the signposted horse routes around a ride.
OverpassModule,
AddonsModule,
// The wanderer import reads trails through the caller's own connection.
@@ -88,6 +91,7 @@ import { Module } from '@nestjs/common';
]),
],
controllers: [
TourHorseRoutesController,
TourTakeOverController,
TourPoiSearchController,
TourSkiController,
@@ -106,6 +110,7 @@ import { Module } from '@nestjs/common';
TourPaddleCheckService,
TourObstacleReviewsService,
TourGpxExportService,
TourHorseRoutesService,
ToursWandererService,
TourLibraryService,
TourPoiSearchService,
+351
View File
@@ -0,0 +1,351 @@
/**
* Tours e2e for rides on horseback (HOR-01): a horse tour saved, read, copied
* and exported with the origin of each of its legs, and the horse routes
* around a map view, through the real JwtAuthGuard, AddonGuard and
* TripAccessGuard against a migrated and seeded temp SQLite db. Overpass is a
* container stub, the permission check a container spy and the broadcast goes
* to a FakeRealtimeService, as in tours-bike.e2e.test.ts.
*
* Fixtures: user 1 owns trip 5, user 2 is a member of it whom the permission
* spy denies 'place_edit', user 3 has no access.
*/
import { DayAssignments } from '../../src/db/entities/DayAssignments.entity';
import { Places } from '../../src/db/entities/Places.entity';
import { Tours } from '../../src/db/entities/Tours.entity';
import { Trips } from '../../src/db/entities/Trips.entity';
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 { OverpassElementsClient } from '../../src/nest/overpass/overpass-elements.service';
import { PermissionsService } from '../../src/nest/permissions/permissions.service';
import { RealtimeModule } from '../../src/nest/realtime/realtime.module';
import { RealtimeService } from '../../src/nest/realtime/realtime.service';
import { HORSE_ROUTES_UNAVAILABLE_MESSAGE } from '../../src/nest/tours/tour-horse-routes.service';
import { ToursModule } from '../../src/nest/tours/tours.module';
import { createSnapshotTestDb } from '../helpers/db-mock';
import { countRows, deleteRows, findRow, insertRows } from '../helpers/factories/rows';
import { setAddonEnabled } from '../helpers/factories/settings';
import { addTripMember } from '../helpers/factories/trips';
import { makeUser } from '../helpers/factories/users';
import { FakeRealtimeService } from '../helpers/fake-realtime';
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
import { TestUnitOfWorkModule } from '../helpers/test-uow';
import { sessionCookie } from './harness';
import { Test } from '@nestjs/testing';
import { FERRATA_BBOX_TOO_LARGE_MESSAGE, HORSE_ROUTES_ATTRIBUTION } from '@trek/shared';
import cookieParser from 'cookie-parser';
import type { Server } from 'http';
import request from 'supertest';
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi, type MockInstance } from 'vitest';
vi.mock('../../src/nest/audit/audit-log.logger', () => ({
LOG_LEVEL: 'error',
logInfo: vi.fn(),
logDebug: vi.fn(),
logError: vi.fn(),
logWarn: vi.fn(),
}));
const { journeyHooks } = vi.hoisted(() => ({
journeyHooks: {
reconcileTripSkeletons: vi.fn().mockResolvedValue(undefined),
onPlaceCreated: vi.fn().mockResolvedValue(undefined),
onPlaceUpdated: vi.fn().mockResolvedValue(undefined),
onPlaceDeleted: vi.fn().mockResolvedValue(undefined),
},
}));
const db = createSnapshotTestDb();
// The horse routes come from OpenStreetMap through Overpass: no network in a test.
const overpassQuery = vi.fn();
const realtime = new FakeRealtimeService();
let orm: TestOrm;
let checkPermission: MockInstance;
const OWNER = 1;
const VIEWER = 2;
const OUTSIDER = 3;
const GEOMETRY = [
[47, 11, 600],
[47.005, 11.005, 640],
[47.01, 11.01, 700],
[47.02, 11.02, 650],
];
const SECTION = {
kind: 'horse_route',
ref: 'relation/42',
name: 'Reitweg Isartal',
geometry: [
[47, 11],
[47.005, 11.005],
[47.01, 11.01],
],
signposted: 'with',
access: [
{ value: 'designated', length_m: 900 },
{ value: 'unknown', length_m: 450 },
],
};
const DRAWN = {
kind: 'free',
geometry: [
[47.01, 11.01],
[47.02, 11.02],
],
};
const rideBody = (overrides: Record<string, unknown> = {}) => ({
name: 'Ausritt am Fluss',
tour_type: 'horse',
route_geometry: GEOMETRY,
waypoints: [
{ lat: 47, lng: 11, role: 'start', sequence: 0, fixed_leg: SECTION },
{ lat: 47.01, lng: 11.01, role: 'via', sequence: 1, fixed_leg: DRAWN },
{ lat: 47.02, lng: 11.02, role: 'end', sequence: 2 },
],
...overrides,
});
const GPX = `<?xml version="1.0"?>
<gpx version="1.1" creator="e2e"><trk><name>Recorded ride</name><trkseg>
<trkpt lat="47" lon="11"><ele>600</ele></trkpt>
<trkpt lat="47.01" lon="11.01"><ele>640</ele></trkpt>
</trkseg></trk></gpx>`;
const overpassAnswer = [
{
type: 'relation',
id: 42,
tags: { route: 'horse', name: 'Reitweg Isartal', ref: 'R1' },
members: [
{ type: 'way', ref: 1, role: '' },
{ type: 'way', ref: 2, role: '' },
],
},
{
type: 'way',
id: 1,
tags: { horse: 'designated' },
nodes: [1, 2],
geometry: [
{ lat: 47.15, lon: 11.25 },
{ lat: 47.16, lon: 11.25 },
],
},
];
describe('Horse tours e2e (real guards + temp SQLite)', () => {
let server: Server;
let app: Awaited<ReturnType<typeof build>>;
async function build() {
const moduleRef = await Test.createTestingModule({
imports: [
await TestUnitOfWorkModule.forRoot(db),
await createTestMikroOrmModule(db),
RealtimeModule,
ToursModule,
],
})
.overrideProvider(RealtimeService)
.useValue(realtime)
.overrideProvider(JourneyDomainService)
.useValue(journeyHooks)
.overrideProvider(MapsService)
.useValue({ pois: vi.fn() })
.overrideProvider(OverpassElementsClient)
.useValue({ query: overpassQuery })
.compile();
const nest = moduleRef.createNestApplication();
nest.use(cookieParser());
nest.useGlobalPipes(new ZodValidationPipe());
nest.useGlobalFilters(new TrekExceptionFilter());
await nest.init();
return nest;
}
beforeAll(async () => {
orm = await createTestOrm(db);
// Pinned ids: the session cookies sign for exactly these users.
await makeUser(orm, { id: 1, username: 'owner', email: 'owner@example.test', role: 'user', password_version: 0 });
await makeUser(orm, { id: 2, username: 'viewer', email: 'viewer@example.test', role: 'user', password_version: 0 });
await makeUser(orm, {
id: 3,
username: 'outsider',
email: 'outsider@example.test',
role: 'user',
password_version: 0,
});
await insertRows(orm, Trips, [{ id: 5, user: 1, title: 'Isar' }]);
await addTripMember(orm, 5, 2);
app = await build();
checkPermission = vi.spyOn(app.get(PermissionsService), 'checkPermission');
server = app.getHttpServer();
});
beforeEach(async () => {
checkPermission.mockImplementation(
(action: string, _role: string, _owner: number, userId: number) =>
!(action === 'place_edit' && userId === VIEWER),
);
await setAddonEnabled(orm, 'tours', true);
realtime.broadcastMock.mockClear();
overpassQuery.mockReset();
await deleteRows(orm, DayAssignments);
await deleteRows(orm, Places);
});
afterAll(async () => {
await app.close();
await orm.close();
});
const send = (method: 'post' | 'put', path: string, body: Record<string, unknown>, userId = OWNER) =>
request(server)[method](`/api/trips/5/tours${path}`).set('Cookie', sessionCookie(userId)).send(body);
const create = async (body: Record<string, unknown> = rideBody()) => {
const res = await send('post', '', body);
expect(res.status).toBe(201);
return res.body.tour.place_id as number;
};
describe('a ride and the origin of its legs', () => {
it('saves a ride, lists it without a riding time and broadcasts the change', async () => {
const placeId = await create();
expect(await findRow(orm, Tours, { place: placeId })).toMatchObject({
tour_type: 'horse',
duration: null,
max_hiking_difficulty: null,
bike_profile: null,
});
const list = await request(server).get('/api/trips/5/tours').set('Cookie', sessionCookie(VIEWER));
expect(list.status).toBe(200);
const tour = list.body.tours.find((item: { place_id: number }) => item.place_id === placeId);
expect(tour).toMatchObject({ tour_type: 'horse', duration: null });
// The heights of its line are read like any other tour's; only a time is never worked out.
expect(tour.elevation_gain).toBeGreaterThan(0);
expect(realtime.broadcastMock).toHaveBeenCalled();
});
it('opens again with each leg as taken, a section with its direction and access', async () => {
const placeId = await create();
const res = await request(server).get(`/api/trips/5/tours/${placeId}`).set('Cookie', sessionCookie(OWNER));
expect(res.status).toBe(200);
expect(res.body.tour.tour_type).toBe('horse');
expect(res.body.waypoints.map((point: { fixed_leg?: unknown }) => point.fixed_leg ?? null)).toEqual([
SECTION,
DRAWN,
null,
]);
});
it('refuses a routed leg, a via ferrata, a riding time worked out and a section on a hike', async () => {
const ferrata = { kind: 'ferrata', ref: 'way/1', name: null, geometry: SECTION.geometry };
const routed = rideBody({
waypoints: [
{ lat: 47, lng: 11, role: 'start', sequence: 0 },
{ lat: 47.01, lng: 11.01, role: 'end', sequence: 1 },
],
});
const bodies = [
routed,
rideBody({
waypoints: [
{ lat: 47, lng: 11, role: 'start', sequence: 0, fixed_leg: ferrata },
{ lat: 47.01, lng: 11.01, role: 'end', sequence: 1 },
],
}),
rideBody({ duration_seconds: 5400 }),
rideBody({ tour_type: 'hike', max_hiking_difficulty: 2 }),
];
const statuses = await bodies.reduce<Promise<number[]>>(
async (done, body) => [...(await done), (await send('post', '', body)).status],
Promise.resolve([]),
);
expect(statuses).toEqual([400, 400, 400, 400]);
expect(await countRows(orm, Tours)).toBe(0);
});
it('a member who may only read cannot save one', async () => {
expect((await send('post', '', rideBody(), VIEWER)).status).toBe(403);
});
it('a copy keeps the type and the legs', async () => {
const placeId = await create();
const copy = await send('post', `/${placeId}/copy`, { name: 'Noch einmal' });
expect(copy.status).toBe(201);
expect(copy.body.tour).toMatchObject({ tour_type: 'horse' });
expect(copy.body.waypoints[0].fixed_leg).toEqual(SECTION);
});
it('exports a ride as horseback riding', async () => {
const placeId = await create();
const res = await request(server)
.get(`/api/trips/5/tours/${placeId}/export.gpx`)
.set('Cookie', sessionCookie(OWNER))
.buffer(true)
.parse((response, done) => {
let text = '';
response.setEncoding('utf8');
response.on('data', (chunk: string) => (text += chunk));
response.on('end', () => done(null, text));
});
expect(res.status).toBe(200);
expect(String(res.body)).toContain('<type>horseback_riding</type>');
});
it('imports a recorded ride as a ride, with nothing of another type', async () => {
const res = await request(server)
.post('/api/trips/5/tours/import/gpx')
.set('Cookie', sessionCookie(OWNER))
.field('tour_type', 'horse')
.attach('file', Buffer.from(GPX), { filename: 'ride.gpx', contentType: 'application/gpx+xml' });
expect(res.status).toBe(201);
expect(res.body.tours[0]).toMatchObject({ tour_type: 'horse', origin: 'gpx', duration: null, bike_profile: null });
});
});
describe('GET horse-routes', () => {
const ask = (bbox: string | undefined, userId?: number) => {
const req = request(server).get('/api/trips/5/tours/horse-routes');
const withQuery = bbox === undefined ? req : req.query({ bbox });
return userId ? withQuery.set('Cookie', sessionCookie(userId)) : withQuery;
};
it('answers the routes in the view, cut into sections, to anyone who sees the trip', async () => {
overpassQuery.mockResolvedValueOnce(overpassAnswer);
const res = await ask('47.12,11.21,47.18,11.29', VIEWER);
expect(res.status).toBe(200);
expect(res.body).toMatchObject({
truncated: false,
source: 'openstreetmap',
attribution: HORSE_ROUTES_ATTRIBUTION,
});
expect(res.body.routes).toEqual([
expect.objectContaining({ id: 'relation/42', name: 'Reitweg Isartal', ref: 'R1', continues: true }),
]);
expect(res.body.routes[0].sections[0]).toMatchObject({
number: 1,
signposted: null,
access: [{ value: 'designated', length_m: 1112 }],
});
});
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);
expect(failed.status).toBe(502);
expect(failed.body).toEqual({ error: HORSE_ROUTES_UNAVAILABLE_MESSAGE, code: 'horse_routes_unavailable' });
const wide = await ask('46,11,47,11.4', OWNER);
expect(wide.status).toBe(400);
expect(wide.body).toEqual({ error: FERRATA_BBOX_TOO_LARGE_MESSAGE });
expect((await ask('47.12,11.21,47.18,11.29', OUTSIDER)).status).toBe(404);
expect((await ask('47.12,11.21,47.18,11.29')).status).toBe(401);
});
it('is not there while the Tours addon is off', async () => {
await setAddonEnabled(orm, 'tours', false);
expect((await ask('47.12,11.21,47.18,11.29', OWNER)).status).toBe(404);
});
});
});
@@ -69,6 +69,7 @@ const UNNUMBERED = [
'Migration20200101045500_a_hike_can_be_marked_as_a_winter_activity',
'Migration20200101045510_a_tour_can_be_a_run',
'Migration20200101045520_a_tour_can_be_a_ski_track',
'Migration20200101045600_a_tour_can_be_ridden_on_horseback',
];
// The last step the positional runner ever had; planLegacyBaseline refuses a
// schema_version past it.
@@ -0,0 +1,72 @@
/**
* `Migration20200101045600_a_tour_can_be_ridden_on_horseback` (HOR-01):
* `tour_types` gains the enabled `horse` key with no routing profile, the
* other types stay as they were, and an instance that already defined the key
* keeps its own row.
*/
import { createMigrationOrm, migrateTo, pendingNames, rawExec, rawQuery } from '../../helpers/migration-step';
import type { MikroORM } from '@mikro-orm/sqlite';
import { describe, expect, it } from 'vitest';
const TARGET = 'Migration20200101045600_a_tour_can_be_ridden_on_horseback';
async function ormBeforeTarget(): Promise<MikroORM> {
const orm = await createMigrationOrm();
const names = await pendingNames(orm);
const index = names.indexOf(TARGET);
expect(index).toBeGreaterThan(0);
await migrateTo(orm, names[index - 1]);
return orm;
}
describe('Tour horse type migration', () => {
it('TOURHORSEMIG-001: adds the enabled horse type without a routing profile and leaves the others alone', async () => {
const orm = await ormBeforeTarget();
try {
const before = await rawQuery(orm, "SELECT key, enabled FROM tour_types WHERE key <> 'horse' ORDER BY key");
expect(await rawQuery(orm, "SELECT key FROM tour_types WHERE key = 'horse'")).toEqual([]);
await migrateTo(orm, TARGET);
expect(
await rawQuery(
orm,
"SELECT key, label_key, routing_profile, is_sport, enabled, sort_order FROM tour_types WHERE key = 'horse'",
),
).toEqual([
{
key: 'horse',
label_key: 'tourTypes.horse',
routing_profile: null,
is_sport: 1,
enabled: 1,
sort_order: 7,
},
]);
expect(await rawQuery(orm, "SELECT key, enabled FROM tour_types WHERE key <> 'horse' ORDER BY key")).toEqual(
before,
);
} finally {
await orm.close(true);
}
}, 30000);
it('TOURHORSEMIG-002: a horse type an instance already defined keeps its own values', async () => {
const orm = await ormBeforeTarget();
try {
await rawExec(
orm,
"INSERT INTO tour_types (key, label_key, icon, color, routing_profile, enabled, sort_order) VALUES ('horse', 'tourTypes.horse', 'Own', '#000000', NULL, 0, 9)",
);
await migrateTo(orm, TARGET);
expect(await rawQuery(orm, "SELECT icon, enabled, sort_order FROM tour_types WHERE key = 'horse'")).toEqual([
{ icon: 'Own', enabled: 0, sort_order: 9 },
]);
} finally {
await orm.close(true);
}
}, 30000);
});
@@ -41,7 +41,8 @@ describe('Tour types migration', () => {
orm,
'SELECT key, enabled, label_key FROM tour_types ORDER BY sort_order',
);
expect(types.map((t) => t.key)).toEqual([...tourTypeKeySchema.options]);
// The keys the contract named then; `horse` came later with a migration of its own (HOR-01).
expect(types.map((t) => t.key)).toEqual(tourTypeKeySchema.options.filter((key) => key !== 'horse'));
expect(types.filter((t) => t.enabled === 1).map((t) => t.key)).toEqual(['hike']);
for (const t of types) expect(t.label_key).toBe(`tourTypes.${t.key}`);
@@ -0,0 +1,113 @@
import { routeSections, type RouteEdge } from '../../../src/nest/tours/horse-route-sections';
import { HORSE_ROUTE_SECTION_MAX_POINTS, type HorseAccess } from '@trek/shared';
import { describe, expect, it } from 'vitest';
// HORSE-SECT-001 to HORSE-SECT-007
/** Node n lies n thousandths of a degree north of 47° N, about 111 m apart. */
const coords = (count: number) =>
new Map<number, [number, number]>(Array.from({ length: count }, (_, n) => [n + 1, [47 + n * 0.001, 11]]));
/** The steps of a way along the nodes given, in that order. */
function way(nodes: number[], order: number, extra: { access?: HorseAccess; signed?: 1 | -1 | 0 } = {}): RouteEdge[] {
return nodes.slice(1).map((to, index) => ({
from: nodes[index] as number,
to,
access: extra.access ?? 'unknown',
signed: extra.signed ?? 0,
order,
}));
}
const firstPoints = (sections: ReturnType<typeof routeSections>) =>
sections.map((section) => [section.geometry[0], section.geometry[section.geometry.length - 1]]);
describe('routeSections (HOR-01)', () => {
it('HORSE-SECT-001: ways that meet end to end are one section, with the access of each along it', () => {
const sections = routeSections(
[...way([1, 2, 3], 0, { access: 'designated' }), ...way([3, 4, 5], 1, { access: 'private' })],
coords(5),
);
expect(sections).toHaveLength(1);
expect(sections[0]?.geometry).toEqual([
[47, 11],
[47.001, 11],
[47.002, 11],
[47.003, 11],
[47.004, 11],
]);
expect(sections[0]?.lengthM).toBeCloseTo(445, -1);
expect(sections[0]?.access.map((share) => share.value).sort()).toEqual(['designated', 'private']);
expect(sections[0]?.access.reduce((sum, share) => sum + share.length_m, 0)).toBeCloseTo(445, -1);
expect(sections[0]?.signposted).toBeNull();
});
it('HORSE-SECT-002: a fork ends a section, and each branch is one of its own', () => {
const sections = routeSections([...way([1, 2, 3], 0), ...way([3, 4], 1), ...way([3, 5], 2)], coords(5));
expect(sections).toHaveLength(3);
for (const section of sections) {
const ends = [section.geometry[0], section.geometry[section.geometry.length - 1]];
expect(ends).toContainEqual([47.002, 11]);
}
});
it('HORSE-SECT-003: a gap stays a gap, never joined by a line of its own', () => {
const sections = routeSections([...way([1, 2], 0), ...way([4, 5], 1)], coords(5));
expect(firstPoints(sections)).toEqual([
[
[47, 11],
[47.001, 11],
],
[
[47.003, 11],
[47.004, 11],
],
]);
});
it('HORSE-SECT-004: a ring without a fork is walked once round', () => {
const ring = new Map<number, [number, number]>([
[1, [47, 11]],
[2, [47.001, 11]],
[3, [47.001, 11.001]],
]);
const sections = routeSections(way([1, 2, 3, 1], 0), ring);
expect(sections).toHaveLength(1);
expect(sections[0]?.geometry).toHaveLength(4);
expect(sections[0]?.geometry[0]).toEqual(sections[0]?.geometry[3]);
});
it('HORSE-SECT-005: says the signposted direction only where all of the section is signposted one way', () => {
expect(routeSections(way([1, 2, 3], 0, { signed: 1 }), coords(3))[0]?.signposted).toBe('with');
expect(routeSections(way([1, 2, 3], 0, { signed: -1 }), coords(3))[0]?.signposted).toBe('against');
const mixed = [...way([1, 2], 0, { signed: 1 }), ...way([2, 3], 1)];
expect(routeSections(mixed, coords(3))[0]?.signposted).toBeNull();
// A way listed against the walk still reads the right way round.
const turned = [...way([1, 2], 0, { signed: 1 }), ...way([3, 2], 1, { signed: -1 })];
expect(routeSections(turned, coords(3))[0]?.signposted).toBe('with');
});
it('HORSE-SECT-006: a stretch longer than a fixed leg takes is cut into pieces that meet end to end', () => {
const count = HORSE_ROUTE_SECTION_MAX_POINTS + 10;
const nodes = Array.from({ length: count }, (_, n) => n + 1);
const places = new Map<number, [number, number]>(nodes.map((n) => [n, [47 + n * 0.00001, 11]]));
const sections = routeSections(way(nodes, 0), places);
expect(sections.map((section) => section.geometry.length)).toEqual([HORSE_ROUTE_SECTION_MAX_POINTS, 11]);
expect(sections[1]?.geometry[0]).toEqual(sections[0]?.geometry[HORSE_ROUTE_SECTION_MAX_POINTS - 1]);
});
it('HORSE-SECT-007: sections follow the order the route lists its ways, and one of no length is left out', () => {
const places = new Map<number, [number, number]>([
[1, [47, 11]],
[2, [47.001, 11]],
[3, [47.1, 11]],
[4, [47.101, 11]],
[5, [47.2, 11]],
[6, [47.2, 11]],
]);
const sections = routeSections([...way([3, 4], 0), ...way([1, 2], 1), ...way([5, 6], 2)], places);
expect(sections.map((section) => section.order)).toEqual([0, 1]);
expect(sections[0]?.geometry[0]).toEqual([47.1, 11]);
});
});
@@ -2,9 +2,9 @@ import { gpxActivityOf } from '../../../src/nest/tours/tour-gpx-export.helpers';
import { describe, expect, it } from 'vitest';
// TOUR-GPX-ACTIVITY-001 to TOUR-GPX-ACTIVITY-005
// TOUR-GPX-ACTIVITY-001 to TOUR-GPX-ACTIVITY-007
describe('gpxActivityOf (PR1-06A, BIK-01, HIK-01, RUN-01, SKI-02)', () => {
describe('gpxActivityOf (PR1-06A, BIK-01, HIK-01, RUN-01, SKI-02, HOR-01)', () => {
it('TOUR-GPX-ACTIVITY-001: a bike tour names its profile, and the plainest riding without a known one', () => {
expect(gpxActivityOf({ tour_type: 'bike', bike_profile: 'mtb' })).toBe('mountain_biking');
expect(gpxActivityOf({ tour_type: 'bike', bike_profile: null })).toBe('cycling');
@@ -44,4 +44,8 @@ describe('gpxActivityOf (PR1-06A, BIK-01, HIK-01, RUN-01, SKI-02)', () => {
expect(gpxActivityOf({ tour_type: 'ski', ski_discipline: null })).toBe('skiing');
expect(gpxActivityOf({ tour_type: 'ski', ski_discipline: 'freeride' })).toBe('skiing');
});
it('TOUR-GPX-ACTIVITY-007: a horse tour is horseback riding (HOR-01)', () => {
expect(gpxActivityOf({ tour_type: 'horse' })).toBe('horseback_riding');
});
});
@@ -0,0 +1,88 @@
import { ADDON_IDS } from '../../../src/addons';
import { AddonGuard } from '../../../src/nest/addons/addon.guard';
import { REQUIRE_ADDON } from '../../../src/nest/addons/require-addon.decorator';
import { JwtAuthGuard } from '../../../src/nest/auth-core/jwt-auth.guard';
import { RESPONSE_CONTRACT_KEY } from '../../../src/nest/common/response-contract';
import { TripAccessGuard } from '../../../src/nest/permissions/trip-access.guard';
import {
parseHorseRoutesQuery,
TourHorseRoutesController,
} from '../../../src/nest/tours/tour-horse-routes.controller';
import type { TourHorseRoutesService } from '../../../src/nest/tours/tour-horse-routes.service';
import { HttpException } from '@nestjs/common';
import { GUARDS_METADATA } from '@nestjs/common/constants';
import {
FERRATA_BBOX_INVALID_MESSAGE,
FERRATA_BBOX_TOO_LARGE_MESSAGE,
HORSE_ROUTES_ATTRIBUTION,
horseRoutesResponseSchema,
type HorseRoutesResponse,
} from '@trek/shared';
import { describe, expect, it, vi } from 'vitest';
// HORSE-CTRL-001 to HORSE-CTRL-004
function thrown(fn: () => unknown): { status: number; body: unknown } {
try {
fn();
} catch (err) {
expect(err).toBeInstanceOf(HttpException);
const e = err as HttpException;
return { status: e.getStatus(), body: e.getResponse() };
}
throw new Error('expected a throw');
}
const answer: HorseRoutesResponse = {
routes: [],
truncated: false,
source: 'openstreetmap',
attribution: HORSE_ROUTES_ATTRIBUTION,
};
describe('TourHorseRoutesController (HOR-01)', () => {
it('HORSE-CTRL-001: reads the box of the map view', () => {
expect(parseHorseRoutesQuery({ bbox: '47.1,11.2,47.4,11.6' }).bbox).toEqual({
south: 47.1,
west: 11.2,
north: 47.4,
east: 11.6,
});
});
it('HORSE-CTRL-002: answers a malformed box and one too large with their own messages', () => {
for (const raw of [{}, { bbox: '1,2,3' }, { bbox: '47.4,11.2,47.1,11.6' }]) {
expect(thrown(() => parseHorseRoutesQuery(raw))).toEqual({
status: 400,
body: { error: FERRATA_BBOX_INVALID_MESSAGE },
});
}
expect(thrown(() => parseHorseRoutesQuery({ bbox: '46,11,47,11.4' }))).toEqual({
status: 400,
body: { error: FERRATA_BBOX_TOO_LARGE_MESSAGE },
});
});
it('HORSE-CTRL-003: hands the box to the service and returns its answer', async () => {
const list = vi.fn(async () => answer);
const controller = new TourHorseRoutesController({ list } as unknown as TourHorseRoutesService);
await expect(controller.list({ bbox: '47.1,11.2,47.4,11.6' })).resolves.toBe(answer);
expect(list).toHaveBeenCalledWith({ south: 47.1, west: 11.2, north: 47.4, east: 11.6 });
});
it('HORSE-CTRL-004: sits behind the Tours addon, the session and the trip access, and declares its contract', () => {
expect(Reflect.getMetadata(GUARDS_METADATA, TourHorseRoutesController)).toEqual([
AddonGuard,
JwtAuthGuard,
TripAccessGuard,
]);
expect(Reflect.getMetadata(REQUIRE_ADDON, TourHorseRoutesController)).toEqual({
addonId: ADDON_IDS.TOURS,
label: 'Tours',
});
expect(Reflect.getMetadata(RESPONSE_CONTRACT_KEY, TourHorseRoutesController.prototype.list)).toBe(
horseRoutesResponseSchema,
);
});
});
@@ -0,0 +1,135 @@
import {
buildHorseRoutesQuery,
HORSE_ROUTE_WAYS_CAP,
horseAccessOf,
horseRouteBboxKey,
snapHorseRouteBbox,
toHorseRoutes,
} from '../../../src/nest/tours/tour-horse-routes.helpers';
import { HORSE_ROUTE_SECTIONS_CAP, HORSE_ROUTES_RESULT_CAP, horseRouteSchema } from '@trek/shared';
import { describe, expect, it } from 'vitest';
// HORSE-HELP-001 to HORSE-HELP-008
const at = (lat: number, lon: number) => ({ lat, lon });
const way = (
id: number,
nodes: number[],
tags: Record<string, string> = {},
geometry: Array<{ lat: number; lon: number } | null> = nodes.map((n) => at(47 + n * 0.001, 11)),
) => ({ type: 'way', id, tags, nodes, geometry });
const relation = (
id: number,
members: Array<{ type?: string; ref: number; role?: string }>,
tags: Record<string, string> = { route: 'horse', name: 'Reitweg', ref: 'R1' },
) => ({ type: 'relation', id, tags, members: members.map((member) => ({ type: 'way', role: '', ...member })) });
describe('horse route helpers (HOR-01)', () => {
it('HORSE-HELP-001: asks for the routes in the box, their members and their ways in it with tags and nodes', () => {
expect(buildHorseRoutesQuery({ south: 47.1, west: 11.2, north: 47.4, east: 11.6 })).toBe(
[
'[out:json][timeout:25];',
'rel["route"="horse"](47.1,11.2,47.4,11.6)->.routes;',
'way(r.routes)(47.1,11.2,47.4,11.6)->.ways;',
`.routes out body qt ${HORSE_ROUTES_RESULT_CAP + 1};`,
`.ways out body geom qt ${HORSE_ROUTE_WAYS_CAP + 1};`,
].join('\n'),
);
});
it('HORSE-HELP-002: grows a box to the 0.05 degree grid, clamped to the globe, and keys it by its edges', () => {
const box = snapHorseRouteBbox({ south: 47.12, west: 11.21, north: 47.18, east: 11.29 });
expect(box).toEqual({ south: 47.1, west: 11.2, north: 47.2, east: 11.3 });
expect(horseRouteBboxKey(box)).toBe('47.1,11.2,47.2,11.3');
expect(snapHorseRouteBbox({ south: -89.99, west: -179.99, north: 89.99, east: 179.99 })).toEqual({
south: -90,
west: -180,
north: 90,
east: 180,
});
});
it('HORSE-HELP-003: reads horse=* as tagged, any other value as other and none as unknown', () => {
const tagged = ['designated', ' Yes ', 'permissive', 'destination', 'discouraged', 'private', 'no'];
expect(tagged.map((value) => horseAccessOf(value))).toEqual([
'designated',
'yes',
'permissive',
'destination',
'discouraged',
'private',
'no',
]);
expect(horseAccessOf('customers')).toBe('other');
expect(horseAccessOf('')).toBe('unknown');
expect(horseAccessOf(undefined)).toBe('unknown');
});
it('HORSE-HELP-004: a route with its sections, the access of its ways and its own name and ref', () => {
const { routes, truncated } = toHorseRoutes([
relation(7, [{ ref: 1 }, { ref: 2, role: 'forward' }]),
way(1, [1, 2, 3], { horse: 'designated' }),
way(2, [3, 4], { horse: 'no' }),
]);
expect(truncated).toBe(false);
expect(routes).toHaveLength(1);
const route = routes[0];
expect(horseRouteSchema.parse(route)).toEqual(route);
expect(route).toMatchObject({
id: 'relation/7',
name: 'Reitweg',
ref: 'R1',
osmUrl: 'https://www.openstreetmap.org/relation/7',
continues: false,
});
expect(route?.sections).toHaveLength(1);
expect(route?.sections[0]).toMatchObject({ number: 1, signposted: null });
expect(route?.sections[0]?.access.map((share) => share.value)).toEqual(['designated', 'no']);
});
it('HORSE-HELP-005: says a route goes on past the box, and leaves out one with no way in it', () => {
const { routes } = toHorseRoutes([
relation(7, [{ ref: 1 }, { ref: 99 }]),
relation(8, [{ ref: 98 }]),
way(1, [1, 2]),
]);
expect(routes.map((route) => [route.id, route.continues])).toEqual([['relation/7', true]]);
});
it('HORSE-HELP-006: reads each way once, skips other members, unplaced points and elements of another shape', () => {
const { routes } = toHorseRoutes([
relation(7, [{ ref: 1 }, { ref: 1, role: 'backward' }, { type: 'node', ref: 5 }, { ref: 2 }], {
route: 'horse',
name: ' ',
}),
way(1, [1, 2, 3], {}, [at(47, 11), null, at(47.002, 11)]),
way(2, [10, 11], { horse: 'yes' }),
{ type: 'way', id: 3 },
{ type: 'node', id: 4, lat: 47, lon: 11 },
null,
]);
expect(routes).toHaveLength(1);
expect(routes[0]).toMatchObject({ name: null, ref: null, continues: false });
// The way with an unplaced middle point has no step left; only the second way gives a section.
expect(routes[0]?.sections.map((section) => section.access[0]?.value)).toEqual(['yes']);
});
it('HORSE-HELP-007: an answer past the caps says it was cut', () => {
const many = Array.from({ length: HORSE_ROUTES_RESULT_CAP + 1 }, (_, index) => relation(index + 1, [{ ref: 1 }]));
const cut = toHorseRoutes([...many, way(1, [1, 2])]);
expect(cut.truncated).toBe(true);
expect(cut.routes).toHaveLength(HORSE_ROUTES_RESULT_CAP);
});
it('HORSE-HELP-008: a route with more sections than an answer carries is cut to the cap and said to be', () => {
const count = HORSE_ROUTE_SECTIONS_CAP + 1;
const members = Array.from({ length: count }, (_, index) => ({ ref: index + 1 }));
// Each way two nodes of its own, apart from the others: as many sections as ways.
const ways = members.map(({ ref }) => way(ref, [ref * 10, ref * 10 + 1]));
const { routes, truncated } = toHorseRoutes([relation(7, members), ...ways]);
expect(truncated).toBe(true);
expect(routes[0]?.sections).toHaveLength(HORSE_ROUTE_SECTIONS_CAP);
expect(routes[0]?.sections.map((section) => section.number).slice(0, 3)).toEqual([1, 2, 3]);
});
});
@@ -0,0 +1,100 @@
import { DomainError } from '../../../src/nest/common/domain-error';
import { OverpassElementsClient } from '../../../src/nest/overpass/overpass-elements.service';
import {
HORSE_ROUTES_KEPT_MS,
HORSE_ROUTES_UNAVAILABLE_MESSAGE,
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 { beforeEach, describe, expect, it, vi } from 'vitest';
// HORSE-SVC-001 to HORSE-SVC-005
const query = vi.fn<(q: string, caller: string) => Promise<unknown[]>>();
let service: TourHorseRoutesService;
const NOW = 1_800_000_000_000;
const box = { south: 47.12, west: 11.21, north: 47.18, east: 11.29 };
const elements = [
{ type: 'relation', id: 7, tags: { route: 'horse', name: 'Reitweg' }, members: [{ type: 'way', ref: 1, role: '' }] },
{
type: 'way',
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();
const moduleRef = await Test.createTestingModule({
providers: [TourHorseRoutesService, { provide: OverpassElementsClient, useValue: { query } }],
}).compile();
service = moduleRef.get(TourHorseRoutesService);
});
describe('TourHorseRoutesService (HOR-01)', () => {
it('HORSE-SVC-001: asks Overpass for the box grown to the grid and answers the contract', async () => {
query.mockResolvedValue(elements);
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(query).toHaveBeenCalledTimes(1);
expect(query.mock.calls[0]?.[0]).toContain('(47.1,11.2,47.2,11.3)');
expect(query.mock.calls[0]?.[1]).toBe('HorseRoutes');
});
it('HORSE-SVC-002: keeps an answer for nearby views, and asks again once it is old', async () => {
query.mockResolvedValue(elements);
await service.list(box, NOW);
await service.list({ south: 47.11, west: 11.22, north: 47.19, east: 11.28 }, NOW + 1000);
expect(query).toHaveBeenCalledTimes(1);
await service.list(box, NOW + HORSE_ROUTES_KEPT_MS);
expect(query).toHaveBeenCalledTimes(2);
});
it('HORSE-SVC-003: two requests for the same box at once share one query', async () => {
let answer: (value: unknown[]) => void = () => undefined;
query.mockReturnValue(
new Promise((resolve) => {
answer = resolve;
}),
);
const both = Promise.all([service.list(box, NOW), service.list(box, NOW)]);
answer(elements);
const [first, second] = await both;
expect(first).toEqual(second);
expect(query).toHaveBeenCalledTimes(1);
});
it('HORSE-SVC-004: no mirror answering is a 502 the client can show, and the next request asks again', async () => {
query.mockRejectedValueOnce(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);
expect((failure as DomainError).getResponse()).toEqual({
error: HORSE_ROUTES_UNAVAILABLE_MESSAGE,
code: HORSE_ROUTES_UNAVAILABLE_CODE,
});
query.mockResolvedValueOnce(elements);
expect((await service.list(box, NOW)).routes).toHaveLength(1);
});
it('HORSE-SVC-005: keeps at most two hundred answers, letting the one kept longest go', async () => {
query.mockResolvedValue([]);
const nth = (n: number) => ({ south: 40 + n * 0.1, west: 5, north: 40.05 + n * 0.1, east: 5.05 });
for (let n = 0; n <= 200; n += 1) await service.list(nth(n), NOW);
expect(query).toHaveBeenCalledTimes(201);
await service.list(nth(200), NOW);
expect(query).toHaveBeenCalledTimes(201);
await service.list(nth(0), NOW);
expect(query).toHaveBeenCalledTimes(202);
});
});