feat(routing): let the admin pick FOSSGIS, the TREK services or an own Valhalla

routing_valhalla_provider (fossgis, trek or custom) sits beside the routing
URLs under Admin, Default user settings, admin only and locked on a managed
install. Without a choice an own Valhalla is custom, an own OSRM alone asks
no Valhalla, and otherwise the TREK services answer.

The planner asks them through the same-origin relay, so no connect-src
changes. A relay that answers 401 (a shared page without a sign-in), 403,
413, 429 or 5xx sends the question to FOSSGIS without a word and is left
alone for ten minutes. A long line to describe goes as a polyline.
This commit is contained in:
Maurice
2026-10-29 10:44:41 +01:00
committed by Maurice
parent 80183bc986
commit 091ebed8e4
45 changed files with 618 additions and 107 deletions
@@ -1,4 +1,5 @@
import { useId, useState } from 'react'
import type { ValhallaProvider } from '@trek/shared'
import { useTranslation } from '../../i18n/TranslationContext'
import { fs } from '../shared/DialogShell'
import { INPUT, LABEL } from '../shared/dialogParts'
@@ -6,6 +7,7 @@ import { INPUT, LABEL } from '../shared/dialogParts'
export interface RoutingDefaults {
routing_base_url?: string
valhalla_base_url?: string
routing_valhalla_provider?: ValhallaProvider
}
interface RoutingFieldsProps {
@@ -25,6 +27,14 @@ const ROUTERS = [
{ key: 'valhalla_base_url', label: 'settings.valhallaBase', hint: 'settings.valhallaBaseHint', placeholder: 'https://valhalla.example.org' },
] as const
// '' is no choice of the admin: the instance then decides as before the choice existed.
const PROVIDERS = [
{ value: '', label: 'settings.valhallaProviderOption.auto' },
{ value: 'trek', label: 'settings.valhallaProviderOption.trek' },
{ value: 'fossgis', label: 'settings.valhallaProviderOption.fossgis' },
{ value: 'custom', label: 'settings.valhallaProviderOption.custom' },
] as const
// The phone screen's look, unchanged: MAdminDefaultUserSettings passes its own hint class.
const PHONE = {
wrap: 'min-w-0 space-y-1.5',
@@ -43,6 +53,12 @@ const DESKTOP = {
input: INPUT,
}
function FieldHint({ id, text, hintClassName }: { id: string; text: string; hintClassName?: string }) {
return hintClassName !== undefined
? <p id={id} className={hintClassName}>{text}</p>
: <p id={id} className="m-0 mt-1 leading-normal text-content-faint" style={fs(11)}>{text}</p>
}
function RoutingUrlField({ router, defaults, onSave, onReset, hintClassName }: RoutingFieldsProps & { router: typeof ROUTERS[number] }) {
const { t } = useTranslation()
const id = useId()
@@ -81,14 +97,45 @@ function RoutingUrlField({ router, defaults, onSave, onReset, hintClassName }: R
aria-describedby={`${id}-hint`}
className={look.input}
/>
{phone
? <p id={`${id}-hint`} className={hintClassName}>{t(router.hint)}</p>
: <p id={`${id}-hint`} className="m-0 mt-1 leading-normal text-content-faint" style={fs(11)}>{t(router.hint)}</p>}
<FieldHint id={`${id}-hint`} text={t(router.hint)} hintClassName={hintClassName} />
</div>
)
}
/** Which Valhalla answers what OSRM cannot; picking "automatic" clears the choice. */
function RoutingProviderField({ defaults, onSave, onReset, hintClassName }: RoutingFieldsProps) {
const { t } = useTranslation()
const id = useId()
const [saving, setSaving] = useState(false)
const phone = hintClassName !== undefined
const look = phone ? PHONE : DESKTOP
const pick = async (value: string) => {
setSaving(true)
try {
if (value === '') await onReset('routing_valhalla_provider')
else await onSave({ routing_valhalla_provider: value as ValhallaProvider })
} finally { setSaving(false) }
}
return (
<div className={`${look.wrap} ${!phone && saving ? 'opacity-60' : ''}`} aria-busy={saving}>
<div className={look.head}>
<label htmlFor={id} className={look.label}>{t('settings.valhallaProvider')}</label>
</div>
<select id={id} value={defaults.routing_valhalla_provider ?? ''} disabled={saving}
onChange={e => void pick(e.target.value)} aria-describedby={`${id}-hint`} className={look.input}>
{PROVIDERS.map(option => <option key={option.value} value={option.value}>{t(option.label)}</option>)}
</select>
<FieldHint id={`${id}-hint`} text={t('settings.valhallaProviderHint')} hintClassName={hintClassName} />
</div>
)
}
export default function RoutingInstanceFields(props: RoutingFieldsProps) {
const phone = props.hintClassName !== undefined
return <div className={phone ? 'flex flex-col gap-3' : 'flex flex-col gap-4'}>{ROUTERS.map(router => <RoutingUrlField key={router.key} router={router} {...props} />)}</div>
return (
<div className={phone ? 'flex flex-col gap-3' : 'flex flex-col gap-4'}>
<RoutingProviderField {...props} />
{ROUTERS.map(router => <RoutingUrlField key={router.key} router={router} {...props} />)}
</div>
)
}
@@ -5,6 +5,8 @@ import { useSettingsStore } from '../../store/settingsStore'
import { valhallaBase, valhallaAvailable, valhallaTurn, resetValhallaTurns, valhallaRouteAvoiding, valhallaRun, valhallaRunOnFoot, valhallaAlternates, alternatesFrom, runFrom, legAvoids, valhallaTraceAttributes } from './valhallaRoute'
const FOSSGIS_VALHALLA = 'https://valhalla1.openstreetmap.de/route'
/** The relay to the TREK services' Valhalla, the base asked when nothing else is configured. */
const TREK_VALHALLA = '/api/routing/valhalla'
/**
* A real polyline6, encoded from three known points and verified by decoding it back.
@@ -36,7 +38,7 @@ const setSettings = (patch: Record<string, string>) =>
useSettingsStore.setState(st => ({ settings: { ...st.settings, ...patch } }))
afterEach(() => {
setSettings({ routing_base_url: '', valhalla_base_url: '' })
setSettings({ routing_base_url: '', valhalla_base_url: '', routing_valhalla_provider: '' })
resetValhallaTurns()
})
@@ -92,11 +94,20 @@ const HAMBURG = { lat: 53.5511, lng: 9.9937 }
const BERLIN = { lat: 52.52, lng: 13.405 }
describe('valhallaBase', () => {
it('VALHALLA-BASE-001: falls back to the public instance when nothing is configured', () => {
expect(valhallaBase()).toBe('https://valhalla1.openstreetmap.de')
it('VALHALLA-BASE-001: asks the TREK services through the relay when nothing is configured', () => {
expect(valhallaBase()).toBe(TREK_VALHALLA)
expect(valhallaAvailable()).toBe(true)
})
it('VALHALLA-BASE-005: keeps the admin choice of a routing service', () => {
setSettings({ routing_valhalla_provider: 'fossgis', valhalla_base_url: 'https://v.example.org' })
expect(valhallaBase()).toBe('https://valhalla1.openstreetmap.de')
setSettings({ routing_valhalla_provider: 'custom' })
expect(valhallaBase()).toBe('https://v.example.org')
setSettings({ routing_valhalla_provider: 'trek', valhalla_base_url: '', routing_base_url: 'https://osrm.example.org' })
expect(valhallaBase()).toBe(TREK_VALHALLA)
})
it('VALHALLA-BASE-002: uses the configured instance and drops its trailing slashes', () => {
setSettings({ valhalla_base_url: 'https://valhalla.example.org//' })
expect(valhallaBase()).toBe('https://valhalla.example.org')
@@ -705,3 +716,81 @@ describe('crossings by boat on a walk (CW-12)', () => {
expect(await valhallaRunOnFoot(points, undefined, { use_ferry: 0 }, { exclude_ferry: true })).toBeNull()
})
})
describe('through the TREK services (routing relay)', () => {
const RELAY = '/api/routing/valhalla/:action'
it('VALHALLA-RELAY-001: asks the relay first, and FOSSGIS is not asked while it answers', async () => {
const relayed: Array<{ action: string; body: Record<string, unknown> }> = []
let fossgis = 0
server.use(
http.post(RELAY, async ({ params, request }) => {
relayed.push({ action: String(params.action), body: await request.json() as Record<string, unknown> })
return HttpResponse.json(answer({ has_toll: false }))
}),
http.post(FOSSGIS_VALHALLA, () => { fossgis++; return HttpResponse.json(answer()) }),
)
const leg = await valhallaRouteAvoiding(HAMBURG, BERLIN, 'driving', 'toll')
expect(leg).not.toBeNull()
expect(leg!.distance).toBeCloseTo(295700, 0)
expect(relayed).toHaveLength(1)
expect(relayed[0].action).toBe('route')
expect(relayed[0].body).toMatchObject({ costing: 'auto', costing_options: { auto: { use_tolls: 0 } } })
expect(fossgis).toBe(0)
})
it('VALHALLA-RELAY-002: turns to FOSSGIS without a word where the relay cannot answer, and leaves it alone a while', async () => {
for (const status of [401, 429, 503]) {
resetValhallaTurns()
let relayCalls = 0
let fossgis = 0
server.use(
http.post(RELAY, () => { relayCalls++; return HttpResponse.json({ error: 'no' }, { status }) }),
http.post(FOSSGIS_VALHALLA, () => { fossgis++; return HttpResponse.json(answer()) }),
)
await expect(valhallaRouteAvoiding(HAMBURG, BERLIN, 'driving', 'toll')).resolves.not.toBeNull()
expect(valhallaBase()).toBe('https://valhalla1.openstreetmap.de')
vi.useFakeTimers({ toFake: ['Date'] })
vi.setSystemTime(Date.now() + 2000)
await valhallaRouteAvoiding(HAMBURG, BERLIN, 'driving', 'ferry')
vi.useRealTimers()
expect([status, relayCalls, fossgis]).toEqual([status, 1, 2])
}
})
it('VALHALLA-RELAY-003: asks the relay again once the rest is over', async () => {
let relayCalls = 0
server.use(
http.post(RELAY, () => { relayCalls++; return HttpResponse.json({ error: 'no' }, { status: 503 }) }),
http.post(FOSSGIS_VALHALLA, () => HttpResponse.json(answer())),
)
await valhallaRouteAvoiding(HAMBURG, BERLIN, 'driving', 'toll')
vi.useFakeTimers({ toFake: ['Date'] })
vi.setSystemTime(Date.now() + 11 * 60_000)
expect(valhallaBase()).toBe(TREK_VALHALLA)
vi.useRealTimers()
})
it("VALHALLA-RELAY-004: reads Valhalla's own refusal through the relay as no way, without asking FOSSGIS", async () => {
let fossgis = 0
server.use(
http.post(RELAY, () => HttpResponse.json({ error_code: 442, error: 'No path could be found for input' }, { status: 400 })),
http.post(FOSSGIS_VALHALLA, () => { fossgis++; return HttpResponse.json(answer()) }),
)
const points = [HAMBURG, BERLIN]
expect(await valhallaRunOnFoot(points, undefined, { use_ferry: 0 }, { exclude_ferry: true })).toEqual({ noPath: true })
expect(fossgis).toBe(0)
expect(valhallaBase()).toBe(TREK_VALHALLA)
})
it('VALHALLA-RELAY-005: describes a line through the relay as a polyline', async () => {
const bodies: Record<string, unknown>[] = []
server.use(http.post(RELAY, async ({ request }) => {
bodies.push(await request.json() as Record<string, unknown>)
return HttpResponse.json({ edges: [] })
}))
await expect(valhallaTraceAttributes(SHAPE_POINTS)).resolves.toEqual({ edges: [] })
expect(bodies[0]).not.toHaveProperty('shape')
expect(bodies[0]).toMatchObject({ encoded_polyline: expect.any(String), costing: 'bicycle', shape_match: 'map_snap' })
})
})
+91 -33
View File
@@ -1,3 +1,5 @@
import { resolveValhallaProvider, type ValhallaRelayAction } from '@trek/shared'
import { valhallaRelayRepo } from '../../repo/valhallaRelayRepo'
import { useSettingsStore } from '../../store/settingsStore'
import { decodePolyline } from './transitGeometry'
import { haversineKm } from '../../utils/geo'
@@ -38,6 +40,18 @@ import type { Waypoint, SnappedWaypoint, RouteAvoidClass } from '../../types'
/** The public instance, matching how the OSRM defaults are shipped rather than configured. */
const FOSSGIS_VALHALLA = 'https://valhalla1.openstreetmap.de'
/**
* The TREK services' Valhalla, reached through this server's relay: same origin, so no
* connect-src to add, and the installation key stays on the server.
*/
const TREK_VALHALLA = '/api/routing/valhalla'
/**
* How long this tab leaves the relay alone after it could not answer: signed out on a
* shared page, the allowance spent, the services down. FOSSGIS answers meanwhile.
*/
const RELAY_REST_MS = 10 * 60_000
/**
* How far Valhalla may look for a road under a point, in metres.
*
@@ -169,21 +183,33 @@ export interface ValhallaRun {
snapped: SnappedWaypoint[]
}
/** Until when this tab asks FOSSGIS instead of a relay that could not answer. */
let relayRestingUntil = 0
/**
* The instance's Valhalla, or null when it should not ask one.
*
* Blank falls back to the public instance, the same reading `routing_base_url` gets —
* The admin's choice (`routing_valhalla_provider`) stands. Without one, an own Valhalla
* is asked, and otherwise the TREK services through the relay, with FOSSGIS behind it —
* with one condition. An operator who filled in their OWN router chose deliberately
* against the public hosts, usually because their instance is not supposed to talk to
* third parties at all, and quietly adding a second public host they never asked for
* would undo that choice. They lose nothing: a self-hosted OSRM built through the MLD
* third parties at all, and quietly adding a second host they never asked for would
* undo that choice. They lose nothing: a self-hosted OSRM built through the MLD
* pipeline answers `exclude` on its own, which is exactly the fallback below.
*/
export function valhallaBase(): string | null {
const settings = useSettingsStore.getState().settings
const configured = settings.valhalla_base_url?.trim()
if (configured) return configured.replace(/\/+$/, '')
return settings.routing_base_url?.trim() ? null : FOSSGIS_VALHALLA
const own = settings.valhalla_base_url?.trim().replace(/\/+$/, '') ?? ''
const provider = resolveValhallaProvider({
provider: settings.routing_valhalla_provider,
valhallaUrl: own,
routingUrl: settings.routing_base_url,
// Whether the TREK services can answer is the relay's to say; until it said no, ask it.
trekAvailable: Date.now() >= relayRestingUntil,
})
if (provider === 'custom') return own
if (provider === 'trek') return TREK_VALHALLA
return provider === 'fossgis' ? FOSSGIS_VALHALLA : null
}
/** True when this engine can be asked at all, so callers can skip building a request. */
@@ -355,9 +381,57 @@ export async function valhallaTurn(base: string, signal?: AbortSignal): Promise<
lastPublicAskAt = Date.now()
}
/** Forget the last turn, for tests that start from a quiet host. */
/** Forget the last turn and a resting relay, for tests that start from a quiet host. */
export function resetValhallaTurns(): void {
lastPublicAskAt = 0
relayRestingUntil = 0
}
/**
* The relay's statuses that say it cannot answer for the TREK services right now: no
* session (a shared page), no key, a body it does not take, an allowance spent, a host
* that is down. A 400 is Valhalla's own refusal of the way and is read as such.
*/
function relayCannotAnswer(status: number): boolean {
return status === 401 || status === 403 || status === 413 || status === 429 || status >= 500
}
async function askRelay(action: ValhallaRelayAction, body: object, signal?: AbortSignal): Promise<Response | null> {
try {
const response = await valhallaRelayRepo.ask(action, body, signal)
if (!relayCannotAnswer(response.status)) return response
} catch (err) {
if (signal?.aborted) throw err
}
relayRestingUntil = Date.now() + RELAY_REST_MS
return null
}
/**
* One question to a Valhalla, in its turn where the host is the public one. The relay
* is asked first where it is the base; where it cannot answer, the same question goes
* to FOSSGIS without a word, so a route never fails because of it.
*/
export async function valhallaPost(
base: string,
action: ValhallaRelayAction,
body: object,
signal?: AbortSignal,
): Promise<Response> {
if (base === TREK_VALHALLA && Date.now() >= relayRestingUntil) {
const relayed = await askRelay(action, body, signal)
if (relayed) return relayed
}
const host = base === TREK_VALHALLA ? FOSSGIS_VALHALLA : base
await valhallaTurn(host, signal)
return fetch(`${host}/${action}`, {
method: 'POST',
// A browser cannot set User-Agent, so this is the whole of what FOSSGIS asks a
// client to identify itself with. It costs a preflight, which is answered.
headers: { 'Content-Type': 'application/json', 'X-Client-Id': 'trek' },
body: JSON.stringify(body),
signal,
})
}
/**
@@ -418,16 +492,7 @@ function routeBody(
/** The parsed answer to one POST, `NO_PATH` when the router found no way, or null for every other failure. */
async function postRoute(base: string, body: Record<string, unknown>, signal?: AbortSignal): Promise<unknown> {
try {
await valhallaTurn(base, signal)
if (signal?.aborted) return null
const response = await fetch(`${base}/route`, {
method: 'POST',
// A browser cannot set User-Agent, so this is the whole of what FOSSGIS asks a
// client to identify itself with. It costs a preflight, which is answered.
headers: { 'Content-Type': 'application/json', 'X-Client-Id': 'trek' },
body: JSON.stringify(body),
signal,
})
const response = await valhallaPost(base, 'route', body, signal)
if (!response.ok) {
// 404 and 405 mean this URL is not a Valhalla — an OSRM pointed at by mistake,
// or a proxy that swallowed the path. Every other status is about this request:
@@ -506,22 +571,15 @@ export async function valhallaTraceAttributes(
const shape = line.filter((_, index) => index % step === 0 || index === line.length - 1).map(([lat, lon]) => ({ lat, lon }))
const bounded = signal ? AbortSignal.any([signal, AbortSignal.timeout(TRACE_TIMEOUT_MS)]) : AbortSignal.timeout(TRACE_TIMEOUT_MS)
try {
await valhallaTurn(base, signal)
if (signal?.aborted) return null
const response = await fetch(`${base}/trace_attributes`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'X-Client-Id': 'trek' },
body: JSON.stringify({
shape,
...TRACE_COSTING[matching],
shape_match: 'map_snap',
filters: {
attributes: traceAttributesFor(matching),
action: 'include',
},
}),
signal: bounded,
})
const response = await valhallaPost(base, 'trace_attributes', {
shape,
...TRACE_COSTING[matching],
shape_match: 'map_snap',
filters: {
attributes: traceAttributesFor(matching),
action: 'include',
},
}, bounded)
if (!response.ok) return null
return await response.json()
} catch {
@@ -1,17 +1,17 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const { valhallaBase, valhallaRun, valhallaRunOnFoot, valhallaTurn } = vi.hoisted(() => ({
const { valhallaBase, valhallaPost, valhallaRun, valhallaRunOnFoot } = vi.hoisted(() => ({
valhallaBase: vi.fn(),
valhallaPost: vi.fn(),
valhallaRun: vi.fn(),
valhallaRunOnFoot: vi.fn(),
valhallaTurn: vi.fn(async () => {}),
}))
vi.mock('../../Map/valhallaRoute', () => ({
valhallaBase,
valhallaPost,
valhallaRun,
valhallaRunOnFoot,
valhallaTurn,
}))
import { enrichTourElevations, parseValhallaElevation, routeBikeTour, routeCityWalk, routeRun, routeWalkingTour, type TourRouteResult } from './tourRouting'
@@ -146,10 +146,10 @@ describe('routeWalkingTour', () => {
)
it('keeps valid route coordinates and explicit missing samples when height data is partial', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
valhallaPost.mockReset().mockResolvedValue({
ok: true,
json: async () => ({ range_height: [[0, 0], [1, null], [2, ' ']] }),
}))
})
const coordinates: [number, number][] = [[48, 11], [48.01, 11.01], [48.02, 11.02]]
await expect(enrichTourElevations(coordinates)).resolves.toEqual([
@@ -157,35 +157,36 @@ describe('routeWalkingTour', () => {
])
})
it('waits for its turn at the host before every height question', async () => {
const order: string[] = []
valhallaTurn.mockImplementation(async () => { order.push('turn') })
vi.stubGlobal('fetch', vi.fn(async (_url: string, init: { body: string }) => {
order.push('fetch')
const shape = (JSON.parse(init.body) as { shape: unknown[] }).shape
return { ok: true, json: async () => ({ range_height: shape.map((_, i) => [i, 100]) }) }
it('asks the heights of its host piece by piece, through the one door every Valhalla question takes', async () => {
valhallaPost.mockReset().mockImplementation(async (_base: string, _action: string, body: { shape: unknown[] }) => ({
ok: true,
json: async () => ({ range_height: body.shape.map((_, i) => [i, 100]) }),
}))
const coordinates = Array.from({ length: 600 }, (_, i) => [48 + i / 1000, 11] as [number, number])
const result = await enrichTourElevations(coordinates)
expect(order).toEqual(['turn', 'fetch', 'turn', 'fetch'])
expect(valhallaTurn).toHaveBeenCalledWith('https://valhalla.test', undefined)
expect(valhallaPost).toHaveBeenCalledTimes(2)
expect(valhallaPost.mock.calls.map(([base, action, body]) => [base, action, body.shape.length, body.range])).toEqual([
['https://valhalla.test', 'height', 500, true],
['https://valhalla.test', 'height', 101, true],
])
expect(result!.every(point => point.length === 3)).toBe(true)
})
it('asks nothing once the caller gave up while waiting for its turn', async () => {
it('gives up without heights once the caller gave up', async () => {
const controller = new AbortController()
valhallaTurn.mockImplementation(async () => { controller.abort() })
const fetchSpy = vi.fn()
vi.stubGlobal('fetch', fetchSpy)
valhallaPost.mockReset().mockImplementation(async () => {
controller.abort()
throw new DOMException('The operation was aborted.', 'AbortError')
})
await expect(enrichTourElevations([[48, 11], [48.01, 11.01]], controller.signal)).resolves.toBeNull()
expect(fetchSpy).not.toHaveBeenCalled()
expect(valhallaPost).toHaveBeenCalledTimes(1)
})
it('keeps the full route as 2D geometry when height enrichment is unavailable', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: false, json: async () => ({}) }))
valhallaPost.mockReset().mockResolvedValue({ ok: false, json: async () => ({}) })
const coordinates: [number, number][] = [[48, 11], [48.01, 11.01]]
await expect(enrichTourElevations(coordinates)).resolves.toEqual(coordinates)
@@ -14,9 +14,9 @@ import {
import type { Waypoint } from '../../../types'
import {
valhallaBase,
valhallaPost,
valhallaRun,
valhallaRunOnFoot,
valhallaTurn,
type CostingOptions,
type FerrySpan,
type SearchFilter,
@@ -416,19 +416,12 @@ export async function enrichTourElevations(
if (chunk.length === 1 && offset > 0) break
try {
// The route came from the same host a moment ago, and the public one allows a
// request a second: without the wait the first height question is refused and
// the tour cannot be saved for want of elevation.
await valhallaTurn(base, signal)
if (signal?.aborted) return null
const response = await fetch(`${base}/height`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'X-Client-Id': 'trek' },
body: JSON.stringify({
shape: chunk.map(([lat, lng]) => ({ lat, lon: lng })),
range: true,
}),
signal,
})
// request a second: valhallaPost waits that turn, or the first height question is
// refused and the tour cannot be saved for want of elevation.
const response = await valhallaPost(base, 'height', {
shape: chunk.map(([lat, lng]) => ({ lat, lon: lng })),
range: true,
}, signal)
if (!response.ok) break
const chunkElevations = parseElevations(await response.json() as HeightResponse, chunk.length)
if (!chunkElevations) break