Merge origin/main into fix/earthquake-click-details

This commit is contained in:
manjunath22466 committed 2026-11-17 11:49:17 +05:30
commit 4804097ca1
204 files changed
+34669 -680

No files matched your search

+41
View File
@@ -175,3 +175,44 @@ test('a vessel snapshot at a time the source drops for a newer one is no failure
assert.equal(probe.feed.loading, false);
assert.deepEqual(probe.applied, []);
});
test('back at live, the live poll goes out at once even while a snapshot at a time was still loading', async () => {
const queries = [];
const probe = ingestion({
getSnapshot(query, { signal }) {
queries.push(query);
if (query.atMs === undefined)
return Promise.resolve({
records: [{ id: '111', latitude: 1, longitude: 2, observedAtMs: 5 }],
observedAtMs: 5,
freshness: 'current',
complete: true,
transportStatus: 'live',
});
// A snapshot at a time answers only when dropped.
return new Promise((_, reject) =>
signal.addEventListener('abort', () => {
const error = new Error('aborted');
error.name = 'AbortError';
reject(error);
}),
);
},
});
probe.state.follows = true;
const timeline = new AbortController();
const atTime = probe.loadAt(5_000, {
signal: timeline.signal,
replace: true,
});
// The clock goes back to live: the timeline drops what loads and resumes
// the live poll in the same turn.
probe.state.follows = false;
timeline.abort();
const live = probe.loadLivePositions({});
await assert.rejects(atTime, { name: 'AbortError' });
await live;
assert.equal(queries.length, 2);
assert.equal(Object.hasOwn(queries[1], 'atMs'), false);
assert.equal(probe.applied.at(-1).rows.length, 1);
});
+20 -5
View File
@@ -27,9 +27,20 @@ export function createIngestion({
async function loadLivePositions(viewer) {
// Following the world clock, the layer shows the snapshots loadAt applies.
if (followsClock()) return;
// Back at live, a snapshot at a time still loading no longer applies:
// it would hold the live poll back until the next refresh.
if (feed.loading && feed.loadingAtTime) dropLoad();
await loadPositions(viewer);
}
/** Let go of the load in flight, so another can start now. */
function dropLoad() {
feed.abort?.abort();
feed.loading = false;
feed.loadingAtTime = false;
feed.abort = null;
}
/**
* Apply the source's snapshot at world time `atMs` (its timeline says it
* can answer one), in place of every vessel when `replace`. Resolves
@@ -41,11 +52,7 @@ export function createIngestion({
async function loadAt(atMs, { signal = null, replace = false } = {}) {
// Whatever polls or loads for another time no longer applies: the
// timeline asks for one time at a time.
if (feed.loading) {
feed.abort?.abort();
feed.loading = false;
feed.abort = null;
}
if (feed.loading) dropLoad();
return loadPositions(readViewer(), { atMs, replace, signal });
}
@@ -53,6 +60,7 @@ export function createIngestion({
const timed = atMs !== undefined;
if (!viewer || feed.loading) return false;
feed.loading = true;
feed.loadingAtTime = timed;
feed.loadingLabel = feed.loaded ? 'refreshing...' : 'loading...';
const requestController = new AbortController();
const requestSessionId = feed.sessionId;
@@ -113,6 +121,10 @@ export function createIngestion({
ownsAisRequest(requestController, requestSessionId) &&
error?.name !== 'AbortError'
) {
// The key is missing only while the source says so; any other
// failure is an outage, not a key to add.
feed.transportStatus =
error?.code === 'key-required' ? 'missing-key' : null;
markUnavailable(error?.message || msg('AIS live load failed'));
console.warn('[Data:ais-live-vessels]', feed.error, error);
}
@@ -123,6 +135,7 @@ export function createIngestion({
feed.sessionId === requestSessionId
) {
feed.loading = false;
feed.loadingAtTime = false;
feed.loadingLabel =
feed.firstConnectPhase === 'loading' ? AIS_FIRST_CONNECT_LABEL : '';
feed.abort = null;
@@ -267,6 +280,8 @@ export function createVesselFeed() {
return {
enabled: false,
loading: false,
/** Whether the load in flight is a snapshot at a time, not a poll. */
loadingAtTime: false,
loaded: false,
stale: false,
partial: false,
+38
View File
@@ -147,3 +147,41 @@ test('vessels are asked for by the area in view, and again only when the view mo
await ingestion.refreshIfMoved();
assert.deepEqual(asked.at(-1), { maxRows: 500 });
});
test('a source refusing for want of a key leaves the feed waiting for its key', async () => {
const keyless = Object.assign(new Error('AISSTREAM_API_KEY not set'), {
code: 'key-required',
});
const probe = setup({
getSnapshot: async () => {
throw keyless;
},
});
await probe.methods.update();
assert.equal(probe.feed.transportStatus, 'missing-key');
assert.equal(probe.feed.error, 'AISSTREAM_API_KEY not set');
const down = setup({
getSnapshot: async () => {
throw new Error('feed down');
},
});
await down.methods.update();
assert.notEqual(down.feed.transportStatus, 'missing-key');
});
test('a source failing for another reason after a missing key is an outage, not a key to add', async () => {
let fail = Object.assign(new Error('AISSTREAM_API_KEY not set'), {
code: 'key-required',
});
const probe = setup({
getSnapshot: async () => {
throw fail;
},
});
await probe.methods.update();
assert.equal(probe.feed.transportStatus, 'missing-key');
fail = new Error('feed down');
await probe.methods.update();
assert.equal(probe.feed.transportStatus, null);
assert.equal(probe.feed.error, 'feed down');
});
+4
View File
@@ -133,7 +133,11 @@ export function createLifecycle({
state.activeLabelCount = 0;
state.selectedRecord = null;
state.trail = null;
state.trailHeadOff?.();
state.trailHeadOff = null;
state.trailPositions = [];
state.trailTimes = [];
state.trailBodyCount = -1;
state.trailId = null;
state.trailBackfillToken = 0;
}
+18
View File
@@ -601,3 +601,21 @@ test('a virtual aid to navigation keeps its disc and its virtual flag', async ()
assert.equal(layer.testing._vesselRecordForTest('993672009').virtual, true);
assert.match(atob(icons.item('993672009').image.split(',')[1]), /<circle/);
});
test('a feed with no AISStream key reports its key as required, and a live one does not', async () => {
let current = snapshot([], {
transportStatus: 'missing-key',
complete: false,
});
const { layer } = setup({
async getSnapshot() {
return current;
},
});
assert.equal(layer.requiresKeyId, 'aisstream');
await layer.update();
assert.equal(layer.getStats().keyRequired, true);
current = snapshot([observation('111')]);
await layer.update();
assert.equal(layer.getStats().keyRequired, false);
});
+6
View File
@@ -53,6 +53,12 @@ export const TRAIL_MAX_POINTS = 400;
export const TRAIL_MIN_MOVE_M = 25;
/** Longest head (m) drawn from the trail's last drawn fix to the vessel: a
* farther vessel (the clock jumped past the fixes the trail holds) keeps no
* head until its fixes arrive. */
export const TRAIL_HEAD_MAX_M = 20000;
/** Whether the layer shows the world clock's time instead of the live feed:
* its source declares a timeline and the clock is away from live. */
export const followsClock = (vesselState) =>
+3
View File
@@ -299,6 +299,8 @@ export function createQueries({
icon: '◭',
source: 'AISStream',
// Without an AISStream key the feed cannot start; the panel names the key.
requiresKeyId: 'aisstream',
updateInterval: REFRESH_MS,
@@ -713,6 +715,7 @@ export function createQueries({
? 'unavailable'
: undefined,
transportStatus: state.feed.transportStatus,
keyRequired: state.feed.transportStatus === 'missing-key',
lastMessageAt: state.feed.lastMessageAt,
rawRowCount: state.feed.rawRowCount,
acceptedRowCount: state.feed.acceptedRowCount,
+2 -2
View File
@@ -90,9 +90,9 @@ export function createVesselSnapshotRenderer({
},
},
);
// The selected vessel at the new time: its trail starts there.
// The selected vessel at the new time: its trail is drawn to it.
if (replace && state.selectedRecord && state.trailId)
tracking.startSelectedVesselTrail(state.selectedRecord);
tracking.retimeSelectedVesselTrail(state.selectedRecord);
state.lastVisibilityUpdate = 0;
rendering.updateVisibility(true);
}
+7
View File
@@ -97,6 +97,13 @@ export function createVesselState({ source, services }) {
trail: null,
/** @type {{x: number, y: number, z: number}[]} Chronological ECEF trail vertices (oldest first) */
trailPositions: [],
/** @type {number[]} Epoch ms of each trail vertex (NaN: undated, drawn
* at any time), parallel to trailPositions. */
trailTimes: [],
/** How many trail vertices the body draws now, or -1 before it draws. */
trailBodyCount: -1,
/** @type {(() => void)|null} Stops drawing the trail's head each frame. */
trailHeadOff: null,
/** @type {string|null} Id of the vessel that owns the active selected-vessel trail. */
trailId: null,
/** @type {number} Monotonic token — invalidates in-flight backfill responses */
+1
View File
@@ -62,6 +62,7 @@ export function createTesting({
state.trailPositions = Array.isArray(options.trailPositions)
? [...options.trailPositions]
: [];
state.trailTimes = state.trailPositions.map(() => Number.NaN);
state.feed.transportStatus = options.transportStatus || null;
state.feed.lastMessageAt = options.lastMessageAt ?? null;
state.feed.rawRowCount = Number.isFinite(options.rawRowCount)
+126 -13
View File
@@ -1,13 +1,22 @@
import { fromDegrees } from '../../geo/ellipsoid.js';
import { distance } from '../../geo/vector.js';
import { findFrame } from '../../render/rendererOf.js';
import {
TRAIL_HEIGHT_M,
TRAIL_COLOR,
TRAIL_HEAD_MAX_M,
TRAIL_MAX_POINTS,
TRAIL_MIN_MOVE_M,
followsClock,
} from './policy.js';
/** A vessel record's own fix time, epoch ms (NaN when it gives none). */
function recordFixMs(record) {
const epoch = record?.lastPositionEpoch;
if (Number.isFinite(epoch)) return epoch * 1000;
return Number.isFinite(record?.receivedAtMs) ? record.receivedAtMs : NaN;
}
export function createTracking({
vesselState,
services,
@@ -89,18 +98,94 @@ export function createTracking({
state.trailBackfillToken += 1;
state.trailId = record.id;
state.trailPositions = [];
state.trailTimes = [];
const current = vesselTrailPosition(record);
if (current) state.trailPositions.push(current);
if (current) {
state.trailPositions.push(current);
state.trailTimes.push(recordFixMs(record));
}
if (!state.trail && state.viewer) {
state.trail = createTrail(state.viewer, {
color: TRAIL_COLOR,
width: 2.5,
});
}
if (state.trail) state.trail.setPositions(state.trailPositions);
if (!state.trailHeadOff && state.viewer)
state.trailHeadOff =
findFrame(state.viewer)?.on('preRender', drawSelectedVesselTrail) ??
null;
drawTrailBody();
backfillVesselTrail(record.id, state.trailBackfillToken, record.reference);
}
/**
* The world clock moved to another time: the trail keeps what it holds,
* drawn up to the new time, until the vessel's track at that time
* replaces it. Clearing it would blank the trail at every step of the clock.
* @param {Object} record - The selected vessel at the new time.
*/
function retimeSelectedVesselTrail(record) {
if (state.trailId !== record.id || !state.trail) {
startSelectedVesselTrail(record);
return;
}
state.trailAbort?.abort();
state.trailAbort = new AbortController();
state.trailBackfillToken += 1;
drawSelectedVesselTrail();
backfillVesselTrail(record.id, state.trailBackfillToken, record.reference, {
replace: true,
});
}
/** The world time the selected vessel is drawn at; Infinity live, where
* every fix is behind it. */
function drawnTimeMs() {
return followsClock(vesselState) ? vesselState.worldNow() : Infinity;
}
/** How many trail vertices are at or before `atMs` (undated ones always). */
function bodyCountAt(atMs) {
let count = state.trailTimes.length;
while (count > 0 && state.trailTimes[count - 1] > atMs) count -= 1;
return count;
}
/** Draw the trail's body: its fixes up to the time the vessel is drawn at.
* A fix ahead of the vessel would draw the trail in front of it. */
function drawTrailBody() {
if (!state.trail) return;
state.trailBodyCount = bodyCountAt(drawnTimeMs());
state.trail.setPositions(
state.trailPositions.slice(0, state.trailBodyCount),
);
}
/** The head: the body's last vertex to where the vessel is drawn, or none
* (no vessel drawn, or one too far from the body to be on its path). */
function trailHeadPositions() {
const record = state.selectedRecord;
if (!record || record.id !== state.trailId || state.trailBodyCount < 1)
return null;
// Where its icon is drawn now (the renderer's, while it moves the icons).
const at = components.rendering.drawnPositionNow(record);
const last = state.trailPositions[state.trailBodyCount - 1];
if (!at || !last) return null;
const metres = distance(last, at);
if (metres < 1 || metres > TRAIL_HEAD_MAX_M) return null;
return [last, { x: at.x, y: at.y, z: at.z }];
}
/**
* Each frame before it draws: the body moved on when the drawn time has
* passed a fix, then the head to where the vessel is drawn now.
*/
function drawSelectedVesselTrail() {
if (!state.trail || !state.trailId) return;
if (bodyCountAt(drawnTimeMs()) !== state.trailBodyCount) drawTrailBody();
state.trail.setHead?.(trailHeadPositions());
}
/**
* Fire-and-forget backfill from the server-side per-vessel ring buffer
* (PRD F3 — "recent path" since server boot, not voyage history). Older
@@ -112,7 +197,12 @@ export function createTracking({
* @returns {Promise<void>}
*/
async function backfillVesselTrail(id, token, reference = id) {
async function backfillVesselTrail(
id,
token,
reference = id,
{ replace = false } = {},
) {
const owner = state.trailAbort;
// Following the world clock, the track ends at the world's time.
const atMs = followsClock(vesselState) ? vesselState.worldNow() : undefined;
@@ -139,6 +229,7 @@ export function createTracking({
if (state.trailId !== id) return;
const older = [];
const olderTimes = [];
for (const sample of samples) {
const lat = Number(sample?.latitude);
const lon = Number(sample?.longitude);
@@ -156,16 +247,29 @@ export function createTracking({
TRAIL_HEIGHT_M,
);
older.push(fromDegrees(lon, lat, heightM));
}
if (!older.length) return;
state.trailPositions = older.concat(state.trailPositions);
if (state.trailPositions.length > TRAIL_MAX_POINTS) {
state.trailPositions = state.trailPositions.slice(
state.trailPositions.length - TRAIL_MAX_POINTS,
olderTimes.push(
Number.isFinite(sample?.observedAtMs) ? sample.observedAtMs : NaN,
);
}
if (state.trail) state.trail.setPositions(state.trailPositions);
if (replace) {
// The track at the new time, then the vessel's own fix at it.
const record = state.selectedRecord;
const current = record?.id === id ? vesselTrailPosition(record) : null;
state.trailPositions = current ? [...older, current] : older;
state.trailTimes = current
? [...olderTimes, recordFixMs(record)]
: olderTimes;
} else {
if (!older.length) return;
state.trailPositions = older.concat(state.trailPositions);
state.trailTimes = olderTimes.concat(state.trailTimes);
}
if (state.trailPositions.length > TRAIL_MAX_POINTS) {
const drop = state.trailPositions.length - TRAIL_MAX_POINTS;
state.trailPositions = state.trailPositions.slice(drop);
state.trailTimes = state.trailTimes.slice(drop);
}
drawTrailBody();
}
/**
@@ -181,9 +285,12 @@ export function createTracking({
const last = state.trailPositions[state.trailPositions.length - 1];
if (last && distance(last, next) <= TRAIL_MIN_MOVE_M) return;
state.trailPositions.push(next);
if (state.trailPositions.length > TRAIL_MAX_POINTS)
state.trailTimes.push(recordFixMs(record));
if (state.trailPositions.length > TRAIL_MAX_POINTS) {
state.trailPositions.shift();
state.trail.setPositions(state.trailPositions);
state.trailTimes.shift();
}
drawTrailBody();
}
/**
@@ -196,6 +303,10 @@ export function createTracking({
state.trailBackfillToken += 1;
state.trailId = null;
state.trailPositions = [];
state.trailTimes = [];
state.trailBodyCount = -1;
state.trailHeadOff?.();
state.trailHeadOff = null;
if (state.trail) state.trail.clear();
}
@@ -215,6 +326,8 @@ export function createTracking({
vesselTrailPosition,
refloorVesselRecords,
startSelectedVesselTrail,
retimeSelectedVesselTrail,
drawSelectedVesselTrail,
backfillVesselTrail,
appendSelectedVesselTrailFix,
clearSelectedVesselTrail,
+134 -3
View File
@@ -5,10 +5,12 @@ import { createTracking } from './tracking.js';
import { TRAIL_HEIGHT_M, TRAIL_MAX_POINTS } from './policy.js';
/** One tracking part over a fake trail and geoid; `geoidN` is N everywhere. */
function setup({ geoidN = 40, track = null } = {}) {
function setup({ geoidN = 40, track = null, clockAt = null } = {}) {
const drawn = [];
const heads = [];
const trail = {
setPositions: (positions) => drawn.push([...positions]),
setHead: (positions) => heads.push(positions),
clear() {},
destroy() {},
};
@@ -16,7 +18,12 @@ function setup({ geoidN = 40, track = null } = {}) {
const records = [];
const vesselState = {
_geoidReady: true,
_source: { getTrack: async () => track },
_source: {
getTrack: async (reference, options) =>
typeof track === 'function' ? track(options) : track,
},
timeline: { active: () => clockAt !== null },
worldNow: () => clockAt,
state: {
viewer: {},
trail: null,
@@ -34,6 +41,17 @@ function setup({ geoidN = 40, track = null } = {}) {
},
rendering: {
getVisual: (record) => visuals.get(record) ?? record,
// Drawn where its visual says, at the trail's height in these tests.
drawnPositionNow: (record) => {
const visual = visuals.get(record);
return visual
? Cesium.Cartesian3.fromDegrees(
visual.drawnLon,
visual.drawnLat,
geoidN + TRAIL_HEIGHT_M,
)
: null;
},
anchorPosition: (record) => ({ anchoredAt: [record.lon, record.lat] }),
syncRecordIcon: (record) => synced.push(record),
forgetClockStep: () => synced.push('forgetClockStep'),
@@ -51,7 +69,16 @@ function setup({ geoidN = 40, track = null } = {}) {
layer: {},
options: {},
});
return { tracking, vesselState, drawn, synced, records, visuals, renders };
return {
tracking,
vesselState,
drawn,
heads,
synced,
records,
visuals,
renders,
};
}
const near = (a, b) =>
@@ -172,3 +199,107 @@ test('a long backfill keeps the newest TRAIL_MAX_POINTS vertices', async () => {
'the live fix stays newest',
);
});
const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
const at = (lat, lon) =>
Cesium.Cartesian3.fromDegrees(lon, lat, 40 + TRAIL_HEIGHT_M);
test('following the clock, the trail ends at the vessel: fixes after its time wait, and a head joins the last one to it', async () => {
const T = 1_800_000_000_000;
const track = {
records: [
{ latitude: 51.8, longitude: 4.0, observedAtMs: T - 120_000 },
{ latitude: 51.81, longitude: 4.0, observedAtMs: T - 60_000 },
],
};
const { tracking, vesselState, drawn, heads, visuals } = setup({
track,
clockAt: T,
});
const record = {
id: 'v',
reference: 'v',
lat: 51.83,
lon: 4.0,
lastPositionEpoch: (T + 120_000) / 1000,
};
vesselState.state.selectedRecord = record;
visuals.set(record, { drawnLat: 51.815, drawnLon: 4.0, drawnAtMs: T });
tracking.startSelectedVesselTrail(record);
await settle();
assert.equal(drawn.at(-1).length, 2, 'the fixes before the time');
assert.ok(near(drawn.at(-1)[1], at(51.81, 4.0)));
tracking.drawSelectedVesselTrail();
const head = heads.at(-1);
assert.ok(near(head[0], at(51.81, 4.0)), 'from the last drawn fix');
assert.ok(near(head[1], at(51.815, 4.0)), 'to the vessel as drawn');
// The clock passes the vessel's own fix: the body takes it on the next
// frame, and the vessel holds there.
vesselState.worldNow = () => T + 150_000;
visuals.get(record).drawnLat = 51.83;
tracking.drawSelectedVesselTrail();
assert.equal(drawn.at(-1).length, 3);
assert.equal(heads.at(-1), null, 'no head with the vessel on its fix');
});
test('a clock jump keeps the trail drawn to the new time until the track at it arrives', async () => {
const T = 1_800_000_000_000;
let release;
const later = new Promise((resolve) => (release = resolve));
let asked = 0;
const first = {
records: [
{ latitude: 51.8, longitude: 4.0, observedAtMs: T - 120_000 },
{ latitude: 51.81, longitude: 4.0, observedAtMs: T - 60_000 },
],
};
const { tracking, vesselState, drawn, visuals } = setup({
track: () => (asked++ === 0 ? first : later),
clockAt: T,
});
const record = {
id: 'v',
reference: 'v',
lat: 51.815,
lon: 4.0,
lastPositionEpoch: T / 1000,
};
vesselState.state.selectedRecord = record;
visuals.set(record, { drawnLat: 51.815, drawnLon: 4.0, drawnAtMs: T });
tracking.startSelectedVesselTrail(record);
await settle();
const before = drawn.length;
// Back a minute and a half: one fix is behind the vessel then.
vesselState.worldNow = () => T - 90_000;
tracking.retimeSelectedVesselTrail(record);
assert.ok(
drawn.slice(before).every((positions) => positions.length >= 1),
'never blanked',
);
assert.equal(drawn.at(-1).length, 1, 'cut to the new time');
release({
records: [
{ latitude: 51.79, longitude: 4.0, observedAtMs: T - 180_000 },
{ latitude: 51.8, longitude: 4.0, observedAtMs: T - 120_000 },
],
});
await settle();
assert.equal(drawn.at(-1).length, 2, 'the track at the new time');
assert.ok(near(drawn.at(-1)[0], at(51.79, 4.0)));
});
test('live, the head joins the last fix to the vessel where it is placed, and not across a jump', () => {
const { tracking, vesselState, heads, visuals } = setup();
const record = { id: 'v', reference: 'v', lat: 51.8, lon: 4.0 };
vesselState.state.selectedRecord = record;
visuals.set(record, { drawnLat: 51.801, drawnLon: 4.0 });
tracking.startSelectedVesselTrail(record);
tracking.drawSelectedVesselTrail();
assert.ok(near(heads.at(-1)[0], at(51.8, 4.0)));
assert.ok(near(heads.at(-1)[1], at(51.801, 4.0)));
// Drawn 100 km on: no head across that.
visuals.get(record).drawnLat = 52.7;
tracking.drawSelectedVesselTrail();
assert.equal(heads.at(-1), null);
});