Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

fix(tours): let a failed search along the tour really ask again, with a probing breaker, hedged mirrors and a countdown

Mauricebf2efca8f078
diff --git a/client/src/api/tourPoiSearch.ts b/client/src/api/tourPoiSearch.ts
index 832277672..1a85c1093 100644
--- a/client/src/api/tourPoiSearch.ts
+++ b/client/src/api/tourPoiSearch.ts
@@ -4,9 +4,10 @@ import apiClient from './client';
/**
* PLN-02: places along a tour. A search runs several stretches against the map
* search on the server, each allowed its own timeout there, so it may take
- * longer than the shared default.
+ * longer than the shared default: up to three rounds of stretches, each asking
+ * the Overpass mirrors one after another for about twenty seconds at most.
*/
-const POI_SEARCH_TIMEOUT_MS = 60_000;
+const POI_SEARCH_TIMEOUT_MS = 75_000;
export const tourPoiSearchApi = {
search: (tripId: number | string, body: TourPoiSearchRequest, signal?: AbortSignal): Promise<TourPoiSearchResponse> =>
diff --git a/client/src/components/Tours/poi/TourPoiSearchCard.tsx b/client/src/components/Tours/poi/TourPoiSearchCard.tsx
index 14e06c16f..b5871b654 100644
--- a/client/src/components/Tours/poi/TourPoiSearchCard.tsx
+++ b/client/src/components/Tours/poi/TourPoiSearchCard.tsx
@@ -1,7 +1,6 @@
import type { TourPoi, WalkTheme } from '@trek/shared';
import { TOUR_POI_CORRIDORS_M } from '@trek/shared';
import {
- AlertTriangle,
ChevronDown,
Coffee,
Landmark,
@@ -13,7 +12,6 @@ import {
Star,
Trees,
Undo2,
- WifiOff,
X,
type LucideIcon,
} from 'lucide-react';
@@ -31,6 +29,7 @@ import { usePopoverList } from '../../shared/usePopoverList';
import type { TourPlannerController } from '../planner/useTourPlanner';
import { RailCard, TourNotice } from '../tourParts';
import { formatPlannedTourDuration } from '../tourPresentation';
+import { SearchNotices } from './TourPoiSearchNotices';
import { usePoiInsertion, type InsertionOutcome } from './usePoiInsertion';
import { useSelectedPoi, useTourPoiSearch, type TourPoiSearch } from './useTourPoiSearch';
@@ -151,47 +150,6 @@ function ThemeGrid({
);
}
-/**
- * What the search answered beyond its places: offline, failed, kinds that
- * could not be searched, partly searched, cut, or empty. That the answer is
- * out of date the search button says, as it is what to press then. Nothing
- * found is said only when every kind was searched.
- */
-function SearchNotices({ search, unit }: { search: TourPoiSearch; unit: Unit }) {
- const { t } = useTranslation();
- const { status, answer } = search;
- if (status === 'offline')
- return <TourNotice icon={<WifiOff size={13} strokeWidth={2} />}>{t('tours.poi.offline')}</TourNotice>;
- if (status === 'error')
- return (
- <TourNotice tone="warning" icon={<AlertTriangle size={13} strokeWidth={2} />}>
- {t('tours.poi.failed')}
- </TourNotice>
- );
- if (!answer) return null;
- const unavailable = answer.unavailable.map((category) => t(TOUR_POI_LOOKS[category].labelKey)).join(', ');
- const notes = [
- unavailable && t('tours.poi.unavailable', { kinds: unavailable }),
- answer.partial && t('tours.poi.partial'),
- answer.capped && t('tours.poi.capped'),
- answer.truncated && t('tours.poi.truncated'),
- ].filter((note): note is string => !!note);
- return (
- <>
- {notes.map((note) => (
- <TourNotice key={note} tone="warning" icon={<AlertTriangle size={13} strokeWidth={2} />}>
- {note}
- </TourNotice>
- ))}
- {answer.pois.length === 0 && answer.unavailable.length === 0 && (
- <p className="m-0 text-content-muted" style={fs(12, 'body')}>
- {t('tours.poi.empty', { distance: formatDistance(km(search.corridorM), unit) })}
- </p>
- )}
- </>
- );
-}
-
/**
* One place found, in one line: its kind's icon in its map colour, its name,
* and how far it lies from the route. A click opens its card over the map,
diff --git a/client/src/components/Tours/poi/TourPoiSearchNotices.tsx b/client/src/components/Tours/poi/TourPoiSearchNotices.tsx
new file mode 100644
index 000000000..092840368
--- /dev/null
+++ b/client/src/components/Tours/poi/TourPoiSearchNotices.tsx
@@ -0,0 +1,115 @@
+import { AlertTriangle, Expand, RefreshCw, WifiOff } from 'lucide-react';
+import { useTranslation } from '../../../i18n';
+import { formatDistance } from '../../../utils/units';
+import { TOUR_POI_LOOKS } from '../../Map/poiCategories';
+import { fs } from '../../shared/DialogShell';
+import { Tooltip } from '../../shared/Tooltip';
+import { TourNotice } from '../tourParts';
+import type { TourPoiSearch } from './useTourPoiSearch';
+
+type Unit = Parameters<typeof formatDistance>[1];
+
+const km = (metres: number) => metres / 1000;
+
+/** Seconds as a clock, 0:17 or 1:05. */
+const clock = (seconds: number) => `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`;
+
+/**
+ * PLN-05: the search sent again from the notice that says why. While the wait
+ * the server named runs it counts down instead, and says what it waits for.
+ */
+function RetryButton({ search }: { search: TourPoiSearch }) {
+ const { t } = useTranslation();
+ const waiting = search.retryInS > 0;
+ const loading = search.status === 'loading';
+ const held = waiting || loading;
+ const button = (
+ <button
+ type="button"
+ onClick={() => {
+ if (!held) void search.search();
+ }}
+ aria-disabled={held || undefined}
+ data-testid="tour-poi-retry"
+ className={`inline-flex flex-none items-center gap-1 rounded-full px-1.5 font-semibold tabular-nums text-current ${held ? 'cursor-default opacity-60' : 'hover:bg-surface-hover'}`}
+ style={fs(11.5, 'body')}
+ >
+ <RefreshCw size={12} strokeWidth={2.2} aria-hidden="true" className={loading ? 'animate-spin' : ''} />
+ {waiting ? t('tours.poi.retryIn', { time: clock(search.retryInS) }) : t('tours.poi.retry')}
+ </button>
+ );
+ return waiting ? (
+ <Tooltip label={t('tours.poi.retryHint')} placement="top">
+ {button}
+ </Tooltip>
+ ) : (
+ button
+ );
+}
+
+/** A warning of the search, with the way to send it again where that may help. */
+function WarningNotice({ text, search }: { text: string; search?: TourPoiSearch }) {
+ return (
+ <TourNotice tone="warning" icon={<AlertTriangle size={13} strokeWidth={2} />}>
+ {search ? (
+ <span className="flex flex-wrap items-center gap-x-1.5 gap-y-1">
+ <span>{text}</span>
+ <RetryButton search={search} />
+ </span>
+ ) : (
+ text
+ )}
+ </TourNotice>
+ );
+}
+
+/**
+ * What the search answered beyond its places: offline, failed, kinds that
+ * could not be searched, partly searched, cut, or empty. That the answer is
+ * out of date the search button says, as it is what to press then. Nothing
+ * found is said only when every kind was searched, with the next wider
+ * corridor one press away; a failure or a gap carries its own retry.
+ */
+export function SearchNotices({ search, unit }: { search: TourPoiSearch; unit: Unit }) {
+ const { t } = useTranslation();
+ const { status, answer } = search;
+ if (status === 'offline')
+ return <TourNotice icon={<WifiOff size={13} strokeWidth={2} />}>{t('tours.poi.offline')}</TourNotice>;
+ if (status === 'error') return <WarningNotice text={t('tours.poi.failed')} search={search} />;
+ if (!answer) return null;
+ const unavailable = answer.unavailable.map((category) => t(TOUR_POI_LOOKS[category].labelKey)).join(', ');
+ const notes = [
+ { text: unavailable && t('tours.poi.unavailable', { kinds: unavailable }), retry: true },
+ { text: answer.partial && t('tours.poi.partial'), retry: !unavailable },
+ { text: answer.capped && t('tours.poi.capped'), retry: false },
+ { text: answer.truncated && t('tours.poi.truncated'), retry: false },
+ ].filter((note): note is { text: string; retry: boolean } => !!note.text);
+ const wider = search.widerCorridorM;
+ return (
+ <>
+ {notes.map((note) => (
+ <WarningNotice key={note.text} text={note.text} search={note.retry ? search : undefined} />
+ ))}
+ {answer.pois.length === 0 && answer.unavailable.length === 0 && (
+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1.5">
+ <p className="m-0 text-content-muted" style={fs(12, 'body')}>
+ {t('tours.poi.empty', { distance: formatDistance(km(search.corridorM), unit) })}
+ </p>
+ {wider !== null && (
+ <button
+ type="button"
+ onClick={search.widen}
+ disabled={!search.canSearch}
+ data-testid="tour-poi-widen"
+ className="inline-flex items-center gap-1 rounded-full border border-edge bg-surface-card px-2 py-0.5 font-medium text-content hover:bg-surface-hover disabled:cursor-default disabled:opacity-50"
+ style={fs(11.5, 'body')}
+ >
+ <Expand size={11} strokeWidth={2.2} aria-hidden="true" />
+ {t('tours.poi.widen', { distance: formatDistance(km(wider), unit) })}
+ </button>
+ )}
+ </div>
+ )}
+ </>
+ );
+}
diff --git a/client/src/components/Tours/poi/tourPoiSearch.test.tsx b/client/src/components/Tours/poi/tourPoiSearch.test.tsx
index 418fb5f9c..1499971a6 100644
--- a/client/src/components/Tours/poi/tourPoiSearch.test.tsx
+++ b/client/src/components/Tours/poi/tourPoiSearch.test.tsx
@@ -14,7 +14,7 @@ import { usePoiInsertion, type PoiInsertionPlanner } from './usePoiInsertion';
import { useTourPoiMarkers } from './useTourPoiMarkers';
import { useTourPoiSearch } from './useTourPoiSearch';
-// FE-TOUR-POI-001 to FE-TOUR-POI-022
+// FE-TOUR-POI-001 to FE-TOUR-POI-026
vi.mock('../planner/useWaypointPlaceNames', () => ({ useWaypointPlaceNames: () => ({}) }));
@@ -519,15 +519,13 @@ describe('choosing where a found place goes (PLN-04)', () => {
it('FE-TOUR-POI-021: the notice of what was added takes it back with undo, only while that is the last step', async () => {
const added: TourPlannerWaypoint = { id: 'new', lat: SPRING.lat, lng: SPRING.lng, role: 'end' };
const withPoint = [PA, PB, { ...PC, role: 'via' as const }, added];
- useTourPoiStore
- .getState()
- .setInserted({
- pointId: 'new',
- name: 'Spring',
- before: { distanceM: 2200, minutes: 40 },
- pointCount: 4,
- mark: 0,
- });
+ useTourPoiStore.getState().setInserted({
+ pointId: 'new',
+ name: 'Spring',
+ before: { distanceM: 2200, minutes: 40 },
+ pointCount: 4,
+ mark: 0,
+ });
const planner = alongPlanner({ waypoints: withPoint, distanceMeters: 2900, walkingDurationMinutes: 52 });
const { unmount } = render(<TourPoiSearchCard planner={planner} />);
const notice = screen.getByTestId('tour-poi-outcome');
@@ -538,15 +536,13 @@ describe('choosing where a found place goes (PLN-04)', () => {
unmount();
// With nothing to undo, or no right to edit, the notice offers no way back.
- useTourPoiStore
- .getState()
- .setInserted({
- pointId: 'new',
- name: 'Spring',
- before: { distanceM: 2200, minutes: 40 },
- pointCount: 4,
- mark: 0,
- });
+ useTourPoiStore.getState().setInserted({
+ pointId: 'new',
+ name: 'Spring',
+ before: { distanceM: 2200, minutes: 40 },
+ pointCount: 4,
+ mark: 0,
+ });
render(<TourPoiSearchCard planner={alongPlanner({ waypoints: withPoint, canUndo: false })} />);
expect(screen.getByTestId('tour-poi-outcome')).toBeInTheDocument();
expect(screen.queryByTestId('tour-poi-undo')).not.toBeInTheDocument();
@@ -570,3 +566,94 @@ describe('choosing where a found place goes (PLN-04)', () => {
expect(result.current.undo).toBeNull();
});
});
+
+describe('a search that could not ask, and its retry (PLN-05)', () => {
+ const NO_VIEWPOINTS: TourPoiSearchResponse = { ...ANSWER, pois: [], unavailable: ['viewpoint'] };
+
+ it('FE-TOUR-POI-023: counts down the wait the server named with the viewpoints it could not search, then asks afresh', async () => {
+ vi.useFakeTimers({ toFake: ['Date', 'setInterval', 'clearInterval'] });
+ try {
+ search.mockResolvedValueOnce({ ...NO_VIEWPOINTS, retry_after_s: 3 });
+ const { result } = renderHook(() => useTourPoiSearch(searchPlanner()));
+ await act(() => result.current.search());
+ expect(result.current.answer?.unavailable).toEqual(['viewpoint']);
+ expect(result.current.retryInS).toBe(3);
+ act(() => {
+ vi.advanceTimersByTime(1000);
+ });
+ expect(result.current.retryInS).toBe(2);
+ act(() => {
+ vi.advanceTimersByTime(2000);
+ });
+ expect(result.current.retryInS).toBe(0);
+
+ await act(() => result.current.search());
+ expect(search).toHaveBeenCalledTimes(2);
+ expect(search.mock.calls[1]?.[1]).toEqual(search.mock.calls[0]?.[1]);
+ expect(result.current.answer).toEqual(ANSWER);
+ expect(result.current.retryInS).toBe(0);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('FE-TOUR-POI-024: Try again beside the viewpoints asks afresh, and its places replace the note, the tour untouched', async () => {
+ search.mockResolvedValueOnce(NO_VIEWPOINTS).mockResolvedValueOnce(ANSWER);
+ const planner = { ...searchPlanner(), ...insertionPlanner() } as unknown as TourPlannerController;
+ render(<TourPoiSearchCard planner={planner} />);
+ fireEvent.click(screen.getByTestId('tour-poi-search'));
+
+ const retry = await screen.findByTestId('tour-poi-retry');
+ expect(retry).toHaveTextContent('Try again');
+ expect(screen.getByText(/Could not be searched right now: Viewpoints/)).toBeInTheDocument();
+ expect(screen.queryByText(/Nothing found/)).not.toBeInTheDocument();
+ fireEvent.click(retry);
+
+ expect(await screen.findByTestId('tour-poi-node:1')).toBeInTheDocument();
+ expect(search).toHaveBeenCalledTimes(2);
+ expect(search.mock.calls[1]?.[1]).toMatchObject({
+ corridor_m: 500,
+ categories: expect.arrayContaining(['viewpoint']),
+ });
+ expect(screen.queryByText(/Could not be searched/)).not.toBeInTheDocument();
+ expect(screen.queryByTestId('tour-poi-retry')).not.toBeInTheDocument();
+ expect(planner.editWaypoints).not.toHaveBeenCalled();
+ });
+
+ it('FE-TOUR-POI-025: a failed request keeps a retry that works, one held by a named wait does not ask early', async () => {
+ search
+ .mockRejectedValueOnce(new Error('502'))
+ .mockResolvedValueOnce({ ...NO_VIEWPOINTS, retry_after_s: 20 })
+ .mockResolvedValueOnce(ANSWER);
+ render(<TourPoiSearchCard planner={searchPlanner()} />);
+ fireEvent.click(screen.getByTestId('tour-poi-search'));
+ expect(await screen.findByText('The search did not work. Try again in a moment.')).toBeInTheDocument();
+
+ fireEvent.click(screen.getByTestId('tour-poi-retry'));
+ await waitFor(() => expect(screen.getByTestId('tour-poi-retry')).toHaveTextContent('Again in 0:20'));
+ const held = screen.getByTestId('tour-poi-retry');
+ expect(held).toHaveAttribute('aria-disabled', 'true');
+ fireEvent.click(held);
+ expect(search).toHaveBeenCalledTimes(2);
+ // The search button itself is never held: changed choices are asked at once.
+ expect(screen.getByTestId('tour-poi-search')).toBeEnabled();
+ });
+
+ it('FE-TOUR-POI-026: nothing found offers the next wider corridor in one press, and none past the widest', async () => {
+ search.mockResolvedValue({ ...ANSWER, pois: [] });
+ render(<TourPoiSearchCard planner={searchPlanner()} />);
+ fireEvent.click(screen.getByTestId('tour-poi-search'));
+ expect(await screen.findByText(/Nothing found within/)).toBeInTheDocument();
+
+ fireEvent.click(screen.getByTestId('tour-poi-widen'));
+ await waitFor(() => expect(search).toHaveBeenCalledTimes(2));
+ expect(search.mock.calls[1]?.[1]).toMatchObject({ corridor_m: 1000 });
+ await waitFor(() => expect(screen.getByTestId('tour-poi-search')).not.toHaveAttribute('data-outdated'));
+
+ fireEvent.click(await screen.findByTestId('tour-poi-widen'));
+ await waitFor(() => expect(search).toHaveBeenCalledTimes(3));
+ expect(search.mock.calls[2]?.[1]).toMatchObject({ corridor_m: 2000 });
+ await waitFor(() => expect(screen.getByTestId('tour-poi-search')).toBeEnabled());
+ expect(screen.queryByTestId('tour-poi-widen')).not.toBeInTheDocument();
+ });
+});
diff --git a/client/src/components/Tours/poi/useRetryCountdown.ts b/client/src/components/Tours/poi/useRetryCountdown.ts
new file mode 100644
index 000000000..db6af384b
--- /dev/null
+++ b/client/src/components/Tours/poi/useRetryCountdown.ts
@@ -0,0 +1,28 @@
+import { useCallback, useEffect, useState } from 'react';
+
+/**
+ * PLN-05: the seconds until asking again makes sense, as the server named
+ * them with an answer, counted down once a second to zero. Starting it with
+ * nothing clears it.
+ */
+export function useRetryCountdown() {
+ const [retry, setRetry] = useState<{ at: number; remaining: number } | null>(null);
+ const at = retry?.at ?? null;
+
+ useEffect(() => {
+ if (at === null) return;
+ const timer = setInterval(() => {
+ const remaining = Math.max(0, Math.ceil((at - Date.now()) / 1000));
+ setRetry((current) => (current?.at === at ? { at, remaining } : current));
+ if (remaining === 0) clearInterval(timer);
+ }, 1000);
+ return () => clearInterval(timer);
+ }, [at]);
+
+ const start = useCallback(
+ (seconds?: number) => setRetry(seconds ? { at: Date.now() + seconds * 1000, remaining: seconds } : null),
+ []
+ );
+
+ return { secondsLeft: retry?.remaining ?? 0, start };
+}
diff --git a/client/src/components/Tours/poi/useTourPoiSearch.ts b/client/src/components/Tours/poi/useTourPoiSearch.ts
index 022fd0cee..1feeef9fe 100644
--- a/client/src/components/Tours/poi/useTourPoiSearch.ts
+++ b/client/src/components/Tours/poi/useTourPoiSearch.ts
@@ -1,5 +1,6 @@
import {
TOUR_POI_CATEGORIES_BY_TYPE,
+ TOUR_POI_CORRIDORS_M,
TOUR_POI_MAX_CATEGORIES,
TOUR_POI_MAX_LINE_POINTS,
WALK_THEME_KEYS,
@@ -16,6 +17,7 @@ import { OnlineOnlyError } from '../../../repo/onlineOnly';
import { tourPoiSearchRepo } from '../../../repo/tourPoiSearchRepo';
import { useTourPoiStore } from '../../../store/tourPoiStore';
import type { TourPlannerController } from '../planner/useTourPlanner';
+import { useRetryCountdown } from './useRetryCountdown';
/** What is ticked when a type is searched for the first time: the three most asked. */
const STARTING_CATEGORIES = (type: PlannableTourType) => TOUR_POI_CATEGORIES_BY_TYPE[type].slice(0, 3);
@@ -50,6 +52,8 @@ export type TourPoiPlanner = Pick<TourPlannerController, 'tripId' | 'tourType' |
* line a place may lie. The answer is shown until the next search: once the
* route or the choices change, it says it was found for the route as it was.
* Nothing about the tour changes here; taking a place in is usePoiInsertion's.
+ * PLN-05: a search that failed or could not ask for some kinds can be sent
+ * again at once, or once the wait the server named has run down.
*/
export function useTourPoiSearch(planner: TourPoiPlanner) {
const { locale } = useTranslation();
@@ -66,6 +70,8 @@ export function useTourPoiSearch(planner: TourPoiPlanner) {
const abortRef = useRef<AbortController | null>(null);
const publish = useTourPoiStore((state) => state.publish);
const clear = useTourPoiStore((state) => state.clear);
+ const retry = useRetryCountdown();
+ const startRetry = retry.start;
const route = planner.route;
const currentKey = keyOf(route, type, categories, corridorM);
@@ -92,38 +98,51 @@ export function useTourPoiSearch(planner: TourPoiPlanner) {
[type]
);
- const search = useCallback(async () => {
- if (!route || route.length < 2 || !categories.length) return;
- abortRef.current?.abort();
- const controller = new AbortController();
- abortRef.current = controller;
- const key = currentKey;
- setLoadingKey(key);
- try {
- const data = await tourPoiSearchRepo.search(
- planner.tripId,
- {
- tour_type: type,
- categories: [...categories],
- corridor_m: corridorM,
- line: thinned(route, TOUR_POI_MAX_LINE_POINTS),
- lang: locale,
- },
- controller.signal
- );
- setAnswer({ key, status: 'ready', data });
- publish(data.pois, theme);
- } catch (err: unknown) {
- if (controller.signal.aborted) return;
- setAnswer({ key, status: err instanceof OnlineOnlyError ? 'offline' : 'error' });
- clear();
- } finally {
- if (abortRef.current === controller) {
- abortRef.current = null;
- setLoadingKey(null);
+ const search = useCallback(
+ async (corridor: number = corridorM) => {
+ if (!route || route.length < 2 || !categories.length) return;
+ abortRef.current?.abort();
+ const controller = new AbortController();
+ abortRef.current = controller;
+ const key = keyOf(route, type, categories, corridor);
+ setLoadingKey(key);
+ try {
+ const data = await tourPoiSearchRepo.search(
+ planner.tripId,
+ {
+ tour_type: type,
+ categories: [...categories],
+ corridor_m: corridor,
+ line: thinned(route, TOUR_POI_MAX_LINE_POINTS),
+ lang: locale,
+ },
+ controller.signal
+ );
+ setAnswer({ key, status: 'ready', data });
+ startRetry(data.retry_after_s);
+ publish(data.pois, theme);
+ } catch (err: unknown) {
+ if (controller.signal.aborted) return;
+ setAnswer({ key, status: err instanceof OnlineOnlyError ? 'offline' : 'error' });
+ startRetry();
+ clear();
+ } finally {
+ if (abortRef.current === controller) {
+ abortRef.current = null;
+ setLoadingKey(null);
+ }
}
- }
- }, [categories, clear, corridorM, currentKey, locale, planner.tripId, publish, route, theme, type]);
+ },
+ [categories, clear, corridorM, locale, planner.tripId, publish, route, startRetry, theme, type]
+ );
+
+ // Nothing found: the next wider corridor, chosen and searched in one step.
+ const widerCorridorM = TOUR_POI_CORRIDORS_M.find((metres) => metres > corridorM) ?? null;
+ const widen = useCallback(() => {
+ if (widerCorridorM === null) return;
+ setCorridorM(widerCorridorM);
+ void search(widerCorridorM);
+ }, [search, widerCorridorM]);
// Leaving the planner, or a tour closed, takes the places off the map.
useEffect(
@@ -147,6 +166,11 @@ export function useTourPoiSearch(planner: TourPoiPlanner) {
setCorridorM,
canSearch,
search,
+ /** The next wider corridor offered, or null at the widest. */
+ widerCorridorM,
+ widen,
+ /** Seconds until asking again makes sense for the kinds that could not be searched; 0 when now. */
+ retryInS: retry.secondsLeft,
status,
answer: answer?.data ?? null,
/** The answer was found for the route or the choices as they were before. */
diff --git a/server/src/nest/maps/maps-along.helpers.ts b/server/src/nest/maps/maps-along.helpers.ts
index 1969f0224..b2e66d0dd 100644
--- a/server/src/nest/maps/maps-along.helpers.ts
+++ b/server/src/nest/maps/maps-along.helpers.ts
@@ -31,8 +31,10 @@ const MAX_OVERPASS_STRETCHES = 8;
* its `[timeout:N]`. Shorter than the explore pill's, because a person waits
* for the search beside the index. The client waits a little longer than this
* (osm.client), never less, or it would hang up on an answer still coming.
+ * Fifteen rather than ten: a public mirror under load queues a query for a
+ * few seconds before it runs, and ten had a plain viewpoint search given up.
*/
-export const OVERPASS_ALONG_QUERY_TIMEOUT_S = 10;
+export const OVERPASS_ALONG_QUERY_TIMEOUT_S = 15;
/** One circle the index is asked in. */
interface AlongBead {
diff --git a/server/src/nest/maps/overpass-hedge.helpers.ts b/server/src/nest/maps/overpass-hedge.helpers.ts
new file mode 100644
index 000000000..26d7ceed9
--- /dev/null
+++ b/server/src/nest/maps/overpass-hedge.helpers.ts
@@ -0,0 +1,80 @@
+/**
+ * PLN-05: asking the Overpass mirrors one after another instead of all at
+ * once. The public mirrors limit slots per IP, so a query sent to all four
+ * costs four slots, and a few searches along a tour beside the ferrata lookup
+ * were enough to have every mirror refuse or drop them together. Pure: no
+ * fetch, no clock beyond the timers it is handed.
+ */
+
+/** A mirror that refused the query because it is busy (HTTP 429), and how long it asked to be left alone. */
+export class OverpassBusy extends Error {
+ constructor(
+ url: string,
+ readonly retryAfterMs: number | null,
+ ) {
+ super(`Overpass 429 @ ${url}`);
+ this.name = 'OverpassBusy';
+ }
+}
+
+/** A Retry-After header in milliseconds, given as seconds or as an HTTP date; null when absent or unreadable. */
+export function retryAfterMs(header: string | null, now = Date.now()): number | null {
+ const value = header?.trim();
+ if (!value) return null;
+ if (/^\d+$/.test(value)) return Number(value) * 1000;
+ const at = Date.parse(value);
+ return Number.isNaN(at) ? null : Math.max(0, at - now);
+}
+
+/** The shortest wait any busy mirror asked for, or null when none named one. */
+export function soonestRetryMs(errors: readonly unknown[]): number | null {
+ const waits = errors.flatMap((err) =>
+ err instanceof OverpassBusy && err.retryAfterMs !== null ? [err.retryAfterMs] : [],
+ );
+ return waits.length ? Math.min(...waits) : null;
+}
+
+/**
+ * The first answer of `urls`, asked in order: the next one is asked once the
+ * last one failed or has kept quiet for `hedgeMs`, so a quick answer costs one
+ * mirror and a dead one costs a moment rather than its whole deadline. Rejects
+ * with every reason (AggregateError) once all of them failed.
+ */
+export function hedged<T>(urls: readonly string[], attempt: (url: string) => Promise<T>, hedgeMs: number): Promise<T> {
+ return new Promise((resolve, reject) => {
+ const errors: unknown[] = [];
+ let started = 0;
+ let done = false;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const next = () => {
+ clearTimeout(timer);
+ if (done || started >= urls.length) return;
+ const url = urls[started];
+ started += 1;
+ if (started < urls.length) timer = setTimeout(next, hedgeMs);
+ attempt(url).then(
+ (value) => {
+ if (done) return;
+ done = true;
+ clearTimeout(timer);
+ resolve(value);
+ },
+ (err: unknown) => {
+ errors.push(err);
+ if (done) return;
+ if (errors.length < urls.length) return next();
+ done = true;
+ reject(new AggregateError(errors, 'Every Overpass endpoint failed'));
+ },
+ );
+ };
+ if (!urls.length) return reject(new AggregateError([], 'No Overpass endpoint'));
+ next();
+ });
+}
+
+/** The mirrors with the one that answered last first: it is the likeliest to answer again. */
+export function lastAnsweredFirst(urls: readonly string[], lastAnswered: string | null): string[] {
+ if (!lastAnswered || !urls.includes(lastAnswered)) return [...urls];
+ return [lastAnswered, ...urls.filter((url) => url !== lastAnswered)];
+}
diff --git a/server/src/nest/maps/pois-along.resolver.ts b/server/src/nest/maps/pois-along.resolver.ts
index 5c70f23ae..fe38b8a97 100644
--- a/server/src/nest/maps/pois-along.resolver.ts
+++ b/server/src/nest/maps/pois-along.resolver.ts
@@ -12,7 +12,8 @@
* `failed`, so the caller can say what could not be searched instead of
* reporting nothing found. Once every Overpass endpoint failed, the next
* searches for a few minutes name its kinds at once instead of waiting out the
- * deadline each time, while a stretch still cached keeps its places.
+ * deadline each time, while a stretch still cached keeps its places and one
+ * probe in a while asks again; the answer says when asking again makes sense.
*
* MapsService.poisAlong delegates here and hands in whether the index is
* switched on, which is a deployment property it owns.
@@ -60,6 +61,8 @@ export interface PoisAlongResult {
truncated: boolean;
/** The line was longer than one search covers; only its first part was searched. */
capped: boolean;
+ /** Seconds until Overpass is asked again, when kinds failed while it holds back; absent otherwise. */
+ retryAfterS?: number;
}
/** What one request of a source brings back. */
@@ -141,13 +144,16 @@ export class PoisAlongResolver {
if (answer.error) logWarn(`[Maps] OpenStreetMap along a line: ${answer.error}`);
}
const sources = [index, overpass, fallback];
+ const failed = [...(unanswered(overpass) ? rest : []), ...(unanswered(fallback) ? indexed : [])];
+ const retryAfterMs = failed.length ? this.osm.overpassAlongRetryAfterMs() : 0;
return {
pois: oncePerPlace([...index.pois, ...overpass.pois, ...fallback.pois]),
- failed: [...(unanswered(overpass) ? rest : []), ...(unanswered(fallback) ? indexed : [])],
+ failed,
partial: sources.some((answer) => answer.answered > 0 && answer.missed > 0),
truncated: sources.some((answer) => answer.truncated),
// A source that answered nothing searched nothing: its kinds are failed or asked of Overpass instead.
capped: sources.some((answer) => answer.answered > 0 && answer.capped),
+ ...(retryAfterMs > 0 ? { retryAfterS: Math.ceil(retryAfterMs / 1000) } : {}),
};
}
diff --git a/server/src/nest/maps/providers/osm.client.ts b/server/src/nest/maps/providers/osm.client.ts
index 1a7d68c29..43bf24898 100644
--- a/server/src/nest/maps/providers/osm.client.ts
+++ b/server/src/nest/maps/providers/osm.client.ts
@@ -38,6 +38,7 @@ import {
OSM_PLACE_ID,
type OverpassPoi,
} from '../maps.helpers';
+import { OverpassBusy, hedged, lastAnsweredFirst, retryAfterMs, soonestRetryMs } from '../overpass-hedge.helpers';
import { readWikiIdentity } from './wiki-identity';
import { Injectable } from '@nestjs/common';
import { normalizePlaceWebsite } from '@trek/shared';
@@ -131,11 +132,20 @@ const POI_CACHE_MAX = 500;
*/
export const POI_RESULT_CAP = 240;
-// POST the query to all mirrors at once and return the first one that answers with
-// valid JSON. Throws {status:502} only if every mirror fails. Racing (rather than
-// trying one-by-one) keeps latency at the fastest reachable mirror instead of the
-// sum of every dead mirror's timeout.
-async function overpassFetch(query: string, timeoutMs = OVERPASS_TIMEOUT_MS): Promise<OverpassPoiElement[]> {
+/** The mirror that answered last, asked first by a hedged query. */
+let lastAnsweredMirror: string | null = null;
+
+// POST the query to the mirrors and return the first one that answers with
+// valid JSON. Throws {status:502} only if every mirror fails, with the shortest
+// wait a busy mirror asked for as `retryAfterMs` when one named it. Without
+// `hedgeMs` every mirror is asked at once, so latency is the fastest reachable
+// mirror's; with it they are asked one after another (overpass-hedge.helpers),
+// so a quick answer costs one mirror's slot instead of every mirror's.
+async function overpassFetch(
+ query: string,
+ timeoutMs = OVERPASS_TIMEOUT_MS,
+ hedgeMs = 0,
+): Promise<OverpassPoiElement[]> {
const body = `data=${encodeURIComponent(query)}`;
const controllers: AbortController[] = [];
@@ -150,6 +160,8 @@ async function overpassFetch(query: string, timeoutMs = OVERPASS_TIMEOUT_MS): Pr
body,
signal: ctrl.signal,
});
+ // A mirror out of slots for this IP: busy, not down, and it may say for how long.
+ if (res.status === 429) throw new OverpassBusy(url, retryAfterMs(res.headers.get('retry-after')));
if (!res.ok) throw new Error(`Overpass ${res.status} @ ${url}`);
const data = (await res.json()) as { elements?: OverpassPoiElement[]; remark?: string };
// Overpass signals an internal timeout / runtime error via `remark` while
@@ -159,6 +171,7 @@ async function overpassFetch(query: string, timeoutMs = OVERPASS_TIMEOUT_MS): Pr
// still surfaces a real error to the client instead of a silent "no places".
if (data.remark) throw new Error(`Overpass remark @ ${url}: ${data.remark}`);
if (!Array.isArray(data.elements)) throw new Error(`Overpass non-OSM body @ ${url}`);
+ lastAnsweredMirror = url;
return data.elements;
} finally {
clearTimeout(timer);
@@ -166,21 +179,23 @@ async function overpassFetch(query: string, timeoutMs = OVERPASS_TIMEOUT_MS): Pr
};
try {
- // Promise.any resolves with the first mirror to return valid JSON, and only
- // rejects (AggregateError) once every mirror has failed.
- return await Promise.any(OVERPASS_MIRRORS.map(attempt));
+ // Either way the first mirror to return valid JSON wins, and only once every
+ // mirror has failed does it reject (AggregateError).
+ return await (hedgeMs > 0
+ ? hedged(lastAnsweredFirst(OVERPASS_MIRRORS, lastAnsweredMirror), attempt, hedgeMs)
+ : Promise.any(OVERPASS_MIRRORS.map(attempt)));
} catch (err) {
// Log WHY every endpoint failed (connection refused, aborted/timed out, non-OSM
// body, …) so an operator can tell blocked egress / a firewall from a transiently
// overloaded mirror — otherwise this is a bare 502 with no breadcrumb (see #1309).
- const reasons =
- err instanceof AggregateError
- ? err.errors.map((e) => (e instanceof Error ? e.message : String(e))).join(' | ')
- : err instanceof Error
- ? err.message
- : String(err);
+ const errors: unknown[] = err instanceof AggregateError ? err.errors : [err];
+ const reasons = errors.map((e) => (e instanceof Error ? e.message : String(e))).join(' | ');
console.error(`[Overpass] all ${OVERPASS_MIRRORS.length} endpoint(s) failed — ${reasons}`);
- throw Object.assign(new Error('Could not reach any Overpass endpoint'), { status: 502 });
+ const wait = soonestRetryMs(errors);
+ throw Object.assign(new Error('Could not reach any Overpass endpoint'), {
+ status: 502,
+ ...(wait !== null ? { retryAfterMs: wait } : {}),
+ });
} finally {
// Cancel the slower/losing requests — we already have (or have given up on) a result.
controllers.forEach((c) => {
@@ -321,13 +336,28 @@ function readPois(
const OVERPASS_ALONG_TIMEOUT_MS = (OVERPASS_ALONG_QUERY_TIMEOUT_S + 2) * 1000;
/**
- * How long the search along a line leaves Overpass alone once every endpoint
- * failed it. While the public mirrors do not answer, each search would wait
- * out the whole deadline only to name the same kinds unavailable; after the
- * pause the next search asks again for real.
+ * How long the search along a line holds back once every endpoint failed it.
+ * While the public mirrors do not answer, each search would wait out the
+ * whole deadline only to name the same kinds unavailable; after the pause the
+ * next search asks again for real. Inside it one probe goes through every
+ * OVERPASS_ALONG_PROBE_MS, so a mirror back early is found by the next retry.
*/
export const OVERPASS_ALONG_COOLDOWN_MS = 3 * 60 * 1000;
+/**
+ * How often a search along a line may probe Overpass during the cooldown; a
+ * busy mirror's Retry-After stretches it, never beyond the cooldown. The
+ * searches beside the probe are refused at once, as in the whole cooldown.
+ */
+export const OVERPASS_ALONG_PROBE_MS = 20 * 1000;
+
+/**
+ * How long a search along a line waits for one mirror before it asks the next
+ * one as well: most answers take well under this, so a healthy mirror costs
+ * one slot instead of all four.
+ */
+export const OVERPASS_ALONG_HEDGE_MS = 1500;
+
/**
* A stretch of a search along a line refused during the cooldown: nothing was
* asked, and the cooldown is logged once rather than with every search.
@@ -341,8 +371,10 @@ export class OverpassCoolingDown extends Error {
@Injectable()
export class OsmClient {
- /** Until when the search along a line leaves Overpass alone after every endpoint failed it; 0 while it asks. */
+ /** Until when the search along a line holds back after every endpoint failed it; 0 while it asks. */
private overpassAlongCooldownUntil = 0;
+ /** When the next probe of the cooldown may go out. */
+ private overpassAlongProbeAt = 0;
/** When an along query was last answered, so a failure that settles after an answer starts no cooldown. */
private overpassAlongAnsweredAt = 0;
/** Whether this cooldown's first skip was logged, so the log holds one line per cooldown. */
@@ -770,8 +802,10 @@ export class OsmClient {
const cacheKey = `along|${kinds}|${osmLang}|${path.radiusM}|${points}|${cap}`;
const cached = cachedPoiAnswer(cacheKey);
if (cached) return cached;
- // Neither a new search nor a later stretch of one under way waits for mirrors that just failed.
+ // Neither a new search nor a later stretch of one under way waits for mirrors that just failed,
+ // but one in a while probes them, so a retry finds them back.
if (this.skipsOverpassAlong()) throw new OverpassCoolingDown();
+ if (Date.now() < this.overpassAlongCooldownUntil) this.overpassAlongProbeAt = Date.now() + OVERPASS_ALONG_PROBE_MS;
const elements = await this.fetchOverpassAlong(overpassAlongQuery(match.filters, path, cap));
const pois = readPois(elements, match, osmLang, KEPT_UNNAMED_ALONG);
@@ -787,37 +821,53 @@ export class OsmClient {
/**
* Whether the search along a line leaves Overpass alone right now, because
- * every endpoint failed it within the last OVERPASS_ALONG_COOLDOWN_MS. Its
- * kinds are then unavailable at once instead of after the whole deadline.
- * The first skip of each cooldown is logged.
+ * every endpoint failed it within the last OVERPASS_ALONG_COOLDOWN_MS and
+ * no probe is due yet. Its kinds are then unavailable at once instead of
+ * after the whole deadline. The first skip of each cooldown is logged.
*/
skipsOverpassAlong(): boolean {
- if (Date.now() >= this.overpassAlongCooldownUntil) return false;
+ if (this.overpassAlongRetryAfterMs() === 0) return false;
if (!this.overpassAlongSkipLogged) {
this.overpassAlongSkipLogged = true;
const until = new Date(this.overpassAlongCooldownUntil).toISOString();
- logWarn(`[Maps] OpenStreetMap along a line: every Overpass endpoint failed, so it is not asked until ${until}`);
+ logWarn(
+ `[Maps] OpenStreetMap along a line: every Overpass endpoint failed, so only a probe now and then asks it until ${until}`,
+ );
}
return true;
}
+ /** How long until a search along a line asks Overpass again, a probe included; 0 when it would now. */
+ overpassAlongRetryAfterMs(): number {
+ const now = Date.now();
+ if (now >= this.overpassAlongCooldownUntil) return 0;
+ return Math.max(0, Math.min(this.overpassAlongProbeAt, this.overpassAlongCooldownUntil) - now);
+ }
+
/**
- * The along query on the mirrors. An answer ends the cooldown; every
- * endpoint failing starts it, unless another along query was answered while
- * this one was in flight: Overpass is up then, and only this query failed.
+ * The along query on the mirrors, one after another. An answer ends the
+ * cooldown; every endpoint failing starts or stretches it, unless another
+ * along query was answered while this one was in flight: Overpass is up
+ * then, and only this query failed. A failed probe keeps the cooldown's
+ * log line, so one outage is one line.
*/
private async fetchOverpassAlong(query: string): Promise<OverpassPoiElement[]> {
const askedAt = Date.now();
try {
- const elements = await overpassFetch(query, OVERPASS_ALONG_TIMEOUT_MS);
+ const elements = await overpassFetch(query, OVERPASS_ALONG_TIMEOUT_MS, OVERPASS_ALONG_HEDGE_MS);
this.overpassAlongAnsweredAt = Date.now();
this.overpassAlongCooldownUntil = 0;
+ this.overpassAlongProbeAt = 0;
return elements;
} catch (err) {
// overpassFetch throws only once every mirror has failed.
if (this.overpassAlongAnsweredAt < askedAt) {
- this.overpassAlongCooldownUntil = Date.now() + OVERPASS_ALONG_COOLDOWN_MS;
- this.overpassAlongSkipLogged = false;
+ const now = Date.now();
+ const busyFor = (err as { retryAfterMs?: number }).retryAfterMs ?? 0;
+ if (now >= this.overpassAlongCooldownUntil) this.overpassAlongSkipLogged = false;
+ this.overpassAlongCooldownUntil = now + OVERPASS_ALONG_COOLDOWN_MS;
+ this.overpassAlongProbeAt =
+ now + Math.min(Math.max(busyFor, OVERPASS_ALONG_PROBE_MS), OVERPASS_ALONG_COOLDOWN_MS);
}
throw err;
}
diff --git a/server/src/nest/tours/tour-poi-search.service.ts b/server/src/nest/tours/tour-poi-search.service.ts
index 7350ca137..60507fd4c 100644
--- a/server/src/nest/tours/tour-poi-search.service.ts
+++ b/server/src/nest/tours/tour-poi-search.service.ts
@@ -235,7 +235,8 @@ function placesWithin(found: MapsPoi[], body: TourPoiSearchRequest, line: Array<
* corridor of the line itself, the nearest to it when there are more than one
* answer carries, listed from the start. Nothing is written. A kind no source
* could be asked for is named as unavailable, so a failed source never reads
- * as nothing found; the distance is measured straight across to the line,
+ * as nothing found, with the seconds until asking again makes sense when the
+ * map search holds back; the distance is measured straight across to the line,
* never a way someone walked or paddled. A search for sights also asks for the
* best known places near the line and lists its highlights first.
*/
@@ -258,14 +259,17 @@ export class TourPoiSearchService {
body.categories.includes('sights') ? this.highlightsAlong(points, body) : [],
]);
const found = withHighlights(placesWithin(along.pois, body, line), highlights, body.corridor_m, line);
+ const unavailable = body.categories.filter((category) =>
+ MAPS_CATEGORIES[category].every((mapsCategory) => along.failed.includes(mapsCategory)),
+ );
return {
pois: answerRows(found.places, found.ranks),
truncated: along.truncated || found.places.length > TOUR_POI_LIMIT,
partial: along.partial,
capped: along.capped,
- unavailable: body.categories.filter((category) =>
- MAPS_CATEGORIES[category].every((mapsCategory) => along.failed.includes(mapsCategory)),
- ),
+ unavailable,
+ // When asking again makes sense, only beside a kind that could not be searched.
+ ...(unavailable.length && along.retryAfterS ? { retry_after_s: along.retryAfterS } : {}),
};
}
diff --git a/server/src/nest/tours/tours.mcp.ts b/server/src/nest/tours/tours.mcp.ts
index e84b7d9ed..cb82568d7 100644
--- a/server/src/nest/tours/tours.mcp.ts
+++ b/server/src/nest/tours/tours.mcp.ts
@@ -239,7 +239,7 @@ export class ToursMcp {
@Tool({
name: 'search_tour_pois',
description:
- 'Search places along the saved line of a tour: what a hike, a run, a ride, a bike tour, a paddle tour, a ski and winter tour or a city walk stops for (viewpoint, peak, shelter, drinking_water, food, toilets, picnic, campsite, sights, slipway, boat_rental, bike_repair for repair stations and bike shops, for a ski and winter tour cafe and restaurant as well, and for a city walk museum for museums and galleries, park for parks and gardens, cafe, restaurant and market), within corridor_m metres of the line. Answers each place with its source (TREK places index or OpenStreetMap), kind, address, website and phone where known, opening hours as the source has them (a hint to check, never a promise), distance_m (straight across to the line, not a detour) and along_m (from the start along the line); up to 60, the nearest to the line when more match, listed from the start. When sights are asked for, the best known places near the line (by the page views of their Wikidata item) are searched too: a square or landmark no category names is added as a sight, and the highlights among them carry highlight: true and come first, the best known first. A place OpenStreetMap has no name for (a tap, a bench) comes with an empty name. unavailable lists the categories no source could be searched for right now: their places are missing, not absent, so ask again later rather than reporting none. partial says some stretches could not be searched, capped that only the first part of a long line was, truncated that more places matched. A tour saved with its points only (route_pending) has no line to search along yet. Nothing is added to the tour or the trip.',
+ 'Search places along the saved line of a tour: what a hike, a run, a ride, a bike tour, a paddle tour, a ski and winter tour or a city walk stops for (viewpoint, peak, shelter, drinking_water, food, toilets, picnic, campsite, sights, slipway, boat_rental, bike_repair for repair stations and bike shops, for a ski and winter tour cafe and restaurant as well, and for a city walk museum for museums and galleries, park for parks and gardens, cafe, restaurant and market), within corridor_m metres of the line. Answers each place with its source (TREK places index or OpenStreetMap), kind, address, website and phone where known, opening hours as the source has them (a hint to check, never a promise), distance_m (straight across to the line, not a detour) and along_m (from the start along the line); up to 60, the nearest to the line when more match, listed from the start. When sights are asked for, the best known places near the line (by the page views of their Wikidata item) are searched too: a square or landmark no category names is added as a sight, and the highlights among them carry highlight: true and come first, the best known first. A place OpenStreetMap has no name for (a tap, a bench) comes with an empty name. unavailable lists the categories no source could be searched for right now: their places are missing, not absent, so ask again later rather than reporting none; retry_after_s, when present, is how many seconds until asking again makes sense, because the OpenStreetMap mirrors failed and are only probed now and then. partial says some stretches could not be searched, capped that only the first part of a long line was, truncated that more places matched. A tour saved with its points only (route_pending) has no line to search along yet. Nothing is added to the tour or the trip.',
inputSchema: {
tripId: idSchema,
placeId: idSchema.describe('The place id of the tour, as list_tours gives it'),
diff --git a/server/tests/e2e/tours-planned.e2e.test.ts b/server/tests/e2e/tours-planned.e2e.test.ts
index 5a846e7fe..3689c215f 100644
--- a/server/tests/e2e/tours-planned.e2e.test.ts
+++ b/server/tests/e2e/tours-planned.e2e.test.ts
@@ -745,6 +745,30 @@ describe('Tours planned e2e (real guards + temp SQLite)', () => {
});
});
+ it('says how many seconds until asking again makes sense while the map search holds back', async () => {
+ mapsPoisAlong.mockResolvedValue({
+ pois: [],
+ failed: ['viewpoint'],
+ partial: false,
+ truncated: false,
+ capped: false,
+ retryAfterS: 20,
+ });
+ const res = await request(server)
+ .post('/api/trips/5/tours/poi-search')
+ .set('Cookie', sessionCookie(VIEWER))
+ .send({ ...body, categories: ['viewpoint'] });
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual({
+ pois: [],
+ truncated: false,
+ partial: false,
+ capped: false,
+ unavailable: ['viewpoint'],
+ retry_after_s: 20,
+ });
+ });
+
it('404 for someone outside the trip, 400 for a body it does not know, 401 without a session', async () => {
const outsider = await request(server)
.post('/api/trips/5/tours/poi-search')
diff --git a/server/tests/unit/nest/maps-along.helpers.test.ts b/server/tests/unit/nest/maps-along.helpers.test.ts
index 96914a421..d35e5f9c1 100644
--- a/server/tests/unit/nest/maps-along.helpers.test.ts
+++ b/server/tests/unit/nest/maps-along.helpers.test.ts
@@ -114,7 +114,7 @@ describe('aroundPath and overpassAlongQuery', () => {
const path = aroundPath([at(0, 0), at(0, 1000)], 500);
const query = overpassAlongQuery(['tourism=viewpoint', 'amenity=drinking_water'], path, 60);
// The deadline the client's own wait is derived from, so the two never drift apart.
- expect(OVERPASS_ALONG_QUERY_TIMEOUT_S).toBe(10);
+ expect(OVERPASS_ALONG_QUERY_TIMEOUT_S).toBe(15);
expect(query.startsWith(`[out:json][timeout:${OVERPASS_ALONG_QUERY_TIMEOUT_S}];`)).toBe(true);
expect(query).toContain('nwr["tourism"="viewpoint"](');
expect(query).toContain('nwr["amenity"="drinking_water"](');
diff --git a/server/tests/unit/nest/maps.pois-along.test.ts b/server/tests/unit/nest/maps.pois-along.test.ts
index 8c57a3c38..d40637e98 100644
--- a/server/tests/unit/nest/maps.pois-along.test.ts
+++ b/server/tests/unit/nest/maps.pois-along.test.ts
@@ -3,7 +3,8 @@
* along it and from Overpass, in stretches of the whole line, for the kinds
* the index does not know. After every Overpass mirror failed, its kinds are
* named unavailable at once for a cooldown instead of after its deadline,
- * unless Overpass answered meanwhile or the stretch is still cached.
+ * unless Overpass answered meanwhile, the stretch is still cached or a probe
+ * is due; the answer then says how many seconds until it is asked again.
*
* The index is asked through a stub here, Overpass through a spy on the OSM
* client: these cases are about who is asked for what, and how a source that
@@ -379,7 +380,7 @@ describe('MapsService.poisAlong', () => {
expect(seen.most).toBe(3);
});
- it('MAPS-ALONG-019c: after every Overpass mirror failed, the next searches name its kinds at once for a while', async () => {
+ it('MAPS-ALONG-019c: after every Overpass mirror failed, the next searches name its kinds at once and say when to retry', async () => {
vi.useFakeTimers({ now: new Date('2026-10-19T10:00:00Z') });
vi.spyOn(console, 'error').mockImplementation(() => {});
// Mirrors that never answer: each request waits out its deadline and is aborted.
@@ -393,22 +394,25 @@ describe('MapsService.poisAlong', () => {
overpass.mockRestore();
try {
const first = svc.poisAlong(['cafe', 'viewpoint', 'drinking_water'], LINE, 500, 'de', 30);
- await vi.advanceTimersByTimeAsync(15_000);
- expect(await first).toMatchObject({ failed: ['viewpoint', 'drinking_water'], partial: false });
+ // The four mirrors asked a second and a half apart, each waiting out its seventeen seconds.
+ await vi.advanceTimersByTimeAsync(25_000);
+ expect(await first).toMatchObject({ failed: ['viewpoint', 'drinking_water'], partial: false, retryAfterS: 20 });
const asked = fetchMock.mock.calls.length;
+ expect(asked).toBe(4);
// Without waiting for any deadline: nothing is asked, the index places stay, the kinds are named.
const again = await svc.poisAlong(['cafe', 'viewpoint', 'drinking_water'], LINE, 500, 'de', 30);
const hike = await svc.poisAlong(['viewpoint', 'shelter'], north(0.1), 500, 'de', 30);
expect(fetchMock).toHaveBeenCalledTimes(asked);
- expect(again).toMatchObject({ failed: ['viewpoint', 'drinking_water'], partial: false });
+ // Three and a half seconds after the failure, the first probe is due in sixteen and a half.
+ expect(again).toMatchObject({ failed: ['viewpoint', 'drinking_water'], partial: false, retryAfterS: 17 });
expect(again.pois.map((poi) => poi.name)).toEqual(['Kaffeehaus']);
expect(hike.failed).toEqual(['viewpoint', 'shelter']);
- // The search that waited out its twelve seconds says why; the skips after it are one line for the
+ // The search that waited out its deadline says why; the skips after it are one line for the
// whole cooldown, three minutes from that failure.
expect(mapsWarnings()).toEqual([
expect.stringContaining('[Maps] OpenStreetMap along a line: viewpoint, drinking_water: 1 of 1 requests failed'),
- expect.stringContaining('every Overpass endpoint failed, so it is not asked until 2026-10-19T10:03:12.000Z'),
+ expect.stringContaining('so only a probe now and then asks it until 2026-10-19T10:03:21.500Z'),
]);
// After the cooldown it is asked again for real, and an answer ends the pause for good.
@@ -416,6 +420,7 @@ describe('MapsService.poisAlong', () => {
fetchMock.mockResolvedValue({ ok: true, json: async () => ({ elements: [] }) });
const later = await svc.poisAlong(['viewpoint'], LINE, 500, 'de', 30);
expect(later.failed).toEqual([]);
+ expect(later).not.toHaveProperty('retryAfterS');
expect(fetchMock.mock.calls.length).toBeGreaterThan(asked);
const answered = fetchMock.mock.calls.length;
await svc.poisAlong(['shelter'], LINE, 500, 'de', 30);
@@ -493,8 +498,9 @@ describe('MapsService.poisAlong', () => {
expect((await svc.poisAlong(['viewpoint'], at(12.5), 500, 'de', 30)).failed).toEqual(['viewpoint']);
const asked = fetchMock.mock.calls.length;
- // A minute on, the first line is answered from the cache as before; a line not asked yet is named at once.
- vi.setSystemTime(new Date('2026-10-19T11:01:01Z'));
+ // Ten seconds on, before the first probe, the first line is answered from the cache as before; a
+ // line not asked yet is named at once.
+ vi.setSystemTime(new Date('2026-10-19T11:00:11Z'));
const again = await svc.poisAlong(['viewpoint'], at(12), 500, 'de', 30);
expect(again).toMatchObject({ failed: [], partial: false });
expect(again.pois.map((poi) => poi.name)).toEqual(['Aussicht']);
@@ -502,7 +508,7 @@ describe('MapsService.poisAlong', () => {
expect(fetchMock).toHaveBeenCalledTimes(asked);
expect(mapsWarnings()).toEqual([
expect.stringContaining('OpenStreetMap along a line: viewpoint: 1 of 1 requests failed: Could not reach any'),
- expect.stringContaining('every Overpass endpoint failed, so it is not asked until 2026-10-19T11:03:01.000Z'),
+ expect.stringContaining('so only a probe now and then asks it until 2026-10-19T11:03:01.000Z'),
]);
} finally {
vi.useRealTimers();
@@ -524,7 +530,7 @@ describe('MapsService.poisAlong', () => {
// Stretches 4 and 5 are not sent: every mirror had just failed the first three.
expect(queriesSent(fetchMock)).toBe(3);
expect(mapsWarnings()).toEqual([
- expect.stringContaining('every Overpass endpoint failed, so it is not asked until'),
+ expect.stringContaining('every Overpass endpoint failed, so only a probe now and then asks it until'),
expect.stringContaining('OpenStreetMap along a line: shelter: 5 of 5 requests failed: Could not reach any'),
]);
} finally {
diff --git a/server/tests/unit/nest/osm.pois-along.test.ts b/server/tests/unit/nest/osm.pois-along.test.ts
index b525240d6..bb6b0621c 100644
--- a/server/tests/unit/nest/osm.pois-along.test.ts
+++ b/server/tests/unit/nest/osm.pois-along.test.ts
@@ -1,14 +1,17 @@
/**
- * MAPS-ALONG-020..029: the Overpass query near a line (PLN-02). One query for
- * every kind the index does not know, the candidates of the line's box kept
- * within reach of the line itself, and unnamed taps and huts kept, because
- * they are what a hike looks for, while an unnamed garden or cafe is not.
- * After every mirror failed, the next queries are refused at once for a
- * cooldown, unless Overpass answered meanwhile or the answer is still cached.
- * The network is a stubbed global fetch.
+ * MAPS-ALONG-020..029, 032..034: the Overpass query near a line (PLN-02). One
+ * query for every kind the index does not know, the candidates of the line's
+ * box kept within reach of the line itself, and unnamed taps and huts kept,
+ * because they are what a hike looks for, while an unnamed garden or cafe is
+ * not. After every mirror failed, the next queries are refused at once for a
+ * cooldown, unless Overpass answered meanwhile, the answer is still cached or
+ * a probe is due (PLN-05). The mirrors are asked one after another, a busy
+ * one's Retry-After heeded. The network is a stubbed global fetch.
*/
import {
OVERPASS_ALONG_COOLDOWN_MS,
+ OVERPASS_ALONG_HEDGE_MS,
+ OVERPASS_ALONG_PROBE_MS,
OsmClient,
OverpassCoolingDown,
} from '../../../src/nest/maps/providers/osm.client';
@@ -36,8 +39,21 @@ const answer = (elements: unknown[]) => ({ ok: true, json: async () => ({ elemen
/** What every mirror answers while Overpass is down. */
const down = () => ({ ok: false, status: 504, json: async () => ({}) });
+/** What a mirror out of slots answers, with the wait it asks for when one is given. */
+const busy = (retryAfter: string | null) => ({
+ ok: false,
+ status: 429,
+ headers: { get: (name: string) => (name.toLowerCase() === 'retry-after' ? retryAfter : null) },
+ json: async () => ({}),
+});
+
+/** A mirror that never answers: the request waits out its deadline and is aborted. */
+const silent = (init?: RequestInit) =>
+ new Promise((_resolve, reject) => init?.signal?.addEventListener('abort', () => reject(new Error('aborted'))));
+
/** The line a skip writes, once per cooldown, before the time it ends. */
-const SKIP_LOGGED = '[Maps] OpenStreetMap along a line: every Overpass endpoint failed, so it is not asked until';
+const SKIP_LOGGED =
+ '[Maps] OpenStreetMap along a line: every Overpass endpoint failed, so only a probe now and then asks it until';
/** The query of a fetch call, read back the way Overpass reads the form. */
const queryOf = (call: unknown[] | undefined) =>
@@ -129,25 +145,35 @@ describe('OsmClient.searchOverpassPoisAlong', () => {
const asked = fetchMock.mock.calls.length;
expect(asked).toBeGreaterThan(0);
- // Inside the cooldown no line and no kind is asked, and the skip is logged once.
- vi.setSystemTime(new Date(Date.now() + OVERPASS_ALONG_COOLDOWN_MS - 1));
+ // Before the first probe no line and no kind is asked, and the skip is logged once.
+ vi.setSystemTime(new Date(Date.now() + OVERPASS_ALONG_PROBE_MS - 1));
await expect(osm.searchOverpassPoisAlong('viewpoint', line(8), 500)).rejects.toThrow('not retrying yet');
await expect(osm.searchOverpassPoisAlong('drinking_water', line(7), 500)).rejects.toThrow('not retrying yet');
expect(osm.skipsOverpassAlong()).toBe(true);
+ expect(osm.overpassAlongRetryAfterMs()).toBe(1);
// An unknown kind is still refused as one.
await expect(osm.searchOverpassPoisAlong('unicorns', line(7), 500)).rejects.toMatchObject({ status: 400 });
expect(fetchMock).toHaveBeenCalledTimes(asked);
expect(logWarn).toHaveBeenCalledTimes(1);
expect(logWarn).toHaveBeenCalledWith(`${SKIP_LOGGED} 2026-10-19T10:03:00.000Z`);
- // Three minutes on it is asked again for real; still down, it starts a new cooldown with a line of its own.
- vi.setSystemTime(new Date('2026-10-19T10:03:00Z'));
- expect(osm.skipsOverpassAlong()).toBe(false);
+ // The probe still failing stretches the cooldown from now, without a second line for the same outage.
+ vi.setSystemTime(new Date('2026-10-19T10:00:20Z'));
await expect(osm.searchOverpassPoisAlong('viewpoint', line(8), 500)).rejects.toMatchObject({ status: 502 });
expect(fetchMock).toHaveBeenCalledTimes(2 * asked);
await expect(osm.searchOverpassPoisAlong('viewpoint', line(8), 500)).rejects.toThrow('not retrying yet');
+ expect(osm.overpassAlongRetryAfterMs()).toBe(OVERPASS_ALONG_PROBE_MS);
+ expect(logWarn).toHaveBeenCalledTimes(1);
+
+ // Three minutes after the last failure it is asked again for real; still down, it starts a new
+ // cooldown with a line of its own.
+ vi.setSystemTime(new Date('2026-10-19T10:03:20Z'));
+ expect(osm.skipsOverpassAlong()).toBe(false);
+ await expect(osm.searchOverpassPoisAlong('viewpoint', line(8), 500)).rejects.toMatchObject({ status: 502 });
+ expect(fetchMock).toHaveBeenCalledTimes(3 * asked);
+ await expect(osm.searchOverpassPoisAlong('viewpoint', line(8), 500)).rejects.toThrow('not retrying yet');
expect(logWarn).toHaveBeenCalledTimes(2);
- expect(logWarn).toHaveBeenLastCalledWith(`${SKIP_LOGGED} 2026-10-19T10:06:00.000Z`);
+ expect(logWarn).toHaveBeenLastCalledWith(`${SKIP_LOGGED} 2026-10-19T10:06:20.000Z`);
} finally {
vi.useRealTimers();
}
@@ -188,7 +214,8 @@ describe('OsmClient.searchOverpassPoisAlong', () => {
const failed = expect(osm.searchOverpassPoisAlong('viewpoint', line(17), 500)).rejects.toMatchObject({
status: 502,
});
- await vi.advanceTimersByTimeAsync(5000);
+ // The failing one tries the four mirrors one after another, the last giving up at seven and a half seconds.
+ await vi.advanceTimersByTimeAsync(10_000);
await expect(answered).resolves.toMatchObject({ pois: [] });
await failed;
// Overpass answered while the failing query was in flight: it is up, and the next search asks.
@@ -197,7 +224,7 @@ describe('OsmClient.searchOverpassPoisAlong', () => {
const again = expect(osm.searchOverpassPoisAlong('viewpoint', line(17), 500)).rejects.toMatchObject({
status: 502,
});
- await vi.advanceTimersByTimeAsync(5000);
+ await vi.advanceTimersByTimeAsync(10_000);
await again;
expect(fetchMock.mock.calls.length).toBeGreaterThan(asked);
@@ -214,6 +241,106 @@ describe('OsmClient.searchOverpassPoisAlong', () => {
}
});
+ it('MAPS-ALONG-032: during the cooldown one probe goes through, the searches beside it are refused, its answer ends it', async () => {
+ vi.useFakeTimers({ now: new Date('2026-10-21T05:06:00Z'), toFake: ['Date'] });
+ const fetchMock = vi.fn().mockResolvedValue(down());
+ vi.stubGlobal('fetch', fetchMock);
+ try {
+ await expect(osm.searchOverpassPoisAlong('viewpoint', line(31), 500)).rejects.toMatchObject({ status: 502 });
+ expect(osm.overpassAlongRetryAfterMs()).toBe(OVERPASS_ALONG_PROBE_MS);
+ const asked = fetchMock.mock.calls.length;
+
+ // The mirrors are back by the time the probe is due: it asks, the search beside it does not.
+ vi.setSystemTime(new Date('2026-10-21T05:06:20Z'));
+ fetchMock.mockResolvedValue(
+ answer([{ type: 'node', id: 31, lat: 47.715, lon: 11.1, tags: { tourism: 'viewpoint' } }]),
+ );
+ const probe = osm.searchOverpassPoisAlong('viewpoint', line(31), 500);
+ await expect(osm.searchOverpassPoisAlong('viewpoint', line(33), 500)).rejects.toBeInstanceOf(OverpassCoolingDown);
+ await expect(probe).resolves.toMatchObject({ pois: [expect.objectContaining({ osm_id: 'node:31' })] });
+ expect(fetchMock).toHaveBeenCalledTimes(asked + 1);
+
+ // Its answer ends the cooldown: the next search asks at once.
+ expect(osm.skipsOverpassAlong()).toBe(false);
+ expect(osm.overpassAlongRetryAfterMs()).toBe(0);
+ await expect(osm.searchOverpassPoisAlong('viewpoint', line(33), 500)).resolves.toMatchObject({
+ source: 'openstreetmap',
+ });
+ expect(fetchMock).toHaveBeenCalledTimes(asked + 2);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('MAPS-ALONG-033: a mirror out of slots is busy: the next is asked at once, and its Retry-After holds the probe back', async () => {
+ vi.useFakeTimers({ now: new Date('2026-10-21T05:10:00Z'), toFake: ['Date'] });
+ const fetchMock = vi.fn().mockResolvedValue(busy('60'));
+ vi.stubGlobal('fetch', fetchMock);
+ const logged = vi.spyOn(console, 'error').mockImplementation(() => {});
+ try {
+ const failed = await osm.searchOverpassPoisAlong('viewpoint', line(35), 500).catch((err: unknown) => err);
+ expect(failed).toMatchObject({ status: 502, retryAfterMs: 60_000 });
+ // Every mirror was asked without waiting for the hedge: a refusal is an answer.
+ expect(fetchMock).toHaveBeenCalledTimes(4);
+ expect(logged).toHaveBeenCalledWith(expect.stringContaining('Overpass 429 @ https://'));
+ expect(osm.overpassAlongRetryAfterMs()).toBe(60_000);
+
+ // A wait longer than the cooldown is cut to it; an HTTP date is read as well.
+ vi.setSystemTime(new Date('2026-10-21T05:20:00Z'));
+ fetchMock.mockResolvedValue(busy('Wed, 21 Oct 2026 06:00:00 GMT'));
+ await expect(osm.searchOverpassPoisAlong('viewpoint', line(37), 500)).rejects.toMatchObject({
+ retryAfterMs: 40 * 60_000,
+ });
+ expect(osm.overpassAlongRetryAfterMs()).toBe(OVERPASS_ALONG_COOLDOWN_MS);
+
+ // A busy mirror without a Retry-After leaves the probe at its own pace.
+ vi.setSystemTime(new Date('2026-10-21T05:30:00Z'));
+ fetchMock.mockResolvedValue(busy(null));
+ const plain = await osm.searchOverpassPoisAlong('viewpoint', line(39), 500).catch((err: unknown) => err);
+ expect(plain).toMatchObject({ status: 502 });
+ expect(plain).not.toHaveProperty('retryAfterMs');
+ expect(osm.overpassAlongRetryAfterMs()).toBe(OVERPASS_ALONG_PROBE_MS);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('MAPS-ALONG-034: the mirrors are asked one after another, not at once, the one that answered last first', async () => {
+ vi.useFakeTimers({ now: new Date('2026-10-21T05:40:00Z') });
+ // The first mirror asked keeps quiet; every other one answers a tenth of a second after it is asked.
+ let sent = 0;
+ const fetchMock = vi.fn(async (_url: unknown, init?: RequestInit) => {
+ sent += 1;
+ if (sent === 1) return silent(init);
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ return answer([]);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ try {
+ const search = osm.searchOverpassPoisAlong('viewpoint', line(41), 500);
+ await vi.advanceTimersByTimeAsync(OVERPASS_ALONG_HEDGE_MS - 1);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(1);
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ await vi.advanceTimersByTimeAsync(100);
+ await expect(search).resolves.toMatchObject({ pois: [] });
+ // The answer settles it: the other two mirrors are never asked, and the quiet one is let go.
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ const answering = fetchMock.mock.calls[1]?.[0];
+ expect(answering).not.toBe(fetchMock.mock.calls[0]?.[0]);
+
+ // The next query starts at the mirror that answered.
+ const next = osm.searchOverpassPoisAlong('viewpoint', line(43), 500);
+ await vi.advanceTimersByTimeAsync(100);
+ await expect(next).resolves.toMatchObject({ pois: [] });
+ expect(fetchMock).toHaveBeenCalledTimes(3);
+ expect(fetchMock.mock.calls[2]?.[0]).toBe(answering);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it('MAPS-ALONG-024b: an answer older than five minutes is asked again, and the oldest of a full cache goes', async () => {
const fetchMock = vi.fn().mockResolvedValue(answer([]));
vi.stubGlobal('fetch', fetchMock);
diff --git a/server/tests/unit/nest/overpass-hedge.helpers.test.ts b/server/tests/unit/nest/overpass-hedge.helpers.test.ts
new file mode 100644
index 000000000..532fb7ab5
--- /dev/null
+++ b/server/tests/unit/nest/overpass-hedge.helpers.test.ts
@@ -0,0 +1,85 @@
+/**
+ * MAPS-ALONG-035..038: asking the Overpass mirrors one after another (PLN-05).
+ * The next mirror is asked once the last failed or kept quiet for the hedge,
+ * the first answer wins, and a busy mirror's Retry-After is read in either
+ * spelling. Pure: the attempts are stubs, the clock is vitest's.
+ */
+import {
+ OverpassBusy,
+ hedged,
+ lastAnsweredFirst,
+ retryAfterMs,
+ soonestRetryMs,
+} from '../../../src/nest/maps/overpass-hedge.helpers';
+
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+const MIRRORS = ['https://a.example', 'https://b.example', 'https://c.example'];
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe('overpass hedge helpers', () => {
+ it('MAPS-ALONG-035: the next mirror is asked after the hedge or at once when the last failed, the first answer wins', async () => {
+ vi.useFakeTimers();
+ const asked: string[] = [];
+ // a keeps quiet, b fails after half a second, c answers.
+ const attempt = vi.fn((url: string) => {
+ asked.push(url);
+ if (url === 'https://a.example') return new Promise<string>(() => {});
+ if (url === 'https://b.example')
+ return new Promise<string>((_resolve, reject) => setTimeout(() => reject(new Error('504')), 500));
+ return Promise.resolve(`answer of ${url}`);
+ });
+
+ const answer = hedged(MIRRORS, attempt, 1000);
+ expect(asked).toEqual(['https://a.example']);
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(asked).toEqual(['https://a.example', 'https://b.example']);
+ // b fails before the next hedge is up, so c is asked then rather than at two seconds.
+ await vi.advanceTimersByTimeAsync(500);
+ expect(asked).toEqual(MIRRORS);
+ await expect(answer).resolves.toBe('answer of https://c.example');
+ });
+
+ it('MAPS-ALONG-036: every mirror failing rejects with every reason; none to ask rejects at once', async () => {
+ const attempt = (url: string) => Promise.reject(new Error(`down @ ${url}`));
+
+ const failed = await hedged(MIRRORS, attempt, 1000).catch((err: unknown) => err);
+
+ expect(failed).toBeInstanceOf(AggregateError);
+ expect((failed as AggregateError).errors.map((err: Error) => err.message)).toEqual(
+ MIRRORS.map((url) => `down @ ${url}`),
+ );
+ await expect(hedged([], attempt, 1000)).rejects.toBeInstanceOf(AggregateError);
+ });
+
+ it('MAPS-ALONG-037: a Retry-After is read as seconds or as a date, the shortest busy wait is the one named', () => {
+ const now = Date.parse('2026-10-21T05:06:00Z');
+ expect(retryAfterMs('30', now)).toBe(30_000);
+ expect(retryAfterMs(' 0 ', now)).toBe(0);
+ expect(retryAfterMs('Wed, 21 Oct 2026 05:07:00 GMT', now)).toBe(60_000);
+ expect(retryAfterMs('Wed, 21 Oct 2026 05:05:00 GMT', now)).toBe(0);
+ expect(retryAfterMs('soon', now)).toBeNull();
+ expect(retryAfterMs('', now)).toBeNull();
+ expect(retryAfterMs(null, now)).toBeNull();
+
+ expect(
+ soonestRetryMs([new OverpassBusy('https://a.example', 90_000), new OverpassBusy('https://b.example', 30_000)]),
+ ).toBe(30_000);
+ // A timeout or a busy mirror that named no wait says nothing about when to ask again.
+ expect(soonestRetryMs([new Error('aborted'), new OverpassBusy('https://a.example', null)])).toBeNull();
+ expect(new OverpassBusy('https://a.example', null).message).toBe('Overpass 429 @ https://a.example');
+ });
+
+ it('MAPS-ALONG-038: the mirror that answered last is asked first, an unknown one changes nothing', () => {
+ expect(lastAnsweredFirst(MIRRORS, 'https://c.example')).toEqual([
+ 'https://c.example',
+ 'https://a.example',
+ 'https://b.example',
+ ]);
+ expect(lastAnsweredFirst(MIRRORS, 'https://gone.example')).toEqual(MIRRORS);
+ expect(lastAnsweredFirst(MIRRORS, null)).toEqual(MIRRORS);
+ });
+});
diff --git a/server/tests/unit/nest/tour-poi-search.service.test.ts b/server/tests/unit/nest/tour-poi-search.service.test.ts
index 7ba4ea14b..db10ec1e7 100644
--- a/server/tests/unit/nest/tour-poi-search.service.test.ts
+++ b/server/tests/unit/nest/tour-poi-search.service.test.ts
@@ -200,6 +200,21 @@ describe('TourPoiSearchService', () => {
).toEqual(['food']);
});
+ it('TOUR-POI-017: says when to ask again beside the kinds it could not search, and nothing of it otherwise', async () => {
+ poisAlong.mockResolvedValue(answer([], { failed: ['viewpoint'], retryAfterS: 20 }));
+ const failed = await service.search({ tour_type: 'hike', categories: ['viewpoint'], corridor_m: 500, line: LINE });
+ expect(failed).toMatchObject({ unavailable: ['viewpoint'], retry_after_s: 20 });
+
+ // A wait the map search names for a kind not asked here, or none at all, leaves the field out.
+ const other = await service.search({ tour_type: 'hike', categories: ['shelter'], corridor_m: 500, line: LINE });
+ expect(other.unavailable).toEqual([]);
+ expect(other).not.toHaveProperty('retry_after_s');
+ poisAlong.mockResolvedValue(answer([], { failed: ['viewpoint'] }));
+ const plain = await service.search({ tour_type: 'hike', categories: ['viewpoint'], corridor_m: 500, line: LINE });
+ expect(plain.unavailable).toEqual(['viewpoint']);
+ expect(plain).not.toHaveProperty('retry_after_s');
+ });
+
it('TOUR-POI-008: an unnamed place is kept and never merged with another unnamed one nearby', async () => {
poisAlong.mockResolvedValue(
answer([
diff --git a/shared/src/i18n/ar/tours.ts b/shared/src/i18n/ar/tours.ts
index f01832c7a..7d356b0f1 100644
--- a/shared/src/i18n/ar/tours.ts
+++ b/shared/src/i18n/ar/tours.ts
@@ -377,6 +377,10 @@ const tours: TranslationStrings = {
'tours.poi.capped': 'الجولة طويلة: تم البحث في جزئها الأول فقط.',
'tours.poi.truncated': 'هناك أماكن أكثر مما يظهر. قلّل المسافة أو الأنواع.',
'tours.poi.empty': 'لم يُعثر على شيء ضمن {distance} من المسار.',
+ 'tours.poi.retry': 'حاول مرة أخرى',
+ 'tours.poi.retryIn': 'مرة أخرى بعد {time}',
+ 'tours.poi.retryHint': 'لم تستجب خوادم OpenStreetMap. السؤال قبل ذلك لن يأتي إلا بالإجابة نفسها.',
+ 'tours.poi.widen': 'توسيع إلى {distance}',
'tours.poi.fromRoute': '{distance} من المسار',
'tours.poi.along': 'عند {distance}',
'tours.poi.source.osm': 'من OpenStreetMap',
diff --git a/shared/src/i18n/az/tours.ts b/shared/src/i18n/az/tours.ts
index 8a1488744..6c97a31b5 100644
--- a/shared/src/i18n/az/tours.ts
+++ b/shared/src/i18n/az/tours.ts
@@ -364,6 +364,10 @@ const tours: TranslationStrings = {
'tours.poi.capped': 'Tur uzundur: yalnız ilk hissəsində axtarış aparıldı.',
'tours.poi.truncated': 'Göstəriləndən çox yer var. Məsafəni və ya növləri azalt.',
'tours.poi.empty': 'Marşrutdan {distance} məsafədə heç nə tapılmadı.',
+ 'tours.poi.retry': 'Yenidən cəhd et',
+ 'tours.poi.retryIn': '{time} sonra yenidən',
+ 'tours.poi.retryHint': 'OpenStreetMap serverləri cavab vermədi. Ondan əvvəl soruşmaq yalnız eyni cavabı verərdi.',
+ 'tours.poi.widen': '{distance} qədər genişləndir',
'tours.poi.fromRoute': 'marşrutdan {distance}',
'tours.poi.along': '{distance}-də',
'tours.poi.source.osm': 'OpenStreetMap-dən',
diff --git a/shared/src/i18n/br/tours.ts b/shared/src/i18n/br/tours.ts
index 98d73d23e..224ac83e2 100644
--- a/shared/src/i18n/br/tours.ts
+++ b/shared/src/i18n/br/tours.ts
@@ -370,6 +370,11 @@ const tours: TranslationStrings = {
'tours.poi.capped': 'O passeio é longo: só a primeira parte foi buscada.',
'tours.poi.truncated': 'Há mais lugares do que os mostrados. Reduza a distância ou os tipos.',
'tours.poi.empty': 'Nada encontrado a até {distance} da rota.',
+ 'tours.poi.retry': 'Tentar novamente',
+ 'tours.poi.retryIn': 'De novo em {time}',
+ 'tours.poi.retryHint':
+ 'Os servidores do OpenStreetMap não responderam. Perguntar antes disso só traria a mesma resposta.',
+ 'tours.poi.widen': 'Ampliar para {distance}',
'tours.poi.fromRoute': 'a {distance} da rota',
'tours.poi.along': 'no {distance}',
'tours.poi.source.osm': 'Do OpenStreetMap',
diff --git a/shared/src/i18n/ca/tours.ts b/shared/src/i18n/ca/tours.ts
index 314394554..aaa75b8ff 100644
--- a/shared/src/i18n/ca/tours.ts
+++ b/shared/src/i18n/ca/tours.ts
@@ -371,6 +371,11 @@ const tours: TranslationStrings = {
'tours.poi.capped': "La ruta és llarga: només se n'ha cercat la primera part.",
'tours.poi.truncated': 'Hi ha més llocs dels que es mostren. Redueix la distància o els tipus.',
'tours.poi.empty': "No s'ha trobat res a menys de {distance} de la ruta.",
+ 'tours.poi.retry': 'Torna-ho a provar',
+ 'tours.poi.retryIn': "De nou d'aquí a {time}",
+ 'tours.poi.retryHint':
+ "Els servidors d'OpenStreetMap no han respost. Preguntar abans només tornaria la mateixa resposta.",
+ 'tours.poi.widen': 'Amplia a {distance}',
'tours.poi.fromRoute': 'a {distance} de la ruta',
'tours.poi.along': 'al {distance}',
'tours.poi.source.osm': "D'OpenStreetMap",
diff --git a/shared/src/i18n/cs/tours.ts b/shared/src/i18n/cs/tours.ts
index 038ba7753..b818a6b7d 100644
--- a/shared/src/i18n/cs/tours.ts
+++ b/shared/src/i18n/cs/tours.ts
@@ -364,6 +364,10 @@ const tours: TranslationStrings = {
'tours.poi.capped': 'Túra je dlouhá: prohledána byla jen její první část.',
'tours.poi.truncated': 'Míst je víc, než se zobrazuje. Zmenši vzdálenost nebo druhy.',
'tours.poi.empty': 'Do {distance} od trasy nic nenalezeno.',
+ 'tours.poi.retry': 'Zkusit znovu',
+ 'tours.poi.retryIn': 'Znovu za {time}',
+ 'tours.poi.retryHint': 'Servery OpenStreetMap neodpověděly. Dřívější dotaz by vrátil jen stejnou odpověď.',
+ 'tours.poi.widen': 'Rozšířit na {distance}',
'tours.poi.fromRoute': '{distance} od trasy',
'tours.poi.along': 'na {distance}',
'tours.poi.source.osm': 'Z OpenStreetMap',
diff --git a/shared/src/i18n/de/tours.ts b/shared/src/i18n/de/tours.ts
index d2ae873b9..8e4acc581 100644
--- a/shared/src/i18n/de/tours.ts
+++ b/shared/src/i18n/de/tours.ts
@@ -373,6 +373,11 @@ const tours: TranslationStrings = {
'tours.poi.capped': 'Die Tour ist lang: Nur ihr erster Teil wurde durchsucht.',
'tours.poi.truncated': 'Es gibt mehr Orte als angezeigt. Verkleinere den Abstand oder wähle weniger Arten.',
'tours.poi.empty': 'Nichts gefunden im Abstand von {distance} zur Route.',
+ 'tours.poi.retry': 'Erneut versuchen',
+ 'tours.poi.retryIn': 'Erneut in {time}',
+ 'tours.poi.retryHint':
+ 'Die OpenStreetMap-Server haben nicht geantwortet. Vorher nachzufragen brächte nur dieselbe Antwort.',
+ 'tours.poi.widen': 'Auf {distance} erweitern',
'tours.poi.fromRoute': '{distance} von der Route',
'tours.poi.along': 'bei {distance}',
'tours.poi.source.osm': 'Aus OpenStreetMap',
diff --git a/shared/src/i18n/en/tours.ts b/shared/src/i18n/en/tours.ts
index c7e7e4279..bd4c8fbb4 100644
--- a/shared/src/i18n/en/tours.ts
+++ b/shared/src/i18n/en/tours.ts
@@ -363,6 +363,10 @@ const tours: TranslationStrings = {
'tours.poi.capped': 'The tour is long: only its first part was searched.',
'tours.poi.truncated': 'There are more places than shown. Narrow the distance or the kinds.',
'tours.poi.empty': 'Nothing found within {distance} of the route.',
+ 'tours.poi.retry': 'Try again',
+ 'tours.poi.retryIn': 'Again in {time}',
+ 'tours.poi.retryHint': 'The OpenStreetMap servers did not answer. Asking before then would only get the same answer.',
+ 'tours.poi.widen': 'Widen to {distance}',
'tours.poi.fromRoute': '{distance} from the route',
'tours.poi.along': 'at {distance}',
'tours.poi.source.osm': 'From OpenStreetMap',
diff --git a/shared/src/i18n/es/tours.ts b/shared/src/i18n/es/tours.ts
index 6f6a897f8..d2cf69463 100644
--- a/shared/src/i18n/es/tours.ts
+++ b/shared/src/i18n/es/tours.ts
@@ -370,6 +370,11 @@ const tours: TranslationStrings = {
'tours.poi.capped': 'La ruta es larga: solo se buscó su primera parte.',
'tours.poi.truncated': 'Hay más lugares de los que se muestran. Reduce la distancia o los tipos.',
'tours.poi.empty': 'No se encontró nada a menos de {distance} de la ruta.',
+ 'tours.poi.retry': 'Reintentar',
+ 'tours.poi.retryIn': 'De nuevo en {time}',
+ 'tours.poi.retryHint':
+ 'Los servidores de OpenStreetMap no respondieron. Preguntar antes solo daría la misma respuesta.',
+ 'tours.poi.widen': 'Ampliar a {distance}',
'tours.poi.fromRoute': 'a {distance} de la ruta',
'tours.poi.along': 'en el {distance}',
'tours.poi.source.osm': 'De OpenStreetMap',
diff --git a/shared/src/i18n/et/tours.ts b/shared/src/i18n/et/tours.ts
index 5a363467c..d38f4d424 100644
--- a/shared/src/i18n/et/tours.ts
+++ b/shared/src/i18n/et/tours.ts
@@ -365,6 +365,10 @@ const tours: TranslationStrings = {
'tours.poi.capped': 'Matk on pikk: läbi otsiti ainult selle esimene osa.',
'tours.poi.truncated': 'Kohti on rohkem, kui näidatakse. Vähenda kaugust või liike.',
'tours.poi.empty': 'Marsruudist {distance} kaugusel ei leitud midagi.',
+ 'tours.poi.retry': 'Proovi uuesti',
+ 'tours.poi.retryIn': 'Uuesti {time} pärast',
+ 'tours.poi.retryHint': 'OpenStreetMapi serverid ei vastanud. Enne seda küsimine annaks vaid sama vastuse.',
+ 'tours.poi.widen': 'Laienda {distance} peale',
'tours.poi.fromRoute': 'marsruudist {distance}',
'tours.poi.along': '{distance} juures',
'tours.poi.source.osm': 'OpenStreetMapist',
diff --git a/shared/src/i18n/fr/tours.ts b/shared/src/i18n/fr/tours.ts
index 5fa7cb819..6c0e29c58 100644
--- a/shared/src/i18n/fr/tours.ts
+++ b/shared/src/i18n/fr/tours.ts
@@ -376,6 +376,11 @@ const tours: TranslationStrings = {
'tours.poi.capped': "L'itinéraire est long : seule sa première partie a été cherchée.",
'tours.poi.truncated': "Il y a plus de lieux qu'affichés. Réduis la distance ou les types.",
'tours.poi.empty': "Rien trouvé à moins de {distance} de l'itinéraire.",
+ 'tours.poi.retry': 'Réessayer',
+ 'tours.poi.retryIn': 'À nouveau dans {time}',
+ 'tours.poi.retryHint':
+ "Les serveurs OpenStreetMap n'ont pas répondu. Redemander avant ne donnerait que la même réponse.",
+ 'tours.poi.widen': 'Élargir à {distance}',
'tours.poi.fromRoute': "à {distance} de l'itinéraire",
'tours.poi.along': 'au {distance}',
'tours.poi.source.osm': "D'OpenStreetMap",
diff --git a/shared/src/i18n/gr/tours.ts b/shared/src/i18n/gr/tours.ts
index 9c97b032d..e21eb6307 100644
--- a/shared/src/i18n/gr/tours.ts
+++ b/shared/src/i18n/gr/tours.ts
@@ -378,6 +378,11 @@ const tours: TranslationStrings = {
'tours.poi.capped': 'Η διαδρομή είναι μεγάλη: αναζητήθηκε μόνο το πρώτο της μέρος.',
'tours.poi.truncated': 'Υπάρχουν περισσότερα μέρη από όσα εμφανίζονται. Μείωσε την απόσταση ή τα είδη.',
'tours.poi.empty': 'Δεν βρέθηκε τίποτα σε απόσταση {distance} από τη διαδρομή.',
+ 'tours.poi.retry': 'Δοκιμή ξανά',
+ 'tours.poi.retryIn': 'Ξανά σε {time}',
+ 'tours.poi.retryHint':
+ 'Οι διακομιστές του OpenStreetMap δεν απάντησαν. Μια ερώτηση νωρίτερα θα έφερνε μόνο την ίδια απάντηση.',
+ 'tours.poi.widen': 'Διεύρυνση σε {distance}',
'tours.poi.fromRoute': '{distance} από τη διαδρομή',
'tours.poi.along': 'στο {distance}',
'tours.poi.source.osm': 'Από το OpenStreetMap',
diff --git a/shared/src/i18n/hu/tours.ts b/shared/src/i18n/hu/tours.ts
index 09709cc6f..ce0d3a1d9 100644
--- a/shared/src/i18n/hu/tours.ts
+++ b/shared/src/i18n/hu/tours.ts
@@ -371,6 +371,10 @@ const tours: TranslationStrings = {
'tours.poi.capped': 'A túra hosszú: csak az első részét kerestük át.',
'tours.poi.truncated': 'Több hely van, mint amennyi látszik. Szűkítsd a távolságot vagy a fajtákat.',
'tours.poi.empty': 'Az útvonaltól {distance} távolságon belül nincs találat.',
+ 'tours.poi.retry': 'Újra',
+ 'tours.poi.retryIn': 'Újra {time} múlva',
+ 'tours.poi.retryHint': 'Az OpenStreetMap szerverei nem válaszoltak. Előbb kérdezni csak ugyanazt a választ hozná.',
+ 'tours.poi.widen': 'Bővítés {distance} távolságra',
'tours.poi.fromRoute': '{distance} az útvonaltól',
'tours.poi.along': '{distance}-nél',
'tours.poi.source.osm': 'Az OpenStreetMapből',
diff --git a/shared/src/i18n/id/tours.ts b/shared/src/i18n/id/tours.ts
index 943511a7b..c42d71ea6 100644
--- a/shared/src/i18n/id/tours.ts
+++ b/shared/src/i18n/id/tours.ts
@@ -365,6 +365,11 @@ const tours: TranslationStrings = {
'tours.poi.capped': 'Turnya panjang: hanya bagian pertamanya yang dicari.',
'tours.poi.truncated': 'Ada lebih banyak tempat daripada yang ditampilkan. Persempit jarak atau jenisnya.',
'tours.poi.empty': 'Tidak ada yang ditemukan dalam {distance} dari rute.',
+ 'tours.poi.retry': 'Coba lagi',
+ 'tours.poi.retryIn': 'Lagi dalam {time}',
+ 'tours.poi.retryHint':
+ 'Server OpenStreetMap tidak menjawab. Bertanya sebelum itu hanya akan mendapat jawaban yang sama.',
+ 'tours.poi.widen': 'Perluas ke {distance}',
'tours.poi.fromRoute': '{distance} dari rute',
'tours.poi.along': 'di {distance}',
'tours.poi.source.osm': 'Dari OpenStreetMap',
diff --git a/shared/src/i18n/it/tours.ts b/shared/src/i18n/it/tours.ts
index cc98a428f..a22bbf0b8 100644
--- a/shared/src/i18n/it/tours.ts
+++ b/shared/src/i18n/it/tours.ts
@@ -373,6 +373,11 @@ const tours: TranslationStrings = {
'tours.poi.capped': 'Il percorso è lungo: è stata cercata solo la prima parte.',
'tours.poi.truncated': 'Ci sono più luoghi di quelli mostrati. Riduci la distanza o i tipi.',
'tours.poi.empty': 'Nulla trovato entro {distance} dal percorso.',
+ 'tours.poi.retry': 'Riprova',
+ 'tours.poi.retryIn': 'Di nuovo tra {time}',
+ 'tours.poi.retryHint':
+ 'I server di OpenStreetMap non hanno risposto. Chiedere prima darebbe solo la stessa risposta.',
+ 'tours.poi.widen': 'Allarga a {distance}',
'tours.poi.fromRoute': 'a {distance} dal percorso',
'tours.poi.along': 'al {distance}',
'tours.poi.source.osm': 'Da OpenStreetMap',
diff --git a/shared/src/i18n/ja/tours.ts b/shared/src/i18n/ja/tours.ts
index f5f5b3877..8e97d9487 100644
--- a/shared/src/i18n/ja/tours.ts
+++ b/shared/src/i18n/ja/tours.ts
@@ -355,6 +355,11 @@ const tours: TranslationStrings = {
'tours.poi.capped': 'ツアーが長いため、最初の部分だけを検索しました。',
'tours.poi.truncated': '表示されている以上の場所があります。距離か種類を絞り込んでください。',
'tours.poi.empty': 'ルートから {distance} 以内には見つかりませんでした。',
+ 'tours.poi.retry': 'もう一度試す',
+ 'tours.poi.retryIn': '{time} 後に再試行',
+ 'tours.poi.retryHint':
+ 'OpenStreetMap のサーバーが応答しませんでした。それより前に問い合わせても同じ結果になるだけです。',
+ 'tours.poi.widen': '{distance} に広げる',
'tours.poi.fromRoute': 'ルートから {distance}',
'tours.poi.along': '{distance} 地点',
'tours.poi.source.osm': 'OpenStreetMap より',
diff --git a/shared/src/i18n/ko/tours.ts b/shared/src/i18n/ko/tours.ts
index c57b46e79..e2509eb67 100644
--- a/shared/src/i18n/ko/tours.ts
+++ b/shared/src/i18n/ko/tours.ts
@@ -354,6 +354,10 @@ const tours: TranslationStrings = {
'tours.poi.capped': '투어가 길어서 앞부분만 검색했습니다.',
'tours.poi.truncated': '표시된 것보다 장소가 더 많습니다. 거리나 종류를 줄이세요.',
'tours.poi.empty': '경로에서 {distance} 이내에 찾은 것이 없습니다.',
+ 'tours.poi.retry': '다시 시도',
+ 'tours.poi.retryIn': '{time} 후 다시',
+ 'tours.poi.retryHint': 'OpenStreetMap 서버가 응답하지 않았습니다. 그 전에 다시 물어도 같은 답만 돌아옵니다.',
+ 'tours.poi.widen': '{distance}(으)로 넓히기',
'tours.poi.fromRoute': '경로에서 {distance}',
'tours.poi.along': '{distance} 지점',
'tours.poi.source.osm': 'OpenStreetMap 제공',
diff --git a/shared/src/i18n/nl/tours.ts b/shared/src/i18n/nl/tours.ts
index 62a43b3b4..197865a63 100644
--- a/shared/src/i18n/nl/tours.ts
+++ b/shared/src/i18n/nl/tours.ts
@@ -372,6 +372,11 @@ const tours: TranslationStrings = {
'tours.poi.capped': 'De tocht is lang: alleen het eerste deel is doorzocht.',
'tours.poi.truncated': 'Er zijn meer plekken dan getoond. Verklein de afstand of de soorten.',
'tours.poi.empty': 'Niets gevonden binnen {distance} van de route.',
+ 'tours.poi.retry': 'Opnieuw proberen',
+ 'tours.poi.retryIn': 'Opnieuw over {time}',
+ 'tours.poi.retryHint':
+ 'De OpenStreetMap-servers gaven geen antwoord. Eerder vragen levert alleen hetzelfde antwoord op.',
+ 'tours.poi.widen': 'Verruim tot {distance}',
'tours.poi.fromRoute': '{distance} van de route',
'tours.poi.along': 'bij {distance}',
'tours.poi.source.osm': 'Uit OpenStreetMap',
diff --git a/shared/src/i18n/pl/tours.ts b/shared/src/i18n/pl/tours.ts
index 40b5ae888..5d8a65952 100644
--- a/shared/src/i18n/pl/tours.ts
+++ b/shared/src/i18n/pl/tours.ts
@@ -380,6 +380,11 @@ const tours: TranslationStrings = {
'tours.poi.capped': 'Trasa jest długa: przeszukano tylko jej pierwszą część.',
'tours.poi.truncated': 'Miejsc jest więcej, niż pokazano. Zmniejsz odległość lub liczbę rodzajów.',
'tours.poi.empty': 'Nic nie znaleziono w odległości {distance} od trasy.',
+ 'tours.poi.retry': 'Spróbuj ponownie',
+ 'tours.poi.retryIn': 'Ponownie za {time}',
+ 'tours.poi.retryHint':
+ 'Serwery OpenStreetMap nie odpowiedziały. Wcześniejsze pytanie dałoby tylko tę samą odpowiedź.',
+ 'tours.poi.widen': 'Poszerz do {distance}',
'tours.poi.fromRoute': '{distance} od trasy',
'tours.poi.along': 'na {distance}',
'tours.poi.source.osm': 'Z OpenStreetMap',
diff --git a/shared/src/i18n/ru/tours.ts b/shared/src/i18n/ru/tours.ts
index 31f3f78d4..b52a68f9d 100644
--- a/shared/src/i18n/ru/tours.ts
+++ b/shared/src/i18n/ru/tours.ts
@@ -383,6 +383,10 @@ const tours: TranslationStrings = {
'tours.poi.capped': 'Маршрут длинный: проверена только его первая часть.',
'tours.poi.truncated': 'Мест больше, чем показано. Уменьшите расстояние или число видов.',
'tours.poi.empty': 'В пределах {distance} от маршрута ничего не найдено.',
+ 'tours.poi.retry': 'Повторить',
+ 'tours.poi.retryIn': 'Снова через {time}',
+ 'tours.poi.retryHint': 'Серверы OpenStreetMap не ответили. Запрос раньше этого времени дал бы тот же ответ.',
+ 'tours.poi.widen': 'Расширить до {distance}',
'tours.poi.fromRoute': '{distance} от маршрута',
'tours.poi.along': 'на {distance}',
'tours.poi.source.osm': 'Из OpenStreetMap',
diff --git a/shared/src/i18n/sk/tours.ts b/shared/src/i18n/sk/tours.ts
index cbe2c1b26..7609a0324 100644
--- a/shared/src/i18n/sk/tours.ts
+++ b/shared/src/i18n/sk/tours.ts
@@ -365,6 +365,10 @@ const tours: TranslationStrings = {
'tours.poi.capped': 'Túra je dlhá: prehľadaná bola len jej prvá časť.',
'tours.poi.truncated': 'Miest je viac, než sa zobrazuje. Zmenši vzdialenosť alebo druhy.',
'tours.poi.empty': 'Do {distance} od trasy sa nič nenašlo.',
+ 'tours.poi.retry': 'Skúsiť znova',
+ 'tours.poi.retryIn': 'Znova o {time}',
+ 'tours.poi.retryHint': 'Servery OpenStreetMap neodpovedali. Skoršia otázka by priniesla len rovnakú odpoveď.',
+ 'tours.poi.widen': 'Rozšíriť na {distance}',
'tours.poi.fromRoute': '{distance} od trasy',
'tours.poi.along': 'na {distance}',
'tours.poi.source.osm': 'Z OpenStreetMap',
diff --git a/shared/src/i18n/sv/tours.ts b/shared/src/i18n/sv/tours.ts
index 2263e64b7..2b3d91e98 100644
--- a/shared/src/i18n/sv/tours.ts
+++ b/shared/src/i18n/sv/tours.ts
@@ -362,6 +362,10 @@ const tours: TranslationStrings = {
'tours.poi.capped': 'Turen är lång: bara den första delen genomsöktes.',
'tours.poi.truncated': 'Det finns fler platser än som visas. Minska avståndet eller slagen.',
'tours.poi.empty': 'Inget hittades inom {distance} från rutten.',
+ 'tours.poi.retry': 'Försök igen',
+ 'tours.poi.retryIn': 'Igen om {time}',
+ 'tours.poi.retryHint': 'OpenStreetMaps servrar svarade inte. Att fråga innan dess ger bara samma svar.',
+ 'tours.poi.widen': 'Vidga till {distance}',
'tours.poi.fromRoute': '{distance} från rutten',
'tours.poi.along': 'vid {distance}',
'tours.poi.source.osm': 'Från OpenStreetMap',
diff --git a/shared/src/i18n/th/tours.ts b/shared/src/i18n/th/tours.ts
index 84f04f2ad..1a200bdbf 100644
--- a/shared/src/i18n/th/tours.ts
+++ b/shared/src/i18n/th/tours.ts
@@ -346,6 +346,10 @@ const tours: TranslationStrings = {
'tours.poi.capped': 'ทัวร์ยาว ค้นหาได้เฉพาะช่วงแรก',
'tours.poi.truncated': 'มีสถานที่มากกว่าที่แสดง ลดระยะหรือประเภทลง',
'tours.poi.empty': 'ไม่พบสิ่งใดภายใน {distance} จากเส้นทาง',
+ 'tours.poi.retry': 'ลองอีกครั้ง',
+ 'tours.poi.retryIn': 'อีกครั้งใน {time}',
+ 'tours.poi.retryHint': 'เซิร์ฟเวอร์ OpenStreetMap ไม่ตอบสนอง การถามก่อนเวลานั้นจะได้คำตอบเดิมเท่านั้น',
+ 'tours.poi.widen': 'ขยายเป็น {distance}',
'tours.poi.fromRoute': 'ห่างจากเส้นทาง {distance}',
'tours.poi.along': 'ที่ {distance}',
'tours.poi.source.osm': 'จาก OpenStreetMap',
diff --git a/shared/src/i18n/tours-locales.spec.ts b/shared/src/i18n/tours-locales.spec.ts
index 6eaeda7a7..3a050eeb4 100644
--- a/shared/src/i18n/tours-locales.spec.ts
+++ b/shared/src/i18n/tours-locales.spec.ts
@@ -20,7 +20,7 @@ const toursModules = import.meta.glob<{ default: TranslationStrings }>('./*/tour
const TOUR_DOMAINS: { file: string; generalKeyCount: number; modules: DomainModules }[] = [
{
file: 'tours',
- generalKeyCount: 1283,
+ generalKeyCount: 1287,
modules: toursModules,
},
{
diff --git a/shared/src/i18n/tr/tours.ts b/shared/src/i18n/tr/tours.ts
index d13fff911..2375ccf62 100644
--- a/shared/src/i18n/tr/tours.ts
+++ b/shared/src/i18n/tr/tours.ts
@@ -364,6 +364,10 @@ const tours: TranslationStrings = {
'tours.poi.capped': 'Tur uzun: yalnızca ilk kısmında arama yapıldı.',
'tours.poi.truncated': 'Gösterilenden fazla yer var. Mesafeyi veya türleri daralt.',
'tours.poi.empty': 'Rotaya {distance} mesafe içinde bir şey bulunamadı.',
+ 'tours.poi.retry': 'Yeniden dene',
+ 'tours.poi.retryIn': '{time} sonra yeniden',
+ 'tours.poi.retryHint': 'OpenStreetMap sunucuları yanıt vermedi. Daha önce sormak yalnızca aynı yanıtı getirir.',
+ 'tours.poi.widen': '{distance} mesafeye genişlet',
'tours.poi.fromRoute': 'rotaya {distance}',
'tours.poi.along': '{distance} noktasında',
'tours.poi.source.osm': "OpenStreetMap'ten",
diff --git a/shared/src/i18n/uk/tours.ts b/shared/src/i18n/uk/tours.ts
index 598efc509..26ed245dc 100644
--- a/shared/src/i18n/uk/tours.ts
+++ b/shared/src/i18n/uk/tours.ts
@@ -378,6 +378,10 @@ const tours: TranslationStrings = {
'tours.poi.capped': 'Маршрут довгий: перевірено лише його першу частину.',
'tours.poi.truncated': 'Місць більше, ніж показано. Зменште відстань або кількість видів.',
'tours.poi.empty': 'У межах {distance} від маршруту нічого не знайдено.',
+ 'tours.poi.retry': 'Спробувати ще',
+ 'tours.poi.retryIn': 'Знову через {time}',
+ 'tours.poi.retryHint': 'Сервери OpenStreetMap не відповіли. Запит раніше дав би лише ту саму відповідь.',
+ 'tours.poi.widen': 'Розширити до {distance}',
'tours.poi.fromRoute': '{distance} від маршруту',
'tours.poi.along': 'на {distance}',
'tours.poi.source.osm': 'З OpenStreetMap',
diff --git a/shared/src/i18n/vi/tours.ts b/shared/src/i18n/vi/tours.ts
index 2b8113ad6..2cad973a9 100644
--- a/shared/src/i18n/vi/tours.ts
+++ b/shared/src/i18n/vi/tours.ts
@@ -363,6 +363,10 @@ const tours: TranslationStrings = {
'tours.poi.capped': 'Chuyến đi dài: chỉ phần đầu được tìm.',
'tours.poi.truncated': 'Có nhiều địa điểm hơn số hiển thị. Hãy thu hẹp khoảng cách hoặc loại.',
'tours.poi.empty': 'Không tìm thấy gì trong khoảng {distance} tới lộ trình.',
+ 'tours.poi.retry': 'Thử lại',
+ 'tours.poi.retryIn': 'Thử lại sau {time}',
+ 'tours.poi.retryHint': 'Máy chủ OpenStreetMap không phản hồi. Hỏi trước lúc đó cũng chỉ nhận cùng một câu trả lời.',
+ 'tours.poi.widen': 'Mở rộng đến {distance}',
'tours.poi.fromRoute': 'cách lộ trình {distance}',
'tours.poi.along': 'tại {distance}',
'tours.poi.source.osm': 'Từ OpenStreetMap',
diff --git a/shared/src/i18n/zh-TW/tours.ts b/shared/src/i18n/zh-TW/tours.ts
index d256d21f0..801864dee 100644
--- a/shared/src/i18n/zh-TW/tours.ts
+++ b/shared/src/i18n/zh-TW/tours.ts
@@ -331,6 +331,10 @@ const tours: TranslationStrings = {
'tours.poi.capped': '路線較長:只搜尋了前一段。',
'tours.poi.truncated': '地點比顯示的更多。請縮小範圍或類型。',
'tours.poi.empty': '距路線 {distance} 內沒有找到任何地點。',
+ 'tours.poi.retry': '重試',
+ 'tours.poi.retryIn': '{time} 後重試',
+ 'tours.poi.retryHint': 'OpenStreetMap 伺服器沒有回應。在此之前再問也只會得到相同的結果。',
+ 'tours.poi.widen': '擴大到 {distance}',
'tours.poi.fromRoute': '距路線 {distance}',
'tours.poi.along': '在 {distance} 處',
'tours.poi.source.osm': '來自 OpenStreetMap',
diff --git a/shared/src/i18n/zh/tours.ts b/shared/src/i18n/zh/tours.ts
index a68a21124..f68ac6026 100644
--- a/shared/src/i18n/zh/tours.ts
+++ b/shared/src/i18n/zh/tours.ts
@@ -332,6 +332,10 @@ const tours: TranslationStrings = {
'tours.poi.capped': '路线较长:只搜索了前一段。',
'tours.poi.truncated': '地点比显示的更多。请缩小范围或类型。',
'tours.poi.empty': '距路线 {distance} 内没有找到任何地点。',
+ 'tours.poi.retry': '重试',
+ 'tours.poi.retryIn': '{time} 后重试',
+ 'tours.poi.retryHint': 'OpenStreetMap 服务器没有响应。在此之前再问也只会得到相同的结果。',
+ 'tours.poi.widen': '扩大到 {distance}',
'tours.poi.fromRoute': '距路线 {distance}',
'tours.poi.along': '在 {distance} 处',
'tours.poi.source.osm': '来自 OpenStreetMap',
diff --git a/shared/src/tours/tour-poi-search.schema.ts b/shared/src/tours/tour-poi-search.schema.ts
index d8ad4baf1..7e0e8972d 100644
--- a/shared/src/tours/tour-poi-search.schema.ts
+++ b/shared/src/tours/tour-poi-search.schema.ts
@@ -107,5 +107,7 @@ export const tourPoiSearchResponseSchema = z.object({
capped: z.boolean(),
/** Kinds no source could be asked for right now; their places are missing, not absent. */
unavailable: z.array(tourPoiCategorySchema),
+ /** PLN-05: seconds until asking again makes sense, beside unavailable kinds only; absent when now. */
+ retry_after_s: z.number().int().positive().optional(),
});
export type TourPoiSearchResponse = z.infer<typeof tourPoiSearchResponseSchema>;