Files
gods-eye-view/src/data/transit.test.mjs
T
Bilawal Sidhu 76c20be277 feat(transit): live public-transit vehicles from open GTFS-Realtime feeds (#587)
Supersedes #218 by @spcpza, ported onto the current component layout with fixes from review.

Verified before merge: format, package boundaries, unit suite, build, and the browser tracking suite; a browser harness for the change where one applies; adversarial review applied.

Contributor: @spcpza. His original commit is the base of this branch, and his own re-port onto main (2026-09-15, `5b69011`) was consulted while finishing the height work. That port reads every vehicle's surface from the app's shared ground-floor system (`cachedGroundFloor` / `warmGroundFloor` / `GROUND_FLOOR_LIFT_M`) rather than sampling the scene per layer, keeps a vehicle hidden until its cell answers, warms a bounded batch per poll on a timer instead of per frame, and renders at the ellipsoid above the altitude gate. That is the sounder primitive — one floor system for the app, with the rooftop-versus-street question already settled against a datum-correct DEM prior — and this branch's height work was rebuilt on it, replacing a bespoke cell cache, ground prior and rooftop rule written here. Credit for that direction is his.

Future work (not in this PR), both written up in docs/CURRENT-STATE.md:

- Readable route names. The realtime feeds carry only `route_id`; `route_short_name` / `route_long_name` live in each operator's static GTFS `routes.txt`, and headsigns in `trips.txt`. Doing it properly wants a server-side metadata loader beside the transit proxy with fixed registered static sources, bounded indexes built once and persisted, a slow conditional refresh, and a versioned route dictionary the browser caches. Shipped here: ids are never rewritten, and a cut one carries an ellipsis instead of reading as a typo.
- Below-ground rendering. Subway vehicles are drawn on the surface directly above themselves, because the feeds carry no depth and a train nobody can see is not worth drawing; the card says so plainly. Real treatment wants OSM tunnel geometry per city and a ghosted sprite tethered to the surface. The owner recorded it and left it.

Round four and after (2026-09-15). The owner tested round three under FLIR and NVG, and then asked for the design to be taken further: elegant in performance, beautiful on camera, trails with a cache for public transport, Cesium-native, and a core other moving layers can adopt. Codex Astra reviewed the plan (it confirmed the speed fault: a glide started from the drawn position at receipt time but spanned the gap between report times, so with MBTA reporting every ~10 s against a 15 s poll every second glide ran at 1.5x; it rejected a queued-segment patch), then wrote the design, then implemented it in commit-sized passes with adversarial review between them and real-browser harness runs by the integrator.

What this PR now contains beyond the contributor's original port:

- Delayed playback in a contact-agnostic core (`src/data/contactPlayback.js`): each vehicle keeps a typed, bounded fix history and a display clock that runs at one second per second through it, a feed-derived lag behind real time, holding at its newest fix rather than extrapolating and never sprinting to catch up. Marker, course, motion word, card and trail all read the same displayed sample. The clock has an explicit time-offset and seek API so a rewind is a later feature, not a rewrite; flights and vessels are untouched.
- A selected-vehicle trail (`src/data/contactTrailRenderer.js`, `src/layers/transit/trails.js`): the retained history drawn with batched Cesium primitives, clipped at display time so the head is exactly the sprite, faded by age, in the mode colour (white under sensor presets), on the same surface path as the marker.
- Bounded proxy-side history (`server/providers/transitHistory.js`): fifteen minutes and at most 128 fixes per vehicle with hard byte ceilings, MBTA only for now (opt-in per feed), served by a small endpoint that never fetches upstream, so a selected trail survives a browser reload while the server keeps running.
- Scene work bounded to what is visible and moving, an occluder, cached DETECT candidates, holds on the render loop only while something visible moves.
- Sensor presets: white-hot haloed sprites under NVG/FLIR/noir (black-hot inverts), saturated mode colours under CRT, per-mode bracket tiers in every theme, the selected card keeping its mode colour.
- A discriminating browser harness (`scripts/qa-transit.mjs`) that samples postRender frames, reads the real card anchor, and measures fleet budgets at 800 and 3,000 vehicles.

Not built, recorded as follow-ups: curated route display names (lowest priority per the owner), fleet-wide tails, route snapping, a rewind UI, adoption of the playback core by flights and vessels.

Verified at merge (2026-09-15 morning): unit suite 3,896 passing, build clean, format and boundary gates clean, tracking regression 109/109, browser harness keyless 200 pass / 0 fail (13 sensor checks unexercised because the live view offered fewer than six isolated sprites; every judged sprite passed), keyed on Google 3D tiles 198 pass with the per-frame allocation gate as the only failure. Follow-ups recorded: the keyed build's playback sampler still allocates per frame (CPU and frame time stay within budget; the 3,000-vehicle metro view sits at a 27.6 ms frame interval against a 25 ms budget), the shared detection overlay's per-paint allocation, friendlier route names, fleet-wide tails, a rewind UI, and adopting the playback core for vessels and flights.
Co-authored-by: spcpza <[email protected]>
2026-09-15 05:18:30 -05:00

226 lines
6.8 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import transitLayer, {
TRANSIT_MODE_COLORS,
TRANSIT_POLL_MS,
TRANSIT_SELECTED_OVERLAY_SOURCE_OPTIONS,
buildTransitSelectionCopy,
createTransitSelectedOverlayEntry,
interpolatedVehiclePosition,
isStaleVehicleFix,
transitVehicleKey,
} from './transit.js';
import { TRANSIT_MODES, getTransitFeed } from './transitFeeds.js';
import { LAYER_STATE_REGISTRY } from './layerState.js';
import { SPRITE_LAYER_ORDER } from './spriteOrder.js';
test('layer module declares the manager contract', () => {
assert.equal(transitLayer.id, 'transit');
assert.equal(typeof transitLayer.name, 'string');
assert.equal(typeof transitLayer.icon, 'string');
assert.equal(transitLayer.updateInterval, TRANSIT_POLL_MS);
for (const method of [
'init',
'enable',
'disable',
'update',
'getStats',
'destroy',
]) {
assert.equal(
typeof transitLayer[method],
'function',
`${method} is implemented`,
);
}
});
test('the layer is registered for share links and sprite stacking', () => {
const entry = LAYER_STATE_REGISTRY.find((row) => row.id === 'transit');
assert.ok(entry, 'transit has a share-link token');
assert.equal(entry.disposition, 'enabled-only');
assert.equal(
LAYER_STATE_REGISTRY.filter((row) => row.token === entry.token).length,
1,
'token is unique',
);
const index = SPRITE_LAYER_ORDER.indexOf('transit');
assert.ok(
index > SPRITE_LAYER_ORDER.indexOf('bikeshare'),
'vehicles draw above bikeshare stations',
);
assert.ok(
index < SPRITE_LAYER_ORDER.indexOf('flights'),
'aircraft stay on top',
);
});
test('every transit mode has a colour and the selected card uses it as accent', () => {
for (const mode of TRANSIT_MODES) {
assert.match(
TRANSIT_MODE_COLORS[mode],
/^#[0-9a-f]{6}$/i,
`${mode} has a colour`,
);
}
const position = Cesium.Cartesian3.fromDegrees(-71.06, 42.36, 3);
const card = createTransitSelectedOverlayEntry(
'mbta:1',
position,
{ title: 'T', details: ['d'] },
'subway',
);
assert.equal(card.accent, TRANSIT_MODE_COLORS.subway);
assert.equal(card.selected, true);
assert.equal(card.protected, true);
assert.equal(card.position, position);
assert.equal(
createTransitSelectedOverlayEntry(
'',
position,
{ title: 'T', details: [] },
'bus',
),
null,
);
assert.equal(
createTransitSelectedOverlayEntry(
'k',
null,
{ title: 'T', details: [] },
'bus',
),
null,
);
assert.equal(
TRANSIT_SELECTED_OVERLAY_SOURCE_OPTIONS.moving,
true,
'the card follows a moving vehicle',
);
});
test('position queries read the published display sample', () => {
const entry = { track: {}, sample: { lat: 1, lon: 2, phase: 'playing' } };
assert.deepEqual(interpolatedVehiclePosition(entry), {
lat: 1,
lon: 2,
settled: false,
});
entry.sample.phase = 'held';
assert.equal(interpolatedVehiclePosition(entry).settled, true);
});
test('fixes older than ten minutes are stale; feeds without timestamps are trusted', () => {
const now = 1_700_000_000_000;
assert.equal(isStaleVehicleFix({ timestamp: now / 1000 - 30 }, now), false);
assert.equal(isStaleVehicleFix({ timestamp: now / 1000 - 601 }, now), true);
assert.equal(isStaleVehicleFix({ timestamp: null }, now), false);
assert.equal(isStaleVehicleFix({}, now), false);
});
test('selection copy reads like a transit card and never leaks nulls', () => {
const feed = getTransitFeed('metrotransit-msp');
const now = 1_788_936_960_000;
const full = buildTransitSelectionCopy(
feed,
{
id: '1557',
label: '1557',
routeId: '17',
lat: 44.9,
lon: -93.4,
bearing: 248,
speedMps: 11.2,
timestamp: 1_788_936_945,
stopId: '57458',
status: 'STOPPED_AT',
occupancy: 'FEW_SEATS_AVAILABLE',
timestampSource: 'vehicle',
},
'bus',
now,
);
assert.equal(full.title, '🚌 Route 17');
assert.deepEqual(full.details, [
// The mode is said in words: a glyph and a route number do not tell a
// reader whether the dot on the street is a bus or a subway train.
'Bus · Metro Transit · Minneapolis–St Paul, MN',
'Reported 15 s ago',
// The operator's speed is labelled as a report: it describes the newest
// fix, not the older segment the screen is drawing.
'reported 40 km/h · reported hdg 248°',
// The operator's claim is kept as a REPORT, not as the live state. It
// describes the moment of the report, which the display may not have
// reached yet — presenting it as "now" is what put STOPPED on a metro
// gliding across the owner's screen.
'Last report: stopped at stop 57458 · few seats available',
'Vehicle 1557',
]);
// A time the feed gave for the SNAPSHOT rather than for this vehicle is
// labelled, so the card never presents a borrowed time as the bus's own.
const borrowed = buildTransitSelectionCopy(
feed,
{
id: '9',
lat: 1,
lon: 1,
timestamp: 1_788_936_900,
timestampSource: 'header',
},
'bus',
now,
);
assert.equal(borrowed.details[1], 'Reported 60 s ago (feed time)');
// A subway says where it is drawn, because a train on a road is otherwise
// read as a bug rather than as a deliberate surface projection.
const underground = buildTransitSelectionCopy(
feed,
{
id: 'T1',
routeId: 'Blue',
lat: 44.9,
lon: -93.4,
timestamp: 1_788_936_945,
},
'subway',
now,
);
assert.deepEqual(underground.details, [
'Subway · Metro Transit · Minneapolis–St Paul, MN',
'Reported 15 s ago',
'Shown at street level · depth not in the feed',
'Vehicle T1',
]);
// No timestamp at all is aged from the fetch, never from "now".
const sparse = buildTransitSelectionCopy(
feed,
{ id: 'abc', lat: 1, lon: 1 },
'rail',
now,
now - 120_000,
);
assert.equal(sparse.title, '🚆 Vehicle abc');
assert.deepEqual(sparse.details, [
'Train · Metro Transit · Minneapolis–St Paul, MN',
'Reported 2 min ago (feed time)',
'Vehicle abc',
]);
for (const line of [...full.details, ...sparse.details])
assert.doesNotMatch(line, /null|undefined|NaN/);
assert.equal(transitVehicleKey('mbta', '17'), 'mbta:17');
});
test('the layer accepts a manager handle for out-of-tick panel repaints', () => {
assert.equal(typeof transitLayer.attachDataManager, 'function');
transitLayer.attachDataManager({ refreshLayerStats() {} });
transitLayer.attachDataManager(null);
});
test('stats before enable are an honest zero, not a fake feed state', () => {
const stats = transitLayer.getStats();
assert.equal(stats.count, 0);
assert.equal(stats.source, 'GTFS-RT');
assert.equal(stats.error, null);
});