mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-23 03:32:19 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
48ef645d65 | ||
|
|
28c9c4d730 | ||
|
|
ec90e98d61 | ||
|
|
94e3d01d75 | ||
|
|
9aa71cdfeb | ||
|
|
80b2ead154 | ||
|
|
b83e1a2c98 | ||
|
|
ed1e2771a0 | ||
|
|
7fa3e5e7bf | ||
|
|
fbd99dad7c | ||
|
|
c20af07adb | ||
|
|
0bd8e9a62c | ||
|
|
0d5a0cdf49 | ||
|
|
03814d8c47 |
No files matched your search
@@ -51,6 +51,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
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
- Stop the OpenSky track-backfill proxy from turning a varied `icao24` into
|
||||
unbounded upstream spend. `/api/flights/track` carries an always-on
|
||||
30-per-minute per-client limiter (90 global) on upstream calls (a cached
|
||||
answer or a malformed request is not charged), and a
|
||||
`429` from OpenSky `/tracks/all` now starts a cooldown for that credit
|
||||
bucket: until OpenSky's retry-after passes, any cached track is served and
|
||||
other lookups are answered `429` locally instead of asking for 4 more
|
||||
credits. The `/tracks/*` bucket is separate from the `/states/*` one
|
||||
`/api/flights` spends, so a flights cooldown does not block backfill. The
|
||||
existing 60-second per-key cache bounds memory, not spend. Single-aircraft
|
||||
backfill, issued once per selected contact, is unaffected (daikaginza, #685).
|
||||
@@ -0,0 +1,13 @@
|
||||
- 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 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).
|
||||
+19
-1
@@ -4350,6 +4350,25 @@ 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 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
|
||||
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: October 23, 2026
|
||||
|
||||
## Control names for assistive technology
|
||||
|
||||
Scope, Bloom, Sharpen and location search have explicit accessible names.
|
||||
@@ -9011,7 +9030,6 @@ apply to `public/` assets or built-preview serving.
|
||||
- `/api/flights`, `/api/military`, and `/api/route` answer `405 Method Not Allowed` with `Allow: GET` to anything but `GET`, before rate limiting and any upstream call.
|
||||
- `/api/flights` negotiates gzip. The cached global snapshot and the regional adsb.lol fallback are each gzipped once per refresh (about 860 KB becomes about 250 KB). Clients that offer gzip get that frame; other clients, and bodies under 1 KiB or that gzip cannot shrink, get identity bytes. Both answers carry `Vary: Accept-Encoding`. Uncached bodies, such as auth failures, are never sent under a cached frame's encoding.
|
||||
- Track endpoints: `/api/vessels/track?mmsi=` (server-accumulated ring buffers; sub-route handled before the rows snapshot), `/api/flights/track?icao24=` (OAuth, 60s cache, sanitized errors, independent OpenSky credit bucket), `/api/military/track?hex=` (400 for an invalid hex, otherwise `503 history_unavailable` with `Retry-After: 1800` and `Cache-Control: no-store`, no upstream request; military tracking uses its locally accumulated trail).
|
||||
- `/api/flights/track` carries an always-on per-client limiter of 30 upstream calls/minute (90 global; refusals send `Retry-After: 60`; cached answers and malformed requests are not charged), because its 60s per-key cache bounds memory rather than spend: a caller varying `icao24` produces a fresh key and a fresh upstream call each time. A `429` from OpenSky `/tracks/all` starts a cooldown for the `/tracks/*` credit bucket (OpenSky's retry-after, bounded 30 s–30 min): while it runs, `/api/flights/track` serves any cached track (not a cached error) and otherwise answers `429` with the remaining cooldown, including to the request that tripped it, instead of spending 4 more credits. It does not read `/api/flights`'s `/states/*` cooldown, since OpenSky meters the two buckets independently.
|
||||
- Realtime debug logs redact API keys, bearer tokens, client secrets, and image data URLs before writing to disk; request bodies are size-capped.
|
||||
- `/api/realtime/debug-log` enforces an always-on 120-per-client/400-global one-minute limiter (not the opt-in `GEV_RATELIMIT_OPENAI_PER_MIN` bucket the cost-bearing OpenAI routes share), appends asynchronously through a serialized queue, and rotates `realtime-conversations.jsonl` at 32 MB keeping one prior generation, so the sink is bounded at twice that regardless of session length. A malformed record answers 400 and a failed write 500, both with a fixed message.
|
||||
|
||||
|
||||
@@ -1704,5 +1704,6 @@
|
||||
"src/ui/stationPanel.test.mjs",
|
||||
"src/ui/styles/live.css",
|
||||
"src/ui/styles/station.css",
|
||||
"src/openSkyTrackGovernor.test.mjs"
|
||||
"src/adsbdbCacheGovernor.test.mjs",
|
||||
"src/layers/enrichmentRateLimitRetry.test.mjs"
|
||||
]
|
||||
@@ -1,5 +1,10 @@
|
||||
import path from 'node:path';
|
||||
import { promises as fsp } from 'node:fs';
|
||||
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. */
|
||||
@@ -12,29 +17,126 @@ const ADSBDB_MAX_RESPONSE_BYTES = 1024 * 1024;
|
||||
* cached. 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 (`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 = 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).
|
||||
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
|
||||
@@ -74,7 +176,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(
|
||||
@@ -95,18 +197,19 @@ export function adsbdbProxy() {
|
||||
);
|
||||
const data =
|
||||
kind === 'route' ? parseRoute(payload) : parseAircraft(payload);
|
||||
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);
|
||||
}
|
||||
@@ -118,11 +221,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]
|
||||
|
||||
@@ -43,13 +43,11 @@ const OPENSKY_STATES_MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
|
||||
|
||||
/**
|
||||
* Credit-governor cooldown for a 429: OpenSky's retry-after bounded to
|
||||
* 30 s … 30 min, or 2 min when the header is absent. Exported for the
|
||||
* `/tracks/*` governor in tracks.js, which reads the same header for its own
|
||||
* bucket.
|
||||
* 30 s … 30 min, or 2 min when the header is absent.
|
||||
* @param {Response} upstream Rate-limited response.
|
||||
* @returns {number} Cooldown (ms).
|
||||
*/
|
||||
export function openSkyRateLimitCooldownMs(upstream) {
|
||||
function openSkyRateLimitCooldownMs(upstream) {
|
||||
// headers.get() gives null when absent, and Number(null) is 0, not NaN.
|
||||
const header = upstream.headers.get('x-rate-limit-retry-after-seconds');
|
||||
const retryAfterSec =
|
||||
|
||||
@@ -1,19 +1,12 @@
|
||||
import { getOpenSkyToken, openSkyRateLimitCooldownMs } from './opensky.js';
|
||||
import { getOpenSkyToken } from './opensky.js';
|
||||
import { readCappedResponseText } from '../common/http.js';
|
||||
import { makeRateLimiter, clientKey } from '../common/rate-limit.js';
|
||||
/**
|
||||
* Vite plugin: aircraft track-history backfill proxies (PRD WS-F F1/F2).
|
||||
*
|
||||
* /api/flights/track?icao24=<hex6> — OpenSky GET /tracks/all (experimental;
|
||||
* 4 credits per call from the `/tracks/*` bucket, which OpenSky keeps
|
||||
* separate from the `/states/*` one `/api/flights` spends). OAuth via the
|
||||
* own credit bucket, 4 credits per call on the free tier). OAuth via the
|
||||
* shared coalesced token. 60s per-icao cache; 404/429 forwarded so the
|
||||
* client can fall back to its accumulated trail silently. It has its own
|
||||
* per-IP limiter, and a 429 from /tracks starts a cooldown for that
|
||||
* bucket — the per-icao cache bounds memory, not spend, since a different
|
||||
* `icao24` is simply a different key. The limiter counts upstream calls
|
||||
* only: a malformed request or one answered from the cache costs OpenSky
|
||||
* nothing and is not charged.
|
||||
* client can fall back to its accumulated trail silently.
|
||||
* /api/military/track?hex=<hex> — compatibility refusal for the retired,
|
||||
* undocumented ADSB.lol trace route. The standalone military source uses
|
||||
* locally accumulated trails; provider-supplied history remains optional.
|
||||
@@ -22,52 +15,9 @@ export function trackBackfillProxies() {
|
||||
const TRACK_CACHE_MS = 60000;
|
||||
const TRACK_CACHE_MAX = 200;
|
||||
const RESPONSE_CAP_BYTES = 5 * 1024 * 1024;
|
||||
/**
|
||||
* Requests/min/IP. The per-icao cache below bounds MEMORY, not request
|
||||
* volume: every distinct `icao24` is a fresh key, and `icao24` is 6 hex
|
||||
* digits, so varying it walks straight past the cache into a live call.
|
||||
*
|
||||
* Sized against demand, not guessed: a backfill is issued once per aircraft
|
||||
* the operator SELECTS (`_backfillTrail`, fired from the tracked-contact
|
||||
* path in the flights layer), and re-selecting the
|
||||
* same aircraft inside a minute is served from cache. The assistant's
|
||||
* `get_aircraft_track` tool asks once per call, a handful per turn. 30/min
|
||||
* is a target switch every two seconds, sustained — well clear of either,
|
||||
* and the same band `/api/geocode` and `/api/regional-brief` already use.
|
||||
*/
|
||||
const TRACK_RATE_PER_MIN = 30;
|
||||
const TRACK_RATE_WINDOW_MS = 60_000;
|
||||
const allowOpenSky = makeRateLimiter({
|
||||
windowMs: TRACK_RATE_WINDOW_MS,
|
||||
max: TRACK_RATE_PER_MIN,
|
||||
globalMax: TRACK_RATE_PER_MIN * 3,
|
||||
});
|
||||
/**
|
||||
* `/tracks/*` credit governor: a 429 from /tracks/all means that bucket is
|
||||
* empty for every `icao24`, so no upstream call is made until OpenSky's
|
||||
* retry-after passes. The `/states/*` cooldown in opensky.js is a different
|
||||
* bucket and does not apply here.
|
||||
*/
|
||||
let openSkyTracksCooldownUntil = 0;
|
||||
const openSkyTracksGovernor = {
|
||||
remainingMs: () => Math.max(0, openSkyTracksCooldownUntil - Date.now()),
|
||||
arm(upstream) {
|
||||
openSkyTracksCooldownUntil =
|
||||
Date.now() + openSkyRateLimitCooldownMs(upstream);
|
||||
},
|
||||
};
|
||||
/** @type {Map<string, {at:number,status:number,body:string}>} */
|
||||
const cache = new Map();
|
||||
|
||||
/** Shared refusal shape, matching the other rate-limited proxies. */
|
||||
function refuse(res, retryAfterSeconds) {
|
||||
res.writeHead(429, {
|
||||
'Content-Type': 'application/json',
|
||||
'Retry-After': String(Math.max(1, Math.ceil(retryAfterSeconds))),
|
||||
});
|
||||
res.end(JSON.stringify({ error: 'Rate limit exceeded' }));
|
||||
}
|
||||
|
||||
function cachePut(key, entry) {
|
||||
cache.set(key, entry);
|
||||
if (cache.size > TRACK_CACHE_MAX) {
|
||||
@@ -76,63 +26,19 @@ export function trackBackfillProxies() {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {object} [options]
|
||||
* @param {() => Promise<object>|object} [options.headers] Request headers,
|
||||
* resolved only when the upstream is actually called.
|
||||
* @param {{remainingMs: () => number, arm: (upstream: Response) => void}} [options.governor]
|
||||
* Credit cooldown for a metered upstream. While it is cooling the upstream
|
||||
* is not called, though an already-fetched track may still be served (it
|
||||
* costs nothing further); an upstream 429 arms it.
|
||||
* @param {() => boolean} [options.admit] Asked once, immediately before an
|
||||
* upstream call; false refuses the request with a 429.
|
||||
*/
|
||||
async function proxyJson(
|
||||
res,
|
||||
key,
|
||||
upstreamUrl,
|
||||
{ headers = () => ({}), governor, admit } = {},
|
||||
) {
|
||||
const blockedMs = governor?.remainingMs() ?? 0;
|
||||
async function proxyJson(res, key, upstreamUrl, headers = {}) {
|
||||
const cached = cache.get(key);
|
||||
const fresh = cached && Date.now() - cached.at < TRACK_CACHE_MS;
|
||||
// Serve-stale while the account is cooling, the way `/api/flights` does:
|
||||
// a stale trail beats no trail, and replaying a cached body spends no
|
||||
// credits. Only a track is worth replaying past its window: an old error
|
||||
// says nothing about now, so it gives way to the cooldown refusal.
|
||||
const replayable =
|
||||
cached && (fresh || (blockedMs > 0 && cached.status === 200));
|
||||
if (replayable) {
|
||||
if (cached && Date.now() - cached.at < TRACK_CACHE_MS) {
|
||||
res.statusCode = cached.status;
|
||||
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
||||
res.setHeader('Cache-Control', 'no-store');
|
||||
res.end(cached.body);
|
||||
return;
|
||||
}
|
||||
if (blockedMs > 0) {
|
||||
refuse(res, blockedMs / 1000);
|
||||
return;
|
||||
}
|
||||
if (admit && !admit()) {
|
||||
refuse(res, TRACK_RATE_WINDOW_MS / 1000);
|
||||
return;
|
||||
}
|
||||
const upstream = await fetch(upstreamUrl, {
|
||||
headers: await headers(),
|
||||
headers,
|
||||
signal: AbortSignal.timeout(12000),
|
||||
});
|
||||
if (upstream.status === 429 && governor) {
|
||||
// The cooldown now answers for every key, with the time left; caching
|
||||
// this 429 would replay it for the key without one.
|
||||
governor.arm(upstream);
|
||||
try {
|
||||
await upstream.body?.cancel();
|
||||
} catch {
|
||||
/* nothing left to release */
|
||||
}
|
||||
refuse(res, governor.remainingMs() / 1000);
|
||||
return;
|
||||
}
|
||||
const { tooLarge, text } = await readCappedResponseText(
|
||||
upstream,
|
||||
RESPONSE_CAP_BYTES,
|
||||
@@ -172,20 +78,12 @@ export function trackBackfillProxies() {
|
||||
);
|
||||
return;
|
||||
}
|
||||
const token = await getOpenSkyToken();
|
||||
await proxyJson(
|
||||
res,
|
||||
`osky:${icao24}`,
|
||||
`https://opensky-network.org/api/tracks/all?icao24=${icao24}&time=0`,
|
||||
{
|
||||
// Resolved only for a live call: no token is minted for a cached
|
||||
// answer, a refusal, or while the /tracks bucket is cooling.
|
||||
headers: async () => {
|
||||
const token = await getOpenSkyToken();
|
||||
return token ? { Authorization: `Bearer ${token}` } : {};
|
||||
},
|
||||
governor: openSkyTracksGovernor,
|
||||
admit: () => allowOpenSky(clientKey(req)),
|
||||
},
|
||||
token ? { Authorization: `Bearer ${token}` } : {},
|
||||
);
|
||||
} catch (error) {
|
||||
res.statusCode = 502;
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
// ADSBDB ENRICHMENT — the keyspace the cache used to remember forever.
|
||||
//
|
||||
// `/api/adsbdb` answers `route/<callsign>` and `type/<hex>`. 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;
|
||||
// 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;
|
||||
}
|
||||
|
||||
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 >= 600,
|
||||
`both client queues together (600/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 < 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 < 1000, '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');
|
||||
});
|
||||
|
||||
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`);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,120 @@
|
||||
// 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));
|
||||
|
||||
/** 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() {} });
|
||||
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: enrichServices,
|
||||
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');
|
||||
});
|
||||
@@ -63,10 +63,25 @@ export function createEnrichment({
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* How long a temporarily failed lookup stays unasked. A rate-limit refusal
|
||||
* says itself when to ask again (`retryAfterMs`), so that wins; any other
|
||||
* temporary failure waits ENRICH_RETRY_COOLDOWN_MS.
|
||||
* @param {*} error The rejection, as `LiveSourceError` carries it.
|
||||
* @returns {number} Milliseconds.
|
||||
*/
|
||||
function _enrichCooldownMs(error) {
|
||||
const hinted = Number(error?.retryAfterMs);
|
||||
return error?.code === 'limited' && Number.isFinite(hinted) && hinted > 0
|
||||
? hinted
|
||||
: ENRICH_RETRY_COOLDOWN_MS;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ask each key at most once per session, except that a lookup whose source
|
||||
* failed temporarily (rejected or threw) may be asked again after
|
||||
* ENRICH_RETRY_COOLDOWN_MS; an answer, found or not, and a permanent
|
||||
* ENRICH_RETRY_COOLDOWN_MS, or after the refusal's own `retryAfterMs` for a
|
||||
* rate limit (see _enrichCooldownMs); an answer, found or not, and a permanent
|
||||
* refusal (see _enrichFailureIsFinal) are final.
|
||||
* @param {string} key Session-unique lookup key.
|
||||
* @param {object} query The source's enrichment query.
|
||||
@@ -133,7 +148,7 @@ export function createEnrichment({
|
||||
flightState._enrichSeen.delete(job.key);
|
||||
flightState._enrichRetryAfter.set(
|
||||
job.key,
|
||||
Date.now() + ENRICH_RETRY_COOLDOWN_MS,
|
||||
Date.now() + _enrichCooldownMs(error),
|
||||
);
|
||||
},
|
||||
)
|
||||
|
||||
@@ -35,7 +35,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.
|
||||
@@ -53,6 +54,7 @@ export function createLocalAdsbEnrichment({
|
||||
let active = 0;
|
||||
let lastDispatchAt = -Infinity;
|
||||
let dripTimer = null;
|
||||
const retryTimers = new Set();
|
||||
let lifetime = new AbortController();
|
||||
|
||||
function entry(icao) {
|
||||
@@ -68,7 +70,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();
|
||||
@@ -97,8 +99,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;
|
||||
@@ -108,6 +112,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) {
|
||||
@@ -160,6 +172,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;
|
||||
},
|
||||
|
||||
@@ -1,357 +0,0 @@
|
||||
// OPENSKY TRACK BACKFILL — the credit budget the per-icao cache does not guard.
|
||||
//
|
||||
// `/api/flights/track` spends 4 OpenSky credits per call from the `/tracks/*`
|
||||
// bucket. OpenSky keeps three independent daily buckets (`/states/*`,
|
||||
// `/tracks/*`, `/flights/*`), so this route neither spends nor is blocked by
|
||||
// the `/states/all` budget `/api/flights` governs. Its 60s per-icao cache
|
||||
// bounds MEMORY, not spend: `icao24` is six hex digits, so a caller that varies
|
||||
// it walks past the cache into a live, credit-consuming call every time.
|
||||
//
|
||||
// These cases drive the real exported route handlers. No network: `fetch` is
|
||||
// stubbed per test and restored afterwards, so a case that reaches upstream
|
||||
// fails loudly rather than making a request.
|
||||
//
|
||||
// NOTE: the `/states/all` cooldown is module-scoped state in `opensky.js` and,
|
||||
// once set, stays set for the life of the process (bounded 30s…30min). The case
|
||||
// that arms it therefore runs LAST. The tracks cooldown lives in each
|
||||
// `trackBackfillProxies()` instance, so every test gets a clear one.
|
||||
//
|
||||
// Run with: npm test
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { trackBackfillProxies } from '../server/providers/aircraft/tracks.js';
|
||||
import { openSkyProxy } from '../server/providers/aircraft/opensky.js';
|
||||
|
||||
/** Collect a plugin's routes into a path → handler map. */
|
||||
function install(plugin) {
|
||||
const routes = new Map();
|
||||
const server = {
|
||||
middlewares: {
|
||||
use(path, handler) {
|
||||
routes.set(path, handler);
|
||||
},
|
||||
},
|
||||
};
|
||||
plugin.configureServer(server);
|
||||
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,
|
||||
setHeader(name, value) {
|
||||
headers.set(String(name).toLowerCase(), String(value));
|
||||
},
|
||||
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 one test, restoring it afterwards. */
|
||||
function stubFetch(t, impl) {
|
||||
const original = globalThis.fetch;
|
||||
globalThis.fetch = impl;
|
||||
t.after(() => {
|
||||
globalThis.fetch = original;
|
||||
});
|
||||
}
|
||||
|
||||
/** An OpenSky /tracks/all answer, shaped like the real one. */
|
||||
const trackOk = () =>
|
||||
new Response(JSON.stringify({ path: [] }), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
|
||||
test('a caller cycling icao24 cannot walk past the per-icao cache unthrottled', async (t) => {
|
||||
let upstreamCalls = 0;
|
||||
stubFetch(t, async () => {
|
||||
upstreamCalls += 1;
|
||||
return trackOk();
|
||||
});
|
||||
const track = install(trackBackfillProxies()).get('/api/flights/track');
|
||||
|
||||
const allowed = [];
|
||||
for (let i = 0; i < 30; i += 1) {
|
||||
// A DIFFERENT icao24 every time: each one is a fresh cache key, which is
|
||||
// exactly the path the 60s cache cannot see.
|
||||
const icao24 = (0x400000 + i).toString(16).padStart(6, '0');
|
||||
allowed.push(await request(track, { url: `/?icao24=${icao24}` }));
|
||||
}
|
||||
assert.equal(
|
||||
allowed.filter((r) => r.statusCode === 429).length,
|
||||
0,
|
||||
'the first 30 distinct lookups in a minute are ordinary use',
|
||||
);
|
||||
|
||||
const refused = await request(track, { url: '/?icao24=4affff' });
|
||||
assert.equal(refused.statusCode, 429, 'the 31st distinct lookup is refused');
|
||||
assert.deepEqual(refused.body, { error: 'Rate limit exceeded' });
|
||||
assert.equal(
|
||||
refused.headers['retry-after'],
|
||||
'60',
|
||||
'a refusal names the limiter window, not a shorter guess',
|
||||
);
|
||||
assert.equal(
|
||||
upstreamCalls,
|
||||
30,
|
||||
'the refused request never reached OpenSky — the point is the credits',
|
||||
);
|
||||
});
|
||||
|
||||
test('each client gets its own quota rather than sharing one bucket', async (t) => {
|
||||
stubFetch(t, async () => trackOk());
|
||||
const track = install(trackBackfillProxies()).get('/api/flights/track');
|
||||
|
||||
for (let i = 0; i < 30; i += 1)
|
||||
await request(track, {
|
||||
url: `/?icao24=${(0x500000 + i).toString(16)}`,
|
||||
remoteAddress: '198.51.100.7',
|
||||
});
|
||||
const exhausted = await request(track, {
|
||||
url: '/?icao24=5affff',
|
||||
remoteAddress: '198.51.100.7',
|
||||
});
|
||||
assert.equal(exhausted.statusCode, 429);
|
||||
|
||||
const neighbour = await request(track, {
|
||||
url: '/?icao24=5abbbb',
|
||||
remoteAddress: '198.51.100.8',
|
||||
});
|
||||
assert.notEqual(
|
||||
neighbour.statusCode,
|
||||
429,
|
||||
'one noisy host must not take the layer away from everyone else',
|
||||
);
|
||||
});
|
||||
|
||||
test('the retired military route is not metered, so the OpenSky limiter never reaches it', async (t) => {
|
||||
let militaryUpstreamCalls = 0;
|
||||
stubFetch(t, async (url) => {
|
||||
if (String(url).includes('/tracks/all')) return trackOk();
|
||||
militaryUpstreamCalls += 1;
|
||||
return new Response('{"trace":[]}', { status: 200 });
|
||||
});
|
||||
const routes = install(trackBackfillProxies());
|
||||
const track = routes.get('/api/flights/track');
|
||||
const trace = routes.get('/api/military/track');
|
||||
|
||||
for (let i = 0; i < 30; i += 1)
|
||||
await request(track, { url: `/?icao24=${(0x610000 + i).toString(16)}` });
|
||||
assert.equal(
|
||||
(await request(track, { url: '/?icao24=61ffff' })).statusCode,
|
||||
429,
|
||||
);
|
||||
// It answers a fixed refusal without any upstream call, so a limiter would
|
||||
// only turn that refusal into a different one.
|
||||
for (let i = 0; i < 31; i += 1) {
|
||||
const military = await request(trace, {
|
||||
url: `/?hex=${(0x620000 + i).toString(16)}`,
|
||||
});
|
||||
assert.equal(military.statusCode, 503);
|
||||
}
|
||||
assert.equal(militaryUpstreamCalls, 0, 'the refusal makes no upstream call');
|
||||
});
|
||||
|
||||
test('a 429 from /tracks stands every other icao24 down until it clears', async (t) => {
|
||||
let upstreamCalls = 0;
|
||||
stubFetch(t, async () => {
|
||||
upstreamCalls += 1;
|
||||
return new Response('{}', {
|
||||
status: 429,
|
||||
headers: { 'x-rate-limit-retry-after-seconds': '120' },
|
||||
});
|
||||
});
|
||||
const track = install(trackBackfillProxies()).get('/api/flights/track');
|
||||
|
||||
const first = await request(track, { url: '/?icao24=71a001' });
|
||||
assert.equal(first.statusCode, 429);
|
||||
assert.equal(upstreamCalls, 1);
|
||||
|
||||
// A DIFFERENT key: the per-icao cache cannot see it, only the cooldown can.
|
||||
const second = await request(track, { url: '/?icao24=71a002' });
|
||||
assert.equal(second.statusCode, 429, 'refused locally');
|
||||
assert.equal(
|
||||
upstreamCalls,
|
||||
1,
|
||||
'the /tracks bucket is empty, so no further credits are asked for',
|
||||
);
|
||||
const retryAfter = Number(second.headers['retry-after']);
|
||||
assert.ok(
|
||||
retryAfter > 60 && retryAfter <= 120,
|
||||
`the refusal carries OpenSky's remaining cooldown (got ${retryAfter})`,
|
||||
);
|
||||
});
|
||||
|
||||
test('a cached track is still served while /tracks is cooling', async (t) => {
|
||||
let cooling = false;
|
||||
stubFetch(t, async () =>
|
||||
cooling
|
||||
? new Response('{}', {
|
||||
status: 429,
|
||||
headers: { 'x-rate-limit-retry-after-seconds': '120' },
|
||||
})
|
||||
: trackOk(),
|
||||
);
|
||||
const track = install(trackBackfillProxies()).get('/api/flights/track');
|
||||
|
||||
assert.equal(
|
||||
(await request(track, { url: '/?icao24=72b001' })).statusCode,
|
||||
200,
|
||||
);
|
||||
cooling = true;
|
||||
assert.equal(
|
||||
(await request(track, { url: '/?icao24=72b002' })).statusCode,
|
||||
429,
|
||||
);
|
||||
const replay = await request(track, { url: '/?icao24=72b001' });
|
||||
assert.equal(
|
||||
replay.statusCode,
|
||||
200,
|
||||
'replaying a fetched body costs nothing',
|
||||
);
|
||||
});
|
||||
|
||||
test('a malformed icao24 is still rejected before any upstream call', async (t) => {
|
||||
let upstreamCalls = 0;
|
||||
stubFetch(t, async () => {
|
||||
upstreamCalls += 1;
|
||||
return trackOk();
|
||||
});
|
||||
const track = install(trackBackfillProxies()).get('/api/flights/track');
|
||||
const bad = await request(track, { url: '/?icao24=nothex' });
|
||||
assert.equal(bad.statusCode, 400);
|
||||
assert.equal(upstreamCalls, 0);
|
||||
});
|
||||
|
||||
// --- LAST: arming the /states/all cooldown is one-way for this process.
|
||||
test('only upstream calls are charged: cached answers and malformed requests are free', async (t) => {
|
||||
let upstreamCalls = 0;
|
||||
stubFetch(t, async () => {
|
||||
upstreamCalls += 1;
|
||||
return trackOk();
|
||||
});
|
||||
const track = install(trackBackfillProxies()).get('/api/flights/track');
|
||||
|
||||
// Re-selecting one aircraft, and a burst of malformed requests: more than a
|
||||
// window's worth of each, none of which costs OpenSky anything.
|
||||
for (let i = 0; i < 40; i += 1) {
|
||||
const repeat = await request(track, { url: '/?icao24=73c000' });
|
||||
assert.equal(repeat.statusCode, 200);
|
||||
const malformed = await request(track, { url: '/?icao24=nothex' });
|
||||
assert.equal(malformed.statusCode, 400);
|
||||
}
|
||||
assert.equal(upstreamCalls, 1, 'one live call, 39 answers from the cache');
|
||||
|
||||
// The window still holds 29 more live calls for this client.
|
||||
for (let i = 1; i < 30; i += 1) {
|
||||
const icao24 = (0x73c000 + i).toString(16);
|
||||
const live = await request(track, { url: `/?icao24=${icao24}` });
|
||||
assert.equal(live.statusCode, 200, `live lookup ${i + 1} of 30 is allowed`);
|
||||
}
|
||||
const refused = await request(track, { url: '/?icao24=73cfff' });
|
||||
assert.equal(refused.statusCode, 429, 'the 31st live lookup is refused');
|
||||
assert.equal(upstreamCalls, 30);
|
||||
});
|
||||
|
||||
test('the request that trips the cooldown, and repeats of it, carry the time left', async (t) => {
|
||||
let upstreamCalls = 0;
|
||||
stubFetch(t, async () => {
|
||||
upstreamCalls += 1;
|
||||
return new Response('{}', {
|
||||
status: 429,
|
||||
headers: { 'x-rate-limit-retry-after-seconds': '120' },
|
||||
});
|
||||
});
|
||||
const track = install(trackBackfillProxies()).get('/api/flights/track');
|
||||
|
||||
for (const attempt of ['first', 'repeat']) {
|
||||
const refused = await request(track, { url: '/?icao24=74d001' });
|
||||
assert.equal(refused.statusCode, 429);
|
||||
const retryAfter = Number(refused.headers['retry-after']);
|
||||
assert.ok(
|
||||
retryAfter > 60 && retryAfter <= 120,
|
||||
`the ${attempt} refusal names OpenSky's cooldown (got ${retryAfter})`,
|
||||
);
|
||||
}
|
||||
assert.equal(upstreamCalls, 1, 'the repeat was answered by the cooldown');
|
||||
});
|
||||
|
||||
test('an error cached before the cooldown is not replayed as stale', async (t) => {
|
||||
t.mock.timers.enable({ apis: ['Date'], now: 1_800_000_000_000 });
|
||||
let mode = 'missing';
|
||||
stubFetch(t, async () =>
|
||||
mode === 'missing'
|
||||
? new Response('{}', { status: 404 })
|
||||
: new Response('{}', {
|
||||
status: 429,
|
||||
headers: { 'x-rate-limit-retry-after-seconds': '600' },
|
||||
}),
|
||||
);
|
||||
const track = install(trackBackfillProxies()).get('/api/flights/track');
|
||||
|
||||
assert.equal(
|
||||
(await request(track, { url: '/?icao24=75e001' })).statusCode,
|
||||
404,
|
||||
);
|
||||
t.mock.timers.tick(61_000); // the 404 has left its 60 s window
|
||||
mode = 'cooling';
|
||||
assert.equal(
|
||||
(await request(track, { url: '/?icao24=75e002' })).statusCode,
|
||||
429,
|
||||
);
|
||||
const later = await request(track, { url: '/?icao24=75e001' });
|
||||
assert.equal(
|
||||
later.statusCode,
|
||||
429,
|
||||
'the old 404 is not served as if it were current',
|
||||
);
|
||||
assert.ok(Number(later.headers['retry-after']) > 60);
|
||||
});
|
||||
|
||||
test('a /states/all 429 does not block track backfill: separate OpenSky buckets', async (t) => {
|
||||
let trackUpstreamCalls = 0;
|
||||
stubFetch(t, async (url) => {
|
||||
if (String(url).includes('states/all')) {
|
||||
return new Response('{}', {
|
||||
status: 429,
|
||||
headers: { 'x-rate-limit-retry-after-seconds': '120' },
|
||||
});
|
||||
}
|
||||
trackUpstreamCalls += 1;
|
||||
return trackOk();
|
||||
});
|
||||
|
||||
const states = install(openSkyProxy()).get('/api/flights');
|
||||
await request(states, { url: '/' });
|
||||
|
||||
const track = install(trackBackfillProxies()).get('/api/flights/track');
|
||||
const backfill = await request(track, { url: '/?icao24=7a1b2c' });
|
||||
assert.equal(
|
||||
backfill.statusCode,
|
||||
200,
|
||||
'the /tracks bucket still has credits, so the trail is fetched',
|
||||
);
|
||||
assert.equal(trackUpstreamCalls, 1);
|
||||
});
|
||||
@@ -5,7 +5,7 @@ import path from 'node:path';
|
||||
import { providerCooldownMs } from '../server/providers/space/cooldown.js';
|
||||
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'))
|
||||
@@ -27,7 +27,7 @@ function fixture(name, overrides = {}, preview = false) {
|
||||
readResponseTextCapped, coalesceProxyRequest, providerCooldownMs,
|
||||
// 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,
|
||||
|
||||
Reference in new issue
Block a user