Merge upstream/main, following its route renames

main renamed the three routes this branch governs:

  /api/opensky       -> /api/flights
  /api/opensky-track -> /api/flights/track
  /api/adsblol/trace -> /api/military/track

The merge took main's names in the route registrations cleanly, which left the
branch's own material pointing at routes that no longer exist — including
`openSkyTrackGovernor.test.mjs`, which looks its handlers up BY path, so it
failed with "handler is not a function" rather than with anything that named
the cause. Renamed in the test, in both doc comments and in the CHANGELOG and
CURRENT-STATE entries this branch adds. The historical CHANGELOG entry that
main also carries is left alone: it records what was true at that release.

Nothing else about the change moved. The limiter, its sizing, the cooldown
read and the serve-stale path are byte-identical to the branch tip; the only
other differences from it are the two append-only bookkeeping files.

  node --test src/openSkyTrackGovernor.test.mjs \
    src/tooling/liveProviders.test.mjs src/proxyErrorResponses.test.mjs
    tests 34  pass 34  fail 0
  npm run format:check            Checked 1210 source files.
  npm run check:boundaries        clean
  npm run layer-token:check       28 published, 0 new
This commit is contained in:
daikaginza committed 2026-10-05 17:39:29 +07:00
commit 0c1b017699
402 files changed
+47328 -3632

No files matched your search

