mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-23 03:32:19 +00:00
Compare commits
15
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7ba53f6d0e | ||
|
|
2eef8cd902 | ||
|
|
a01eaff89e | ||
|
|
d8a8f1b917 | ||
|
|
678a816e65 | ||
|
|
bfcf12af49 | ||
|
|
a073e6e658 | ||
|
|
f2e8e63c48 | ||
|
|
5668c0c08b | ||
|
|
2e2cae4701 | ||
|
|
d380977928 | ||
|
|
9bb557bc2a | ||
|
|
0c1b017699 | ||
|
|
22804a46da | ||
|
|
65018015a0 |
No files matched your search
@@ -1,4 +0,0 @@
|
||||
- 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).
|
||||
@@ -0,0 +1,11 @@
|
||||
- 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) 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
|
||||
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).
|
||||
@@ -9011,6 +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 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.
|
||||
|
||||
@@ -9924,12 +9925,7 @@ 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. 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`).
|
||||
capability keeps the ellipsoid.
|
||||
|
||||
A viewer with no renderer bound gets the Cesium engine
|
||||
(`src/render/cesium/mapEngine.js`), with the other unbound ports, from the
|
||||
|
||||
@@ -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`, imagery's or terrain's (the stub fetches nothing).
|
||||
video) or `fetchTile` (the stub fetches nothing).
|
||||
@@ -78,8 +78,6 @@
|
||||
"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",
|
||||
@@ -1705,5 +1703,6 @@
|
||||
"src/ui/livePanel.test.mjs",
|
||||
"src/ui/stationPanel.test.mjs",
|
||||
"src/ui/styles/live.css",
|
||||
"src/ui/styles/station.css"
|
||||
"src/ui/styles/station.css",
|
||||
"src/openSkyTrackGovernor.test.mjs"
|
||||
]
|
||||
@@ -392,6 +392,8 @@
|
||||
"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",
|
||||
@@ -1387,7 +1389,6 @@
|
||||
"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",
|
||||
@@ -2435,7 +2436,6 @@
|
||||
"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,7 +2534,6 @@
|
||||
"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",
|
||||
@@ -3224,7 +3223,6 @@
|
||||
"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",
|
||||
@@ -3390,7 +3388,6 @@
|
||||
"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",
|
||||
@@ -3972,7 +3969,6 @@
|
||||
"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",
|
||||
@@ -4286,7 +4282,6 @@
|
||||
"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",
|
||||
@@ -6258,7 +6253,6 @@
|
||||
"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",
|
||||
|
||||
@@ -43,11 +43,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 =
|
||||
|
||||
@@ -1,12 +1,19 @@
|
||||
import { getOpenSkyToken } 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.
|
||||
* 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. 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.
|
||||
@@ -15,9 +22,52 @@ 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 layer), and re-selecting the
|
||||
* 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.
|
||||
*/
|
||||
const TRACK_RATE_PER_MIN = 30;
|
||||
const TRACK_RATE_WINDOW_MS = 60_000;
|
||||
const allowOpenSky = makeRateLimiter({
|
||||
windowMs: TRACK_RATE_WINDOW_MS,
|
||||
max: TRACK_RATE_PER_MIN,
|
||||
globalMax: TRACK_RATE_PER_MIN * 3,
|
||||
});
|
||||
/**
|
||||
* `/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();
|
||||
|
||||
/** 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) {
|
||||
@@ -26,19 +76,63 @@ export function trackBackfillProxies() {
|
||||
}
|
||||
}
|
||||
|
||||
async function proxyJson(res, key, upstreamUrl, headers = {}) {
|
||||
/**
|
||||
* @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 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, admit } = {},
|
||||
) {
|
||||
const blockedMs = governor?.remainingMs() ?? 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/flights` does:
|
||||
// a stale trail beats no trail, and replaying a cached body spends no
|
||||
// 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');
|
||||
res.end(cached.body);
|
||||
return;
|
||||
}
|
||||
if (blockedMs > 0) {
|
||||
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) {
|
||||
// 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,
|
||||
@@ -78,12 +172,20 @@ export function trackBackfillProxies() {
|
||||
);
|
||||
return;
|
||||
}
|
||||
const token = await getOpenSkyToken();
|
||||
await proxyJson(
|
||||
res,
|
||||
`osky:${icao24}`,
|
||||
`https://opensky-network.org/api/tracks/all?icao24=${icao24}&time=0`,
|
||||
token ? { Authorization: `Bearer ${token}` } : {},
|
||||
{
|
||||
// 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;
|
||||
|
||||
@@ -0,0 +1,357 @@
|
||||
// OPENSKY TRACK BACKFILL — the credit budget the per-icao cache does not guard.
|
||||
//
|
||||
// `/api/flights/track` spends 4 OpenSky credits per call from the `/tracks/*`
|
||||
// bucket. OpenSky keeps three independent daily buckets (`/states/*`,
|
||||
// `/tracks/*`, `/flights/*`), so this route neither spends nor is blocked by
|
||||
// the `/states/all` budget `/api/flights` governs. Its 60s per-icao cache
|
||||
// bounds MEMORY, not spend: `icao24` is six hex digits, so a caller that varies
|
||||
// it walks past the cache into a live, credit-consuming call every time.
|
||||
//
|
||||
// These cases drive the real exported route handlers. No network: `fetch` is
|
||||
// stubbed per test and restored afterwards, so a case that reaches upstream
|
||||
// fails loudly rather than making a request.
|
||||
//
|
||||
// NOTE: the `/states/all` cooldown is module-scoped state in `opensky.js` and,
|
||||
// once set, stays set for the life of the process (bounded 30s…30min). The case
|
||||
// that arms it therefore runs LAST. The tracks cooldown lives in each
|
||||
// `trackBackfillProxies()` instance, so every test gets a clear one.
|
||||
//
|
||||
// Run with: npm test
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { trackBackfillProxies } from '../server/providers/aircraft/tracks.js';
|
||||
import { openSkyProxy } from '../server/providers/aircraft/opensky.js';
|
||||
|
||||
/** Collect a plugin's routes into a path → handler map. */
|
||||
function install(plugin) {
|
||||
const routes = new Map();
|
||||
const server = {
|
||||
middlewares: {
|
||||
use(path, handler) {
|
||||
routes.set(path, handler);
|
||||
},
|
||||
},
|
||||
};
|
||||
plugin.configureServer(server);
|
||||
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,
|
||||
setHeader(name, value) {
|
||||
headers.set(String(name).toLowerCase(), String(value));
|
||||
},
|
||||
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 one test, restoring it afterwards. */
|
||||
function stubFetch(t, impl) {
|
||||
const original = globalThis.fetch;
|
||||
globalThis.fetch = impl;
|
||||
t.after(() => {
|
||||
globalThis.fetch = original;
|
||||
});
|
||||
}
|
||||
|
||||
/** An OpenSky /tracks/all answer, shaped like the real one. */
|
||||
const trackOk = () =>
|
||||
new Response(JSON.stringify({ path: [] }), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
|
||||
test('a caller cycling icao24 cannot walk past the per-icao cache unthrottled', async (t) => {
|
||||
let upstreamCalls = 0;
|
||||
stubFetch(t, async () => {
|
||||
upstreamCalls += 1;
|
||||
return trackOk();
|
||||
});
|
||||
const track = install(trackBackfillProxies()).get('/api/flights/track');
|
||||
|
||||
const allowed = [];
|
||||
for (let i = 0; i < 30; i += 1) {
|
||||
// A DIFFERENT icao24 every time: each one is a fresh cache key, which is
|
||||
// exactly the path the 60s cache cannot see.
|
||||
const icao24 = (0x400000 + i).toString(16).padStart(6, '0');
|
||||
allowed.push(await request(track, { url: `/?icao24=${icao24}` }));
|
||||
}
|
||||
assert.equal(
|
||||
allowed.filter((r) => r.statusCode === 429).length,
|
||||
0,
|
||||
'the first 30 distinct lookups in a minute are ordinary use',
|
||||
);
|
||||
|
||||
const refused = await request(track, { url: '/?icao24=4affff' });
|
||||
assert.equal(refused.statusCode, 429, 'the 31st distinct lookup is refused');
|
||||
assert.deepEqual(refused.body, { error: 'Rate limit exceeded' });
|
||||
assert.equal(
|
||||
refused.headers['retry-after'],
|
||||
'60',
|
||||
'a refusal names the limiter window, not a shorter guess',
|
||||
);
|
||||
assert.equal(
|
||||
upstreamCalls,
|
||||
30,
|
||||
'the refused request never reached OpenSky — the point is the credits',
|
||||
);
|
||||
});
|
||||
|
||||
test('each client gets its own quota rather than sharing one bucket', async (t) => {
|
||||
stubFetch(t, async () => trackOk());
|
||||
const track = install(trackBackfillProxies()).get('/api/flights/track');
|
||||
|
||||
for (let i = 0; i < 30; i += 1)
|
||||
await request(track, {
|
||||
url: `/?icao24=${(0x500000 + i).toString(16)}`,
|
||||
remoteAddress: '198.51.100.7',
|
||||
});
|
||||
const exhausted = await request(track, {
|
||||
url: '/?icao24=5affff',
|
||||
remoteAddress: '198.51.100.7',
|
||||
});
|
||||
assert.equal(exhausted.statusCode, 429);
|
||||
|
||||
const neighbour = await request(track, {
|
||||
url: '/?icao24=5abbbb',
|
||||
remoteAddress: '198.51.100.8',
|
||||
});
|
||||
assert.notEqual(
|
||||
neighbour.statusCode,
|
||||
429,
|
||||
'one noisy host must not take the layer away from everyone else',
|
||||
);
|
||||
});
|
||||
|
||||
test('the retired military route is not metered, so the OpenSky limiter never reaches it', async (t) => {
|
||||
let militaryUpstreamCalls = 0;
|
||||
stubFetch(t, async (url) => {
|
||||
if (String(url).includes('/tracks/all')) return trackOk();
|
||||
militaryUpstreamCalls += 1;
|
||||
return new Response('{"trace":[]}', { status: 200 });
|
||||
});
|
||||
const routes = install(trackBackfillProxies());
|
||||
const track = routes.get('/api/flights/track');
|
||||
const trace = routes.get('/api/military/track');
|
||||
|
||||
for (let i = 0; i < 30; i += 1)
|
||||
await request(track, { url: `/?icao24=${(0x610000 + i).toString(16)}` });
|
||||
assert.equal(
|
||||
(await request(track, { url: '/?icao24=61ffff' })).statusCode,
|
||||
429,
|
||||
);
|
||||
// It answers a fixed refusal without any upstream call, so a limiter would
|
||||
// only turn that refusal into a different one.
|
||||
for (let i = 0; i < 31; i += 1) {
|
||||
const military = await request(trace, {
|
||||
url: `/?hex=${(0x620000 + i).toString(16)}`,
|
||||
});
|
||||
assert.equal(military.statusCode, 503);
|
||||
}
|
||||
assert.equal(militaryUpstreamCalls, 0, 'the refusal makes no upstream call');
|
||||
});
|
||||
|
||||
test('a 429 from /tracks stands every other icao24 down until it clears', 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');
|
||||
|
||||
const first = await request(track, { url: '/?icao24=71a001' });
|
||||
assert.equal(first.statusCode, 429);
|
||||
assert.equal(upstreamCalls, 1);
|
||||
|
||||
// A DIFFERENT key: the per-icao cache cannot see it, only the cooldown can.
|
||||
const second = await request(track, { url: '/?icao24=71a002' });
|
||||
assert.equal(second.statusCode, 429, 'refused locally');
|
||||
assert.equal(
|
||||
upstreamCalls,
|
||||
1,
|
||||
'the /tracks bucket is empty, so no further credits are asked for',
|
||||
);
|
||||
const retryAfter = Number(second.headers['retry-after']);
|
||||
assert.ok(
|
||||
retryAfter > 60 && retryAfter <= 120,
|
||||
`the refusal carries OpenSky's remaining cooldown (got ${retryAfter})`,
|
||||
);
|
||||
});
|
||||
|
||||
test('a cached track is still served while /tracks is cooling', async (t) => {
|
||||
let cooling = false;
|
||||
stubFetch(t, async () =>
|
||||
cooling
|
||||
? new Response('{}', {
|
||||
status: 429,
|
||||
headers: { 'x-rate-limit-retry-after-seconds': '120' },
|
||||
})
|
||||
: trackOk(),
|
||||
);
|
||||
const track = install(trackBackfillProxies()).get('/api/flights/track');
|
||||
|
||||
assert.equal(
|
||||
(await request(track, { url: '/?icao24=72b001' })).statusCode,
|
||||
200,
|
||||
);
|
||||
cooling = true;
|
||||
assert.equal(
|
||||
(await request(track, { url: '/?icao24=72b002' })).statusCode,
|
||||
429,
|
||||
);
|
||||
const replay = await request(track, { url: '/?icao24=72b001' });
|
||||
assert.equal(
|
||||
replay.statusCode,
|
||||
200,
|
||||
'replaying a fetched body costs nothing',
|
||||
);
|
||||
});
|
||||
|
||||
test('a malformed icao24 is still rejected before any upstream call', async (t) => {
|
||||
let upstreamCalls = 0;
|
||||
stubFetch(t, async () => {
|
||||
upstreamCalls += 1;
|
||||
return trackOk();
|
||||
});
|
||||
const track = install(trackBackfillProxies()).get('/api/flights/track');
|
||||
const bad = await request(track, { url: '/?icao24=nothex' });
|
||||
assert.equal(bad.statusCode, 400);
|
||||
assert.equal(upstreamCalls, 0);
|
||||
});
|
||||
|
||||
// --- 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) => {
|
||||
if (String(url).includes('states/all')) {
|
||||
return new Response('{}', {
|
||||
status: 429,
|
||||
headers: { 'x-rate-limit-retry-after-seconds': '120' },
|
||||
});
|
||||
}
|
||||
trackUpstreamCalls += 1;
|
||||
return trackOk();
|
||||
});
|
||||
|
||||
const states = install(openSkyProxy()).get('/api/flights');
|
||||
await request(states, { url: '/' });
|
||||
|
||||
const track = install(trackBackfillProxies()).get('/api/flights/track');
|
||||
const backfill = await request(track, { url: '/?icao24=7a1b2c' });
|
||||
assert.equal(
|
||||
backfill.statusCode,
|
||||
200,
|
||||
'the /tracks bucket still has credits, so the trail is fetched',
|
||||
);
|
||||
assert.equal(trackUpstreamCalls, 1);
|
||||
});
|
||||
@@ -23,7 +23,6 @@ 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.
|
||||
@@ -69,26 +68,15 @@ async function terrainProvider(spec, { worldDataToken }) {
|
||||
);
|
||||
},
|
||||
});
|
||||
const options = {
|
||||
const resource = new Cesium.Resource({
|
||||
url: spec.url,
|
||||
retryCallback: policy.retryCallback,
|
||||
retryAttempts: policy.retryAttempts,
|
||||
};
|
||||
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, {
|
||||
});
|
||||
return 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}`);
|
||||
}
|
||||
|
||||
@@ -491,38 +491,6 @@ 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') });
|
||||
|
||||
@@ -1,137 +0,0 @@
|
||||
/**
|
||||
* @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;
|
||||
}
|
||||
@@ -1,171 +0,0 @@
|
||||
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);
|
||||
});
|
||||
Vendored
+1
-18
@@ -40,24 +40,7 @@ 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;
|
||||
/**
|
||||
* 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>;
|
||||
}
|
||||
| { kind: 'quantizedMesh'; url: string; requestVertexNormals?: boolean }
|
||||
) & {
|
||||
/** Vertical exaggeration of the drawn terrain; default 1. */
|
||||
exaggeration?: number;
|
||||
|
||||
Reference in new issue
Block a user