routing: a slow route is not a down relay, and the relay takes whole days

A request to the TREK Valhalla that runs out its deadline (a long bike
route) is answered 504 and no longer rests the relay for every user or a
tab for ten minutes; that one day goes to OSRM. Only an unreachable host
or a server error rests it.

A day goes to the relay with up to twenty stops per request and no pause
between pieces; a request that ends up at the public FOSSGIS Valhalla is
cut to ten and paced, as before. The 1.1 s spacing of the server applies
to the public hosts only, not to an admin's own OSRM or Valhalla. The
relay keeps its connections open and asks for maneuvers only, which the
relay contract now accepts.
This commit is contained in:
Maurice
2026-10-30 16:16:09 +01:00
parent a55d4e786f
commit c508bb9758
11 changed files with 505 additions and 76 deletions
+63 -2
View File
@@ -747,6 +747,22 @@ describe('server Roadtrip router through the TREK services (routing relay)', ()
});
});
it('ROUTER-RELAY-007: a question the relay ran out of time on is not handed to FOSSGIS, and OSRM routes the day', async () => {
const slow = [
() => Promise.reject(new DomainError(504, 'The TREK routing service took too long for this route')),
() => Promise.resolve(answer(504, { error: 'gateway timeout' })),
];
await oneByOne([...slow.entries()], async ([userId, timedOut]) => {
vi.mocked(safeFetchAdminConfigured).mockClear();
relay.ask.mockReset().mockImplementationOnce(timedOut);
const route = await settled(setup().router.route(userId, 1, 1, points.slice(0, 2), 'driving', ['toll']));
expect(route.avoidMissed).toEqual(['toll']);
const asked = vi.mocked(safeFetchAdminConfigured).mock.calls.map(([url]) => String(url));
expect(asked).toHaveLength(1);
expect(asked[0]).toContain('routing.openstreetmap.de/routed-car');
});
});
it('ROUTER-RELAY-003: reads the TREK Valhalla saying no way joins the points as a refusal, and fails on any other error', async () => {
const costingOptions = { max_hiking_difficulty: 3 };
relay.ask.mockResolvedValueOnce(answer(400, { error_code: 442, error: 'No path could be found for input' }));
@@ -908,13 +924,22 @@ describe('server Roadtrip router: every day through Valhalla where it routes the
);
});
it('ROUTER-DAY-005: a day that avoids something keeps FOSSGIS behind the relay and its ten locations', async () => {
it('ROUTER-DAY-011: a day that avoids something asks the relay twenty locations at a time, with only the maneuvers', async () => {
const route = await settled(setup().router.route(4, 1, 1, day(12), 'driving', ['toll']));
expect(relayBodies().map((body) => body.locations.length)).toEqual([12]);
expect(relay.ask.mock.calls[0][2]).toMatchObject({ directions_type: 'maneuvers' });
expect(route.parts).toHaveLength(11);
expect(safeFetchAdminConfigured).not.toHaveBeenCalled();
});
it('ROUTER-DAY-005: a day that avoids something keeps FOSSGIS behind the relay, cut again in its ten locations', async () => {
relay.ask.mockReset().mockResolvedValue(answer(503, { error: 'The TREK routing service is resting' }));
vi.mocked(safeFetchAdminConfigured).mockImplementation(
async (_url, init) => new Response(JSON.stringify(legsFor(bodyOf(init)))),
);
const route = await settled(setup().router.route(4, 1, 1, day(12), 'driving', ['toll']));
expect(relayBodies().map((body) => body.locations.length)).toEqual([10, 3]);
// Twelve for the relay, then the day cut again: FOSSGIS refuses an eleventh location.
expect(relayBodies().map((body) => body.locations.length)).toEqual([12, 10, 3]);
expect(vi.mocked(safeFetchAdminConfigured).mock.calls.map(([url]) => url)).toEqual(
Array(2).fill('https://valhalla1.openstreetmap.de/route'),
);
@@ -986,6 +1011,42 @@ describe('server Roadtrip router: every day through Valhalla where it routes the
expect(relay.ask).not.toHaveBeenCalled();
});
it('ROUTER-DAY-012: paces the public hosts a request every 1.1 s, an own Valhalla and an own OSRM not at all', async () => {
const own = (url: unknown) => String(url).startsWith('https://valhalla.internal');
vi.mocked(safeFetchAdminConfigured).mockImplementation(async (url, init) =>
own(url) ? new Response(JSON.stringify(legsFor(bodyOf(init)))) : osrm(),
);
const ownValhalla = setup({ valhalla_base_url: 'https://valhalla.internal' }).router.route(
1,
1,
1,
day(21),
'cycling',
[],
);
const ownOsrm = setup({ routing_base_url: 'http://router.internal' }).router;
const twoDays = Promise.all([
ownOsrm.route(2, 1, 1, points, 'driving', []),
ownOsrm.route(2, 1, 2, points, 'driving', []),
]);
await vi.advanceTimersByTimeAsync(1000);
expect(await ownValhalla).toMatchObject({ parts: expect.any(Array) });
expect(await twoDays).toHaveLength(2);
expect(safeFetchAdminConfigured).toHaveBeenCalledTimes(4);
vi.mocked(safeFetchAdminConfigured).mockClear();
const { router } = setup();
const publicDays = Promise.all([
router.route(3, 1, 1, points, 'driving', []),
router.route(3, 1, 2, points, 'driving', []),
]);
await vi.advanceTimersByTimeAsync(1000);
expect(safeFetchAdminConfigured).toHaveBeenCalledTimes(1);
await vi.advanceTimersByTimeAsync(200);
await publicDays;
expect(safeFetchAdminConfigured).toHaveBeenCalledTimes(2);
});
it('ROUTER-DAY-007: with FOSSGIS chosen, a day that avoids nothing stays with OSRM as before', async () => {
relay.trekValhalla.mockReturnValue(TREK_VALHALLA);
const { router } = setup({ routing_valhalla_provider: 'fossgis' });
@@ -81,9 +81,10 @@ describe('RoutingRelayService.ask', () => {
contentType: 'application/json',
body: Buffer.from('{"trip":{"legs":[]}}'),
});
const [url, init, redirects] = vi.mocked(safeFetchAdminConfigured).mock.calls[0];
const [url, init, redirects, , , reuseConnections] = vi.mocked(safeFetchAdminConfigured).mock.calls[0];
expect(url).toBe('https://valhalla.liketrek.com/route');
expect(redirects).toBe(0);
expect(reuseConnections).toBe(true);
expect(init?.signal).toBeInstanceOf(AbortSignal);
expect((init?.headers as Record<string, string>).Authorization).toBe('Bearer tk1.k.p.s');
expect(JSON.parse(String(init?.body))).toEqual(ROUTE);
@@ -158,12 +159,10 @@ describe('RoutingRelayService.ask', () => {
await expect(relay.ask(1, 'route', ROUTE)).rejects.toMatchObject({ status: 502 });
});
it('RELAY-009: after a host that hung, the next question is answered 503 at once, and asked again after the rest', async () => {
it('RELAY-009: after a host that could not be reached, the next question is answered 503 at once, and asked again after the rest', async () => {
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(new Date('2026-10-29T10:00:00Z'));
vi.mocked(safeFetchAdminConfigured).mockRejectedValueOnce(
new DOMException('The operation was aborted due to timeout', 'TimeoutError'),
);
vi.mocked(safeFetchAdminConfigured).mockRejectedValueOnce(new TypeError('fetch failed'));
await expect(relay.ask(1, 'height', { shape: [{ lat: 47, lon: 11 }] })).rejects.toMatchObject({ status: 502 });
const resting = await relay.ask(1, 'height', { shape: [{ lat: 47.1, lon: 11 }] });
@@ -177,12 +176,27 @@ describe('RoutingRelayService.ask', () => {
});
it('RELAY-010: passes an error of the host on and rests after it', async () => {
vi.mocked(safeFetchAdminConfigured).mockResolvedValueOnce(upstream(504, '{"error":"gateway"}'));
expect((await relay.ask(1, 'route', ROUTE)).status).toBe(504);
vi.mocked(safeFetchAdminConfigured).mockResolvedValueOnce(upstream(502, '{"error":"gateway"}'));
expect((await relay.ask(1, 'route', ROUTE)).status).toBe(502);
expect((await relay.ask(1, 'route', ROUTE)).status).toBe(503);
expect(safeFetchAdminConfigured).toHaveBeenCalledTimes(1);
});
it('RELAY-016: answers 504 for a question that ran out its deadline, and asks the host the next one', async () => {
vi.mocked(safeFetchAdminConfigured).mockRejectedValueOnce(
new DOMException('The operation was aborted due to timeout', 'TimeoutError'),
);
await expect(relay.ask(1, 'route', ROUTE)).rejects.toMatchObject({
status: 504,
message: 'The TREK routing service took too long for this route',
});
vi.mocked(safeFetchAdminConfigured).mockResolvedValueOnce(upstream(504, '{"error":"gateway timeout"}'));
expect((await relay.ask(1, 'route', ROUTE)).status).toBe(504);
vi.mocked(safeFetchAdminConfigured).mockResolvedValueOnce(upstream(200, '{}'));
expect((await relay.ask(1, 'route', ROUTE)).status).toBe(200);
expect(safeFetchAdminConfigured).toHaveBeenCalledTimes(3);
});
it("RELAY-011: follows a spent allowance's Retry-After, at most an hour of it, and passes it on", async () => {
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(new Date('2026-10-29T10:00:00Z'));
+89 -2
View File
@@ -5,13 +5,21 @@
*/
import { afterEach, describe, expect, it, vi } from 'vitest';
const built = vi.hoisted(() => ({ agents: [] as unknown[], proxies: [] as Array<Record<string, unknown>> }));
const built = vi.hoisted(() => ({
agents: [] as unknown[],
proxies: [] as Array<Record<string, unknown>>,
closed: [] as unknown[],
}));
vi.mock('undici', () => ({
Agent: class {
constructor(opts: unknown) {
constructor(readonly opts: unknown) {
built.agents.push(opts);
}
close() {
built.closed.push(this.opts);
return Promise.resolve();
}
},
ProxyAgent: class {
constructor(opts: Record<string, unknown>) {
@@ -33,6 +41,7 @@ afterEach(() => {
for (const key of PROXY_KEYS) delete process.env[key];
built.agents.length = 0;
built.proxies.length = 0;
built.closed.length = 0;
});
describe('proxyFor', () => {
@@ -87,3 +96,81 @@ describe('createOutboundDispatcher', () => {
});
});
});
describe('createOutboundDispatcher, connections kept (the routing relay)', () => {
it('SSRF-KEEP-001: hands the same dispatcher back for the same vetted addresses, held open ten seconds', async () => {
const { createOutboundDispatcher } = await loadGuard({});
const first = createOutboundDispatcher(
'https://valhalla.liketrek.com/route',
['203.0.113.7'],
true,
undefined,
undefined,
true,
);
const again = createOutboundDispatcher(
'https://valhalla.liketrek.com/height',
['203.0.113.7'],
true,
undefined,
undefined,
true,
);
expect(again).toBe(first);
expect(built.agents).toHaveLength(1);
expect(built.agents[0]).toMatchObject({ keepAliveTimeout: 10_000 });
});
it('SSRF-KEEP-002: a name that resolves elsewhere, or other timeouts, get a dispatcher of their own', async () => {
const { createOutboundDispatcher } = await loadGuard({});
const first = createOutboundDispatcher(
'https://valhalla.liketrek.com/',
['203.0.113.7'],
true,
undefined,
undefined,
true,
);
const moved = createOutboundDispatcher(
'https://valhalla.liketrek.com/',
['203.0.113.8'],
true,
undefined,
undefined,
true,
);
const slower = createOutboundDispatcher(
'https://valhalla.liketrek.com/',
['203.0.113.7'],
true,
60_000,
undefined,
true,
);
expect(new Set([first, moved, slower]).size).toBe(3);
// The new address is the one the socket gets, never the old one.
const lookup = (
built.agents[1] as { connect: { lookup: (h: string, o: object, cb: (...a: unknown[]) => void) => void } }
).connect.lookup;
const seen: unknown[] = [];
lookup('valhalla.liketrek.com', {}, (...args: unknown[]) => seen.push(...args));
expect(seen).toContain('203.0.113.8');
expect(seen).not.toContain('203.0.113.7');
});
it('SSRF-KEEP-003: keeps at most 32 and closes the oldest; a caller that does not ask keeps none', async () => {
const { createOutboundDispatcher } = await loadGuard({});
const at = (n: number) =>
createOutboundDispatcher('https://h.example/', [`203.0.113.${n}`], true, undefined, undefined, true);
const oldest = at(0);
for (let n = 1; n <= 32; n++) at(n);
expect(built.closed).toEqual([built.agents[0]]);
expect(at(0)).not.toBe(oldest);
built.agents.length = 0;
createOutboundDispatcher('https://h.example/', ['203.0.113.1']);
createOutboundDispatcher('https://h.example/', ['203.0.113.1']);
expect(built.agents).toHaveLength(2);
expect(built.agents[0]).not.toHaveProperty('keepAliveTimeout');
});
});