feat(vessels): key vessels by their source's stable id, and share a selected vessel

AIS Vessels are keyed by the id their live source gives, with the MMSI as an
attribute: an MMSI can be shared, spoofed or reused, so two vessels with one
MMSI are now two vessels. Looking a vessel up or selecting it by MMSI still
finds it.

A share link made while a vessel is selected opens that vessel. A UUID vessel
id travels as 16 bytes in a new thing field (13). A shared thing that is not
reporting now says so in a sentence per kind, with its id (ICAO, NORAD, MMSI
or vessel UUID) on a second line.
This commit is contained in:
Sameh Khamis committed 2026-11-10 18:12:53 -08:00
1 parent 57ff81f723
commit cbbf55cacd
74 files changed
+2481 -586

No files matched your search

+1 -1
View File
@@ -150,7 +150,7 @@ export function createHistory({ state: layerState, services, parts, source }) {
return (
items.find(
(item) =>
String(item?.icao24 || item?.mmsi || item?.id) === String(subject.id),
String(item?.icao24 || item?.id || item?.mmsi) === String(subject.id),
) || subject
);
}
+1 -1
View File
@@ -117,7 +117,7 @@ export function createPanel({ state: layerState, parts }) {
.slice(page, page + AWARENESS_PAGE_SIZE)
.map((item, index) => {
const label = formatAwarenessLabel(item);
const targetId = item.icao24 || item.mmsi || item.id;
const targetId = item.icao24 || item.id || item.mmsi;
const distance = presentAwarenessDistance(item.distanceM);
if (!targetId)
return {
+2 -2
View File
@@ -85,7 +85,7 @@ export function createSubject({ state: layerState, services, parts, source }) {
.getNearby(position, AWARENESS_RADIUS_M, AWARENESS_QUERY_LIMIT)
.filter(
(item) =>
!parts.queries.isSame(subject, item, 'ais-live-vessels', 'mmsi'),
!parts.queries.isSame(subject, item, 'ais-live-vessels', 'id'),
);
const coverage = installationsState.stats?.coverage;
const installationRadius =
@@ -519,7 +519,7 @@ export function createSubject({ state: layerState, services, parts, source }) {
if (!Number.isFinite(latitude) || !Number.isFinite(longitude)) return null;
return {
layerId: record.layerId,
id: record.properties?.mmsi || record.id,
id: record.properties?.vesselId || record.id,
label: record.label || record.id,
memberNames: record.properties?.memberNames || [],
position: Cesium.Cartesian3.fromDegrees(longitude, latitude, 0),
+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.getVisual(record).billboard?.position ||
components.rendering.getVisual(record).position,
@@ -101,7 +101,7 @@ export function createCards({
);
return {
id: vesselOverlayEntryId(record),
actionable: Boolean(record?.mmsi),
actionable: Boolean(record?.id),
position:
components.rendering.getVisual(record).billboard?.position ||
components.rendering.getVisual(record).position,
@@ -114,11 +114,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';
@@ -161,7 +161,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');
}
+5 -5
View File
@@ -37,19 +37,19 @@ function store() {
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.byMmsi.get('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.byMmsi.keys()], ['111']);
assert.deepEqual([...probe.records.byId.keys()], ['111']);
assert.deepEqual(probe.events.slice(-3), [
['update', '111'],
['remove', '222', true],
['removed', '222'],
]);
assert.equal(probe.records.byMmsi.get('111').motion, null);
assert.equal(probe.records.byId.get('111').motion, null);
});
test('following the clock, a vessel keeps where its fix moved from', () => {
@@ -58,7 +58,7 @@ test('following the clock, a vessel keeps where its fix moved from', () => {
probe.reconcile([row('111', { lat: 52, last_position_epoch: 1_010 })], {
follow: true,
});
const record = probe.records.byMmsi.get('111');
const record = probe.records.byId.get('111');
assert.deepEqual(record.motion, {
fromLat: 51.93,
fromLon: 4.05,
@@ -75,7 +75,7 @@ test('following the clock, a vessel keeps where its fix moved from', () => {
live.reconcile([row('111')]);
live.reconcile([row('111', { lat: 52, last_position_epoch: 1_010 })]);
assert.equal(
Object.hasOwn(live.records.byMmsi.get('111'), 'motion'),
Object.hasOwn(live.records.byId.get('111'), 'motion'),
false,
'live records are as before',
);
+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
@@ -47,7 +47,7 @@ export function createEvidence({
)
: null;
return {
id: record.mmsi,
id: record.id,
show: bb?.show === true,
alpha: bb?.color?.alpha ?? null,
x: screen?.x ?? null,
+3 -1
View File
@@ -201,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,
+4 -4
View File
@@ -116,7 +116,7 @@ export function createLifecycle({
state.feed.abort = null;
state.billboardCollection = null;
state.records.all = [];
state.records.byMmsi = new Map();
state.records.byId = new Map();
state.records.unkeyed = [];
state.clickHandler = null;
state.keyTarget = null;
@@ -133,7 +133,7 @@ export function createLifecycle({
state.selectedRecord = null;
state.trail = null;
state.trailPositions = [];
state.trailMmsi = null;
state.trailId = null;
state.trailBackfillToken = 0;
}
const methods = {
@@ -188,9 +188,9 @@ export function createLifecycle({
});
}
// Pick-ownership (H2): vessel picks carry the record OBJECT as their id;
// the registry resolver reduces it to the record's mmsi (a string key).
// the registry resolver reduces it to the record's id (a string key).
registerPickOwner('ais-live-vessels', (pickedId) =>
state.records.byMmsi.has(pickedId),
state.records.byId.has(pickedId),
);
restoreSpriteOrderOnEnable('ais', activeViewer);
// Vessels are asked for by view, so ask again when the view moves away.
+96 -2
View File
@@ -98,7 +98,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', '_scratchFocusScreen'])
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);
@@ -272,7 +272,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();
@@ -421,3 +421,97 @@ 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, primitives } = 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(primitives.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, primitives } = setup({
getSnapshot: async () =>
snapshot([{ ...observation('7f3c9a10-provider-id'), name: 'NO MMSI' }]),
});
await layer.update();
assert.equal(primitives.size, 1);
const [primitive] = primitives;
assert.equal(primitive.id.id, '7f3c9a10-provider-id');
assert.equal(primitive.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'],
);
});
+109 -48
View File
@@ -28,6 +28,9 @@ import {
} 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,
services,
@@ -38,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.
@@ -175,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}}
@@ -188,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),
@@ -225,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;
@@ -275,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: Cesium.Cartesian3, 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: Cesium.Cartesian3, latitude: number, longitude: number, speedKt: number|null, course: number|null, type: string }|null}
*/
findByQuery(query) {
if (query === null || query === undefined) return null;
@@ -286,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();
@@ -306,6 +337,7 @@ export function createQueries({
components.rendering.getVisual(record).position;
if (!position) return null;
return {
id: record.id,
mmsi: record.mmsi,
name: record.name,
position,
@@ -322,7 +354,7 @@ export function createQueries({
* @param {Cesium.Cartesian3} centerCartesian Center 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: Cesium.Cartesian3, distanceM: number }>}
* @returns {Array<{ id: string, mmsi: string, name: string, position: Cesium.Cartesian3, distanceM: number }>}
*/
getNearby(centerCartesian, rangeM, maxCount = 25) {
const records = state.records.all;
@@ -342,6 +374,7 @@ export function createQueries({
const distanceM = Cesium.Cartesian3.distance(centerCartesian, position);
if (!Number.isFinite(distanceM) || distanceM > range) continue;
entries.push({
id: record.id,
mmsi: record.mmsi,
name: record.name,
position,
@@ -363,7 +396,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;
@@ -373,7 +406,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);
@@ -382,7 +415,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,
@@ -392,8 +425,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,
@@ -414,22 +447,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) {
@@ -445,8 +478,8 @@ export function createQueries({
const position = visual.billboard?.position || visual.position;
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,
@@ -479,16 +512,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;
@@ -505,12 +538,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,
@@ -521,6 +555,33 @@ 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: Cesium.Cartesian3, 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 visual = components.rendering.getVisual(record);
const position = visual?.billboard?.position || visual?.position;
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`
@@ -546,16 +607,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;
},
@@ -608,7 +669,7 @@ 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,
@@ -676,7 +737,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]);
+32 -23
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 || ''),
@@ -68,7 +76,7 @@ function motionBetween(record, next) {
export class VesselRecords {
constructor({ now = () => Date.now() } = {}) {
this.now = now;
this.byMmsi = new Map();
this.byId = new Map();
this.unkeyed = [];
this.all = [];
}
@@ -112,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) {
const before = effects.beforeUpdate(record);
// A feed re-serving a cached row repeats its fix: the fix keeps the
@@ -131,6 +139,7 @@ export class VesselRecords {
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;
@@ -148,15 +157,15 @@ export class VesselRecords {
effects.updated(record, before);
} 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.byMmsi.delete(mmsi);
effects.removed(mmsi);
this.byId.delete(id);
effects.removed(id);
continue;
}
if (
@@ -179,18 +188,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
@@ -18,8 +18,8 @@ function setup() {
beforeUpdate: (record) => record.type,
updated: (record, before) => events.push(['update', record, before]),
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 {
@@ -40,14 +40,14 @@ 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')[2], 'Cargo');
assert.equal(probe.store.byMmsi.has('222'), false);
assert.equal(probe.store.byId.has('222'), false);
for (const field of ['position', 'surfacePosition', 'normal', 'billboard'])
assert.equal(Object.hasOwn(record, field), false);
assert.deepEqual(structuredClone(record), record);
@@ -56,14 +56,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,
);
@@ -77,13 +77,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,
@@ -107,7 +107,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);
});
@@ -120,14 +120,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
@@ -141,3 +141,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);
});
+10 -10
View File
@@ -307,7 +307,7 @@ export function createRendering({
if (visual.billboard) {
// The bridge camera sits on this sprite; showing it would fill the view.
visual.billboard.show =
visible && record.mmsi !== state.cockpitSubjectMmsi;
visible && record.id !== state.cockpitSubjectId;
if (visible && doRotations && scene) {
const rot = screenProjectedRotation(
scene,
@@ -445,8 +445,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)]
: [];
@@ -532,17 +531,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;
@@ -574,7 +573,8 @@ export function createRendering({
text &&
text !== 'VESSEL' &&
!/^MMSI\s*\d+$/i.test(text) &&
text !== record.mmsi,
text !== record.mmsi &&
text !== record.id,
);
}
+21 -18
View File
@@ -39,13 +39,15 @@ 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 picked = pickContact
? pickContact(viewer.scene, click.position)
: viewer.scene.pick(click.position);
const pickedId = resolvePickId(picked);
let record = pickedId ? state.records.byMmsi.get(pickedId) : null;
let record = pickedId ? state.records.byId.get(pickedId) : null;
const rawId = picked?.id ?? picked?.primitive?.id;
// Every vessel record carries an `mmsi` field ('' when unknown); its
// key is `id`.
const ownRecordPick =
rawId && typeof rawId === 'object' && Object.hasOwn(rawId, 'mmsi');
@@ -85,10 +87,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;
@@ -100,8 +102,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();
@@ -123,17 +125,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.getVisual(record).billboard?.position ||
components.rendering.getVisual(record).position,
@@ -160,7 +162,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') {
@@ -169,8 +171,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;
@@ -188,7 +190,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 {
@@ -204,10 +206,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,
@@ -215,7 +217,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,
+4 -4
View File
@@ -44,7 +44,7 @@ export function createVesselSnapshotRenderer({
const nextIcon = rendering.shipIcon(record, selected);
if (nextIcon !== prevIcon) visual.billboard.image = nextIcon;
}
if (record.mmsi === state.trailMmsi)
if (record.id === state.trailId)
tracking.appendSelectedVesselTrailFix(record);
if (selected) {
cards.updateSelectedVesselHud(record);
@@ -55,8 +55,8 @@ 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);
@@ -64,7 +64,7 @@ export function createVesselSnapshotRenderer({
},
);
// The selected vessel at the new time: its trail starts there.
if (replace && state.selectedRecord && state.trailMmsi)
if (replace && state.selectedRecord && state.trailId)
tracking.startSelectedVesselTrail(state.selectedRecord);
state.lastVisibilityUpdate = 0;
rendering.updateVisibility(true);
+4 -4
View File
@@ -86,14 +86,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 {Cesium.Cartesian3[]} Chronological 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
@@ -32,6 +32,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;
@@ -42,15 +47,15 @@ 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;
state.billboardCollection = options.billboardCollection || { remove() {} };
state.trail = options.trail || null;
state.trailMmsi = options.trailMmsi || null;
state.trailId = options.trailId || null;
state.trailPositions = Array.isArray(options.trailPositions)
? [...options.trailPositions]
: [];
@@ -141,8 +146,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,
@@ -166,14 +171,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 {
+7 -11
View File
@@ -86,7 +86,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);
@@ -97,25 +97,21 @@ 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;
@@ -139,7 +135,7 @@ export function createTracking({
token !== state.trailBackfillToken
)
return;
if (state.trailMmsi !== mmsi) return;
if (state.trailId !== id) return;
const older = [];
for (const sample of samples) {
@@ -198,7 +194,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();
}