fix(map): open a day the routing relay could not answer drawn, without waiting for it again

On an instance that routes its days with Valhalla (the TREK services by
default), a day the relay could not answer in time was drawn by OSRM and
kept only under the OSRM key. The next visit missed the Valhalla key, asked
the relay again and waited out its deadline, up to twelve seconds a day,
before the kept road showed, so every reload showed straight lines first.

OSRM's answer now stands in for such a day for an hour under a key of its
own, on the device only. Reopening the trip draws it at once; after the
hour the relay is asked again and its answer becomes the day's. Days that
avoid something keep asking Valhalla, since the stand-in drives the road
they mean to leave out.

Closes #3228
This commit is contained in:
Maurice
2026-11-26 22:09:59 +01:00
parent 7d802081ce
commit 10d95a39ac
4 changed files with 69 additions and 5 deletions
+14 -2
View File
@@ -3,7 +3,7 @@ import { pluginsApi } from '../../api/client'
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 { cacheRoute, keepStandIn, rememberRoute, routeInMemory, standIn, storedRoute } from './routeStore'
import { formatDuration, formatRouteDistance, getDistanceUnit, legSegment } from './routeText'
import type { RouteAlternative } from './routeTypes'
import { valhallaAvailable, valhallaPlansDays, valhallaRoutesDays, type AvoidClass } from './valhallaRoute'
@@ -289,6 +289,12 @@ function withEngine(route: RouteWithLegs, engine: RouteEngine): RouteWithLegs {
* 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.
*
* A day that avoids nothing and that Valhalla could not route is not put to it again for a
* while: OSRM's answer, the same road an OSRM instance draws, stands in for it under a key
* of its own, so every visit does not wait out the relay first (#3228). Never under the
* Valhalla key, which holds only what Valhalla answered. A day that avoids something is
* asked again, since the stand-in drives the very road it means to leave out.
*/
async function valhallaOrOsrmDay(
waypoints: Waypoint[],
@@ -299,6 +305,9 @@ async function valhallaOrOsrmDay(
signal?: AbortSignal
},
): Promise<RouteWithLegs> {
const standInKey = avoiding.length ? null : `${keys.valhalla}:standin`
const stoodIn = standInKey ? await standIn(standInKey) : null
if (stoodIn) return stoodIn
const asking = avoiding.length > 0 || valhallaRoutesDays()
const routed = asking ? await valhallaDayRoute(waypoints, profile, avoiding, signal) : null
if (routed) {
@@ -307,7 +316,10 @@ async function valhallaOrOsrmDay(
}
const plain = (await storedRoute(keys.plain)) ?? await osrmWithLegs(waypoints, keys.coords, profile, signal)
cacheRoute(keys.plain, plain)
return withFallbackNoted(plain, avoiding)
const drawn = withFallbackNoted(plain, avoiding)
// A day left before Valhalla answered was never refused by it.
if (standInKey && !signal?.aborted) keepStandIn(standInKey, drawn)
return drawn
}
/** Fetches a full route via OSRM and returns coordinates, distance, and duration estimates for driving/walking. */
+18
View File
@@ -39,3 +39,21 @@ export async function storedRoute(key: string): Promise<RouteWithLegs | null> {
if (kept) rememberRoute(key, kept);
return kept;
}
/**
* How long OSRM's answer stands in for a day Valhalla could not route. Long enough that
* reopening the trip draws that day at once instead of waiting out the relay again on
* every visit (#3228), short enough that a Valhalla back from an outage gets the day again
* the same day.
*/
const STAND_IN_MS = 60 * 60 * 1000;
/** Keeps OSRM's answer for a day Valhalla could not route, on the device only, for `STAND_IN_MS`. */
export function keepStandIn(key: string, route: RouteWithLegs): void {
void routeCacheRepo.put(key, route);
}
/** The answer that stood in for a day Valhalla could not route, while it is recent enough. */
export function standIn(key: string): Promise<RouteWithLegs | null> {
return routeCacheRepo.get<RouteWithLegs>(key, STAND_IN_MS);
}
@@ -59,6 +59,8 @@ interface Traffic {
osrm: string[];
}
const HOUR = 60 * 60 * 1000;
const answered = (body: RouteBody) => HttpResponse.json({ trip: valhallaTrip(body.locations) });
/** Every routing host answering, the relay as `relay` says; what each was asked is recorded. */
@@ -274,9 +276,41 @@ describe('the route cache keeps the engine apart', () => {
up = true;
resetValhallaTurns();
expect((await calculateRouteWithLegs(points, { profile: 'driving' })).distance).toBe(2000);
expect(traffic.relay).toHaveLength(1);
const now = Date.now();
vi.spyOn(Date, 'now').mockReturnValue(now + HOUR + 1);
expect((await calculateRouteWithLegs(points, { profile: 'driving' })).distance).toBe(4000);
expect([traffic.relay.length, traffic.osrm.length]).toEqual([2, 1]);
});
it('VDAY-CACHE-005: a day the relay could not route opens drawn after a reload, without waiting for the relay again (#3228)', async () => {
const points = freshDay(3);
let slow = true;
const traffic = listen((body) =>
slow ? HttpResponse.json({ error: 'The TREK routing service took too long' }, { status: 504 }) : answered(body)
);
expect((await calculateRouteWithLegs(points, { profile: 'driving' })).engine).toBe('osrm');
const { offlineDb } = await import('../../db/offlineDb');
const stoodIn = (key: string) => key.includes(`${points[0].lng},${points[0].lat}`) && key.endsWith(':standin');
await vi.waitFor(async () => expect(await offlineDb.routeCache.filter((row) => stoodIn(row.key)).count()).toBe(1));
// A reload: the modules, and with them the routes in memory and the relay's rest, start over.
vi.resetModules();
const reloaded = await import('./RouteCalculator');
const again = await reloaded.calculateRouteWithLegs(points, { profile: 'driving' });
expect([again.distance, again.engine]).toEqual([2000, 'osrm']);
expect([traffic.relay.length, traffic.osrm.length]).toEqual([1, 1]);
// An hour on, the relay gets the day again and its answer is kept as the day's.
slow = false;
const now = Date.now();
vi.spyOn(Date, 'now').mockReturnValue(now + HOUR + 1);
const routed = await reloaded.calculateRouteWithLegs(points, { profile: 'driving' });
expect([routed.distance, routed.engine]).toEqual([4000, 'valhalla']);
expect([traffic.relay.length, traffic.osrm.length]).toEqual([2, 1]);
});
});
describe('the route cache while the relay rests', () => {
+3 -3
View File
@@ -23,11 +23,11 @@ async function prune(): Promise<void> {
* anything this store cannot read or write is simply routed again.
*/
export const routeCacheRepo = {
/** The route kept under `key`, unless it is missing or too old. */
async get<T>(key: string): Promise<T | null> {
/** The route kept under `key`, unless it is missing or older than `maxAgeMs`. */
async get<T>(key: string, maxAgeMs = MAX_AGE_MS): Promise<T | null> {
try {
const row = await offlineDb.routeCache.get(key);
if (!row || Date.now() - row.savedAt > MAX_AGE_MS) return null;
if (!row || Date.now() - row.savedAt > maxAgeMs) return null;
return row.route as T;
} catch {
// A closed or blocked database: the leg is routed again.