diff --git a/DATA_SOURCES.md b/DATA_SOURCES.md index 0b012e812..563f28544 100644 --- a/DATA_SOURCES.md +++ b/DATA_SOURCES.md @@ -170,9 +170,9 @@ The optional Local ADS-B layer and the broadcast-FM receiver use radio you recei - **City of Toronto RESCU cameras.** Keyless. The camera list is the City's public `tmcearthcameras.json` on `opendata.toronto.ca` (dataset "Traffic Cameras", Transportation Services), served as JSONP and unwrapped with an anchored pattern. This is the municipal network the Ontario 511 pack does not carry: downtown arterials plus the Gardiner, DVP, Allen and Lake Shore. The list publishes no frame URL, so frame URLs are BUILT from the documented `CameraImages/loc####.jpg` convention and a strictly-digits camera number, pinning the frame proxy to the portal origin by construction; the list fetch refuses redirects and bounds the body it buffers. Frames are fetched at request time and never stored or redistributed. The dataset publishes no camera facing: the `D1`-`D4` fields are the directions of the *comparison* images (static reference stills captured in 2016 under a different path), not a bearing for the live pan-tilt-zoom frame, so headings use the shared id-hash fallback at low confidence and are corrected with the in-app calibration gizmo. A camera that is temporarily out of service still answers 200 with a byte-identical "Image Unavailable" placeholder rather than an error (about 6% of the network at any moment), so such a camera reads as healthy; the frame it shows is the agency's, not a synthesized one. The licence requires the attribution statement above. Disable with `CCTV_TORONTO_ENABLED=0`. - **Camera frame content.** Public camera frames can contain people, vehicles and license plates, and the camera layer does nothing with them beyond putting them on the map. A successful upstream response is relayed as the provider served it: nothing in the camera pipeline blurs, redacts, enhances or restores it, and nothing there runs face, plate or object detection or otherwise recognises or classifies what is in the picture. (The ALPR layer described below maps where plate-reader cameras are, from locations contributors tagged in OpenStreetMap; it reads nothing from any camera frame.) When an upstream has no frame for a camera, what you see instead is a Google Street View still or the app's own placeholder card; the panel's source badge names which of them you are looking at, and a refresh that fails after a frame has arrived leaves the last good picture on screen rather than replacing it. The browser resamples each frame for display: onto a fixed 1920x1080 surface for the camera's projection plane in the scene, and onto a 192x108 canvas for the small ambient card. That scaling is the only change made to the picture, and the only pixels the camera layer reads back are a 64x36 downscale hashed to tell whether the picture has changed. Live streams are piped through; the still path reads the image into memory to pass it on — TxDOT wraps its JPEG in a JSON envelope, which is decoded there — and no frame is written to disk (the disk cache, `.gev-cache/`, holds feed JSON for other layers and never camera imagery). Outside that pipeline, the voice assistant is the one feature that sends imagery anywhere: when it answers a question about what is in view it may attach a downscaled screenshot of the rendered scene — including any camera plane on screen — to the request it sends to the voice model. Frames are fetched only from server-registered camera URLs — a client cannot hand the proxy a URL (see [SECURITY.md](SECURITY.md)). What the app does stays inside the line README draws: no named-person search, no face recognition, no tracking individuals. - **Transit (GTFS-Realtime).** The proxy requests only registered operator feeds, validates redirects, bounds responses, and uses conditional requests, short snapshot caching and failure backoff. All sixteen registered regions are live-enabled; each can be disabled independently. Vehicles use delayed playback between reports, with report age and waiting states shown separately. Session-local selected trails are available for every feed. MBTA additionally retains up to 15 minutes of recently observed positions in the running proxy, so available history can survive a browser reload; server restart clears it. History reads never fetch upstream, and other feeds have no proxy retention. Nothing is archived to disk or collected in the background. Operator text credits are included as a courtesy and do not imply endorsement. Heights are aligned to work with Google 3D tiles; subway markers are shown at street level because these feeds do not supply depth. The TTC feed is BusTime, the surface system: it carries buses and streetcars and no subway at all. About four in ten of its vehicles report no route at all (unassigned or deadheading), and those are shown with the feed default rather than a route-established mode. It sends no ETag or Last-Modified, so its conditional requests fall through to the ordinary snapshot cache. Three Golden Horseshoe neighbours run alongside it — MiWay, Hamilton HSR and Durham Region Transit — each bus-only and each polled only near its own region. Durham Region Transit publishes no bearing on any vehicle, so those sprites take their heading from observed movement like any other feed that omits it. Guelph, Kingston and Barrie extend the same pattern eastward and north. Hamilton, Guelph, Burlington and YRT publish route ids that are not the number on the vehicle, so those entries carry a route-name table taken from each operator’s own published GTFS; any id missing from a table renders unchanged rather than blank. A label is never invented: YRT runs a route `9101` that appears nowhere in its published routes, so it stays as the feed sends it. Burlington’s is the one that cannot be shortcut: `351` is route 1 while `3510` is route 10, so the table is a real join rather than a trimmed prefix. GO Transit / Metrolinx is deliberately absent: its REALTIME feed requires an API key issued by manual review, which the keyless admission rule excludes (its static schedule download is keyless, but carries no vehicle positions). Barrie and YRT/Viva each invite acceptance of their licence through a form, and each licence also states that using the data is itself acceptance; this deployment relies on that clause, which is recorded in both entries. Grand River Transit in Waterloo is absent for a different reason: it answers, but its feed header was months stale and it publishes no per-vehicle timestamps, so it would render vehicles that look live and are not. Ottawa’s OC Transpo falls to the same keyless admission rule as GO Transit — its realtime feed requires an API key. London Transit and Thunder Bay Transit publish vehicle positions over plain HTTP with no HTTPS endpoint available. Every other Ontario system — Brampton, Oakville, Niagara, Milton, Windsor, Greater Sudbury, UP Express and a dozen smaller operators — publishes static GTFS schedules only, with no realtime vehicle positions to register. Between the nine included and these exclusions, every Ontario realtime vehicle-position feed catalogued in the Mobility Database is accounted for. -- **Radio country coverage (optional).** Set `RADIO_PRIORITY_COUNTRIES=IN,PL` in the local `.env` and restart to include stations beyond the global click charts. The operator may choose up to eight unique ISO alpha-2 country codes; no key is needed. Each country adds one bounded query (at most 200 rows) and reserves up to 40 unique, usable stations inside the existing 750-station catalog. Country seeds precede specialist-tag seeds and global popularity fill; unused slots return to the shared pool. This is a coverage preference, not an exhaustive national directory or a guarantee of stations in every city. Countries with no eligible HTTPS MP3/AAC geolocated stations remain empty. An unset list preserves global selection. Country requests share the directory cache and three-worker pool; a failed country query cannot replace a healthy snapshot. Failed/degraded refreshes back off for one minute, with at most three mirrors per query. +- **Radio country coverage (optional).** Set `RADIO_PRIORITY_COUNTRIES=IN,PL` in the local `.env` and restart to include stations beyond the global click charts. The operator may choose up to eight unique ISO alpha-2 country codes; no key is needed. Each country adds one bounded query (at most 200 rows) and reserves up to 40 unique, usable stations inside the existing 750-station catalog. Country seeds precede specialist-tag seeds and global popularity fill; unused slots return to the shared pool. This is a coverage preference, not an exhaustive national directory or a guarantee of stations in every city. Countries with no eligible HTTPS MP3/AAC geolocated stations remain empty. An unset list preserves global selection. Country requests share the directory cache and three-worker pool; failed country queries are reported in coverage without blocking a healthy global refresh. Failed/degraded refreshes back off for one minute, with at most three mirrors per query. -- **Radio Browser.** `/api/radio/stations` discovers official API mirrors, makes bounded and coalesced healthy/geolocated HTTPS-station queries, caches the normalized public-domain directory for 45 minutes, and may serve the last good catalog for up to seven days during an outage. Refreshes must meet minimum accepted-query and station coverage before replacing a warm catalog; schema-valid responses whose rows all fail the product's health policy do not count as successful queries. A usable partial cold catalog is explicitly `DEGRADED`, and malformed or empty successful payloads are rejected atomically. Every directory and click-count request rejects redirects, validates all resolved addresses as globally routable (including reserved/documentation IPv4 and special/non-global IPv6 exclusions), and pins the TLS connection to a validated address. Only MP3/AAC non-HLS directory rows with public HTTPS stream targets are returned; favicons are intentionally omitted. Pressing play connects one browser audio element directly to the selected broadcaster and calls the directory's click counter through known-ID-only `POST /api/radio/click/:uuid`. GEV never proxies, caches, records, bundles, or redistributes audio. Radio Browser supplies station-level tags, not dependable current-song or upcoming-program metadata, so Radio filtering never claims either. Direct playback exposes the listener's IP address to the broadcaster, whose own stream terms apply. +- **Radio Browser.** In every installation, including when `RADIO_PRIORITY_COUNTRIES` is unset, each request tries at most three mirror candidates (later fallback candidates are skipped), and failed or partial catalog refreshes back off for 60 seconds. A cold-start failure therefore continues returning 503 during that delay even if upstream recovers. `/api/radio/stations` discovers official API mirrors, makes bounded and coalesced healthy/geolocated HTTPS-station queries, caches the normalized public-domain directory for 45 minutes, and may serve the last good catalog for up to seven days during an outage. Refreshes must meet minimum accepted-query and station coverage before replacing a warm catalog; broad/specialist responses whose rows all fail the product's health policy do not count as successful queries. Optional priority-country outcomes are advisory: valid, in-limit responses with no eligible stations succeed as empty results, while failed or malformed country queries report unsuccessful coverage without degrading the global catalog. A usable partial cold catalog is explicitly `DEGRADED`, and malformed or empty successful payloads are rejected atomically. Every directory and click-count request rejects redirects, validates all resolved addresses as globally routable (including reserved/documentation IPv4 and special/non-global IPv6 exclusions), and pins the TLS connection to a validated address. Only MP3/AAC non-HLS directory rows with public HTTPS stream targets are returned; favicons are intentionally omitted. Pressing play connects one browser audio element directly to the selected broadcaster and calls the directory's click counter through known-ID-only `POST /api/radio/click/:uuid`. GEV never proxies, caches, records, bundles, or redistributes audio. Radio Browser supplies station-level tags, not dependable current-song or upcoming-program metadata, so Radio filtering never claims either. Direct playback exposes the listener's IP address to the broadcaster, whose own stream terms apply. - **TomTom Traffic.** Optional and BYOK: without `TOMTOM_API_KEY` the traffic layer runs its built-in simulation and no TomTom data (or attribution) appears. With a key, flow vector tiles are fetched through the server-side `/api/tomtom` proxy (120 s cache + a daily tile-budget governor — `TOMTOM_DAILY_TILE_BUDGET`, default 6,000 — sized so a 31-day month stays inside TomTom's 200K monthly free allowance; still a configurable application safety ceiling, not a guarantee; TomTom's [current pricing](https://docs.tomtom.com/pricing/) lists 200K free tile requests per month) and the "Traffic flow data © TomTom" credit is registered in the Data attribution popover the moment live mode activates. TomTom data is served live and cached only transiently (≤120 s TTL under `.gev-cache/`, gitignored) — it is not bundled or redistributed. One 23 KB point-in-time tile snapshot is committed as a decode-test fixture (`src/data/fixtures/`, © TomTom, never served to the app). - **Routing (OSRM / FOSSGIS).** `/api/route` proxies the public OSRM instances FOSSGIS e.V. runs for the OpenStreetMap community (car, bike, foot profiles). They are keyless and intended for fair, interactive use — the proxy rate-limits clients (60/min, 200/min total), caps route span and response size, caches each route for 10 minutes, and identifies itself in the User-Agent. Heavy or automated use must run its own OSRM. Routes are computed from OpenStreetMap data (ODbL); the Directions layer and voice routes never redistribute them. A route the router cannot find is reported as such; the Directions layer draws nothing in that case, and voice routes fall back to a clearly labeled straight line. - **Re:Earth Terrain.** Keyless (no API key). Used two ways: (1) `src/mapStackController.js` swaps in a `Cesium.CesiumTerrainProvider` pointed at Re:Earth's `cesium-mesh/ellipsoid` quantized-mesh endpoint for globe stacks without a Cesium ion token (e.g. OSM), replacing a flat `EllipsoidTerrainProvider`; falls back to the flat provider if the endpoint can't be reached. (2) The server-side `/api/terrain/heights` proxy (disk-cached, serve-stale) resolves per-point ellipsoidal ground height for entity placement. Both are best-effort with a keyless-safe fallback (bundled EGM96 geoid math) if Re:Earth is unreachable. diff --git a/changelog.d/1206-radio-priority-countries.md b/changelog.d/1206-radio-priority-countries.md new file mode 100644 index 000000000..75536344e --- /dev/null +++ b/changelog.d/1206-radio-priority-countries.md @@ -0,0 +1,5 @@ +- Add optional keyless Radio priority-country coverage with up to 40 stations + per configured country inside the existing 750-station cap. Country query + failures do not block a healthy global catalog. Bound mirror attempts to three + and retry failed or partial refreshes after 60 seconds on all installations, + including those without priority countries configured (m3ayush, #1206). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 014bfd849..5abc85750 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -4066,8 +4066,9 @@ programmatic activation do not trigger this reveal. Radio directory admission is atomic on both sides of the proxy boundary. A refresh is healthy only when it reaches the minimum accepted-query and station -coverage; schema-valid responses with zero normalized stations count as failed -queries rather than inflating refresh health. Each specialist query also needs +coverage from broad/specialist queries; their schema-valid responses with zero +normalized stations count as failed queries rather than inflating refresh health. +Optional priority-country outcomes do not gate catalog health. Each specialist query also needs an accepted station whose normalized tags match that requested category; rows tagged only for another category remain usable catalog data but do not earn specialist health credit. A partial cold result remains @@ -5516,6 +5517,41 @@ Existing catalog validation, category filters, tuning and voice playback behavio remain unchanged. Audio connects directly to the broadcaster after an explicit play action; the source does not relay or record streams. +### Radio priority-country coverage + +Optional `RADIO_PRIORITY_COUNTRIES` is a server-owned comma-separated list of +up to eight ISO alpha-2 codes (for example `IN,PL`). Restart after changing it. +It needs no API key and adds no POWER UP entry. An empty list preserves the +existing global/tag-based directory. Invalid configuration fails at startup. + +Each country adds one Radio Browser search capped at 200 rows, with existing +HTTPS/geolocation/codec validation and an additional matching-country check. +Up to 40 unique accepted stations per country are seeded before the specialist +tag queries and global popularity fill, within the unchanged 750-station cap. +No country gets exhaustive coverage. A valid, in-limit country response with +zero eligible stations succeeds with zero selected stations. +The response's `coverage.priorityCountries` reports accepted query status and +selected counts when configured. The existing broad/specialist health policy +still applies separately. Country outcomes are advisory: failed, malformed or +oversized country queries report unsuccessful coverage but cannot degrade or +block admission of an otherwise healthy global catalog. Queries share the existing +three-worker pool, single-flight refresh and 45-minute cache. + +For every installation, including those with no priority countries configured, +at most three mirrors are tried per request; fallback mirrors beyond the first +three candidates are not attempted. Failed or partial catalog refreshes retry +after one minute, so a cold-start failure can continue returning 503 for that +minute even if upstream recovers sooner. Healthy catalogs retain the 45-minute +cache. The seven-day last-good expiry and known-station-only click reporting +remain in force. + +Validation: `node --test src/data/radioProxy.test.mjs` covers configuration, +country quotas under global popularity pressure, duplicate records, concurrency, +cache reuse, country mismatch/oversize/empty/ineligible responses, failure isolation on cold +and warm refreshes beyond seven days, and retry/backoff recovery both with and +without configured countries. `node scripts/qa-radio.mjs --url http://localhost:4173` covers the existing +750-station browser presentation and playback contract. + ## Local RTL-SDR and Local ADS-B The Radio panel holds a Local RTL-SDR card below internet radio. One browser @@ -5807,30 +5843,3 @@ datacenters, dams and the Nepal locator retain that shared credit while displaye Military fragments stitch by source identity. Different mapped parcels merge only when their footprints touch or contain one another, never across a seam tolerance gap. - - -### Radio priority-country coverage - -Optional `RADIO_PRIORITY_COUNTRIES` is a server-owned comma-separated list of -up to eight ISO alpha-2 codes (for example `IN,PL`). Restart after changing it. -It needs no API key and adds no POWER UP entry. An empty list preserves the -existing global/tag-based directory. Invalid configuration fails at startup. - -Each country adds one Radio Browser search capped at 200 rows, with existing -HTTPS/geolocation/codec validation and an additional matching-country check. -Up to 40 unique accepted stations per country are seeded before the specialist -tag queries and global popularity fill, within the unchanged 750-station cap. -No country gets exhaustive coverage; an empty valid country response is allowed. -The response's `coverage.priorityCountries` reports accepted query status and -selected counts when configured. The existing broad/specialist health policy -still applies separately; a failed country query marks the refresh degraded -and cannot evict a healthy cached catalog. Queries share the existing three-worker -pool, single-flight refresh and 45-minute cache. At most three mirrors are tried -per query; failed or partial refreshes retry after one minute. The seven-day -last-good expiry and known-station-only click reporting remain in force. - -Validation: `node --test src/data/radioProxy.test.mjs` covers configuration, -country quotas under global popularity pressure, duplicate records, concurrency, -cache reuse, country mismatch/oversize/empty responses, stale fallback and retry -backoff. `node scripts/qa-radio.mjs --url http://localhost:4173` covers the existing -750-station browser presentation and playback contract. diff --git a/server/providers/radio/catalog.js b/server/providers/radio/catalog.js index fa1b7f6be..d26eab6e6 100644 --- a/server/providers/radio/catalog.js +++ b/server/providers/radio/catalog.js @@ -254,11 +254,11 @@ export function createRadioProxyMiddleware({ ), ); return { - // Query coverage is based on accepted rows, not merely a payload that - // happens to match the upstream schema. Specialist responses must - // also contain an accepted station tagged for the requested category. + // A valid country response can contain no playable stations. Country + // coverage is advisory; only broad/specialist queries gate health. + // Specialist responses need an accepted station with matching tags. succeeded: country - ? rows.length === 0 || stations.length > 0 + ? true : stations.length > 0 && requestedTagCovered, stations, }; @@ -312,8 +312,6 @@ export function createRadioProxyMiddleware({ const broadQueryHealthy = outcomes[0].succeeded && outcomes[0].stations.length > 0; const healthReasons = []; - if (outcomes.slice(baseQueryCount).some((outcome) => !outcome.succeeded)) - healthReasons.push('priority-country-query-unhealthy'); if (!broadQueryHealthy) healthReasons.push('broad-query-unhealthy'); if (successfulQueries < RADIO_CATALOG_MIN_SUCCESSFUL_QUERIES) healthReasons.push('query-coverage-below-policy'); diff --git a/src/data/radioProxy.test.mjs b/src/data/radioProxy.test.mjs index a5ac3dee7..01b1305f8 100644 --- a/src/data/radioProxy.test.mjs +++ b/src/data/radioProxy.test.mjs @@ -585,71 +585,109 @@ test('low-click country stations survive a full global catalog, with bounded cac assert.equal((await invoke(middleware, `/click/${id}`, 'POST')).status, 204); }); -test('an unavailable country retains the last healthy snapshot instead of silently losing its stations', async () => { - let clock = 4_000_000; - let fail = false; - const middleware = createProxy({ - priorityCountries: ['IN'], now: () => clock, - fetchImpl: async (url) => { - if (String(url).includes('/json/servers')) return responseJson([{ name: 'de1.api.radio-browser.info' }]); - if (new URL(url).searchParams.has('countrycode')) { - if (fail) throw new Error('offline'); - return responseJson([station({ countrycode: 'IN', country: 'India', tags: 'community' })]); - } - return responseJson(healthyRowsForQuery(url)); - }, - }); - const first = JSON.parse((await invoke(middleware, '/stations')).body); - assert.equal(first.degraded, false); - clock += 46 * 60 * 1000; - fail = true; - const stale = JSON.parse((await invoke(middleware, '/stations')).body); - assert.equal(stale.stale, true); - assert.match(stale.degradedReason, /priority-country-query-unhealthy/); - assert.deepEqual(stale.stations, first.stations); - assert.equal(stale.acceptedGeneration, first.acceptedGeneration); - clock += 8 * 24 * 60 * 60 * 1000; - assert.equal((await invoke(middleware, '/stations')).status, 503); -}); - -test('country discovery rejects wrong-country and oversized responses, but accepts an honest empty country', async () => { - for (const mode of ['wrong', 'oversized', 'empty']) { +test('country failures never block cold or warm global catalog admission, even after seven days', async () => { + for (const coldFailure of [false, true]) { + let clock = 4_000_000; + let fail = coldFailure; + let calls = 0; const middleware = createProxy({ - priorityCountries: ['IN'], + priorityCountries: ['IN'], now: () => clock, fetchImpl: async (url) => { + calls++; if (String(url).includes('/json/servers')) return responseJson([{ name: 'de1.api.radio-browser.info' }]); - if (new URL(url).searchParams.has('countrycode')) return responseJson( - mode === 'empty' ? [] : mode === 'wrong' ? [station()] : - catalogRows('10000000', 'community', 201).map((row) => ({ ...row, countrycode: 'IN' })), - ); + if (new URL(url).searchParams.has('countrycode')) { + if (fail) throw new Error('offline'); + return responseJson([station({ countrycode: 'IN', country: 'India', tags: 'community' })]); + } return responseJson(healthyRowsForQuery(url)); }, }); - const body = JSON.parse((await invoke(middleware, '/stations')).body); - assert.equal(body.degraded, mode !== 'empty'); - assert.equal(body.coverage.priorityCountries[0].stationCount, 0); - assert.equal(body.coverage.priorityCountries[0].succeeded, mode === 'empty'); + let generation = 0; + for (const elapsed of [0, 46 * 60 * 1000, 8 * 24 * 60 * 60 * 1000]) { + clock += elapsed; + if (elapsed) fail = true; + const response = await invoke(middleware, '/stations'); + const body = JSON.parse(response.body); + assert.equal(response.status, 200); + assert.equal(body.stale, false); + assert.equal(body.degraded, false); + assert.ok(body.acceptedGeneration > generation); + generation = body.acceptedGeneration; + assert.equal(body.coverage.priorityCountries[0].succeeded, !fail); + assert.equal(body.coverage.priorityCountries[0].stationCount, fail ? 0 : 1); + const count = calls; + clock += 60_001; + assert.deepEqual(JSON.parse((await invoke(middleware, '/stations')).body), body); + assert.equal(calls, count, 'country failure does not shorten the healthy cache'); + } } }); - -test('failed cold country refreshes are coalesced and back off instead of hammering mirrors', async () => { - let clock = 9_000_000; - let calls = 0; - const middleware = createProxy({ - priorityCountries: 'IN', now: () => clock, - fetchImpl: async (url) => { - calls++; - if (String(url).includes('/json/servers')) return responseJson([{ name: 'de1.api.radio-browser.info' }]); - throw new Error('offline'); - }, - }); - assert.equal((await invoke(middleware, '/stations')).status, 503); - const initial = calls; - assert.ok(initial <= 31, 'ten queries try at most three mirrors, plus discovery'); - assert.equal((await invoke(middleware, '/stations')).status, 503); - assert.equal(calls, initial); - clock += 60_001; - assert.equal((await invoke(middleware, '/stations')).status, 503); - assert.ok(calls > initial); +test('valid countries with no eligible stations are accepted and cached; malformed country responses stay isolated', async () => { + for (const mode of ['wrong', 'oversized', 'empty', 'ineligible', 'malformed']) { + let clock = 4_000_000; + let calls = 0; + const middleware = createProxy({ + priorityCountries: ['IN'], now: () => clock, + fetchImpl: async (url) => { + calls++; + if (String(url).includes('/json/servers')) return responseJson([{ name: 'de1.api.radio-browser.info' }]); + if (new URL(url).searchParams.has('countrycode')) { + const rows = { + empty: [], wrong: [station()], malformed: [{ name: 'missing fields' }], + oversized: catalogRows('10000000', 'community', 201).map((row) => ({ ...row, countrycode: 'IN' })), + ineligible: [{ hls: 1 }, { codec: 'OGG' }, { codec: 'OPUS' }, { url_resolved: 'https://127.0.0.1/live.mp3' }] + .map((overrides) => station({ countrycode: 'IN', ...overrides })), + }; + return responseJson(rows[mode]); + } + return responseJson(healthyRowsForQuery(url)); + }, + }); + const response = await invoke(middleware, '/stations'); + const body = JSON.parse(response.body); + assert.equal(response.status, 200, mode); + assert.equal(body.degraded, false, mode); + assert.ok(body.acceptedGeneration > 0, mode); + assert.equal(body.coverage.priorityCountries[0].stationCount, 0, mode); + assert.equal(body.coverage.priorityCountries[0].succeeded, !['oversized', 'malformed'].includes(mode), mode); + const count = calls; + clock += 44 * 60 * 1000; + assert.deepEqual(JSON.parse((await invoke(middleware, '/stations')).body), body); + assert.equal(calls, count, `${mode} country response preserves the 45-minute cache`); + } }); + +for (const priorityCountries of ['', 'IN']) { + test(`cold failures coalesce, bound mirrors and back off with priority countries ${priorityCountries || 'unset'}`, async () => { + let clock = Date.UTC(2026, 0, 1); + let calls = 0; + let offline = true; + const middleware = createProxy({ + priorityCountries, now: () => clock, + fetchImpl: async (url) => { + calls++; + if (String(url).includes('/json/servers')) return responseJson([{ name: 'de1.api.radio-browser.info' }]); + if (offline) throw new Error('offline'); + if (new URL(url).searchParams.has('countrycode')) return responseJson([]); + return responseJson(healthyRowsForQuery(url)); + }, + }); + const responses = await Promise.all([invoke(middleware, '/stations'), invoke(middleware, '/stations')]); + assert.ok(responses.every((response) => response.status === 503)); + const initial = calls; + assert.equal(initial, 1 + (priorityCountries ? 10 : 9) * 3, 'one discovery and at most three mirrors per query'); + offline = false; + clock += 59_999; + assert.equal((await invoke(middleware, '/stations')).status, 503); + assert.equal(calls, initial); + clock += 2; + const recovered = await invoke(middleware, '/stations'); + assert.equal(recovered.status, 200); + assert.equal(JSON.parse(recovered.body).degraded, false); + assert.ok(calls > initial); + const afterRecovery = calls; + await invoke(middleware, '/stations'); + assert.equal(calls, afterRecovery); + }); +}