+8 -4
View File
@@ -1,7 +1,7 @@
/**
* Vite plugin: adsb.lol military aircraft proxy with 12 s response cache.
*
* Proxies GET /api/adsblol/mil to https://api.adsb.lol/v2/mil. When upstream
* Serves GET /api/military from https://api.adsb.lol/v2/mil. When upstream
* fails — a thrown fetch OR a non-OK status such as 429 — the proxy serves its
* cached body as STALE instead of relaying the failure, and it backs off from
* upstream for the Retry-After period (bounded) so a rate limit is never
@@ -55,10 +55,11 @@ export function adsbLolProxy() {
res.writeHead(status, {
'Content-Type': 'application/json',
'Cache-Control': 'no-store',
'X-ADS-B-Cache': cacheStatus,
'X-Feed-Source': 'adsb.lol',
'X-Feed-Cache': cacheStatus,
...(['HIT', 'STALE'].includes(cacheStatus)
? {
'X-ADS-B-Cache-Age-Ms': String(Math.max(0, Date.now() - _cacheAt)),
'X-Feed-Age-Ms': String(Math.max(0, Date.now() - _cacheAt)),
}
: {}),
...extra,
@@ -67,8 +68,11 @@ export function adsbLolProxy() {
}
const installMiddleware = (server) => {
server.middlewares.use('/api/adsblol/mil', async (req, res) => {
server.middlewares.use('/api/military', async (req, res, next) => {
try {
// This mount also matches its /track route, served by its own handler.
if (new URL(req.url || '/', 'http://localhost').pathname !== '/')
return next();
const now = Date.now();
if (_cache && now - _cacheAt < CACHE_MS) {
serve(res, 200, _cache, 'HIT');
+39 -11
View File
@@ -25,6 +25,36 @@ let _openskyCacheMeta = null;
let _openskyCacheSourceEpochMs = null;
/** TTL for the OpenSky response cache (ms). */
const OPENSKY_CACHE_MS = 9000;
/** Per-attempt limit for the global snapshot; it normally arrives in ~1.5 s. */
const OPENSKY_ATTEMPT_TIMEOUT_MS = 10_000;
const OPENSKY_STATES_URL =
'https://opensky-network.org/api/states/all?extended=1';
/**
* Fetch and read the global snapshot, giving each attempt
* OPENSKY_ATTEMPT_TIMEOUT_MS and retrying once when an attempt times out or
* the connection fails. A second failure throws, which the proxy answers
* from its stale cache or the regional fallback.
* @param {Record<string, string>} headers Request headers.
* @returns {Promise<{upstream: Response, body: string}>}
*/
async function fetchOpenSkyStates(headers) {
for (let attempt = 1; ; attempt++) {
try {
const upstream = await fetch(OPENSKY_STATES_URL, {
headers,
signal: AbortSignal.timeout(OPENSKY_ATTEMPT_TIMEOUT_MS),
});
return { upstream, body: await upstream.text() };
} catch (error) {
if (attempt >= 2) throw error;
console.warn(
'[OpenSky] global snapshot attempt failed, retrying:',
error?.message || error,
);
}
}
}
// --- OpenSky credit governor (field-test fix 2026-07-06) -------------------
// The global /states/all this proxy fetches costs 4 CREDITS per call against
// OpenSky's ~4000/day authenticated budget — a day with the app open burned
@@ -45,7 +75,7 @@ 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
* 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.
@@ -122,6 +152,7 @@ export async function getOpenSkyToken() {
{
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
signal: AbortSignal.timeout(OPENSKY_ATTEMPT_TIMEOUT_MS),
body: `grant_type=client_credentials&client_id=${encodeURIComponent(clientId)}&client_secret=${encodeURIComponent(clientSecret)}`,
},
);
@@ -364,8 +395,12 @@ function openSkySourceIsStale(sourceEpochMs, now = Date.now()) {
*/
export function openSkyProxy() {
const installMiddleware = (server) => {
server.middlewares.use('/api/opensky', async (req, res) => {
server.middlewares.use('/api/flights', async (req, res, next) => {
try {
// This mount also matches its /track route, served by its own handler.
if (new URL(req.url || '/', 'http://localhost').pathname !== '/')
return next();
res.setHeader('X-Feed-Source', 'OpenSky Network');
const requestedMode = normalizeOpenSkyAuthMode(
process.env.OPENSKY_AUTH_MODE,
);
@@ -485,10 +520,7 @@ export function openSkyProxy() {
}
}
let upstream = await fetch(
'https://opensky-network.org/api/states/all?extended=1',
{ headers },
);
let { upstream, body } = await fetchOpenSkyStates(headers);
// Auto-mode fallback: if OAuth was rejected, retry with Basic credentials
if (
(upstream.status === 401 || upstream.status === 403) &&
@@ -500,15 +532,11 @@ export function openSkyProxy() {
Accept: 'application/json',
Authorization: `Basic ${Buffer.from(`${basicUser}:${basicPass}`).toString('base64')}`,
};
upstream = await fetch(
'https://opensky-network.org/api/states/all?extended=1',
{ headers: retryHeaders },
);
({ upstream, body } = await fetchOpenSkyStates(retryHeaders));
usedMode = 'basic';
reason = 'oauth_rejected_fallback_basic';
}
let body = await upstream.text();
const sourceEpochMs = upstream.ok ? openSkySourceEpochMs(body) : null;
if (
upstream.ok &&
+7 -7
View File
@@ -4,14 +4,14 @@ 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;
* /api/flights/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. 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
* `/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.
* /api/adsblol/trace?hex=<hex> — adsb.lol tar1090 readsb trace
* /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 —
* credit "adsb.lol (ODbL)" in the UI.
@@ -65,7 +65,7 @@ export function trackBackfillProxies() {
async function proxyJson(res, key, upstreamUrl, headers = {}, blockedMs = 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/opensky` does:
// 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)) {
@@ -108,7 +108,7 @@ export function trackBackfillProxies() {
}
function install(middlewares) {
middlewares.use('/api/opensky-track', async (req, res) => {
middlewares.use('/api/flights/track', async (req, res) => {
try {
if (!allow(clientKey(req))) {
refuse(res, 10);
@@ -126,7 +126,7 @@ export function trackBackfillProxies() {
);
return;
}
// This route spends the SAME daily credit budget as `/api/opensky`
// 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();
@@ -145,7 +145,7 @@ export function trackBackfillProxies() {
}
});
middlewares.use('/api/adsblol/trace', async (req, res) => {
middlewares.use('/api/military/track', 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