mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-23 03:32:19 +00:00
fix(server): stop track backfill from spending the OpenSky credit budget
`/api/opensky-track` costs 4 OpenSky credits per call against the same ~4000/day account as `/api/opensky`, but participated in none of that proxy's credit governor. Its 60-second per-icao cache bounds memory, not spend: `icao24` is six hex digits, so a caller that varies it produces a fresh key and a fresh upstream call every time. Both track-backfill routes now carry an always-on 30/min per-client limiter (90 global) — the band `/api/geocode` and `/api/regional-brief` already use, and far above the real demand, which is one backfill per aircraft the operator selects. `/api/opensky-track` additionally reads the 429 cooldown `/api/opensky` already maintains. While the account is out of budget it serves any cached track and otherwise answers 429 with the remaining cooldown, instead of minting a token and spending four more credits. adsb.lol is free and unmetered, so only the limiter applies there.
This commit is contained in:
1 parent
b210ab0fe4
commit
65018015a0
7 files changed
+313
-6
No files matched your search
@@ -41,6 +41,21 @@ const OPENSKY_CACHE_MS = 9000;
|
||||
let _openskyTtlMs = OPENSKY_CACHE_MS;
|
||||
/** @type {number} Epoch-ms before which no upstream fetch is attempted. */
|
||||
let _openskyCooldownUntil = 0;
|
||||
/**
|
||||
* 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/opensky-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
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
import { getOpenSkyToken } from './opensky.js';
|
||||
import { getOpenSkyToken, openSkyCooldownRemainingMs } 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/opensky-track?icao24=<hex6> — OpenSky GET /tracks/all (experimental;
|
||||
* 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.
|
||||
* 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/opensky` is in its 429 credit cooldown — the per-icao cache bounds
|
||||
* memory, not spend, since a different `icao24` is simply a different key.
|
||||
* /api/adsblol/trace?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 —
|
||||
@@ -16,9 +20,36 @@ 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, 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.
|
||||
*/
|
||||
const TRACK_RATE_PER_MIN = 30;
|
||||
const allow = makeRateLimiter({
|
||||
windowMs: 60_000,
|
||||
max: TRACK_RATE_PER_MIN,
|
||||
globalMax: TRACK_RATE_PER_MIN * 3,
|
||||
});
|
||||
/** @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) {
|
||||
@@ -27,15 +58,27 @@ export function trackBackfillProxies() {
|
||||
}
|
||||
}
|
||||
|
||||
async function proxyJson(res, key, upstreamUrl, headers = {}) {
|
||||
/**
|
||||
* @param {number} [blockedMs] - When > 0 the upstream must not be called;
|
||||
* an already-fetched body may still be served (it costs nothing further).
|
||||
*/
|
||||
async function proxyJson(res, key, upstreamUrl, headers = {}, blockedMs = 0) {
|
||||
const cached = cache.get(key);
|
||||
if (cached && Date.now() - cached.at < TRACK_CACHE_MS) {
|
||||
const fresh = cached && Date.now() - cached.at < TRACK_CACHE_MS;
|
||||
// Serve-stale while the account is cooling, the way `/api/opensky` does:
|
||||
// a stale trail beats no trail, and replaying a cached body spends no
|
||||
// credits.
|
||||
if (cached && (fresh || blockedMs > 0)) {
|
||||
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;
|
||||
}
|
||||
const upstream = await fetch(upstreamUrl, {
|
||||
headers,
|
||||
signal: AbortSignal.timeout(12000),
|
||||
@@ -67,6 +110,10 @@ export function trackBackfillProxies() {
|
||||
function install(middlewares) {
|
||||
middlewares.use('/api/opensky-track', async (req, res) => {
|
||||
try {
|
||||
if (!allow(clientKey(req))) {
|
||||
refuse(res, 10);
|
||||
return;
|
||||
}
|
||||
const incoming = new URL(req.url || '', 'http://localhost');
|
||||
const icao24 = String(incoming.searchParams.get('icao24') || '')
|
||||
.trim()
|
||||
@@ -79,12 +126,17 @@ export function trackBackfillProxies() {
|
||||
);
|
||||
return;
|
||||
}
|
||||
const token = await getOpenSkyToken();
|
||||
// This route spends the SAME daily credit budget as `/api/opensky`
|
||||
// (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();
|
||||
await proxyJson(
|
||||
res,
|
||||
`osky:${icao24}`,
|
||||
`https://opensky-network.org/api/tracks/all?icao24=${icao24}&time=0`,
|
||||
token ? { Authorization: `Bearer ${token}` } : {},
|
||||
coolingMs,
|
||||
);
|
||||
} catch (error) {
|
||||
res.statusCode = 502;
|
||||
@@ -95,6 +147,13 @@ export function trackBackfillProxies() {
|
||||
|
||||
middlewares.use('/api/adsblol/trace', async (req, res) => {
|
||||
try {
|
||||
// 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);
|
||||
return;
|
||||
}
|
||||
const incoming = new URL(req.url || '', 'http://localhost');
|
||||
const hex = String(incoming.searchParams.get('hex') || '')
|
||||
.trim()
|
||||
|
||||
Reference in new issue
Block a user