From 80b2ead154367397d448da8412c8389d094df677 Mon Sep 17 00:00:00 2001 From: daikaginza Date: Fri, 23 Oct 2026 12:39:32 +0700 Subject: [PATCH] fix(adsbdb): 720/min by default, configurable, and a 429 is not an answer The cap becomes GEV_RATELIMIT_ADSBDB_PER_MIN with a 720 default, read through resolvePerMinuteCap like the other cost limiters (0 disables, an unreadable value takes the default). On a 429 both enrichment queues make the key askable again after the error's retry-after, so the next request for that aircraft is dispatched instead of dropped. --- .env.example | 6 ++++ .../689-adsbdb-cache-and-rate-limit.md | 15 ++++---- docs/CURRENT-STATE.md | 14 +++++--- server/providers/aircraft/enrichment.js | 36 +++++++++++++------ src/layers/flights/enrichment.js | 12 +++++-- src/layers/localAdsb/enrichment.js | 22 +++++++++--- src/proxyErrorResponses.test.mjs | 4 +-- 7 files changed, 78 insertions(+), 31 deletions(-) diff --git a/.env.example b/.env.example index 55cb367a03..26906f3955 100644 --- a/.env.example +++ b/.env.example @@ -49,6 +49,12 @@ GOOGLE_MAPS_SERVER_API_KEY= # Quotas). # GEV_RATELIMIT_GOOGLE_PER_MIN=60 # uncomment to tighten from the default 120 +# Optional: per-IP requests/minute for the keyless adsbdb aircraft-enrichment +# proxy (/api/adsbdb). DEFAULTS TO 720: one tab's two enrichment queues +# (Flights and Local ADS-B) top out at 600. Same rules as above: 0 disables, +# an unreadable value takes the default. +# GEV_RATELIMIT_ADSBDB_PER_MIN=720 + # Optional: Google Photorealistic 3D Tiles through Cesium ion, Bing world # imagery, and Cesium World Terrain. The free Community plan is for eligible # personal/non-commercial use and has quotas; check current Cesium terms. A diff --git a/changelog.d/689-adsbdb-cache-and-rate-limit.md b/changelog.d/689-adsbdb-cache-and-rate-limit.md index c5a426c531..39b0942aa3 100644 --- a/changelog.d/689-adsbdb-cache-and-rate-limit.md +++ b/changelog.d/689-adsbdb-cache-and-rate-limit.md @@ -2,9 +2,12 @@ cache eviction, so a caller cycling through the callsign or hex keyspace could drive unlimited live requests at the free community API and grow `.gev-cache/adsbdb.json` without end — every distinct key, 404s included, was - remembered forever. The route now admits 360 requests/minute per client - address (the browser's own drip cannot exceed 300), refusing the rest with - 429 and `Retry-After` before any cache, disk or upstream work. Each cache - holds at most 20,000 entries, dropping the least-recently-written first, and - entries past the existing 24-hour TTL are discarded when the file is read - back. Cached answers and response shapes are unchanged (daikaginza, #689). + remembered forever. The route now admits 720 requests/minute per client + address (`GEV_RATELIMIT_ADSBDB_PER_MIN`; one tab's two enrichment queues top + out at 600), refusing the rest with 429 and `Retry-After` before any cache, + disk or upstream work. A refused lookup is asked for again once the refusal + has passed instead of leaving that aircraft without metadata for the + session. Each cache holds at most 20,000 entries, dropping the + least-recently-written first, and entries past the existing 24-hour TTL are + discarded when the file is read back. Cached answers and response shapes are + unchanged (daikaginza, #689). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 7c763e96b8..fdd07710b0 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1907,10 +1907,14 @@ policy, fallback behavior, response shapes and rendering remain unchanged. ### ADSBDB enrichment bounds -`/api/adsbdb` admits 360 requests/minute per client address, with a global -backstop of three times that; a refused request answers 429 with `Retry-After` -and reaches neither the cache nor api.adsbdb.com. The browser's own enrichment -drip cannot exceed 300/minute, so an ordinary session never meets the limit. +`/api/adsbdb` admits 720 requests/minute per client address +(`GEV_RATELIMIT_ADSBDB_PER_MIN`; `0` disables), with a global backstop of three +times that; a refused request answers 429 with `Retry-After` and reaches +neither the cache nor api.adsbdb.com. Each browser enrichment queue drips at +most 300/minute and one tab runs two (Flights and Local ADS-B), so an ordinary +session never meets the limit. When a lookup is refused anyway, both queues +make that key askable again after the refusal's retry-after rather than +treating the 429 as an answer. Both enrichment caches hold at most 20,000 entries each, dropping the least-recently-written first, and entries past their 24-hour TTL are discarded @@ -1918,7 +1922,7 @@ when `.gev-cache/adsbdb.json` is read back. A cache file above 16 MB is skipped rather than parsed. An evicted key costs one upstream request the next time it is asked for; cached answers are otherwise unchanged. -Updated: September 21, 2026 +Updated: October 23, 2026 ## Control names for assistive technology diff --git a/server/providers/aircraft/enrichment.js b/server/providers/aircraft/enrichment.js index 027a11d46d..8046f5b5e4 100644 --- a/server/providers/aircraft/enrichment.js +++ b/server/providers/aircraft/enrichment.js @@ -1,6 +1,10 @@ import path from 'node:path'; import { promises as fsp } from 'node:fs'; -import { makeRateLimiter, clientKey } from '../common/rate-limit.js'; +import { + makeRateLimiter, + clientKey, + resolvePerMinuteCap, +} from '../common/rate-limit.js'; import { readResponseJsonCapped } from '../common/http.js'; /** Route and aircraft lookups are a few hundred bytes; 1 MiB is a hard bound. */ @@ -39,17 +43,27 @@ export function adsbdbProxy(options = {}) { const CACHE_MAX_ENTRIES = cacheMaxEntries; const CACHE_MAX_DISK_BYTES = cacheMaxDiskBytes; /** - * Requests/minute/IP. The browser cannot exceed 300 by construction — - * `ENRICH_DISPATCH_GAP_MS` (200 ms) drips at most five enrichment lookups a - * second — so 360 leaves the real client untouched while still capping an - * enumerating caller. The global backstop is the usual generous multiple. + * Requests/minute/IP (`GEV_RATELIMIT_ADSBDB_PER_MIN`; unset takes the + * default, `0` disables). Each browser queue drips at most five lookups a + * second (`ENRICH_DISPATCH_GAP_MS`, 200 ms), and one tab can run two — the + * Flights layer's and Local ADS-B's — so a real session tops out at 600. + * The assistant's aviation tools look up through the same source, unqueued + * but one at a time per tool call. 720 leaves all of that untouched while + * still capping an enumerating caller. The global backstop is the usual + * generous multiple. */ - const RATE_PER_MIN = 360; - const allow = makeRateLimiter({ - windowMs: 60_000, - max: RATE_PER_MIN, - globalMax: RATE_PER_MIN * 3, - }); + const RATE_PER_MIN = resolvePerMinuteCap( + process.env.GEV_RATELIMIT_ADSBDB_PER_MIN, + 720, + ); + const allow = + RATE_PER_MIN > 0 + ? makeRateLimiter({ + windowMs: 60_000, + max: RATE_PER_MIN, + globalMax: RATE_PER_MIN * 3, + }) + : () => true; // Maps, not plain objects: `size` is O(1), so the ceiling can be enforced on // every write, and iteration is true insertion order (an all-digit callsign // like "1234" would sort ahead of everything else as an object key). diff --git a/src/layers/flights/enrichment.js b/src/layers/flights/enrichment.js index aaf8ceb38d..fbc4230223 100644 --- a/src/layers/flights/enrichment.js +++ b/src/layers/flights/enrichment.js @@ -21,7 +21,7 @@ export function createEnrichment({ if (flightState.lifetime.signal.aborted) return; if (flightState._enrichSeen.has(key)) return; flightState._enrichSeen.add(key); - const job = { query, onData }; + const job = { key, query, onData }; // Priority (tracked / model-eligible) goes to the FRONT so a deep ambient // backlog can never delay the plane the user just clicked or zoomed into. if (priority) flightState._enrichQueue.unshift(job); @@ -64,8 +64,14 @@ export function createEnrichment({ .then((data) => { if (!lifetime.signal.aborted && data && data.found) job.onData(data); }) - .catch(() => { - /* enrichment never surfaces errors */ + .catch((error) => { + // Enrichment never surfaces errors. A 429 is not an answer, though: + // the key becomes askable again once the refusal has passed. + if (error?.code === 'limited') + setTimeout(() => { + if (!lifetime.signal.aborted) + flightState._enrichSeen.delete(job.key); + }, error.retryAfterMs); }) .finally(() => { if (lifetime.signal.aborted) return; diff --git a/src/layers/localAdsb/enrichment.js b/src/layers/localAdsb/enrichment.js index 4fb4673a8d..9b9354bfe1 100644 --- a/src/layers/localAdsb/enrichment.js +++ b/src/layers/localAdsb/enrichment.js @@ -34,7 +34,8 @@ export function localAdsbClass(record, meta = null) { * session, at most four requests are in flight and dispatches are dripped * 200 ms apart. Only the selected aircraft (type + route) and aircraft that * are about to render as 3D models (type) are ever looked up — never one - * request per contact per tick. + * request per contact per tick. A rate-limit refusal is not an answer: the key + * becomes askable again once the refusal's retry-after has passed. * @param {object} options * @param {{getEnrichment?: Function}|null} options.source Flights source. * @param {() => void} options.onChange Called when metadata arrives. @@ -52,6 +53,7 @@ export function createLocalAdsbEnrichment({ let active = 0; let lastDispatchAt = -Infinity; let dripTimer = null; + const retryTimers = new Set(); let lifetime = new AbortController(); function entry(icao) { @@ -67,7 +69,7 @@ export function createLocalAdsbEnrichment({ function enqueue(key, query, apply, priority) { if (typeof source?.getEnrichment !== 'function' || seen.has(key)) return; seen.add(key); - const job = { query, apply }; + const job = { key, query, apply }; if (priority) queue.unshift(job); else queue.push(job); drain(); @@ -96,8 +98,10 @@ export function createLocalAdsbEnrichment({ onChange?.(); } }) - .catch(() => { - /* enrichment never surfaces errors */ + .catch((error) => { + // Enrichment never surfaces errors; a 429 only defers the key. + if (error?.code === 'limited') + forgetLater(job.key, error.retryAfterMs); }) .finally(() => { if (signal.aborted) return; @@ -107,6 +111,14 @@ export function createLocalAdsbEnrichment({ } } + function forgetLater(key, delayMs) { + const timer = setTimeout(() => { + retryTimers.delete(timer); + seen.delete(key); + }, delayMs); + retryTimers.add(timer); + } + return { /** @param {string} icao @returns {object|null} */ get(icao) { @@ -159,6 +171,8 @@ export function createLocalAdsbEnrichment({ lifetime = new AbortController(); clearTimeout(dripTimer); dripTimer = null; + for (const timer of retryTimers) clearTimeout(timer); + retryTimers.clear(); queue.length = 0; active = 0; }, diff --git a/src/proxyErrorResponses.test.mjs b/src/proxyErrorResponses.test.mjs index 78f3f59f0b..d68f0e06d0 100644 --- a/src/proxyErrorResponses.test.mjs +++ b/src/proxyErrorResponses.test.mjs @@ -4,7 +4,7 @@ import { readFileSync } from 'node:fs'; import path from 'node:path'; import { parseTerrainPoints } from './data/terrainHeightsProxy.js'; import { readResponseTextCapped, coalesceProxyRequest } from './sources/httpBody.js'; -import { makeRateLimiter, clientKey } from '../server/providers/common/rate-limit.js'; +import { makeRateLimiter, clientKey, resolvePerMinuteCap } from '../server/providers/common/rate-limit.js'; const source = ['local.js', 'common/http.js', 'aircraft/enrichment.js', 'terrain.js', 'space/celestrak.js', 'space/launch-library.js', '../../src/data/spaceProviderRequests.js'] .map(file => readFileSync(new URL(`../server/providers/${file}`, import.meta.url), 'utf8')) @@ -26,7 +26,7 @@ function fixture(name, overrides = {}, preview = false) { readResponseTextCapped, coalesceProxyRequest, // The rate-limited proxies reach for these; give them the real ones so a // fixture request is throttled exactly as production would be. - makeRateLimiter, clientKey, + makeRateLimiter, clientKey, resolvePerMinuteCap, // terrain.js gates cross-site requests first; fixture requests carry no // browser headers, so admit them like a loopback tool. admitSameSiteKeyless: () => false,