Merge origin/main: shipwrecks, news, transit fronts, signal-lost trails and uncredited photos on the renderer's ports

Upstream's layers and changes are carried onto the ports, with no Cesium
outside src/render and no reach into the viewer:

- Shipwrecks draw as one icon set, clicked through the input dispatcher.
- News draws through draw sets, the camera port and the input dispatcher;
  its beacons pulse each frame through the frame port.
- The scene occlusion probe moves into src/render/cesium and reaches
  detection through a new application hook, createOcclusionProbe; its
  private Cesium reads go through internals.js.
- Flight and military trails, the stale and SIGNAL LOST cue, coasting and
  following the world clock run on the draw and frame ports. GPU icons
  follow the scene clock while the world clock is followed, and fade when
  stale. A report that holds is not planned again every tick.
- Vessels are keyed by their record id.

The stub boot now enables military, shipwrecks and news as well.
This commit is contained in:
Sameh Khamis committed 2026-11-10 20:03:28 -08:00
commit a755f63638
331 files changed
+40654 -1666

No files matched your search

+8 -6
View File
@@ -60,7 +60,7 @@ export function createCards({
parts.push(`${roundHeadingDegrees(direction)}°`);
return {
id: vesselOverlayEntryId(record),
actionable: Boolean(record?.mmsi),
actionable: Boolean(record?.id),
position: components.rendering.iconPosition(record),
gapPx: 10,
accent: accentForVesselType(record.type),
@@ -99,7 +99,7 @@ export function createCards({
);
return {
id: vesselOverlayEntryId(record),
actionable: Boolean(record?.mmsi),
actionable: Boolean(record?.id),
position: components.rendering.iconPosition(record),
gapPx: 12,
accent: accentForVesselType(record.type),
@@ -110,11 +110,11 @@ export function createCards({
};
}
/** Stable overlay identity for MMSI-keyed and source-retained unkeyed rows. */
/** Stable overlay identity for keyed and source-retained unkeyed rows. */
function vesselOverlayEntryId(record) {
const mmsi = String(record?.mmsi || '').trim();
if (mmsi) return `vessel:${mmsi}`;
const id = String(record?.id || '').trim();
if (id) return `vessel:${id}`;
const name = String(record?.name || 'VESSEL').trim() || 'VESSEL';
const lat = Number.isFinite(record?.lat) ? record.lat.toFixed(5) : 'x';
const lon = Number.isFinite(record?.lon) ? record.lon.toFixed(5) : 'x';
@@ -157,7 +157,9 @@ export function createCards({
function displayVesselName(record) {
const name = String(record.name || '').trim();
if (name && name !== 'VESSEL' && name !== record.mmsi) return name;
// A source may name a vessel by its id when it has no name.
if (name && name !== 'VESSEL' && name !== record.mmsi && name !== record.id)
return name;
return record.mmsi ? `MMSI ${record.mmsi}` : t('VESSEL');
}
+177
View File
@@ -0,0 +1,177 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { VesselRecords } from './records.js';
import { createIngestion, createVesselFeed } from './ingestion.js';
// Vessels follow the world clock only while their source declares a
// timeline (src/time/snapshotTimeline.js); these cover the layer's side.
const row = (mmsi, fields = {}) => ({
mmsi,
lat: 51.93,
lon: 4.05,
name: mmsi,
last_position_epoch: 1_000,
...fields,
});
function store() {
const records = new VesselRecords({ now: () => 5_000_000 });
const events = [];
const effects = {
add: (record) => events.push(['add', record.mmsi]),
beforeUpdate: () => null,
updated: (record) => events.push(['update', record.mmsi]),
remove: (record, evicted) => events.push(['remove', record.mmsi, evicted]),
removed: (mmsi) => events.push(['removed', mmsi]),
staleSelected: (record) => events.push(['stale', record.mmsi]),
};
return {
records,
events,
reconcile: (rows, options = {}) =>
records.reconcile(rows, options, effects),
};
}
test('rows at another time stand in for every vessel, selected or not', () => {
const probe = store();
probe.reconcile([row('111'), row('222')]);
const selectedRecord = probe.records.byId.get('222');
probe.reconcile([row('111', { last_position_epoch: 900 })], {
complete: false,
selectedRecord,
replace: true,
});
assert.deepEqual([...probe.records.byId.keys()], ['111']);
assert.deepEqual(probe.events.slice(-3), [
['update', '111'],
['remove', '222', true],
['removed', '222'],
]);
assert.equal(probe.records.byId.get('111').motion, null);
});
test('following the clock, a vessel keeps where its fix moved from', () => {
const probe = store();
probe.reconcile([row('111')]);
probe.reconcile([row('111', { lat: 52, last_position_epoch: 1_010 })], {
follow: true,
});
const record = probe.records.byId.get('111');
assert.deepEqual(record.motion, {
fromLat: 51.93,
fromLon: 4.05,
fromMs: 1_000_000,
toLat: 52,
toLon: 4.05,
toMs: 1_010_000,
});
probe.reconcile([row('111', { lat: 52, last_position_epoch: 1_010 })], {
follow: true,
});
assert.equal(record.motion.toMs, 1_010_000, 'a repeated fix keeps its move');
const live = store();
live.reconcile([row('111')]);
live.reconcile([row('111', { lat: 52, last_position_epoch: 1_010 })]);
assert.equal(
Object.hasOwn(live.records.byId.get('111'), 'motion'),
false,
'live records are as before',
);
});
function ingestion(source) {
const feed = createVesselFeed();
feed.enabled = true;
feed.sessionId = 1;
const applied = [];
const state = { follows: false, reloads: 0, radiusKm: 50 };
const methods = createIngestion({
feed,
readSource: () => source,
readViewer: () => ({}),
readArea: () => ({ lat: 1, lon: 2, radiusKm: state.radiusKm }),
getRowLimit: () => 500,
readCount: () => applied.at(-1)?.rows.length ?? 0,
now: () => 9999,
setSourceLabel: () => {},
applyRows: (_viewer, rows, options) => applied.push({ rows, options }),
classifySnapshot: (payload) => ({
acceptedRows: payload.rows,
acceptedRowCount: payload.rows.length,
rawRowCount: payload.rows.length,
transportStatus: payload.status,
lastMessageAt: payload.lastMessageAt,
error: null,
}),
isDefinitiveTransportFailure: () => false,
isGraceEligibleTransport: () => false,
markUnavailable: () => {},
settleFirstConnect: () => {},
followsClock: () => state.follows,
reloadAtClock: () => {
state.reloads += 1;
},
});
return { feed, applied, state, ...methods };
}
test('vessel polls carry no time; a snapshot at a time carries it and replaces', async () => {
const queries = [];
const probe = ingestion({
async getSnapshot(query) {
queries.push(query);
return {
records: [{ id: '111', latitude: 1, longitude: 2, observedAtMs: 5 }],
observedAtMs: 5,
freshness: 'current',
complete: true,
transportStatus: 'live',
};
},
});
await probe.methods.update();
assert.equal(Object.hasOwn(queries[0], 'atMs'), false);
assert.deepEqual(probe.applied[0].options, { complete: true });
probe.state.follows = true;
await probe.methods.update();
assert.equal(queries.length, 1, 'no poll while following');
assert.equal(await probe.loadAt(5_000, { replace: true }), true);
assert.equal(queries[1].atMs, 5_000);
assert.deepEqual(probe.applied[1].options, { complete: true, replace: true });
assert.equal(probe.feed.lastUpdate, 5);
// Following the clock, a moved view reloads the time shown.
probe.state.radiusKm = 2_000;
await probe.refreshIfMoved({});
assert.equal(probe.state.reloads, 1);
assert.equal(queries.length, 2);
});
test('an empty vessel snapshot at another time shows no vessels', async () => {
const probe = ingestion({
async getSnapshot() {
return { records: [], observedAtMs: 5, freshness: 'current' };
},
});
probe.state.follows = true;
await probe.loadAt(5_000, { replace: true });
assert.deepEqual(probe.applied, [
{ rows: [], options: { complete: true, replace: true } },
]);
});
test('a vessel snapshot at a time the source drops for a newer one is no failure', async () => {
const probe = ingestion({
async getSnapshot() {
throw new DOMException('Superseded', 'AbortError');
},
});
probe.state.follows = true;
await assert.rejects(probe.loadAt(5_000, { replace: true }), {
name: 'AbortError',
});
assert.equal(probe.feed.error, null);
assert.equal(probe.feed.loading, false);
assert.deepEqual(probe.applied, []);
});
+4 -4
View File
@@ -99,7 +99,7 @@ function finiteOrNull(value) {
* @returns {object|null} Subject info, or null without a usable fix.
*/
export function vesselCockpitInfo(record) {
if (!record?.mmsi) return null;
if (!record?.id) return null;
const latitude = Number(record.lat);
const longitude = Number(record.lon);
if (!Number.isFinite(latitude) || !Number.isFinite(longitude)) return null;
@@ -111,9 +111,9 @@ export function vesselCockpitInfo(record) {
return {
kind: 'vessel',
layerId: VESSEL_COCKPIT_LAYER_ID,
id: String(record.mmsi),
mmsi: String(record.mmsi),
name: String(record.name || record.mmsi),
id: String(record.id),
mmsi: String(record.mmsi || ''),
name: String(record.name || record.mmsi || record.id),
type: String(record.type || ''),
typeLabel: displayVesselType(record.type),
destination: String(record.destination || '').trim(),
+23 -3
View File
@@ -43,6 +43,7 @@ test('an unknown or missing type has no eye height of its own', () => {
test('vessel info faces the true heading and moves along course over ground', () => {
const info = vesselCockpitInfo({
id: '211000000',
mmsi: '211000000',
name: 'NORDIC STAR',
type: '70',
@@ -58,6 +59,7 @@ test('vessel info faces the true heading and moves along course over ground', ()
assert.equal(info.kind, 'vessel');
assert.equal(info.layerId, VESSEL_COCKPIT_LAYER_ID);
assert.equal(info.id, '211000000');
assert.equal(info.mmsi, '211000000');
assert.equal(info.typeLabel, 'CARGO');
assert.equal(info.track, 90);
assert.equal(info.motionCourse, 95);
@@ -70,7 +72,7 @@ test('vessel info faces the true heading and moves along course over ground', ()
});
test('a missing heading or course falls back to the other', () => {
const base = { mmsi: '1', lat: 1, lon: 1, speed: 3 };
const base = { id: '1', mmsi: '1', lat: 1, lon: 1, speed: 3 };
assert.equal(vesselCockpitInfo({ ...base, course: 40 }).track, 40);
assert.equal(vesselCockpitInfo({ ...base, heading: 50 }).motionCourse, 50);
const neither = vesselCockpitInfo(base);
@@ -79,7 +81,7 @@ test('a missing heading or course falls back to the other', () => {
});
test('the subject says whether its track is the heading or the course', () => {
const base = { mmsi: '1', lat: 1, lon: 1, speed: 3 };
const base = { id: '1', mmsi: '1', lat: 1, lon: 1, speed: 3 };
assert.equal(
vesselCockpitInfo({ ...base, heading: 50, course: 40 }).trackSource,
'heading',
@@ -99,11 +101,12 @@ test('the subject says whether its track is the heading or the course', () => {
test('a vessel without identity or position is not a subject', () => {
assert.equal(vesselCockpitInfo(null), null);
assert.equal(vesselCockpitInfo({ lat: 1, lon: 1 }), null);
assert.equal(vesselCockpitInfo({ mmsi: '1', lat: 'x', lon: 1 }), null);
assert.equal(vesselCockpitInfo({ id: '1', mmsi: '1', lat: 'x', lon: 1 }), null);
});
test('a vessel missing from recent refreshes reads as stale', () => {
const info = vesselCockpitInfo({
id: '1',
mmsi: '1',
lat: 1,
lon: 1,
@@ -111,3 +114,20 @@ test('a vessel missing from recent refreshes reads as stale', () => {
});
assert.equal(info.stale, true);
});
test('a vessel is the subject by its id; an MMSI is only shown when known', () => {
const info = vesselCockpitInfo({
id: 'b6a7c1e2-provider-id',
mmsi: '',
name: 'NORDIC STAR',
lat: 54.5,
lon: 10.2,
});
assert.equal(info.id, 'b6a7c1e2-provider-id');
assert.equal(info.mmsi, '');
assert.equal(
vesselCockpitInfo({ mmsi: '211000000', lat: 54.5, lon: 10.2 }),
null,
'a record with no id is unkeyed and cannot be ridden',
);
});
+1 -1
View File
@@ -45,7 +45,7 @@ export function createEvidence({
const position = drawn ? visual.position : null;
const screen = position ? query?.project(position) : null;
return {
id: record.mmsi,
id: record.id,
show: drawn && visual.visible === true,
alpha: drawn ? state.icons.focus(visual.iconId) : null,
x: screen?.x ?? null,
+27
View File
@@ -10,6 +10,9 @@ import { createCards } from './cards.js';
import { createTesting } from './testing.js';
import { createEvidence } from './evidence.js';
import { createQueries } from './queries.js';
import { followsClock } from './policy.js';
import { createSnapshotTimeline } from '../../time/snapshotTimeline.js';
import { worldClock } from '../../time/worldClock.js';
/** Compose one vessel layer with application-owned scene services. */
export function createVesselLayer({ source, services, options = {} } = {}) {
const vesselState = createVesselState({ source, services });
@@ -31,6 +34,7 @@ export function createVesselLayer({ source, services, options = {} } = {}) {
tracking: parts.tracking,
selection: parts.selection,
cards: parts.cards,
followsClock: () => followsClock(vesselState),
});
parts.ingestion = createIngestion({
@@ -50,6 +54,29 @@ export function createVesselLayer({ source, services, options = {} } = {}) {
setSourceLabel: (source) => {
layer.source = source;
},
followsClock: () => followsClock(vesselState),
reloadAtClock: () => vesselState.timeline.reload(),
});
// Vessels follow the world clock while the source declares a timeline.
vesselState.timeline = createSnapshotTimeline({
id: 'ais-live-vessels',
clock: worldClock,
source: () => vesselState._source,
load: (atMs, { signal, replace }) =>
parts.ingestion.loadAt(atMs, { signal, replace }),
clear: () => {
const { state } = vesselState;
if (state.viewer)
parts.snapshots.reconcileVessels(state.viewer, [], {
complete: true,
replace: true,
});
state.feed.count = state.records.all.length;
state.feed.lastUpdate = null;
},
resumeLive: () => {
void parts.ingestion.loadLivePositions(vesselState.state.viewer);
},
});
Object.assign(
layer,
+60 -7
View File
@@ -21,9 +21,36 @@ export function createIngestion({
settleFirstConnect,
now,
setSourceLabel,
followsClock = () => false,
reloadAtClock = () => {},
}) {
async function loadLivePositions(viewer) {
if (!viewer || feed.loading) return;
// Following the world clock, the layer shows the snapshots loadAt applies.
if (followsClock()) return;
await loadPositions(viewer);
}
/**
* Apply the source's snapshot at world time `atMs` (its timeline says it
* can answer one), in place of every vessel when `replace`. Resolves
* whether it was applied.
* @param {number} atMs
* @param {{signal?: AbortSignal|null, replace?: boolean}} [options]
* @returns {Promise<boolean>}
*/
async function loadAt(atMs, { signal = null, replace = false } = {}) {
// Whatever polls or loads for another time no longer applies.
if (replace && feed.loading) {
feed.abort?.abort();
feed.loading = false;
feed.abort = null;
}
return loadPositions(readViewer(), { atMs, replace, signal });
}
async function loadPositions(viewer, { atMs, replace = false, signal } = {}) {
const timed = atMs !== undefined;
if (!viewer || feed.loading) return false;
feed.loading = true;
feed.loadingLabel = feed.loaded ? 'refreshing...' : 'loading...';
const requestController = new AbortController();
@@ -33,21 +60,29 @@ export function createIngestion({
try {
// Combine the layer's teardown-abort with a hard timeout so a hung upstream
// can't wedge the poll indefinitely (parity with the track fetch + flights).
const signal =
const requestSignal =
typeof AbortSignal.any === 'function'
? AbortSignal.any([
requestController.signal,
AbortSignal.timeout(10000),
...(signal ? [signal] : []),
])
: requestController.signal;
// Ask for the vessels in view; a wide view asks for every vessel.
const area = readArea(viewer);
feed.lastArea = area;
const snapshot = await readSource().getSnapshot(
{ maxRows: getRowLimit(), ...(area ? { area } : {}) },
{ signal },
{
maxRows: getRowLimit(),
...(area ? { area } : {}),
...(timed ? { atMs } : {}),
},
{ signal: requestSignal },
);
if (!ownsAisRequest(requestController, requestSessionId)) return;
if (!ownsAisRequest(requestController, requestSessionId)) return false;
if (signal?.aborted) return false;
// The clock left the live edge while this poll was out.
if (!timed && followsClock()) return false;
setSourceLabel(snapshot.source);
// Map observations into the existing display store; source fields stop here.
applyAisFeedSnapshot(viewer, {
@@ -67,8 +102,12 @@ export function createIngestion({
: new Date(snapshot.observedAtMs).toISOString(),
silentForMs: snapshot.silentForMs,
reconnectAttempt: snapshot.reconnectAttempt,
...(replace && { replace }),
});
return true;
} catch (error) {
// A snapshot at a time the source dropped for a newer one is no failure.
if (timed && error?.name === 'AbortError') throw error;
if (
ownsAisRequest(requestController, requestSessionId) &&
error?.name !== 'AbortError'
@@ -76,6 +115,7 @@ export function createIngestion({
markUnavailable(error?.message || msg('AIS live load failed'));
console.warn('[Data:ais-live-vessels]', feed.error, error);
}
return false;
} finally {
if (
feed.abort === requestController &&
@@ -113,6 +153,9 @@ export function createIngestion({
feed.acceptedRowCount = snapshot.acceptedRowCount;
feed.partial = payload?.complete === false;
// At another time, a snapshot with no vessels shows none, not the last.
if (payload?.replace && snapshot.acceptedRowCount === 0)
applyRows(viewer, [], { complete: true, replace: true });
if (snapshot.acceptedRowCount === 0 && !snapshot.emptyCoverage) {
feed.count = readCount();
feed.stale = feed.count > 0 || Boolean(payload?.refreshing);
@@ -139,6 +182,7 @@ export function createIngestion({
settleFirstConnect('ready');
applyRows(viewer, snapshot.acceptedRows, {
complete: payload?.complete !== false,
...(payload?.replace && { replace: true }),
});
feed.count = readCount();
feed.stale =
@@ -157,9 +201,11 @@ export function createIngestion({
return { reconciled: true, ...snapshot };
}
/** The layer's row for a source record: keyed by its id, MMSI shown when known. */
function vesselDisplayRow(record) {
return {
mmsi: record.id,
id: record.id,
mmsi: String(record.mmsi ?? '').trim(),
reference: record.reference,
lat: record.latitude,
lon: record.longitude,
@@ -180,10 +226,16 @@ export function createIngestion({
}
/** Ask again when the view moved away from the last area asked for. */
function refreshIfMoved(viewer) {
if (!feed.enabled || feed.loading) return Promise.resolve();
const following = followsClock();
if (!feed.enabled || (feed.loading && !following)) return Promise.resolve();
const active = viewer || readViewer();
if (!viewAreaMovedEnough(feed.lastArea ?? null, readArea(active)))
return Promise.resolve();
// Following the world clock, the new area is asked for at the same time.
if (following) {
reloadAtClock();
return Promise.resolve();
}
return loadLivePositions(active);
}
@@ -196,6 +248,7 @@ export function createIngestion({
return {
loadLivePositions,
loadAt,
refreshIfMoved,
ownsAisRequest,
applyAisFeedSnapshot,
+7 -4
View File
@@ -116,7 +116,7 @@ export function createLifecycle({
state.feed.abort = null;
state.icons = null;
state.records.all = [];
state.records.byMmsi = new Map();
state.records.byId = new Map();
state.records.unkeyed = [];
state.clickSubscription = null;
state.keyTarget = null;
@@ -132,7 +132,7 @@ export function createLifecycle({
state.selectedRecord = null;
state.trail = null;
state.trailPositions = [];
state.trailMmsi = null;
state.trailId = null;
state.trailBackfillToken = 0;
}
const methods = {
@@ -185,9 +185,9 @@ export function createLifecycle({
/* grid failed to load — anchors stay at ellipsoid 0 */
});
}
// Pick-ownership (H2): a vessel icon's pick id is its row id, the MMSI.
// Pick-ownership (H2): a vessel icon's pick id is its row id, the record's id.
registerPickOwner('ais-live-vessels', (pickedId) =>
state.records.byMmsi.has(pickedId),
state.records.byId.has(pickedId),
);
// Vessels are asked for by view, so ask again when the view moves away.
removeViewListener();
@@ -196,10 +196,12 @@ export function createLifecycle({
state.feed.removeViewListener = camera.on('moveEnd', () => {
components.ingestion.refreshIfMoved(activeViewer);
});
vesselState.timeline?.start();
return components.ingestion.loadLivePositions(activeViewer);
},
disable() {
vesselState.timeline?.stop();
removeViewListener();
state.feed.enabled = false;
invalidateAisSession();
@@ -220,6 +222,7 @@ export function createLifecycle({
},
destroy(viewer) {
vesselState.timeline?.stop();
removeViewListener();
const activeViewer = viewer || state.viewer;
invalidateAisSession();
+62
View File
@@ -0,0 +1,62 @@
/**
* Where a vessel is at world time `tMs` while the layer follows the world
* clock: between the fix it moved from and the fix it moved to, along the
* great circle; at the earlier fix before it, at the newer fix after it. A
* vessel is never projected past its newest fix.
* @param {{lat: number, lon: number, motion?: {fromLat: number, fromLon: number,
* fromMs: number, toLat: number, toLon: number, toMs: number}|null}} record
* @param {number} tMs
* @returns {{lat: number, lon: number}}
*/
export function vesselPositionAt(record, tMs) {
const motion = record?.motion;
if (
!motion ||
!Number.isFinite(tMs) ||
!(motion.toMs > motion.fromMs) ||
tMs >= motion.toMs
)
return record;
if (tMs <= motion.fromMs) return { lat: motion.fromLat, lon: motion.fromLon };
const fraction = (tMs - motion.fromMs) / (motion.toMs - motion.fromMs);
return greatCircleAt(
motion.fromLat,
motion.fromLon,
motion.toLat,
motion.toLon,
fraction,
);
}
const RAD = Math.PI / 180;
/** The point `fraction` of the way from one position to another. */
function greatCircleAt(lat1, lon1, lat2, lon2, fraction) {
const p1 = unit(lat1, lon1);
const p2 = unit(lat2, lon2);
const dot = Math.min(
1,
Math.max(-1, p1[0] * p2[0] + p1[1] * p2[1] + p1[2] * p2[2]),
);
const angle = Math.acos(dot);
if (angle < 1e-12) return { lat: lat2, lon: lon2 };
const a = Math.sin((1 - fraction) * angle) / Math.sin(angle);
const b = Math.sin(fraction * angle) / Math.sin(angle);
const x = a * p1[0] + b * p2[0];
const y = a * p1[1] + b * p2[1];
const z = a * p1[2] + b * p2[2];
return {
lat: Math.atan2(z, Math.hypot(x, y)) / RAD,
lon: Math.atan2(y, x) / RAD,
};
}
function unit(lat, lon) {
const phi = lat * RAD;
const lambda = lon * RAD;
return [
Math.cos(phi) * Math.cos(lambda),
Math.cos(phi) * Math.sin(lambda),
Math.sin(phi),
];
}
+31
View File
@@ -0,0 +1,31 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { vesselPositionAt } from './motion.js';
const record = {
lat: 1,
lon: 1,
motion: {
fromLat: 0,
fromLon: 0,
fromMs: 1_000,
toLat: 1,
toLon: 1,
toMs: 3_000,
},
};
test('a vessel holds at its fixes and moves between them along the great circle', () => {
assert.deepEqual(vesselPositionAt(record, 500), { lat: 0, lon: 0 });
assert.equal(vesselPositionAt(record, 3_000), record);
assert.equal(vesselPositionAt(record, 9_000), record, 'never projected past');
const half = vesselPositionAt(record, 2_000);
assert.ok(Math.abs(half.lat - 0.5) < 1e-3);
assert.ok(Math.abs(half.lon - 0.5) < 1e-3);
});
test('a vessel with no move is at its record', () => {
const still = { lat: 4, lon: 5 };
assert.equal(vesselPositionAt(still, 2_000), still);
assert.equal(vesselPositionAt({ ...still, motion: null }, 2_000).lat, 4);
});
+95 -2
View File
@@ -101,7 +101,7 @@ test('vessel construction is inert and each instance owns its records, icon cach
const two = createVesselState({ source, services: services() });
for (const key of ['state', 'shipIconCache'])
assert.notEqual(one[key], two[key]);
assert.notEqual(one.state.records.byMmsi, two.state.records.byMmsi);
assert.notEqual(one.state.records.byId, two.state.records.byId);
assert.notEqual(one.state.feed, two.state.feed);
assert.notEqual(one.state.records.all, two.state.records.all);
assert.notEqual(one.state.records.unkeyed, two.state.records.unkeyed);
@@ -275,7 +275,7 @@ test('partial-feed expiry releases a selected vessel and its pending trail', asy
layer.selectById('222');
current = snapshot([observation('111')], { complete: false });
await layer.update();
assert.equal(layer.getSelectedInfo().mmsi, '222');
assert.equal(layer.getSelectedInfo().id, '222');
assert.equal(signal.aborted, false);
advance(5 * 60 * 1000);
await layer.update();
@@ -463,3 +463,96 @@ test('vessel stats name the provider the last snapshot reported', async () => {
await layer.update();
assert.equal(layer.getStats().source, 'Datalastic');
});
test('two vessels sharing an MMSI under different ids stay two vessels', async () => {
const shared = (id, longitude) => ({
...observation(id),
mmsi: '123456789',
longitude,
name: `HULL ${id}`,
});
const { layer, icons } = setup({
getSnapshot: async () =>
snapshot([shared('hull-a', 4.05), shared('hull-b', 4.25)]),
});
await layer.update();
assert.equal(layer.getStats().count, 2);
assert.equal(icons.size, 2);
assert.equal(layer.hasContact('hull-a'), true);
assert.equal(layer.hasContact('hull-b'), true);
// An MMSI is not a key, but a link naming one still finds a vessel with it.
assert.equal(layer.hasContact('123456789'), true);
assert.equal(layer.hasContact('987654321'), false);
assert.deepEqual(
layer
.getAllPositions()
.map(({ id }) => id)
.sort(),
['hull-a', 'hull-b'],
);
assert.equal(layer.selectById('hull-b'), true);
assert.deepEqual(
[layer.getSelectedInfo().id, layer.getSelectedInfo().mmsi],
['hull-b', '123456789'],
);
assert.equal(
layer.selectById('123456789'),
true,
'a link naming the MMSI selects a vessel with it',
);
assert.equal(layer.getSelectedInfo().mmsi, '123456789');
assert.equal(layer.selectById('hull-b'), true);
// A lookup by the shared MMSI still finds a vessel that has it.
assert.equal(layer.findByQuery('123456789').mmsi, '123456789');
});
test('a vessel with an id and no MMSI renders and can be selected', async () => {
const { layer, icons } = setup({
getSnapshot: async () =>
snapshot([{ ...observation('7f3c9a10-provider-id'), name: 'NO MMSI' }]),
});
await layer.update();
// Its icon row is keyed by its id.
assert.deepEqual(icons.ids(), ['7f3c9a10-provider-id']);
assert.equal(layer.findByQuery('7f3c9a10-provider-id').mmsi, '');
assert.equal(layer.selectById('7f3c9a10-provider-id'), true);
const info = layer.getSelectedInfo();
assert.equal(info.id, '7f3c9a10-provider-id');
assert.equal(info.mmsi, '');
assert.equal(layer.getCockpitSubject().id, '7f3c9a10-provider-id');
assert.equal(layer.testing._getVesselStateForTest().trailId, info.id);
});
test('a vessel keyed by a UUID is found in any case and names its drawn fix', async () => {
const uuid = '0770e3ca-b896-c307-f499-4f9df2b8f86b';
const { layer } = setup({
getSnapshot: async () =>
snapshot([{ ...observation(uuid.toUpperCase()), name: 'UUID HULL' }]),
});
await layer.update();
assert.equal(layer.getSelectedFix(), null, 'nothing selected');
// A share link carries the UUID in lowercase.
assert.equal(layer.hasContact(uuid), true);
assert.equal(layer.selectById(uuid), true);
const fix = layer.getSelectedFix();
assert.equal(fix.id, uuid.toUpperCase());
assert.ok(fix.position, 'where the vessel is drawn');
assert.equal(fix.observedAtMs, 500);
assert.equal(layer.hasContact('0770e3ca-b896-c307-f499-4f9df2b8f86c'), false);
});
test('AIS feed rows stay keyed by their MMSI', async () => {
const { vesselSnapshot } = await import('../../sources/live/vessels.js');
const row = { mmsi: '235000001', lat: 51.93, lon: 4.05, name: 'TERN' };
const { layer } = setup({
getSnapshot: async () =>
vesselSnapshot({ rows: [row, { ...row, lon: 4.2 }], status: 'live' }),
});
await layer.update();
assert.equal(layer.getStats().count, 1, 'one MMSI is one vessel on AIS');
assert.equal(layer.selectById('235000001'), true);
assert.deepEqual(
[layer.getSelectedInfo().id, layer.getSelectedInfo().mmsi],
['235000001', '235000001'],
);
});
+5
View File
@@ -53,6 +53,11 @@ export const TRAIL_MAX_POINTS = 400;
export const TRAIL_MIN_MOVE_M = 25;
/** 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) =>
vesselState.timeline?.active() === true;
export const DEFAULT_AIS_RUNTIME = Object.freeze({
now: () => Date.now(),
setTimeout: (callback, delayMs) => setTimeout(callback, delayMs),
+116 -49
View File
@@ -24,7 +24,12 @@ import {
REFRESH_MS,
FOCUS_EVIDENCE_DEV,
VESSEL_LIFT_M,
followsClock,
} from './policy.js';
import { VESSEL_OVERLAY_SOURCE_ID } from '../../data/vesselLabels.js';
const UUID_KEY =
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
export function createQueries({
vesselState,
@@ -36,6 +41,28 @@ export function createQueries({
const { state } = vesselState;
const { formatKnots } = services.labels;
/**
* The vessel keyed `id`, else the first whose MMSI is `id`: a link or a
* caller that names a vessel by its MMSI still finds it. A share link
* carries a UUID key in lowercase, so a UUID matches in any case.
* @param {string} id
* @returns {object|null}
*/
function recordFor(id) {
const record = state.records.byId?.get(id);
if (record) return record;
if (UUID_KEY.test(id)) {
const wanted = id.toLowerCase();
for (const candidate of state.records.byId?.values() ?? [])
if (candidate.id.toLowerCase() === wanted) return candidate;
return null;
}
if (!/^\d{1,10}$/.test(id)) return null;
for (const candidate of state.records.byId?.values() ?? [])
if (candidate.mmsi === id) return candidate;
return null;
}
/**
* Seconds until the server's next reconnect attempt, or 0 when none is
* scheduled. Mirrors the flights layer's `retryInSec` chip affordance.
@@ -173,8 +200,9 @@ export function createQueries({
* fields are null, never NaN/undefined. navStatus is always null: the
* /api/vessels proxy does not surface AIS NavigationalStatus, so it
* cannot be derived client-side.
* @param {Object|null|undefined} record - `state.records.byMmsi`/`state.records.all` entry.
* @returns {{id: string|null, mmsi: string|null, name: string|null,
* @param {Object|null|undefined} record - `state.records.byId`/`state.records.all` entry.
* @returns {{id: string|null, vesselId: string|null, mmsi: string|null,
* name: string|null,
* lat: number|null, lon: number|null, speedKts: number|null,
* courseDeg: number|null, shipType: string|null, destination: string|null,
* navStatus: null}}
@@ -186,10 +214,14 @@ export function createQueries({
const t = String(v ?? '').trim();
return t || null;
};
const vesselId = text(record?.id);
const mmsi = text(record?.mmsi);
const name = text(record?.name);
return {
id: name || mmsi,
// A display label, as every layer's analyst `id` is; `vesselId` is the
// key and `mmsi` the vessel's MMSI when known.
id: name || mmsi || vesselId,
vesselId,
mmsi,
name,
lat: num(record?.lat),
@@ -223,32 +255,32 @@ export function createQueries({
* trail picks as no-ops. The interaction wire also reserves sibling-owned
* picks before this reducer so their camera action cannot mutate AIS state.
*
* @param {{selectedMmsi?: string|number|null, pickedMmsi?: string|number|null,
* @param {{selectedId?: string|number|null, pickedId?: string|number|null,
* gesture?: 'click'|'escape'}} input - Current selection plus owned pick.
* @returns {{action: 'none'|'select'|'deselect'}}
*/
function reduceVesselSelection(input = {}) {
const selectedMmsi = normalizeSelectionMmsi(input.selectedMmsi);
const pickedMmsi = normalizeSelectionMmsi(input.pickedMmsi);
const selectedId = normalizeSelectionId(input.selectedId);
const pickedId = normalizeSelectionId(input.pickedId);
const gesture = input.gesture || 'click';
if (gesture === 'escape') {
return selectedMmsi ? { action: 'deselect' } : { action: 'none' };
return selectedId ? { action: 'deselect' } : { action: 'none' };
}
if (gesture !== 'click') {
return { action: 'none' };
}
if (pickedMmsi) {
if (pickedMmsi === selectedMmsi) {
if (pickedId) {
if (pickedId === selectedId) {
return { action: 'none' };
}
return { action: 'select' };
}
return selectedMmsi ? { action: 'deselect' } : { action: 'none' };
return selectedId ? { action: 'deselect' } : { action: 'none' };
}
function normalizeSelectionMmsi(value) {
function normalizeSelectionId(value) {
if (value === null || value === undefined) return null;
const text = String(value).trim();
return text || null;
@@ -273,9 +305,10 @@ export function createQueries({
statsRefreshInterval: 1000,
/**
* Find a vessel by exact MMSI or case-insensitive name substring.
* @param {string|number} query MMSI or partial vessel name.
* @returns {{ mmsi: string, name: string, position: {x: number, y: number, z: number}, latitude: number, longitude: number, speedKt: number|null, course: number|null, type: string }|null}
* Find a vessel by its exact id, exact MMSI or case-insensitive name
* substring. Vessels can share an MMSI; the first that has it is found.
* @param {string|number} query Vessel id, MMSI or partial vessel name.
* @returns {{ id: string, mmsi: string, name: string, position: {x: number, y: number, z: number}, latitude: number, longitude: number, speedKt: number|null, course: number|null, type: string }|null}
*/
findByQuery(query) {
if (query === null || query === undefined) return null;
@@ -284,9 +317,9 @@ export function createQueries({
const q = String(query).trim();
if (!q) return null;
let record = null;
if (/^\d+$/.test(q)) {
record = state.records.byMmsi.get(q) || null;
let record = state.records.byId.get(q) || null;
if (!record && /^\d+$/.test(q)) {
record = records.find((r) => r.mmsi === q) || null;
}
if (!record) {
const lower = q.toLowerCase();
@@ -302,6 +335,7 @@ export function createQueries({
const position = components.rendering.iconPosition(record);
if (!position) return null;
return {
id: record.id,
mmsi: record.mmsi,
name: record.name,
position,
@@ -318,7 +352,7 @@ export function createQueries({
* @param {{x: number, y: number, z: number}} centerCartesian ECEF centre of the search.
* @param {number} rangeM Max distance in meters (non-finite = unbounded).
* @param {number} [maxCount=25] Maximum entries to return.
* @returns {Array<{ mmsi: string, name: string, position: {x: number, y: number, z: number}, distanceM: number }>}
* @returns {Array<{ id: string, mmsi: string, name: string, position: {x: number, y: number, z: number}, distanceM: number }>}
*/
getNearby(centerCartesian, rangeM, maxCount = 25) {
const records = state.records.all;
@@ -337,6 +371,7 @@ export function createQueries({
const distanceM = distance(centerCartesian, position);
if (!Number.isFinite(distanceM) || distanceM > range) continue;
entries.push({
id: record.id,
mmsi: record.mmsi,
name: record.name,
position,
@@ -358,7 +393,7 @@ export function createQueries({
* @returns {Array<{ id: string, name: string, latitude: number,
* longitude: number, course: number|null, heading: number|null,
* type: string, color: string, stale: boolean }>} Empty while the
* layer is off. A ship with no MMSI has an `unkeyed:` id.
* layer is off. A ship with no id has an `unkeyed:` id.
*/
getRadarContacts(lat, lon, rangeM, maxCount = 60) {
const records = state.records.all;
@@ -368,7 +403,7 @@ export function createQueries({
const cap =
Number.isFinite(maxCount) && maxCount > 0 ? Math.floor(maxCount) : 60;
const center = { lat, lon };
const subject = state.cockpitSubjectMmsi;
const subject = state.cockpitSubjectId;
const finite = (value) => {
if (value === null || value === undefined || value === '') return null;
const number = Number(value);
@@ -377,7 +412,7 @@ export function createQueries({
const entries = [];
records.forEach((record, index) => {
if (subject && String(record.mmsi) === subject) return;
if (subject && String(record.id) === subject) return;
const distanceM = greatCircleMeters(center, {
lat: record.lat,
lon: record.lon,
@@ -387,8 +422,8 @@ export function createQueries({
});
entries.sort((a, b) => a.distanceM - b.distanceM);
return entries.slice(0, cap).map(({ record, index }) => ({
// A ship with no MMSI still needs a key of its own on the scope.
id: record.mmsi ? String(record.mmsi) : `unkeyed:${index}`,
// A ship with no id still needs a key of its own on the scope.
id: record.id ? String(record.id) : `unkeyed:${index}`,
name: String(record.name || record.mmsi || ''),
latitude: record.lat,
longitude: record.lon,
@@ -409,22 +444,22 @@ export function createQueries({
* Whether this layer still carries a vessel, in O(1).
*
* Mirror of `flights.hasContact`: presence consumers must not infer absence
* from the capped `getAllPositions` rows. `vesselMap` is MMSI-keyed.
* from the capped `getAllPositions` rows. Records are keyed by id.
* A disabled layer keeps its records, so it must decline rather than answer
* from data the user can no longer see.
* @param {string} mmsi Vessel identifier.
* @param {string} id Vessel id.
* @returns {boolean|null} Presence, or null when the layer is disabled or
* holds no data and therefore cannot answer.
*/
hasContact(mmsi) {
hasContact(id) {
if (
!state.feed.enabled ||
!state.records.byMmsi ||
state.records.byMmsi.size === 0
!state.records.byId ||
state.records.byId.size === 0
)
return null;
if (!mmsi) return false;
return state.records.byMmsi.has(String(mmsi).trim());
if (!id) return false;
return Boolean(recordFor(String(id).trim()));
},
getAllPositions(maxCount = 800) {
@@ -439,8 +474,8 @@ export function createQueries({
const position = components.rendering.iconPosition(record);
if (!position) continue;
result.push({
id: record.mmsi,
label: record.name || record.mmsi,
id: record.id,
label: record.name || record.mmsi || record.id,
position,
latitude: record.lat,
longitude: record.lon,
@@ -473,16 +508,16 @@ export function createQueries({
},
/**
* Select a vessel by MMSI via the same path as a map click
* (highlight + HUD update).
* @param {string|number} mmsi Vessel MMSI.
* Select a vessel by id via the same path as a map click
* (highlight + HUD update). An AIS feed's vessels are keyed by MMSI.
* @param {string|number} id Vessel id.
* @returns {boolean} True if a matching vessel was selected.
*/
selectById(mmsi) {
if (mmsi === null || mmsi === undefined) return false;
const target = String(mmsi).trim();
selectById(id) {
if (id === null || id === undefined) return false;
const target = String(id).trim();
if (!target) return false;
const record = state.records.byMmsi.get(target);
const record = recordFor(target);
if (!record) return false;
components.selection.selectVessel(record);
return true;
@@ -499,12 +534,13 @@ export function createQueries({
/**
* Get info about the currently selected vessel.
* @returns {{ mmsi: string, name: string, latitude: number, longitude: number, speedKt: number|null, course: number|null, type: string }|null}
* @returns {{ id: string, mmsi: string, name: string, latitude: number, longitude: number, speedKt: number|null, course: number|null, type: string }|null}
*/
getSelectedInfo() {
const record = state.selectedRecord;
if (!record) return null;
return {
id: record.id,
mmsi: record.mmsi,
name: record.name,
latitude: record.lat,
@@ -515,6 +551,32 @@ export function createQueries({
};
},
/**
* Where the selected vessel is drawn now, for a share link that names it:
* its id, its drawn position and the time that position stands for (the
* world time while the layer follows the clock, else its fix's time).
* @returns {{ id: string, position: {x: number, y: number, z: number}, observedAtMs: number|null }|null}
* Null when the layer is off, nothing is selected or it is not drawn.
*/
getSelectedFix() {
if (!state.feed.enabled) return null;
const record = state.selectedRecord;
if (!record?.id) return null;
const position = components.rendering.iconPosition(record);
if (!position) return null;
const fixEpoch = record.lastPositionEpoch;
const observedAtMs = followsClock(vesselState)
? vesselState.worldNow()
: Number.isFinite(fixEpoch)
? fixEpoch * 1000
: (record.fixReceivedAtMs ?? null);
return {
id: record.id,
position,
observedAtMs: Number.isFinite(observedAtMs) ? observedAtMs : null,
};
},
/**
* Describe the selected vessel for the Cockpit bridge view.
* @returns {object|null} `vesselCockpitInfo` fields plus `seaSurfaceHeightM`
@@ -540,16 +602,16 @@ export function createQueries({
/**
* Mark the vessel whose bridge the Cockpit camera occupies, or release it.
* Its sprite, card and detection bracket stay hidden while it is held.
* @param {string|number|null} mmsi Subject MMSI, or null to release.
* @param {string|number|null} id Subject vessel id, or null to release.
* @returns {boolean} Always true.
*/
setCockpitSubject(mmsi) {
const next = normalizeSelectionMmsi(mmsi);
if (state.cockpitSubjectMmsi === next) return true;
state.cockpitSubjectMmsi = next;
setCockpitSubject(id) {
const next = normalizeSelectionId(id);
if (state.cockpitSubjectId === next) return true;
state.cockpitSubjectId = next;
// The ridden ship's trail runs from under the eye: hidden, its history
// kept, while the bridge holds the ship it belongs to.
state.trail?.setVisible?.(!next || next !== state.trailMmsi);
state.trail?.setVisible?.(!next || next !== state.trailId);
components.rendering.updateVisibility(true);
return true;
},
@@ -571,7 +633,7 @@ export function createQueries({
* @param {Object} [options={}] - Options from the detection system.
* @param {number} [options.maxCount] - Maximum objects to return (defaults to all).
* @param {number} [options.seed] - Seed offset for stride sampling.
* @returns {Array<{position: {x: number, y: number, z: number}, id: string, type: string, skipLabel: boolean}>}
* @returns {Array<{position: {x: number, y: number, z: number}, id: string, type: string, skipLabel: boolean, cardSourceId: string, cardEntryId: string}>}
*/
getDetectableObjects(options = {}) {
if (!state.feed.enabled || !state.icons?.show) return [];
@@ -597,10 +659,13 @@ export function createQueries({
if (!position) continue;
result.push({
position,
sourceId: record.mmsi,
sourceId: record.id,
id: record.name || record.mmsi || 'VESSEL',
type: 'SEA',
skipLabel: record === selected,
// Detection hides the callout while this card paints.
cardSourceId: VESSEL_OVERLAY_SOURCE_ID,
cardEntryId: components.cards.vesselOverlayEntryId(record),
klass: record.type
? String(record.type).toUpperCase().slice(0, 14)
: undefined,
@@ -647,6 +712,8 @@ export function createQueries({
retryInSec: aisRetryInSec(),
// Same field as flights and military, so Contacts names the provider.
source: layer.source,
// Following the world clock, the snapshot's age is told from its time.
...(followsClock(vesselState) && { atMs: vesselState.worldNow() }),
};
},
};
@@ -660,7 +727,7 @@ export function createQueries({
mapAnalystRecord,
vesselDatumHeightM,
reduceVesselSelection,
normalizeSelectionMmsi,
normalizeSelectionId,
methods,
};
}
+1 -1
View File
@@ -134,7 +134,7 @@ test("the ridden ship's trail is hidden while the bridge holds it", () => {
};
const layer = layerWith([record('own', 0), record('other', 2)], {
trail,
trailMmsi: 'own',
trailId: 'own',
});
layer.setCockpitSubject('own');
assert.deepEqual(shown, [false]);
+73 -22
View File
@@ -3,17 +3,25 @@ import {
SELECTED_PIN_REFRESHES,
} from './recordPolicy.js';
/** Normalize AIS display fields without allocating scene resources. */
/**
* Normalize AIS display fields without allocating scene resources. `id` is the
* vessel's key, the stable id its source gives; a row that names none (an
* AIS feed's own rows) is keyed by its MMSI. `mmsi` is only an attribute,
* shown when known: vessels can share one. A row with neither is unkeyed.
*/
export function normalizeVessel(row) {
const lat = Number(row.lat);
const lon = Number(row.lon);
if (!Number.isFinite(lat) || !Number.isFinite(lon)) return null;
const mmsi = String(row.mmsi || '').trim();
const id = String(row.id ?? mmsi).trim();
return {
lat,
lon,
name: String(row.name || row.mmsi || 'VESSEL'),
mmsi: String(row.mmsi || '').trim(),
reference: row.reference ?? String(row.mmsi || '').trim(),
name: String(row.name || mmsi || 'VESSEL'),
id,
mmsi,
reference: row.reference ?? id,
imo: String(row.imo || ''),
type: String(row.type || ''),
destination: String(row.destination || ''),
@@ -44,17 +52,51 @@ function finiteNumber(value) {
return Number.isFinite(number) ? number : null;
}
/**
* The move from a record's fix to the next row's, when the fix moves on in
* time; otherwise the move it was making, if the row repeats its fix.
*/
function motionBetween(record, next) {
const fromEpoch = record.lastPositionEpoch;
const toEpoch = next.lastPositionEpoch;
if (fromEpoch === toEpoch) return record.motion ?? null;
if (!Number.isFinite(fromEpoch) || !Number.isFinite(toEpoch)) return null;
if (!(toEpoch > fromEpoch)) return null;
return {
fromLat: record.lat,
fromLon: record.lon,
fromMs: fromEpoch * 1000,
toLat: next.lat,
toLon: next.lon,
toMs: toEpoch * 1000,
};
}
/** Own stable vessel records and bounded incomplete/selected retention. */
export class VesselRecords {
constructor({ now = () => Date.now() } = {}) {
this.now = now;
this.byMmsi = new Map();
this.byId = new Map();
this.unkeyed = [];
this.all = [];
}
/**
* Fold a refresh into the records. Following the world clock (`follow`),
* a vessel whose fix moves on keeps where it moved from, so it can be drawn
* between the two (see motion.js). `replace`: the rows are the world at
* another time (the clock jumped), so they stand in for every vessel: one
* they lack is gone at once, selected or not, and none moves from where it
* was at the time the clock left.
*/
reconcile(
rows,
{ complete = true, selectedRecord = null, cap = Infinity },
{
complete = true,
selectedRecord = null,
cap = Infinity,
replace = false,
follow = false,
},
effects,
) {
const receivedAtMs = this.now();
@@ -78,14 +120,14 @@ export class VesselRecords {
if (!next) continue;
next.receivedAtMs = receivedAtMs;
stampFix(next, receivedAtMs, feedLatestEpoch);
if (!next.mmsi) {
if (!next.id) {
effects.add(next);
this.unkeyed.push(next);
continue;
}
if (seen.has(next.mmsi)) continue;
seen.add(next.mmsi);
const record = this.byMmsi.get(next.mmsi);
if (seen.has(next.id)) continue;
seen.add(next.id);
const record = this.byId.get(next.id);
if (record) {
// A feed re-serving a cached row repeats its fix: the fix keeps the
// time it was first received, so it goes on ageing.
@@ -93,7 +135,10 @@ export class VesselRecords {
record.fixReceivedAtMs = next.fixReceivedAtMs;
record.fixFeedEpoch = next.fixFeedEpoch;
}
if (replace) record.motion = null;
else if (follow) record.motion = motionBetween(record, next);
record.reference = next.reference;
record.mmsi = next.mmsi;
record.receivedAtMs = next.receivedAtMs;
record.lat = next.lat;
record.lon = next.lon;
@@ -111,11 +156,17 @@ export class VesselRecords {
effects.updated(record);
} else {
effects.add(next);
this.byMmsi.set(next.mmsi, next);
this.byId.set(next.id, next);
}
}
for (const [mmsi, record] of this.byMmsi) {
if (seen.has(mmsi)) continue;
for (const [id, record] of this.byId) {
if (seen.has(id)) continue;
if (replace) {
effects.remove(record, record === selectedRecord);
this.byId.delete(id);
effects.removed(id);
continue;
}
if (
!complete &&
Number.isFinite(record.receivedAtMs) &&
@@ -136,18 +187,18 @@ export class VesselRecords {
}
// Selection teardown still sees the record before its store entry is removed.
effects.remove(record, record === selectedRecord);
this.byMmsi.delete(mmsi);
effects.removed(mmsi);
this.byId.delete(id);
effects.removed(id);
}
if (this.byMmsi.size + this.unkeyed.length > cap) {
for (const [mmsi, record] of this.byMmsi) {
if (this.byMmsi.size + this.unkeyed.length <= cap) break;
if (seen.has(mmsi) || record === selectedRecord) continue;
if (this.byId.size + this.unkeyed.length > cap) {
for (const [id, record] of this.byId) {
if (this.byId.size + this.unkeyed.length <= cap) break;
if (seen.has(id) || record === selectedRecord) continue;
effects.remove(record, false);
this.byMmsi.delete(mmsi);
effects.removed(mmsi);
this.byId.delete(id);
effects.removed(id);
}
}
this.all = [...this.byMmsi.values(), ...this.unkeyed];
this.all = [...this.byId.values(), ...this.unkeyed];
}
}
+56 -16
View File
@@ -17,8 +17,8 @@ function setup() {
add: (record) => events.push(['add', record]),
updated: (record) => events.push(['update', record]),
remove: (record, evicted) =>
events.push(['remove', record, evicted, store.byMmsi.has(record.mmsi)]),
removed: (id) => events.push(['removed', id, store.byMmsi.has(id)]),
events.push(['remove', record, evicted, store.byId.has(record.id)]),
removed: (id) => events.push(['removed', id, store.byId.has(id)]),
staleSelected: (record) => events.push(['stale', record]),
};
return {
@@ -39,15 +39,15 @@ test('vessel reconciliation preserves record identity and first duplicate while
row('222', { name: 'duplicate' }),
row('bad', { lat: NaN }),
]);
assert.equal(probe.store.byMmsi.size, 2);
assert.equal(probe.store.byMmsi.get('222').name, '222');
const record = probe.store.byMmsi.get('111');
assert.equal(probe.store.byId.size, 2);
assert.equal(probe.store.byId.get('222').name, '222');
const record = probe.store.byId.get('111');
probe.reconcile([row('111', { lat: 51.94, type: 'Tanker' })]);
assert.equal(probe.store.byMmsi.get('111'), record);
assert.equal(probe.store.byId.get('111'), record);
assert.equal(record.lat, 51.94);
assert.equal(probe.events.find((event) => event[0] === 'update')[1], record);
assert.equal(record.type, 'Tanker');
assert.equal(probe.store.byMmsi.has('222'), false);
assert.equal(probe.store.byId.has('222'), false);
for (const field of [
'position',
'surfacePosition',
@@ -62,14 +62,14 @@ test('vessel reconciliation preserves record identity and first duplicate while
test('selected vessel remains pinned for three complete misses and teardown precedes removal', () => {
const probe = setup();
probe.reconcile([row('111'), row('222')]);
const selectedRecord = probe.store.byMmsi.get('111');
const selectedRecord = probe.store.byId.get('111');
for (let i = 1; i <= 3; i++) {
probe.reconcile([row('222')], { selectedRecord });
assert.equal(probe.store.byMmsi.get('111'), selectedRecord);
assert.equal(probe.store.byId.get('111'), selectedRecord);
assert.equal(selectedRecord.missedRefreshes, i);
}
probe.reconcile([row('222')], { selectedRecord });
assert.equal(probe.store.byMmsi.has('111'), false);
assert.equal(probe.store.byId.has('111'), false);
const removal = probe.events.find(
(event) => event[0] === 'remove' && event[1] === selectedRecord,
);
@@ -83,13 +83,13 @@ test('selected vessel remains pinned for three complete misses and teardown prec
test('partial retention respects age and row cap while preserving the selected contact', () => {
const probe = setup();
probe.reconcile([row('111'), row('222')], { cap: 2 });
const selectedRecord = probe.store.byMmsi.get('111');
const selectedRecord = probe.store.byId.get('111');
probe.reconcile([row('333')], { complete: false, selectedRecord, cap: 2 });
assert.deepEqual([...probe.store.byMmsi.keys()], ['111', '333']);
assert.deepEqual([...probe.store.byId.keys()], ['111', '333']);
assert.equal(selectedRecord.missedRefreshes, 1);
probe.advance(5 * 60 * 1000);
probe.reconcile([row('333')], { complete: false, selectedRecord, cap: 2 });
assert.equal(probe.store.byMmsi.has('111'), false);
assert.equal(probe.store.byId.has('111'), false);
assert.equal(
probe.events.find(
(event) => event[0] === 'remove' && event[1] === selectedRecord,
@@ -113,7 +113,7 @@ test('unkeyed records rebuild on each refresh and numeric coercion keeps unknown
),
true,
);
assert.equal(probe.store.byMmsi.size, 0);
assert.equal(probe.store.byId.size, 0);
assert.equal(probe.store.all.length, 1);
assert.equal(normalizeVessel(row('bad', { lon: Infinity })), null);
});
@@ -126,14 +126,14 @@ test("each fix keeps when it was first received and its refresh's newest fix", (
row('333'),
]);
for (const mmsi of ['111', '222', '333']) {
const record = probe.store.byMmsi.get(mmsi);
const record = probe.store.byId.get(mmsi);
assert.equal(record.fixFeedEpoch, 1_800_000_030, mmsi);
assert.equal(record.fixReceivedAtMs, 1000, mmsi);
}
// A new fix is stamped afresh.
probe.advance(60_000);
probe.reconcile([row('111', { last_position_epoch: 1_800_000_050 })]);
const record = probe.store.byMmsi.get('111');
const record = probe.store.byId.get('111');
assert.equal(record.fixFeedEpoch, 1_800_000_050);
assert.equal(record.fixReceivedAtMs, 61_000);
// The same fix re-served by later polls keeps its first receipt, while
@@ -147,3 +147,43 @@ test("each fix keeps when it was first received and its refresh's newest fix", (
assert.equal(record.fixFeedEpoch, 1_800_000_050);
assert.equal(record.receivedAtMs, 91_000);
});
test('vessels are keyed by their source id; a shared MMSI is only an attribute', () => {
const probe = setup();
probe.reconcile([
row('123456789', { id: 'hull-a', name: 'A' }),
row('123456789', { id: 'hull-b', name: 'B' }),
row('', { id: 'hull-c', name: 'C' }),
]);
assert.deepEqual(
[...probe.store.byId.keys()],
['hull-a', 'hull-b', 'hull-c'],
);
assert.equal(probe.store.unkeyed.length, 0);
const [a, b, c] = probe.store.all;
assert.deepEqual([a.mmsi, b.mmsi, c.mmsi], ['123456789', '123456789', '']);
assert.equal(a.reference, 'hull-a');
// The number moves to another hull: the vessel keeps its id.
probe.reconcile([
row('', { id: 'hull-a', name: 'A' }),
row('123456789', { id: 'hull-b', name: 'B' }),
row('123456789', { id: 'hull-c', name: 'C' }),
]);
assert.equal(probe.store.byId.get('hull-a'), a);
assert.equal(a.mmsi, '');
assert.equal(probe.store.byId.get('hull-c').mmsi, '123456789');
});
test('an AIS row with no id is keyed by its MMSI; one with neither is unkeyed', () => {
assert.deepEqual(
[
normalizeVessel(row('366999712')).id,
normalizeVessel(row('366999712')).mmsi,
],
['366999712', '366999712'],
);
const probe = setup();
probe.reconcile([row(''), row('', { id: '' })]);
assert.equal(probe.store.byId.size, 0);
assert.equal(probe.store.unkeyed.length, 2);
});
+52 -24
View File
@@ -26,7 +26,12 @@ import {
FOCUS_UPDATE_MS,
LABEL_GRID_PX,
CARD_MIN_SEP_PX,
followsClock,
} from './policy.js';
import { vesselPositionAt } from './motion.js';
/** How often vessels move on as the world clock plays (wall ms). */
const FOLLOW_POSITION_MS = 250;
/** The ship artwork's own raster size (px). */
const SHIP_ICON_PX = 32;
@@ -56,11 +61,11 @@ export function createRendering({
function prepareRecordVisual(record) {
let visual = visualRecords.get(record);
if (!visual) {
// Unkeyed records (no MMSI) are rebuilt every poll, so their rows take
// a fresh id that no MMSI can collide with.
// Unkeyed records (no id) are rebuilt every poll, so their rows take
// a fresh id that no vessel id can collide with.
visual = {
iconId:
record.mmsi || `ais-unkeyed:${++vesselState._unkeyedIconSequence}`,
record.id || `ais-unkeyed:${++vesselState._unkeyedIconSequence}`,
visible: false,
};
visualRecords.set(record, visual);
@@ -71,17 +76,21 @@ export function createRendering({
/**
* Where a record's icon is anchored: VESSEL_LIFT_M above the sea surface
* (the geoid, once its grid has loaded).
* (the geoid, once its grid has loaded). Following the world clock, a
* vessel is drawn where it was at the time.
* @param {Object} record - Vessel record with a finite lat/lon.
* @returns {{x: number, y: number, z: number}} ECEF metres: icon items,
* focus and the layer's queries take it as it is.
*/
function anchorPosition(record) {
const { lat, lon } = followsClock(vesselState)
? vesselPositionAt(record, vesselState.worldNow())
: record;
const heightM = components.queries.vesselDatumHeightM(
components.tracking.currentGeoidN(record.lat, record.lon),
components.tracking.currentGeoidN(lat, lon),
VESSEL_LIFT_M,
);
return fromDegrees(record.lon, record.lat, heightM);
return fromDegrees(lon, lat, heightM);
}
// Reused projection buffers for the card pass, grown to the candidates.
@@ -155,8 +164,7 @@ export function createRendering({
/** Whether the Cockpit's bridge camera rides this record's ship. */
function isCockpitSubject(record) {
return (
Boolean(state.cockpitSubjectMmsi) &&
record.mmsi === state.cockpitSubjectMmsi
Boolean(state.cockpitSubjectId) && record.id === state.cockpitSubjectId
);
}
@@ -166,12 +174,12 @@ export function createRendering({
* view, so it is hidden while held.
*/
function syncCockpitSubjectIcon() {
const held = state.cockpitSubjectMmsi || null;
if (vesselState._iconHiddenMmsi === held) return;
const before = vesselState._iconHiddenMmsi;
vesselState._iconHiddenMmsi = held;
for (const mmsi of [before, held]) {
const record = mmsi ? state.records.byMmsi.get(mmsi) : null;
const held = state.cockpitSubjectId || null;
if (vesselState._iconHiddenId === held) return;
const before = vesselState._iconHiddenId;
vesselState._iconHiddenId = held;
for (const id of [before, held]) {
const record = id ? state.records.byId.get(id) : null;
if (record) syncRecordIcon(record);
}
}
@@ -302,7 +310,27 @@ export function createRendering({
function installRuntime(viewer) {
if (state.preRenderRemover || !viewer) return;
state.preRenderRemover =
findFrame(viewer)?.on('preRender', () => updateVisibility()) ?? null;
findFrame(viewer)?.on('preRender', () => {
if (followsClock(vesselState)) followClockPositions();
updateVisibility();
}) ?? null;
}
// As the world clock plays, vessels between two fixes move on along them.
let followedAtWallMs = -Infinity;
let followedAtMs = null;
function followClockPositions() {
const wallMs = performance.now();
if (wallMs - followedAtWallMs < FOLLOW_POSITION_MS) return;
followedAtWallMs = wallMs;
const atMs = vesselState.worldNow();
if (atMs === followedAtMs) return;
followedAtMs = atMs;
for (const record of state.records.all) {
if (!record.motion) continue;
prepareRecordVisual(record);
syncRecordIcon(record);
}
}
function scheduleTrailingVisibilityPass(now) {
@@ -494,8 +522,7 @@ export function createRendering({
const selected = state.selectedRecord;
// From the bridge, the selected vessel is the viewer; its card would be
// pinned to the camera position.
const selectedCarded =
selected && selected.mmsi !== state.cockpitSubjectMmsi;
const selectedCarded = selected && selected.id !== state.cockpitSubjectId;
const entries = selectedCarded
? [components.cards.buildSelectedVesselCard(selected)]
: [];
@@ -591,17 +618,17 @@ export function createRendering({
VESSEL_CARD_FADE_DISTANCE_M,
);
if (!card.interactive) return card;
const mmsi = String(card.id || '').startsWith('vessel:')
const id = String(card.id || '').startsWith('vessel:')
? card.id.slice('vessel:'.length)
: '';
const mmsi = state.records.byId.get(id)?.mmsi || '';
return {
...card,
accessibilityLabel: t('Focus vessel {name}, MMSI {mmsi}', {
name: card.title,
mmsi,
}),
accessibilityLabel: mmsi
? t('Focus vessel {name}, MMSI {mmsi}', { name: card.title, mmsi })
: t('Focus {label}', { label: card.title }),
activate: () => {
const record = state.records.byMmsi.get(mmsi);
const record = state.records.byId.get(id);
if (!record) return false;
components.selection.selectAndFocusVessel(record);
return true;
@@ -633,7 +660,8 @@ export function createRendering({
text &&
text !== 'VESSEL' &&
!/^MMSI\s*\d+$/i.test(text) &&
text !== record.mmsi,
text !== record.mmsi &&
text !== record.id,
);
}
+22 -21
View File
@@ -29,13 +29,13 @@ export function createSelection({
if (!state.feed.enabled) return;
// The bridge view owns the selection: a click on open water must not
// deselect the vessel the camera is riding.
if (state.cockpitSubjectMmsi) return;
if (state.cockpitSubjectId) return;
const pickedId = event.id;
let record = pickedId ? state.records.byMmsi.get(pickedId) : null;
let record = pickedId ? state.records.byId.get(pickedId) : null;
// A vessel icon's pick is an item of the layer's icon set, whose id is
// its row id: the MMSI, or an unkeyed row's. Removing a row removes its
// item, so an evicted vessel cannot be picked at all; a live row whose
// record is gone stays a no-op below.
// its row id: the record's id, or an unkeyed row's. Removing a row
// removes its item, so an evicted vessel cannot be picked at all; a
// live row whose record is gone stays a no-op below.
const hit = event.drawHit;
const ownRecordPick =
Boolean(hit) &&
@@ -78,10 +78,10 @@ export function createSelection({
if (cycloneBackground && cardHit?.sourceId !== VESSEL_OVERLAY_SOURCE_ID)
return;
if (!record && cardHit) {
const mmsi = String(cardHit.entryId || '').startsWith('vessel:')
const id = String(cardHit.entryId || '').startsWith('vessel:')
? cardHit.entryId.slice('vessel:'.length)
: null;
record = mmsi ? state.records.byMmsi.get(mmsi) || null : null;
record = id ? state.records.byId.get(id) || null : null;
// A stale card id is not empty terrain and must not clear a newer
// selection. The next paint will evict its hit rectangle.
if (!record) return;
@@ -93,8 +93,8 @@ export function createSelection({
selectAndFocusVessel(record);
} else {
const transition = components.queries.reduceVesselSelection({
selectedMmsi: state.selectedRecord?.mmsi,
pickedMmsi: null,
selectedId: state.selectedRecord?.id,
pickedId: null,
gesture: 'click',
});
if (transition.action === 'deselect') clearVesselInspection();
@@ -113,17 +113,17 @@ export function createSelection({
/** Select one live vessel and request one UI-owned camera transfer. */
function selectAndFocusVessel(record) {
if (!record?.mmsi) return false;
if (!record?.id) return false;
const transition = components.queries.reduceVesselSelection({
selectedMmsi: state.selectedRecord?.mmsi,
pickedMmsi: record.mmsi,
selectedId: state.selectedRecord?.id,
pickedId: record.id,
gesture: 'click',
});
if (transition.action === 'select') selectVessel(record);
requestWorldFocus({
kind: 'vessel',
id: record.mmsi,
label: record.name || record.mmsi,
id: record.id,
label: record.name || record.mmsi || record.id,
position: components.rendering.iconPosition(record),
});
return true;
@@ -146,7 +146,7 @@ export function createSelection({
function onVesselKeyDown(event) {
if (!state.feed.enabled || event.key !== 'Escape') return;
const transition = components.queries.reduceVesselSelection({
selectedMmsi: state.selectedRecord?.mmsi,
selectedId: state.selectedRecord?.id,
gesture: 'escape',
});
if (transition.action === 'deselect') {
@@ -155,8 +155,8 @@ export function createSelection({
}
function selectVessel(record) {
if (!record?.mmsi) return;
const reuseTrail = state.trailMmsi === record.mmsi;
if (!record?.id) return;
const reuseTrail = state.trailId === record.id;
clearSelection({ preserveTrail: reuseTrail });
state.selectedRecord = record;
record.missedRefreshes = 0;
@@ -169,7 +169,7 @@ export function createSelection({
selectEntityContext(record);
}
// Track-history trail (PRD F3/F4): seed with the current position + async
// backfill from the server-side per-MMSI ring buffer.
// backfill from the source's recent track for this vessel.
if (reuseTrail) {
components.tracking.appendSelectedVesselTrailFix(record);
} else {
@@ -185,10 +185,10 @@ export function createSelection({
*/
function registerSelectedContext(record) {
if (!record?.mmsi) return null;
if (!record?.id) return null;
try {
return registerEntityContext(record, {
id: `ais-${record.mmsi}`,
id: `ais-${record.id}`,
layerId: 'ais-live-vessels',
layerName: 'Live AIS Vessels',
source: aisLiveVesselsLayer.source,
@@ -196,7 +196,8 @@ export function createSelection({
latitude: record.lat,
longitude: record.lon,
properties: {
mmsi: record.mmsi,
vesselId: record.id,
mmsi: record.mmsi || null,
type: record.type,
speedKt: record.speed,
course: record.course,
+16 -4
View File
@@ -7,16 +7,25 @@ export function createVesselSnapshotRenderer({
tracking,
selection,
cards,
followsClock = () => false,
}) {
function reconcileVessels(viewer, rows, { complete = true } = {}) {
/** `replace`: the rows are the world at another time (see VesselRecords). */
function reconcileVessels(
viewer,
rows,
{ complete = true, replace = false } = {},
) {
rendering.ensureCollections(viewer);
const occluder = rendering.makeOccluder();
const follow = followsClock();
records.reconcile(
rows,
{
complete,
selectedRecord: state.selectedRecord,
cap: rendering.renderRowLimit(),
...(replace && { replace }),
...(follow && { follow }),
},
{
add(record) {
@@ -27,7 +36,7 @@ export function createVesselSnapshotRenderer({
const selected = record === state.selectedRecord;
rendering.prepareRecordVisual(record);
rendering.syncRecordIcon(record);
if (record.mmsi === state.trailMmsi)
if (record.id === state.trailId)
tracking.appendSelectedVesselTrailFix(record);
if (selected) {
cards.updateSelectedVesselHud(record);
@@ -38,14 +47,17 @@ export function createVesselSnapshotRenderer({
if (evicted) selection.clearVesselInspection({ evicted: true });
rendering.removeRecordPrimitives(record);
},
removed(mmsi) {
if (state.trailMmsi === mmsi) tracking.clearSelectedVesselTrail();
removed(id) {
if (state.trailId === id) tracking.clearSelectedVesselTrail();
},
staleSelected(record) {
cards.updateSelectedVesselHud(record);
},
},
);
// The selected vessel at the new time: its trail starts there.
if (replace && state.selectedRecord && state.trailId)
tracking.startSelectedVesselTrail(state.selectedRecord);
state.lastVisibilityUpdate = 0;
rendering.updateVisibility(true);
}
+22 -8
View File
@@ -1,6 +1,7 @@
import { createVesselFeed } from './ingestion.js';
import { VesselRecords } from './records.js';
import { DEFAULT_AIS_RUNTIME } from './policy.js';
import { DEFAULT_AIS_RUNTIME, followsClock } from './policy.js';
import { worldTimeFor } from '../../time/worldClock.js';
export function createVesselState({ source, services }) {
const {
@@ -28,6 +29,19 @@ export function createVesselState({ source, services }) {
vesselState._aisRuntime = DEFAULT_AIS_RUNTIME;
/** Follows the world clock while the source declares a timeline (set by the
* layer); see followsClock in policy.js. */
vesselState.timeline = null;
/** The world time the layer draws at while it follows the clock. */
vesselState.worldNow = worldTimeFor('ais-live-vessels');
/** The time records are judged at: the world's while following the clock. */
vesselState.recordsNow = () =>
followsClock(vesselState)
? vesselState.worldNow()
: vesselState._aisRuntime.now();
vesselState._aisSessionSequence = 0;
/**
@@ -43,15 +57,15 @@ export function createVesselState({ source, services }) {
vesselState.shipIconCache = new Map();
/** Row ids for unkeyed (no-MMSI) records, which are rebuilt every poll. */
/** Row ids for unkeyed (no-id) records, which are rebuilt every poll. */
vesselState._unkeyedIconSequence = 0;
// The ship whose icon is hidden under the bridge camera (cockpit subject).
vesselState._iconHiddenMmsi = null;
vesselState._iconHiddenId = null;
vesselState.state = {
feed: createVesselFeed(),
records: new VesselRecords({ now: () => vesselState._aisRuntime.now() }),
records: new VesselRecords({ now: () => vesselState.recordsNow() }),
viewer: null,
/** The vessels' icons as drawn (`iconBook.js`), and their draw set. */
@@ -75,14 +89,14 @@ export function createVesselState({ source, services }) {
activeFocusCount: 0,
activeLabelCount: 0,
selectedRecord: null,
/** @type {string|null} MMSI whose bridge the Cockpit camera occupies; its sprite and card stay hidden. */
cockpitSubjectMmsi: null,
/** @type {string|null} Id of the vessel whose bridge the Cockpit camera occupies; its sprite and card stay hidden. */
cockpitSubjectId: null,
/** @type {{setPositions: Function, clear: Function, destroy: Function}|null} Selected-vessel fading trail */
trail: null,
/** @type {{x: number, y: number, z: number}[]} Chronological ECEF trail vertices (oldest first) */
trailPositions: [],
/** @type {string|null} MMSI that owns the active selected-vessel trail. */
trailMmsi: 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 */
trailBackfillToken: 0,
trailAbort: null,
+14 -9
View File
@@ -33,6 +33,11 @@ export function createTesting({
function _setVesselStateForTest(options = {}) {
components.lifecycle.resetState();
const records = Array.isArray(options.records) ? options.records : [];
// A test record that names no id is keyed by its MMSI, as an AIS feed's
// own rows are (see normalizeVessel).
for (const record of [...records, options.selectedRecord])
if (record && typeof record === 'object' && record.id === undefined)
record.id = String(record.mmsi || '').trim();
state.viewer = options.viewer || null;
state.feed.enabled = options.enabled !== false;
state.feed.loaded = options.loaded === true;
@@ -43,17 +48,17 @@ export function createTesting({
state.feed.lastUpdate = options.lastUpdate ?? null;
state.records.all = records;
state.feed.count = records.length;
state.records.byMmsi = new Map(
state.records.byId = new Map(
records
.filter((record) => record?.mmsi)
.map((record) => [record.mmsi, record]),
.filter((record) => record?.id)
.map((record) => [record.id, record]),
);
state.selectedRecord = options.selectedRecord || null;
// `icons: null` leaves the layer to make its own draw set.
state.icons =
options.icons === null ? null : options.icons || createVesselIconBook();
state.trail = options.trail || null;
state.trailMmsi = options.trailMmsi || null;
state.trailId = options.trailId || null;
state.trailPositions = Array.isArray(options.trailPositions)
? [...options.trailPositions]
: [];
@@ -143,8 +148,8 @@ export function createTesting({
lastMessageAt: state.feed.lastMessageAt,
rawRowCount: state.feed.rawRowCount,
acceptedRowCount: state.feed.acceptedRowCount,
selectedMmsi: state.selectedRecord?.mmsi || null,
trailMmsi: state.trailMmsi,
selectedId: state.selectedRecord?.id || null,
trailId: state.trailId,
trailPositionCount: state.trailPositions.length,
sessionId: state.feed.sessionId,
firstConnectPhase: state.feed.firstConnectPhase,
@@ -168,14 +173,14 @@ export function createTesting({
/**
* Read lifecycle ownership state without exposing the mutable state object.
* Test-only seam.
* @returns {{trailMmsi: string|null, trailPositionCount: number, vesselCount: number}}
* @returns {{trailId: string|null, trailPositionCount: number, vesselCount: number}}
*/
function _getVesselStateForTest() {
return {
trailMmsi: state.trailMmsi,
trailId: state.trailId,
trailPositionCount: state.trailPositions.length,
vesselCount: state.records.byMmsi.size,
vesselCount: state.records.byId.size,
};
}
return {
+20 -12
View File
@@ -5,6 +5,7 @@ import {
TRAIL_COLOR,
TRAIL_MAX_POINTS,
TRAIL_MIN_MOVE_M,
followsClock,
} from './policy.js';
export function createTracking({
@@ -80,7 +81,7 @@ export function createTracking({
state.trailAbort?.abort();
state.trailAbort = new AbortController();
state.trailBackfillToken += 1;
state.trailMmsi = record.mmsi;
state.trailId = record.id;
state.trailPositions = [];
const current = vesselTrailPosition(record);
if (current) state.trailPositions.push(current);
@@ -91,32 +92,33 @@ export function createTracking({
});
}
if (state.trail) state.trail.setPositions(state.trailPositions);
backfillVesselTrail(
record.mmsi,
state.trailBackfillToken,
record.reference,
);
backfillVesselTrail(record.id, state.trailBackfillToken, record.reference);
}
/**
* Fire-and-forget backfill from the server-side per-MMSI ring buffer
* Fire-and-forget backfill from the server-side per-vessel ring buffer
* (PRD F3 — "recent path" since server boot, not voyage history). Older
* samples are spliced AHEAD of the live accumulation, capped at
* TRAIL_MAX_POINTS (newest kept). Any failure (404/timeout/malformed)
* silently keeps the live-only trail.
* @param {string} mmsi - MMSI of the selected vessel.
* @param {string} id - Key of the selected vessel.
* @param {number} token - Backfill token captured at request time.
* @returns {Promise<void>}
*/
async function backfillVesselTrail(mmsi, token, reference = mmsi) {
async function backfillVesselTrail(id, token, reference = id) {
const owner = state.trailAbort;
// Following the world clock, the track ends at the world's time.
const atMs = followsClock(vesselState) ? vesselState.worldNow() : undefined;
const signal = owner
? AbortSignal.any([owner.signal, AbortSignal.timeout(8000)])
: AbortSignal.timeout(8000);
let samples = null;
try {
const track = await vesselState._source.getTrack?.(reference, { signal });
const track = await vesselState._source.getTrack?.(
reference,
atMs === undefined ? { signal } : { signal, atMs },
);
samples = track?.records ?? null;
} catch {
return; // silent — keep the live-accumulated trail
@@ -128,13 +130,19 @@ export function createTracking({
token !== state.trailBackfillToken
)
return;
if (state.trailMmsi !== mmsi) return;
if (state.trailId !== id) return;
const older = [];
for (const sample of samples) {
const lat = Number(sample?.latitude);
const lon = Number(sample?.longitude);
if (!Number.isFinite(lat) || !Number.isFinite(lon)) continue;
// Following the clock, an undated sample may be later than the time.
if (
atMs !== undefined &&
!(Number.isFinite(sample?.observedAtMs) && sample.observedAtMs <= atMs)
)
continue;
// Per-sample N (≤ TRAIL_MAX_POINTS lookups) — same sea-surface datum as
// the live vertices so the spliced trail is height-continuous.
const heightM = components.queries.vesselDatumHeightM(
@@ -180,7 +188,7 @@ export function createTracking({
state.trailAbort?.abort();
state.trailAbort = null;
state.trailBackfillToken += 1;
state.trailMmsi = null;
state.trailId = null;
state.trailPositions = [];
if (state.trail) state.trail.clear();
}
+1 -1
View File
@@ -23,7 +23,7 @@ function setup({ geoidN = 40, track = null } = {}) {
trailPositions: [],
trailBackfillToken: 0,
trailAbort: null,
trailMmsi: null,
trailId: null,
records: { all: records },
},
};