fix(server): charge the track limiter for upstream calls only and stop replaying stale errors

A cached answer or a malformed request costs OpenSky nothing, so neither
is charged to the 30/min window. During a /tracks cooldown only a cached
track is replayed; an old cached error gives way to the cooldown refusal.
The 429 that arms the cooldown is no longer cached, so it and its repeats
carry Retry-After. No token is minted unless the upstream is called.
This commit is contained in:
Said Turksever committed 2026-11-23 01:23:44 +00:00
1 parent 2eef8cd902
commit 7ba53f6d0e
4 files changed
+135 -21

No files matched your search

@@ -1,6 +1,7 @@
- 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), and a
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
+1 -1
View File
@@ -9011,7 +9011,7 @@ 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 requests/minute (90 global; refusals send `Retry-After: 60`), 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 and otherwise answers `429` with the remaining cooldown instead of spending 4 more credits. It does not read `/api/flights`'s `/states/*` cooldown, since OpenSky meters the two buckets independently.
- `/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.
+48 -19
View File
@@ -11,7 +11,9 @@ import { makeRateLimiter, clientKey } from '../common/rate-limit.js';
* 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.
* `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.
* /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.
@@ -75,19 +77,32 @@ export function trackBackfillProxies() {
}
/**
* @param {{remainingMs: () => number, arm: (upstream: Response) => void}} [governor]
* @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 body may still be served (it
* 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) {
async function proxyJson(
res,
key,
upstreamUrl,
{ headers = () => ({}), governor, admit } = {},
) {
const blockedMs = governor?.remainingMs() ?? 0;
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.
if (cached && (fresh || blockedMs > 0)) {
// 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) {
res.statusCode = cached.status;
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.setHeader('Cache-Control', 'no-store');
@@ -98,11 +113,26 @@ export function trackBackfillProxies() {
refuse(res, blockedMs / 1000);
return;
}
if (admit && !admit()) {
refuse(res, TRACK_RATE_WINDOW_MS / 1000);
return;
}
const upstream = await fetch(upstreamUrl, {
headers,
headers: await headers(),
signal: AbortSignal.timeout(12000),
});
if (upstream.status === 429) governor?.arm(upstream);
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,
@@ -130,10 +160,6 @@ export function trackBackfillProxies() {
function install(middlewares) {
middlewares.use('/api/flights/track', async (req, res) => {
try {
if (!allowOpenSky(clientKey(req))) {
refuse(res, TRACK_RATE_WINDOW_MS / 1000);
return;
}
const incoming = new URL(req.url || '', 'http://localhost');
const icao24 = String(incoming.searchParams.get('icao24') || '')
.trim()
@@ -146,17 +172,20 @@ export function trackBackfillProxies() {
);
return;
}
// While the /tracks bucket is cooling, do not mint a token either.
const token =
openSkyTracksGovernor.remainingMs() > 0
? null
: await getOpenSkyToken();
await proxyJson(
res,
`osky:${icao24}`,
`https://opensky-network.org/api/tracks/all?icao24=${icao24}&time=0`,
token ? { Authorization: `Bearer ${token}` } : {},
openSkyTracksGovernor,
{
// 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)),
},
);
} catch (error) {
res.statusCode = 502;
+84
View File
@@ -246,6 +246,90 @@ test('a malformed icao24 is still rejected before any upstream call', async (t)
});
// --- 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) => {