Files
gods-eye-view/src/layers/flights/enrichment.js
T
Sameh Khamis f2537743ab fix(flights): class an aircraft by its feed's type from the first fix
A civil aircraft was drawn as an airliner until its type lookup answered,
even when its feed already named the type: a helicopter showed the
airliner icon and model for as long as the lookup took.

- Flights classes every contact, and picks its model, by the feed's own
  ICAO type designator from the first fix. A looked-up type replaces it
  once the lookup answers and outranks the feed's on every later poll;
  the lookup still runs and fills the type name and registration.
- A surface emitter category still keeps only a ground type (ZVEH, GRND)
  from the feed.
- State vectors have no type field, so an /api/flights answer may send
  `typeByIcao` beside them, by ICAO address, as `emergencyByIcao` is sent.
  The regional adsb.lol fallback now sends it from each row's `t`.
2026-11-17 17:37:48 -08:00

343 lines
13 KiB
JavaScript

import { classifyAircraft } from '../../data/aircraftClass.js';
import { findCamera } from '../../render/rendererOf.js';
import { frustumPlanes, sphereOutside } from '../../geo/frustum.js';
import { horizonFrom } from '../../geo/horizon.js';
import { distanceSquared, vec } from '../../geo/vector.js';
import { parsePlanespottersPhoto } from '../../data/planespottersPhoto.js';
import {
ENRICH_MAX_INFLIGHT,
ENRICH_DISPATCH_GAP_MS,
ENRICH_AMBIENT_BUDGET_CEIL,
ENRICH_AMBIENT_REFILL_TOKENS,
ENRICH_AMBIENT_REFILL_WINDOW_MS,
ENRICH_AMBIENT_PER_SWEEP,
ENRICH_RETRY_COOLDOWN_MS,
} from './policy.js';
/** A contact counts as on screen while a sphere this big around it is (m). */
const AMBIENT_CULL_RADIUS_M = 1;
export function createEnrichment({
flightState,
services,
parts,
layer,
resolveAsset,
}) {
const { isMilitaryIcao } = services.militaryRegistry;
const { isTr3b } = services.aircraftPresentation;
/**
* Whether `key` is answered, queued, or cooling down after a failure. A
* key past its cool-down is released here so it can be asked again.
* @param {string} key Lookup key.
* @returns {boolean}
*/
function _enrichHeld(key) {
if (flightState._enrichSeen.has(key)) return true;
const retryAfter = flightState._enrichRetryAfter.get(key);
if (retryAfter === undefined) return false;
if (Date.now() < retryAfter) return true;
flightState._enrichRetryAfter.delete(key);
return false;
}
/**
* Whether a source failure is permanent: an unsupported lookup, or an HTTP
* 4xx other than 401/403 (an authorization refusal that may clear), 408
* (timeout) and 429 (rate limited). Anything else, including an error without a
* status, is temporary.
* @param {*} error The rejection, as `LiveSourceError` / `httpError` carry it.
* @returns {boolean}
*/
function _enrichFailureIsFinal(error) {
if (error?.code === 'unsupported') return true;
const status = Number(error?.status);
return (
Number.isInteger(status) &&
status >= 400 &&
status < 500 &&
status !== 401 &&
status !== 403 &&
status !== 408 &&
status !== 429
);
}
/**
* 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; 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.
* @param {function(object):void} onData Receives a `found` answer.
* @param {boolean} [priority] Front of the queue.
* @param {function(*):?object} [read] Reads the source's answer first, for
* a lookup whose answer may arrive in more than one shape.
*/
function _enqueueEnrich(key, query, onData, priority = false, read = null) {
if (flightState.lifetime.signal.aborted) return;
if (_enrichHeld(key)) return;
flightState._enrichSeen.add(key);
const job = { key, query, onData, read };
// Priority (tracked / model-eligible) goes to the FRONT so a deep ambient
// backlog can never delay the plane the user just clicked or zoomed into.
if (priority) flightState._enrichQueue.unshift(job);
else flightState._enrichQueue.push(job);
_drainEnrich();
}
function _drainEnrich() {
if (flightState.lifetime.signal.aborted) return;
while (
flightState._enrichActive < ENRICH_MAX_INFLIGHT &&
flightState._enrichQueue.length
) {
// Drip: at most one dispatch per ENRICH_DISPATCH_GAP_MS. When the gap
// hasn't elapsed yet, park a single wake-up timer and stop — completions
// and enqueues in the meantime re-enter here harmlessly.
const wait =
ENRICH_DISPATCH_GAP_MS -
(Date.now() - flightState._enrichLastDispatchMs);
if (wait > 0) {
if (!flightState._enrichDripTimer) {
flightState._enrichDripTimer = setTimeout(() => {
flightState._enrichDripTimer = null;
_drainEnrich();
}, wait);
}
return;
}
flightState._enrichLastDispatchMs = Date.now();
const job = flightState._enrichQueue.shift();
flightState._enrichActive += 1;
const lifetime = flightState.lifetime;
Promise.resolve()
.then(() => {
lifetime.signal.throwIfAborted();
return flightState.feed._source.getEnrichment?.(job.query, {
signal: lifetime.signal,
});
})
.then(
(answer) => {
const data = job.read ? job.read(answer) : answer;
if (!lifetime.signal.aborted && data && data.found)
job.onData(data);
},
(error) => {
// The source failed: release the key after a cool-down. A layer
// teardown is not a failure and schedules nothing, and a
// permanent refusal is as final as an answer.
if (lifetime.signal.aborted || _enrichFailureIsFinal(error)) return;
flightState._enrichSeen.delete(job.key);
flightState._enrichRetryAfter.set(
job.key,
Date.now() + ENRICH_RETRY_COOLDOWN_MS,
);
},
)
.catch(() => {
/* enrichment never surfaces errors */
})
.finally(() => {
if (lifetime.signal.aborted) return;
flightState._enrichActive -= 1;
_drainEnrich();
});
}
}
function _requestTypeEnrichment(icao24, priority = false) {
if (!/^[0-9a-f]{6}$/i.test(icao24)) return;
_enqueueEnrich(
`t:${icao24}`,
{ kind: 'type', id: icao24.toLowerCase() },
(data) => {
const meta = flightState.records.data.get(icao24);
if (!meta) return; // evicted while the lookup was in flight
// A looked-up type outranks the feed's own from now on.
if (data.typeCode) {
meta.typeCode = data.typeCode;
meta.typeLookedUp = true;
}
meta.typeName = data.typeName || meta.typeName;
meta.registration = data.registration || meta.registration;
if (meta.typeCode) {
const klass = classifyAircraft({
typeCode: meta.typeCode,
category: meta.category,
});
if (klass !== meta.klass) {
meta.klass = klass;
parts.icons._applyIconPresentation(icao24);
}
// The type picks the fleet model and its length — resync the live
// model, any in-flight load, and the tracked standalone model.
parts.rendering._syncModelToClass(icao24);
}
if (icao24 === flightState._trackedIcao && flightState._trackedEntity)
parts.tracking._updateTrackedLabelModel(icao24);
},
priority,
);
}
function _requestRouteEnrichment(icao24) {
const cs = String(flightState.records.data.get(icao24)?.callsign || '')
.trim()
.toUpperCase();
if (!/^[A-Z]{3}\d/.test(cs)) return; // airline-style callsigns only (LLL + digit); GA tails won't resolve
_enqueueEnrich(
`r:${cs}`,
{ kind: 'route', id: cs },
(data) => {
const meta = flightState.records.data.get(icao24);
if (!meta) return;
// A late answer for a callsign the plane no longer flies is dropped.
if (
String(meta.callsign || '')
.trim()
.toUpperCase() !== cs
)
return;
meta.routeCallsign = cs;
meta.airline = data.airline || meta.airline;
if (data.origin && data.destination)
meta.route = { origin: data.origin, destination: data.destination };
if (icao24 === flightState._trackedIcao && flightState._trackedEntity)
parts.tracking._updateTrackedLabelModel(icao24);
},
true,
); // route lookups only fire for the TRACKED plane — front of the queue
}
/** The tracked plane's photo from Planespotters, asked once per hex at the
* front of the queue like its route. A miss is final; a temporary failure
* is asked again after the cool-down. A military aircraft or a converted
* TR-3B is never looked up. The answer is read with
* `parsePlanespottersPhoto` whatever shape the source returns (the upstream
* answer, a server's cached shape, or an already-read photo), so only a
* checked photo is ever stored. */
function _requestPhotoEnrichment(icao24) {
if (!/^[0-9a-f]{6}$/i.test(icao24)) return;
const id = icao24.toLowerCase();
if (isMilitaryIcao(id) || isTr3b(id)) return;
_enqueueEnrich(
`p:${id}`,
{ kind: 'photo', id },
(data) => {
const meta = flightState.records.data.get(id);
if (!meta) return; // evicted while the lookup was in flight
const { src, width, height, photographer, link } = data;
meta.photo = { src, width, height, photographer, link };
},
true,
parsePlanespottersPhoto,
);
}
/** QA seam: headless harnesses (scripts/qa-enrich-ambient.mjs) shrink the
* bucket knobs via window.__GEV_ENRICH_AMBIENT_QA = {ceil, refillTokens,
* windowMs} — they cannot wait out a real 5-minute window. Read lazily each
* refill so a pre-boot override (or a mid-run windowMs swap) applies.
* Production never sets this; the constants above are the defaults. */
function _ambientBudgetKnobs() {
const o =
(typeof window !== 'undefined' && window.__GEV_ENRICH_AMBIENT_QA) || null;
return {
ceil:
Number.isFinite(o?.ceil) && o.ceil > 0
? o.ceil
: ENRICH_AMBIENT_BUDGET_CEIL,
refillTokens:
Number.isFinite(o?.refillTokens) && o.refillTokens > 0
? o.refillTokens
: ENRICH_AMBIENT_REFILL_TOKENS,
windowMs:
Number.isFinite(o?.windowMs) && o.windowMs > 0
? o.windowMs
: ENRICH_AMBIENT_REFILL_WINDOW_MS,
};
}
/** Advance the token bucket: add refillTokens per FULLY elapsed window since
* the anchor, clamp at the ceiling, and move the anchor forward by the whole
* windows consumed (while the bucket sits full this still advances, so idle
* time never banks more than one bucket's worth of burst). */
function _refillAmbientBudget(nowMs) {
const { ceil, refillTokens, windowMs } = _ambientBudgetKnobs();
if (!flightState._enrichAmbientRefillAnchorMs) {
flightState._enrichAmbientRefillAnchorMs = nowMs;
return;
}
const windows = Math.floor(
(nowMs - flightState._enrichAmbientRefillAnchorMs) / windowMs,
);
if (windows <= 0) return;
flightState._enrichAmbientBudget = Math.min(
ceil,
flightState._enrichAmbientBudget + windows * refillTokens,
);
flightState._enrichAmbientRefillAnchorMs += windows * windowMs;
}
function _sweepAmbientEnrichment() {
_refillAmbientBudget(Date.now());
if (
flightState._enrichAmbientBudget <= 0 ||
!flightState._viewer ||
!flightState._icons?.show
)
return;
try {
// What is on screen, from the camera's pose: past the limb or outside
// the view frustum is not looked at.
const pose = findCamera(flightState._viewer)?.pose();
if (!pose) return;
const camPos = pose.position;
const occluder = horizonFrom(camPos);
const planes = frustumPlanes(pose);
const position = vec();
const cand = [];
const icons = flightState._icons;
const t = parts.icons._displayMs();
for (const icao24 of icons.ids()) {
// Answered, queued, negative this session, or cooling down after a
// failure: never spend a token on it.
if (_enrichHeld(`t:${icao24}`)) continue;
if (!/^[0-9a-f]{6}$/i.test(icao24)) continue; // adsbdb keys are 6-char hex only
if (flightState.records.data.get(icao24)?.onGround) continue; // ground traffic never spends ambient budget (click-to-enrich still works)
if (!icons.position(icao24, t, position)) continue;
if (!occluder.isPointVisible(position)) continue; // beyond the limb
if (sphereOutside(planes, position, AMBIENT_CULL_RADIUS_M)) continue; // off-screen
cand.push([icao24, distanceSquared(camPos, position)]);
}
cand.sort((a, b) => a[1] - b[1]); // nearest first — what the user is looking at resolves first
const n = Math.min(
cand.length,
ENRICH_AMBIENT_PER_SWEEP,
flightState._enrichAmbientBudget,
);
for (let i = 0; i < n; i++) {
flightState._enrichAmbientBudget -= 1;
_requestTypeEnrichment(cand[i][0]); // non-priority: fills the back of the queue
}
} catch {
/* ambient enrichment is best-effort — never disturb the poll loop */
}
}
return {
_enqueueEnrich,
_drainEnrich,
_requestTypeEnrichment,
_requestRouteEnrichment,
_requestPhotoEnrichment,
_ambientBudgetKnobs,
_refillAmbientBudget,
_sweepAmbientEnrichment,
};
}