mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-18 01:02:23 +00:00
Merge main and switch Cesium and Navara in place through Vue
Preserve the camera, map source and layer selection across engine sessions. Restore the previous engine if startup fails and retain local history navigation.
This commit is contained in:
commit
b8f4d097c4
1691 files changed
+225876
-41594
No files matched your search
@@ -20,6 +20,23 @@ export function createAnimation({
|
||||
parts,
|
||||
source,
|
||||
}) {
|
||||
function syncRenderDemand() {
|
||||
const needed = Boolean(
|
||||
layerState._enabled &&
|
||||
(layerState._dots.length || layerState._heatJamPrim),
|
||||
);
|
||||
// Height easing only runs in a held frame. Settle it before releasing, so
|
||||
// a population emptied mid-correction cannot report loading forever.
|
||||
if (!needed && layerState._heightPending) parts.retention.finishHeights();
|
||||
if (needed === Boolean(layerState._renderHeld)) return;
|
||||
layerState._renderHeld = needed;
|
||||
if (needed) {
|
||||
layerState._lastAnimTime = 0;
|
||||
services.render.holdContinuousRender('traffic');
|
||||
layerState._viewer?.scene?.requestRender?.();
|
||||
} else services.render.releaseContinuousRender('traffic');
|
||||
}
|
||||
|
||||
/**
|
||||
* Spawn animated dot primitives along a single road.
|
||||
*
|
||||
@@ -188,6 +205,7 @@ export function createAnimation({
|
||||
: null,
|
||||
});
|
||||
}
|
||||
syncRenderDemand();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -206,6 +224,8 @@ export function createAnimation({
|
||||
*/
|
||||
|
||||
function animate() {
|
||||
syncRenderDemand();
|
||||
if (!layerState._renderHeld) return;
|
||||
const now = Date.now();
|
||||
// Delta time in seconds, capped to avoid jumps when returning from background tab
|
||||
const dt = layerState._lastAnimTime
|
||||
@@ -339,6 +359,13 @@ export function createAnimation({
|
||||
layerState._count = 0;
|
||||
layerState._bucketCounts = { free: 0, slow: 0, jam: 0, sim: 0 };
|
||||
layerState._closedRoads = 0;
|
||||
syncRenderDemand();
|
||||
}
|
||||
return { spawnDotsForRoad, animate, maybeStopLight, clearDots };
|
||||
return {
|
||||
spawnDotsForRoad,
|
||||
animate,
|
||||
maybeStopLight,
|
||||
clearDots,
|
||||
syncRenderDemand,
|
||||
};
|
||||
}
|
||||
Vendored
+62
-17
@@ -8,15 +8,17 @@ import {
|
||||
trafficStyleProfile,
|
||||
} from '../../data/trafficPresetStyle.js';
|
||||
import { TRAFFIC_TIMING_ENABLED } from './policy.js';
|
||||
import { t, translateKnown } from '../../i18n/index.js';
|
||||
|
||||
export function createControls({ state: layerState, services, parts, source }) {
|
||||
/** One status line: feed, drawn road source, then degraded-coverage notes. */
|
||||
function roadStatusLabel(feed) {
|
||||
const source = layerState._roadSource;
|
||||
if (layerState._roadError)
|
||||
return `UNAVAILABLE · ${source} · Roads unavailable`;
|
||||
return t('UNAVAILABLE · {source} · Roads unavailable', { source });
|
||||
const notes = [feed.loadingLabel];
|
||||
if (!layerState._liveMode || feed.error) notes.push(`Roads: ${source}`);
|
||||
if (!layerState._liveMode || feed.error)
|
||||
notes.push(t('Roads: {source}', { source }));
|
||||
// An explicit TomTom or Hybrid choice without a key draws OpenStreetMap.
|
||||
if (
|
||||
!layerState._liveMode &&
|
||||
@@ -24,16 +26,24 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
)
|
||||
notes.push(
|
||||
layerState._flowStatusUnavailable
|
||||
? `${layerState._roadMode === 'tomtom' ? 'TomTom roads' : 'Hybrid'} unavailable while the traffic service is unreachable`
|
||||
? layerState._roadMode === 'tomtom'
|
||||
? t(
|
||||
'TomTom roads unavailable while the traffic service is unreachable',
|
||||
)
|
||||
: t('Hybrid unavailable while the traffic service is unreachable')
|
||||
: layerState._roadMode === 'tomtom'
|
||||
? 'TomTom roads need a TomTom key'
|
||||
: 'Hybrid needs a TomTom key',
|
||||
? t('TomTom roads need a TomTom key')
|
||||
: t('Hybrid needs a TomTom key'),
|
||||
);
|
||||
if (layerState._surfacePending) notes.push('Local surface still loading');
|
||||
if (layerState._roadWarning) notes.push(layerState._roadWarning);
|
||||
else if (layerState._roadPartial) notes.push('Partial coverage');
|
||||
if (layerState._detailError) notes.push('Detailed roads unavailable');
|
||||
else if (layerState._detailLimited) notes.push('Reduced detail coverage');
|
||||
if (layerState._surfacePending)
|
||||
notes.push(t('Local surface still loading'));
|
||||
// The warning is a road-source message (source.js marks the known ones).
|
||||
if (layerState._roadWarning)
|
||||
notes.push(translateKnown(layerState._roadWarning));
|
||||
else if (layerState._roadPartial) notes.push(t('Partial coverage'));
|
||||
if (layerState._detailError) notes.push(t('Detailed roads unavailable'));
|
||||
else if (layerState._detailLimited)
|
||||
notes.push(t('Reduced detail coverage'));
|
||||
return notes.join(' · ');
|
||||
}
|
||||
|
||||
@@ -161,13 +171,22 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
getRowControls() {
|
||||
const selected =
|
||||
layerState._roadMode || resolveRoadMode(null, layerState._liveMode);
|
||||
const needsKey = layerState._liveMode ? '' : ' (needs a TomTom key)';
|
||||
const live = layerState._liveMode;
|
||||
const titles = {
|
||||
tomtom: `TomTom roads only, each with its live flow${needsKey}`,
|
||||
osm: 'OpenStreetMap roads, with TomTom flow matched when available',
|
||||
hybrid: `TomTom roads first; OpenStreetMap fills the rest, simulated${needsKey}`,
|
||||
tomtom: live
|
||||
? t('TomTom roads only, each with its live flow')
|
||||
: t(
|
||||
'TomTom roads only, each with its live flow (needs a TomTom key)',
|
||||
),
|
||||
osm: t('OpenStreetMap roads, with TomTom flow matched when available'),
|
||||
hybrid: live
|
||||
? t('TomTom roads first; OpenStreetMap fills the rest, simulated')
|
||||
: t(
|
||||
'TomTom roads first; OpenStreetMap fills the rest, simulated (needs a TomTom key)',
|
||||
),
|
||||
};
|
||||
const labels = { tomtom: 'TomTom', osm: 'OSM', hybrid: 'Hybrid' };
|
||||
// TomTom and OSM are provider names and stay as they are.
|
||||
const labels = { tomtom: 'TomTom', osm: 'OSM', hybrid: t('Hybrid') };
|
||||
return {
|
||||
chips: TRAFFIC_ROAD_MODES.map((mode) => ({
|
||||
id: `roads-${mode}`,
|
||||
@@ -240,7 +259,8 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
* `error` carries this instant's health, so a live-configured layer whose
|
||||
* flow feed went down reads DEGRADED with the reason instead of a stale
|
||||
* LIVE coverage number. `flowCoveragePct` is shown dots on matched roads /
|
||||
* all shown dots (0–100 int), excluding closures; `tilesFetched` counts flow-tile requests
|
||||
* all shown dots (0–100 int, kept within 1–99 while both kinds are shown),
|
||||
* excluding closures; `tilesFetched` counts flow-tile requests
|
||||
* issued to the proxy this session (decode-cache hits excluded).
|
||||
* @returns {{count:number, lastUpdate:number|null, loading:boolean,
|
||||
* mode:'live'|'sim', error:string|null, flowCoveragePct:number,
|
||||
@@ -285,12 +305,23 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
Boolean(layerState._heightPending);
|
||||
const { free, slow, jam, sim } = layerState._bucketCounts;
|
||||
const matched = free + slow + jam;
|
||||
// The label reads 0 as "no matches" and 100 as nothing simulated, so
|
||||
// rounding must not reach either while both kinds of dot are shown.
|
||||
const flowCoveragePct =
|
||||
matched + sim > 0 ? Math.round((100 * matched) / (matched + sim)) : 0;
|
||||
matched + sim > 0
|
||||
? Math.min(
|
||||
sim > 0 ? 99 : 100,
|
||||
Math.max(
|
||||
matched > 0 ? 1 : 0,
|
||||
Math.round((100 * matched) / (matched + sim)),
|
||||
),
|
||||
)
|
||||
: 0;
|
||||
const feed = parts.model.trafficFeedPresentation({
|
||||
liveMode: layerState._liveMode,
|
||||
fetching: loading,
|
||||
flowError: layerState._flowError,
|
||||
stale: layerState._flowStale,
|
||||
coveragePct: flowCoveragePct,
|
||||
statusUnavailable: layerState._flowStatusUnavailable,
|
||||
roadSource: layerState._roadSource,
|
||||
@@ -302,6 +333,20 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
lastUpdate: layerState._lastUpdate,
|
||||
loading,
|
||||
mode: feed.mode,
|
||||
// Cached proxy tiles (TomTom budget spent or upstream failing): the
|
||||
// manager reads this as STALE. Any error (flow, roads, detail) reads
|
||||
// DEGRADED instead.
|
||||
stale: Boolean(
|
||||
layerState._liveMode &&
|
||||
layerState._flowStale &&
|
||||
!(
|
||||
layerState._roadError ||
|
||||
layerState._roadWarning ||
|
||||
layerState._detailError ||
|
||||
feed.error
|
||||
),
|
||||
),
|
||||
oldestTileAt: layerState._flowOldestTileAt ?? null,
|
||||
error:
|
||||
layerState._roadError ||
|
||||
layerState._roadWarning ||
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
FAST_FETCH_ALTITUDE,
|
||||
roadDotBudget,
|
||||
} from './policy.js';
|
||||
import { msg } from '../../i18n/index.js';
|
||||
|
||||
export function createFlow({ state: layerState, services, parts, source }) {
|
||||
const { registerDynamicCredit, TOMTOM_CREDIT } = services.credits;
|
||||
@@ -36,11 +37,13 @@ export function createFlow({ state: layerState, services, parts, source }) {
|
||||
const status = Number.isFinite(error.status)
|
||||
? error.status
|
||||
: Number(message.match(/HTTP (\d{3})/)?.[1]);
|
||||
if (status === 503) return 'TomTom key unavailable';
|
||||
if (status === 429) return 'TomTom daily budget reached';
|
||||
if (status === 502 || status === 504) return 'TomTom upstream unreachable';
|
||||
// English in state; trafficFeedPresentation translates it for the panel.
|
||||
if (status === 503) return msg('TomTom key unavailable');
|
||||
if (status === 429) return msg('TomTom daily budget reached');
|
||||
if (status === 502 || status === 504)
|
||||
return msg('TomTom upstream unreachable');
|
||||
if (Number.isFinite(status)) return `TomTom flow error (HTTP ${status})`;
|
||||
return 'TomTom flow unavailable';
|
||||
return msg('TomTom flow unavailable');
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -183,10 +186,19 @@ export function createFlow({ state: layerState, services, parts, source }) {
|
||||
return layerState._warmFlow;
|
||||
layerState._warmFlowGeneration = generation;
|
||||
const signal = layerState._activeFetchAbort?.signal;
|
||||
layerState._warmFlow = ensureFlowStatus(signal).then(() => {
|
||||
layerState._warmFlow = ensureFlowStatus(signal).then(async () => {
|
||||
if (!layerState._liveMode || generation !== layerState._loadGeneration)
|
||||
return [];
|
||||
return fetchFlowForBounds(clamped, { signal });
|
||||
if (typeof source.fetchFlowDetail !== 'function')
|
||||
return fetchFlowForBounds(clamped, { signal });
|
||||
// The proxy serves cached tiles once the TomTom budget is spent or the
|
||||
// upstream fails; carry that mark so getStats() reads STALE, not LIVE.
|
||||
const detail = await source.fetchFlowDetail(clamped, { signal });
|
||||
if (generation === layerState._loadGeneration) {
|
||||
layerState._flowStale = detail.stale === true;
|
||||
layerState._flowOldestTileAt = detail.oldestTileAt ?? null;
|
||||
}
|
||||
return detail.segments;
|
||||
});
|
||||
layerState._warmFlow.catch(() => {});
|
||||
return layerState._warmFlow;
|
||||
|
||||
@@ -19,7 +19,7 @@ import { VectorTile } from '@mapbox/vector-tile';
|
||||
* tree-shakeable; decoding happens client-side so the proxy stays a dumb
|
||||
* binary cache.
|
||||
*
|
||||
* @module data/flowTiles
|
||||
* @module layers/traffic/flowDecode
|
||||
*/
|
||||
|
||||
const FLOW_LAYER_NAME = 'Traffic flow';
|
||||
|
||||
@@ -4,30 +4,79 @@ import { clipTileLine } from '../../sources/openFreeMap.js';
|
||||
import { tileToBBox } from '../../data/tomtomTiles.js';
|
||||
import { decodeFlowTile } from './flowDecode.js';
|
||||
|
||||
const FLOW_TILE_PATH = (z, x, y) => `/api/tomtom/flow/${z}/${x}/${y}.pbf`;
|
||||
|
||||
/**
|
||||
* Whether the proxy answered a tile from its cache past the refresh window
|
||||
* (STALE-BUDGET once the daily budget is spent, STALE-ERROR when TomTom
|
||||
* fails), and when the proxy fetched it.
|
||||
*/
|
||||
function tileFreshness(response) {
|
||||
const status = response.headers?.get?.('x-tomtom-cache') || '';
|
||||
const fetchedAt = Number(response.headers?.get?.('x-tomtom-fetched-at'));
|
||||
return {
|
||||
stale: status.startsWith('STALE'),
|
||||
fetchedAt: fetchedAt > 0 ? fetchedAt : null,
|
||||
};
|
||||
}
|
||||
|
||||
/** Own one bounded decoded flow cache; every request still passes the server tile budget. */
|
||||
export function createFlowTileSource({
|
||||
fetchImpl = (...args) => globalThis.fetch(...args),
|
||||
} = {}) {
|
||||
// Freshness travels in response headers, but the tile cache keeps only
|
||||
// decoded segments: hold each response's freshness until its tile decodes,
|
||||
// then key it by the decoded tile, which the cache hands back on a hit.
|
||||
const pending = new Map();
|
||||
const freshness = new WeakMap();
|
||||
const tiles = createVectorTileSource({
|
||||
template: '/api/tomtom/flow/{z}/{x}/{y}.pbf',
|
||||
template: FLOW_TILE_PATH('{z}', '{x}', '{y}'),
|
||||
allowedOrigin: 'http://localhost',
|
||||
decode: (bytes, z, x, y) =>
|
||||
decodeFlowTile(bytes, z, x, y, { strict: true })
|
||||
decode: (bytes, z, x, y) => {
|
||||
// Take the mark before decoding, so a tile that fails to decode
|
||||
// leaves nothing behind.
|
||||
const path = FLOW_TILE_PATH(z, x, y);
|
||||
const entry = pending.get(path);
|
||||
const mark = entry?.mark;
|
||||
entry?.release();
|
||||
const segments = decodeFlowTile(bytes, z, x, y, { strict: true })
|
||||
.filter(isDrivableFlowSegment)
|
||||
.flatMap((segment) =>
|
||||
clipTileLine(segment.coords, tileToBBox(z, x, y)).map((coords) => ({
|
||||
...segment,
|
||||
coords,
|
||||
})),
|
||||
),
|
||||
fetchImpl,
|
||||
);
|
||||
if (mark) freshness.set(segments, mark);
|
||||
return segments;
|
||||
},
|
||||
fetchImpl: async (url, init) => {
|
||||
const response = await fetchImpl(url, init);
|
||||
if (response.ok && !init.signal.aborted) {
|
||||
const path = String(url);
|
||||
const entry = {
|
||||
mark: tileFreshness(response),
|
||||
release() {
|
||||
if (pending.get(path) === entry) pending.delete(path);
|
||||
init.signal.removeEventListener('abort', entry.release);
|
||||
},
|
||||
};
|
||||
pending.get(path)?.release();
|
||||
pending.set(path, entry);
|
||||
// The vector source aborts this signal for failed/cancelled body reads,
|
||||
// including size-limit failures that never reach decode.
|
||||
init.signal.addEventListener('abort', entry.release, { once: true });
|
||||
}
|
||||
return response;
|
||||
},
|
||||
ttlMs: 120_000,
|
||||
maxTiles: 16,
|
||||
});
|
||||
let partial = false;
|
||||
/**
|
||||
* Flow segments for bounds, with whether any covering tile failed to load
|
||||
* for this request.
|
||||
* for this request, whether any came from the proxy's stale cache, and when
|
||||
* the oldest tile was fetched.
|
||||
*/
|
||||
async function fetchFlowDetail(bounds, { signal, zoom = 12 } = {}) {
|
||||
const result = await tiles.fetchBounds(bounds, {
|
||||
@@ -44,7 +93,16 @@ export function createFlowTileSource({
|
||||
coords,
|
||||
})),
|
||||
);
|
||||
return { segments, partial: result.partial === true };
|
||||
const marks = result.tiles.map((tile) => freshness.get(tile) || {});
|
||||
const times = marks
|
||||
.map((mark) => mark.fetchedAt)
|
||||
.filter((at) => Number.isFinite(at));
|
||||
return {
|
||||
segments,
|
||||
partial: result.partial === true,
|
||||
stale: marks.some((mark) => mark.stale === true),
|
||||
oldestTileAt: times.length ? Math.min(...times) : null,
|
||||
};
|
||||
}
|
||||
return {
|
||||
fetchFlowDetail,
|
||||
@@ -52,6 +110,9 @@ export function createFlowTileSource({
|
||||
return (await fetchFlowDetail(bounds, options)).segments;
|
||||
},
|
||||
getFlowSessionStats: () => ({ ...tiles.getStats(), partial }),
|
||||
resetFlowTileCache: () => tiles.clear(),
|
||||
resetFlowTileCache: () => {
|
||||
for (const entry of pending.values()) entry.release();
|
||||
tiles.clear();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -2,9 +2,9 @@ import * as Cesium from 'cesium';
|
||||
import * as geo from '../../geo/index.js';
|
||||
import { tilesForBounds, tileToBBox } from '../../data/tomtomTiles.js';
|
||||
|
||||
export const RETICLE_RANGE_KM = 10;
|
||||
export const RETICLE_TILE_CAP = 16;
|
||||
export const tileKey = (tile) => `${tile.z}/${tile.x}/${tile.y}`;
|
||||
const RETICLE_RANGE_KM = 10;
|
||||
const RETICLE_TILE_CAP = 16;
|
||||
const tileKey = (tile) => `${tile.z}/${tile.x}/${tile.y}`;
|
||||
const cross = (a, b, c) =>
|
||||
(b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
|
||||
|
||||
|
||||
@@ -12,7 +12,6 @@ export function createLifecycle({
|
||||
parts,
|
||||
source,
|
||||
}) {
|
||||
const { holdContinuousRender, releaseContinuousRender } = services.render;
|
||||
const { resetFlowTileCache } = source;
|
||||
|
||||
const methods = {
|
||||
@@ -43,6 +42,8 @@ export function createLifecycle({
|
||||
layerState._lastViewCenter = null;
|
||||
layerState._flowRoads = null;
|
||||
layerState._flowError = null;
|
||||
layerState._flowStale = false;
|
||||
layerState._flowOldestTileAt = null;
|
||||
if (TRAFFIC_TIMING_ENABLED) {
|
||||
layerState._trafficTimingCurrentAnchor = null;
|
||||
layerState._trafficTimingSequence = 0;
|
||||
@@ -81,7 +82,7 @@ export function createLifecycle({
|
||||
layerState._enabled = true;
|
||||
layerState._surfaceFrameRemover = observeTrafficSurface(viewer.scene);
|
||||
if (layerState._roadMode !== 'tomtom') source.prefetch?.();
|
||||
holdContinuousRender('traffic'); // per-frame animator (perf wave 2)
|
||||
parts.animation.syncRenderDemand();
|
||||
layerState._lastAnimTime = 0;
|
||||
layerState._pointCollection.show = true;
|
||||
|
||||
@@ -142,7 +143,7 @@ export function createLifecycle({
|
||||
disable(viewer) {
|
||||
layerState._enabled = false;
|
||||
services.credits?.hideOsmCredit?.(layerState._viewer, 'traffic');
|
||||
releaseContinuousRender('traffic');
|
||||
parts.animation.syncRenderDemand();
|
||||
clearTimeout(layerState._fetchTimeout);
|
||||
clearInterval(layerState._enableKickTimer);
|
||||
layerState._enableKickTimer = null;
|
||||
@@ -160,6 +161,8 @@ export function createLifecycle({
|
||||
// A stale outage from the last session would misreport a fresh enable —
|
||||
// the next load re-derives feed health from real evidence.
|
||||
layerState._flowError = null;
|
||||
layerState._flowStale = false;
|
||||
layerState._flowOldestTileAt = null;
|
||||
|
||||
layerState._surfaceFrameRemover?.();
|
||||
layerState._surfaceFrameRemover = null;
|
||||
|
||||
+53
-11
@@ -1,5 +1,6 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { roadSurfaceChunks } from './surface.js';
|
||||
import { t, translateKnown } from '../../i18n/index.js';
|
||||
import {
|
||||
flowDensityMult,
|
||||
flowBucket,
|
||||
@@ -228,6 +229,7 @@ export function createModel({ state: layerState, services, parts, source }) {
|
||||
* @param {boolean} [input.liveMode] - `/api/tomtom/status` reported a key.
|
||||
* @param {boolean} [input.fetching] - A viewport load is in flight.
|
||||
* @param {string|null} [input.flowError] - `deriveTrafficFlowError` result, if any.
|
||||
* @param {boolean} [input.stale] - The flow came from cached proxy tiles.
|
||||
* @param {number} [input.coveragePct] - Share of shown dots on matched roads, 0–100.
|
||||
* @param {boolean} [input.statusUnavailable] - The status probe itself failed.
|
||||
* @param {string} [input.roadSource] - Name of the geometry being drawn.
|
||||
@@ -238,6 +240,7 @@ export function createModel({ state: layerState, services, parts, source }) {
|
||||
liveMode = false,
|
||||
fetching = false,
|
||||
flowError = null,
|
||||
stale = false,
|
||||
coveragePct = 0,
|
||||
statusUnavailable = false,
|
||||
roadSource = 'OpenStreetMap',
|
||||
@@ -251,19 +254,36 @@ export function createModel({ state: layerState, services, parts, source }) {
|
||||
// drops `loadingLabel` in its error branch, so the owner's SIMULATED copy
|
||||
// has to BE the error text or the steady state reverts to a bare
|
||||
// "TomTom daily budget reached" that never says what is on screen.
|
||||
const degraded = `SIMULATED — ${flowError}`;
|
||||
// The reason is ours (flow.js marks it) or carries an HTTP code.
|
||||
const degraded = t('SIMULATED — {reason}', {
|
||||
reason: translateKnown(flowError),
|
||||
});
|
||||
return { mode, error: degraded, loadingLabel: degraded };
|
||||
}
|
||||
// Cached proxy tiles (TomTom budget spent or upstream failing) are not live.
|
||||
if (liveMode && stale && !fetching) {
|
||||
return {
|
||||
mode,
|
||||
error: null,
|
||||
loadingLabel: t('STALE · Roads: {source} · Flow: cached TomTom tiles', {
|
||||
source: roadSource,
|
||||
}),
|
||||
};
|
||||
}
|
||||
// TomTom and Hybrid name their geometry; OpenStreetMap keeps its match copy.
|
||||
if (liveMode && roadSource === 'TomTom') {
|
||||
return {
|
||||
mode,
|
||||
error: null,
|
||||
loadingLabel: fetching
|
||||
? 'Syncing flow · Roads: TomTom'
|
||||
? t('Syncing flow · Roads: {source}', { source: roadSource })
|
||||
: coveragePct > 0
|
||||
? 'LIVE · Roads: TomTom · Roads without flow hidden'
|
||||
: 'LIVE · Roads: TomTom · No flow roads in view',
|
||||
? t('LIVE · Roads: {source} · Roads without flow hidden', {
|
||||
source: roadSource,
|
||||
})
|
||||
: t('LIVE · Roads: {source} · No flow roads in view', {
|
||||
source: roadSource,
|
||||
}),
|
||||
};
|
||||
}
|
||||
if (liveMode && roadSource === 'TomTom + OpenStreetMap') {
|
||||
@@ -271,8 +291,16 @@ export function createModel({ state: layerState, services, parts, source }) {
|
||||
mode,
|
||||
error: null,
|
||||
loadingLabel: fetching
|
||||
? `Syncing flow · Roads: ${roadSource}`
|
||||
: `${coveragePct > 0 ? 'LIVE' : 'SIMULATED'} · Roads: ${roadSource} · Flow ${coveragePct}%`,
|
||||
? t('Syncing flow · Roads: {source}', { source: roadSource })
|
||||
: coveragePct > 0
|
||||
? t('LIVE · Roads: {source} · Flow {percent}%', {
|
||||
source: roadSource,
|
||||
percent: coveragePct,
|
||||
})
|
||||
: t('SIMULATED · Roads: {source} · Flow {percent}%', {
|
||||
source: roadSource,
|
||||
percent: coveragePct,
|
||||
}),
|
||||
};
|
||||
}
|
||||
if (liveMode) {
|
||||
@@ -280,10 +308,24 @@ export function createModel({ state: layerState, services, parts, source }) {
|
||||
mode,
|
||||
error: null,
|
||||
loadingLabel: fetching
|
||||
? 'Syncing flow · Roads: OpenStreetMap · Flow: TomTom · Unmatched: simulated'
|
||||
? t(
|
||||
'Syncing flow · Roads: OpenStreetMap · Flow: TomTom · Unmatched: simulated',
|
||||
)
|
||||
: coveragePct > 0
|
||||
? `LIVE · Roads: OpenStreetMap · Flow: TomTom · ${coveragePct}% cov${coveragePct < 100 ? ' · Unmatched: simulated' : ''}`
|
||||
: 'SIMULATED · Roads: OpenStreetMap · Flow: TomTom (no matches)',
|
||||
? coveragePct < 100
|
||||
? t(
|
||||
'LIVE · Roads: OpenStreetMap · Flow: TomTom · {percent}% cov · Unmatched: simulated',
|
||||
{
|
||||
percent: coveragePct,
|
||||
},
|
||||
)
|
||||
: t(
|
||||
'LIVE · Roads: OpenStreetMap · Flow: TomTom · {percent}% cov',
|
||||
{
|
||||
percent: coveragePct,
|
||||
},
|
||||
)
|
||||
: t('SIMULATED · Roads: OpenStreetMap · Flow: TomTom (no matches)'),
|
||||
};
|
||||
}
|
||||
// Keyless simulation — one terse line that names the mode and the remedy
|
||||
@@ -293,8 +335,8 @@ export function createModel({ state: layerState, services, parts, source }) {
|
||||
mode,
|
||||
error: null,
|
||||
loadingLabel: statusUnavailable
|
||||
? 'SIMULATED — traffic service unreachable'
|
||||
: 'SIMULATED — add TomTom key for live',
|
||||
? t('SIMULATED — traffic service unreachable')
|
||||
: t('SIMULATED — add TomTom key for live'),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -37,7 +37,14 @@ function setup(t) {
|
||||
visibleRoadsForAltitude: (roads) => roads,
|
||||
},
|
||||
};
|
||||
const ctx = { state, services: {}, parts, source: {} };
|
||||
const ctx = {
|
||||
state,
|
||||
services: {
|
||||
render: { holdContinuousRender() {}, releaseContinuousRender() {} },
|
||||
},
|
||||
parts,
|
||||
source: {},
|
||||
};
|
||||
parts.style = createStyle(ctx);
|
||||
parts.model = createModel(ctx);
|
||||
parts.animation = createAnimation(ctx);
|
||||
@@ -558,6 +565,37 @@ test('provisional opposite-direction heights cannot overwrite a measured sibling
|
||||
assert.notEqual(forward.waypoints, reverse.waypoints);
|
||||
});
|
||||
|
||||
test('a closure that empties the population mid-correction settles heights and clears loading before release', (t) => {
|
||||
const h = setup(t);
|
||||
h.parts.retention.reconcile(h.roads(), 450, true);
|
||||
h.settle();
|
||||
assert.equal(h.state._renderHeld, true);
|
||||
const road = h.state._roads[0];
|
||||
// Republishing the sole road starts a height correction.
|
||||
const corrected = h.roads(0, 120);
|
||||
h.parts.retention.reconcile(corrected, 450, true);
|
||||
assert.equal(h.state._heightPending, true);
|
||||
assert.equal(road.heightMoving, true);
|
||||
// The closure arrives before the next population pass, which then removes
|
||||
// the final points after their fade, long before the correction finishes.
|
||||
corrected[0].flow = { level: 0, closure: true };
|
||||
for (let i = 0; i < 20 && h.state._dots.length; i++) h.frame();
|
||||
assert.equal(h.state._dots.length, 0);
|
||||
assert.equal(h.state._heatJamPrim, null);
|
||||
assert.equal(h.state._renderHeld, false);
|
||||
assert.equal(h.state._heightPending, false);
|
||||
assert.equal(h.state._populationPending, false);
|
||||
assert.equal(road.heightMoving, false);
|
||||
assert.ok(
|
||||
Math.abs(C.Cartographic.fromCartesian(road.waypoints[0]).height - 120) <
|
||||
0.01,
|
||||
);
|
||||
// Frames driven by other layers stay idle and cannot revive the work.
|
||||
h.frame();
|
||||
assert.equal(h.state._heightPending, false);
|
||||
assert.equal(h.state._renderHeld, false);
|
||||
});
|
||||
|
||||
test('large height corrections obey a screen-pixel bound and reuse projection scratch objects', (t) => {
|
||||
const h = setup(t);
|
||||
h.state._viewer.scene = {
|
||||
|
||||
@@ -175,13 +175,3 @@ export const STYLED_MIN_BASE_PX = 5;
|
||||
/** @const {number} Maximum tile cache entries before LRU eviction */
|
||||
|
||||
export const TILE_CACHE_MAX_ENTRIES = 64;
|
||||
|
||||
/**
|
||||
* Milliseconds the first dot paint will wait for flow data. Cached flow
|
||||
* settles within this window (decode cache, 120 s TTL) and renders fully
|
||||
* colored; a cold tile fetch loses the race, dots paint immediately in
|
||||
* white, and recolorDotsInPlace applies the colors when flow arrives —
|
||||
* field-test round 1's "takes forever to load" was the sequential wait.
|
||||
*/
|
||||
|
||||
export const FLOW_RENDER_RACE_MS = 250;
|
||||
@@ -0,0 +1,45 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createAnimation } from './animation.js';
|
||||
|
||||
test('traffic render demand follows animated population and jam lines across empty, disable and re-enable', () => {
|
||||
const calls = [];
|
||||
const state = { _enabled: true, _dots: [], _motion: { rebuilds: 0 } };
|
||||
const animation = createAnimation({
|
||||
state,
|
||||
services: {
|
||||
render: {
|
||||
holdContinuousRender: (id) => calls.push(['hold', id]),
|
||||
releaseContinuousRender: (id) => calls.push(['release', id]),
|
||||
},
|
||||
},
|
||||
parts: {
|
||||
retention: { clear() {} },
|
||||
rendering: {
|
||||
removeHeatLines() {
|
||||
state._heatJamPrim = null;
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
animation.syncRenderDemand();
|
||||
assert.deepEqual(calls, []);
|
||||
state._dots.push({});
|
||||
animation.syncRenderDemand();
|
||||
animation.syncRenderDemand();
|
||||
assert.deepEqual(calls, [['hold', 'traffic']]);
|
||||
animation.clearDots();
|
||||
assert.deepEqual(calls.at(-1), ['release', 'traffic']);
|
||||
state._heatJamPrim = {};
|
||||
animation.syncRenderDemand();
|
||||
assert.deepEqual(calls.at(-1), ['hold', 'traffic']);
|
||||
state._enabled = false;
|
||||
animation.syncRenderDemand();
|
||||
assert.deepEqual(calls.at(-1), ['release', 'traffic']);
|
||||
state._enabled = true;
|
||||
animation.clearDots();
|
||||
assert.equal(state._renderHeld, false);
|
||||
state._dots.push({});
|
||||
animation.syncRenderDemand();
|
||||
assert.equal(state._renderHeld, true);
|
||||
});
|
||||
@@ -50,6 +50,7 @@ export function createRendering({
|
||||
layerState._heatSlowPrim = null;
|
||||
}
|
||||
layerState._heatLineCount = 0;
|
||||
parts.animation.syncRenderDemand?.();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -152,6 +153,7 @@ export function createRendering({
|
||||
}
|
||||
|
||||
layerState._heatLineCount = kept.length;
|
||||
parts.animation.syncRenderDemand?.();
|
||||
if (candidates.length > kept.length) {
|
||||
console.log(
|
||||
`[Data:Traffic] Heat-lines capped at ${HEAT_LINE_CAP} (${candidates.length} congested roads in view)`,
|
||||
|
||||
@@ -125,6 +125,7 @@ export function createRetention({ state, parts }) {
|
||||
count++;
|
||||
}
|
||||
state._count = count;
|
||||
parts.animation.syncRenderDemand?.();
|
||||
}
|
||||
function reconcile(roads, height, replace) {
|
||||
altitude = height;
|
||||
@@ -241,6 +242,29 @@ export function createRetention({ state, parts }) {
|
||||
road.heightMoving = moving;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Settle every retained road on its corrected heights at once. Easing only
|
||||
* runs inside the held animation frame, so once nothing is left to animate
|
||||
* the remaining correction would otherwise stay pending indefinitely.
|
||||
* Published roads whose record was just dropped are settled too, so a later
|
||||
* held frame cannot revive their correction.
|
||||
*/
|
||||
function finishHeights() {
|
||||
const roads = new Set(state._roads);
|
||||
for (const record of records.values()) roads.add(record.road);
|
||||
for (const road of roads) {
|
||||
if (!road.heightMoving) continue;
|
||||
for (let i = 0; i < road.waypoints.length; i++)
|
||||
Cesium.Cartesian3.clone(road.targetWaypoints[i], road.waypoints[i]);
|
||||
for (let i = 0; i < road.segmentDist.length; i++)
|
||||
road.segmentDist[i] = Cesium.Cartesian3.distance(
|
||||
road.waypoints[i],
|
||||
road.waypoints[i + 1],
|
||||
);
|
||||
road.heightMoving = false;
|
||||
}
|
||||
state._heightPending = false;
|
||||
}
|
||||
function clear() {
|
||||
if (timer !== null) {
|
||||
if (typeof cancelAnimationFrame === 'function')
|
||||
@@ -252,5 +276,5 @@ export function createRetention({ state, parts }) {
|
||||
state._populationPending = false;
|
||||
state._heightPending = false;
|
||||
}
|
||||
return { reconcile, easeHeights, clear, refreshCounts };
|
||||
return { reconcile, easeHeights, finishHeights, clear, refreshCounts };
|
||||
}
|
||||
@@ -283,6 +283,64 @@ test('flow application preserves direct values and leaves Hybrid fill simulated'
|
||||
assert.equal(state._flowPending, 0);
|
||||
});
|
||||
|
||||
test('stale proxy flow tiles reach the layer stats and never read LIVE', async () => {
|
||||
const { createFlow } = await import('./flow.js');
|
||||
const { createModel } = await import('./model.js');
|
||||
const { createControls } = await import('./controls.js');
|
||||
const { createState } = await import('./state.js');
|
||||
const { layerFeedState } = await import('../../data/feedState.js');
|
||||
let detail = {
|
||||
segments: [flow],
|
||||
partial: false,
|
||||
stale: true,
|
||||
oldestTileAt: 1000,
|
||||
};
|
||||
const source = {
|
||||
fetchFlowDetail: async () => detail,
|
||||
fetchFlowForBounds: async () => detail.segments,
|
||||
getFlowSessionStats: () => ({ tilesFetched: 1 }),
|
||||
};
|
||||
const state = createState({ services: {} });
|
||||
Object.assign(state, {
|
||||
_enabled: true,
|
||||
_liveMode: true,
|
||||
_loadGeneration: 1,
|
||||
_flowStatusPromise: Promise.resolve(),
|
||||
_bucketCounts: { free: 3, slow: 0, jam: 0, sim: 1 },
|
||||
});
|
||||
const parts = {};
|
||||
const context = { state, services: { credits: {} }, parts, source };
|
||||
parts.model = createModel(context);
|
||||
parts.flow = createFlow(context);
|
||||
const controls = createControls(context);
|
||||
|
||||
await parts.flow.applyFlowToRoads([{ coords: coordinates }], box, 1);
|
||||
const stale = controls.methods.getStats();
|
||||
assert.equal(stale.mode, 'live');
|
||||
assert.equal(stale.stale, true);
|
||||
assert.equal(stale.oldestTileAt, 1000);
|
||||
assert.doesNotMatch(stale.loadingLabel, /LIVE/);
|
||||
assert.equal(layerFeedState(stale), 'stale');
|
||||
|
||||
// A road failure outranks cached flow: the row reads the failure.
|
||||
state._roadError = 'Road geometry unavailable';
|
||||
assert.equal(controls.methods.getStats().stale, false);
|
||||
state._roadError = null;
|
||||
|
||||
detail = {
|
||||
segments: [flow],
|
||||
partial: false,
|
||||
stale: false,
|
||||
oldestTileAt: 2000,
|
||||
};
|
||||
state._loadGeneration = 2;
|
||||
await parts.flow.applyFlowToRoads([{ coords: coordinates }], box, 2);
|
||||
const live = controls.methods.getStats();
|
||||
assert.equal(live.stale, false);
|
||||
assert.match(live.loadingLabel, /^LIVE · Roads: OpenStreetMap/);
|
||||
assert.equal(layerFeedState(live), 'nominal');
|
||||
});
|
||||
|
||||
test('status names the drawn road source for each mode', async () => {
|
||||
const { createModel } = await import('./model.js');
|
||||
const { trafficFeedPresentation: present } = createModel({
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
// The traffic road-status notes follow the UI language; English keeps
|
||||
// its wording.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { setLocale } from '../../i18n/index.js';
|
||||
import { createState } from './state.js';
|
||||
import { createControls } from './controls.js';
|
||||
|
||||
function loadingLabel(overrides) {
|
||||
const state = createState({ services: {} });
|
||||
Object.assign(state, overrides);
|
||||
const controls = createControls({
|
||||
state,
|
||||
services: {},
|
||||
source: { getFlowSessionStats: () => ({}) },
|
||||
parts: { model: { trafficFeedPresentation: () => ({ loadingLabel: '' }) } },
|
||||
});
|
||||
return controls.methods.getStats().loadingLabel;
|
||||
}
|
||||
|
||||
const DEGRADED = {
|
||||
_liveMode: false,
|
||||
_roadMode: 'tomtom',
|
||||
_roadSource: 'OpenStreetMap',
|
||||
_roadPartial: true,
|
||||
_detailLimited: true,
|
||||
_surfacePending: 2,
|
||||
};
|
||||
|
||||
test('en: road status notes keep their English wording', () => {
|
||||
setLocale('en');
|
||||
assert.equal(
|
||||
loadingLabel(DEGRADED),
|
||||
' · Roads: OpenStreetMap · TomTom roads need a TomTom key · Local surface still loading · Partial coverage · Reduced detail coverage',
|
||||
);
|
||||
assert.equal(
|
||||
loadingLabel({ _roadError: 'x', _roadSource: 'OpenStreetMap' }),
|
||||
'UNAVAILABLE · OpenStreetMap · Roads unavailable',
|
||||
);
|
||||
});
|
||||
|
||||
for (const locale of ['es', 'ru']) {
|
||||
test(`${locale}: road status notes are in the UI language`, () => {
|
||||
setLocale(locale);
|
||||
try {
|
||||
const label = loadingLabel({
|
||||
...DEGRADED,
|
||||
_roadPartial: false,
|
||||
_roadWarning: 'OpenFreeMap tiles rate-limited',
|
||||
});
|
||||
for (const english of [
|
||||
'Roads:',
|
||||
'TomTom key',
|
||||
'still loading',
|
||||
'rate-limited',
|
||||
'detail coverage',
|
||||
])
|
||||
assert.ok(
|
||||
!label.includes(english),
|
||||
`${locale}: "${english}" in ${label}`,
|
||||
);
|
||||
} finally {
|
||||
setLocale('en');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function roadChips(liveMode) {
|
||||
const state = createState({ services: {} });
|
||||
state._liveMode = liveMode;
|
||||
const controls = createControls({
|
||||
state,
|
||||
services: {},
|
||||
source: { getFlowSessionStats: () => ({}) },
|
||||
parts: {},
|
||||
});
|
||||
return controls.methods.getRowControls().chips;
|
||||
}
|
||||
|
||||
test('en: road-source chips keep their English labels and titles', () => {
|
||||
setLocale('en');
|
||||
assert.deepEqual(
|
||||
roadChips(false).map((chip) => [chip.label, chip.title]),
|
||||
[
|
||||
[
|
||||
'TomTom',
|
||||
'TomTom roads only, each with its live flow (needs a TomTom key)',
|
||||
],
|
||||
['OSM', 'OpenStreetMap roads, with TomTom flow matched when available'],
|
||||
[
|
||||
'Hybrid',
|
||||
'TomTom roads first; OpenStreetMap fills the rest, simulated (needs a TomTom key)',
|
||||
],
|
||||
],
|
||||
);
|
||||
assert.equal(
|
||||
roadChips(true)[2].title,
|
||||
'TomTom roads first; OpenStreetMap fills the rest, simulated',
|
||||
);
|
||||
});
|
||||
|
||||
for (const [locale, hybrid] of [
|
||||
['ru', 'Гибрид'],
|
||||
['es', 'Híbrido'],
|
||||
]) {
|
||||
test(`${locale}: the Hybrid chip and every chip title are translated`, () => {
|
||||
setLocale(locale);
|
||||
try {
|
||||
for (const live of [false, true]) {
|
||||
const chips = roadChips(live);
|
||||
assert.deepEqual(
|
||||
chips.map((chip) => chip.label),
|
||||
['TomTom', 'OSM', hybrid],
|
||||
);
|
||||
for (const chip of chips)
|
||||
assert.doesNotMatch(
|
||||
chip.title,
|
||||
/roads only|roads, with|fills the rest|needs a/,
|
||||
`${locale}: ${chip.title}`,
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
setLocale('en');
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -59,16 +59,20 @@ export class RoadRequestError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
// AI tool services import this module, so it marks its English with a local
|
||||
// msg(); the traffic panel translates the message (controls.js).
|
||||
const msg = (text) => text;
|
||||
|
||||
/** Name the road upstream without exposing raw transport errors or missing codes. */
|
||||
export function roadRequestError(status, cause) {
|
||||
const code = Number.isFinite(status) ? status : null;
|
||||
const message =
|
||||
code === 429
|
||||
? 'OpenFreeMap tiles rate-limited'
|
||||
? msg('OpenFreeMap tiles rate-limited')
|
||||
: code === 504 || cause?.name === 'TimeoutError'
|
||||
? 'OpenFreeMap tiles timed out'
|
||||
? msg('OpenFreeMap tiles timed out')
|
||||
: code === null
|
||||
? 'OpenFreeMap tiles unavailable'
|
||||
? msg('OpenFreeMap tiles unavailable')
|
||||
: `OpenFreeMap tiles unavailable (HTTP ${code})`;
|
||||
return Object.assign(new RoadRequestError(message, { status: code, cause }), {
|
||||
retryable: cause?.retryable !== false,
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { getEventListeners } from 'node:events';
|
||||
import { createFlowTileSource } from './flowSource.js';
|
||||
import { tilesForBounds, tileToBBox } from '../../data/tomtomTiles.js';
|
||||
import { decodeFlowTile } from './flowDecode.js';
|
||||
import { decodeOpenFreeMapTile } from '../../sources/openFreeMap.js';
|
||||
@@ -514,6 +516,26 @@ test('late closures hide and stop dots; coverage counts shown matched dots, and
|
||||
assert.equal(controls.getStats().flowCoveragePct, 80);
|
||||
});
|
||||
|
||||
test('coverage never rounds to "no matches" or full coverage while both kinds of dot are shown', async () => {
|
||||
const { state, controls } = await matchingContext(async () => []);
|
||||
state._bucketCounts = { free: 1, slow: 0, jam: 0, sim: 300 };
|
||||
assert.equal(controls.getStats().flowCoveragePct, 1);
|
||||
assert.equal(
|
||||
controls.getStats().loadingLabel,
|
||||
'LIVE · Roads: OpenStreetMap · Flow: TomTom · 1% cov · Unmatched: simulated',
|
||||
);
|
||||
state._bucketCounts = { free: 300, slow: 0, jam: 0, sim: 1 };
|
||||
assert.equal(controls.getStats().flowCoveragePct, 99);
|
||||
assert.equal(
|
||||
controls.getStats().loadingLabel,
|
||||
'LIVE · Roads: OpenStreetMap · Flow: TomTom · 99% cov · Unmatched: simulated',
|
||||
);
|
||||
state._bucketCounts = { free: 300, slow: 0, jam: 0, sim: 0 };
|
||||
assert.equal(controls.getStats().flowCoveragePct, 100);
|
||||
state._bucketCounts = { free: 0, slow: 0, jam: 0, sim: 300 };
|
||||
assert.equal(controls.getStats().flowCoveragePct, 0);
|
||||
});
|
||||
|
||||
test('refresh failure removes cached matches and reports simulated flow', async () => {
|
||||
const { flow, state, model, controls } = await matchingContext(async () => {
|
||||
throw new Error('HTTP 429');
|
||||
@@ -867,3 +889,154 @@ test('traffic separates API and public tile transports, including the default ti
|
||||
assert.ok(publicUrls.length >= 4);
|
||||
assert.ok(apiUrls.length >= 4);
|
||||
});
|
||||
|
||||
test('flow detail reports stale proxy tiles and the oldest tile time, also from its cache', async () => {
|
||||
const fetchedAt = Date.UTC(2026, 9, 16, 8);
|
||||
const reply = (status, at) => async () =>
|
||||
new Response(fixture, {
|
||||
headers: { 'x-tomtom-cache': status, 'x-tomtom-fetched-at': String(at) },
|
||||
});
|
||||
const stale = createTrafficSource({
|
||||
fetchImpl: reply('STALE-BUDGET', fetchedAt),
|
||||
});
|
||||
const first = await stale.fetchFlowDetail(bounds);
|
||||
assert.ok(first.segments.length > 0);
|
||||
assert.equal(first.stale, true);
|
||||
assert.equal(first.oldestTileAt, fetchedAt);
|
||||
// The decoded tile is served from cache now, and keeps its mark.
|
||||
const again = await stale.fetchFlowDetail(bounds);
|
||||
assert.equal(stale.getFlowSessionStats().tilesFetched, 1);
|
||||
assert.equal(again.stale, true);
|
||||
assert.equal(again.oldestTileAt, fetchedAt);
|
||||
|
||||
const fresh = createTrafficSource({ fetchImpl: reply('MISS', fetchedAt) });
|
||||
const live = await fresh.fetchFlowDetail(bounds);
|
||||
assert.equal(live.stale, false);
|
||||
assert.equal(live.oldestTileAt, fetchedAt);
|
||||
|
||||
const unmarked = createTrafficSource({
|
||||
fetchImpl: async () => new Response(fixture),
|
||||
});
|
||||
const plain = await unmarked.fetchFlowDetail(bounds);
|
||||
assert.equal(plain.stale, false);
|
||||
assert.equal(plain.oldestTileAt, null);
|
||||
});
|
||||
|
||||
// Capture constructor-owned Maps only while constructing the source, so tests
|
||||
// can assert retained metadata without adding a diagnostic API to production.
|
||||
function flowSourceWithMaps(fetchImpl) {
|
||||
const maps = [];
|
||||
const NativeMap = globalThis.Map;
|
||||
let source;
|
||||
try {
|
||||
globalThis.Map = class extends NativeMap {
|
||||
constructor(...args) {
|
||||
super(...args);
|
||||
maps.push(this);
|
||||
}
|
||||
};
|
||||
source = createFlowTileSource({ fetchImpl });
|
||||
} finally {
|
||||
globalThis.Map = NativeMap;
|
||||
}
|
||||
return { source, pending: maps[0] };
|
||||
}
|
||||
|
||||
test('flow freshness is released after body failures, size rejection, decode and reset', async () => {
|
||||
for (const failure of ['body', 'size', 'decode']) {
|
||||
let requestSignal;
|
||||
let fail = true;
|
||||
const { source, pending } = flowSourceWithMaps(async (url, { signal }) => {
|
||||
requestSignal = signal;
|
||||
return {
|
||||
ok: true,
|
||||
headers: new Headers({
|
||||
'x-tomtom-cache': fail ? 'STALE-ERROR' : 'MISS',
|
||||
'x-tomtom-fetched-at': fail ? '1000' : '2000',
|
||||
...(fail && failure === 'size'
|
||||
? { 'content-length': '99999999' }
|
||||
: {}),
|
||||
}),
|
||||
async arrayBuffer() {
|
||||
if (fail && failure === 'body') throw new Error('body disconnected');
|
||||
return fail && failure === 'decode' ? new Uint8Array([255]) : fixture;
|
||||
},
|
||||
};
|
||||
});
|
||||
await assert.rejects(source.fetchFlowDetail(bounds));
|
||||
assert.equal(pending.size, 0, `${failure} leaves no pending metadata`);
|
||||
assert.equal(getEventListeners(requestSignal, 'abort').length, 0);
|
||||
assert.equal(source.getFlowSessionStats().cacheEntries, 0);
|
||||
fail = false;
|
||||
const fresh = await source.fetchFlowDetail(bounds);
|
||||
assert.equal(fresh.stale, false);
|
||||
assert.equal(fresh.oldestTileAt, 2000);
|
||||
assert.equal(pending.size, 0, 'successful decode releases metadata');
|
||||
assert.equal(getEventListeners(requestSignal, 'abort').length, 0);
|
||||
source.resetFlowTileCache();
|
||||
assert.equal(pending.size, 0);
|
||||
}
|
||||
});
|
||||
|
||||
test('flow reset and late cancelled headers cannot retain or replace newer freshness', async () => {
|
||||
let resolveOld;
|
||||
let oldSignal;
|
||||
let calls = 0;
|
||||
const { source, pending } = flowSourceWithMaps((url, { signal }) => {
|
||||
if (++calls === 1) {
|
||||
oldSignal = signal;
|
||||
return new Promise((resolve) => {
|
||||
resolveOld = resolve;
|
||||
});
|
||||
}
|
||||
return Promise.resolve(
|
||||
new Response(fixture, {
|
||||
headers: { 'x-tomtom-cache': 'MISS', 'x-tomtom-fetched-at': '2000' },
|
||||
}),
|
||||
);
|
||||
});
|
||||
const old = source.fetchFlowDetail(bounds);
|
||||
const rejected = assert.rejects(old, { name: 'AbortError' });
|
||||
while (!resolveOld) await new Promise((resolve) => setImmediate(resolve));
|
||||
source.resetFlowTileCache();
|
||||
const fresh = await source.fetchFlowDetail(bounds);
|
||||
resolveOld(
|
||||
new Response(fixture, {
|
||||
headers: {
|
||||
'x-tomtom-cache': 'STALE-ERROR',
|
||||
'x-tomtom-fetched-at': '1000',
|
||||
},
|
||||
}),
|
||||
);
|
||||
await rejected;
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
assert.equal(pending.size, 0);
|
||||
assert.equal(getEventListeners(oldSignal, 'abort').length, 0);
|
||||
assert.equal(fresh.stale, false);
|
||||
assert.equal(fresh.oldestTileAt, 2000);
|
||||
assert.equal((await source.fetchFlowDetail(bounds)).oldestTileAt, 2000);
|
||||
});
|
||||
|
||||
test('cancelling a flow body releases its freshness before a new request', async () => {
|
||||
const controller = new AbortController();
|
||||
let requestSignal;
|
||||
const { source, pending } = flowSourceWithMaps(async (url, { signal }) => {
|
||||
requestSignal = signal;
|
||||
return {
|
||||
ok: true,
|
||||
headers: new Headers({ 'x-tomtom-cache': 'STALE-ERROR' }),
|
||||
async arrayBuffer() {
|
||||
assert.equal(pending.size, 1);
|
||||
controller.abort();
|
||||
return fixture;
|
||||
},
|
||||
};
|
||||
});
|
||||
await assert.rejects(
|
||||
source.fetchFlowDetail(bounds, { signal: controller.signal }),
|
||||
{ name: 'AbortError' },
|
||||
);
|
||||
assert.equal(pending.size, 0);
|
||||
assert.equal(getEventListeners(requestSignal, 'abort').length, 0);
|
||||
assert.equal(source.getFlowSessionStats().cacheEntries, 0);
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import { normalizeRoadMode } from './roadModes.js';
|
||||
import * as Cesium from 'cesium';
|
||||
import { FLOW_BUCKET_COLORS, TRAFFIC_TIMING_ENABLED } from './policy.js';
|
||||
import { FLOW_BUCKET_COLORS } from './policy.js';
|
||||
|
||||
export function createState({ services }) {
|
||||
const layerState = {};
|
||||
@@ -108,6 +108,16 @@ export function createState({ services }) {
|
||||
|
||||
layerState._flowError = null;
|
||||
|
||||
/**
|
||||
* True while the drawn flow came from cached proxy tiles (TomTom budget
|
||||
* spent or upstream failing); `_flowOldestTileAt` is the oldest tile's
|
||||
* fetch time in ms, or null.
|
||||
* @type {boolean}
|
||||
*/
|
||||
|
||||
layerState._flowStale = false;
|
||||
layerState._flowOldestTileAt = null;
|
||||
|
||||
/**
|
||||
* True when `/api/tomtom/status` itself could not be reached, so the layer is
|
||||
* simulating because it could not ask — not because the server said "no key".
|
||||
|
||||
@@ -184,6 +184,9 @@ export function createViewport({ state: layerState, services, parts, source }) {
|
||||
layerState._fetching = false;
|
||||
layerState._flowPending = 0;
|
||||
layerState._roadError = null;
|
||||
// Nothing is drawn up here, cached or not.
|
||||
layerState._flowStale = false;
|
||||
layerState._flowOldestTileAt = null;
|
||||
parts.animation.clearDots();
|
||||
layerState._lastBounds = null;
|
||||
layerState._lastViewCenter = null;
|
||||
|
||||
Reference in new issue
Block a user