fix(tours): keep the Places layers off the search breaker and keep partial way answers

The ways and routes layers now count failures on a breaker of their own, so
busy or slow layer answers no longer send place search to the fallback for a
minute, and a layer's 404 no longer clears the count of search failures.

When a later batch of /v1/ways fails, the batches that answered are kept and
only the ids still open go to the Overpass mirrors.

The wiki, the compose file and the chart now say that the way ids of a planned
tour and the horse routes box go to the TREK Places API.
This commit is contained in:
Maurice
2026-10-20 20:43:23 +02:00
parent 371083ed47
commit d924dcf99d
12 changed files with 248 additions and 67 deletions
@@ -6,7 +6,7 @@ import {
type TrekPlacesMiss,
type TrekPlacesRoutes,
type TrekPlacesRouteType,
type TrekWayTags,
type TrekWaysAnswer,
} from './trek-places.client';
import { Injectable } from '@nestjs/common';
@@ -37,8 +37,16 @@ const WHY: Record<TrekPlacesMiss, string> = {
export class TrekPlacesLayersService {
private readonly told = new Map<Layer, TrekPlacesMiss>();
wayTags(ids: readonly number[]): Promise<TrekPlacesLayerRead<TrekWayTags[]>> {
return this.read('ways', () => trekPlacesWays(ids));
/**
* An answer that stopped part way is still an answer: the caller keeps what
* came and asks elsewhere for the rest. Why it stopped is said like a miss.
*/
wayTags(ids: readonly number[]): Promise<TrekPlacesLayerRead<TrekWaysAnswer>> {
return this.read(
'ways',
() => trekPlacesWays(ids),
(answer) => (answer.complete ? null : { failure: answer.failure }),
);
}
routes(
@@ -49,10 +57,16 @@ export class TrekPlacesLayersService {
return this.read('routes', () => trekPlacesRoutes(bbox, type, limits));
}
private async read<T>(layer: Layer, ask: () => Promise<T>): Promise<TrekPlacesLayerRead<T>> {
private async read<T>(
layer: Layer,
ask: () => Promise<T>,
shortOf: (value: T) => { failure: unknown } | null = () => null,
): Promise<TrekPlacesLayerRead<T>> {
try {
const value = await ask();
this.told.delete(layer);
const short = shortOf(value);
if (short) this.tell(layer, trekPlacesMiss(short.failure), short.failure);
else this.told.delete(layer);
return { ok: true, value };
} catch (err: unknown) {
const miss = trekPlacesMiss(err);
+64 -25
View File
@@ -138,8 +138,23 @@ function instanceToken(): string {
*/
const BREAKER_FAILURES_BEFORE_OPEN = 4;
const BREAKER_COOLDOWN_MS = 60_000;
let breakerFailures = 0;
let breakerOpenUntil = 0;
interface Breaker {
failures: number;
openUntil: number;
}
/**
* Place search (autocomplete, full search, the category pills, the offline
* download, the lookup by id) shares one breaker. The OpenStreetMap layers
* Tours reads have their own: the service answers a heavy layer query with a
* 503 when it interrupts it, and a view of routes may run its full 20 s, so a
* few busy layer answers would otherwise send every keystroke to the fallback
* for a minute although the service is there. The other way round, a layer's
* 404 for "not built yet" would clear the count of real search failures.
*/
const searchBreaker: Breaker = { failures: 0, openUntil: 0 };
const layersBreaker: Breaker = { failures: 0, openUntil: 0 };
/**
* Whether a failure says anything about reachability.
@@ -158,8 +173,10 @@ function countsAgainstReachability(err: unknown): boolean {
/** Test seam: the breaker is process state, so a suite has to be able to clear it. */
export function resetTrekPlacesBreaker(): void {
breakerFailures = 0;
breakerOpenUntil = 0;
for (const breaker of [searchBreaker, layersBreaker]) {
breaker.failures = 0;
breaker.openUntil = 0;
}
}
const SWITCHED_OFF_MESSAGE = 'TREK Places API is switched off on this instance';
@@ -186,8 +203,9 @@ export function trekPlacesBaseUrl(): string {
async function getJson<T>(
path: string,
params: Record<string, string | number | undefined>,
opts: { maxBytes?: number; timeoutMs?: number } = {},
opts: { maxBytes?: number; timeoutMs?: number; breaker?: Breaker } = {},
): Promise<T> {
const breaker = opts.breaker ?? searchBreaker;
// TREK_PLACES_ENABLED=false is the operator's word that nothing leaves for
// the index. Every caller checks it before asking, and this is the one place
// every request passes, so a caller that did not is still stopped here. Ahead
@@ -201,7 +219,7 @@ async function getJson<T>(
if (v !== undefined && v !== null && v !== '') url.searchParams.set(k, String(v));
}
if (Date.now() < breakerOpenUntil) {
if (Date.now() < breaker.openUntil) {
throw new Error('TREK Places API unreachable, not retrying yet');
}
@@ -225,21 +243,21 @@ async function getJson<T>(
const text = await readCapped(res, opts.maxBytes ?? MAX_BYTES);
const parsed = JSON.parse(text) as T;
// An answer of any kind means the service is there.
breakerFailures = 0;
breaker.failures = 0;
return parsed;
} catch (err: unknown) {
if (countsAgainstReachability(err)) {
breakerFailures += 1;
if (breakerFailures >= BREAKER_FAILURES_BEFORE_OPEN) {
breakerOpenUntil = Date.now() + BREAKER_COOLDOWN_MS;
breaker.failures += 1;
if (breaker.failures >= BREAKER_FAILURES_BEFORE_OPEN) {
breaker.openUntil = Date.now() + BREAKER_COOLDOWN_MS;
// Back to the threshold rather than to zero: when the cooldown ends,
// one more failure re-opens the breaker instead of buying another four
// full timeouts.
breakerFailures = BREAKER_FAILURES_BEFORE_OPEN - 1;
breaker.failures = BREAKER_FAILURES_BEFORE_OPEN - 1;
}
} else {
// The service answered. A 404 is an answer.
breakerFailures = 0;
breaker.failures = 0;
}
throw err;
} finally {
@@ -744,7 +762,11 @@ const elementsAnswerSchema = z.object({ elements: z.array(z.unknown()) });
* having no grade.
*/
async function trekPlacesWaysPart(ids: readonly number[]): Promise<TrekWayTags[]> {
const body = await getJson<unknown>('/v1/ways', { ids: ids.join(',') }, { timeoutMs: WAYS_TIMEOUT_MS });
const body = await getJson<unknown>(
'/v1/ways',
{ ids: ids.join(',') },
{ timeoutMs: WAYS_TIMEOUT_MS, breaker: layersBreaker },
);
const answer = elementsAnswerSchema.safeParse(body);
if (!answer.success) throw new Error('TREK Places API answered /v1/ways without elements');
const asked = new Set(ids);
@@ -752,19 +774,36 @@ async function trekPlacesWaysPart(ids: readonly number[]): Promise<TrekWayTags[]
}
/**
* The tags of OpenStreetMap ways by id, from the ways layer. Asked in batches
* of WAYS_MAX_IDS, one after another; the first batch that fails fails the
* whole call, so the caller never mistakes half an answer for all of it.
* What the ways layer answered for a tour: every batch (`complete`), or the
* batches before the one that failed, with the ids that batch and the ones
* after it held, and why it failed. The caller asks another source for those
* ids only, never again for the ways already answered.
*/
export async function trekPlacesWays(ids: readonly number[]): Promise<TrekWayTags[]> {
export type TrekWaysAnswer =
| { complete: true; ways: TrekWayTags[] }
| { complete: false; ways: TrekWayTags[]; unanswered: number[]; failure: unknown };
/**
* The tags of OpenStreetMap ways by id, from the ways layer. Asked in batches
* of WAYS_MAX_IDS, one after another. When the first batch fails the call
* throws, as the layer gave nothing. When a later one fails, nothing more is
* asked (a service that just failed would mostly cost one more deadline per
* batch) and the answer says which ids are still open.
*/
export async function trekPlacesWays(ids: readonly number[]): Promise<TrekWaysAnswer> {
const wanted = [...new Set(ids)].filter((id) => osmIdSchema.safeParse(id).success);
const parts = Array.from({ length: Math.ceil(wanted.length / WAYS_MAX_IDS) }, (_, index) =>
wanted.slice(index * WAYS_MAX_IDS, (index + 1) * WAYS_MAX_IDS),
);
return parts.reduce<Promise<TrekWayTags[]>>(
async (done, part) => [...(await done), ...(await trekPlacesWaysPart(part))],
Promise.resolve([]),
);
const starts = Array.from({ length: Math.ceil(wanted.length / WAYS_MAX_IDS) }, (_, index) => index * WAYS_MAX_IDS);
return starts.reduce<Promise<TrekWaysAnswer>>(async (previous, start) => {
const done = await previous;
if (!done.complete) return done;
try {
const part = await trekPlacesWaysPart(wanted.slice(start, start + WAYS_MAX_IDS));
return { complete: true, ways: [...done.ways, ...part] };
} catch (failure: unknown) {
if (start === 0) throw failure;
return { complete: false, ways: done.ways, unanswered: wanted.slice(start), failure };
}
}, Promise.resolve<TrekWaysAnswer>({ complete: true, ways: [] }));
}
/**
@@ -786,7 +825,7 @@ export async function trekPlacesRoutes(
limitRelations: clampedInt(limits.relations, 1, ROUTES_MAX_RELATIONS),
limitWays: clampedInt(limits.ways, 1, ROUTES_MAX_WAYS),
},
{ maxBytes: ROUTES_MAX_BYTES, timeoutMs: ROUTES_TIMEOUT_MS },
{ maxBytes: ROUTES_MAX_BYTES, timeoutMs: ROUTES_TIMEOUT_MS, breaker: layersBreaker },
);
const answer = elementsAnswerSchema.extend({ truncated: z.unknown() }).safeParse(body);
if (!answer.success) throw new Error('TREK Places API answered /v1/routes without elements');
@@ -104,17 +104,20 @@ export class TourTrailGradeService {
/**
* Reads the grades of the ways not kept yet into what is kept: from the ways
* layer in one go, else from the mirrors part by part. Gives back the ways
* no source answered.
* layer first, then from the mirrors part by part for the ways the layer
* did not answer (all of them when it gave nothing, only the rest when it
* stopped part way). Gives back the ways no source answered.
*/
private async read(ids: number[], now: number): Promise<number[]> {
const layer = await this.layers.wayTags(ids);
let rest = ids;
if (layer.ok) {
this.keepAll(ids, layer.value, now);
return [];
const open = new Set(layer.value.complete ? [] : layer.value.unanswered);
this.keepAll(ids.filter((id) => !open.has(id)), layer.value.ways, now);
rest = ids.filter((id) => open.has(id));
}
const parts = Array.from({ length: Math.ceil(ids.length / WAYS_PER_QUERY) }, (_, index) =>
ids.slice(index * WAYS_PER_QUERY, (index + 1) * WAYS_PER_QUERY),
const parts = Array.from({ length: Math.ceil(rest.length / WAYS_PER_QUERY) }, (_, index) =>
rest.slice(index * WAYS_PER_QUERY, (index + 1) * WAYS_PER_QUERY),
);
// One question after another, so a long tour does not flood the shared mirrors.
return parts.reduce<Promise<number[]>>(async (done, part) => {
+4 -1
View File
@@ -325,7 +325,10 @@ describe('Bike tours e2e (real guards + temp SQLite)', () => {
overpassQuery.mockReset();
placesWayTags.mockResolvedValueOnce({
ok: true,
value: [{ type: 'way', id: 21, tags: { 'mtb:scale': '1', surface: 'gravel', highway: 'track' } }],
value: {
complete: true,
ways: [{ type: 'way', id: 21, tags: { 'mtb:scale': '1', surface: 'gravel', highway: 'track' } }],
},
});
const res = await ask({ way_ids: [21, 22] }, VIEWER);
expect(res.status).toBe(200);
@@ -5,7 +5,7 @@ import { Test } from '@nestjs/testing';
import { beforeEach, describe, expect, it, vi } from 'vitest';
// TOUR-GRADE-001 to TOUR-GRADE-016
// TOUR-GRADE-001 to TOUR-GRADE-017
const query = vi.fn<(q: string, caller: string) => Promise<unknown[]>>();
const wayTags = vi.fn<TrekPlacesLayersService['wayTags']>();
@@ -158,10 +158,13 @@ describe('TourTrailGradeService (BIK-05)', () => {
it('TOUR-GRADE-011: reads the ways from the TREK Places ways layer first and asks no mirror', async () => {
wayTags.mockResolvedValue({
ok: true,
value: [
{ type: 'way', id: 1, tags: { 'mtb:scale': '2', sac_scale: 'hiking', surface: 'gravel', highway: 'path' } },
{ type: 'way', id: 2, tags: { highway: 'track' } },
],
value: {
complete: true,
ways: [
{ type: 'way', id: 1, tags: { 'mtb:scale': '2', sac_scale: 'hiking', surface: 'gravel', highway: 'path' } },
{ type: 'way', id: 2, tags: { highway: 'track' } },
],
},
});
const answer = await service.grades({ way_ids: [1, 2, 3, 1] });
expect(wayTags).toHaveBeenCalledWith([1, 2, 3]);
@@ -184,7 +187,10 @@ describe('TourTrailGradeService (BIK-05)', () => {
});
it('TOUR-GRADE-012: hands a long tour to the layer whole, which asks it in batches itself', async () => {
wayTags.mockResolvedValue({ ok: true, value: [{ type: 'way', id: 900, tags: { 'mtb:scale': '5' } }] });
wayTags.mockResolvedValue({
ok: true,
value: { complete: true, ways: [{ type: 'way', id: 900, tags: { 'mtb:scale': '5' } }] },
});
const ids = Array.from({ length: 900 }, (_, index) => index + 1);
const answer = await service.grades({ way_ids: ids });
expect(wayTags).toHaveBeenCalledTimes(1);
@@ -215,7 +221,10 @@ describe('TourTrailGradeService (BIK-05)', () => {
it('TOUR-GRADE-015: keeps what the layer answered a day, a way it left out as having no grade', async () => {
vi.useFakeTimers();
try {
wayTags.mockResolvedValue({ ok: true, value: [{ type: 'way', id: 1, tags: { 'mtb:scale': '3' } }] });
wayTags.mockResolvedValue({
ok: true,
value: { complete: true, ways: [{ type: 'way', id: 1, tags: { 'mtb:scale': '3' } }] },
});
expect(await service.grades({ way_ids: [1, 2] })).toMatchObject({ unanswered: [] });
expect(await service.grades({ way_ids: [2, 1] })).toMatchObject({ ways: [{ id: 1 }], unanswered: [] });
expect(wayTags).toHaveBeenCalledTimes(1);
@@ -232,8 +241,36 @@ describe('TourTrailGradeService (BIK-05)', () => {
wayTags.mockResolvedValue({
ok: true,
// Typed rows from the client, but read through the same check as the mirrors' answer.
value: [{ type: 'way', id: 0, tags: { 'mtb:scale': '1' } }],
value: { complete: true, ways: [{ type: 'way', id: 0, tags: { 'mtb:scale': '1' } }] },
});
expect(await service.grades({ way_ids: [1] })).toEqual({ ways: [], unanswered: [] });
});
it('TOUR-GRADE-017: a layer that stopped part way keeps what it answered and asks the mirrors only for the rest', async () => {
const ids = Array.from({ length: 1000 }, (_, index) => index + 1);
const rest = ids.slice(500);
wayTags.mockResolvedValue({
ok: true,
value: {
complete: false,
ways: [{ type: 'way', id: 7, tags: { 'mtb:scale': '2' } }],
unanswered: rest,
failure: new Error('TREK Places API 503'),
},
});
query.mockResolvedValueOnce([way(600, { surface: 'gravel' })]).mockRejectedValueOnce(new Error('all mirrors down'));
const answer = await service.grades({ way_ids: ids });
// 500 ways left in parts of 400: two questions, none of them naming a way the layer answered.
expect(query).toHaveBeenCalledTimes(2);
expect(query.mock.calls[0]?.[0]).toBe(`[out:json][timeout:25];way(id:${rest.slice(0, 400).join(',')});out tags;`);
expect(query.mock.calls[1]?.[0]).toBe(`[out:json][timeout:25];way(id:${rest.slice(400).join(',')});out tags;`);
expect(answer.ways.map((grade) => grade.id)).toEqual([7, 600]);
expect(answer.unanswered).toEqual(rest.slice(400));
// The ways the layer answered are kept: asked again, nothing goes out for them.
query.mockClear();
wayTags.mockClear();
await service.grades({ way_ids: ids.slice(0, 500) });
expect(wayTags).not.toHaveBeenCalled();
expect(query).not.toHaveBeenCalled();
});
});
@@ -11,7 +11,7 @@ import { Test } from '@nestjs/testing';
import { beforeEach, describe, expect, it, vi } from 'vitest';
// TREK-LAYERS-001 to TREK-LAYERS-006
// TREK-LAYERS-001 to TREK-LAYERS-007
vi.mock('../../../src/nest/audit/audit-log.logger', () => ({
LOG_LEVEL: 'error',
@@ -54,11 +54,11 @@ beforeEach(async () => {
describe('TrekPlacesLayersService', () => {
it('TREK-LAYERS-001: hands on what a layer answered, asked as the caller asked', async () => {
ways.mockResolvedValue([{ type: 'way', id: 1, tags: { highway: 'path' } }]);
ways.mockResolvedValue({ complete: true, ways: [{ type: 'way', id: 1, tags: { highway: 'path' } }] });
routes.mockResolvedValue({ elements: [], truncated: true });
expect(await service.wayTags([1, 2])).toEqual({
ok: true,
value: [{ type: 'way', id: 1, tags: { highway: 'path' } }],
value: { complete: true, ways: [{ type: 'way', id: 1, tags: { highway: 'path' } }] },
});
expect(await service.routes(BOX, 'horse', CAPS)).toEqual({ ok: true, value: { elements: [], truncated: true } });
expect(ways).toHaveBeenCalledWith([1, 2]);
@@ -103,9 +103,12 @@ describe('TrekPlacesLayersService', () => {
});
it('TREK-LAYERS-005: after a layer answered, the same failure is said again', async () => {
ways.mockRejectedValueOnce(down()).mockResolvedValueOnce([]).mockRejectedValueOnce(down());
ways
.mockRejectedValueOnce(down())
.mockResolvedValueOnce({ complete: true, ways: [] })
.mockRejectedValueOnce(down());
await service.wayTags([1]);
expect(await service.wayTags([1])).toEqual({ ok: true, value: [] });
expect(await service.wayTags([1])).toEqual({ ok: true, value: { complete: true, ways: [] } });
await service.wayTags([1]);
expect(warn).toHaveBeenCalledTimes(2);
});
@@ -119,4 +122,25 @@ describe('TrekPlacesLayersService', () => {
await service.routes(BOX, 'horse', CAPS);
expect(info.mock.calls.map(([line]) => line.includes('/v1/ways'))).toEqual([true, false]);
});
it('TREK-LAYERS-007: an answer that stopped part way is handed on, and why it stopped is said once', async () => {
const partial = {
complete: false as const,
ways: [{ type: 'way' as const, id: 1, tags: {} }],
unanswered: [501, 502],
failure: down(),
};
ways.mockResolvedValue(partial);
expect(await service.wayTags([1, 501, 502])).toEqual({ ok: true, value: partial });
await service.wayTags([1, 501, 502]);
expect(warn).toHaveBeenCalledTimes(1);
expect(warn.mock.calls[0]?.[0]).toContain('/v1/ways');
expect(warn.mock.calls[0]?.[0]).toContain('TREK Places API 503');
// A whole answer in between clears it, so the next stop is said again.
ways.mockResolvedValueOnce({ complete: true, ways: [] });
await service.wayTags([1]);
await service.wayTags([1, 501, 502]);
expect(warn).toHaveBeenCalledTimes(2);
expect(info).not.toHaveBeenCalled();
});
});
@@ -878,7 +878,7 @@ describe('indexRowTerm (#2663)', () => {
});
});
// TREK-PLACES-WAYS-01 to 05, TREK-PLACES-ROUTES-01 to 05, TREK-PLACES-MISS-01
// TREK-PLACES-WAYS-01 to 06, TREK-PLACES-ROUTES-01 to 05, TREK-PLACES-MISS-01, TREK-PLACES-BREAKER-01 to 03
/** A fetch answering each call with the next of `answers`, the last one again once they run out. */
function stubFetchSequence(answers: { body: unknown; status?: number }[]) {
@@ -911,17 +911,20 @@ describe('trekPlacesWays', () => {
missing: [13],
keys: ['highway', 'mtb:scale'],
});
const ways = await trekPlacesWays([11, 12, 13]);
const answer = await trekPlacesWays([11, 12, 13]);
const url = new URL(calls[0].url);
expect(url.pathname).toBe('/v1/ways');
expect(url.searchParams.get('ids')).toBe('11,12,13');
expect((calls[0].init?.headers as Record<string, string>)['X-TREK-Instance']).toMatch(/^trek-/);
expect(calls[0].init?.signal).toBeInstanceOf(AbortSignal);
// A way without tags reads as one without tags, never as a malformed row.
expect(ways).toEqual([
{ type: 'way', id: 11, tags: { 'mtb:scale': '2', highway: 'path' } },
{ type: 'way', id: 12, tags: {} },
]);
expect(answer).toEqual({
complete: true,
ways: [
{ type: 'way', id: 11, tags: { 'mtb:scale': '2', highway: 'path' } },
{ type: 'way', id: 12, tags: {} },
],
});
});
it('TREK-PLACES-WAYS-02: asks in batches of 500, one after another, each id once, and nothing for no id', async () => {
@@ -932,8 +935,8 @@ describe('trekPlacesWays', () => {
expect(askedIds(calls[0])?.startsWith('1,2,3,')).toBe(true);
expect(askedIds(calls[2])?.endsWith(',1200')).toBe(true);
calls = [];
await expect(trekPlacesWays([])).resolves.toEqual([]);
await expect(trekPlacesWays([0, -1])).resolves.toEqual([]);
await expect(trekPlacesWays([])).resolves.toEqual({ complete: true, ways: [] });
await expect(trekPlacesWays([0, -1])).resolves.toEqual({ complete: true, ways: [] });
expect(calls).toHaveLength(0);
});
@@ -947,7 +950,7 @@ describe('trekPlacesWays', () => {
'row',
],
});
expect(await trekPlacesWays([1, 2, 3])).toEqual([{ type: 'way', id: 1, tags: { surface: 'gravel' } }]);
expect((await trekPlacesWays([1, 2, 3])).ways).toEqual([{ type: 'way', id: 1, tags: { surface: 'gravel' } }]);
});
it('TREK-PLACES-WAYS-04: an answer without elements fails rather than reading as ways without tags', async () => {
@@ -957,12 +960,27 @@ describe('trekPlacesWays', () => {
await expect(trekPlacesWays([1])).rejects.toThrow('without elements');
});
it('TREK-PLACES-WAYS-05: a batch that fails fails the call and asks no further, and the off switch asks nothing', async () => {
stubFetchSequence([{ body: { elements: [] } }, { body: {}, status: 503 }, { body: { elements: [] } }]);
it('TREK-PLACES-WAYS-05: a later batch that fails stops there and names the ids still open', async () => {
stubFetchSequence([
{ body: { elements: [{ type: 'way', id: 2, tags: { surface: 'gravel' } }] } },
{ body: { detail: 'busy' }, status: 503 },
{ body: { elements: [] } },
]);
const ids = Array.from({ length: 1400 }, (_, index) => index + 1);
const answer = await trekPlacesWays(ids);
expect(calls).toHaveLength(2);
if (answer.complete) throw new Error('expected an answer that stopped part way');
expect(answer.ways).toEqual([{ type: 'way', id: 2, tags: { surface: 'gravel' } }]);
expect(answer.unanswered).toEqual(ids.slice(500));
expect(trekPlacesMiss(answer.failure)).toBe('failed');
});
it('TREK-PLACES-WAYS-06: a first batch that fails fails the call and asks no further, and the off switch asks nothing', async () => {
stubFetchSequence([{ body: {}, status: 503 }, { body: { elements: [] } }]);
const ids = Array.from({ length: 1400 }, (_, index) => index + 1);
const failure = await trekPlacesWays(ids).catch((err: unknown) => err);
expect(trekPlacesMiss(failure)).toBe('failed');
expect(calls).toHaveLength(2);
expect(calls).toHaveLength(1);
stubFetch({}, 404);
expect(trekPlacesMiss(await trekPlacesWays([1]).catch((err: unknown) => err))).toBe('not_built');
env.maps.trekPlacesEnabled = false;
@@ -1064,3 +1082,39 @@ describe('trekPlacesMiss', () => {
expect(trekPlacesMiss('nope')).toBe('failed');
});
});
describe('the layers breaker', () => {
const VIEW = { south: 47.1, west: 11.2, north: 47.2, east: 11.3 };
const CAPS = { relations: 60, ways: 4000 };
it('TREK-PLACES-BREAKER-01: busy layer answers never stop place search', async () => {
stubFetch({ detail: 'busy' }, 503);
for (let i = 0; i < 4; i++) {
await expect(trekPlacesRoutes(VIEW, 'horse', CAPS)).rejects.toThrow(/503/);
}
stubFetch({ query: 'x', results: [PLACE] });
await expect(trekPlacesSearch('x')).resolves.toHaveLength(1);
expect(calls).toHaveLength(1);
});
it('TREK-PLACES-BREAKER-02: the layers stop dialling on their own after a few failures', async () => {
stubFetch({ detail: 'busy' }, 503);
for (let i = 0; i < 4; i++) await expect(trekPlacesWays([1])).rejects.toThrow(/503/);
const dialled = calls.length;
await expect(trekPlacesRoutes(VIEW, 'horse', CAPS)).rejects.toThrow('unreachable, not retrying yet');
await expect(trekPlacesWays([1])).rejects.toThrow('unreachable, not retrying yet');
expect(calls).toHaveLength(dialled);
});
it('TREK-PLACES-BREAKER-03: a layer not built yet does not clear the count of search failures', async () => {
stubFetch({}, 503);
for (let i = 0; i < 3; i++) await expect(trekPlacesSearch('x')).rejects.toThrow(/503/);
stubFetch({ detail: 'not built' }, 404);
await expect(trekPlacesWays([1])).rejects.toThrow(/404/);
stubFetch({}, 503);
await expect(trekPlacesSearch('x')).rejects.toThrow(/503/);
calls = [];
await expect(trekPlacesSearch('x')).rejects.toThrow('unreachable, not retrying yet');
expect(calls).toHaveLength(0);
});
});