From 03814d8c47eac5fcac327793618e597f5e88a9e9 Mon Sep 17 00:00:00 2001 From: daikaginza Date: Mon, 21 Sep 2026 10:38:17 +0700 Subject: [PATCH 1/5] fix(adsbdb): rate-limit /api/adsbdb and cap its enrichment caches MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Both keys this route accepts come from the caller — a callsign is 2-8 of [A-Z0-9], a hex is six of [0-9a-f] — and every distinct key that reached upstream was cached, 404s included, with nothing ever removing one. A caller walking the keyspace could therefore drive unlimited live requests at the free community API and grow `.gev-cache/adsbdb.json` without end. Admit 360 requests/minute per client address, global backstop 3x, refusing the rest with 429 and `Retry-After` before any cache, disk or upstream work. The browser cannot exceed 300/min by construction: ENRICH_DISPATCH_GAP_MS is 200 ms, so the enrichment queue drips at most five lookups a second. Hold each store to 20,000 entries, dropping least-recently-written first, and discard entries past the existing 24-hour TTL when the file is read back. A cache file above 16 MB is skipped rather than parsed. Sized from a real session's own file: 397 aircraft entries (~100 B) and 3 route entries (~231 B), so the ceiling is about fifty times an ordinary working set and bounds the file at roughly 7 MB. The two stores become Maps: `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" sorts ahead of everything else as an object key. The on-disk JSON shape is unchanged. Refs #261 --- CHANGELOG.md | 11 ++ docs/CURRENT-STATE.md | 15 ++ scripts/format-scope.json | 3 +- scripts/package-boundaries.json | 2 + server/providers/aircraft/enrichment.js | 136 +++++++++++++-- src/adsbdbCacheGovernor.test.mjs | 209 ++++++++++++++++++++++++ src/proxyErrorResponses.test.mjs | 4 + 7 files changed, 362 insertions(+), 18 deletions(-) create mode 100644 src/adsbdbCacheGovernor.test.mjs diff --git a/CHANGELOG.md b/CHANGELOG.md index 29dbedfaa8..f17a232f88 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,16 @@ # Changelog +- Bound the adsbdb enrichment proxy. `/api/adsbdb` had no request limit and no + 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. + - CCTV cameras whose bearing is a guess now say so. Packs mark bearings derived from a hash of the camera id as `headingConfidence: 'low'`, but nothing read the flag, so roughly 70% of a default catalog rendered like surveyed facings. The HUD diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index fdb42fc0c2..49d760b84a 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1105,6 +1105,21 @@ The existing aircraft normalizer is separately available through the portable `gods-eye-view/sources/adsb-lol` export. Provider URLs, local credentials, cache 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. + +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 +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 + ## Control names for assistive technology Scope, Bloom, Sharpen and location search have explicit accessible names. diff --git a/scripts/format-scope.json b/scripts/format-scope.json index eee546dd54..d74996ee4f 100644 --- a/scripts/format-scope.json +++ b/scripts/format-scope.json @@ -839,5 +839,6 @@ "src/ui/imageryBoxTool.test.mjs", "src/ui/recentImagery.test.mjs", "src/layers/recentImagery/testDoubles.mjs", - "scripts/qa-recent-imagery.mjs" + "scripts/qa-recent-imagery.mjs", + "src/adsbdbCacheGovernor.test.mjs" ] diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 189192f10e..1681eeb765 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -36,6 +36,8 @@ "server/providers/live.js", "server/providers/common/http.js", "server/providers/common/query.js", + "server/providers/common/rate-limit.js", + "src/sources/rateLimit.js", "server/providers/aircraft/opensky.js", "server/providers/aircraft/adsb-lol.js", "server/providers/aircraft/enrichment.js", diff --git a/server/providers/aircraft/enrichment.js b/server/providers/aircraft/enrichment.js index 400050151d..d629bd6897 100644 --- a/server/providers/aircraft/enrichment.js +++ b/server/providers/aircraft/enrichment.js @@ -1,5 +1,6 @@ import path from 'node:path'; import { promises as fsp } from 'node:fs'; +import { makeRateLimiter, clientKey } from '../common/rate-limit.js'; /** * adsbdb.com enrichment proxy: callsign → route (airline + origin/destination * airports) and hex → aircraft type/registration. Free community API — cached @@ -7,29 +8,116 @@ import { promises as fsp } from 'node:fs'; * persisted to disk so restarts don't re-hammer it. Adapted from skylight * (MIT) server/src/enrich/routes.ts. */ -export function adsbdbProxy() { +export function adsbdbProxy(options = {}) { + // Destructured in the body, not the signature: `proxyErrorResponses.test.mjs` + // extracts these proxies by slicing to the first closing brace in column zero. + const { + cacheMaxEntries = 20_000, + cacheMaxDiskBytes = 16 * 1024 * 1024, + cachePath, + } = options; const TTL_MS = 24 * 3600_000; - const CACHE_PATH = path.join(process.cwd(), '.gev-cache', 'adsbdb.json'); - let cache = { routes: {}, aircraft: {} }; + const CACHE_PATH = + cachePath || path.join(process.cwd(), '.gev-cache', 'adsbdb.json'); + /** + * Entry ceiling per store. + * + * Both keyspaces are enumerable by the caller — a callsign is 2-8 of + * `[A-Z0-9]`, a hex is six of `[0-9a-f]` — and every distinct key that + * reaches upstream is cached, 404s included. Without a ceiling the maps, and + * the file they are written to, grow for as long as a caller keeps asking. + * Sized from a real session's own file: `.gev-cache/adsbdb.json` held 397 + * aircraft entries (~100 B each) and 3 route entries (~231 B each), so + * 20,000 per store is roughly fifty times an ordinary working set and still + * bounds the file at about 7 MB. + */ + 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. + */ + const RATE_PER_MIN = 360; + const allow = makeRateLimiter({ + windowMs: 60_000, + max: RATE_PER_MIN, + globalMax: RATE_PER_MIN * 3, + }); + // 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). + let cache = { routes: new Map(), aircraft: new Map() }; let dirty = false; let loaded = false; const inflight = new Map(); + /** Rehydrate one store, dropping entries that expired while we were down. */ + function toStore(raw) { + const store = new Map(); + const now = Date.now(); + for (const [key, entry] of Object.entries(raw ?? {})) { + const at = Number(entry?.at); + if (!Number.isFinite(at) || now - at >= TTL_MS) continue; + store.set(key, entry); + } + prune(store); + return store; + } + + /** Hold the store at its ceiling, dropping least-recently-written first. */ + function prune(store) { + while (store.size > CACHE_MAX_ENTRIES) { + const oldest = store.keys().next().value; + if (oldest === undefined) break; + store.delete(oldest); + } + } + + /** Write `key` as the newest entry, then restore the ceiling. */ + function remember(store, key, entry) { + store.delete(key); // re-insert so insertion order tracks last write + store.set(key, entry); + prune(store); + dirty = true; + } + async function loadOnce() { if (loaded) return; loaded = true; + let sizeBytes = null; try { - const parsed = JSON.parse(await fsp.readFile(CACHE_PATH, 'utf8')); - cache = { routes: parsed.routes ?? {}, aircraft: parsed.aircraft ?? {} }; + sizeBytes = (await fsp.stat(CACHE_PATH)).size; } catch { - /* first run */ + sizeBytes = null; // cannot measure it — let the read below decide + } + if (sizeBytes !== null && sizeBytes > CACHE_MAX_DISK_BYTES) { + console.warn('[adsbdb-proxy] cache file above ceiling — starting empty'); + } else { + try { + const parsed = JSON.parse(await fsp.readFile(CACHE_PATH, 'utf8')); + cache = { + routes: toStore(parsed.routes), + aircraft: toStore(parsed.aircraft), + }; + } catch { + /* first run */ + } } setInterval(async () => { if (!dirty) return; dirty = false; try { await fsp.mkdir(path.dirname(CACHE_PATH), { recursive: true }); - await fsp.writeFile(CACHE_PATH, JSON.stringify(cache), 'utf8'); + await fsp.writeFile( + CACHE_PATH, + JSON.stringify({ + routes: Object.fromEntries(cache.routes), + aircraft: Object.fromEntries(cache.aircraft), + }), + 'utf8', + ); } catch { dirty = true; } // retry next tick @@ -69,7 +157,7 @@ export function adsbdbProxy() { function lookup(kind, key) { const store = kind === 'route' ? cache.routes : cache.aircraft; - if (fresh(store[key])) return Promise.resolve(store[key].data); + if (fresh(store.get(key))) return Promise.resolve(store.get(key).data); const ik = `${kind}:${key}`; if (!inflight.has(ik)) { inflight.set( @@ -86,18 +174,19 @@ export function adsbdbProxy() { kind === 'route' ? parseRoute(await res.json()) : parseAircraft(await res.json()); - store[key] = { at: Date.now(), data }; // data may be null — negative cache - dirty = true; + // data may be null — negative cache + remember(store, key, { at: Date.now(), data }); return data; } if (res.status === 404) { - store[key] = { at: Date.now(), data: null }; // known-missing — cache the miss - dirty = true; + // known-missing — cache the miss + remember(store, key, { at: Date.now(), data: null }); } // other statuses: leave uncached so we retry later - return fresh(store[key]) ? store[key].data : null; + return fresh(store.get(key)) ? store.get(key).data : null; } catch { - return fresh(store[key]) ? store[key].data : null; // network error → stale if any + // network error → stale if any + return fresh(store.get(key)) ? store.get(key).data : null; } finally { inflight.delete(ik); } @@ -109,11 +198,24 @@ export function adsbdbProxy() { const installMiddleware = (server) => { server.middlewares.use('/api/adsbdb', async (req, res) => { - await loadOnce(); - const send = (status, obj) => { - res.writeHead(status, { 'Content-Type': 'application/json' }); + const send = (status, obj, headers = {}) => { + res.writeHead(status, { + 'Content-Type': 'application/json', + ...headers, + }); res.end(JSON.stringify(obj)); }; + // Before any work: a refused request must not touch the cache, the disk, + // or api.adsbdb.com. + if (!allow(clientKey(req))) + return send( + 429, + { error: 'Rate limit exceeded' }, + { + 'Retry-After': '10', + }, + ); + await loadOnce(); try { const [, kind, rawKey] = String(req.url || '') .split('?')[0] diff --git a/src/adsbdbCacheGovernor.test.mjs b/src/adsbdbCacheGovernor.test.mjs new file mode 100644 index 0000000000..98a60251b4 --- /dev/null +++ b/src/adsbdbCacheGovernor.test.mjs @@ -0,0 +1,209 @@ +// ADSBDB ENRICHMENT — the keyspace the cache used to remember forever. +// +// `/api/adsbdb` answers `route/` and `type/`. Both keys come +// from the caller: a callsign is 2-8 of [A-Z0-9], a hex is six of [0-9a-f]. +// Every distinct key that reached upstream was cached — 404s included — and +// nothing ever removed one, so a caller walking the keyspace grew both the +// in-memory maps and `.gev-cache/adsbdb.json` without bound, at one live +// request to the free community API per new key. +// +// These cases drive the real exported route handler. No network: `fetch` is +// stubbed per test and restored afterwards, so a case that reaches upstream +// fails loudly rather than making a request. +// +// Run with: npm test +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import path from 'node:path'; +import os from 'node:os'; +import { adsbdbProxy } from '../server/providers/aircraft/enrichment.js'; + +/** Collect a plugin's routes into a path → handler map. */ +function install(plugin) { + const routes = new Map(); + plugin.configureServer({ + middlewares: { + use(routePath, handler) { + routes.set(routePath, handler); + }, + }, + }); + return routes; +} + +function request(handler, { url = '/', remoteAddress = '127.0.0.1' } = {}) { + return new Promise((resolve, reject) => { + const headers = new Map(); + const req = { method: 'GET', url, headers: {}, socket: { remoteAddress } }; + const res = { + statusCode: 200, + writeHead(status, hdrs = {}) { + this.statusCode = status; + for (const [name, value] of Object.entries(hdrs)) + headers.set(String(name).toLowerCase(), String(value)); + }, + end(body = '') { + let parsed = null; + try { + parsed = body ? JSON.parse(String(body)) : null; + } catch { + parsed = String(body); + } + resolve({ + statusCode: this.statusCode, + headers: Object.fromEntries(headers), + body: parsed, + }); + }, + }; + Promise.resolve(handler(req, res)).catch(reject); + }); +} + +/** + * Replace global fetch for the duration of one test, counting the calls the + * cache failed to absorb. Every hex answers with the same aircraft, so a + * second live call for a key we already asked about is a cache miss, nothing + * else. + */ +function stubUpstream(t) { + const asked = []; + const original = globalThis.fetch; + globalThis.fetch = async (url) => { + asked.push(String(url)); + return new Response( + JSON.stringify({ + response: { + aircraft: { + icao_type: 'B738', + manufacturer: 'Boeing', + type: '737-800', + registration: 'N-FIXTURE', + }, + }, + }), + { status: 200 }, + ); + }; + t.after(() => { + globalThis.fetch = original; + }); + return asked; +} + +/** A cache path inside the OS temp dir: these cases never load or write it. */ +const scratchCachePath = () => + path.join(os.tmpdir(), `gev-adsbdb-fixture-${process.pid}-absent.json`); + +const hex = (i) => i.toString(16).padStart(6, '0'); + +test('an enrichment lookup still answers, and is cached', async (t) => { + const asked = stubUpstream(t); + const routes = install( + adsbdbProxy({ cachePath: scratchCachePath(), cacheMaxEntries: 10 }), + ); + const handler = routes.get('/api/adsbdb'); + + const first = await request(handler, { url: '/type/abc123' }); + assert.equal(first.statusCode, 200); + assert.equal(first.body.found, true); + assert.equal(first.body.typeCode, 'B738'); + assert.equal(asked.length, 1); + + const second = await request(handler, { url: '/type/abc123' }); + assert.equal(second.body.typeCode, 'B738'); + assert.equal(asked.length, 1, 'a warm key costs no upstream request'); +}); + +test('the cache stops growing, and an evicted key is simply re-fetched', async (t) => { + const asked = stubUpstream(t); + // A ceiling of 3 exercises the same path 20,000 does, in four keys. + const routes = install( + adsbdbProxy({ cachePath: scratchCachePath(), cacheMaxEntries: 3 }), + ); + const handler = routes.get('/api/adsbdb'); + + for (let i = 1; i <= 4; i += 1) + await request(handler, { url: `/type/${hex(i)}` }); + assert.equal(asked.length, 4, 'four distinct keys, four upstream requests'); + + // The newest is still warm... + await request(handler, { url: `/type/${hex(4)}` }); + assert.equal(asked.length, 4); + + // ...and the oldest was evicted, so it costs exactly one re-fetch, and + // still answers correctly. + const again = await request(handler, { url: `/type/${hex(1)}` }); + assert.equal(asked.length, 5); + assert.match(asked[4], new RegExp(`/aircraft/${hex(1)}$`)); + assert.equal(again.body.typeCode, 'B738'); +}); + +test('route and aircraft keys are held to the ceiling independently', async (t) => { + const asked = stubUpstream(t); + const routes = install( + adsbdbProxy({ cachePath: scratchCachePath(), cacheMaxEntries: 2 }), + ); + const handler = routes.get('/api/adsbdb'); + + await request(handler, { url: '/type/aaaaaa' }); + await request(handler, { url: '/type/bbbbbb' }); + // Two callsigns must not push the two hexes out — they are separate stores. + await request(handler, { url: '/route/BAW1' }); + await request(handler, { url: '/route/DLH2' }); + assert.equal(asked.length, 4); + + await request(handler, { url: '/type/aaaaaa' }); + assert.equal(asked.length, 4, 'the aircraft store kept its own two keys'); +}); + +test('a caller enumerating the keyspace is refused, and refusal costs nothing', async (t) => { + const asked = stubUpstream(t); + const routes = install(adsbdbProxy({ cachePath: scratchCachePath() })); + const handler = routes.get('/api/adsbdb'); + + let refused = null; + let served = 0; + // The browser cannot exceed 300/min (ENRICH_DISPATCH_GAP_MS is 200 ms), so + // an enumerating caller runs out well before a real session would. + for (let i = 0; i < 400 && !refused; i += 1) { + const res = await request(handler, { url: `/type/${hex(i)}` }); + if (res.statusCode === 429) refused = res; + else served += 1; + } + + assert.ok(refused, 'an unbounded sweep is eventually refused'); + assert.equal(refused.body.error, 'Rate limit exceeded'); + assert.equal(refused.headers['retry-after'], '10'); + assert.ok( + served >= 300, + `a real session's ceiling of 300/min must fit; served ${served}`, + ); + assert.equal( + asked.length, + served, + 'a refused request never reaches api.adsbdb.com', + ); +}); + +test('a different client keeps its own budget', async (t) => { + stubUpstream(t); + const routes = install(adsbdbProxy({ cachePath: scratchCachePath() })); + const handler = routes.get('/api/adsbdb'); + + let noisy = 0; + for (let i = 0; i < 400; i += 1) { + const res = await request(handler, { + url: `/type/${hex(i)}`, + remoteAddress: '10.0.0.1', + }); + if (res.statusCode === 200) noisy += 1; + } + assert.ok(noisy > 0 && noisy < 400, 'the noisy client was throttled'); + + const quiet = await request(handler, { + url: '/type/ffffff', + remoteAddress: '10.0.0.2', + }); + assert.equal(quiet.statusCode, 200, 'a quiet client is not collateral'); +}); diff --git a/src/proxyErrorResponses.test.mjs b/src/proxyErrorResponses.test.mjs index 2b45a3b9e5..9cc1ff9c76 100644 --- a/src/proxyErrorResponses.test.mjs +++ b/src/proxyErrorResponses.test.mjs @@ -3,6 +3,7 @@ import assert from 'node:assert/strict'; import { readFileSync } from 'node:fs'; import path from 'node:path'; import { readResponseTextCapped, coalesceProxyRequest } from './sources/httpBody.js'; +import { makeRateLimiter, clientKey } 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')) @@ -22,6 +23,9 @@ function fixture(name, overrides = {}, preview = false) { const logs = []; const deps = { 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, path, process: { cwd: () => '/fixture', env: {} }, fsp: { readFile: async () => { throw new Error('cache absent'); }, From 7fa3e5e7bfc2ec17cbda59901bb3d40e7a0aa327 Mon Sep 17 00:00:00 2001 From: daikaginza Date: Sun, 18 Oct 2026 13:36:07 +0700 Subject: [PATCH 2/5] docs(changelog): move the entry into a changelog.d fragment Main now takes pending entries as changelog.d/-.md files (#787), so the entry leaves CHANGELOG.md for changelog.d/689-adsbdb-cache-and-rate-limit.md. --- changelog.d/689-adsbdb-cache-and-rate-limit.md | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 changelog.d/689-adsbdb-cache-and-rate-limit.md diff --git a/changelog.d/689-adsbdb-cache-and-rate-limit.md b/changelog.d/689-adsbdb-cache-and-rate-limit.md new file mode 100644 index 0000000000..c5a426c531 --- /dev/null +++ b/changelog.d/689-adsbdb-cache-and-rate-limit.md @@ -0,0 +1,10 @@ +- Bound the adsbdb enrichment proxy. `/api/adsbdb` had no request limit and no + 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). From b83e1a2c98d61e53dd860ac5335760eef6f9c7cd Mon Sep 17 00:00:00 2001 From: daikaginza Date: Fri, 23 Oct 2026 12:39:32 +0700 Subject: [PATCH 3/5] test(adsbdb): size the limiter for two client queues and retry a 429 Review on #689: one tab runs two enrichment queues (Flights and Local ADS-B) at 200 ms each, so a real session reaches 600/min, not 300; and a 429 left the aircraft's metadata empty for the session, because both queues mark a key seen before dispatch and swallow the error. The cases pin 600/min fitting, the GEV_RATELIMIT_ADSBDB_PER_MIN override (0 off), and both queues asking again after the refusal. Four fail on the branch as it stands. --- scripts/format-scope.json | 3 +- src/adsbdbCacheGovernor.test.mjs | 43 ++++++-- src/layers/enrichmentRateLimitRetry.test.mjs | 110 +++++++++++++++++++ 3 files changed, 148 insertions(+), 8 deletions(-) create mode 100644 src/layers/enrichmentRateLimitRetry.test.mjs diff --git a/scripts/format-scope.json b/scripts/format-scope.json index 60e0d18a53..dd18717503 100644 --- a/scripts/format-scope.json +++ b/scripts/format-scope.json @@ -1087,5 +1087,6 @@ "src/ui/cctvBadges.test.mjs", "scripts/qa-status-badges.mjs", "src/dockerTrustedPeers.test.mjs", - "src/adsbdbCacheGovernor.test.mjs" + "src/adsbdbCacheGovernor.test.mjs", + "src/layers/enrichmentRateLimitRetry.test.mjs" ] diff --git a/src/adsbdbCacheGovernor.test.mjs b/src/adsbdbCacheGovernor.test.mjs index 98a60251b4..010ce9c9be 100644 --- a/src/adsbdbCacheGovernor.test.mjs +++ b/src/adsbdbCacheGovernor.test.mjs @@ -164,9 +164,9 @@ test('a caller enumerating the keyspace is refused, and refusal costs nothing', let refused = null; let served = 0; - // The browser cannot exceed 300/min (ENRICH_DISPATCH_GAP_MS is 200 ms), so - // an enumerating caller runs out well before a real session would. - for (let i = 0; i < 400 && !refused; i += 1) { + // Each client queue drips one lookup per ENRICH_DISPATCH_GAP_MS (200 ms), + // and one tab runs two (Flights and Local ADS-B): 600/min must fit. + for (let i = 0; i < 1000 && !refused; i += 1) { const res = await request(handler, { url: `/type/${hex(i)}` }); if (res.statusCode === 429) refused = res; else served += 1; @@ -176,8 +176,8 @@ test('a caller enumerating the keyspace is refused, and refusal costs nothing', assert.equal(refused.body.error, 'Rate limit exceeded'); assert.equal(refused.headers['retry-after'], '10'); assert.ok( - served >= 300, - `a real session's ceiling of 300/min must fit; served ${served}`, + served >= 600, + `both client queues together (600/min) must fit; served ${served}`, ); assert.equal( asked.length, @@ -192,14 +192,14 @@ test('a different client keeps its own budget', async (t) => { const handler = routes.get('/api/adsbdb'); let noisy = 0; - for (let i = 0; i < 400; i += 1) { + for (let i = 0; i < 1000; i += 1) { const res = await request(handler, { url: `/type/${hex(i)}`, remoteAddress: '10.0.0.1', }); if (res.statusCode === 200) noisy += 1; } - assert.ok(noisy > 0 && noisy < 400, 'the noisy client was throttled'); + assert.ok(noisy > 0 && noisy < 1000, 'the noisy client was throttled'); const quiet = await request(handler, { url: '/type/ffffff', @@ -207,3 +207,32 @@ test('a different client keeps its own budget', async (t) => { }); assert.equal(quiet.statusCode, 200, 'a quiet client is not collateral'); }); + +test('GEV_RATELIMIT_ADSBDB_PER_MIN sets the cap, and 0 turns it off', async (t) => { + stubUpstream(t); + const original = process.env.GEV_RATELIMIT_ADSBDB_PER_MIN; + t.after(() => { + if (original === undefined) delete process.env.GEV_RATELIMIT_ADSBDB_PER_MIN; + else process.env.GEV_RATELIMIT_ADSBDB_PER_MIN = original; + }); + + process.env.GEV_RATELIMIT_ADSBDB_PER_MIN = '5'; + const tight = install(adsbdbProxy({ cachePath: scratchCachePath() })).get( + '/api/adsbdb', + ); + const statuses = []; + for (let i = 0; i < 6; i += 1) + statuses.push( + (await request(tight, { url: `/type/${hex(i)}` })).statusCode, + ); + assert.deepEqual(statuses, [200, 200, 200, 200, 200, 429]); + + process.env.GEV_RATELIMIT_ADSBDB_PER_MIN = '0'; + const open = install(adsbdbProxy({ cachePath: scratchCachePath() })).get( + '/api/adsbdb', + ); + for (let i = 0; i < 1500; i += 1) { + const res = await request(open, { url: `/type/${hex(i)}` }); + assert.equal(res.statusCode, 200, `request ${i} with the limiter off`); + } +}); diff --git a/src/layers/enrichmentRateLimitRetry.test.mjs b/src/layers/enrichmentRateLimitRetry.test.mjs new file mode 100644 index 0000000000..06df7b6485 --- /dev/null +++ b/src/layers/enrichmentRateLimitRetry.test.mjs @@ -0,0 +1,110 @@ +// A 429 from /api/adsbdb must not leave an aircraft's metadata empty for the +// rest of the session. +// +// Both enrichment queues (Flights and Local ADS-B) mark a key as seen before +// they dispatch it, so a second request for the same aircraft is dropped. That +// is right for an answer or a 404, and wrong for a refusal: the server said +// "later", not "no". These cases drive the real queues against a source that +// refuses once and then answers. +// +// Run with: npm test +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { LiveSourceError } from '../sources/live/contract.js'; +import { createLocalAdsbEnrichment } from './localAdsb/enrichment.js'; +import { createFlightState } from './flights/state.js'; +import { createEnrichment } from './flights/enrichment.js'; + +/** Short real delay, so the case needs no clock control. */ +const RETRY_AFTER_MS = 20; + +/** A source that refuses the first lookup with a 429, then answers. */ +function refusingOnce() { + const calls = []; + return { + calls, + async getEnrichment(query) { + calls.push(query); + if (calls.length === 1) + throw new LiveSourceError('limited', 'Flights rate limited', { + status: 429, + retryAfterMs: RETRY_AFTER_MS, + }); + return { found: true, typeCode: 'B738', typeName: 'Boeing 737-800' }; + }, + }; +} + +const settle = (ms) => new Promise((done) => setTimeout(done, ms)); + +test('Local ADS-B asks again after a 429 once the refusal has passed', async (t) => { + const source = refusingOnce(); + const enrichment = createLocalAdsbEnrichment({ source, onChange() {} }); + t.after(() => enrichment.destroy()); + const record = { icao: 'abc123', category: 'A3' }; + + enrichment.request(record); + await settle(0); + assert.equal(source.calls.length, 1); + enrichment.request(record); + await settle(0); + assert.equal(source.calls.length, 1, 'no retry inside the refusal window'); + + await settle(RETRY_AFTER_MS + 250); // refusal window, then the 200 ms drip + enrichment.request(record); + await settle(250); + assert.equal(source.calls.length, 2, 'the aircraft is asked for again'); + assert.equal(enrichment.get('abc123')?.typeCode, 'B738'); +}); + +test('an answered lookup is still asked for only once', async (t) => { + const calls = []; + const enrichment = createLocalAdsbEnrichment({ + source: { + async getEnrichment(query) { + calls.push(query); + return { found: false }; + }, + }, + onChange() {}, + }); + t.after(() => enrichment.destroy()); + enrichment.request({ icao: 'def456' }); + await settle(RETRY_AFTER_MS + 250); + enrichment.request({ icao: 'def456' }); + await settle(250); + assert.equal(calls.length, 1, 'a 404 is an answer, not a refusal'); +}); + +test('Flights asks again after a 429 once the refusal has passed', async (t) => { + const source = refusingOnce(); + const flightState = createFlightState({ + source, + services: { + groundSnap: { createGroundSnap: () => ({ clear() {} }) }, + }, + }); + t.after(() => flightState.lifetime.abort()); + const enrichment = createEnrichment({ flightState, services: {}, parts: {} }); + let applied = null; + const ask = () => + enrichment._enqueueEnrich( + 't:abc123', + { kind: 'type', id: 'abc123' }, + (data) => { + applied = data; + }, + ); + + ask(); + await settle(0); + ask(); + await settle(0); + assert.equal(source.calls.length, 1, 'no retry inside the refusal window'); + + await settle(RETRY_AFTER_MS + 250); + ask(); + await settle(250); + assert.equal(source.calls.length, 2, 'the aircraft is asked for again'); + assert.equal(applied?.typeCode, 'B738'); +}); From 80b2ead154367397d448da8412c8389d094df677 Mon Sep 17 00:00:00 2001 From: daikaginza Date: Fri, 23 Oct 2026 12:39:32 +0700 Subject: [PATCH 4/5] 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, From 28c9c4d7308a105e667182adb6770dbb54dbfffd Mon Sep 17 00:00:00 2001 From: daika Date: Tue, 10 Nov 2026 15:51:42 +0700 Subject: [PATCH 5/5] test(adsbdb): give the Flights retry case the services enrichment now reads --- src/layers/enrichmentRateLimitRetry.test.mjs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/layers/enrichmentRateLimitRetry.test.mjs b/src/layers/enrichmentRateLimitRetry.test.mjs index 06df7b6485..8f860b2823 100644 --- a/src/layers/enrichmentRateLimitRetry.test.mjs +++ b/src/layers/enrichmentRateLimitRetry.test.mjs @@ -37,6 +37,12 @@ function refusingOnce() { const settle = (ms) => new Promise((done) => setTimeout(done, ms)); +/** The services Flights enrichment reads: neither military nor a TR-3B. */ +const enrichServices = { + militaryRegistry: { isMilitaryIcao: () => false }, + aircraftPresentation: { isTr3b: () => false }, +}; + test('Local ADS-B asks again after a 429 once the refusal has passed', async (t) => { const source = refusingOnce(); const enrichment = createLocalAdsbEnrichment({ source, onChange() {} }); @@ -85,7 +91,11 @@ test('Flights asks again after a 429 once the refusal has passed', async (t) => }, }); t.after(() => flightState.lifetime.abort()); - const enrichment = createEnrichment({ flightState, services: {}, parts: {} }); + const enrichment = createEnrichment({ + flightState, + services: enrichServices, + parts: {}, + }); let applied = null; const ask = () => enrichment._enqueueEnrich(