diff --git a/charts/trek/templates/configmap.yaml b/charts/trek/templates/configmap.yaml index 128b4f2c4..42a2c390c 100644 --- a/charts/trek/templates/configmap.yaml +++ b/charts/trek/templates/configmap.yaml @@ -121,6 +121,9 @@ data: {{- if .Values.env.TREK_PHOTON_URL }} TREK_PHOTON_URL: {{ .Values.env.TREK_PHOTON_URL | quote }} {{- end }} + {{- if .Values.env.TREK_VALHALLA_URL }} + TREK_VALHALLA_URL: {{ .Values.env.TREK_VALHALLA_URL | quote }} + {{- end }} {{- if .Values.env.GOOGLE_LIST_DATA_BASE }} GOOGLE_LIST_DATA_BASE: {{ .Values.env.GOOGLE_LIST_DATA_BASE | quote }} {{- end }} diff --git a/charts/trek/values.yaml b/charts/trek/values.yaml index 4f1c895de..05270b102 100644 --- a/charts/trek/values.yaml +++ b/charts/trek/values.yaml @@ -124,6 +124,9 @@ env: # The address search (Photon) of the TREK services. With a key, search and reverse lookups ask it before # Nominatim and fall back to Nominatim when it does not answer. Never asked when NOMINATIM_URL is set. # Defaults to https://photon.liketrek.com. + # TREK_VALHALLA_URL: "" + # The Valhalla of the TREK services, which this server relays routing to unless the admin picks another + # routing service. The browser never talks to it. Defaults to https://valhalla.liketrek.com. # AMAP_API_BASE: "" # Send the Amap (高德地图) calls through an egress proxy, a cache or a gateway that speaks the same API instead of # restapi.amap.com directly. The key itself is a credential and goes under secretEnv.AMAP_API_KEY, or into diff --git a/server/.env.example b/server/.env.example index 711b08ce5..1a6a0d65f 100644 --- a/server/.env.example +++ b/server/.env.example @@ -74,6 +74,7 @@ DEMO_MODE=false # Demo mode: resets data hourly # TREK_SERVICES_KEY= # A key issued to you for this installation. Wins over the stored one and turns self-registration off; meant for hosted and pre-provisioned instances. (default: none) # TREK_SERVICES_HOSTS=places.liketrek.com,photon.liketrek.com,valhalla.liketrek.com # Comma-separated hosts that receive the installation key over https. No other host ever sees it. (default: places.liketrek.com,photon.liketrek.com,valhalla.liketrek.com) # TREK_PHOTON_URL=https://photon.liketrek.com # The address search (Photon) of the TREK services. Once the installation holds a key, search and reverse lookups ask it before Nominatim and fall back to Nominatim whenever it does not answer. Never asked with TREK_SERVICES=off, without a key, or when NOMINATIM_URL is set. (default: https://photon.liketrek.com) +# TREK_VALHALLA_URL=https://valhalla.liketrek.com # The Valhalla of the TREK services. Routes and elevation are asked of it unless Admin > Default user settings picks another routing service; the browser never talks to it, this server relays its questions with the installation key. (default: https://valhalla.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. # GOOGLE_LIST_DATA_BASE= # Optional HTTP(S) base URL of a list-data service, e.g. https://maps.example.com. Paste a URL beginning with this base to fetch and parse it directly. Unset keeps the original Google list import flow. diff --git a/server/src/app-config/boot-derive.ts b/server/src/app-config/boot-derive.ts index 6d658b1e5..c29ac9cbd 100644 --- a/server/src/app-config/boot-derive.ts +++ b/server/src/app-config/boot-derive.ts @@ -67,6 +67,8 @@ const DEFAULT_SERVICE_HOSTS = ['places.liketrek.com', 'photon.liketrek.com', 'va /** The address search of the TREK services, asked before Nominatim while the installation holds a key. */ const DEFAULT_PHOTON_URL = 'https://photon.liketrek.com'; +/** The TREK services' Valhalla, asked through this server's routing relay. */ +const DEFAULT_VALHALLA_URL = 'https://valhalla.liketrek.com'; /** * How this installation identifies itself to the liketrek services. Unset is @@ -81,6 +83,7 @@ export function deriveServices(raw: RawEnv) { key: raw.TREK_SERVICES_KEY?.trim() || null, hosts: hosts?.length ? hosts : DEFAULT_SERVICE_HOSTS, photonUrl: stripTrailingSlashes(raw.TREK_PHOTON_URL?.trim() || DEFAULT_PHOTON_URL), + valhallaUrl: stripTrailingSlashes(raw.TREK_VALHALLA_URL?.trim() || DEFAULT_VALHALLA_URL), }; } diff --git a/server/src/app-config/env.schema.ts b/server/src/app-config/env.schema.ts index 937ddf675..e4bd4cb8e 100644 --- a/server/src/app-config/env.schema.ts +++ b/server/src/app-config/env.schema.ts @@ -189,6 +189,7 @@ export const envSchema = z.object({ TREK_SERVICES_KEY: optionalWith(isServiceKeyShape, 'must be a TREK services key (tk1...)'), TREK_SERVICES_HOSTS: anyString, TREK_PHOTON_URL: url, + TREK_VALHALLA_URL: url, PLACES_API_KEY: anyString, AMAP_API_BASE: url, AMAP_API_KEY: anyString, diff --git a/server/src/nest/app-config/tokens.ts b/server/src/nest/app-config/tokens.ts index e31877db5..bc3ac7f8f 100644 --- a/server/src/nest/app-config/tokens.ts +++ b/server/src/nest/app-config/tokens.ts @@ -31,7 +31,10 @@ export const storageConfig = registerAs('storage', () => BOOT_DERIVERS.storage(p export const transitConfig = registerAs('transit', () => BOOT_DERIVERS.transit(process.env)); /** KitineraryExtractorService's binary probe (KITINERARY_EXTRACTOR_PATH, then PATH). */ export const kitineraryConfig = registerAs('kitinerary', () => BOOT_DERIVERS.kitinerary(process.env)); -/** The installation identity towards the liketrek services (TREK_SERVICES, TREK_SERVICES_KEY, TREK_SERVICES_HOSTS). */ +/** + * The installation identity towards the liketrek services and their Valhalla + * (TREK_SERVICES, TREK_SERVICES_KEY, TREK_SERVICES_HOSTS, TREK_VALHALLA_URL). + */ export const servicesConfig = registerAs('services', () => BOOT_DERIVERS.services(process.env)); export const BOOT_STABLE_TOKENS = [httpConfig, storageConfig, transitConfig, kitineraryConfig, servicesConfig]; diff --git a/server/src/nest/app.module.ts b/server/src/nest/app.module.ts index 5decd6456..c695eaf79 100644 --- a/server/src/nest/app.module.ts +++ b/server/src/nest/app.module.ts @@ -84,6 +84,7 @@ import { ReservationImportModule } from './reservation-import/reservation-import import { ReservationsModule } from './reservations/reservations.module'; import { RoadtripModule } from './roadtrip/roadtrip.module'; import { RouteUsageModule } from './route-usage/route-usage.module'; +import { RoutingRelayModule } from './routing-relay/routing-relay.module'; import { SchedulingModule } from './scheduling/scheduling.module'; import { SchoolHolidaysModule } from './school-holidays/school-holidays.module'; import { ServiceIdentityModule } from './service-identity/service-identity.module'; @@ -184,6 +185,7 @@ import { APP_FILTER, APP_GUARD, APP_INTERCEPTOR, APP_PIPE } from '@nestjs/core'; FeedsModule, SettingsModule, ServiceIdentityModule, + RoutingRelayModule, StorageModule, BackupModule, AuthModule, diff --git a/server/src/nest/roadtrip/roadtrip-router.service.ts b/server/src/nest/roadtrip/roadtrip-router.service.ts index efa3609f8..4fe367661 100644 --- a/server/src/nest/roadtrip/roadtrip-router.service.ts +++ b/server/src/nest/roadtrip/roadtrip-router.service.ts @@ -3,9 +3,11 @@ import type { PluginsRepository } from '../../db/repositories/Plugins.repository import { readCappedJson, discardBody } from '../../utils/cappedFetch'; import { safeFetchAdminConfigured } from '../../utils/ssrfGuard'; import { logWarn } from '../audit/audit-log.logger'; +import { DomainError } from '../common/domain-error'; import { normalize, declaredProfiles } from '../plugins/contributions/plugin-route-normalize'; import { pluginsEnabled } from '../plugins/kill-switch'; import { PluginHooks } from '../plugins/plugin-hooks.service'; +import { RoutingRelayService, type ValhallaRelayAnswer } from '../routing-relay/routing-relay.service'; import { SettingsService } from '../settings/settings.service'; import { HEIGHT_CHUNK_SIZE, @@ -18,7 +20,12 @@ import { } from './valhalla-hike.helpers'; import { InjectRepository } from '@mikro-orm/nestjs'; import { Injectable } from '@nestjs/common'; -import type { GeometryPoint } from '@trek/shared'; +import { + resolveValhallaProvider, + type GeometryPoint, + type ValhallaProvider, + type ValhallaRelayAction, +} from '@trek/shared'; import { formatDurationShort, haversineKm, @@ -151,11 +158,44 @@ const refusalSchema = z.object({ error_code: z.number() }); const REFUSAL_MAX_BYTES = 64 * 1024; /** Valhalla's word in a router's 400 that the way cannot be had, or null where the 400 says something else. */ -async function refusalOf(response: Response): Promise<'no_way' | 'too_long' | null> { - const refusal = refusalSchema.safeParse(await readCappedJson(response, REFUSAL_MAX_BYTES)); +function refusalIn(payload: unknown): 'no_way' | 'too_long' | null { + const refusal = refusalSchema.safeParse(payload); return refusal.success ? (REFUSAL_CODES.get(refusal.data.error_code) ?? null) : null; } +async function refusalOf(response: Response): Promise<'no_way' | 'too_long' | null> { + return refusalIn(await readCappedJson(response, REFUSAL_MAX_BYTES)); +} + +/** The public Valhalla FOSSGIS runs, which TREK ships with. */ +const FOSSGIS_VALHALLA = 'https://valhalla1.openstreetmap.de'; + +/** + * What the relay says when it cannot answer for the TREK services right now: + * no key, an allowance spent, a body it does not take, a host that is down. + * The question then goes to FOSSGIS, as the planner in the browser sends it. + */ +function relayCannotAnswer(status: number): boolean { + return status === 401 || status === 403 || status === 413 || status === 429 || status >= 500; +} + +/** The relay's answer read as the queue reads a router's: the payload, a refusal, or a failure. */ +function payloadOf(answer: ValhallaRelayAnswer): unknown { + let payload: unknown; + try { + payload = JSON.parse(answer.body.toString('utf8')); + } catch { + payload = undefined; + } + if (answer.status === 400) { + const why = refusalIn(payload); + if (why) throw new RouteRefusal(why, 'Routing provider returned 400'); + } + if (answer.status < 200 || answer.status >= 300) throw new Error(`Routing provider returned ${answer.status}`); + if (payload === undefined) throw new Error('Routing response is invalid or too large'); + return payload; +} + /** How often a piece of a line whose heights could not be read is asked again, as the planner asks a route again. */ const HEIGHT_RETRIES = 1; /** How long a line's heights are kept, as long as a route is: a proposal and the hike created from it ask once. */ @@ -169,14 +209,29 @@ function heightsKey(userId: number, valhalla: string, line: ReadonlyArray): { base: string; valhalla: string } { +/** + * The routers a user's settings name: their own OSRM (blank for the public + * hosts) and the Valhalla to ask, if any, chosen as the browser chooses it + * (`valhallaBase`). `trekValhalla` is the TREK services' Valhalla while it can + * be asked. + */ +function routersOf(settings: Record, trekValhalla: string | null): { base: string; valhalla: string } { const base = typeof settings.routing_base_url === 'string' ? settings.routing_base_url.trim().replace(/\/+$/, '') : ''; const configuredValhalla = typeof settings.valhalla_base_url === 'string' ? settings.valhalla_base_url.trim().replace(/\/+$/, '') : ''; - // An own OSRM without a Valhalla means no Valhalla at all, as in the browser (`valhallaBase`). - return { base, valhalla: configuredValhalla || (base ? '' : 'https://valhalla1.openstreetmap.de') }; + const provider = resolveValhallaProvider({ + provider: settings.routing_valhalla_provider, + valhallaUrl: configuredValhalla, + routingUrl: base, + trekAvailable: trekValhalla !== null, + }); + const valhallaOf: Record = { + custom: configuredValhalla, + trek: trekValhalla ?? FOSSGIS_VALHALLA, + fossgis: FOSSGIS_VALHALLA, + }; + return { base, valhalla: provider ? valhallaOf[provider] : '' }; } /** Valhalla's maneuver type for boarding a ferry. */ @@ -249,6 +304,7 @@ export class RoadtripRouterService { private readonly settings: SettingsService, private readonly hooks: PluginHooks, @InjectRepository(Plugins) private readonly plugins: PluginsRepository, + private readonly relay: RoutingRelayService, ) {} async profiles(): Promise { @@ -297,6 +353,28 @@ export class RoadtripRouterService { } } + /** + * One question to a Valhalla. The TREK services' one is asked through the + * relay, under the user's allowance there and with the installation key; a + * relay that cannot answer hands the question to FOSSGIS through the paced + * queue. Every other Valhalla is asked through the queue directly. + */ + private async askValhalla( + userId: number, + valhalla: string, + action: ValhallaRelayAction, + body: object, + timeoutMs?: number, + ): Promise { + if (!this.relay.serves(valhalla)) return this.request(`${valhalla}/${action}`, body, timeoutMs); + const answer = await this.relay.ask(userId, action, body, timeoutMs).catch((err: unknown) => { + if (err instanceof DomainError) return null; + throw err; + }); + if (answer && !relayCannotAnswer(answer.status)) return payloadOf(answer); + return this.request(`${FOSSGIS_VALHALLA}/${action}`, body, timeoutMs); + } + async route( userId: number, tripId: number, @@ -319,6 +397,7 @@ export class RoadtripRouterService { avoid, settings.routing_base_url, settings.valhalla_base_url, + settings.routing_valhalla_provider, ...(footOnly ? ['foot-only'] : []), ...(hiking ? [{ hiking }] : []), ]); @@ -350,19 +429,21 @@ export class RoadtripRouterService { parts = route.legs; } else { const mode = profile === 'walking' || profile === 'cycling' ? profile : 'driving'; - const { base, valhalla } = routersOf(settings); + const { base, valhalla } = routersOf(settings, this.relay.trekValhalla()); let weighted = false; if (hiking) { const cycling = mode === 'cycling'; if (!valhalla) { throw new RouteRefusal('no_valhalla', `No Valhalla is set to plan a ${cycling ? 'bike tour' : 'hike'} with`); } - const legs = await this.valhallaLegs(valhalla, points, cycling ? 'bicycle' : 'pedestrian', { ...hiking }); + const legs = await this.valhallaLegs(userId, valhalla, points, cycling ? 'bicycle' : 'pedestrian', { + ...hiking, + }); ({ line, distance, duration, parts, snapped } = routeOfLegs(points, legs)); weighted = true; } else if (footOnly && valhalla) { try { - const legs = await this.valhallaLegs(valhalla, points, 'pedestrian', { use_ferry: 0 }, true); + const legs = await this.valhallaLegs(userId, valhalla, points, 'pedestrian', { use_ferry: 0 }, true); ({ line, distance, duration, parts, snapped } = routeOfLegs(points, legs)); ferryLegs = legs.flatMap((leg, index) => (crossesByBoat(leg) ? [index] : [])); weighted = true; @@ -377,7 +458,7 @@ export class RoadtripRouterService { use_highways: avoid.includes('motorway') ? 0 : 1, use_ferry: avoid.includes('ferry') ? 0 : 1, }; - const legs = await this.valhallaLegs(valhalla, points, 'auto', options); + const legs = await this.valhallaLegs(userId, valhalla, points, 'auto', options); ({ line, distance, duration, parts, snapped } = routeOfLegs(points, legs)); avoidMissed = avoid.filter((cls) => legs.some((leg) => @@ -479,6 +560,7 @@ export class RoadtripRouterService { * a ferry's edge (`offBoatLines`). */ private async valhallaLegs( + userId: number, valhalla: string, points: Point[], costing: 'auto' | 'pedestrian' | 'bicycle', @@ -487,7 +569,7 @@ export class RoadtripRouterService { ): Promise { const legs: ValhallaLegs = []; for (let start = 0; start < points.length - 1; start += 9) { - const payload = await this.request(`${valhalla}/route`, { + const payload = await this.askValhalla(userId, valhalla, 'route', { locations: points.slice(start, start + 10).map((p) => ({ lat: p.lat, lon: p.lng, @@ -506,7 +588,7 @@ export class RoadtripRouterService { /** The Valhalla a user's routes are asked of, or null where there is none to ask. */ private async valhallaFor(userId: number): Promise { - return routersOf(await this.settings.getUserSettings(userId)).valhalla || null; + return routersOf(await this.settings.getUserSettings(userId), this.relay.trekValhalla()).valhalla || null; } /** @@ -526,7 +608,9 @@ export class RoadtripRouterService { const key = heightsKey(userId, valhalla, line); const kept = this.heightsCache.get(key); const heights = - kept && Date.now() - kept.at < HEIGHTS_TTL_MS ? kept.heights : await this.readHeights(key, valhalla, line); + kept && Date.now() - kept.at < HEIGHTS_TTL_MS + ? kept.heights + : await this.readHeights(userId, key, valhalla, line); return line.map(([lat, lng], index): GeometryPoint => { const height = heights[index]; return height === null ? [lat, lng] : [lat, lng, height]; @@ -535,6 +619,7 @@ export class RoadtripRouterService { /** The heights of a line asked piece by piece, kept under `key` where every piece was answered. */ private async readHeights( + userId: number, key: string, valhalla: string, line: ReadonlyArray, @@ -545,7 +630,7 @@ export class RoadtripRouterService { // One piece after another through the queue; the first that fails twice ends the reading. const whole = await offsets.reduce>(async (going, offset) => { if (!(await going)) return false; - const read = await this.pieceHeights(valhalla, line.slice(offset, offset + HEIGHT_CHUNK_SIZE), offset); + const read = await this.pieceHeights(userId, valhalla, line.slice(offset, offset + HEIGHT_CHUNK_SIZE), offset); // The point a piece shares with the one before keeps the height it already has. read?.forEach((height, index) => { if (index > 0 || heights[offset] === null) heights[offset + index] = height; @@ -565,6 +650,7 @@ export class RoadtripRouterService { * `retries` times where its question fails, or null where it failed every time. */ private async pieceHeights( + userId: number, valhalla: string, piece: ReadonlyArray, offset: number, @@ -572,13 +658,13 @@ export class RoadtripRouterService { ): Promise | null> { let why: string; try { - const read = heightsOf(await this.request(`${valhalla}/height`, heightBody(piece)), piece.length); + const read = heightsOf(await this.askValhalla(userId, valhalla, 'height', heightBody(piece)), piece.length); if (read) return read; why = 'the answer does not name every point'; } catch (err: unknown) { why = err instanceof Error ? err.message : String(err); } - if (retries > 0) return await this.pieceHeights(valhalla, piece, offset, retries - 1); + if (retries > 0) return await this.pieceHeights(userId, valhalla, piece, offset, retries - 1); logWarn(`[Router] heights stop at point ${offset}: ${why}`); return null; } @@ -594,7 +680,8 @@ export class RoadtripRouterService { async wayIds(userId: number, line: ReadonlyArray): Promise { const valhalla = await this.valhallaFor(userId); if (!valhalla) throw new RouteRefusal('no_valhalla', 'No Valhalla is set to describe a line with'); - return tracedWaysOf(await this.request(`${valhalla}/trace_attributes`, traceBody(line), TRACE_TIMEOUT_MS)); + const answer = await this.askValhalla(userId, valhalla, 'trace_attributes', traceBody(line), TRACE_TIMEOUT_MS); + return tracedWaysOf(answer); } /** @@ -614,7 +701,7 @@ export class RoadtripRouterService { ): Promise> { const valhalla = await this.valhallaFor(userId); if (!valhalla) throw new RouteRefusal('no_valhalla', 'No Valhalla is set to plan a hike with'); - const payload = await this.request(`${valhalla}/route`, { + const payload = await this.askValhalla(userId, valhalla, 'route', { locations: [from, to].map((p) => ({ lat: p.lat, lon: p.lng, radius: 50 })), costing: 'pedestrian', costing_options: { pedestrian: { ...costingOptions } }, diff --git a/server/src/nest/roadtrip/roadtrip.module.ts b/server/src/nest/roadtrip/roadtrip.module.ts index 1cbbbff52..44b6b48fb 100644 --- a/server/src/nest/roadtrip/roadtrip.module.ts +++ b/server/src/nest/roadtrip/roadtrip.module.ts @@ -20,6 +20,7 @@ import { PermissionsModule } from '../permissions/permissions.module'; import { PlacesModule } from '../places/places.module'; import { PluginsRuntimeModule } from '../plugins/plugins-runtime.module'; import { RealtimeModule } from '../realtime/realtime.module'; +import { RoutingRelayModule } from '../routing-relay/routing-relay.module'; import { SettingsModule } from '../settings/settings.module'; import { TripMembershipModule } from '../trip-membership/trip-membership.module'; import { ChargingLookupController } from './charging-lookup.controller'; @@ -79,6 +80,7 @@ import { Module } from '@nestjs/common'; AddonsModule, RealtimeModule, + RoutingRelayModule, SettingsModule, PluginsRuntimeModule, MapsModule, diff --git a/server/src/nest/routing-relay/routing-relay.controller.ts b/server/src/nest/routing-relay/routing-relay.controller.ts new file mode 100644 index 000000000..8319fecfb --- /dev/null +++ b/server/src/nest/routing-relay/routing-relay.controller.ts @@ -0,0 +1,50 @@ +import type { User } from '../../types'; +import { CurrentUser } from '../auth-core/current-user.decorator'; +import { JwtAuthGuard } from '../auth-core/jwt-auth.guard'; +import { ValhallaHeightDto, ValhallaRouteDto, ValhallaTraceDto } from './routing-relay.dto'; +import { RoutingRelayService, type ValhallaRelayAnswer } from './routing-relay.service'; +import { Body, Controller, HttpCode, Post, Res, UseGuards } from '@nestjs/common'; + +import type { Response } from 'express'; + +/** + * /api/routing/valhalla/:action: the planner's Valhalla questions, asked of + * the TREK services through this server. Same origin, so the browser needs no + * new connect-src, and Valhalla's own answer comes back as it was sent, its + * refusals included: a 400 that says no way joins the points is the planner's + * to read. + */ +@Controller('api/routing/valhalla') +@UseGuards(JwtAuthGuard) +export class RoutingRelayController { + constructor(private readonly relay: RoutingRelayService) {} + + // response-contract-exempt: passes Valhalla's own answer through @Res(), status and body as they came. + @Post('route') + @HttpCode(200) + async route(@CurrentUser() user: User, @Body() body: ValhallaRouteDto, @Res() res: Response): Promise { + passOn(res, await this.relay.ask(user.id, 'route', body)); + } + + // response-contract-exempt: passes Valhalla's own answer through @Res(), status and body as they came. + @Post('trace_attributes') + @HttpCode(200) + async traceAttributes( + @CurrentUser() user: User, + @Body() body: ValhallaTraceDto, + @Res() res: Response, + ): Promise { + passOn(res, await this.relay.ask(user.id, 'trace_attributes', body)); + } + + // response-contract-exempt: passes Valhalla's own answer through @Res(), status and body as they came. + @Post('height') + @HttpCode(200) + async height(@CurrentUser() user: User, @Body() body: ValhallaHeightDto, @Res() res: Response): Promise { + passOn(res, await this.relay.ask(user.id, 'height', body)); + } +} + +function passOn(res: Response, answer: ValhallaRelayAnswer): void { + res.status(answer.status).type(answer.contentType).send(answer.body); +} diff --git a/server/src/nest/routing-relay/routing-relay.dto.ts b/server/src/nest/routing-relay/routing-relay.dto.ts new file mode 100644 index 000000000..b5da3dde3 --- /dev/null +++ b/server/src/nest/routing-relay/routing-relay.dto.ts @@ -0,0 +1,8 @@ +import { valhallaHeightRequestSchema, valhallaRouteRequestSchema, valhallaTraceRequestSchema } from '@trek/shared'; + +import { createZodDto } from 'nestjs-zod'; + +/** The bodies of the three Valhalla questions the relay takes, validated at the Zod pipe. */ +export class ValhallaRouteDto extends createZodDto(valhallaRouteRequestSchema) {} +export class ValhallaTraceDto extends createZodDto(valhallaTraceRequestSchema) {} +export class ValhallaHeightDto extends createZodDto(valhallaHeightRequestSchema) {} diff --git a/server/src/nest/routing-relay/routing-relay.module.ts b/server/src/nest/routing-relay/routing-relay.module.ts new file mode 100644 index 000000000..085cb3401 --- /dev/null +++ b/server/src/nest/routing-relay/routing-relay.module.ts @@ -0,0 +1,19 @@ +import { AppConfigModule } from '../app-config/app-config.module'; +import { RateLimitModule } from '../common/rate-limit.module'; +import { ServiceIdentityModule } from '../service-identity/service-identity.module'; +import { RoutingRelayController } from './routing-relay.controller'; +import { RoutingRelayService } from './routing-relay.service'; +import { Module } from '@nestjs/common'; + +/** + * The TREK services' Valhalla behind this server: the planner in the browser + * asks it through the controller, the road trip router on the server through + * the exported service, both under the same limits. + */ +@Module({ + imports: [AppConfigModule, RateLimitModule, ServiceIdentityModule], + controllers: [RoutingRelayController], + providers: [RoutingRelayService], + exports: [RoutingRelayService], +}) +export class RoutingRelayModule {} diff --git a/server/src/nest/routing-relay/routing-relay.service.ts b/server/src/nest/routing-relay/routing-relay.service.ts new file mode 100644 index 000000000..088a43e38 --- /dev/null +++ b/server/src/nest/routing-relay/routing-relay.service.ts @@ -0,0 +1,119 @@ +import { readCapped } from '../../utils/cappedFetch'; +import { safeFetchAdminConfigured } from '../../utils/ssrfGuard'; +import { servicesConfig } from '../app-config/tokens'; +import { logWarn } from '../audit/audit-log.logger'; +import { DomainError } from '../common/domain-error'; +import { RateLimitService } from '../common/rate-limit.service'; +import { ServiceIdentityPort } from '../service-identity/service-identity.interface'; +import { Inject, Injectable } from '@nestjs/common'; +import type { ConfigType } from '@nestjs/config'; +import { VALHALLA_RELAY_REQUEST_SCHEMAS, compactValhallaRequest, type ValhallaRelayAction } from '@trek/shared'; + +/** Questions one user may put to the TREK Valhalla a minute, the browser and the server's own routing together. */ +const QUESTIONS_PER_MINUTE = 120; +const RATE_WINDOW_MS = 60_000; +const DEFAULT_TIMEOUT_MS = 30_000; +/** A day with alternates, or the description of a long line, stays far below this. */ +const MAX_ANSWER_BYTES = 8 * 1024 * 1024; + +/** Valhalla's answer as it came: its status, its content type and its body untouched. */ +export interface ValhallaRelayAnswer { + status: number; + contentType: string; + body: Buffer; +} + +/** + * The TREK services' Valhalla, asked on behalf of a signed-in user. The + * address comes from configuration (TREK_VALHALLA_URL), never from the + * request; the installation key goes with it only to a host + * TREK_SERVICES_HOSTS lists, so a browser never sees the key and a user + * cannot send it anywhere else. Every question counts against the user's + * allowance here, whichever surface asks it. + */ +@Injectable() +export class RoutingRelayService { + constructor( + @Inject(servicesConfig.KEY) private readonly config: ConfigType, + private readonly identity: ServiceIdentityPort, + private readonly rateLimit: RateLimitService, + ) {} + + /** The TREK Valhalla's address while it can be asked: the services are on and hold a key for it. */ + trekValhalla(): string | null { + return this.keyHeaders(new URL(this.config.valhallaUrl)) ? this.config.valhallaUrl : null; + } + + /** Whether an address names the TREK Valhalla, whose questions go through here and nowhere else. */ + serves(base: string): boolean { + return base.trim().replace(/\/+$/, '') === this.config.valhallaUrl; + } + + async ask( + userId: number, + action: ValhallaRelayAction, + body: object, + timeoutMs = DEFAULT_TIMEOUT_MS, + ): Promise { + const parsed = VALHALLA_RELAY_REQUEST_SCHEMAS[action].safeParse(compactValhallaRequest(action, body)); + if (!parsed.success) { + throw new DomainError(400, parsed.error.issues[0]?.message ?? 'Invalid routing request'); + } + const url = this.endpoint(action); + const headers = this.keyHeaders(url); + if (!headers) throw new DomainError(503, 'The TREK routing service is not available on this instance'); + const allowed = await this.rateLimit.check( + 'valhalla-relay', + String(userId), + QUESTIONS_PER_MINUTE, + RATE_WINDOW_MS, + Date.now(), + ); + if (!allowed) throw new DomainError(429, 'Too many routing requests, try again in a minute'); + return this.forward(url, headers, parsed.data, timeoutMs); + } + + private async forward( + url: URL, + identity: Record, + body: unknown, + timeoutMs: number, + ): Promise { + try { + const response = await safeFetchAdminConfigured( + url.href, + { + method: 'POST', + headers: { ...identity, 'Content-Type': 'application/json', Accept: 'application/json' }, + body: JSON.stringify(body), + signal: AbortSignal.timeout(timeoutMs), + }, + 0, + undefined, + MAX_ANSWER_BYTES, + ); + this.identity.observe(url, response); + const { bytes, truncated } = await readCapped(response, MAX_ANSWER_BYTES); + if (truncated) throw new Error('the answer is larger than the relay passes on'); + return { + status: response.status, + contentType: response.headers.get('content-type') ?? 'application/json', + body: bytes, + }; + } catch (err) { + logWarn(`[Routing relay] ${url.pathname}: ${err instanceof Error ? err.message : String(err)}`); + throw new DomainError(502, 'The TREK routing service did not answer'); + } + } + + private endpoint(action: ValhallaRelayAction): URL { + return new URL(`${this.config.valhallaUrl}/${action}`); + } + + /** The identity headers for the TREK Valhalla, or null while there is no key to send. */ + private keyHeaders(url: URL): Record | null { + if (this.config.mode === 'off') return null; + const headers = this.identity.headersFor(url); + return headers.Authorization ? headers : null; + } +} diff --git a/server/src/nest/service-identity/service-identity.module.ts b/server/src/nest/service-identity/service-identity.module.ts index 85e5ccdf2..8c73e52a2 100644 --- a/server/src/nest/service-identity/service-identity.module.ts +++ b/server/src/nest/service-identity/service-identity.module.ts @@ -18,7 +18,8 @@ import { Module, type OnModuleDestroy } from '@nestjs/common'; * The installation identity towards the liketrek services: the key, its * registration and renewal, and the admin view of it. The Places client reads * the request side through serviceIdentitySlot, which this module fills with - * the port the container resolved. + * the port the container resolved; a provider (the routing relay) injects the + * exported port instead. */ @Module({ imports: [AppConfigModule, AuditModule, SchedulingModule, SettingsModule], @@ -33,6 +34,7 @@ import { Module, type OnModuleDestroy } from '@nestjs/common'; ServiceKeyStore, { provide: ServiceIdentityPort, useClass: ServiceRequestIdentity }, ], + exports: [ServiceIdentityPort], }) export class ServiceIdentityModule implements OnModuleDestroy { constructor(private readonly port: ServiceIdentityPort) { diff --git a/server/tests/e2e/routing-relay.e2e.test.ts b/server/tests/e2e/routing-relay.e2e.test.ts new file mode 100644 index 000000000..db66425f5 --- /dev/null +++ b/server/tests/e2e/routing-relay.e2e.test.ts @@ -0,0 +1,156 @@ +/** + * /api/routing/valhalla e2e: the real JwtAuthGuard, the Zod pipe over the + * shared contract and RoutingRelayModule on a migrated temp database, against + * a stub Valhalla behind safeFetchAdminConfigured. The identity port is a + * fake: NODE_ENV=test registers no key, and the key is the port's to give. + */ +import { servicesConfig } from '../../src/nest/app-config/tokens'; +import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter'; +import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe'; +import { RoutingRelayModule } from '../../src/nest/routing-relay/routing-relay.module'; +import { ServiceIdentityPort } from '../../src/nest/service-identity/service-identity.interface'; +import { createSnapshotTestDb } from '../helpers/db-mock'; +import { makeUser } from '../helpers/factories/users'; +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 cookieParser from 'cookie-parser'; +import request from 'supertest'; +import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; + +const { safeFetchAdminConfigured } = vi.hoisted(() => ({ safeFetchAdminConfigured: vi.fn() })); +vi.mock('../../src/utils/ssrfGuard', async (importOriginal) => ({ + ...(await importOriginal()), + safeFetchAdminConfigured, +})); + +const db = createSnapshotTestDb(); +const USER = 1; +const identity = { + headersFor: vi.fn((): Record => ({ 'User-Agent': 'TREK/5.1.0', Authorization: 'Bearer tk1.k.p.s' })), + observe: vi.fn(), +}; +const ROUTE = { + locations: [ + { lat: 48.2, lon: 16.37, radius: 50 }, + { lat: 47.8, lon: 13.04, radius: 50 }, + ], + costing: 'auto', + costing_options: { auto: { use_tolls: 0 } }, + directions_options: { units: 'kilometers' }, +}; + +let orm: TestOrm; +let app: Awaited>; + +async function build() { + const moduleRef = await Test.createTestingModule({ + imports: [await TestUnitOfWorkModule.forRoot(db), await createTestMikroOrmModule(db), RoutingRelayModule], + }) + .overrideProvider(servicesConfig.KEY) + .useValue({ + mode: 'auto', + key: null, + hosts: ['places.liketrek.com', 'valhalla.liketrek.com'], + valhallaUrl: 'https://valhalla.liketrek.com', + }) + .overrideProvider(ServiceIdentityPort) + .useValue(identity) + .compile(); + const nest = moduleRef.createNestApplication(); + nest.use(cookieParser()); + nest.useGlobalFilters(new TrekExceptionFilter()); + nest.useGlobalPipes(new ZodValidationPipe()); + await nest.init(); + return nest; +} + +const as = (userId: number) => ({ Cookie: sessionCookie(userId) }); +const valhallaAnswers = (status: number, body: unknown) => + safeFetchAdminConfigured.mockResolvedValue( + new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } }), + ); + +beforeAll(async () => { + orm = await createTestOrm(db); + await makeUser(orm, { id: USER, username: 'planner', email: 'planner@example.test' }); + app = await build(); +}); + +beforeEach(() => { + safeFetchAdminConfigured.mockReset(); + identity.headersFor.mockClear(); +}); + +afterAll(async () => { + await app.close(); + await orm.close(); +}); + +describe('POST /api/routing/valhalla/:action', () => { + it('RELAY-E2E-001: answers 401 without a session and asks nothing', async () => { + const res = await request(app.getHttpServer()).post('/api/routing/valhalla/route').send(ROUTE); + expect(res.status).toBe(401); + expect(safeFetchAdminConfigured).not.toHaveBeenCalled(); + }); + + it('RELAY-E2E-002: relays a route with the installation key and answers with Valhalla’s own body', async () => { + const trip = { trip: { legs: [{ shape: '_p~iF~ps|U', summary: { length: 1.2, time: 90 } }] } }; + valhallaAnswers(200, trip); + const res = await request(app.getHttpServer()).post('/api/routing/valhalla/route').set(as(USER)).send(ROUTE); + expect(res.status).toBe(200); + expect(res.body).toEqual(trip); + const [url, init] = safeFetchAdminConfigured.mock.calls[0] as [string, RequestInit]; + expect(url).toBe('https://valhalla.liketrek.com/route'); + expect((init.headers as Record).Authorization).toBe('Bearer tk1.k.p.s'); + expect(JSON.parse(String(init.body))).toEqual(ROUTE); + }); + + it('RELAY-E2E-003: passes Valhalla’s refusal on with its status, for the planner to read', async () => { + valhallaAnswers(400, { error_code: 442, error: 'No path could be found for input' }); + const res = await request(app.getHttpServer()).post('/api/routing/valhalla/route').set(as(USER)).send(ROUTE); + expect(res.status).toBe(400); + expect(res.body).toEqual({ error_code: 442, error: 'No path could be found for input' }); + }); + + it('RELAY-E2E-004: refuses a body outside the contract at the pipe, before Valhalla is asked', async () => { + const tooMany = { ...ROUTE, locations: Array.from({ length: 21 }, () => ROUTE.locations[0]) }; + const route = await request(app.getHttpServer()).post('/api/routing/valhalla/route').set(as(USER)).send(tooMany); + expect(route.status).toBe(400); + const both = await request(app.getHttpServer()) + .post('/api/routing/valhalla/trace_attributes') + .set(as(USER)) + .send({ shape: [ROUTE.locations[0], ROUTE.locations[1]], encoded_polyline: 'abc', costing: 'pedestrian' }); + expect(both.status).toBe(400); + expect(safeFetchAdminConfigured).not.toHaveBeenCalled(); + }); + + it('RELAY-E2E-005: relays heights and the description of a line', async () => { + valhallaAnswers(200, { range_height: [[0, 512]] }); + const heights = await request(app.getHttpServer()) + .post('/api/routing/valhalla/height') + .set(as(USER)) + .send({ shape: [{ lat: 47, lon: 11 }], range: true }); + expect(heights.body).toEqual({ range_height: [[0, 512]] }); + valhallaAnswers(200, { edges: [] }); + const trace = await request(app.getHttpServer()) + .post('/api/routing/valhalla/trace_attributes') + .set(as(USER)) + .send({ encoded_polyline: '_p~iF~ps|U_ulLnnqC', costing: 'pedestrian', shape_match: 'map_snap' }); + expect(trace.status).toBe(200); + expect(safeFetchAdminConfigured.mock.calls.map(([url]) => url)).toEqual([ + 'https://valhalla.liketrek.com/height', + 'https://valhalla.liketrek.com/trace_attributes', + ]); + }); + + it('RELAY-E2E-006: answers 503 while the installation holds no key, so the planner turns to FOSSGIS', async () => { + identity.headersFor.mockReturnValueOnce({ 'User-Agent': 'TREK/5.1.0' }); + const res = await request(app.getHttpServer()).post('/api/routing/valhalla/route').set(as(USER)).send(ROUTE); + expect(res.status).toBe(503); + expect(res.body).toEqual({ error: 'The TREK routing service is not available on this instance' }); + expect(safeFetchAdminConfigured).not.toHaveBeenCalled(); + }); +}); diff --git a/server/tests/unit/app-config/derive.test.ts b/server/tests/unit/app-config/derive.test.ts index 6b3492527..6dd621635 100644 --- a/server/tests/unit/app-config/derive.test.ts +++ b/server/tests/unit/app-config/derive.test.ts @@ -323,6 +323,14 @@ describe('deriveServices (servicesConfig token)', () => { 'https://geo.example.org/photon', ); }); + + it('relays routing to valhalla.liketrek.com unless TREK_VALHALLA_URL names another, without its trailing slash', () => { + expect(deriveServices({}).valhallaUrl).toBe('https://valhalla.liketrek.com'); + expect(deriveServices({ TREK_VALHALLA_URL: ' http://valhalla.lan:8002/ ' }).valhallaUrl).toBe( + 'http://valhalla.lan:8002', + ); + expect(deriveServices({ TREK_VALHALLA_URL: ' ' }).valhallaUrl).toBe('https://valhalla.liketrek.com'); + }); }); describe('deriveFiles (#1364)', () => { diff --git a/server/tests/unit/nest/roadtrip-router.test.ts b/server/tests/unit/nest/roadtrip-router.test.ts index a2910d86f..ef263b3cc 100644 --- a/server/tests/unit/nest/roadtrip-router.test.ts +++ b/server/tests/unit/nest/roadtrip-router.test.ts @@ -1,4 +1,6 @@ +import { DomainError } from '../../../src/nest/common/domain-error'; import { RoadtripRouterService, RouteRefusal } from '../../../src/nest/roadtrip/roadtrip-router.service'; +import type { ValhallaRelayAnswer } from '../../../src/nest/routing-relay/routing-relay.service'; import { safeFetchAdminConfigured } from '../../../src/utils/ssrfGuard'; import { valhallaPolyline } from '../../helpers/valhalla'; @@ -35,6 +37,13 @@ const osrm = () => waypoints: points.map((p) => ({ location: [p.lng, p.lat], distance: 25 })), }), ); +const TREK_VALHALLA = 'https://valhalla.liketrek.com'; +/** The routing relay: no TREK Valhalla to ask unless a case opens one. */ +const relay = { + trekValhalla: vi.fn((): string | null => null), + serves: vi.fn((base: string) => base === TREK_VALHALLA), + ask: vi.fn<(...args: unknown[]) => Promise>(), +}; function setup(settings = {}) { const hooks = { providersOf: vi.fn(() => ['scenic']), route: vi.fn() }; // RRT1/RRT2 (Plan 3j Task 3, confirmed at Task 5's own HEAD) — `declaredProfiles` @@ -42,7 +51,12 @@ function setup(settings = {}) { const plugins = { findCapabilities: vi.fn(async () => JSON.stringify({ routeProfiles: [{ id: 'car' }] })) }; return { hooks, - router: new RoadtripRouterService({ getUserSettings: () => settings } as never, hooks as never, plugins as never), + router: new RoadtripRouterService( + { getUserSettings: () => settings } as never, + hooks as never, + plugins as never, + relay as never, + ), }; } beforeEach(() => { @@ -50,6 +64,8 @@ beforeEach(() => { vi.mocked(safeFetchAdminConfigured) .mockReset() .mockImplementation(async () => osrm()); + relay.trekValhalla.mockReset().mockReturnValue(null); + relay.ask.mockReset(); }); afterEach(() => vi.useRealTimers()); @@ -674,3 +690,124 @@ describe('server Roadtrip router: other ways on foot (RTE-02)', () => { expect(safeFetchAdminConfigured).not.toHaveBeenCalled(); }); }); + +describe('server Roadtrip router through the TREK services (routing relay)', () => { + const answer = (status: number, body: unknown): ValhallaRelayAnswer => ({ + status, + contentType: 'application/json', + body: Buffer.from(JSON.stringify(body)), + }); + const tolled = { + trip: { + legs: [ + { + shape: valhallaPolyline([ + [48, 10], + [49, 11], + ]), + summary: { length: 25, time: 1200, has_toll: false }, + }, + ], + }, + }; + const settled = async (pending: Promise): Promise => { + await vi.runAllTimersAsync(); + return await pending; + }; + + beforeEach(() => relay.trekValhalla.mockReturnValue(TREK_VALHALLA)); + + it('ROUTER-RELAY-001: asks the TREK Valhalla through the relay by default, under the asking user', async () => { + relay.ask.mockResolvedValueOnce(answer(200, tolled)); + const route = await setup().router.route(7, 1, 1, points.slice(0, 2), 'driving', ['toll']); + expect(route.avoidMissed).toEqual([]); + expect(relay.ask).toHaveBeenCalledTimes(1); + const [userId, action, body] = relay.ask.mock.calls[0] as [number, string, { costing: string }]; + expect([userId, action, body.costing]).toEqual([7, 'route', 'auto']); + expect(safeFetchAdminConfigured).not.toHaveBeenCalled(); + }); + + it('ROUTER-RELAY-002: hands the question to FOSSGIS where the relay cannot answer', async () => { + const refusals = [ + () => Promise.resolve(answer(429, { error: 'Too many routing requests' })), + () => Promise.resolve(answer(502, { error: 'down' })), + () => Promise.reject(new DomainError(503, 'The TREK routing service is not available on this instance')), + ]; + for (const [userId, refusal] of refusals.entries()) { + vi.mocked(safeFetchAdminConfigured) + .mockReset() + .mockResolvedValueOnce(new Response(JSON.stringify(tolled))); + relay.ask.mockReset().mockImplementationOnce(refusal); + const route = await settled(setup().router.route(userId, 1, 1, points.slice(0, 2), 'driving', ['toll'])); + expect(route.avoidMissed).toEqual([]); + expect(vi.mocked(safeFetchAdminConfigured).mock.calls[0][0]).toBe('https://valhalla1.openstreetmap.de/route'); + } + }); + + it('ROUTER-RELAY-003: reads the TREK Valhalla saying no way joins the points as a refusal, and fails on any other error', async () => { + const costingOptions = { max_hiking_difficulty: 3 }; + relay.ask.mockResolvedValueOnce(answer(400, { error_code: 442, error: 'No path could be found for input' })); + const refused = setup().router.route(1, 1, 0, points.slice(0, 2), 'walking', [], { costingOptions }); + await expect(refused).rejects.toMatchObject({ why: 'no_way' }); + + relay.ask.mockRejectedValueOnce(new Error('socket hang up')); + await expect(setup().router.route(1, 1, 0, points.slice(0, 2), 'walking', [], { costingOptions })).rejects.toThrow( + 'socket hang up', + ); + expect(safeFetchAdminConfigured).not.toHaveBeenCalled(); + }); + + it('ROUTER-RELAY-004: an admin choice of FOSSGIS or an own Valhalla never reaches the relay', async () => { + vi.mocked(safeFetchAdminConfigured).mockImplementation(async () => new Response(JSON.stringify(tolled))); + await setup({ routing_valhalla_provider: 'fossgis' }).router.route(1, 1, 1, points.slice(0, 2), 'driving', [ + 'toll', + ]); + expect(vi.mocked(safeFetchAdminConfigured).mock.calls[0][0]).toBe('https://valhalla1.openstreetmap.de/route'); + await settled( + setup({ valhalla_base_url: 'https://valhalla.internal' }).router.route(2, 1, 1, points.slice(0, 2), 'driving', [ + 'toll', + ]), + ); + expect(vi.mocked(safeFetchAdminConfigured).mock.calls[1][0]).toBe('https://valhalla.internal/route'); + expect(relay.ask).not.toHaveBeenCalled(); + }); + + it('ROUTER-RELAY-005: an own OSRM alone asks no Valhalla, unless the admin picked the TREK services', async () => { + const own = { routing_base_url: 'http://router.internal' }; + await setup(own).router.route(1, 1, 1, points, 'driving', ['toll']); + expect(relay.ask).not.toHaveBeenCalled(); + + relay.ask.mockResolvedValueOnce(answer(200, tolled)); + await setup({ ...own, routing_valhalla_provider: 'trek' }).router.route(1, 1, 1, points.slice(0, 2), 'driving', [ + 'toll', + ]); + expect(relay.ask).toHaveBeenCalledTimes(1); + }); + + it('ROUTER-RELAY-006: reads heights and the ways under a line through the relay', async () => { + relay.ask.mockImplementation(async (_userId, action, body) => + action === 'height' + ? answer(200, { + range_height: (body as { shape: unknown[] }).shape.map((_point, index) => [index, 400 + index]), + }) + : answer(200, { edges: [{ way_id: 5, length: 0.3 }] }), + ); + const { router } = setup(); + const line: Array<[number, number]> = [ + [47, 11], + [47.001, 11], + [47.002, 11], + ]; + expect(await router.heights(3, line)).toEqual([ + [47, 11, 400], + [47.001, 11, 401], + [47.002, 11, 402], + ]); + expect(await router.wayIds(3, line)).toEqual([{ wayId: 5, metres: 300 }]); + expect(relay.ask.mock.calls.map(([userId, action]) => [userId, action])).toEqual([ + [3, 'height'], + [3, 'trace_attributes'], + ]); + expect(safeFetchAdminConfigured).not.toHaveBeenCalled(); + }); +}); diff --git a/server/tests/unit/nest/routing-relay/routing-relay.controller.test.ts b/server/tests/unit/nest/routing-relay/routing-relay.controller.test.ts new file mode 100644 index 000000000..1b1207c57 --- /dev/null +++ b/server/tests/unit/nest/routing-relay/routing-relay.controller.test.ts @@ -0,0 +1,53 @@ +/** + * RoutingRelayController: each route hands its action and the signed-in user + * to the relay and writes Valhalla's answer as it came, status, type and body. + */ +import { RoutingRelayController } from '../../../../src/nest/routing-relay/routing-relay.controller'; +import type { RoutingRelayService } from '../../../../src/nest/routing-relay/routing-relay.service'; +import type { User } from '../../../../src/types'; + +import type { Response } from 'express'; +import { describe, expect, it, vi } from 'vitest'; + +function response() { + const res = { status: vi.fn(), type: vi.fn(), send: vi.fn() }; + res.status.mockReturnValue(res); + res.type.mockReturnValue(res); + return res; +} + +const user = { id: 4 } as User; +const answer = { status: 400, contentType: 'application/json', body: Buffer.from('{"error_code":171}') }; + +describe('RoutingRelayController', () => { + it('RELAY-CTRL-001: asks the relay for the user and passes each answer on untouched', async () => { + const ask = vi.fn().mockResolvedValue(answer); + const controller = new RoutingRelayController({ ask } as unknown as RoutingRelayService); + const route = { locations: [], costing: 'auto' } as never; + const trace = { encoded_polyline: 'abc', costing: 'pedestrian' } as never; + const height = { shape: [{ lat: 47, lon: 11 }] } as never; + + for (const [call, action, body] of [ + [(res: Response) => controller.route(user, route, res), 'route', route], + [(res: Response) => controller.traceAttributes(user, trace, res), 'trace_attributes', trace], + [(res: Response) => controller.height(user, height, res), 'height', height], + ] as const) { + const res = response(); + await call(res as unknown as Response); + expect(ask).toHaveBeenLastCalledWith(4, action, body); + expect(res.status).toHaveBeenCalledWith(400); + expect(res.type).toHaveBeenCalledWith('application/json'); + expect(res.send).toHaveBeenCalledWith(answer.body); + } + }); + + it('RELAY-CTRL-002: lets a refusal of the relay itself reach the exception filter', async () => { + const refusal = new Error('refused'); + const controller = new RoutingRelayController({ + ask: vi.fn().mockRejectedValue(refusal), + } as unknown as RoutingRelayService); + const res = response(); + await expect(controller.height(user, { shape: [] } as never, res as unknown as Response)).rejects.toBe(refusal); + expect(res.send).not.toHaveBeenCalled(); + }); +}); diff --git a/server/tests/unit/nest/routing-relay/routing-relay.service.test.ts b/server/tests/unit/nest/routing-relay/routing-relay.service.test.ts new file mode 100644 index 000000000..8aa9fb971 --- /dev/null +++ b/server/tests/unit/nest/routing-relay/routing-relay.service.test.ts @@ -0,0 +1,157 @@ +/** + * RoutingRelayService: the TREK services' Valhalla asked for a user. The key + * goes along only when the identity hands one over for that host, the body is + * held to the shared contract, every question counts against the user's + * minute, and Valhalla's answer comes back untouched. The upstream behind + * safeFetchAdminConfigured is a stub. + */ +import { servicesConfig } from '../../../../src/nest/app-config/tokens'; +import { DomainError } from '../../../../src/nest/common/domain-error'; +import { RateLimitModule } from '../../../../src/nest/common/rate-limit.module'; +import { RateLimitService } from '../../../../src/nest/common/rate-limit.service'; +import { RoutingRelayService } from '../../../../src/nest/routing-relay/routing-relay.service'; +import { ServiceIdentityPort } from '../../../../src/nest/service-identity/service-identity.interface'; +import { safeFetchAdminConfigured } from '../../../../src/utils/ssrfGuard'; +import { createSnapshotTestDb } from '../../../helpers/db-mock'; +import { createTestModule, type TestModule } from '../../../helpers/test-module'; + +import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +vi.mock('../../../../src/utils/ssrfGuard', () => ({ safeFetchAdminConfigured: vi.fn() })); + +const config = { + mode: 'auto' as 'auto' | 'off', + key: null, + hosts: ['places.liketrek.com', 'valhalla.liketrek.com'], + valhallaUrl: 'https://valhalla.liketrek.com', +}; +const identity = { + headersFor: vi.fn((): Record => ({ 'User-Agent': 'TREK/5.1.0', Authorization: 'Bearer tk1.k.p.s' })), + observe: vi.fn(), +}; +const ROUTE = { + locations: [ + { lat: 48.2, lon: 16.37, radius: 50 }, + { lat: 47.8, lon: 13.04, radius: 50 }, + ], + costing: 'auto', + costing_options: { auto: { use_tolls: 0 } }, +}; +const upstream = (status: number, body: string, type = 'application/json') => + new Response(body, { status, headers: { 'content-type': type } }); + +const testDb = createSnapshotTestDb(); +let t: TestModule; +let relay: RoutingRelayService; + +beforeEach(async () => { + vi.mocked(safeFetchAdminConfigured).mockReset(); + identity.headersFor.mockClear(); + identity.observe.mockClear(); + config.mode = 'auto'; + t = await createTestModule({ + db: testDb, + imports: [RateLimitModule], + providers: [ + RoutingRelayService, + { provide: servicesConfig.KEY, useValue: config }, + { provide: ServiceIdentityPort, useValue: identity }, + ], + }); + relay = t.get(RoutingRelayService); + await t.get(RateLimitService).reset(); +}); + +afterEach(async () => { + await t.close(); +}); + +afterAll(() => testDb.close()); + +describe('RoutingRelayService.ask', () => { + it('RELAY-001: posts the route to the configured Valhalla with the key and hands the answer back untouched', async () => { + vi.mocked(safeFetchAdminConfigured).mockResolvedValueOnce(upstream(200, '{"trip":{"legs":[]}}')); + const answer = await relay.ask(1, 'route', ROUTE); + expect(answer).toEqual({ + status: 200, + contentType: 'application/json', + body: Buffer.from('{"trip":{"legs":[]}}'), + }); + const [url, init, redirects] = vi.mocked(safeFetchAdminConfigured).mock.calls[0]; + expect(url).toBe('https://valhalla.liketrek.com/route'); + expect(redirects).toBe(0); + expect(init?.signal).toBeInstanceOf(AbortSignal); + expect((init?.headers as Record).Authorization).toBe('Bearer tk1.k.p.s'); + expect(JSON.parse(String(init?.body))).toEqual(ROUTE); + const [observed] = identity.observe.mock.calls[0] as unknown as [URL]; + expect(observed.href).toBe('https://valhalla.liketrek.com/route'); + }); + + it('RELAY-002: passes a refusal on with its status, so the planner reads it as it reads Valhalla', async () => { + vi.mocked(safeFetchAdminConfigured).mockResolvedValueOnce(upstream(400, '{"error_code":442}')); + const answer = await relay.ask(1, 'route', ROUTE); + expect(answer.status).toBe(400); + expect(answer.body.toString()).toBe('{"error_code":442}'); + }); + + it('RELAY-003: sends a description of a line as a polyline', async () => { + vi.mocked(safeFetchAdminConfigured).mockResolvedValueOnce(upstream(200, '{"edges":[]}')); + const shape = Array.from({ length: 4000 }, (_, i) => ({ lat: 47 + i / 1e4, lon: 11.123456789 })); + await relay.ask(1, 'trace_attributes', { shape, costing: 'pedestrian', shape_match: 'map_snap' }); + const [url, init] = vi.mocked(safeFetchAdminConfigured).mock.calls[0]; + expect(url).toBe('https://valhalla.liketrek.com/trace_attributes'); + const sent = JSON.parse(String(init?.body)) as Record; + expect(sent).not.toHaveProperty('shape'); + expect(typeof sent.encoded_polyline).toBe('string'); + }); + + it('RELAY-004: refuses a body the contract does not take before asking anything', async () => { + const tooMany = { ...ROUTE, locations: Array.from({ length: 21 }, () => ROUTE.locations[0]) }; + await expect(relay.ask(1, 'route', tooMany)).rejects.toMatchObject({ status: 400 }); + await expect(relay.ask(1, 'height', { shape: [] })).rejects.toBeInstanceOf(DomainError); + expect(safeFetchAdminConfigured).not.toHaveBeenCalled(); + }); + + it('RELAY-005: answers 503 without a key and while the services are off, and asks nothing', async () => { + identity.headersFor.mockReturnValueOnce({ 'User-Agent': 'TREK/5.1.0' }); + await expect(relay.ask(1, 'route', ROUTE)).rejects.toMatchObject({ status: 503 }); + config.mode = 'off'; + await expect(relay.ask(2, 'route', ROUTE)).rejects.toMatchObject({ status: 503 }); + expect(safeFetchAdminConfigured).not.toHaveBeenCalled(); + }); + + it('RELAY-006: holds every user to 120 questions a minute, each user apart', async () => { + vi.mocked(safeFetchAdminConfigured).mockImplementation(async () => upstream(200, '{}')); + for (let i = 0; i < 120; i++) await relay.ask(1, 'height', { shape: [{ lat: 47, lon: 11 }] }); + const refused = await relay.ask(1, 'route', ROUTE).catch((err: unknown) => err); + expect(refused).toBeInstanceOf(DomainError); + expect(refused).toMatchObject({ status: 429, message: 'Too many routing requests, try again in a minute' }); + expect((await relay.ask(2, 'route', ROUTE)).status).toBe(200); + expect(safeFetchAdminConfigured).toHaveBeenCalledTimes(121); + }); + + it('RELAY-007: answers 502 where the host does not answer or sends more than it passes on', async () => { + vi.mocked(safeFetchAdminConfigured).mockRejectedValueOnce(new Error('connect ECONNREFUSED')); + await expect(relay.ask(1, 'route', ROUTE)).rejects.toMatchObject({ + status: 502, + message: 'The TREK routing service did not answer', + }); + vi.mocked(safeFetchAdminConfigured).mockResolvedValueOnce(upstream(200, 'x'.repeat(8 * 1024 * 1024 + 1))); + await expect(relay.ask(1, 'route', ROUTE)).rejects.toMatchObject({ status: 502 }); + }); +}); + +describe('RoutingRelayService.trekValhalla and serves', () => { + it('RELAY-010: names the TREK Valhalla only while there is a key to take there', () => { + expect(relay.trekValhalla()).toBe('https://valhalla.liketrek.com'); + identity.headersFor.mockReturnValueOnce({}); + expect(relay.trekValhalla()).toBeNull(); + config.mode = 'off'; + expect(relay.trekValhalla()).toBeNull(); + }); + + it('RELAY-011: knows its own address, with or without a trailing slash, and no other', () => { + expect(relay.serves('https://valhalla.liketrek.com/')).toBe(true); + expect(relay.serves('https://valhalla1.openstreetmap.de')).toBe(false); + }); +}); diff --git a/server/vitest.config.ts b/server/vitest.config.ts index 41b6bd3cc..bf10fd1d1 100644 --- a/server/vitest.config.ts +++ b/server/vitest.config.ts @@ -186,6 +186,9 @@ export default defineConfig({ // points against the headroom of the domains beside them. 'src/nest/roadtrip/**/*.ts': { statements: 88, branches: 80, functions: 95, lines: 95 }, 'src/nest/route-usage/**/*.ts': { statements: 84, branches: 66, functions: 77, lines: 83 }, + // New domain in this change, unmeasured: on the 80 floor until the first + // full CI run, then raised with scripts/coverage-thresholds.mjs, never lowered. + 'src/nest/routing-relay/**/*.ts': { statements: 80, branches: 80, functions: 80, lines: 80 }, 'src/nest/scheduling/**/*.ts': { statements: 99, branches: 92, functions: 99, lines: 99 }, 'src/nest/school-holidays/**/*.ts': { statements: 97, branches: 95, functions: 99, lines: 97 }, // New domain in this change, unmeasured: on the 80 floor until the first diff --git a/shared/src/index.ts b/shared/src/index.ts index eef6ee341..360e6a163 100644 --- a/shared/src/index.ts +++ b/shared/src/index.ts @@ -231,6 +231,8 @@ export * from './oidc/oidc.schema'; export * from './oauth/oauth.schema'; export * from './admin/admin.schema'; export * from './service-identity/service-identity.schema'; +export * from './routing-relay/routing-relay.schema'; +export * from './routing-relay/valhalla-provider'; export * from './ai/ai-connections.schema'; export * from './assistant/assistant.schema'; export * from './assistant/assistant-attachments.schema'; diff --git a/shared/src/routing-relay/routing-relay.schema.spec.ts b/shared/src/routing-relay/routing-relay.schema.spec.ts new file mode 100644 index 000000000..8a57c58ea --- /dev/null +++ b/shared/src/routing-relay/routing-relay.schema.spec.ts @@ -0,0 +1,145 @@ +import { + VALHALLA_RELAY_MAX_LOCATIONS, + valhallaHeightRequestSchema, + valhallaRouteRequestSchema, + valhallaTraceRequestSchema, +} from './routing-relay.schema'; +import { compactValhallaRequest, encodePolyline6, resolveValhallaProvider } from './valhalla-provider'; + +import { describe, expect, it } from 'vitest'; + +const route = { + locations: [ + { lat: 48.2, lon: 16.37, radius: 50 }, + { lat: 47.8, lon: 13.04, radius: 50, search_filter: { exclude_ferry: true } }, + ], + costing: 'auto', + costing_options: { auto: { use_tolls: 0, use_ferry: 1 } }, + directions_options: { units: 'kilometers' }, +}; + +const line = (count: number) => Array.from({ length: count }, (_, i) => ({ lat: 47 + i / 1e4, lon: 11.123456789 })); + +describe('valhallaRouteRequestSchema', () => { + it('takes the route the planner asks for, its costing options included', () => { + expect(valhallaRouteRequestSchema.parse(route)).toEqual(route); + expect(valhallaRouteRequestSchema.parse({ ...route, alternates: 3 }).alternates).toBe(3); + const bike = { + ...route, + costing: 'bicycle', + costing_options: { bicycle: { bicycle_type: 'Road', use_hills: 0.2 } }, + }; + expect(valhallaRouteRequestSchema.safeParse(bike).success).toBe(true); + }); + + it('refuses one location, more than the relay allows, a costing TREK never asks and a point off the globe', () => { + expect(valhallaRouteRequestSchema.safeParse({ ...route, locations: route.locations.slice(0, 1) }).success).toBe( + false, + ); + const many = Array.from({ length: VALHALLA_RELAY_MAX_LOCATIONS + 1 }, () => route.locations[0]); + expect(valhallaRouteRequestSchema.safeParse({ ...route, locations: many }).success).toBe(false); + expect(valhallaRouteRequestSchema.safeParse({ ...route, costing: 'truck' }).success).toBe(false); + const off = [{ lat: 91, lon: 0 }, route.locations[1]]; + expect(valhallaRouteRequestSchema.safeParse({ ...route, locations: off }).success).toBe(false); + }); + + it('drops what it does not know instead of passing it on', () => { + const parsed = valhallaRouteRequestSchema.parse({ ...route, id: 'x', date_time: { type: 0 } }); + expect(parsed).not.toHaveProperty('id'); + expect(parsed).not.toHaveProperty('date_time'); + }); + + it('refuses a body past 64 KB', () => { + const options = Object.fromEntries(Array.from({ length: 2000 }, (_, i) => [`option_${i}`, 'x'.repeat(40)])); + expect(valhallaRouteRequestSchema.safeParse({ ...route, costing_options: { auto: options } }).success).toBe(false); + }); +}); + +describe('valhallaTraceRequestSchema', () => { + const trace = { + costing: 'pedestrian', + costing_options: { pedestrian: { max_hiking_difficulty: 6 } }, + shape_match: 'map_snap', + filters: { attributes: ['edge.way_id', 'edge.length'], action: 'include' }, + }; + + it('takes a line point by point or encoded, but not both and not neither', () => { + expect(valhallaTraceRequestSchema.safeParse({ ...trace, shape: line(2) }).success).toBe(true); + expect(valhallaTraceRequestSchema.safeParse({ ...trace, encoded_polyline: 'abc' }).success).toBe(true); + expect(valhallaTraceRequestSchema.safeParse({ ...trace, shape: line(2), encoded_polyline: 'abc' }).success).toBe( + false, + ); + expect(valhallaTraceRequestSchema.safeParse(trace).success).toBe(false); + }); + + it('carries a line of four thousand points once it is encoded', () => { + const shape = line(4000); + expect(valhallaTraceRequestSchema.safeParse({ ...trace, shape }).success).toBe(false); + const compact = compactValhallaRequest('trace_attributes', { ...trace, shape }); + expect(compact).not.toHaveProperty('shape'); + expect(valhallaTraceRequestSchema.safeParse(compact).success).toBe(true); + }); +}); + +describe('valhallaHeightRequestSchema', () => { + it('takes a piece of a line and refuses an empty one', () => { + expect(valhallaHeightRequestSchema.safeParse({ shape: line(500), range: true }).success).toBe(true); + expect(valhallaHeightRequestSchema.safeParse({ shape: [] }).success).toBe(false); + }); +}); + +describe('compactValhallaRequest', () => { + it('leaves a route and a height question as they are', () => { + expect(compactValhallaRequest('route', route)).toBe(route); + const heights = { shape: line(3), range: true }; + expect(compactValhallaRequest('height', heights)).toBe(heights); + }); +}); + +describe('encodePolyline6', () => { + it('writes the reference polyline, read at precision 6', () => { + const points = [ + { lat: 3.85, lon: -12.02 }, + { lat: 4.07, lon: -12.095 }, + { lat: 4.3252, lon: -12.6453 }, + ]; + expect(encodePolyline6(points)).toBe('_p~iF~ps|U_ulLnnqC_mqNvxq`@'); + expect(encodePolyline6([])).toBe(''); + }); +}); + +describe('resolveValhallaProvider', () => { + const unset = { provider: undefined, valhallaUrl: '', routingUrl: '', trekAvailable: true }; + + it('asks the TREK services by default, and FOSSGIS where they cannot be asked', () => { + expect(resolveValhallaProvider(unset)).toBe('trek'); + expect(resolveValhallaProvider({ ...unset, trekAvailable: false })).toBe('fossgis'); + }); + + it('reads an own Valhalla without a choice as custom, and an own OSRM alone as no Valhalla', () => { + expect(resolveValhallaProvider({ ...unset, valhallaUrl: 'https://v.example.org' })).toBe('custom'); + expect(resolveValhallaProvider({ ...unset, routingUrl: 'https://osrm.example.org' })).toBeNull(); + expect( + resolveValhallaProvider({ + ...unset, + routingUrl: 'https://osrm.example.org', + valhallaUrl: 'https://v.example.org', + }), + ).toBe('custom'); + }); + + it('keeps the admin choice, falling back to FOSSGIS from an unavailable TREK and to the defaults from custom without a URL', () => { + expect(resolveValhallaProvider({ ...unset, provider: 'fossgis', valhallaUrl: 'https://v.example.org' })).toBe( + 'fossgis', + ); + expect(resolveValhallaProvider({ ...unset, provider: 'trek', routingUrl: 'https://osrm.example.org' })).toBe( + 'trek', + ); + expect(resolveValhallaProvider({ ...unset, provider: 'trek', trekAvailable: false })).toBe('fossgis'); + expect(resolveValhallaProvider({ ...unset, provider: 'custom' })).toBe('trek'); + expect( + resolveValhallaProvider({ ...unset, provider: 'custom', routingUrl: 'https://osrm.example.org' }), + ).toBeNull(); + expect(resolveValhallaProvider({ ...unset, provider: 'nonsense', valhallaUrl: ' ' })).toBe('trek'); + }); +}); diff --git a/shared/src/routing-relay/routing-relay.schema.ts b/shared/src/routing-relay/routing-relay.schema.ts new file mode 100644 index 000000000..7844db65c --- /dev/null +++ b/shared/src/routing-relay/routing-relay.schema.ts @@ -0,0 +1,101 @@ +import { z } from 'zod'; + +/** + * POST /api/routing/valhalla/:action: the TREK services' Valhalla, asked + * through this server so the installation key never reaches a browser. The + * bodies are Valhalla's own, narrowed to what TREK asks: the planner in the + * browser and the road trip router on the server send exactly these. + */ + +/** Which Valhalla an instance asks: the public FOSSGIS one, the TREK services' one, or an own one. */ +export const valhallaProviderSchema = z.enum(['fossgis', 'trek', 'custom']); +export type ValhallaProvider = z.infer; + +export const valhallaRelayActionSchema = z.enum(['route', 'trace_attributes', 'height']); +export type ValhallaRelayAction = z.infer; + +/** The largest body the relay takes, in bytes of its JSON. */ +export const VALHALLA_RELAY_MAX_BODY_BYTES = 64 * 1024; +/** Locations one route may carry: the TREK Valhalla allows twenty for every costing TREK asks. */ +export const VALHALLA_RELAY_MAX_LOCATIONS = 20; +/** Points of a line a description may carry, as many as the planner thins a line to. */ +export const VALHALLA_RELAY_MAX_TRACE_POINTS = 4000; +/** Points one height question may carry: the planner asks 500 at a time. */ +export const VALHALLA_RELAY_MAX_HEIGHT_POINTS = 1000; +/** Alternate ways one route may ask for besides its own. */ +export const VALHALLA_RELAY_MAX_ALTERNATES = 5; + +const point = z.object({ + lat: z.number().min(-90).max(90), + lon: z.number().min(-180).max(180), +}); + +const costingSchema = z.enum(['auto', 'pedestrian', 'bicycle']); + +const optionName = z.string().min(1).max(64); +/** Per costing, its weightings and switches by name: a number, a word or a flag. */ +const costingOptionsSchema = z.record( + optionName, + z.record(optionName, z.union([z.number(), z.string().max(64), z.boolean()])), +); + +/** The UTF-8 length of the body's JSON: every escape encodeURIComponent writes stands for one byte. */ +function relayBytes(body: unknown): number { + return encodeURIComponent(JSON.stringify(body)).replace(/%[\dA-F]{2}/g, '_').length; +} + +const withinRelayBytes = { + check: (body: unknown) => relayBytes(body) <= VALHALLA_RELAY_MAX_BODY_BYTES, + message: `The request is larger than ${VALHALLA_RELAY_MAX_BODY_BYTES / 1024} KB`, +}; + +const locationSchema = point.extend({ + radius: z.number().int().min(0).max(1000).optional(), + search_filter: z.object({ exclude_ferry: z.boolean().optional() }).optional(), +}); + +export const valhallaRouteRequestSchema = z + .object({ + locations: z.array(locationSchema).min(2).max(VALHALLA_RELAY_MAX_LOCATIONS), + costing: costingSchema, + costing_options: costingOptionsSchema.optional(), + directions_options: z.object({ units: z.enum(['kilometers', 'miles']).optional() }).optional(), + alternates: z.number().int().min(0).max(VALHALLA_RELAY_MAX_ALTERNATES).optional(), + }) + .refine(withinRelayBytes.check, withinRelayBytes.message); +export type ValhallaRouteRequest = z.infer; + +/** A line described either point by point or as Valhalla's polyline of precision 6, never both. */ +export const valhallaTraceRequestSchema = z + .object({ + shape: z.array(point).min(2).max(VALHALLA_RELAY_MAX_TRACE_POINTS).optional(), + encoded_polyline: z.string().min(1).max(VALHALLA_RELAY_MAX_BODY_BYTES).optional(), + costing: costingSchema, + costing_options: costingOptionsSchema.optional(), + shape_match: z.enum(['map_snap', 'walk_or_snap', 'edge_walk']).optional(), + filters: z + .object({ + attributes: z.array(z.string().min(1).max(64)).max(40), + action: z.enum(['include', 'exclude']), + }) + .optional(), + }) + .refine((body) => (body.shape === undefined) !== (body.encoded_polyline === undefined), { + message: 'Send the line as shape or as encoded_polyline', + }) + .refine(withinRelayBytes.check, withinRelayBytes.message); +export type ValhallaTraceRequest = z.infer; + +export const valhallaHeightRequestSchema = z + .object({ + shape: z.array(point).min(1).max(VALHALLA_RELAY_MAX_HEIGHT_POINTS), + range: z.boolean().optional(), + }) + .refine(withinRelayBytes.check, withinRelayBytes.message); +export type ValhallaHeightRequest = z.infer; + +export const VALHALLA_RELAY_REQUEST_SCHEMAS = { + route: valhallaRouteRequestSchema, + trace_attributes: valhallaTraceRequestSchema, + height: valhallaHeightRequestSchema, +} as const satisfies Record; diff --git a/shared/src/routing-relay/valhalla-provider.ts b/shared/src/routing-relay/valhalla-provider.ts new file mode 100644 index 000000000..bdf599b74 --- /dev/null +++ b/shared/src/routing-relay/valhalla-provider.ts @@ -0,0 +1,69 @@ +import { valhallaProviderSchema, type ValhallaProvider, type ValhallaRelayAction } from './routing-relay.schema'; + +/** What decides which Valhalla an instance asks, as its settings hold it. */ +export interface ValhallaChoice { + /** `routing_valhalla_provider`; anything but one of its three values reads as not chosen. */ + provider: unknown; + /** `valhalla_base_url`, an own Valhalla. */ + valhallaUrl: unknown; + /** `routing_base_url`, an own OSRM. */ + routingUrl: unknown; + /** Whether the TREK services' Valhalla can be asked from here: the services are on and hold a key. */ + trekAvailable: boolean; +} + +function filled(value: unknown): boolean { + return typeof value === 'string' && value.trim() !== ''; +} + +/** + * The Valhalla an instance asks, or null where it asks none. A choice the + * admin made stands; without one an own Valhalla is `custom`, an own OSRM + * alone means no Valhalla at all (an operator who chose their own router is + * not handed a third party they never asked for), and otherwise the TREK + * services answer where they can and FOSSGIS where they cannot. + */ +export function resolveValhallaProvider(choice: ValhallaChoice): ValhallaProvider | null { + const chosen = valhallaProviderSchema.safeParse(choice.provider); + if (chosen.success && chosen.data === 'fossgis') return 'fossgis'; + if (chosen.success && chosen.data === 'trek') return choice.trekAvailable ? 'trek' : 'fossgis'; + if (filled(choice.valhallaUrl)) return 'custom'; + if (filled(choice.routingUrl)) return null; + return choice.trekAvailable ? 'trek' : 'fossgis'; +} + +function encodeSigned(value: number): string { + let rest = value < 0 ? ~(value << 1) : value << 1; + let out = ''; + while (rest >= 0x20) { + out += String.fromCharCode((0x20 | (rest & 0x1f)) + 63); + rest >>= 5; + } + return out + String.fromCharCode(rest + 63); +} + +/** A line as Valhalla's encoded polyline of precision 6, the form its `encoded_polyline` takes. */ +export function encodePolyline6(points: ReadonlyArray<{ lat: number; lon: number }>): string { + let lat = 0; + let lon = 0; + let out = ''; + for (const point of points) { + const nextLat = Math.round(point.lat * 1e6); + const nextLon = Math.round(point.lon * 1e6); + out += encodeSigned(nextLat - lat) + encodeSigned(nextLon - lon); + lat = nextLat; + lon = nextLon; + } + return out; +} + +/** + * A question as the relay takes it. A description sends its line as a + * polyline instead of point by point: four thousand points written out run + * past the relay's 64 KB, encoded they are a fifth of that. + */ +export function compactValhallaRequest(action: ValhallaRelayAction, body: object): object { + if (action !== 'trace_attributes' || !('shape' in body) || !Array.isArray(body.shape)) return body; + const { shape, ...rest } = body as { shape: Array<{ lat: number; lon: number }> }; + return { ...rest, encoded_polyline: encodePolyline6(shape) }; +} diff --git a/wiki/Environment-Variables.md b/wiki/Environment-Variables.md index 87ca2f1bf..3a2c51b12 100644 --- a/wiki/Environment-Variables.md +++ b/wiki/Environment-Variables.md @@ -395,6 +395,7 @@ TREK's own place index, the [TREK Places API](TREK-Places-API), answers the sugg | `TREK_SERVICES_KEY` | A key issued to you for this installation. Wins over the stored key and turns self-registration off. A value that is not a key aborts startup. | none | | `TREK_SERVICES_HOSTS` | Comma-separated hosts that receive the installation key over https. | `places.liketrek.com,photon.liketrek.com,valhalla.liketrek.com` | | `TREK_PHOTON_URL` | The address search of the TREK services, a [Photon](https://github.com/komoot/photon) instance. Once the installation holds a key, the OpenStreetMap search and the reverse lookups ask it before Nominatim and fall back to Nominatim whenever it does not answer. It is never asked with `TREK_SERVICES=off`, without a key, or when `NOMINATIM_URL` is set. See [Address search](TREK-Places-API#address-search). | `https://photon.liketrek.com` | +| `TREK_VALHALLA_URL` | The Valhalla of the TREK services. Routes, elevation and the description of a line go there unless the admin picks another routing service under Admin, Default user settings; this server relays them with the installation key, so the browser never talks to it. A trailing slash is stripped, and a value that is not a full URL aborts startup. | `https://valhalla.liketrek.com` | On Helm these go under `env:` in `values.yaml`, except `TREK_SERVICES_KEY`, which goes under `secretEnv:`. The chart passes `TREK_PLACES_ENABLED` through whenever it is set at all, so an unquoted `false` or `--set env.TREK_PLACES_ENABLED=false` reaches the container as well.