Files
gods-eye-view/src/layers/vessels/ownership.test.mjs
T
Sameh Khamis 7186f720df Sprites for helicopters, ground vehicles, stations and vessel types; history to live without an empty map; model parts in Cesium
Aircraft icons are one size; helicopters turn a three-frame rotor while
airborne or moving; ADS-B ground vehicles share one amber sprite and
stations/obstacles one mast; vessels get hull sprites by type and one buoy.
Going live keeps contacts until the first live answer and replaces them by
id; fast playback holds before the loaded positions end and prefetches
ahead. Cesium models move their parts from the optional model part state.
2026-11-17 15:09:54 -08:00

638 lines
21 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import test from 'node:test';
import assert from 'node:assert/strict';
import { createVesselLayer } from './index.js';
import { createVesselState } from './state.js';
import * as Cesium from 'cesium';
import { createVesselIconBook } from './iconBook.js';
import { liftedForHorizon } from '../../geo/horizon.js';
import { bindFakeCesiumCamera } from '../../testSupport/fakeCameraPort.mjs';
import { fakeDrawPort } from '../../testSupport/fakeDrawPort.mjs';
import { aidSprite, vesselSprite } from '../../data/vesselSprites.js';
import { VESSEL_KIND_STYLES } from '../../data/vesselTypes.js';
import { AID_TO_NAVIGATION_STYLE } from '../../data/vesselLabels.js';
import { cssColor } from '../../render/color.js';
/** A query port with nothing on screen: the viewer doubles have no scene. */
const offscreen = {
project: () => null,
projectMany: (source, out) => out.fill(NaN),
};
const noop = () => {};
function services() {
return {
context: {
clearSelectedEntityContextForLayer: noop,
registerEntityContext: () => null,
},
trails: {
createTrail: () => ({ setPositions: noop, clear: noop, destroy: noop }),
},
labels: { formatKnots: (knots) => `${knots} kt` },
picking: { unregisterPickOwner: noop },
overlay: {
setOverlayEntries: noop,
setOverlaySourceVisible: noop,
clearOverlaySource: noop,
},
geoid: {},
sprites: {},
focus: {
focusNowMs: (now) => now,
getFocusTarget: () => null,
focusPassIsNeeded: () => false,
forgetSpriteFocus: noop,
},
worldFocus: {},
render: {
holdContinuousRender: noop,
releaseContinuousRender: noop,
governorRequestRender: noop,
},
};
}
function setup(source, options = {}, viewer = {}) {
const layer = createVesselLayer({ source, services: services(), options });
const icons = createVesselIconBook();
if (viewer.camera)
bindFakeCesiumCamera(viewer, { query: offscreen, draw: fakeDrawPort() });
layer.testing._setVesselStateForTest({ viewer, icons });
let now = 1000;
layer.testing._setAisRuntimeForTest({
now: () => now,
setTimeout,
clearTimeout,
});
return {
layer,
icons,
advance: (ms) => {
now += ms;
},
};
}
const observation = (id, reference = id) => ({
id,
reference,
latitude: 51.93,
longitude: 4.05,
name: id,
observedAtMs: 500,
speedMps: 4,
headingDeg: 180,
courseDeg: 170,
});
const snapshot = (records, extra = {}) => ({
records,
source: 'Fixture vessels',
complete: true,
stale: false,
freshness: 'current',
observedAtMs: 500,
transportStatus: 'live',
rawRowCount: records.length,
...extra,
});
test('vessel construction is inert and each instance owns its records and clock', () => {
let requested = 0;
const source = {
getSnapshot() {
requested++;
},
};
const one = createVesselState({ source, services: services() });
const two = createVesselState({ source, services: services() });
assert.notEqual(one.state, two.state);
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);
assert.notEqual(one.state.trailPositions, two.state.trailPositions);
const { layer } = setup(source);
const other = createVesselLayer({ source, services: services() });
layer.testing._beginAisSessionForTest();
assert.equal(other.getStats().loading, false);
assert.equal(requested, 0);
layer.testing._setVesselStateForTest({ enabled: false });
});
test('missing vessel source fails before mutating the viewer', () => {
const layer = createVesselLayer({ services: services() });
assert.throws(() => layer.init({}), /snapshot source/);
layer.setSource({ getSnapshot: noop });
});
test('partial observations retain missing contacts only until their receipt deadline', async () => {
let current = snapshot([observation('111'), observation('222')]);
const { layer, advance } = setup({
async getSnapshot() {
return current;
},
});
await layer.update();
current = snapshot([observation('111')], { complete: false, rawRowCount: 2 });
await layer.update();
assert.equal(layer.hasContact('222'), true);
assert.equal(layer.getStats().stale, false);
assert.equal(layer.getStats().partial, true);
assert.equal(layer.getStats().rawRowCount, 2);
assert.equal(layer.getStats().acceptedRowCount, 1);
assert.equal(layer.getStats().lastUpdate, 500);
advance(5 * 60 * 1000);
await layer.update();
assert.equal(layer.hasContact('222'), false);
});
test('a complete feed still removes an absent unselected vessel immediately', async () => {
let current = snapshot([observation('111'), observation('222')]);
const { layer } = setup({
async getSnapshot() {
return current;
},
});
await layer.update();
current = snapshot([observation('111')]);
await layer.update();
assert.equal(layer.hasContact('222'), false);
});
test('an incomplete feed bounds its retained union to the configured row budget', async () => {
let current = snapshot(
Array.from({ length: 500 }, (_, i) => observation(String(i + 1000))),
);
const { layer } = setup(
{
async getSnapshot() {
return current;
},
},
{ maxRows: 500 },
);
await layer.update();
current = snapshot(
Array.from({ length: 500 }, (_, i) => observation(String(i + 2000))),
{ complete: false },
);
await layer.update();
assert.equal(layer.getStats().count, 500);
assert.equal(layer.hasContact('1000'), false);
assert.equal(layer.hasContact('2000'), true);
});
test('unknown source time does not become fresh at the time of receipt', async () => {
const { layer } = setup({
async getSnapshot() {
return snapshot([observation('111')], {
observedAtMs: null,
freshness: 'unknown',
});
},
});
await layer.update();
assert.equal(layer.getStats().lastUpdate, null);
assert.equal(layer.getStats().stale, true);
});
test('refresh replaces the history reference and clearing selection cancels late history', async (t) => {
const originalDocument = globalThis.document;
globalThis.document = { getElementById: () => null };
t.after(() => {
if (originalDocument === undefined) delete globalThis.document;
else globalThis.document = originalDocument;
});
let current = snapshot([observation('111', 'old-reference')]);
let request;
let resolveTrack;
const { layer } = setup({
async getSnapshot() {
return current;
},
getTrack(reference, { signal }) {
request = { reference, signal };
return new Promise((resolve) => {
resolveTrack = resolve;
});
},
});
await layer.update();
current = snapshot([observation('111', 'new-reference')]);
await layer.update();
assert.equal(layer.selectById('111'), true);
assert.equal(request.reference, 'new-reference');
layer.clearSelection();
assert.equal(request.signal.aborted, true);
resolveTrack({ records: [{ latitude: 51.94, longitude: 4.04 }] });
await new Promise(setImmediate);
assert.equal(layer.testing._getVesselStateForTest().trailPositionCount, 0);
});
test('destroy cancels pending observations and ignores their later completion', async (t) => {
const originalDocument = globalThis.document;
globalThis.document = { getElementById: () => null };
t.after(() => {
if (originalDocument === undefined) delete globalThis.document;
else globalThis.document = originalDocument;
});
let requestSignal;
let resolve;
const { layer } = setup({
getSnapshot(_query, { signal }) {
requestSignal = signal;
return new Promise((done) => {
resolve = done;
});
},
});
const pending = layer.update();
layer.destroy();
assert.equal(requestSignal.aborted, true);
resolve(snapshot([observation('111')]));
await pending;
assert.equal(layer.getStats().count, 0);
assert.equal(layer.hasContact('111'), null);
});
test('partial-feed expiry releases a selected vessel and its pending trail', async (t) => {
const originalDocument = globalThis.document;
globalThis.document = { getElementById: () => null };
t.after(() => {
if (originalDocument === undefined) delete globalThis.document;
else globalThis.document = originalDocument;
});
let current = snapshot([observation('111'), observation('222')]);
let signal;
let finish;
const { layer, advance } = setup({
async getSnapshot() {
return current;
},
getTrack(_reference, options) {
signal = options.signal;
return new Promise((resolve) => {
finish = resolve;
});
},
});
await layer.update();
layer.selectById('222');
current = snapshot([observation('111')], { complete: false });
await layer.update();
assert.equal(layer.getSelectedInfo().id, '222');
assert.equal(signal.aborted, false);
advance(5 * 60 * 1000);
await layer.update();
assert.equal(layer.getSelectedInfo(), null);
assert.equal(signal.aborted, true);
finish({ records: [] });
await new Promise(setImmediate);
assert.equal(layer.testing._getVesselStateForTest().trailPositionCount, 0);
});
test('refresh keeps the icon row and its pick identity, and eviction releases the row', async () => {
let current = snapshot([observation('111')]);
const { layer, icons } = setup({ getSnapshot: async () => current });
await layer.update();
assert.deepEqual(icons.ids(), ['111']);
const meta = icons.item('111').meta;
const drawn = () => icons.item('111').pos;
const near = (a, b) => Cesium.Cartesian3.distance(a, b) < 0.01;
assert.ok(near(layer.findByQuery('111').position, drawn()));
const oldPosition = drawn();
current = snapshot([{ ...observation('111'), longitude: 4.06 }]);
await layer.update();
assert.equal(icons.size, 1);
assert.equal(
icons.item('111').meta,
meta,
'focus identity survives a refresh',
);
assert.ok(!near(drawn(), oldPosition));
assert.ok(near(layer.findByQuery('111').position, drawn()));
current = snapshot([observation('222')]);
await layer.update();
assert.equal(icons.has('111'), false);
assert.equal(layer.findByQuery('111'), null);
});
test('partial vessel snapshots preserve freshness and recover after a complete update', async (t) => {
const originalDocument = globalThis.document;
globalThis.document = { getElementById: () => null };
t.after(() => {
if (originalDocument === undefined) delete globalThis.document;
else globalThis.document = originalDocument;
});
const { vesselSnapshot } = await import('../../sources/live/vessels.js');
const { layerFeedState } = await import('../../data/feedState.js');
const valid = {
mmsi: '123456789',
lat: 51.93,
lon: 4.05,
last_position_epoch: 1,
};
let current = vesselSnapshot({
rows: [valid, { ...valid }, { mmsi: '987654321', lat: 200, lon: 4 }],
status: 'live',
});
const { layer } = setup({ getSnapshot: async () => current });
await layer.update();
assert.equal(layer.getStats().partial, true);
assert.equal(layer.getStats().stale, false);
assert.equal(layer.getStats().rawRowCount, 3);
assert.equal(layer.getStats().acceptedRowCount, 1);
assert.equal(layerFeedState(layer.getStats()), 'partial');
assert.equal(layer.hasContact('123456789'), true);
for (const extra of [
{ stale: true },
{ freshness: 'stale' },
{ freshness: 'unknown', observedAtMs: null },
{ transportStatus: 'stale' },
]) {
const original = current;
current = { ...original, ...extra };
await layer.update();
assert.equal(layer.getStats().partial, true);
assert.equal(layerFeedState(layer.getStats()), 'stale');
current = original;
}
current = { ...current, transportStatus: 'reconnecting' };
await layer.update();
assert.equal(layerFeedState(layer.getStats()), 'degraded');
assert.match(layer.getStats().error, /reconnecting/);
current = vesselSnapshot({ rows: [valid], status: 'live' });
await layer.update();
assert.equal(layer.getStats().partial, false);
assert.equal(layer.getStats().stale, false);
assert.equal(layer.getStats().error, null);
assert.equal(layerFeedState(layer.getStats()), 'nominal');
current = { ...current, complete: false };
await layer.update();
assert.equal(layer.getStats().partial, true);
layer.destroy();
assert.equal(layer.getStats().partial, false);
});
test('authoritative empty coverage clears old contacts without declaring an outage', async () => {
let current = snapshot([observation('111')]);
const { layer } = setup({
async getSnapshot() {
return current;
},
});
await layer.update();
current = snapshot([], { observedAtMs: null, lastMessageAt: 500 });
await layer.update();
assert.ok(!layer.hasContact('111'));
assert.equal(layer.getStats().count, 0);
assert.equal(layer.getStats().error, null);
assert.equal(layer.getStats().stale, false);
assert.equal(layer.getStats().lastUpdate, null);
});
test('empty coverage cannot hide stale, incomplete or rejected source data', async () => {
for (const patch of [
{ freshness: 'unknown' },
{ freshness: 'stale' },
{ complete: false },
{ rawRowCount: 1 },
{ transportStatus: 'stale' },
{ lastMessageAt: null },
]) {
let current = snapshot([observation('111')]);
const { layer } = setup({
async getSnapshot() {
return current;
},
});
await layer.update();
current = snapshot([], {
observedAtMs: null,
lastMessageAt: 500,
...patch,
});
await layer.update();
assert.equal(layer.hasContact('111'), true, JSON.stringify(patch));
assert.ok(layer.getStats().error, JSON.stringify(patch));
}
});
test('cards and detection judge the horizon where the icon shader culls the row', async () => {
// A camera over the limb that sees the row's cull point (lifted to 12 m) but
// not the drawn position (3 m above the ellipsoid before the geoid loads).
const ship = Cesium.Cartesian3.fromDegrees(4.05, 51.93, 3);
const lifted = Cesium.Cartesian3.fromDegrees(4.05, 51.93, 12);
const occluder = new Cesium.EllipsoidalOccluder(Cesium.Ellipsoid.WGS84, ship);
let positionWC = null;
for (let lon = 4.05; lon < 40 && !positionWC; lon += 0.0005) {
occluder.cameraPosition = Cesium.Cartesian3.fromDegrees(
lon,
51.93,
400_000,
);
if (occluder.isPointVisible(lifted) && !occluder.isPointVisible(ship))
positionWC = occluder.cameraPosition;
}
assert.ok(positionWC, 'found a camera between the two horizons');
const viewer = { camera: { positionWC, heading: 0, pitch: 0, roll: 0 } };
const current = snapshot([observation('111')]);
const { layer, icons } = setup(
{ getSnapshot: async () => current },
{},
viewer,
);
await layer.update();
occluder.cameraPosition = positionWC;
assert.equal(
occluder.isPointVisible(liftedForHorizon(icons.item('111').pos)),
true,
);
assert.deepEqual(
layer.getDetectableObjects().map((entry) => entry.sourceId),
['111'],
);
layer.testing._setVesselStateForTest({ enabled: false });
});
test('vessel stats name the provider the last snapshot reported', async () => {
const { layer } = setup({
label: 'Vessels',
async getSnapshot() {
return snapshot([observation('111')], { source: 'Datalastic' });
},
});
assert.equal(layer.getStats().source, 'Vessels');
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'],
);
});
test('an aid to navigation is drawn as the upright buoy, a vessel as its kind’s hull turned with course', async () => {
const aid = {
...observation('993672001'),
mmsi: '993672001',
type: 'Port Hand Mark',
speedMps: 0,
};
const ship = { ...observation('366999002'), type: 'Cargo' };
const sailing = { ...observation('366999003'), type: '36' };
const { layer, icons } = setup({
async getSnapshot() {
return snapshot([aid, ship, sailing]);
},
});
await layer.update();
const itemOf = (id) => {
assert.ok(icons.has(id), id);
return icons.item(id);
};
const buoy = itemOf('993672001');
assert.equal(buoy.image, aidSprite());
assert.equal(buoy.rotationMode, 'screen', 'upright');
assert.equal(buoy.rotation, 0, 'never turned');
assert.deepEqual(buoy.color, cssColor(AID_TO_NAVIGATION_STYLE.css));
// The source's virtual flag reaches the layer's record.
const recordOf = (id) => layer.testing._vesselRecordForTest(id);
assert.equal(recordOf('993672001').virtual, false);
assert.equal(recordOf('366999002').virtual, false);
const cargo = itemOf('366999002');
assert.equal(cargo.image, vesselSprite('cargo'));
assert.equal(cargo.rotationMode, 'course');
assert.deepEqual(cargo.color, cssColor(VESSEL_KIND_STYLES.cargo.css));
const sail = itemOf('366999003');
assert.equal(sail.image, vesselSprite('sailing'));
assert.deepEqual(sail.color, cssColor(VESSEL_KIND_STYLES.sailing.css));
// Every vessel and aid draws the same size before its speed scale.
assert.deepEqual(cargo.size, buoy.size);
assert.deepEqual(sail.size, buoy.size);
});
test('a virtual aid to navigation keeps its buoy and its virtual flag', async () => {
const aid = {
...observation('993672009'),
mmsi: '993672009',
type: 'Isolated danger',
virtual: true,
};
const { layer, icons } = setup({
async getSnapshot() {
return snapshot([aid]);
},
});
await layer.update();
assert.ok(icons.has('993672009'));
assert.equal(layer.testing._vesselRecordForTest('993672009').virtual, true);
assert.equal(icons.item('993672009').image, aidSprite());
});
test('a feed with no AISStream key reports its key as required, and a live one does not', async () => {
let current = snapshot([], {
transportStatus: 'missing-key',
complete: false,
});
const { layer } = setup({
async getSnapshot() {
return current;
},
});
assert.equal(layer.requiresKeyId, 'aisstream');
await layer.update();
assert.equal(layer.getStats().keyRequired, true);
current = snapshot([observation('111')]);
await layer.update();
assert.equal(layer.getStats().keyRequired, false);
});