mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-30 16:33:16 +00:00
5989ba5f1f
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
154 lines
6.4 KiB
TypeScript
154 lines
6.4 KiB
TypeScript
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);
|
|
});
|
|
});
|