Skip to content

armgit / TREK

Public Imported from GitHub
0

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

fix(maps): say which engine drew a day and keep Valhalla days found while the relay rests

Maurice7dc313c5679a
diff --git a/client/src/components/Map/RouteCalculator.test.ts b/client/src/components/Map/RouteCalculator.test.ts
index 6d40ada9b..12464f562 100644
--- a/client/src/components/Map/RouteCalculator.test.ts
+++ b/client/src/components/Map/RouteCalculator.test.ts
@@ -15,8 +15,8 @@ import {
calculateAlternatives,
avoidedClasses,
routeEngineFor,
- osrmLegSegment,
} from './RouteCalculator'
+import { legSegment } from './routeText'
// Every route now goes to the FOSSGIS per-profile hosts. The car-only project-osrm.org
// demo ignored the profile in the URL, so walking routes followed the road network.
@@ -1239,11 +1239,11 @@ describe('a trip that avoids something', () => {
})
})
-describe('osrmLegSegment', () => {
+describe('legSegment', () => {
const waypoints = [{ lat: 48, lng: 2 }, { lat: 50, lng: 4 }, { lat: 52, lng: 6 }]
it('spans waypoint i to i + 1 with the label at the midpoint', () => {
- const seg = osrmLegSegment({ distance: 1500, duration: 600 }, 1, waypoints)
+ const seg = legSegment({ distance: 1500, duration: 600 }, 1, waypoints)
expect(seg.from).toEqual([50, 4])
expect(seg.to).toEqual([52, 6])
expect(seg.mid).toEqual([51, 5])
@@ -1252,7 +1252,7 @@ describe('osrmLegSegment', () => {
})
it('formats driving as measured and walking at 5 km/h', () => {
- const seg = osrmLegSegment({ distance: 5000, duration: 600 }, 0, waypoints)
+ const seg = legSegment({ distance: 5000, duration: 600 }, 0, waypoints)
expect(seg.drivingText).toBe('10 min')
expect(seg.walkingText).toBe('1 h 0 min')
expect(seg.durationText).toBeUndefined()
@@ -1260,6 +1260,6 @@ describe('osrmLegSegment', () => {
it('writes short metric distances in metres', () => {
useSettingsStore.setState({ settings: { ...useSettingsStore.getState().settings, distance_unit: 'metric' } })
- expect(osrmLegSegment({ distance: 420.4, duration: 60 }, 0, waypoints).distanceText).toBe('420 m')
+ expect(legSegment({ distance: 420.4, duration: 60 }, 0, waypoints).distanceText).toBe('420 m')
})
})
diff --git a/client/src/components/Map/RouteCalculator.ts b/client/src/components/Map/RouteCalculator.ts
index d49222a52..2cd585eb3 100644
--- a/client/src/components/Map/RouteCalculator.ts
+++ b/client/src/components/Map/RouteCalculator.ts
@@ -1,11 +1,12 @@
import { useSettingsStore } from '../../store/settingsStore'
import { pluginsApi } from '../../api/client'
-import type { RouteResult, RouteSegment, RouteWithLegs, SnappedWaypoint, Waypoint, RouteAnchors } from '../../types'
+import type { RouteEngine, RouteResult, RouteSegment, RouteWithLegs, SnappedWaypoint, Waypoint, RouteAnchors } from '../../types'
import { haversineKm } from '../../utils/geo'
import { countRoute } from './routeUsageCounter'
import { cacheRoute, rememberRoute, routeInMemory, storedRoute } from './routeStore'
-import { formatDuration, formatRouteDistance, getDistanceUnit } from './routeText'
-import { valhallaAvailable, valhallaRoutesDays, type AvoidClass } from './valhallaRoute'
+import { formatDuration, formatRouteDistance, getDistanceUnit, legSegment } from './routeText'
+import type { RouteAlternative } from './routeTypes'
+import { valhallaAvailable, valhallaPlansDays, valhallaRoutesDays, type AvoidClass } from './valhallaRoute'
import { EXCLUDABLE_CLASSES, valhallaDayAlternatives, valhallaDayRoute, valhallaExcluding } from './valhallaDayRoute'
import { furthestFrom, sameRoad, type RouteUsageSurface } from '@trek/shared'
@@ -214,14 +215,6 @@ export function parsePluginProfile(profile: string): { pluginId: string; profile
return { pluginId: rest.slice(0, slash), profileId: rest.slice(slash + 1) }
}
-/**
- * Which engine priced a route: OSRM, Valhalla (which routes the days with the TREK
- * services or an own Valhalla, and otherwise weighs road classes away), or a route
- * provider plugin. Their figures are three different speed models, so a figure from one
- * read against a figure from another measures the models, not the roads.
- */
-export type RouteEngine = 'osrm' | 'valhalla' | 'plugin'
-
/** One of the three profiles both engines know, or null for a plugin's own. */
function builtInProfile(profile: RouteProfileKey): 'driving' | 'walking' | 'cycling' | null {
return profile === 'driving' || profile === 'walking' || profile === 'cycling' ? profile : null
@@ -242,14 +235,15 @@ export function avoidedClasses(profile: RouteProfileKey, avoid: readonly AvoidCl
}
/**
- * The engine `calculateRouteWithLegs` hands a request with this profile and avoidance to:
- * Valhalla for every day where it routes the days, and for a day that avoids something
- * wherever it can; OSRM for the rest.
+ * The engine a request with this profile and avoidance is planned with: Valhalla for every
+ * day where it routes the days, and for a day that avoids something wherever it can; OSRM
+ * for the rest. Planned, not promised: a day Valhalla cannot answer, or one asked while
+ * the relay rests, is drawn by OSRM, and the answer says so in its `engine`.
*/
export function routeEngineFor(profile: RouteProfileKey, avoid: readonly AvoidClass[]): RouteEngine {
if (parsePluginProfile(profile)) return 'plugin'
if (avoidedClasses(profile, avoid).length) return 'valhalla'
- return builtInProfile(profile) && valhallaRoutesDays() ? 'valhalla' : 'osrm'
+ return builtInProfile(profile) && valhallaPlansDays() ? 'valhalla' : 'osrm'
}
/** The profile Valhalla routes a request under, or null where `routeEngineFor` gives it to another engine. */
@@ -259,10 +253,12 @@ function valhallaProfile(profile: RouteProfileKey, avoid: readonly AvoidClass[])
/**
* Where a Valhalla answer is kept: beside the OSRM key, which keeps the shape it always
- * had, with the engine and the classes the day weighs away.
+ * had. A day that weighs classes away keeps the key it has had since only Valhalla could
+ * answer one, so the days a device already holds stay found; a day that avoids nothing
+ * names the engine instead.
*/
function valhallaKey(plainKey: string, avoiding: readonly AvoidClass[]): string {
- return `${plainKey}:valhalla${avoiding.length ? `:avoid=${avoiding.join(',')}` : ''}`
+ return avoiding.length ? `${plainKey}:avoid=${avoiding.join(',')}` : `${plainKey}:valhalla`
}
/**
@@ -272,7 +268,41 @@ function valhallaKey(plainKey: string, avoiding: readonly AvoidClass[]): string
* held on a road nobody weighed.
*/
function withFallbackNoted(plain: RouteWithLegs, avoiding: AvoidClass[]): RouteWithLegs {
- return avoiding.length ? { ...plain, avoidance: { asked: avoiding, achieved: [], fellBack: true } } : plain
+ const drawn = withEngine(plain, 'osrm')
+ return avoiding.length ? { ...drawn, avoidance: { asked: avoiding, achieved: [], fellBack: true } } : drawn
+}
+
+/**
+ * A kept route with the engine that drew it. A key holds one engine's answers only, so an
+ * entry kept before answers named their engine is that key's.
+ */
+function withEngine(route: RouteWithLegs, engine: RouteEngine): RouteWithLegs {
+ return route.engine ? route : { ...route, engine }
+}
+
+/**
+ * A day planned with Valhalla: its answer, kept under the Valhalla key, or where it gives
+ * none OSRM's for the whole day, kept under the plain key. One engine per day, never one
+ * leg from each. While the relay rests, a day that avoids nothing is not put to it at all.
+ */
+async function valhallaOrOsrmDay(
+ waypoints: Waypoint[],
+ { profile, avoiding, keys, signal }: {
+ profile: 'driving' | 'walking' | 'cycling'
+ avoiding: AvoidClass[]
+ keys: { valhalla: string; plain: string; coords: string }
+ signal?: AbortSignal
+ },
+): Promise<RouteWithLegs> {
+ const asking = avoiding.length > 0 || valhallaRoutesDays()
+ const routed = asking ? await valhallaDayRoute(waypoints, profile, avoiding, signal) : null
+ if (routed) {
+ cacheRoute(keys.valhalla, routed)
+ return routed
+ }
+ const plain = (await storedRoute(keys.plain)) ?? await osrmWithLegs(waypoints, keys.coords, profile, signal)
+ cacheRoute(keys.plain, plain)
+ return withFallbackNoted(plain, avoiding)
}
/** Fetches a full route via OSRM and returns coordinates, distance, and duration estimates for driving/walking. */
@@ -502,31 +532,11 @@ export async function calculateSegments(
if (data.code !== 'Ok' || !data.routes?.[0]) throw new Error('No route found')
const legs = data.routes[0].legs
- return legs.map((leg: OsrmLeg, i: number): RouteSegment => osrmLegSegment(leg, i, waypoints))
+ return legs.map((leg: OsrmLeg, i: number): RouteSegment => legSegment(leg, i, waypoints))
}
interface OsrmLeg { distance: number; duration: number }
-/**
- * The connector data for OSRM leg i, which runs from waypoint i to waypoint i + 1:
- * both ends, the midpoint the label sits on, and the walking time at 5 km/h next to
- * the driving time OSRM measured.
- */
-export function osrmLegSegment(leg: OsrmLeg, i: number, waypoints: Waypoint[]): RouteSegment {
- const from: [number, number] = [waypoints[i].lat, waypoints[i].lng]
- const to: [number, number] = [waypoints[i + 1].lat, waypoints[i + 1].lng]
- const mid: [number, number] = [(from[0] + to[0]) / 2, (from[1] + to[1]) / 2]
- const walkingDuration = leg.distance / (5000 / 3600)
- return {
- mid, from, to,
- distance: leg.distance,
- duration: leg.duration,
- walkingText: formatDuration(walkingDuration),
- drivingText: formatDuration(leg.duration),
- distanceText: formatRouteDistance(leg.distance),
- }
-}
-
/**
* One OSRM call per waypoint-run that returns BOTH the real road geometry (for the
* map) and per-leg distance/duration (for the sidebar connectors). Results are cached
@@ -575,24 +585,18 @@ export async function calculateRouteWithLegs(
// weighed road until the next reload, however soon Valhalla came back.
const pluginScope = profile.startsWith('plugin:') ? `:${tripId ?? ''}:${dayId ?? ''}` : ''
const plainKey = `${profile}:${getDistanceUnit()}:${coords}${pluginScope}`
+ // Which engine the day is planned with does not follow the relay's rest, so a day kept
+ // from Valhalla is still found while the relay rests, offline above all.
const cacheKey = valhallaDay ? valhallaKey(plainKey, avoiding) : plainKey
// A plugin route stays in memory: its answer depends on the trip and the day,
// and may carry live data such as charging stops. The rest is kept on the device
// too, so a trip that shows its whole route opens drawn (#2794).
const cached = pluginScope ? routeInMemory(cacheKey) : await storedRoute(cacheKey)
- if (cached) return cached
+ if (cached) return withEngine(cached, routeEngineFor(profile, avoid))
if (valhallaDay) {
- const routed = await valhallaDayRoute(waypoints, valhallaDay, avoiding, signal)
- if (routed) {
- cacheRoute(cacheKey, routed)
- return routed
- }
- // Null is a Valhalla that could not answer at all, and the whole day goes to OSRM:
- // one engine per day, never one leg from each.
- const plain = (await storedRoute(plainKey)) ?? await osrmWithLegs(waypoints, coords, profile, signal)
- cacheRoute(plainKey, plain)
- return withFallbackNoted(plain, avoiding)
+ const keys = { valhalla: cacheKey, plain: plainKey, coords }
+ return valhallaOrOsrmDay(waypoints, { profile: valhallaDay, avoiding, keys, signal })
}
// Plugin profile (`plugin:<id>/<profile>`): the server invokes that routeProvider
@@ -607,27 +611,18 @@ export async function calculateRouteWithLegs(
waypoints: waypoints.map((p) => ({ lat: p.lat, lng: p.lng })),
}, { signal })
if (!route) throw new Error('No route found')
- const legs: RouteSegment[] = route.legs.map((leg, i): RouteSegment => {
- const from: [number, number] = [waypoints[i].lat, waypoints[i].lng]
- const to: [number, number] = [waypoints[i + 1].lat, waypoints[i + 1].lng]
- const mid: [number, number] = [(from[0] + to[0]) / 2, (from[1] + to[1]) / 2]
- return {
- mid, from, to,
- distance: leg.distance,
- duration: leg.duration,
- walkingText: formatDuration(leg.distance / (5000 / 3600)),
- drivingText: formatDuration(leg.duration),
- distanceText: formatRouteDistance(leg.distance),
- durationText: formatDuration(leg.duration),
- ...(leg.note ? { noteText: leg.note } : {}),
- }
- })
+ const legs = route.legs.map((leg, i): RouteSegment => ({
+ ...legSegment(leg, i, waypoints),
+ durationText: formatDuration(leg.duration),
+ ...(leg.note ? { noteText: leg.note } : {}),
+ }))
const result: RouteWithLegs = {
coordinates: route.coordinates,
distance: route.distance,
duration: route.duration,
legs,
...(route.viaPoints.length ? { vias: route.viaPoints } : {}),
+ engine: 'plugin',
}
rememberRoute(cacheKey, result)
return result
@@ -663,13 +658,13 @@ async function osrmWithLegs(
// The day plan's connectors also show the leg's own duration line.
const legs: RouteSegment[] = (route.legs || []).map(
(leg: OsrmLeg, i: number): RouteSegment => ({
- ...osrmLegSegment(leg, i, waypoints),
+ ...legSegment(leg, i, waypoints),
durationText: formatDuration(leg.duration),
})
)
const snapped = readSnapped(data, waypoints)
- return { coordinates, distance: route.distance, duration: route.duration, legs, ...(snapped ? { snapped } : {}) }
+ return { coordinates, distance: route.distance, duration: route.duration, legs, ...(snapped ? { snapped } : {}), engine: 'osrm' }
}
/**
@@ -703,35 +698,6 @@ function readSnapped(data: unknown, waypoints: Waypoint[]): SnappedWaypoint[] |
return out
}
-/** One way of driving a leg, as a router offers it. */
-export interface RouteAlternative {
- coordinates: [number, number][]
- distance: number
- duration: number
- /** Where this route differs most from the first one — the point that would pin it. */
- divergence: { lat: number; lng: number } | null
- /** Set when this way exists because a road class was left out of it. */
- avoids?: AvoidClass
- /**
- * Which engine priced this route. Absent means OSRM, which answers every route of a
- * trip that avoids nothing where Valhalla does not route the days, except the
- * avoidance offer.
- *
- * It exists because the engines do not agree on speed: measured over twelve European
- * legs the per-leg drive times run from 14.7 % under OSRM's to 13.2 % over, and the
- * sign depends on the region: Valhalla is faster on Spanish autovía and slower through
- * a city. So a figure from one of them subtracted from a figure from the other is not a
- * difference in driving time, it is the gap between two speed models, and the reader
- * has no way of telling the two apart.
- */
- engine?: RouteEngine
- /** Whether the way crosses by ferry, where the engine that drew it says so. */
- hasFerry?: boolean
-}
-
-/** What two routes are compared by: their line, and their figures where there is none. */
-export type RoadLine = Pick<RouteAlternative, 'coordinates' | 'distance' | 'duration'>
-
/**
* Hosts that have already answered "I do not do exclude", by base URL.
*
@@ -835,9 +801,15 @@ export async function calculateAlternatives(
from: Waypoint,
to: Waypoint,
profile: 'driving' | 'walking' | 'cycling' = 'driving',
- { signal, limit = 3, avoid = [] }: { signal?: AbortSignal; limit?: number; avoid?: readonly AvoidClass[] } = {},
+ { signal, limit = 3, avoid = [], engine = routeEngineFor(profile, avoid) }: {
+ signal?: AbortSignal
+ limit?: number
+ avoid?: readonly AvoidClass[]
+ /** The engine that drew the leg, where it is known; the planned one otherwise. */
+ engine?: RouteEngine
+ } = {},
): Promise<RouteAlternative[]> {
- const routes = routeEngineFor(profile, avoid) === 'valhalla'
+ const routes = engine === 'valhalla'
? await alternativesFromValhalla(from, to, profile, avoidedClasses(profile, avoid), { limit, signal })
: await alternativesFromOsrm(from, to, profile, limit, signal)
if (!routes.length) return routes
@@ -864,7 +836,8 @@ async function alternativesFromValhalla(
avoiding: AvoidClass[],
{ limit, signal }: { limit: number; signal?: AbortSignal },
): Promise<RouteAlternative[]> {
- const offered = await valhallaDayAlternatives(from, to, profile, avoiding, { limit, signal })
+ const asking = avoiding.length > 0 || valhallaRoutesDays()
+ const offered = asking ? await valhallaDayAlternatives(from, to, profile, avoiding, { limit, signal }) : null
if (offered) return offered
if (avoiding.length) throw new Error('No route found')
return alternativesFromOsrm(from, to, profile, limit, signal)
diff --git a/client/src/components/Map/routeText.ts b/client/src/components/Map/routeText.ts
index 5d79ca8c4..ee06e8b70 100644
--- a/client/src/components/Map/routeText.ts
+++ b/client/src/components/Map/routeText.ts
@@ -1,5 +1,5 @@
import { useSettingsStore } from '../../store/settingsStore';
-import type { DistanceUnit } from '../../types';
+import type { DistanceUnit, RouteSegment, Waypoint } from '../../types';
import { formatDistance } from '../../utils/units';
/** The unit a route's texts are written in, which is why it is part of the route cache key. */
@@ -25,3 +25,28 @@ export function formatDuration(seconds: number): string {
}
return `${m} min`;
}
+
+/**
+ * The connector data for leg i of a routed chain, which runs from waypoint i to waypoint
+ * i + 1: both ends, the midpoint the label sits on, and the walking time at 5 km/h next to
+ * the time the engine measured. The same for every engine, so a day reads alike whichever
+ * of them drew it.
+ */
+export function legSegment(
+ leg: { distance: number; duration: number },
+ i: number,
+ waypoints: Waypoint[]
+): RouteSegment {
+ const from: [number, number] = [waypoints[i].lat, waypoints[i].lng];
+ const to: [number, number] = [waypoints[i + 1].lat, waypoints[i + 1].lng];
+ return {
+ mid: [(from[0] + to[0]) / 2, (from[1] + to[1]) / 2],
+ from,
+ to,
+ distance: leg.distance,
+ duration: leg.duration,
+ walkingText: formatDuration(leg.distance / (5000 / 3600)),
+ drivingText: formatDuration(leg.duration),
+ distanceText: formatRouteDistance(leg.distance),
+ };
+}
diff --git a/client/src/components/Map/routeTypes.ts b/client/src/components/Map/routeTypes.ts
new file mode 100644
index 000000000..77805b907
--- /dev/null
+++ b/client/src/components/Map/routeTypes.ts
@@ -0,0 +1,30 @@
+import type { RouteAvoidClass, RouteEngine } from '../../types';
+
+/** One way of driving a leg, as a router offers it. */
+export interface RouteAlternative {
+ coordinates: [number, number][];
+ distance: number;
+ duration: number;
+ /** Where this route differs most from the first one — the point that would pin it. */
+ divergence: { lat: number; lng: number } | null;
+ /** Set when this way exists because a road class was left out of it. */
+ avoids?: RouteAvoidClass;
+ /**
+ * Which engine priced this route. Absent means OSRM, which answers every route of a
+ * trip that avoids nothing where Valhalla does not route the days, except the
+ * avoidance offer.
+ *
+ * It exists because the engines do not agree on speed: measured over twelve European
+ * legs the per-leg drive times run from 14.7 % under OSRM's to 13.2 % over, and the
+ * sign depends on the region: Valhalla is faster on Spanish autovía and slower through
+ * a city. So a figure from one of them subtracted from a figure from the other is not a
+ * difference in driving time, it is the gap between two speed models, and the reader
+ * has no way of telling the two apart.
+ */
+ engine?: RouteEngine;
+ /** Whether the way crosses by ferry, where the engine that drew it says so. */
+ hasFerry?: boolean;
+}
+
+/** What two routes are compared by: their line, and their figures where there is none. */
+export type RoadLine = Pick<RouteAlternative, 'coordinates' | 'distance' | 'duration'>;
diff --git a/client/src/components/Map/valhallaDayRoute.test.ts b/client/src/components/Map/valhallaDayRoute.test.ts
index 8efd0ace1..c83bdbf5e 100644
--- a/client/src/components/Map/valhallaDayRoute.test.ts
+++ b/client/src/components/Map/valhallaDayRoute.test.ts
@@ -117,12 +117,12 @@ describe('which engine routes a day', () => {
expect(routeEngineFor('plugin:ev/fast', [])).toBe('plugin');
});
- it('VDAY-ENGINE-004: while the relay rests after a failure, the days go back to OSRM', async () => {
- listen(() => HttpResponse.json({ error: 'resting' }, { status: 503 }));
- await calculateRouteWithLegs(freshDay(2), { profile: 'driving' });
- expect(routeEngineFor('driving', [])).toBe('osrm');
- resetValhallaTurns();
+ it('VDAY-ENGINE-004: while the relay rests the days stay planned with Valhalla, and OSRM draws them and says so', async () => {
+ const traffic = listen(() => HttpResponse.json({ error: 'resting' }, { status: 503 }));
+ expect((await calculateRouteWithLegs(freshDay(2), { profile: 'driving' })).engine).toBe('osrm');
+ expect((await calculateRouteWithLegs(freshDay(2), { profile: 'driving' })).engine).toBe('osrm');
expect(routeEngineFor('driving', [])).toBe('valhalla');
+ expect([traffic.relay.length, traffic.osrm.length]).toEqual([1, 2]);
});
});
@@ -139,6 +139,7 @@ describe('a day where Valhalla routes the days', () => {
expect([route.distance, route.duration, route.legs.length, route.snapped?.length]).toEqual([4000, 600, 2, 3]);
expect(route.legs[0]).toMatchObject({ distanceText: '2 km', durationText: '5 min' });
expect(route).not.toHaveProperty('avoidance');
+ expect(route.engine).toBe('valhalla');
});
it('VDAY-002: the relay takes twenty locations a request, an own Valhalla too', async () => {
@@ -176,6 +177,7 @@ describe('a day where Valhalla routes the days', () => {
expect([traffic.relay.length, traffic.fossgis.length, traffic.osrm.length]).toEqual([1, 0, 1]);
expect(traffic.osrm[0]).toContain(OSRM.walking);
expect(route).not.toHaveProperty('avoidance');
+ expect(route.engine).toBe('osrm');
}
});
@@ -190,6 +192,21 @@ describe('a day where Valhalla routes the days', () => {
expect([traffic.fossgis.length, traffic.osrm.length]).toEqual([0, 1]);
});
+ it('VDAY-004b: an own Valhalla that does not answer in time hands the day to OSRM without a second wait', async () => {
+ choose({ valhalla_base_url: OWN_VALHALLA });
+ const timeout = AbortSignal.timeout.bind(AbortSignal);
+ const deadlines = vi
+ .spyOn(AbortSignal, 'timeout')
+ .mockImplementation((ms) =>
+ ms === 12_000 ? AbortSignal.abort(new DOMException('signal timed out', 'TimeoutError')) : timeout(ms)
+ );
+ const traffic = listen();
+ const route = await calculateRouteWithLegs(freshDay(3), { profile: 'cycling' });
+ expect([route.distance, route.engine]).toEqual([2000, 'osrm']);
+ expect(deadlines.mock.calls.filter(([ms]) => ms === 12_000)).toHaveLength(1);
+ expect([traffic.relay.length, traffic.fossgis.length, traffic.osrm.length]).toEqual([0, 0, 1]);
+ });
+
it('VDAY-005: an own Valhalla that cannot answer leaves the day to OSRM', async () => {
choose({ valhalla_base_url: OWN_VALHALLA });
const traffic = listen();
@@ -245,6 +262,31 @@ describe('the route cache keeps the engine apart', () => {
});
});
+describe('the route cache while the relay rests', () => {
+ it('VDAY-CACHE-003: a day kept from Valhalla is still found while the relay rests, as it is offline', async () => {
+ const points = freshDay(3);
+ let up = true;
+ const traffic = listen((body) => (up ? answered(body) : HttpResponse.json({ error: 'down' }, { status: 503 })));
+ expect((await calculateRouteWithLegs(points, { profile: 'driving' })).distance).toBe(4000);
+
+ up = false;
+ await calculateRouteWithLegs(freshDay(2), { profile: 'driving' });
+ const kept = await calculateRouteWithLegs(points, { profile: 'driving' });
+ expect([kept.distance, kept.engine]).toEqual([4000, 'valhalla']);
+ expect([traffic.relay.length, traffic.osrm.length]).toEqual([2, 1]);
+ });
+
+ it('VDAY-CACHE-004: a day that avoids something keeps its key, whichever Valhalla answered it', async () => {
+ const points = freshDay(3);
+ const traffic = listen();
+ await calculateRouteWithLegs(points, { profile: 'driving', avoid: ['toll'] });
+ choose({ routing_valhalla_provider: 'fossgis' });
+ const kept = await calculateRouteWithLegs(points, { profile: 'driving', avoid: ['toll'] });
+ expect(kept.engine).toBe('valhalla');
+ expect([traffic.relay.length, traffic.fossgis.length, traffic.osrm.length]).toEqual([1, 0, 0]);
+ });
+});
+
describe('other ways for a leg Valhalla routes', () => {
const from = { lat: 47, lng: 9 };
const to = { lat: 47, lng: 9.2 };
diff --git a/client/src/components/Map/valhallaDayRoute.ts b/client/src/components/Map/valhallaDayRoute.ts
index 628f1c929..9adcdc1cb 100644
--- a/client/src/components/Map/valhallaDayRoute.ts
+++ b/client/src/components/Map/valhallaDayRoute.ts
@@ -3,8 +3,8 @@ import { sameRoad } from '@trek/shared';
import { useSettingsStore } from '../../store/settingsStore';
import type { RouteSegment, RouteWithLegs, Waypoint } from '../../types';
import { haversineKm } from '../../utils/geo';
-import type { RouteAlternative } from './RouteCalculator';
-import { formatDuration, formatRouteDistance } from './routeText';
+import { formatDuration, legSegment } from './routeText';
+import type { RouteAlternative } from './routeTypes';
import { countRoute } from './routeUsageCounter';
import {
legAvoids,
@@ -73,21 +73,10 @@ export async function valhallaDayRoute(
if (!signal?.aborted) countRoute({ ...sample, failed: !run });
if (!run) return null;
- const legs: RouteSegment[] = run.legs.map((leg, i): RouteSegment => {
- const from: [number, number] = [waypoints[i].lat, waypoints[i].lng];
- const to: [number, number] = [waypoints[i + 1].lat, waypoints[i + 1].lng];
- return {
- mid: [(from[0] + to[0]) / 2, (from[1] + to[1]) / 2],
- from,
- to,
- distance: leg.distance,
- duration: leg.duration,
- walkingText: formatDuration(leg.distance / (5000 / 3600)),
- drivingText: formatDuration(leg.duration),
- distanceText: formatRouteDistance(leg.distance),
- durationText: formatDuration(leg.duration),
- };
- });
+ const legs = run.legs.map((leg, i): RouteSegment => ({
+ ...legSegment(leg, i, waypoints),
+ durationText: formatDuration(leg.duration),
+ }));
return {
coordinates: run.total.coordinates,
@@ -99,6 +88,7 @@ export async function valhallaDayRoute(
? { avoidance: { asked: avoid, achieved: avoid.filter((cls) => legAvoids(run.total, cls)) } }
: {}),
hasFerry: run.total.hasFerry,
+ engine: 'valhalla',
};
}
diff --git a/client/src/components/Map/valhallaRoute.ts b/client/src/components/Map/valhallaRoute.ts
index a11e2aad9..7ceec5e37 100644
--- a/client/src/components/Map/valhallaRoute.ts
+++ b/client/src/components/Map/valhallaRoute.ts
@@ -69,11 +69,12 @@ const RELAY_REST_MS = 10 * 60_000
const RELAY_MAX_WAIT_MS = 60 * 60_000
/**
- * How long a route or a height question may take through the relay. The server gives the
- * TREK Valhalla ten seconds; this leaves room for its 502 to arrive first, and where the
- * relay itself hangs, FOSSGIS answers soon after.
+ * How long a route or a height question may take through the relay or at an own Valhalla.
+ * The server gives the TREK Valhalla ten seconds; this leaves room for its 502 to arrive
+ * first. Where the relay itself hangs, FOSSGIS answers soon after; where an own Valhalla
+ * does, OSRM routes the day, rather than the day waiting as long as the browser would.
*/
-const RELAY_TIMEOUT_MS = 12_000
+const ASK_TIMEOUT_MS = 12_000
/**
* How far Valhalla may look for a road under a point, in metres.
@@ -183,6 +184,14 @@ export interface ValhallaNoPath {
const NO_PATH_CODES = new Set([170, 171, 442])
const NO_PATH: ValhallaNoPath = { noPath: true }
+/** A host that let a question run out its deadline, apart from one that refused it. */
+const TOO_SLOW = { tooSlow: true } as const
+type TooSlow = typeof TOO_SLOW
+
+function tooSlow(answer: unknown): answer is TooSlow {
+ return answer === TOO_SLOW
+}
+
/** A routed chain: one leg per pair of consecutive waypoints, plus the whole of it. */
export interface ValhallaRun {
legs: ValhallaLeg[]
@@ -221,28 +230,40 @@ export function valhallaBase(): string | null {
return provider === 'fossgis' ? FOSSGIS_VALHALLA : null
}
-function currentProvider(): { provider: ValhallaProvider | null; own: string } {
+/**
+ * The provider as the settings choose it. Whether the TREK services can answer is the
+ * relay's to say; until it said no, it is asked, and `ignoreRest` reads past its no.
+ */
+function currentProvider(ignoreRest = false): { provider: ValhallaProvider | null; own: string } {
const settings = useSettingsStore.getState().settings
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,
+ trekAvailable: ignoreRest || Date.now() >= relayRestingUntil,
})
return { provider, own }
}
/**
- * Whether the days are routed here rather than by OSRM: with the TREK services or an own
- * Valhalla. While the relay rests after a failure this reads as FOSSGIS, so the days go
- * back to OSRM until it is asked again.
+ * Whether the days are asked here right now rather than of OSRM: with the TREK services
+ * or an own Valhalla. While the relay rests after a failure this reads as FOSSGIS, so the
+ * days go to OSRM until it is asked again.
*/
export function valhallaRoutesDays(): boolean {
return valhallaRoutesEveryDay(currentProvider().provider)
}
+/**
+ * Whether the days are planned with this engine, resting relay or not. The route cache is
+ * keyed by it: a day this device already holds from Valhalla stays found while the relay
+ * rests, offline above all, where every question to it fails and it rests at once.
+ */
+export function valhallaPlansDays(): boolean {
+ return valhallaRoutesEveryDay(currentProvider(true).provider)
+}
+
/** True when this engine can be asked at all, so callers can skip building a request. */
export function valhallaAvailable(): boolean {
return valhallaBase() !== null
@@ -484,16 +505,17 @@ function relayWait(response: Response): number | null {
return Number.isNaN(at) ? null : Math.max(0, at - Date.now())
}
+/** A route or a height question held to `ASK_TIMEOUT_MS`; a description brings its own deadline. */
+function withDeadline(action: ValhallaRelayAction, signal?: AbortSignal): AbortSignal | undefined {
+ if (action === 'trace_attributes') return signal
+ const deadline = AbortSignal.timeout(ASK_TIMEOUT_MS)
+ return signal ? AbortSignal.any([signal, deadline]) : deadline
+}
+
async function askRelay(action: ValhallaRelayAction, body: object, signal?: AbortSignal): Promise<Response | null> {
- let bounded = signal
- // A description brings its own deadline; a route or a height gets the relay's.
- if (action !== 'trace_attributes') {
- const deadline = AbortSignal.timeout(RELAY_TIMEOUT_MS)
- bounded = signal ? AbortSignal.any([signal, deadline]) : deadline
- }
let wait = RELAY_REST_MS
try {
- const response = await valhallaRelayRepo.ask(action, body, bounded)
+ const response = await valhallaRelayRepo.ask(action, body, withDeadline(action, signal))
if (!(await relayCannotAnswer(response))) return response
wait = Math.min(relayWait(response) ?? RELAY_REST_MS, RELAY_MAX_WAIT_MS)
} catch (err) {
@@ -530,7 +552,8 @@ export async function valhallaPost(
// 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,
+ // An own Valhalla routes every day, so one that hangs would hold each of them up.
+ signal: host === FOSSGIS_VALHALLA ? signal : withDeadline(action, signal),
})
}
@@ -549,24 +572,25 @@ export function valhallaSpacing(signal?: AbortSignal): Promise<void> {
* One question, and one more try after a pause when it earned no answer.
*
* Not when the host just proved it is not a Valhalla at all: that answer will not change
- * on a second ask, and asking anyway is the request the memo exists to save. Nor when
- * the relay now rests and nothing may stand in for it: the second ask would not leave
- * this tab, and OSRM is waiting for the day.
+ * on a second ask, and asking anyway is the request the memo exists to save. Nor, where
+ * nothing may stand in for this engine, when the relay now rests or the host used up its
+ * whole deadline: the second ask would not leave this tab or would most likely wait as
+ * long again, and OSRM is waiting for the day.
*/
async function askWithRetry<T>(
base: string,
- ask: () => Promise<T | null>,
+ ask: () => Promise<T | TooSlow | null>,
signal: AbortSignal | undefined,
publicFallback: boolean,
): Promise<T | null> {
let answer = await ask()
- for (let attempt = 0; !answer && attempt < CHUNK_RETRIES && !signal?.aborted; attempt++) {
+ for (let attempt = 0; (!answer || tooSlow(answer)) && attempt < CHUNK_RETRIES && !signal?.aborted; attempt++) {
if (notValhalla.has(base)) break
- if (base === TREK_VALHALLA && !publicFallback && Date.now() < relayRestingUntil) break
+ if (!publicFallback && (tooSlow(answer) || (base === TREK_VALHALLA && Date.now() < relayRestingUntil))) break
await pause(CHUNK_PAUSE_MS, signal)
answer = await ask()
}
- return answer
+ return tooSlow(answer) ? null : answer
}
/** The request body for a chain of waypoints, weighted away from `avoid`. */
@@ -597,7 +621,10 @@ function routeBody(
}
}
-/** The parsed answer to one POST, `NO_PATH` when the router found no way, or null for every other failure. */
+/**
+ * The parsed answer to one POST, `NO_PATH` when the router found no way, `TOO_SLOW` when
+ * it did not answer in time, or null for every other failure.
+ */
async function postRoute(
base: string,
body: Record<string, unknown>,
@@ -616,8 +643,8 @@ async function postRoute(
return null
}
return await response.json()
- } catch {
- return null
+ } catch (err) {
+ return err instanceof DOMException && err.name === 'TimeoutError' ? TOO_SLOW : null
}
}
@@ -708,10 +735,10 @@ async function requestRun(
avoid: readonly AvoidClass[],
signal: AbortSignal | undefined,
{ costingOptions, searchFilter, publicFallback }: RunAsk,
-): Promise<Omit<ValhallaRun, 'snapped'> | ValhallaNoPath | null> {
+): Promise<Omit<ValhallaRun, 'snapped'> | ValhallaNoPath | TooSlow | null> {
const body = routeBody(waypoints, profile, avoid, costingOptions, searchFilter)
const data = await postRoute(base, body, signal, publicFallback)
- if (data === NO_PATH) return NO_PATH
+ if (data === NO_PATH || tooSlow(data)) return data
return data === null ? null : runFrom(data)
}
@@ -765,6 +792,7 @@ async function alternates(
const body = { ...routeBody([from, to], profile, avoid, costingOptions), ...(count > 0 ? { alternates: count } : {}) }
return askWithRetry(base, async () => {
const data = await postRoute(base, body, signal, publicFallback)
+ if (tooSlow(data)) return data
return data === null ? null : alternatesFrom(data)
}, signal, publicFallback)
}
diff --git a/client/src/components/Roadtrip/alternativeOverlays.test.ts b/client/src/components/Roadtrip/alternativeOverlays.test.ts
index a2088b50c..81c9e3570 100644
--- a/client/src/components/Roadtrip/alternativeOverlays.test.ts
+++ b/client/src/components/Roadtrip/alternativeOverlays.test.ts
@@ -2,7 +2,7 @@ import { describe, it, expect } from 'vitest'
import { alternativeSubline, alternativesBusy, alternativesPhase, buildAlternativeOverlays, otherEngineNote, type AlternativeOverlay } from './alternativeOverlays'
import { formatDurationShort } from './roadtripModel'
import { ALT_PRIMARY, ALT_SECONDARY, ALT_LABEL_PRIMARY_BG, ALT_LABEL_SECONDARY_BG } from './alternativeColors'
-import type { RouteAlternative } from '../Map/RouteCalculator'
+import type { RouteAlternative } from '../Map/routeTypes'
/**
* FE-ALTOVL-001..023: turning the router's answers into something drawable.
diff --git a/client/src/components/Roadtrip/alternativeOverlays.ts b/client/src/components/Roadtrip/alternativeOverlays.ts
index 293d58478..4a5fd30f1 100644
--- a/client/src/components/Roadtrip/alternativeOverlays.ts
+++ b/client/src/components/Roadtrip/alternativeOverlays.ts
@@ -1,6 +1,7 @@
import { formatDurationShort } from './roadtripModel'
import { ALT_PRIMARY, ALT_SECONDARY, ALT_LABEL_PRIMARY_BG, ALT_LABEL_SECONDARY_BG } from './alternativeColors'
-import type { RouteAlternative, RouteEngine } from '../Map/RouteCalculator'
+import type { RouteAlternative } from '../Map/routeTypes'
+import type { RouteEngine } from '../../types'
import type { LegAlternatives } from './useRouteAlternatives'
/** One offered route, ready to draw: the line, its colour, and where its label sits. */
diff --git a/client/src/components/Roadtrip/alternativePins.ts b/client/src/components/Roadtrip/alternativePins.ts
index 12e8f05cd..1c15d3929 100644
--- a/client/src/components/Roadtrip/alternativePins.ts
+++ b/client/src/components/Roadtrip/alternativePins.ts
@@ -1,5 +1,5 @@
import { MAX_WAY_PINS, pinWay, type PinnedWay, type WayPin } from '@trek/shared'
-import type { RoadLine } from '../Map/RouteCalculator'
+import type { RoadLine } from '../Map/routeTypes'
import { isStoredStop, type RouteSegment } from '@trek/shared/roadtrip'
import type { RailLegRoute, RailLegRouter, RoadtripDay, RoadtripStop } from './useRoadtripRoutes'
import type { OfferedRoute, RailDrive, ViaAnchor } from './useRouteAlternatives'
diff --git a/client/src/components/Roadtrip/useRoadtripRoutes.test.ts b/client/src/components/Roadtrip/useRoadtripRoutes.test.ts
index 7c68f8664..01397bd4c 100644
--- a/client/src/components/Roadtrip/useRoadtripRoutes.test.ts
+++ b/client/src/components/Roadtrip/useRoadtripRoutes.test.ts
@@ -1176,6 +1176,19 @@ describe('a leg asked for again on demand', () => {
.toMatchObject({ engine: 'plugin' })
})
+ it('FE-ROADTRIP-ROUTES-047c: a day OSRM drew where Valhalla routes the days is OSRM\'s leg, not a stand-in', async () => {
+ act(() => { useSettingsStore.setState(s => ({ settings: { ...s.settings, routing_valhalla_provider: 'trek' } })) })
+ calculateRouteWithLegs.mockResolvedValue({ ...routed(1), engine: 'osrm' })
+ const { result } = renderHook(() => useRoadtripRoutes(7, [day(1, 1)], map(1, [{ id: 1, at: HAMBURG }, { id: 2, at: BERLIN }])))
+ await waitFor(() => expect(result.current.loading).toBe(false))
+ const [from, to] = result.current.days[0].stops
+ expect(result.current.legRouter!(from, to, 1)).toMatchObject({ engine: 'osrm', standIn: false })
+
+ calculateRouteWithLegs.mockResolvedValue({ ...routed(1), engine: 'valhalla' })
+ act(() => { result.current.reroute!() })
+ await waitFor(() => expect(result.current.legRouter!(from, to, 1).engine).toBe('valhalla'))
+ })
+
it('FE-ROADTRIP-ROUTES-048: a day the stand-in engine drove while avoiding says the avoidance did not happen', async () => {
act(() => { useSettingsStore.setState(s => ({ settings: { ...s.settings, roadtrip_avoid: 'toll,ferry' } })) })
calculateRouteWithLegs.mockResolvedValue({ ...routed(1), avoidance: { asked: ['ferry', 'toll'], achieved: [], fellBack: true } })
diff --git a/client/src/components/Roadtrip/useRoadtripRoutes.ts b/client/src/components/Roadtrip/useRoadtripRoutes.ts
index 2a7b31da1..55ffccd1b 100644
--- a/client/src/components/Roadtrip/useRoadtripRoutes.ts
+++ b/client/src/components/Roadtrip/useRoadtripRoutes.ts
@@ -1,14 +1,14 @@
import { useRoadtripSettings } from '../../hooks/useRoadtripSettings'
import { assembleRoadtrip, bookendStaysOf, carrierLegsFor, carrierSeam, foldRouteRun, hotelBookendsOn, isCarrierMode, isStationaryJoin, mergeRouteSegments, oneNightPerStay, seatCarrierStops, seatNightBookends, standsAsDay, terminalAssignmentId, viasOnLeg, type CarrierSeam, type RoadtripStop, type RoadtripRoutes, type PlanDay, type QuietDay, type RoutedLeg } from '@trek/shared/roadtrip'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
-import { avoidedClasses, calculateRouteWithLegs, routeEngineFor, RoutingRefusedError, type RouteEngine } from '../Map/RouteCalculator'
+import { avoidedClasses, calculateRouteWithLegs, routeEngineFor, RoutingRefusedError } from '../Map/RouteCalculator'
import { resolveLegMode } from '../Planner/legMode'
import { splitIntoRuns, parseAvoid, type DriveLimits } from './roadtripModel'
import { spillChains } from './nightSpill'
import { useSettingsStore } from '../../store/settingsStore'
import { useTripStore } from '../../store/tripStore'
import { useVehicleRange } from './useVehicleRange'
-import type { Assignment, AssignmentsMap, Accommodation, Day, Reservation, RouteAvoidClass, SnappedWaypoint } from '../../types'
+import type { Assignment, AssignmentsMap, Accommodation, Day, Reservation, RouteAvoidClass, RouteEngine, RouteWithLegs, SnappedWaypoint } from '../../types'
import type { RoadtripVia, RoadtripDayBoundary } from '@trek/shared'
import { dayWindow } from './dayWindow'
import { useTranslation } from '../../i18n/TranslationContext'
@@ -82,10 +82,32 @@ const seamShape = (from: RoadtripStop, to: RoadtripStop, viasByDay: Record<numbe
/**
* A drive between two days as it was answered: the leg, the shape it was asked for
- * (`seamShape`), whether OSRM answered in place of the engine asked (`standIn`), and the
- * classes the answer could not avoid.
+ * (`seamShape`), whether OSRM answered in place of the engine asked (`standIn`), the
+ * engine the leg is planned with (`plannedEngine`), and the classes the answer could not
+ * avoid.
*/
-type SeamLeg = RoutedLeg & { shape: string; standIn?: boolean; missed?: RouteAvoidClass[] }
+type SeamLeg = RoutedLeg & { shape: string; standIn?: boolean; engine?: RouteEngine; missed?: RouteAvoidClass[] }
+
+/**
+ * The engine a leg is planned with, read off its answer: the one that drew it. A day that
+ * avoids nothing and that Valhalla could not answer went to OSRM without a word, so it is
+ * OSRM's, and the ways offered beside it are OSRM's too. A day that avoids something stays
+ * Valhalla's while OSRM stands in for it (`standIn`), since only Valhalla can weigh it.
+ */
+const plannedEngine = (r: RouteWithLegs): RouteEngine | undefined => (r.avoidance?.fellBack ? 'valhalla' : r.engine)
+
+/**
+ * Remembers, per leg of a run, the engine it is planned with and whether OSRM stood in for
+ * it, so a picker opened on one of them knows the line on the map is not its engine's and
+ * does not read it as the road already taken.
+ */
+function noteEngines(keys: string[], r: RouteWithLegs, engines: Record<string, RouteEngine>, standIns: Set<string>): void {
+ const engine = plannedEngine(r)
+ for (const key of keys) {
+ if (engine) engines[key] = engine
+ if (r.avoidance?.fellBack) standIns.add(key)
+ }
+}
/** The drive from one stop to the next, identified the same way `planKey` identifies them. */
const legKey = (from: RoadtripStop, to: RoadtripStop): string => `${stopKey(from)}>${stopKey(to)}`
@@ -93,6 +115,7 @@ const legKey = (from: RoadtripStop, to: RoadtripStop): string => `${stopKey(from
const EMPTY_ACCOMMODATIONS: Accommodation[] = []
const EMPTY_RESERVATIONS: Reservation[] = []
const NO_STAND_INS: ReadonlySet<string> = new Set()
+const NO_ENGINES: Readonly<Record<string, RouteEngine>> = {}
/** One leg as the rail's own router answered it, for a surface checking a choice against it. */
export interface RailLegRoute {
@@ -120,7 +143,7 @@ export interface RailLegRouter {
mode: string
/** The classes the rail weighs away on this leg: none unless the leg is driven by Valhalla. */
avoid: RouteAvoidClass[]
- /** Which engine prices this leg on the rail. */
+ /** Which engine prices this leg on the rail, read off its answer once there is one (`plannedEngine`). */
engine: RouteEngine
/**
* True when the line the rail has for this leg came from OSRM standing in for `engine`,
@@ -249,6 +272,8 @@ export function useRoadtripRoutes(
const [seamLegs, setSeamLegs] = useState<Record<string, SeamLeg>>({})
/** The legs of the day runs that OSRM drew while the engine asked did not answer. */
const [standInLegs, setStandInLegs] = useState<ReadonlySet<string>>(NO_STAND_INS)
+ /** The engine each leg of the day runs is planned with, as its answer said (`plannedEngine`). */
+ const [runEngines, setRunEngines] = useState<Readonly<Record<string, RouteEngine>>>(NO_ENGINES)
/** Bumped to route everything again (`reroute`): every answer already cached comes back at once. */
const [rerouteRound, setRerouteRound] = useState(0)
const [loading, setLoading] = useState(false)
@@ -417,6 +442,7 @@ export function useRoadtripRoutes(
setSnapByDay({})
setMissedByDay({})
setStandInLegs(NO_STAND_INS)
+ setRunEngines(NO_ENGINES)
setLoading(false)
return
}
@@ -428,6 +454,7 @@ export function useRoadtripRoutes(
const collectedSnaps: Record<number, Record<string, SnappedWaypoint>> = {}
const collectedMisses: Record<number, RouteAvoidClass[]> = {}
const collectedStandIns = new Set<string>()
+ const collectedEngines: Record<string, RouteEngine> = {}
const tasks: (() => Promise<void>)[] = []
/**
@@ -518,9 +545,7 @@ export function useRoadtripRoutes(
}
}
const folded = foldRouteRun(run, stopAt, r, mode, distanceUnit)
- // Remembered per leg, so a picker opened on one of them knows the line on the
- // map is not its engine's and does not read it as the road already taken.
- if (r.avoidance?.fellBack) for (const key of Object.keys(folded)) collectedStandIns.add(key)
+ noteEngines(Object.keys(folded), r, collectedEngines, collectedStandIns)
Object.assign(dayLegs, folded)
return
} catch (err) {
@@ -565,6 +590,7 @@ export function useRoadtripRoutes(
setSnapByDay({ ...collectedSnaps })
setMissedByDay({ ...collectedMisses })
setStandInLegs(new Set(collectedStandIns))
+ setRunEngines({ ...collectedEngines })
}
void (async () => {
for (let i = 0; i < tasks.length; i++) {
@@ -770,6 +796,7 @@ export function useRoadtripRoutes(
vias: [],
shape,
standIn: r.avoidance?.fellBack === true,
+ engine: plannedEngine(r),
missed: r.avoidance ? r.avoidance.asked.filter(cls => !r.avoidance!.achieved.includes(cls)) : [],
},
}))
@@ -799,7 +826,7 @@ export function useRoadtripRoutes(
return {
mode,
avoid: avoidedClasses(mode, avoid),
- engine: routeEngineFor(mode, avoid),
+ engine: (byRun ? runEngines[key] : seamLegs[key]?.engine) ?? routeEngineFor(mode, avoid),
standIn: byRun ? standInLegs.has(key) : seamLegs[key]?.standIn === true,
route: async (pins, signal) => {
await spacedRequest(signal)
@@ -816,7 +843,7 @@ export function useRoadtripRoutes(
}
},
}
- }, [legModeOf, avoid, spacedRequest, tripId, plan, legsByDay, standInLegs, seamLegs])
+ }, [legModeOf, avoid, spacedRequest, tripId, plan, legsByDay, standInLegs, runEngines, seamLegs])
const reroute = useCallback(() => setRerouteRound(round => round + 1), [])
diff --git a/client/src/components/Roadtrip/useRouteAlternatives.test.ts b/client/src/components/Roadtrip/useRouteAlternatives.test.ts
index 054d628a1..6aaefdf4b 100644
--- a/client/src/components/Roadtrip/useRouteAlternatives.test.ts
+++ b/client/src/components/Roadtrip/useRouteAlternatives.test.ts
@@ -88,12 +88,23 @@ describe('useRouteAlternatives', () => {
act(() => { result.current.ask(request({ avoid: ['toll'], engine: 'valhalla' })) })
expect(calculateAlternatives).toHaveBeenCalledTimes(1)
- const [from, to, profile, options] = calculateAlternatives.mock.calls[0] as [unknown, unknown, string, { avoid: string[]; signal: AbortSignal }]
+ const [from, to, profile, options] = calculateAlternatives.mock.calls[0] as [unknown, unknown, string, { avoid: string[]; signal: AbortSignal; engine: string }]
expect([from, to, profile]).toEqual([{ lat: 53.55, lng: 9.99 }, { lat: 52.52, lng: 13.4 }, 'driving'])
expect(options.avoid).toEqual(['toll'])
+ expect(options.engine).toBe('valhalla')
expect(options.signal).toBeInstanceOf(AbortSignal)
})
+ it('FE-ALTHOOK-003b: a leg OSRM drew where Valhalla routes the days is offered OSRM\'s ways', () => {
+ const { result } = renderHook(() => useRouteAlternatives())
+
+ act(() => { result.current.ask(request({ engine: 'osrm' })) })
+
+ const options = calculateAlternatives.mock.calls[0][3] as { engine: string }
+ expect(options.engine).toBe('osrm')
+ expect(result.current.open?.engine).toBe('osrm')
+ })
+
it('FE-ALTHOOK-004: Current is the rail\'s own leg, priced by the rail\'s engine, and never asked for again', async () => {
// A trip that avoids a class is driven by the second engine; its current road carries
// that engine, so the overlays read every offer against it and not against OSRM.
diff --git a/client/src/components/Roadtrip/useRouteAlternatives.ts b/client/src/components/Roadtrip/useRouteAlternatives.ts
index 865eed47c..9ab3ff52d 100644
--- a/client/src/components/Roadtrip/useRouteAlternatives.ts
+++ b/client/src/components/Roadtrip/useRouteAlternatives.ts
@@ -1,6 +1,8 @@
import { useCallback, useMemo, useRef, useState } from 'react'
import { sameRoad } from '@trek/shared'
-import { calculateAlternatives, type RouteAlternative, type RouteEngine } from '../Map/RouteCalculator'
+import { calculateAlternatives } from '../Map/RouteCalculator'
+import type { RouteAlternative } from '../Map/routeTypes'
+import type { RouteEngine } from '../../types'
import type { RailLegRoute, RailLegRouter } from './useRoadtripRoutes'
/** One offered way of driving a leg, with what it means for this trip. */
@@ -164,7 +166,9 @@ export function useRouteAlternatives(): RouteAlternativesState {
const profile: 'driving' | 'walking' | 'cycling' =
router.mode === 'walking' ? 'walking' : router.mode === 'cycling' ? 'cycling' : 'driving'
- void calculateAlternatives(from, to, profile, { signal: controller.signal, avoid: router.avoid })
+ // Asked of the engine the leg is planned with, so a leg OSRM drew in a day Valhalla
+ // could not answer is offered OSRM's ways, timed alike.
+ void calculateAlternatives(from, to, profile, { signal: controller.signal, avoid: router.avoid, engine: router.engine })
.then(alternatives => {
if (controller.signal.aborted) return
const routes: OfferedRoute[] = [current]
diff --git a/client/src/types.ts b/client/src/types.ts
index 2020bcb86..7cfdcae53 100644
--- a/client/src/types.ts
+++ b/client/src/types.ts
@@ -349,8 +349,21 @@ export interface RouteWithLegs {
avoidance?: { asked: RouteAvoidClass[]; achieved: RouteAvoidClass[]; fellBack?: boolean }
/** Whether the road crosses by ferry, where the engine that drew it says so. */
hasFerry?: boolean
+ /**
+ * The engine that drew this route, which is not always the one the day is planned with:
+ * where Valhalla routes the days and cannot answer one, OSRM draws it.
+ */
+ engine?: RouteEngine
}
+/**
+ * Which engine priced a route: OSRM, Valhalla (which routes the days with the TREK
+ * services or an own Valhalla, and otherwise weighs road classes away), or a route
+ * provider plugin. Their figures are three different speed models, so a figure from one
+ * read against a figure from another measures the models, not the roads.
+ */
+export type RouteEngine = 'osrm' | 'valhalla' | 'plugin'
+
/** A road class a route can be asked to leave out. */
export type RouteAvoidClass = 'motorway' | 'toll' | 'ferry'