diff --git a/client/src/components/Map/RouteCalculator.ts b/client/src/components/Map/RouteCalculator.ts index fe36e400d..032dc0f32 100644 --- a/client/src/components/Map/RouteCalculator.ts +++ b/client/src/components/Map/RouteCalculator.ts @@ -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 { + 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. */ diff --git a/client/src/components/Map/routeStore.ts b/client/src/components/Map/routeStore.ts index ecfa14806..731594aac 100644 --- a/client/src/components/Map/routeStore.ts +++ b/client/src/components/Map/routeStore.ts @@ -39,3 +39,21 @@ export async function storedRoute(key: string): Promise { 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 { + return routeCacheRepo.get(key, STAND_IN_MS); +} diff --git a/client/src/components/Map/valhallaDayRoute.test.ts b/client/src/components/Map/valhallaDayRoute.test.ts index 3a77c441f..5d00c44fa 100644 --- a/client/src/components/Map/valhallaDayRoute.test.ts +++ b/client/src/components/Map/valhallaDayRoute.test.ts @@ -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', () => { diff --git a/client/src/repo/routeCacheRepo.ts b/client/src/repo/routeCacheRepo.ts index c1ff05a34..ebf7e3071 100644 --- a/client/src/repo/routeCacheRepo.ts +++ b/client/src/repo/routeCacheRepo.ts @@ -23,11 +23,11 @@ async function prune(): Promise { * 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(key: string): Promise { + /** The route kept under `key`, unless it is missing or older than `maxAgeMs`. */ + async get(key: string, maxAgeMs = MAX_AGE_MS): Promise { 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.