Compare commits

..
Author SHA1 Message Date
Sameh Khamis 1d60144f60 Changelog entry for quantized-mesh terrain fetchTile (#1902) 2026-11-22 16:13:05 -08:00
Sameh Khamis eebde0bdca Quantized-mesh terrain can supply its tiles through fetchTile, like imagery
A `quantizedMesh` terrain spec takes an optional `fetchTile`, called with
the tile (rows from the north), its URL as Cesium resolved it and an abort
signal. Cesium still reads `layer.json` at the url and schedules, cancels
and decodes the tiles; only the bytes of each tile come from `fetchTile`.
A `missing` tile draws its parent's terrain there and a deferred one is
asked for again shortly.
2026-11-22 15:44:07 -08:00
18 changed files with 420 additions and 577 deletions

No files matched your search

-6
View File
@@ -51,12 +51,6 @@ 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
+4
View File
@@ -0,0 +1,4 @@
- Quantized-mesh terrain can supply its tiles through `fetchTile`, as `xyz`
imagery does: Cesium still reads `layer.json`, schedules, cancels and
decodes the tiles, and a `missing` tile draws its parent's terrain there
(samehkhamis, #1902).
@@ -1,13 +0,0 @@
- 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).
+6 -20
View File
@@ -4350,25 +4350,6 @@ 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.
@@ -9943,7 +9924,12 @@ unless its plugin hands the application a map engine of its own
terrain as `quantizedMesh` terrain at its URL (`src/maps/keylessTerrain.js`);
while the keyless terrain does not answer, the ellipsoid stands in and the
map stack tries it again behind it. A renderer without the `terrain`
capability keeps the ellipsoid.
capability keeps the ellipsoid. A `quantizedMesh` terrain source can supply
its tiles through `fetchTile`, like `xyz` imagery: Cesium still reads
`layer.json` at the source's URL, schedules, cancels and decodes the tiles,
and only each tile's bytes come from `fetchTile`; a `missing` tile draws its
parent's terrain, a `defer`red one is asked for again shortly
(`src/render/cesium/terrainTiles.js`).
A viewer with no renderer bound gets the Cesium engine
(`src/render/cesium/mapEngine.js`), with the other unbound ports, from the
+1 -1
View File
@@ -872,4 +872,4 @@ course. The stub keeps no drawn course. These wait for scenes that capture
an icon mid-turn. Height queries that count a set
(`includeInHeightQueries`) are not checked either: the stub's heights are
scripted, so it does not model them. Nor are video frames (a check needs a
video) or `fetchTile` (the stub fetches nothing).
video) or `fetchTile`, imagery's or terrain's (the stub fetches nothing).
+3 -3
View File
@@ -78,6 +78,8 @@
"src/render/cesium/uploadProbe.test.mjs",
"src/render/cesium/tileRequests.js",
"src/render/cesium/tileRequests.test.mjs",
"src/render/cesium/terrainTiles.js",
"src/render/cesium/terrainTiles.test.mjs",
"src/queries/heights.test.mjs",
"src/render/cesium/heights.test.mjs",
"src/render/cesium/drawLineAges.test.mjs",
@@ -1703,7 +1705,5 @@
"src/ui/livePanel.test.mjs",
"src/ui/stationPanel.test.mjs",
"src/ui/styles/live.css",
"src/ui/styles/station.css",
"src/adsbdbCacheGovernor.test.mjs",
"src/layers/enrichmentRateLimitRetry.test.mjs"
"src/ui/styles/station.css"
]
+8 -2
View File
@@ -392,8 +392,6 @@
"server/providers/common/compress.js",
"server/providers/common/http.js",
"server/providers/common/query.js",
"server/providers/common/rate-limit.js",
"src/sources/rateLimit.js",
"server/providers/aircraft/opensky.js",
"server/providers/aircraft/adsb-lol.js",
"server/providers/aircraft/enrichment.js",
@@ -1389,6 +1387,7 @@
"src/render/cesium/effects.js",
"src/render/cesium/screenModulation.js",
"src/render/cesium/globe.js",
"src/render/cesium/terrainTiles.js",
"src/render/baseTilesets.js",
"src/render/cesium/imagery.js",
"src/render/cesium/imageryFrames.js",
@@ -2436,6 +2435,7 @@
"src/render/cesium/gpuIcons.js",
"src/render/cesium/effects.js",
"src/render/cesium/globe.js",
"src/render/cesium/terrainTiles.js",
"src/render/cesium/query.js",
"src/render/cesium/quality.js",
"src/render/input/wheel.js",
@@ -2534,6 +2534,7 @@
"src/render/stub/math.js",
"src/render/cesium/unbound.js",
"src/render/cesium/globe.js",
"src/render/cesium/terrainTiles.js",
"src/render/baseTilesets.js",
"src/render/cesium/google3d.js",
"src/render/cesium/imagery.js",
@@ -3223,6 +3224,7 @@
"src/sources/requestDeadline.js",
"src/layers/traffic/lifecycle.js",
"src/render/cesium/globe.js",
"src/render/cesium/terrainTiles.js",
"src/render/baseTilesets.js",
"src/render/cesium/google3d.js",
"src/render/cesium/imagery.js",
@@ -3388,6 +3390,7 @@
"modules": [
"src/render/cesium/google3d.js",
"src/render/cesium/globe.js",
"src/render/cesium/terrainTiles.js",
"src/render/cesium/imagery.js",
"src/render/cesium/imageryFrames.js",
"src/render/cesium/tileRequests.js",
@@ -3969,6 +3972,7 @@
"src/maps/catalog.js",
"src/maps/controller.js",
"src/render/cesium/globe.js",
"src/render/cesium/terrainTiles.js",
"src/render/baseTilesets.js",
"src/render/cesium/iconSetPrimitive.js",
"src/render/recession.js",
@@ -4282,6 +4286,7 @@
"src/render/motion/iconMotion.js",
"src/render/cesium/query.js",
"src/render/cesium/globe.js",
"src/render/cesium/terrainTiles.js",
"src/render/baseTilesets.js",
"src/render/cesium/drawHit.js",
"src/render/cesium/draw.js",
@@ -6253,6 +6258,7 @@
"src/layers/recentImagery/rendering.js",
"src/render/baseTilesets.js",
"src/render/cesium/globe.js",
"src/render/cesium/terrainTiles.js",
"src/layers/recentImagery/thumbnails.js",
"src/maps/imageryHost.js",
"src/layers/streetLevel/index.js",
+17 -133
View File
@@ -1,10 +1,5 @@
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. */
@@ -17,126 +12,29 @@ const ADSBDB_MAX_RESPONSE_BYTES = 1024 * 1024;
* cached. Adapted from skylight
* (MIT) server/src/enrich/routes.ts.
*/
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;
export function adsbdbProxy() {
const TTL_MS = 24 * 3600_000;
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() };
const CACHE_PATH = path.join(process.cwd(), '.gev-cache', 'adsbdb.json');
let cache = { routes: {}, aircraft: {} };
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 {
sizeBytes = (await fsp.stat(CACHE_PATH)).size;
const parsed = JSON.parse(await fsp.readFile(CACHE_PATH, 'utf8'));
cache = { routes: parsed.routes ?? {}, aircraft: parsed.aircraft ?? {} };
} catch {
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 */
}
/* 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({
routes: Object.fromEntries(cache.routes),
aircraft: Object.fromEntries(cache.aircraft),
}),
'utf8',
);
await fsp.writeFile(CACHE_PATH, JSON.stringify(cache), 'utf8');
} catch {
dirty = true;
} // retry next tick
@@ -176,7 +74,7 @@ export function adsbdbProxy(options = {}) {
function lookup(kind, key) {
const store = kind === 'route' ? cache.routes : cache.aircraft;
if (fresh(store.get(key))) return Promise.resolve(store.get(key).data);
if (fresh(store[key])) return Promise.resolve(store[key].data);
const ik = `${kind}:${key}`;
if (!inflight.has(ik)) {
inflight.set(
@@ -197,19 +95,18 @@ export function adsbdbProxy(options = {}) {
);
const data =
kind === 'route' ? parseRoute(payload) : parseAircraft(payload);
// data may be null — negative cache
remember(store, key, { at: Date.now(), data });
store[key] = { at: Date.now(), data }; // data may be null — negative cache
dirty = true;
return data;
}
if (res.status === 404) {
// known-missing — cache the miss
remember(store, key, { at: Date.now(), data: null });
store[key] = { at: Date.now(), data: null }; // known-missing — cache the miss
dirty = true;
}
// other statuses: leave uncached so we retry later
return fresh(store.get(key)) ? store.get(key).data : null;
return fresh(store[key]) ? store[key].data : null;
} catch {
// network error → stale if any
return fresh(store.get(key)) ? store.get(key).data : null;
return fresh(store[key]) ? store[key].data : null; // network error → stale if any
} finally {
inflight.delete(ik);
}
@@ -221,24 +118,11 @@ export function adsbdbProxy(options = {}) {
const installMiddleware = (server) => {
server.middlewares.use('/api/adsbdb', async (req, res) => {
const send = (status, obj, headers = {}) => {
res.writeHead(status, {
'Content-Type': 'application/json',
...headers,
});
await loadOnce();
const send = (status, obj) => {
res.writeHead(status, { 'Content-Type': 'application/json' });
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]
-238
View File
@@ -1,238 +0,0 @@
// 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`);
}
});
@@ -1,120 +0,0 @@
// 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');
});
+2 -17
View File
@@ -63,25 +63,10 @@ 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, or after the refusal's own `retryAfterMs` for a
* rate limit (see _enrichCooldownMs); an answer, found or not, and a permanent
* ENRICH_RETRY_COOLDOWN_MS; 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.
@@ -148,7 +133,7 @@ export function createEnrichment({
flightState._enrichSeen.delete(job.key);
flightState._enrichRetryAfter.set(
job.key,
Date.now() + _enrichCooldownMs(error),
Date.now() + ENRICH_RETRY_COOLDOWN_MS,
);
},
)
+4 -18
View File
@@ -35,8 +35,7 @@ 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. A rate-limit refusal is not an answer: the key
* becomes askable again once the refusal's retry-after has passed.
* request per contact per tick.
* @param {object} options
* @param {{getEnrichment?: Function}|null} options.source Flights source.
* @param {() => void} options.onChange Called when metadata arrives.
@@ -54,7 +53,6 @@ export function createLocalAdsbEnrichment({
let active = 0;
let lastDispatchAt = -Infinity;
let dripTimer = null;
const retryTimers = new Set();
let lifetime = new AbortController();
function entry(icao) {
@@ -70,7 +68,7 @@ export function createLocalAdsbEnrichment({
function enqueue(key, query, apply, priority) {
if (typeof source?.getEnrichment !== 'function' || seen.has(key)) return;
seen.add(key);
const job = { key, query, apply };
const job = { query, apply };
if (priority) queue.unshift(job);
else queue.push(job);
drain();
@@ -99,10 +97,8 @@ export function createLocalAdsbEnrichment({
onChange?.();
}
})
.catch((error) => {
// Enrichment never surfaces errors; a 429 only defers the key.
if (error?.code === 'limited')
forgetLater(job.key, error.retryAfterMs);
.catch(() => {
/* enrichment never surfaces errors */
})
.finally(() => {
if (signal.aborted) return;
@@ -112,14 +108,6 @@ 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) {
@@ -172,8 +160,6 @@ export function createLocalAdsbEnrichment({
lifetime = new AbortController();
clearTimeout(dripTimer);
dripTimer = null;
for (const timer of retryTimers) clearTimeout(timer);
retryTimers.clear();
queue.length = 0;
active = 0;
},
+2 -2
View File
@@ -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, resolvePerMinuteCap } from '../server/providers/common/rate-limit.js';
import { makeRateLimiter, clientKey } 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, resolvePerMinuteCap,
makeRateLimiter, clientKey,
// terrain.js gates cross-site requests first; fixture requests carry no
// browser headers, so admit them like a loopback tool.
admitSameSiteKeyless: () => false,
+15 -3
View File
@@ -23,6 +23,7 @@ import { createCesiumImagery } from './imagery.js';
import { attributionText } from './vectorBase.js';
import { loadVectorStyle } from '../vectorBase/index.js';
import { createTerrainRetryPolicy } from '../../maps/terrainRetry.js';
import { tileFetchResource, trackTileRequests } from './terrainTiles.js';
// The base marks live outside the adapter, so code that is not Cesium's can
// mark a base; they are re-exported here for the code that still is.
@@ -68,15 +69,26 @@ async function terrainProvider(spec, { worldDataToken }) {
);
},
});
const resource = new Cesium.Resource({
const options = {
url: spec.url,
retryCallback: policy.retryCallback,
retryAttempts: policy.retryAttempts,
});
return Cesium.CesiumTerrainProvider.fromUrl(resource, {
};
if (spec.fetchTile !== undefined && typeof spec.fetchTile !== 'function')
throw new TypeError('Quantized-mesh terrain fetchTile is a function');
// With `fetchTile`, Cesium still reads `layer.json` at the url; each
// tile's bytes come from `fetchTile`.
const tiles = new WeakMap();
const resource = spec.fetchTile
? tileFetchResource(options, spec.fetchTile, (request) =>
request ? tiles.get(request) : undefined,
)
: new Cesium.Resource(options);
const provider = await Cesium.CesiumTerrainProvider.fromUrl(resource, {
requestVertexNormals: spec.requestVertexNormals ?? false,
requestWaterMask: false,
});
return spec.fetchTile ? trackTileRequests(provider, tiles) : provider;
}
throw new TypeError(`Unknown terrain kind: ${spec.kind}`);
}
+32
View File
@@ -491,6 +491,38 @@ test('terrain: quantized mesh at its url, asked again when its host is busy', as
);
});
test('terrain: quantized mesh tiles through fetchTile', async (t) => {
const { scene, port } = setup();
const made = new Cesium.EllipsoidTerrainProvider();
const own = made.requestTileGeometry;
const asked = [];
t.mock.method(Cesium.CesiumTerrainProvider, 'fromUrl', async (...args) => {
asked.push(args);
return made;
});
const fetchTile = async () => ({ missing: true });
await port.setTerrain({
kind: 'quantizedMesh',
url: 'https://terrain.example/mesh',
fetchTile,
});
assert.equal(scene.terrainProvider, made);
const [[resource]] = asked;
assert.equal(resource.url, 'https://terrain.example/mesh');
assert.ok(resource.retryAttempts > 0, 'layer.json keeps its retry policy');
assert.ok(resource instanceof Cesium.Resource);
assert.notEqual(resource.constructor, Cesium.Resource);
assert.notEqual(made.requestTileGeometry, own, 'tile requests are tracked');
await assert.rejects(
port.setTerrain({
kind: 'quantizedMesh',
url: 'https://terrain.example/mesh',
fetchTile: 'nope',
}),
/fetchTile is a function/,
);
});
test('setBase replaces the imagery and says what it drew', async () => {
const { scene, port } = setup();
const overlay = port.imagery.add({ kind: 'xyz', url: url('overlay') });
+137
View File
@@ -0,0 +1,137 @@
/**
* @module render/cesium/terrainTiles
* @description Quantized-mesh terrain tiles fetched through a terrain
* spec's `fetchTile`, the way imagery layers fetch theirs.
*
* Cesium still reads `layer.json` itself, decides which tiles a frame needs,
* schedules and cancels their requests and decodes the meshes; only the
* fetch of each tile's bytes goes through `fetchTile`. Every resource
* Cesium derives from the terrain's resource (its `layer.json`, each tile)
* is a {@link tileFetchResource}, so a tile request reaches `fetchTile`
* with the tile's URL as Cesium resolved it.
*/
import * as Cesium from 'cesium';
/** Delay before a deferred terrain tile is asked for again. */
export const TERRAIN_RETRY_DELAY_MS = 250;
/** A tile `fetchTile` says is not there; Cesium draws the parent's instead. */
export class MissingTerrainTile extends Error {
constructor() {
super('Terrain tile is missing');
this.name = 'MissingTerrainTile';
}
}
const wait = (ms, signal) =>
new Promise((resolve, reject) => {
const timer = setTimeout(done, ms);
function done() {
signal.removeEventListener('abort', aborted);
resolve();
}
function aborted() {
clearTimeout(timer);
reject(signal.reason);
}
signal.addEventListener('abort', aborted, { once: true });
});
/** Whether a resource's template values name one tile. */
const isTile = (values) =>
Number.isInteger(values?.x) &&
Number.isInteger(values?.y) &&
Number.isInteger(values?.z);
/**
* A Cesium `Resource` whose tile fetches go through `fetchTile`.
*
* `tileOf` gives the tile, in the terrain's own tiling scheme (rows from
* the north, as `requestTileGeometry` counts them), that a Cesium request
* is for; without one it is read from the resolved template values.
* @param {object} options Cesium `Resource` options.
* @param {(request: {tile: import('../contract/globe').TileRequest,
* url: string, signal: AbortSignal})
* => Promise<import('../contract/globe').TileFetch>} fetchTile
* @param {(request: object|undefined) => import('../contract/globe').TileRequest|undefined} tileOf
* @param {{retryDelayMs?: number}} [timing]
* @returns {object} A Cesium `Resource`.
*/
export function tileFetchResource(options, fetchTile, tileOf, timing = {}) {
const retryDelayMs = timing.retryDelayMs ?? TERRAIN_RETRY_DELAY_MS;
class TileFetchResource extends Cesium.Resource {
/**
* Clones stay of this kind, so derived tile resources keep the hook.
* `clone(result)` copies every field onto `result`, its URL included.
*/
clone(result) {
return super.clone(
result ?? new TileFetchResource({ url: this.url, parseUrl: false }),
);
}
fetchArrayBuffer() {
const values = this.templateValues;
if (!isTile(values)) return super.fetchArrayBuffer();
const request = this.request;
const url = this.url;
const tile = tileOf(request) ?? {
x: values.x,
y: values.y,
level: values.z,
};
if (
request.state === Cesium.RequestState.ISSUED ||
request.state === Cesium.RequestState.ACTIVE
)
throw new Cesium.RuntimeError('The Resource is already being fetched.');
const controller = new AbortController();
request.url = url;
request.state = Cesium.RequestState.UNISSUED;
request.deferred = undefined;
// Cesium cancels a request whose tile is no longer wanted.
request.cancelFunction = () => controller.abort();
request.requestFunction = async () => {
for (;;) {
const answer = await fetchTile({
tile: { ...tile },
url,
signal: controller.signal,
});
controller.signal.throwIfAborted();
if (answer?.defer) {
await wait(retryDelayMs, controller.signal);
continue;
}
if (!answer || answer.missing) throw new MissingTerrainTile();
return answer.bytes;
}
};
const promise = Cesium.RequestScheduler.request(request);
if (!promise) return undefined;
return promise.finally(() => {
request.cancelFunction = undefined;
});
}
}
return new TileFetchResource(options);
}
/**
* A terrain provider whose tile requests tell `tileFetchResource` which
* tile each is for. Requests Cesium makes without a `Request` are given one.
* @param {object} provider Cesium `CesiumTerrainProvider`.
* @param {WeakMap<object, import('../contract/globe').TileRequest>} tiles
* @returns {object} The same provider.
*/
export function trackTileRequests(provider, tiles) {
const own = provider.requestTileGeometry.bind(provider);
provider.requestTileGeometry = (x, y, level, request) => {
const asked = request ?? new Cesium.Request({ throttle: false });
tiles.set(asked, { x, y, level });
return own(x, y, level, asked);
};
return provider;
}
+171
View File
@@ -0,0 +1,171 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import * as Cesium from 'cesium';
import {
MissingTerrainTile,
tileFetchResource,
trackTileRequests,
} from './terrainTiles.js';
const ROOT = 'https://terrain.invalid/mesh/';
const LAYER = JSON.stringify({
tilejson: '2.1.0',
format: 'quantized-mesh-1.0',
version: '1.0.0',
scheme: 'tms',
tiles: ['{z}/{x}/{y}.terrain?v={version}'],
projection: 'EPSG:4326',
bounds: [-180, -90, 180, 90],
minzoom: 0,
maxzoom: 2,
available: [
[{ startX: 0, startY: 0, endX: 1, endY: 0 }],
[{ startX: 0, startY: 0, endX: 3, endY: 1 }],
[{ startX: 0, startY: 0, endX: 7, endY: 3 }],
],
});
/** One triangle over the tile: the smallest mesh Cesium decodes. */
function meshBytes() {
const view = new DataView(new ArrayBuffer(160));
let at = 88; // centre, heights, bounding sphere, horizon point: all zero
view.setFloat64(24 + 8 + 24, 1, true); // bounding sphere radius
const u32 = (v) => (view.setUint32(at, v, true), (at += 4));
const u16 = (v) => (view.setUint16(at, v, true), (at += 2));
u32(3);
// Zig-zag deltas of u (0, 32767, 0), v (0, 0, 32767) and h (0, 0, 0).
[0, 65534, 65533, 0, 0, 65534, 0, 0, 0].forEach(u16);
u32(1);
[0, 0, 0].forEach(u16); // high-water-mark indices 0, 1, 2
(u32(2), u16(0), u16(2)); // west
(u32(2), u16(0), u16(1)); // south
(u32(1), u16(1)); // east
(u32(1), u16(2)); // north
return view.buffer.slice(0, at);
}
/** Answers `layer.json` the way a host would; tiles never reach the network. */
function serveLayer(t) {
const fetched = [];
t.mock.method(
Cesium.Resource._Implementations,
'loadWithXhr',
(url, responseType, method, data, headers, deferred) => {
fetched.push(url);
if (url.startsWith(`${ROOT}layer.json`)) deferred.resolve(LAYER);
else deferred.reject(new Error(`unexpected fetch ${url}`));
},
);
return fetched;
}
async function terrain(fetchTile, timing) {
const tiles = new WeakMap();
const resource = tileFetchResource(
{ url: ROOT },
fetchTile,
(request) => (request ? tiles.get(request) : undefined),
timing,
);
const provider = await Cesium.CesiumTerrainProvider.fromUrl(resource, {
requestWaterMask: false,
});
return trackTileRequests(provider, tiles);
}
test('terrain fetchTile: tiles come from fetchTile, layer.json from the url', async (t) => {
const fetched = serveLayer(t);
const asked = [];
const provider = await terrain(async (request) => {
asked.push(request);
return { bytes: meshBytes() };
});
const data = await provider.requestTileGeometry(
1,
0,
1,
new Cesium.Request(),
);
assert.ok(data instanceof Cesium.QuantizedMeshTerrainData);
assert.deepEqual(
fetched.map((u) => new URL(u).pathname),
['/mesh/layer.json'],
);
assert.equal(asked.length, 1);
// Rows from the north for the tile; the URL is Cesium's, rows from the
// south as the layer's tms scheme counts them.
assert.deepEqual(asked[0].tile, { x: 1, y: 0, level: 1 });
assert.equal(asked[0].url, `${ROOT}1/1/1.terrain?v=1.0.0`);
assert.ok(asked[0].signal instanceof AbortSignal);
});
test('terrain fetchTile: a request Cesium makes without a Request still names its tile', async (t) => {
serveLayer(t);
const asked = [];
const provider = await terrain(async (request) => {
asked.push(request.tile);
return { bytes: meshBytes() };
});
await provider.requestTileGeometry(3, 1, 2);
assert.deepEqual(asked, [{ x: 3, y: 1, level: 2 }]);
});
test('terrain fetchTile: a missing tile fails, so the parent is drawn there', async (t) => {
serveLayer(t);
const provider = await terrain(async () => ({ missing: true }));
await assert.rejects(
provider.requestTileGeometry(0, 0, 0, new Cesium.Request()),
MissingTerrainTile,
);
});
test('terrain fetchTile: a deferred tile is asked for again', async (t) => {
serveLayer(t);
let calls = 0;
const provider = await terrain(
async () => (++calls < 3 ? { defer: true } : { bytes: meshBytes() }),
{ retryDelayMs: 1 },
);
const data = await provider.requestTileGeometry(
0,
0,
0,
new Cesium.Request(),
);
assert.ok(data instanceof Cesium.QuantizedMeshTerrainData);
assert.equal(calls, 3);
});
test('terrain fetchTile: cancelling the request aborts the fetch', async (t) => {
serveLayer(t);
let signal;
const provider = await terrain(
(request) =>
new Promise((resolve, reject) => {
signal = request.signal;
signal.addEventListener('abort', () => reject(signal.reason));
}),
);
const request = new Cesium.Request();
const pending = provider.requestTileGeometry(0, 0, 0, request);
pending.catch(() => {});
await new Promise((resolve) => setImmediate(resolve));
assert.equal(signal.aborted, false);
request.cancel();
// Cesium's scheduler cancels on its next update.
Cesium.RequestScheduler.update();
assert.equal(signal.aborted, true);
});
test('terrain fetchTile: resources that are not tiles fetch as before', async (t) => {
const fetched = serveLayer(t);
const resource = tileFetchResource(
{ url: ROOT },
async () => assert.fail('not a tile'),
() => undefined,
);
const derived = resource.getDerivedResource({ url: 'layer.json' });
assert.equal(derived.constructor, resource.constructor);
assert.equal(await derived.fetchArrayBuffer(), LAYER);
assert.equal(fetched.length, 1);
});
+18 -1
View File
@@ -40,7 +40,24 @@ export type TerrainSpec = (
* Quantized-mesh terrain (Cesium's tile format) in the folder `url`,
* holding `layer.json` and its tiles; heights above the ellipsoid.
*/
| { kind: 'quantizedMesh'; url: string; requestVertexNormals?: boolean }
| {
kind: 'quantizedMesh';
url: string;
requestVertexNormals?: boolean;
/**
* Fetches a tile in place of the renderer, as imagery's `fetchTile`
* does, with the tile's URL as the renderer resolved it (`layer.json`
* is still read from `url`). `tile` is in the terrain's tiling scheme,
* rows counted from the north; `bytes` are the tile uncompressed.
* `missing` draws the parent tile's terrain there; `defer` asks
* again shortly. `signal` aborts when the tile is no longer wanted.
*/
fetchTile?: (request: {
tile: TileRequest;
url: string;
signal: AbortSignal;
}) => Promise<TileFetch>;
}
) & {
/** Vertical exaggeration of the drawn terrain; default 1. */
exaggeration?: number;