mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-28 23:50:08 +00:00
fix(map): draw a reopened trip's routes from the device at once
The rounds that pace their router requests told a cached leg from a request by how long it took, anything past 60 ms counting as a request. Since routes are kept on the device, a leg read back after a reload is an IndexedDB read, which on a page busy drawing the map often takes longer, so every leg waited out a request's pause and the trip filled in one leg a second as if it were routed again. The whole trip's route, the road trip day rounds and the join release now count whether a router actually answered. A relay that refused also kept its rest only in memory, so every reload asked it again for the first day; the rest now holds on the device until it ends. Closes #3228
This commit is contained in:
@@ -3,6 +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 { routerAnswer } from './routerAsks'
|
||||
import { cacheRoute, keepStandIn, rememberRoute, routeInMemory, standIn, storedRoute } from './routeStore'
|
||||
import { formatDuration, formatRouteDistance, getDistanceUnit, legSegment } from './routeText'
|
||||
import type { RouteAlternative } from './routeTypes'
|
||||
@@ -109,12 +110,12 @@ async function routedFetch(
|
||||
const sample = { profile, surface: kind, selfHosted, waypoints: waypoints.length, km }
|
||||
const asked = withoutUTurnIfRefused(url)
|
||||
try {
|
||||
const response = await fetch(asked, { signal })
|
||||
const response = await routerAnswer(fetch(asked, { signal }))
|
||||
countRoute({ ...sample, failed: !response.ok })
|
||||
if (response.ok || !asked.includes(U_TURN_PARAM)) return response
|
||||
const plain = await droppedUTurn(asked, response)
|
||||
if (!plain) return response
|
||||
const second = await fetch(plain, { signal })
|
||||
const second = await routerAnswer(fetch(plain, { signal }))
|
||||
countRoute({ ...sample, failed: !second.ok })
|
||||
return second
|
||||
} catch (err) {
|
||||
@@ -636,11 +637,11 @@ export async function calculateRouteWithLegs(
|
||||
const pluginProfile = parsePluginProfile(profile)
|
||||
if (pluginProfile) {
|
||||
if (tripId == null) throw new Error('Plugin routing needs a trip context')
|
||||
const { route } = await pluginsApi.pluginRoute(pluginProfile.pluginId, pluginProfile.profileId, {
|
||||
const { route } = await routerAnswer(pluginsApi.pluginRoute(pluginProfile.pluginId, pluginProfile.profileId, {
|
||||
tripId,
|
||||
dayId: dayId ?? null,
|
||||
waypoints: waypoints.map((p) => ({ lat: p.lat, lng: p.lng })),
|
||||
}, { signal })
|
||||
}, { signal }))
|
||||
if (!route) throw new Error('No route found')
|
||||
const legs = route.legs.map((leg, i): RouteSegment => ({
|
||||
...legSegment(leg, i, waypoints),
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
import { encodePolyline6 } from '@trek/shared';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { buildAssignment, buildDay, buildPlace } from '../../../tests/helpers/factories';
|
||||
import { server } from '../../../tests/helpers/msw/server';
|
||||
import type { AssignmentsMap, Settings } from '../../types';
|
||||
|
||||
const RELAY = '/api/routing/valhalla/route';
|
||||
const FOSSGIS_OSRM = 'https://routing.openstreetmap.de/routed-car/route/v1/driving';
|
||||
const OWN_OSRM = 'https://osrm.example.org';
|
||||
const OWN_VALHALLA = 'https://valhalla.example.org';
|
||||
|
||||
type Point = { lat: number; lon: number };
|
||||
|
||||
/** Valhalla's trip through some points: one leg per pair. */
|
||||
function valhallaTrip(points: Point[]) {
|
||||
const legs = points.slice(1).map((to, i) => ({
|
||||
shape: encodePolyline6([points[i], to]),
|
||||
summary: { length: 2, time: 300, has_toll: false, has_highway: false, has_ferry: false },
|
||||
}));
|
||||
return { trip: { legs, summary: { length: 2 * legs.length, time: 300 * legs.length } } };
|
||||
}
|
||||
|
||||
/** OSRM's answer for a request's coordinates: one leg per pair. */
|
||||
function osrmAnswer(coords: string) {
|
||||
const points = coords.split(';').map((pair) => pair.split(',').map(Number));
|
||||
const legs = points.slice(1).map(() => ({ distance: 1000, duration: 120 }));
|
||||
return {
|
||||
code: 'Ok',
|
||||
routes: [{ geometry: { coordinates: points }, distance: 1000 * legs.length, duration: 120 * legs.length, legs }],
|
||||
waypoints: points.map((location) => ({ location, distance: 0 })),
|
||||
};
|
||||
}
|
||||
|
||||
/** Every routing host answering, the relay as `relay` says; each request is counted. */
|
||||
function listen(relay: (locations: Point[]) => Response) {
|
||||
const asked: string[] = [];
|
||||
const valhalla =
|
||||
(name: string, answer: (locations: Point[]) => Response) =>
|
||||
async ({ request }: { request: Request }) => {
|
||||
asked.push(name);
|
||||
const body = (await request.json()) as { locations: Point[] };
|
||||
return answer(body.locations);
|
||||
};
|
||||
const osrm =
|
||||
(name: string) =>
|
||||
({ params }: { params: Record<string, unknown> }) => {
|
||||
asked.push(name);
|
||||
return HttpResponse.json(osrmAnswer(String(params.coords)));
|
||||
};
|
||||
const ok = (locations: Point[]) => HttpResponse.json(valhallaTrip(locations));
|
||||
server.use(
|
||||
http.post(RELAY, valhalla('relay', relay)),
|
||||
http.post('https://valhalla1.openstreetmap.de/route', valhalla('fossgis-valhalla', ok)),
|
||||
http.post(`${OWN_VALHALLA}/route`, valhalla('own-valhalla', ok)),
|
||||
http.get(`${FOSSGIS_OSRM}/:coords`, osrm('fossgis-osrm')),
|
||||
http.get(`${OWN_OSRM}/route/v1/driving/:coords`, osrm('own-osrm'))
|
||||
);
|
||||
return asked;
|
||||
}
|
||||
|
||||
let seed = 0;
|
||||
/** A trip of three days with three stops each, at points no other test asked for. */
|
||||
function freshTrip() {
|
||||
seed += 1;
|
||||
const days = [1, 2, 3].map((n) => buildDay({ id: seed * 10 + n, day_number: n }));
|
||||
const assignments: AssignmentsMap = {};
|
||||
for (const day of days) {
|
||||
assignments[String(day.id)] = [0, 1, 2].map((i) =>
|
||||
buildAssignment({
|
||||
day_id: day.id,
|
||||
order_index: i,
|
||||
place: buildPlace({ lat: 30 + seed / 10 + (day.day_number ?? 0) / 100, lng: 5 + i / 100 }),
|
||||
})
|
||||
);
|
||||
}
|
||||
return { days, assignments, reservations: [], accommodations: [], optimizeFromAccommodation: false };
|
||||
}
|
||||
|
||||
/** A fresh page: every module, the routes in memory and the relay's rest start over; the device keeps its database. */
|
||||
async function reload(settings: Partial<Settings>) {
|
||||
vi.resetModules();
|
||||
const { useSettingsStore } = await import('../../store/settingsStore');
|
||||
useSettingsStore.setState((st) => ({ settings: { ...st.settings, ...settings } }));
|
||||
return import('./tripRouteGeometry');
|
||||
}
|
||||
|
||||
/** Lets the writes to the device cache, which nobody awaits, land. */
|
||||
async function settle() {
|
||||
const { offlineDb } = await import('../../db/offlineDb');
|
||||
await offlineDb.routeCache.count();
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
// The relay's rest is kept on the device; each test starts from a relay never asked.
|
||||
localStorage.clear();
|
||||
});
|
||||
|
||||
const PROVIDERS: [string, Partial<Settings>, (locations: Point[]) => Response][] = [
|
||||
['the TREK services', {}, (locations) => HttpResponse.json(valhallaTrip(locations))],
|
||||
['the TREK services, not set up here', {}, () => HttpResponse.json({ error: 'not available' }, { status: 503 })],
|
||||
['the TREK services, too slow', {}, () => HttpResponse.json({ error: 'too slow' }, { status: 504 })],
|
||||
['FOSSGIS', { routing_valhalla_provider: 'fossgis' }, () => HttpResponse.json({}, { status: 500 })],
|
||||
['an own OSRM', { routing_base_url: OWN_OSRM }, () => HttpResponse.json({}, { status: 500 })],
|
||||
['an own Valhalla', { valhalla_base_url: OWN_VALHALLA }, () => HttpResponse.json({}, { status: 500 })],
|
||||
];
|
||||
|
||||
describe('a routed trip after a reload (#3228)', () => {
|
||||
it.each(PROVIDERS)(
|
||||
'RCR-001: with %s every day is drawn from the device without asking a router',
|
||||
async (_name, settings, relay) => {
|
||||
const asked = listen(relay);
|
||||
const trip = freshTrip();
|
||||
|
||||
const first = await reload(settings);
|
||||
const plan = first.planTripRoute(trip, 'driving');
|
||||
const routed = await first.routeTripLegs(plan, { tripId: 1 });
|
||||
expect(routed.flat(2).every(Boolean)).toBe(true);
|
||||
expect(asked.length).toBeGreaterThan(0);
|
||||
await settle();
|
||||
|
||||
asked.length = 0;
|
||||
const second = await reload(settings);
|
||||
const again = await second.routeTripLegs(second.planTripRoute(trip, 'driving'), { tripId: 1 });
|
||||
expect(again.flat(2).every(Boolean)).toBe(true);
|
||||
expect(asked).toEqual([]);
|
||||
},
|
||||
30_000
|
||||
);
|
||||
|
||||
it('RCR-002: legs the device answers are not paced like requests, however long the device takes to read', async () => {
|
||||
// A reload empties the routes in memory, so every leg is read back from the device,
|
||||
// and on a page busy drawing the map such a read takes well past 60 ms. Paced as a
|
||||
// request, each leg then waited 1.1 s and the trip filled in as slowly as a cold one.
|
||||
const asked = listen((locations) => HttpResponse.json(valhallaTrip(locations)));
|
||||
const trip = freshTrip();
|
||||
const first = await reload({ routing_valhalla_provider: 'fossgis' });
|
||||
await first.routeTripLegs(first.planTripRoute(trip, 'driving'), { tripId: 1 });
|
||||
await settle();
|
||||
|
||||
asked.length = 0;
|
||||
const second = await reload({ routing_valhalla_provider: 'fossgis' });
|
||||
const { routeCacheRepo } = await import('../../repo/routeCacheRepo');
|
||||
const read = routeCacheRepo.get.bind(routeCacheRepo);
|
||||
vi.spyOn(routeCacheRepo, 'get').mockImplementation(async (key, maxAgeMs) => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
return read(key, maxAgeMs);
|
||||
});
|
||||
const startedAt = performance.now();
|
||||
const again = await second.routeTripLegs(second.planTripRoute(trip, 'driving'), { tripId: 1 });
|
||||
|
||||
expect(again.flat(2).every(Boolean)).toBe(true);
|
||||
expect(asked).toEqual([]);
|
||||
expect(performance.now() - startedAt).toBeLessThan(1000);
|
||||
}, 30_000);
|
||||
|
||||
const REFUSING: [string, Partial<Settings>, (locations: Point[]) => Response][] = [
|
||||
PROVIDERS[1],
|
||||
[
|
||||
'the TREK services, over their allowance',
|
||||
{},
|
||||
() => HttpResponse.json({ error: 'slow down' }, { status: 429, headers: { 'Retry-After': '600' } }),
|
||||
],
|
||||
];
|
||||
|
||||
it.each(REFUSING)(
|
||||
'RCR-003: with %s a new tab does not put a day to the relay again while it rests',
|
||||
async (_name, settings, relay) => {
|
||||
// The relay said no for this instance, not for one tab. Kept for the tab alone, a new
|
||||
// tab or a reopened app asked it again and the next day waited for the refusal.
|
||||
const asked = listen(relay);
|
||||
const first = await reload(settings);
|
||||
await first.routeTripLegs(first.planTripRoute(freshTrip(), 'driving'), { tripId: 1 });
|
||||
expect(asked.filter((name) => name === 'relay')).toHaveLength(1);
|
||||
await settle();
|
||||
|
||||
asked.length = 0;
|
||||
sessionStorage.clear();
|
||||
const second = await reload(settings);
|
||||
const again = await second.routeTripLegs(second.planTripRoute(freshTrip(), 'driving'), { tripId: 1 });
|
||||
expect(again.flat(2).every(Boolean)).toBe(true);
|
||||
expect(asked.filter((name) => name === 'relay')).toEqual([]);
|
||||
},
|
||||
30_000
|
||||
);
|
||||
|
||||
const ASKING: [string, Partial<Settings>, string][] = [
|
||||
['the TREK services', {}, 'relay'],
|
||||
['an own Valhalla', { valhalla_base_url: OWN_VALHALLA }, 'own-valhalla'],
|
||||
['an own OSRM', { routing_base_url: OWN_OSRM }, 'own-osrm'],
|
||||
];
|
||||
|
||||
it.each(ASKING)(
|
||||
'RCR-004: with %s the days a router is asked for go out a request apart',
|
||||
async (_name, settings, host) => {
|
||||
// The other side of RCR-002: a leg that did go out keeps its pause, or the public
|
||||
// routers get a burst and answer 429 from the second request on.
|
||||
const at: number[] = [];
|
||||
const asked = listen((locations) => HttpResponse.json(valhallaTrip(locations)));
|
||||
const trip = freshTrip();
|
||||
const page = await reload(settings);
|
||||
const startedAt = performance.now();
|
||||
await page.routeTripLegs(page.planTripRoute(trip, 'driving'), {
|
||||
tripId: 1,
|
||||
onProgress: (done) => {
|
||||
if (done > 0) at.push(performance.now() - startedAt);
|
||||
},
|
||||
});
|
||||
expect(asked).toEqual([host, host, host]);
|
||||
expect(at[1] - at[0]).toBeGreaterThanOrEqual(1000);
|
||||
expect(at[2] - at[1]).toBeGreaterThanOrEqual(1000);
|
||||
},
|
||||
30_000
|
||||
);
|
||||
|
||||
it.each([
|
||||
['the TREK services', {}],
|
||||
['an own OSRM', { routing_base_url: OWN_OSRM }],
|
||||
] as [string, Partial<Settings>][])(
|
||||
'RCR-005: with %s a round that reaches no router ends at once',
|
||||
async (_name, settings) => {
|
||||
// Offline, or a host that is not there: nothing went out, so nothing waits a pause.
|
||||
server.use(
|
||||
http.post(RELAY, () => HttpResponse.error()),
|
||||
http.get(`${FOSSGIS_OSRM}/:coords`, () => HttpResponse.error()),
|
||||
http.get(`${OWN_OSRM}/route/v1/driving/:coords`, () => HttpResponse.error())
|
||||
);
|
||||
const page = await reload(settings);
|
||||
const startedAt = performance.now();
|
||||
await page.routeTripLegs(page.planTripRoute(freshTrip(), 'driving'), { tripId: 1 });
|
||||
expect(performance.now() - startedAt).toBeLessThan(1000);
|
||||
},
|
||||
30_000
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,153 @@
|
||||
import { encodePolyline6 } from '@trek/shared';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
|
||||
import { server } from '../../../tests/helpers/msw/server';
|
||||
import { useSettingsStore } from '../../store/settingsStore';
|
||||
import type { Settings, Waypoint } from '../../types';
|
||||
import { calculateRouteWithLegs } from './RouteCalculator';
|
||||
import { routerAnswer, routerAsks } from './routerAsks';
|
||||
import { resetValhallaTurns } from './valhallaRoute';
|
||||
|
||||
const RELAY = '/api/routing/valhalla/route';
|
||||
const FOSSGIS_OSRM = 'https://routing.openstreetmap.de/routed-car/route/v1/driving';
|
||||
const OWN_OSRM = 'https://osrm.example.org';
|
||||
const OWN_VALHALLA = 'https://valhalla.example.org';
|
||||
const PLUGIN = '/api/plugin-routes/charger/fast';
|
||||
|
||||
type Point = { lat: number; lon: number };
|
||||
|
||||
let seed = 0;
|
||||
/** Points no other test asked for, so no route cache answers in their place. */
|
||||
function freshDay(count: number): Waypoint[] {
|
||||
seed += 1;
|
||||
return Array.from({ length: count }, (_, i) => ({ lat: 20 + seed / 100, lng: 8 + i / 100 }));
|
||||
}
|
||||
|
||||
function valhallaTrip(points: Point[]) {
|
||||
const legs = points.slice(1).map((to, i) => ({
|
||||
shape: encodePolyline6([points[i], to]),
|
||||
summary: { length: 2, time: 300, has_toll: false, has_highway: false, has_ferry: false },
|
||||
}));
|
||||
return { trip: { legs, summary: { length: 2 * legs.length, time: 300 * legs.length } } };
|
||||
}
|
||||
|
||||
function osrmAnswer(coords: string) {
|
||||
const points = coords.split(';').map((pair) => pair.split(',').map(Number));
|
||||
const legs = points.slice(1).map(() => ({ distance: 1000, duration: 120 }));
|
||||
return {
|
||||
code: 'Ok',
|
||||
routes: [{ geometry: { coordinates: points }, distance: 1000 * legs.length, duration: 120 * legs.length, legs }],
|
||||
waypoints: points.map((location) => ({ location, distance: 0 })),
|
||||
};
|
||||
}
|
||||
|
||||
const pluginRoute = {
|
||||
pluginId: 'charger',
|
||||
profile: 'fast',
|
||||
coordinates: [
|
||||
[20, 8],
|
||||
[20, 8.01],
|
||||
],
|
||||
distance: 1000,
|
||||
duration: 120,
|
||||
legs: [{ distance: 1000, duration: 120 }],
|
||||
viaPoints: [],
|
||||
};
|
||||
|
||||
const choose = (patch: Partial<Settings>) =>
|
||||
useSettingsStore.setState((st) => ({ settings: { ...st.settings, ...patch } }));
|
||||
|
||||
/** How many questions a router answered while `action` ran. */
|
||||
async function answersDuring(action: () => Promise<unknown>): Promise<number> {
|
||||
const before = routerAsks();
|
||||
// A refused question rejects; whether it counted is what the caller looks at.
|
||||
await Promise.allSettled([action()]);
|
||||
return routerAsks() - before;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
choose({ routing_valhalla_provider: '', valhalla_base_url: '', routing_base_url: '' });
|
||||
resetValhallaTurns();
|
||||
});
|
||||
|
||||
describe('questions a router answered (#3228)', () => {
|
||||
it('RASK-001: an OSRM answer counts, a refusal and a rate limit included', async () => {
|
||||
choose({ routing_valhalla_provider: 'fossgis', routing_base_url: OWN_OSRM });
|
||||
let status = 200;
|
||||
server.use(
|
||||
http.get(`${OWN_OSRM}/route/v1/driving/:coords`, ({ params }) =>
|
||||
status === 200 ? HttpResponse.json(osrmAnswer(String(params.coords))) : HttpResponse.json({}, { status })
|
||||
)
|
||||
);
|
||||
expect(await answersDuring(() => calculateRouteWithLegs(freshDay(2), { profile: 'driving' }))).toBe(1);
|
||||
status = 429;
|
||||
expect(await answersDuring(() => calculateRouteWithLegs(freshDay(2), { profile: 'driving' }))).toBe(1);
|
||||
});
|
||||
|
||||
it('RASK-002: an OSRM that refuses the u-turn permission and is asked again counts twice', async () => {
|
||||
choose({ routing_valhalla_provider: 'fossgis', routing_base_url: OWN_OSRM });
|
||||
server.use(
|
||||
http.get(`${OWN_OSRM}/route/v1/driving/:coords`, ({ request, params }) =>
|
||||
request.url.includes('continue_straight')
|
||||
? HttpResponse.json({ code: 'InvalidQuery' }, { status: 400 })
|
||||
: HttpResponse.json(osrmAnswer(String(params.coords)))
|
||||
)
|
||||
);
|
||||
expect(await answersDuring(() => calculateRouteWithLegs(freshDay(3), { profile: 'driving' }))).toBe(2);
|
||||
});
|
||||
|
||||
it('RASK-003: the TREK relay and an own Valhalla count', async () => {
|
||||
server.use(
|
||||
http.post(RELAY, async ({ request }) =>
|
||||
HttpResponse.json(valhallaTrip(((await request.json()) as { locations: Point[] }).locations))
|
||||
),
|
||||
http.post(`${OWN_VALHALLA}/route`, async ({ request }) =>
|
||||
HttpResponse.json(valhallaTrip(((await request.json()) as { locations: Point[] }).locations))
|
||||
)
|
||||
);
|
||||
expect(await answersDuring(() => calculateRouteWithLegs(freshDay(2), { profile: 'driving' }))).toBe(1);
|
||||
choose({ valhalla_base_url: OWN_VALHALLA });
|
||||
expect(await answersDuring(() => calculateRouteWithLegs(freshDay(2), { profile: 'driving' }))).toBe(1);
|
||||
});
|
||||
|
||||
it('RASK-004: a plugin route counts, a refusal included', async () => {
|
||||
let status = 200;
|
||||
server.use(
|
||||
http.post(PLUGIN, () =>
|
||||
status === 200 ? HttpResponse.json({ route: pluginRoute }) : HttpResponse.json({ error: 'busy' }, { status })
|
||||
)
|
||||
);
|
||||
const ask = () => calculateRouteWithLegs(freshDay(2), { profile: 'plugin:charger/fast', tripId: 1, dayId: seed });
|
||||
expect(await answersDuring(ask)).toBe(1);
|
||||
status = 429;
|
||||
expect(await answersDuring(ask)).toBe(1);
|
||||
});
|
||||
|
||||
it('RASK-005: a question that never reached a router adds nothing', async () => {
|
||||
// Offline, an unknown host, a refused connection: nothing went out that a router
|
||||
// could count against this device, so nothing is paced for it either.
|
||||
server.use(
|
||||
http.post(RELAY, () => HttpResponse.error()),
|
||||
http.get(`${FOSSGIS_OSRM}/:coords`, () => HttpResponse.error()),
|
||||
http.get(`${OWN_OSRM}/route/v1/driving/:coords`, () => HttpResponse.error()),
|
||||
http.post(PLUGIN, () => HttpResponse.error())
|
||||
);
|
||||
expect(await answersDuring(() => calculateRouteWithLegs(freshDay(2), { profile: 'driving' }))).toBe(0);
|
||||
resetValhallaTurns();
|
||||
choose({ routing_valhalla_provider: 'fossgis', routing_base_url: OWN_OSRM });
|
||||
expect(await answersDuring(() => calculateRouteWithLegs(freshDay(2), { profile: 'driving' }))).toBe(0);
|
||||
expect(
|
||||
await answersDuring(() => calculateRouteWithLegs(freshDay(2), { profile: 'plugin:charger/fast', tripId: 1 }))
|
||||
).toBe(0);
|
||||
});
|
||||
|
||||
it('RASK-006: an error that carries a router reply still counts as answered', async () => {
|
||||
const before = routerAsks();
|
||||
await expect(
|
||||
routerAnswer(Promise.reject(Object.assign(new Error('429'), { response: { status: 429 } })))
|
||||
).rejects.toThrow('429');
|
||||
await expect(routerAnswer(Promise.reject(new TypeError('Failed to fetch')))).rejects.toThrow('Failed to fetch');
|
||||
expect(routerAsks() - before).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* How many questions a router has answered in this tab: OSRM, a Valhalla (the relay
|
||||
* included) or a plugin's route provider. A route the cache answers adds nothing.
|
||||
*
|
||||
* The rounds that pace their requests (the whole trip's route, the road trip rail)
|
||||
* compare this before and after a leg to tell a leg that went out from one the cache
|
||||
* answered. They used to go by how long the leg took, and a leg read back from the
|
||||
* device after a reload often takes longer than that guess allowed on a page busy
|
||||
* drawing the map, so every leg waited out a request's pause and the trip filled in
|
||||
* as slowly as one never routed before (#3228).
|
||||
*/
|
||||
let answered = 0;
|
||||
|
||||
/**
|
||||
* Whether a failed question still reached a router: an axios error that carries the
|
||||
* router's reply. A fetch that throws never got one (offline, an unknown host, a refused
|
||||
* connection, a question given up).
|
||||
*/
|
||||
function cameBackWithAnswer(err: unknown): boolean {
|
||||
return typeof err === 'object' && err !== null && 'response' in err && Boolean(err.response);
|
||||
}
|
||||
|
||||
/**
|
||||
* Waits for a question to a router and notes it once the router answered, whatever it
|
||||
* said, a refusal or a rate limit included. A question that never reached one adds
|
||||
* nothing, so a round that cannot reach any router (offline above all) ends at once
|
||||
* instead of waiting a request's pause after every leg.
|
||||
*/
|
||||
export async function routerAnswer<T>(question: Promise<T>): Promise<T> {
|
||||
try {
|
||||
const answer = await question;
|
||||
answered += 1;
|
||||
return answer;
|
||||
} catch (err) {
|
||||
if (cameBackWithAnswer(err)) answered += 1;
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/** Questions a router has answered so far; only the difference between two readings means anything. */
|
||||
export function routerAsks(): number {
|
||||
return answered;
|
||||
}
|
||||
@@ -11,6 +11,14 @@ vi.mock('./RouteCalculator', async (importActual) => {
|
||||
|
||||
const { calculateRouteWithLegs, RoutingRefusedError } = await import('./RouteCalculator')
|
||||
|
||||
// Whether the mocked router's answers count as requests that went out. A round paces
|
||||
// only those; by default the mock answers like the cache, and the pacing tests say otherwise.
|
||||
const router = vi.hoisted(() => ({ overNetwork: false, asked: 0 }))
|
||||
vi.mock('./routerAsks', () => ({
|
||||
routerAnswer: <T>(question: Promise<T>) => question,
|
||||
routerAsks: () => (router.overNetwork ? ++router.asked : router.asked),
|
||||
}))
|
||||
|
||||
const leg = (distance: number): RouteSegment => ({
|
||||
mid: [0, 0], from: [0, 0], to: [0, 0], distance, duration: 600,
|
||||
distanceText: '10 km', durationText: '10 min', walkingText: '2 h', drivingText: '10 min',
|
||||
@@ -39,6 +47,7 @@ const ASSIGNMENTS: AssignmentsMap = {
|
||||
const input = { days: DAYS, assignments: ASSIGNMENTS, reservations: [], accommodations: [], optimizeFromAccommodation: false }
|
||||
|
||||
beforeEach(() => {
|
||||
router.overNetwork = false
|
||||
vi.mocked(calculateRouteWithLegs).mockReset()
|
||||
vi.mocked(calculateRouteWithLegs).mockResolvedValue({
|
||||
coordinates: [[48.86, 2.35], [48.90, 2.42]],
|
||||
@@ -119,6 +128,7 @@ describe('tripRouteGeometry', () => {
|
||||
|
||||
it('FE-MAP-TRG-014: a host that never answers costs one leg its road, not the whole round', async () => {
|
||||
neverAnswers()
|
||||
router.overNetwork = true
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
const pending = routeTrip(input, { profile: 'driving', tripId: 7 })
|
||||
@@ -139,6 +149,7 @@ describe('tripRouteGeometry', () => {
|
||||
// once is exactly the burst they answer with 429 from the second second on, and each
|
||||
// refused leg used to stay a straight line with no distance and no word about it.
|
||||
it('FE-MAP-TRG-007: asks the router one leg at a time, a second apart', async () => {
|
||||
router.overNetwork = true
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
// A round trip takes time; only a network answer is paced, a cache hit is not.
|
||||
@@ -165,6 +176,7 @@ describe('tripRouteGeometry', () => {
|
||||
})
|
||||
|
||||
it('FE-MAP-TRG-008: a rate limit is waited out and the leg asked for again', async () => {
|
||||
router.overNetwork = true
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
vi.mocked(calculateRouteWithLegs)
|
||||
@@ -187,6 +199,7 @@ describe('tripRouteGeometry', () => {
|
||||
})
|
||||
|
||||
it('FE-MAP-TRG-009: a host that says how long to wait is given that long', async () => {
|
||||
router.overNetwork = true
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
vi.mocked(calculateRouteWithLegs)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { RouteProfileKey } from './RouteCalculator'
|
||||
import { calculateRouteWithRetries, sleepUnlessAborted as sleep } from './routeRetry'
|
||||
import { routerAsks } from './routerAsks'
|
||||
import { buildDayRouteRuns, type DayRouteInputs, type DayRoutePoint } from './dayRoutePlan'
|
||||
import { dayViaLookup, foldViaLegs, threadVias, viasOnDayLeg, type DayViaLookup } from '../../utils/dayRouteVias'
|
||||
import { projectDayItinerary } from './dayTourProjection'
|
||||
@@ -185,8 +186,6 @@ export function summariseTripRoute(days: TripOverviewDay[]): TripRouteSummary {
|
||||
* first and paces itself the same way).
|
||||
*/
|
||||
const REQUEST_SPACING_MS = 1100
|
||||
/** Anything answered faster than this came out of RouteCalculator's cache, not the network. */
|
||||
const CACHE_HIT_MS = 60
|
||||
/**
|
||||
* The longest one leg may take, its rate-limit retries included. The OSRM request has no
|
||||
* deadline of its own, and a round that waits for every leg must not hang on a host that
|
||||
@@ -258,10 +257,12 @@ export async function routeTripLegs(
|
||||
onProgress?.(0, tasks.length)
|
||||
for (let i = 0; i < tasks.length; i++) {
|
||||
if (signal?.aborted) break
|
||||
const startedAt = performance.now()
|
||||
const asksBefore = routerAsks()
|
||||
await tasks[i]()
|
||||
onProgress?.(i + 1, tasks.length)
|
||||
const wasNetwork = performance.now() - startedAt > CACHE_HIT_MS
|
||||
// Paced by what went out, not by how long the leg took: a leg read back from the
|
||||
// device after a reload can take longer than a request on a busy page (#3228).
|
||||
const wasNetwork = routerAsks() !== asksBefore
|
||||
if (wasNetwork && i < tasks.length - 1) await sleep(REQUEST_SPACING_MS, signal)
|
||||
}
|
||||
return routed
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* Where the TREK routing relay's rest outlives the page. Without it every reload, every
|
||||
* new tab and every reopened app put the first day it routed to a relay that had just said
|
||||
* it could not answer, and that day waited for the refusal again before its kept road
|
||||
* showed (#3228). The relay is the instance's, so its rest holds for every tab of this
|
||||
* device and ends when it would have; a device that cannot store it simply asks again.
|
||||
*/
|
||||
const RELAY_REST_KEY = 'trek_valhalla_relay_rest';
|
||||
|
||||
/** Until when the relay rests, as kept on this device; 0 when it does not. */
|
||||
export function keptRelayRest(): number {
|
||||
try {
|
||||
const until = Number(localStorage.getItem(RELAY_REST_KEY));
|
||||
return Number.isFinite(until) && until > Date.now() ? until : 0;
|
||||
} catch {
|
||||
// No storage here (a private window, a blocked origin): the relay is asked again.
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/** Keeps the relay's rest on this device until then; 0 forgets it. */
|
||||
export function keepRelayRest(until: number): void {
|
||||
try {
|
||||
if (until > 0) localStorage.setItem(RELAY_REST_KEY, String(until));
|
||||
else localStorage.removeItem(RELAY_REST_KEY);
|
||||
} catch {
|
||||
// No storage here: the rest holds for this page only.
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,8 @@ import { useSettingsStore } from '../../store/settingsStore'
|
||||
import { decodePolyline } from './transitGeometry'
|
||||
import { ferrySpansOf, type ValhallaManeuver } from './valhallaFerries'
|
||||
import { haversineKm } from '../../utils/geo'
|
||||
import { routerAnswer } from './routerAsks'
|
||||
import { keepRelayRest, keptRelayRest } from './valhallaRelayRest'
|
||||
import type { Waypoint, SnappedWaypoint, RouteAvoidClass } from '../../types'
|
||||
|
||||
/**
|
||||
@@ -211,7 +213,13 @@ export interface ValhallaRun {
|
||||
}
|
||||
|
||||
/** Until when this tab asks FOSSGIS instead of a relay that could not answer. */
|
||||
let relayRestingUntil = 0
|
||||
let relayRestingUntil = keptRelayRest()
|
||||
|
||||
/** Rests the relay until then, on this page and on the device (valhallaRelayRest). */
|
||||
function restRelay(until: number): void {
|
||||
relayRestingUntil = until
|
||||
keepRelayRest(until)
|
||||
}
|
||||
|
||||
/**
|
||||
* The instance's Valhalla, or null when it should not ask one.
|
||||
@@ -503,7 +511,7 @@ export async function valhallaTurn(base: string, signal?: AbortSignal): Promise<
|
||||
/** Forget the last turn and a resting relay, for tests that start from a quiet host. */
|
||||
export function resetValhallaTurns(): void {
|
||||
lastPublicAskAt = 0
|
||||
relayRestingUntil = 0
|
||||
restRelay(0)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -544,13 +552,13 @@ function withDeadline(action: ValhallaRelayAction, signal?: AbortSignal): AbortS
|
||||
async function askRelay(action: ValhallaRelayAction, body: object, signal?: AbortSignal): Promise<Response | null> {
|
||||
let wait = RELAY_REST_MS
|
||||
try {
|
||||
const response = await valhallaRelayRepo.ask(action, body, withDeadline(action, signal))
|
||||
const response = await routerAnswer(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) {
|
||||
if (signal?.aborted) throw err
|
||||
}
|
||||
relayRestingUntil = Date.now() + wait
|
||||
restRelay(Date.now() + wait)
|
||||
return null
|
||||
}
|
||||
|
||||
@@ -575,7 +583,7 @@ export async function valhallaPost(
|
||||
if (base === TREK_VALHALLA && (!publicFallback || overPublicLimit(action, body))) return new Response(null, { status: 503 })
|
||||
const host = base === TREK_VALHALLA ? FOSSGIS_VALHALLA : base
|
||||
await valhallaTurn(host, signal)
|
||||
return fetch(`${host}/${action}`, {
|
||||
return routerAnswer(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.
|
||||
@@ -583,7 +591,7 @@ export async function valhallaPost(
|
||||
body: JSON.stringify(body),
|
||||
// An own Valhalla routes every day, so one that hangs would hold each of them up.
|
||||
signal: host === FOSSGIS_VALHALLA ? signal : withDeadline(action, signal),
|
||||
})
|
||||
}))
|
||||
}
|
||||
|
||||
/** Whether a route carries more locations than the public instance takes, so it cannot stand in for the relay. */
|
||||
|
||||
@@ -27,6 +27,7 @@ import { useRoadtripRoutes } from './useRoadtripRoutes'
|
||||
import { DEFAULT_SETTINGS, useSettingsStore } from '../../store/settingsStore'
|
||||
import { useTripStore } from '../../store/tripStore'
|
||||
import { lineMetres } from './corridor'
|
||||
import { routerAnswer } from '../Map/routerAsks'
|
||||
|
||||
const HAMBURG: [number, number] = [53.5511, 9.9937]
|
||||
const LUENEBURG: [number, number] = [53.2464, 10.4115]
|
||||
@@ -831,6 +832,45 @@ describe('useRoadtripRoutes', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('FE-ROADTRIP-ROUTES-067: days and joins the device answers slowly are still not paced like requests (#3228)', async () => {
|
||||
// After a reload every road is read back from the device rather than from memory,
|
||||
// and on a page busy drawing the map that read can take longer than a request. No
|
||||
// router is asked here, so nothing may wait a request's 1.1 s turn.
|
||||
calculateRouteWithLegs.mockImplementation(() => new Promise(resolve => setTimeout(() => resolve(routed(1)), 100)))
|
||||
const MUNICH: [number, number] = [48.1374, 11.5755]
|
||||
const INNSBRUCK: [number, number] = [47.2692, 11.4041]
|
||||
const BOZEN: [number, number] = [46.4983, 11.3548]
|
||||
setting({ roadtrip_connect_days: true })
|
||||
const daysList = [day(1, 1), day(2, 2), day(3, 3)]
|
||||
const assignments = {
|
||||
...map(1, [{ id: 1, at: HAMBURG, time: '09:00' }, { id: 2, at: LUENEBURG }]),
|
||||
...map(2, [{ id: 3, at: BERLIN, time: '09:00' }, { id: 4, at: MUNICH }]),
|
||||
...map(3, [{ id: 5, at: INNSBRUCK, time: '09:00' }, { id: 6, at: BOZEN }]),
|
||||
} as AssignmentsMap
|
||||
renderHook(() => useRoadtripRoutes(7, daysList, assignments))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(askedFor(INNSBRUCK, BOZEN).length).toBeGreaterThan(0)
|
||||
expect(askedFor(MUNICH, INNSBRUCK).length).toBeGreaterThan(0)
|
||||
}, { timeout: 1000 })
|
||||
})
|
||||
|
||||
it('FE-ROADTRIP-ROUTES-068: days a router answers still go out a request apart (#3228)', async () => {
|
||||
// The other side of FE-ROADTRIP-ROUTES-067: a day that did reach a router keeps its
|
||||
// pause, or the public OSRM gets a burst and answers 429 from the second day on.
|
||||
const askedAt: number[] = []
|
||||
calculateRouteWithLegs.mockImplementation(() => {
|
||||
askedAt.push(performance.now())
|
||||
return routerAnswer(Promise.resolve(routed(1)))
|
||||
})
|
||||
const { days: daysList, assignments } = twoDays()
|
||||
const { result } = renderHook(() => useRoadtripRoutes(7, daysList, assignments))
|
||||
await waitFor(() => expect(result.current.loading).toBe(false), { timeout: 4000 })
|
||||
|
||||
expect(askedAt).toHaveLength(2)
|
||||
expect(askedAt[1] - askedAt[0]).toBeGreaterThanOrEqual(1000)
|
||||
})
|
||||
|
||||
it('FE-ROADTRIP-ROUTES-051: a join OSRM answered in the engine’s place is drawn, flagged, and asked for again on request', async () => {
|
||||
// Filed like any answer, it stood in for the weighed road until the page was loaded
|
||||
// again, and a picker on it read the stand-in line as the road already taken.
|
||||
|
||||
@@ -2,6 +2,7 @@ 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 } from '../Map/RouteCalculator'
|
||||
import { routerAsks } from '../Map/routerAsks'
|
||||
import { resolveLegMode } from '../Planner/legMode'
|
||||
import { splitIntoRuns, parseAvoid, type DriveLimits } from './roadtripModel'
|
||||
import { spillChains } from './nightSpill'
|
||||
@@ -25,8 +26,6 @@ export type { RoadtripStop, RoadtripDay, RoadtripRoutes, QuietDay, AccessSpur, R
|
||||
* the first handful answer and the rest come back 429.
|
||||
*/
|
||||
const REQUEST_SPACING_MS = 1100
|
||||
/** Anything answered faster than this came out of RouteCalculator cache, not the network. */
|
||||
const CACHE_HIT_MS = 60
|
||||
/** How often a leg that failed (usually a rate limit) is tried again, and how long after. */
|
||||
const RETRY_DELAYS_MS = [1500, 4000]
|
||||
|
||||
@@ -596,14 +595,15 @@ export function useRoadtripRoutes(
|
||||
void (async () => {
|
||||
for (let i = 0; i < tasks.length; i++) {
|
||||
if (controller.signal.aborted) return
|
||||
const startedAt = performance.now()
|
||||
const asksBefore = routerAsks()
|
||||
await tasks[i]()
|
||||
if (controller.signal.aborted) return
|
||||
publish()
|
||||
// Only pace what actually went out. RouteCalculator answers a repeat from its
|
||||
// cache in well under a millisecond, and switching back into road trip mode is
|
||||
// all repeats — waiting a second between those made a warm view feel broken.
|
||||
const wasNetwork = performance.now() - startedAt > CACHE_HIT_MS
|
||||
// Only pace what actually went out. Switching back into road trip mode is all
|
||||
// repeats, and reopening the trip reads them back from the device, which can take
|
||||
// longer than a request would on a busy page: a second between those made a warm
|
||||
// view feel broken and a reload look like nothing was kept (#3228).
|
||||
const wasNetwork = routerAsks() !== asksBefore
|
||||
if (wasNetwork && i < tasks.length - 1) await sleep(REQUEST_SPACING_MS, controller.signal)
|
||||
}
|
||||
if (controller.signal.aborted) return
|
||||
@@ -770,7 +770,7 @@ export function useRoadtripRoutes(
|
||||
// shape: it is asked for on its own, so the points the traveller dropped on it
|
||||
// never reached the router and dragging one did visibly nothing.
|
||||
const shaping = viasOnLeg(seam.from, seam.to, viasByDay[seam.from.ownerDayId] ?? [])
|
||||
const startedAt = performance.now()
|
||||
const asksBefore = routerAsks()
|
||||
const r = await calculateRouteWithLegs(
|
||||
[
|
||||
{ lat: seam.from.lat, lng: seam.from.lng },
|
||||
@@ -782,7 +782,7 @@ export function useRoadtripRoutes(
|
||||
// A seam this device routed before came back from its cache and went nowhere, so
|
||||
// its slot goes back before the store below re-runs this effect. Holding it made a
|
||||
// trip of connected days wait a second per join on every open (#2794).
|
||||
if (performance.now() - startedAt <= CACHE_HIT_MS) release()
|
||||
if (routerAsks() === asksBefore) release()
|
||||
if (controller.signal.aborted) return
|
||||
// One leg per waypoint PAIR, so a shaped seam comes back in pieces and the rail
|
||||
// wants the whole drive: merged here, exactly as a day run folds its via legs
|
||||
|
||||
Reference in New Issue
Block a user