fix(server): give /tracks its own credit cooldown, armed by its own 429

The branch read the /states/all cooldown from /api/flights and never set
one from /tracks/all, which is backwards for an API that meters the two
separately: a flights cooldown blocked backfill that still had credits,
and a /tracks 429 left every other icao24 free to ask again.

tracks.js now keeps a cooldown for the /tracks bucket, armed by a 429
from /tracks/all with OpenSky's retry-after (opensky.js exports its
existing parser so both buckets read the header the same way). The two
routes get separate limiters, and a limiter refusal sends Retry-After 60,
the window, rather than 10.
This commit is contained in:
daikaginza committed 2026-10-23 12:34:46 +07:00
1 parent a073e6e658
commit bfcf12af49
4 files changed
+67 -55

No files matched your search

@@ -1,10 +1,10 @@
- Stop the track-backfill proxies from spending the OpenSky credit budget the
main flights proxy is protecting. `/api/flights/track` and
`/api/military/track` now carry an always-on 30-per-minute per-client limiter
(90 global), and `/api/flights/track` honours the 429 cooldown that
`/api/flights` already sets: while the account is out of budget it serves any
cached track and otherwise answers `429` with the remaining cooldown rather
than spending 4 more credits. The existing 60-second per-key cache bounds
memory, not spend — a caller varying `icao24` produced a fresh upstream call
every time. Single-aircraft backfill, which is issued once per selected
contact, is unaffected (daikaginza, #685).
- Stop the track-backfill proxies from turning a varied `icao24`/`hex` into
unbounded upstream spend. `/api/flights/track` and `/api/military/track`
each carry an always-on 30-per-minute per-client limiter (90 global), 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).
+1 -1
View File
@@ -5276,7 +5276,7 @@ pins and share links already supply complete boxes.
- `/api/military-installations` uses an independent limiter with the same 90-per-client/300-global one-minute bounds, so viewport installation refreshes never consume `/api/overpass` annotation capacity.
- `/api/route` proxies bounded OSRM route requests for annotation routes, with profile allowlisting, distance caps, response caps, caching, and sanitized "no route found" errors.
- 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=` (60s cache, 5MB cap, ODbL attribution required in UI).
- Both track-backfill routes carry an always-on per-client limiter of 30 requests/minute (90 global), because their 60s per-key cache bounds memory rather than spend: a caller varying `icao24`/`hex` produces a fresh key and a fresh upstream call each time. `/api/flights/track` additionally reads `/api/flights`'s 429 credit cooldown and, while it is active, serves any cached track and otherwise answers `429` with the remaining cooldown instead of spending 4 more credits against an account that is already out of budget.
- Each track-backfill route carries its own always-on per-client limiter of 30 requests/minute (90 global; refusals send `Retry-After: 60`), because their 60s per-key cache bounds memory rather than spend: a caller varying `icao24`/`hex` 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.
- 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.
+4 -17
View File
@@ -35,11 +35,13 @@ 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.
* 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.
* @param {Response} upstream Rate-limited response.
* @returns {number} Cooldown (ms).
*/
function openSkyRateLimitCooldownMs(upstream) {
export 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 =
@@ -120,21 +122,6 @@ let _openskyTtlMs = OPENSKY_CACHE_MS;
let _openskyCooldownUntil = 0;
let _openskyCooldownStatus = 429;
const _openskySnapshotInFlight = new Map();
/**
* Milliseconds left on the 429 cooldown, or 0 when upstream may be called.
*
* Read-only view of lever 2 above, exported so the OTHER routes that spend the
* same daily credit budget can honor it. `/api/flights/track` costs 4 credits
* per call against this account just as `/states/all` does, so minting one
* while this proxy is cooling would spend budget the account has already been
* told it does not have. Only this module writes the cooldown.
*
* @param {number} [now] - Epoch-ms; injectable so tests need no clock control.
* @returns {number} Remaining cooldown in ms (0 when clear).
*/
export function openSkyCooldownRemainingMs(now = Date.now()) {
return Math.max(0, _openskyCooldownUntil - now);
}
/**
* Picks the cache TTL from the remaining daily credit budget.
* Client polls every 30 s, so tiers ≤30 s cost the same 480 credits/h; the
+52 -27
View File
@@ -1,16 +1,17 @@
import { getOpenSkyToken, openSkyCooldownRemainingMs } from './opensky.js';
import { getOpenSkyToken, openSkyRateLimitCooldownMs } 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;
* own credit bucket, 4 credits per call on the free tier). OAuth via the
* 4 credits per call from the `/tracks/*` bucket, which OpenSky keeps
* separate from the `/states/*` one `/api/flights` spends). OAuth via the
* shared coalesced token. 60s per-icao cache; 404/429 forwarded so the
* client can fall back to its accumulated trail silently. Both routes are
* rate-limited per IP, and the OpenSky one additionally stands down while
* `/api/flights` is in its 429 credit cooldown — the per-icao cache bounds
* memory, not spend, since a different `icao24` is simply a different key.
* client can fall back to its accumulated trail silently. Each route 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.
* /api/military/track?hex=<hex> — adsb.lol tar1090 readsb trace
* (undocumented but live; no browser CORS, hence this proxy). Up to ~24h
* of real history per aircraft. Treat as best-effort; data is ODbL —
@@ -28,16 +29,36 @@ export function trackBackfillProxies() {
* 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, military and vessels layers), and re-selecting the
* same aircraft inside a minute is served from cache. 30/min is a target
* switch every two seconds, sustained — well clear of any human, and the
* same band `/api/geocode` and `/api/regional-brief` already use.
* 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.
* Each route gets its own limiter: they spend different upstreams.
*/
const TRACK_RATE_PER_MIN = 30;
const allow = makeRateLimiter({
windowMs: 60_000,
max: TRACK_RATE_PER_MIN,
globalMax: TRACK_RATE_PER_MIN * 3,
});
const TRACK_RATE_WINDOW_MS = 60_000;
const trackLimiter = () =>
makeRateLimiter({
windowMs: TRACK_RATE_WINDOW_MS,
max: TRACK_RATE_PER_MIN,
globalMax: TRACK_RATE_PER_MIN * 3,
});
const allowOpenSky = trackLimiter();
const allowAdsbLol = trackLimiter();
/**
* `/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();
@@ -59,10 +80,13 @@ export function trackBackfillProxies() {
}
/**
* @param {number} [blockedMs] - When > 0 the upstream must not be called;
* an already-fetched body may still be served (it costs nothing further).
* @param {{remainingMs: () => number, arm: (upstream: Response) => void}} [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
* costs nothing further); an upstream 429 arms it.
*/
async function proxyJson(res, key, upstreamUrl, headers = {}, blockedMs = 0) {
async function proxyJson(res, key, upstreamUrl, headers = {}, governor) {
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:
@@ -83,6 +107,7 @@ export function trackBackfillProxies() {
headers,
signal: AbortSignal.timeout(12000),
});
if (upstream.status === 429) governor?.arm(upstream);
const { tooLarge, text } = await readCappedResponseText(
upstream,
RESPONSE_CAP_BYTES,
@@ -110,8 +135,8 @@ export function trackBackfillProxies() {
function install(middlewares) {
middlewares.use('/api/flights/track', async (req, res) => {
try {
if (!allow(clientKey(req))) {
refuse(res, 10);
if (!allowOpenSky(clientKey(req))) {
refuse(res, TRACK_RATE_WINDOW_MS / 1000);
return;
}
const incoming = new URL(req.url || '', 'http://localhost');
@@ -126,17 +151,17 @@ export function trackBackfillProxies() {
);
return;
}
// This route spends the SAME daily credit budget as `/api/flights`
// (4 credits per call), so it honors that proxy's 429 cooldown. While
// the account is cooling, do not mint a token and do not call upstream.
const coolingMs = openSkyCooldownRemainingMs();
const token = coolingMs > 0 ? null : await getOpenSkyToken();
// 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}` } : {},
coolingMs,
openSkyTracksGovernor,
);
} catch (error) {
res.statusCode = 502;
@@ -150,8 +175,8 @@ export function trackBackfillProxies() {
// adsb.lol is free and unmetered, so no credit governor applies here —
// the limiter is for the operator's own IP reputation with a community
// service, the same reason `/api/overpass` carries one.
if (!allow(clientKey(req))) {
refuse(res, 10);
if (!allowAdsbLol(clientKey(req))) {
refuse(res, TRACK_RATE_WINDOW_MS / 1000);
return;
}
const incoming = new URL(req.url || '', 'http://localhost');