mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-04 10:24:02 +00:00
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]>
368 lines
13 KiB
JavaScript
368 lines
13 KiB
JavaScript
import test from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
import { PbfWriter } from 'pbf';
|
|
import {
|
|
TRANSIT_BACKOFF_LADDER_MS,
|
|
TRANSIT_PROXY_STALE_MAX_MS,
|
|
TRANSIT_PROXY_TTL_MS,
|
|
TransitFeedShapeError,
|
|
buildTransitSnapshot,
|
|
isAcceptableTransitUpstreamUrl,
|
|
nextTransitBackoffMs,
|
|
repairVehicleTimestamps,
|
|
resolveTransitRoute,
|
|
transitCacheState,
|
|
transitRedirectDecision,
|
|
transitResponseHeaders,
|
|
transitUpstreamHeaders,
|
|
} from './transitProxy.js';
|
|
import { getTransitFeed } from './transitFeeds.js';
|
|
|
|
test('route resolution admits only the catalog and registered feed ids', () => {
|
|
assert.deepEqual(resolveTransitRoute('/feeds'), { route: 'feeds' });
|
|
assert.deepEqual(resolveTransitRoute('/feeds/?x=1'), { route: 'feeds' });
|
|
assert.equal(resolveTransitRoute('/vehicles/mbta')?.feed?.id, 'mbta');
|
|
assert.equal(resolveTransitRoute('/vehicles/mbta/')?.feed?.id, 'mbta');
|
|
assert.equal(resolveTransitRoute('/vehicles/mbta?trip=1')?.feed?.id, 'mbta');
|
|
assert.equal(resolveTransitRoute('/vehicles/nope'), null);
|
|
assert.equal(resolveTransitRoute('/vehicles/'), null);
|
|
assert.equal(resolveTransitRoute('/vehicles/mbta/extra'), null);
|
|
assert.equal(resolveTransitRoute('/vehicles/..%2F..%2Fetc'), null);
|
|
assert.equal(resolveTransitRoute('/vehicles/%E0%A4%A'), null); // malformed escape never throws
|
|
assert.equal(resolveTransitRoute('/'), null);
|
|
assert.equal(resolveTransitRoute(''), null);
|
|
assert.equal(resolveTransitRoute(undefined), null);
|
|
});
|
|
|
|
test('upstream headers identify the proxy and carry feed-specific identification', () => {
|
|
const plain = transitUpstreamHeaders(getTransitFeed('mbta'));
|
|
assert.match(plain['User-Agent'], /gods-eye-view-transit-proxy/);
|
|
assert.match(plain.Accept, /x-protobuf/);
|
|
const entur = transitUpstreamHeaders(getTransitFeed('entur-norway'));
|
|
assert.equal(entur['ET-Client-Name'], 'gods-eye-view-transit');
|
|
assert.ok(transitUpstreamHeaders(null)['User-Agent']);
|
|
});
|
|
|
|
test('only https upstreams are acceptable, including after a redirect', () => {
|
|
assert.equal(
|
|
isAcceptableTransitUpstreamUrl('https://cdn.mbta.com/x.pb'),
|
|
true,
|
|
);
|
|
assert.equal(
|
|
isAcceptableTransitUpstreamUrl(
|
|
'http://gtfs.ovapi.nl/nl/vehiclePositions.pb',
|
|
),
|
|
false,
|
|
);
|
|
assert.equal(isAcceptableTransitUpstreamUrl('ftp://x'), false);
|
|
assert.equal(isAcceptableTransitUpstreamUrl('not a url'), false);
|
|
});
|
|
|
|
test('snapshot shape carries provenance the layer displays', () => {
|
|
const writer = new PbfWriter();
|
|
const header = new PbfWriter();
|
|
header.writeStringField(1, '2.0');
|
|
header.writeVarintField(3, 1_700_000_000);
|
|
writer.writeBytesField(1, header.finish());
|
|
const snapshot = buildTransitSnapshot(
|
|
getTransitFeed('mbta'),
|
|
writer.finish(),
|
|
12345,
|
|
);
|
|
assert.equal(snapshot.feedId, 'mbta');
|
|
assert.equal(snapshot.name, 'MBTA');
|
|
assert.equal(snapshot.fetchedAt, 12345);
|
|
assert.equal(snapshot.feedTimestamp, 1_700_000_000);
|
|
assert.equal(snapshot.version, '2.0');
|
|
assert.equal(snapshot.count, 0);
|
|
assert.deepEqual(snapshot.vehicles, []);
|
|
});
|
|
|
|
test('cache policy: fresh within TTL, stale until the serve-stale window, expired after', () => {
|
|
const now = 1_000_000;
|
|
assert.equal(transitCacheState(null, now), 'none');
|
|
assert.equal(transitCacheState({ at: Number.NaN }, now), 'none');
|
|
assert.equal(transitCacheState({ at: now }, now), 'fresh');
|
|
assert.equal(
|
|
transitCacheState({ at: now - TRANSIT_PROXY_TTL_MS + 1 }, now),
|
|
'fresh',
|
|
);
|
|
assert.equal(
|
|
transitCacheState({ at: now - TRANSIT_PROXY_TTL_MS }, now),
|
|
'stale',
|
|
);
|
|
assert.equal(
|
|
transitCacheState({ at: now - TRANSIT_PROXY_STALE_MAX_MS + 1 }, now),
|
|
'stale',
|
|
);
|
|
assert.equal(
|
|
transitCacheState({ at: now - TRANSIT_PROXY_STALE_MAX_MS }, now),
|
|
'expired',
|
|
);
|
|
assert.equal(transitCacheState({ at: now + 5000 }, now), 'fresh'); // clock skew never expires a fresh fetch
|
|
});
|
|
|
|
test('response headers mark cache state and never let a stale-error response be cached downstream', () => {
|
|
assert.equal(
|
|
transitResponseHeaders('HIT', 'cdn.mbta.com')['X-Transit-Upstream'],
|
|
'cdn.mbta.com',
|
|
);
|
|
assert.equal(
|
|
transitResponseHeaders('HIT')['Cache-Control'],
|
|
'public, max-age=15',
|
|
);
|
|
assert.equal(
|
|
transitResponseHeaders('STALE-ERROR')['Cache-Control'],
|
|
'no-store',
|
|
);
|
|
assert.equal(transitResponseHeaders('MISS')['X-GEV-Cache'], 'MISS');
|
|
});
|
|
|
|
/** A minimal FeedMessage with the given header fields and vehicle entities. */
|
|
function encodeFeed({
|
|
incrementality = null,
|
|
timestamp = 1_700_000_000,
|
|
entities = [],
|
|
}) {
|
|
const writer = new PbfWriter();
|
|
const header = new PbfWriter();
|
|
header.writeStringField(1, '2.0');
|
|
if (incrementality !== null) header.writeVarintField(2, incrementality);
|
|
if (timestamp !== null) header.writeVarintField(3, timestamp);
|
|
writer.writeBytesField(1, header.finish());
|
|
for (const entity of entities) {
|
|
const feedEntity = new PbfWriter();
|
|
feedEntity.writeStringField(1, entity.id);
|
|
const vehicle = new PbfWriter();
|
|
const position = new PbfWriter();
|
|
position.writeFloatField(1, entity.lat);
|
|
position.writeFloatField(2, entity.lon);
|
|
vehicle.writeBytesField(2, position.finish());
|
|
if (entity.timestamp) vehicle.writeVarintField(5, entity.timestamp);
|
|
const descriptor = new PbfWriter();
|
|
descriptor.writeStringField(1, entity.vehicleId || entity.id);
|
|
vehicle.writeBytesField(8, descriptor.finish());
|
|
feedEntity.writeBytesField(4, vehicle.finish());
|
|
writer.writeBytesField(2, feedEntity.finish());
|
|
}
|
|
return writer.finish();
|
|
}
|
|
|
|
test('a redirect is judged before it is followed, not after it has been answered', () => {
|
|
const feed = { url: 'https://data.example.gov/download/feed.pb' };
|
|
// Same origin, absolute and relative, is the only case that may proceed.
|
|
assert.deepEqual(
|
|
transitRedirectDecision(
|
|
feed.url,
|
|
feed.url,
|
|
'https://data.example.gov/files/a.pb',
|
|
),
|
|
{ ok: true, url: 'https://data.example.gov/files/a.pb' },
|
|
);
|
|
assert.deepEqual(transitRedirectDecision(feed.url, feed.url, '/files/b.pb'), {
|
|
ok: true,
|
|
url: 'https://data.example.gov/files/b.pb',
|
|
});
|
|
// Another host is refused even though it is https — this is the hop that used
|
|
// to be contacted first and inspected afterwards.
|
|
const offOrigin = transitRedirectDecision(
|
|
feed.url,
|
|
feed.url,
|
|
'https://cdn.elsewhere.test/a.pb',
|
|
);
|
|
assert.equal(offOrigin.ok, false);
|
|
assert.match(offOrigin.reason, /left https:\/\/data\.example\.gov/);
|
|
// A downgrade to http, a missing Location, and a malformed target all refuse.
|
|
assert.equal(
|
|
transitRedirectDecision(feed.url, feed.url, 'http://data.example.gov/a.pb')
|
|
.ok,
|
|
false,
|
|
);
|
|
assert.equal(transitRedirectDecision(feed.url, feed.url, null).ok, false);
|
|
assert.equal(
|
|
transitRedirectDecision(feed.url, feed.url, 'javascript:alert(1)').ok,
|
|
false,
|
|
);
|
|
assert.equal(
|
|
transitRedirectDecision(feed.url, feed.url, 'data:text/plain,x').ok,
|
|
false,
|
|
);
|
|
assert.equal(
|
|
transitRedirectDecision('not-a-url', 'not-a-url', '/a.pb').ok,
|
|
false,
|
|
);
|
|
// A sibling port is a different origin.
|
|
assert.equal(
|
|
transitRedirectDecision(
|
|
feed.url,
|
|
feed.url,
|
|
'https://data.example.gov:8443/a.pb',
|
|
).ok,
|
|
false,
|
|
);
|
|
});
|
|
|
|
test('failure cooldown climbs and stops climbing, and a healthy feed waits for nothing', () => {
|
|
assert.equal(nextTransitBackoffMs(0), 0);
|
|
assert.equal(nextTransitBackoffMs(-3), 0);
|
|
assert.deepEqual([1, 2, 3, 4].map(nextTransitBackoffMs), [
|
|
...TRANSIT_BACKOFF_LADDER_MS,
|
|
]);
|
|
// Past the ladder the wait stays at its last rung rather than growing forever.
|
|
assert.equal(nextTransitBackoffMs(9), TRANSIT_BACKOFF_LADDER_MS.at(-1));
|
|
assert.equal(nextTransitBackoffMs(500), TRANSIT_BACKOFF_LADDER_MS.at(-1));
|
|
});
|
|
|
|
test('a differential feed is refused rather than read as a full snapshot', () => {
|
|
const feed = getTransitFeed('mbta');
|
|
const differential = encodeFeed({
|
|
incrementality: 1,
|
|
entities: [{ id: 'v1', lat: 42.36, lon: -71.05, timestamp: 1_700_000_000 }],
|
|
});
|
|
assert.throws(
|
|
() => buildTransitSnapshot(feed, differential, 1_700_000_000_000),
|
|
(error) =>
|
|
error instanceof TransitFeedShapeError &&
|
|
error.transitReason === 'differential',
|
|
);
|
|
// The same bytes with FULL_DATASET decode normally, so the refusal is about
|
|
// the header and not about the payload.
|
|
const full = encodeFeed({
|
|
incrementality: 0,
|
|
entities: [{ id: 'v1', lat: 42.36, lon: -71.05, timestamp: 1_700_000_000 }],
|
|
});
|
|
assert.equal(buildTransitSnapshot(feed, full, 1_700_000_000_000).count, 1);
|
|
// An absent incrementality field means FULL_DATASET by the spec's default.
|
|
assert.equal(
|
|
buildTransitSnapshot(feed, encodeFeed({ entities: [] }), 1).count,
|
|
0,
|
|
);
|
|
});
|
|
|
|
test('a vehicle with no time of its own borrows the feed header time and says so', () => {
|
|
const fetchedAtS = 1_700_000_500;
|
|
const repaired = repairVehicleTimestamps(
|
|
[
|
|
{ id: 'own', timestamp: 1_700_000_400 },
|
|
{ id: 'none' },
|
|
{ id: 'zero', timestamp: 0 },
|
|
],
|
|
1_700_000_450,
|
|
fetchedAtS,
|
|
);
|
|
assert.deepEqual(
|
|
repaired.map((vehicle) => [
|
|
vehicle.id,
|
|
vehicle.timestamp,
|
|
vehicle.timestampSource,
|
|
]),
|
|
[
|
|
['own', 1_700_000_400, 'vehicle'],
|
|
['none', 1_700_000_450, 'header'],
|
|
['zero', 1_700_000_450, 'header'],
|
|
],
|
|
);
|
|
// With no header either, fetch time is used and is labelled as such — never
|
|
// presented as the vehicle's own report.
|
|
const noHeader = repairVehicleTimestamps([{ id: 'none' }], null, fetchedAtS);
|
|
assert.deepEqual(
|
|
[noHeader[0].timestamp, noHeader[0].timestampSource],
|
|
[fetchedAtS, 'fetch'],
|
|
);
|
|
assert.deepEqual(repairVehicleTimestamps(null, null, fetchedAtS), []);
|
|
});
|
|
|
|
test('the snapshot builder fills timestamps from the header it decoded', () => {
|
|
const feed = getTransitFeed('mbta');
|
|
const bytes = encodeFeed({
|
|
timestamp: 1_700_000_000,
|
|
entities: [{ id: 'unstamped', lat: 42.36, lon: -71.05 }],
|
|
});
|
|
const snapshot = buildTransitSnapshot(feed, bytes, 1_700_000_900_000);
|
|
assert.equal(snapshot.vehicles[0].timestamp, 1_700_000_000);
|
|
assert.equal(snapshot.vehicles[0].timestampSource, 'header');
|
|
assert.equal(snapshot.feedTimestamp, 1_700_000_000);
|
|
});
|
|
|
|
test('conditional-request validators and gzip ride along with feed identification', () => {
|
|
const entur = getTransitFeed('entur-norway');
|
|
const plain = transitUpstreamHeaders(entur);
|
|
assert.equal(plain['Accept-Encoding'], 'gzip');
|
|
assert.equal(plain['ET-Client-Name'], 'gods-eye-view-transit');
|
|
assert.equal('If-None-Match' in plain, false);
|
|
const conditional = transitUpstreamHeaders(entur, {
|
|
etag: 'W/"abc"',
|
|
lastModified: 'Wed, 10 Sep 2026 12:00:00 GMT',
|
|
});
|
|
assert.equal(conditional['If-None-Match'], 'W/"abc"');
|
|
assert.equal(
|
|
conditional['If-Modified-Since'],
|
|
'Wed, 10 Sep 2026 12:00:00 GMT',
|
|
);
|
|
assert.match(conditional['User-Agent'], /gods-eye-view/);
|
|
});
|
|
|
|
test('retained routes validate the entire identifier and only MBTA is opted in', () => {
|
|
assert.equal(resolveTransitRoute('/trail/mbta/bus%201').vehicleId, 'bus 1');
|
|
for (const path of [
|
|
'/trail/mbta/a%2Fb',
|
|
'/trail/mbta/%00',
|
|
'/trail/mbta/%5C',
|
|
'/trail/mbta/%2E%2E',
|
|
'/trail/mbta/%E0%A4%A',
|
|
`/trail/mbta/${encodeURIComponent('é'.repeat(129))}`,
|
|
'/trail/capmetro-austin/b',
|
|
])
|
|
assert.equal(resolveTransitRoute(path), null);
|
|
});
|
|
test('client history validates response bounds, epochs and cancellation through parsing', async () => {
|
|
const { fetchTransitHistory } = await import('./transitProxy.js');
|
|
const payload = {
|
|
version: 1,
|
|
feedId: 'mbta',
|
|
vehicleId: 'b',
|
|
epochs: [{ id: 1, trip: '', route: '1', mode: 'bus' }],
|
|
fixes: [[1000, 42, -71, 1, 1]],
|
|
};
|
|
assert.deepEqual(
|
|
await fetchTransitHistory(
|
|
'mbta',
|
|
'b',
|
|
new AbortController().signal,
|
|
async () => new Response(JSON.stringify(payload)),
|
|
),
|
|
payload,
|
|
);
|
|
for (const value of [
|
|
{ ...payload, vehicleId: 'wrong' },
|
|
{ ...payload, fixes: [[1000, 91, -71, 1, 1]] },
|
|
{ ...payload, fixes: Array(129).fill(payload.fixes[0]) },
|
|
{ ...payload, epochs: [] },
|
|
])
|
|
await assert.rejects(
|
|
fetchTransitHistory(
|
|
'mbta',
|
|
'b',
|
|
undefined,
|
|
async () => new Response(JSON.stringify(value)),
|
|
),
|
|
);
|
|
await assert.rejects(
|
|
fetchTransitHistory(
|
|
'mbta',
|
|
'b',
|
|
undefined,
|
|
async () => new Response('x'.repeat(32769)),
|
|
),
|
|
/limit/,
|
|
);
|
|
const controller = new AbortController();
|
|
await assert.rejects(
|
|
fetchTransitHistory('mbta', 'b', controller.signal, async () => {
|
|
controller.abort();
|
|
return new Response(JSON.stringify(payload));
|
|
}),
|
|
{ name: 'AbortError' },
|
|
);
|
|
});
|