feat(app): layer catalog per engine

- src/app/layers/renderers.js: the layer renderer registry
  (registerLayerRenderers(engineKind, { [layerId]: factory }),
  rendererFor(layerId, engine), layerAvailableOn(layerId, engineKind)).
  Every application layer is registered for Cesium as CESIUM_BUILTIN (it
  still draws itself until its render/cesium.js); Navara factories come with
  the layer tasks. On it, the stable availability API phase 4 injects into
  its layer list: createLayerAvailability(engineKind) →
  { engine, isAvailable(id), available(), unavailable() } with { id, name }
  rows (src/app/layers/directory.js holds the ids and names in catalog
  order; a test keeps it equal to the constructed catalog).
- createApplicationCatalog({ engineKind, availability }) constructs only the
  layers the engine can show, in the same order (shared instances made
  once, on demand); the catalog carries `availability` and the others'
  metadata (`unavailableMetadata`). Cesium builds the same 30 layers in the
  same order as before; Navara builds none yet (no Navara renderers) - the
  standalone app now asks the catalog for it instead of making an empty one.
- catalogControlServices: a role whose layer the engine leaves out gets an
  empty stand-in (absentLayerControlServices folded in); any other missing
  layer is still a wiring error.
- LayerLifecycle(viewer, { engine }): every module call (init, enable,
  update, disable, destroy) gets { signal, engine } as its second argument;
  viewer is null on Navara.
- Links: a link that turns on layers this engine leaves out keeps them in
  the durable state (re-saved links carry them; back on Cesium they turn
  on) and activates nothing; a notice names them ("NOT ON THIS ENGINE · Kept
  in the link: …"). The Navara notice lists the engine's data layers from
  the registry.
- The dev launcher's CCTV wiring check matches the new catalog form.
This commit is contained in:
German Khokhlov committed 2026-10-16 22:07:55 +04:00
1 parent e1be2eac19
commit b0cbed081b
23 files changed
+826 -146

No files matched your search

+46
View File
@@ -2793,3 +2793,49 @@ test('explicit provider switches reach durable state without adopting unrelated
coordinator.destroy();
}
});
test('a link through an engine without some layers keeps their state and activates nothing', async () => {
// The Navara catalog: only satellites registered.
const manager = new DataLayerManager({});
const enabled = [];
manager.register(
fakeLayer('satellites', { enable: () => (enabled.push('satellites'), true) }),
);
manager.finalizeRegistrations(
LAYER_STATE_REGISTRY.filter(({ id }) => id === 'satellites'),
);
const shared = normalizeLayerState({
enabledLayerIds: ['flights', 'ais-live-vessels', 'satellites'],
});
const sink = shareSink();
const coordinator = new LayerStateCoordinator(manager, sink, {
storage: memoryStorage(),
});
const results = await coordinator.start({
shareLayerState: shared,
shareCreatedAtMs: 1_000,
});
assert.deepEqual(enabled, ['satellites'], 'only the registered layer runs');
const missing = results
.filter(({ phase, targetEnabled }) => phase === 'missing' && targetEnabled)
.map(({ layerId }) => layerId)
.sort();
assert.deepEqual(missing, ['ais-live-vessels', 'flights']);
// Re-saved (the link the user copies on Navara): the state is all there.
assert.deepEqual(
sink.provider().enabledLayerIds,
['ais-live-vessels', 'flights', 'satellites'],
);
// An explicit change of a layer that is here keeps the others too.
await manager.setEnabled('satellites', false, { origin: 'user' });
assert.deepEqual(sink.provider().enabledLayerIds, [
'ais-live-vessels',
'flights',
]);
// And back on Cesium the link turns them on.
const decoded = decodeLayerStateParams(
new URLSearchParams(encode(sink.provider())),
);
assert.deepEqual(decoded.enabledLayerIds, ['ais-live-vessels', 'flights']);
coordinator.destroy();
});
+55 -13
View File
@@ -1,3 +1,4 @@
import { engineFromViewer } from '../globe/cesium/engineFromViewer.js';
import { cancelCameraArrival } from './cameraArrival.js';
function cloneLayerParams(value) {
@@ -74,12 +75,20 @@ function refreshFailureFromStats(stats, label) {
* for real-time data overlays on the CesiumJS globe.
*/
export class LayerLifecycle {
/**
* @param {object | null} viewer The Cesium viewer (null on Navara).
* @param {{ engine?: import('../globe/contract.js').GlobeEngine,
* allowQaRegistration?: boolean, getSourceAvailability?: Function }} [options]
* `engine` (default: the viewer's registered engine): every module call
* gets `{ signal, engine }` as its second argument.
*/
constructor(
viewer,
{ allowQaRegistration = false, getSourceAvailability } = {},
{ allowQaRegistration = false, getSourceAvailability, engine } = {},
) {
this._catalogSourceAvailability = getSourceAvailability;
this.viewer = viewer;
this.engine = engine ?? engineFromViewer(viewer) ?? null;
this._activityListeners = new Set();
this.layers = new Map(); // id → { module, enabled, initialized, intervalId, lifecycleState, lifecycleUncertain }
this._listeners = new Set();
@@ -92,6 +101,11 @@ export class LayerLifecycle {
this._qaLayerIds = new Set();
}
/** The second argument of every layer module call: `{ signal, engine }`. */
_moduleContext(signal = null) {
return { signal, engine: this.engine };
}
register(layerModule) {
if (this._registrationsFinalized) {
throw new Error('Data-layer registrations are finalized');
@@ -292,7 +306,10 @@ export class LayerLifecycle {
let result;
let failure = null;
try {
result = await entry.module.update(this.viewer, { signal });
result = await entry.module.update(
this.viewer,
this._moduleContext(signal),
);
// Even a rejected/partial update may have changed the data exposed by
// the layer. Publish before classifying its result so observers see it.
this._publishActivity({ type: 'data-updated', layerId });
@@ -739,7 +756,9 @@ export class LayerLifecycle {
let compensated = false;
let compensationError = null;
try {
compensated = (await entry.module.enable(this.viewer)) !== false;
compensated =
(await entry.module.enable(this.viewer, this._moduleContext())) !==
false;
if (!compensated) {
compensationError = lifecycleRejectedError(
layerId,
@@ -757,7 +776,10 @@ export class LayerLifecycle {
if (!compensated) {
try {
cleanupConfirmed =
(await entry.module.disable(this.viewer)) !== false;
(await entry.module.disable(
this.viewer,
this._moduleContext(),
)) !== false;
} catch (error) {
console.warn(
`[Data] ${layerId} cancelled-disable final cleanup error:`,
@@ -805,7 +827,10 @@ export class LayerLifecycle {
return false;
};
try {
const disabled = await entry.module.disable(this.viewer, { signal });
const disabled = await entry.module.disable(
this.viewer,
this._moduleContext(signal),
);
if (disabled === false)
throw lifecycleRejectedError(layerId, 'disable');
} catch (e) {
@@ -854,7 +879,7 @@ export class LayerLifecycle {
// where an asynchronous enable finishes after this callback.
try {
abortCleanup = Promise.resolve(
entry.module.disable(this.viewer),
entry.module.disable(this.viewer, this._moduleContext()),
).catch((error) => {
console.warn(
`[Data] ${layerId} cancelled-enable cleanup error:`,
@@ -883,7 +908,8 @@ export class LayerLifecycle {
let cleanupConfirmed = false;
try {
cleanupConfirmed =
(await entry.module.disable(this.viewer)) !== false;
(await entry.module.disable(this.viewer, this._moduleContext())) !==
false;
} catch (error) {
console.warn(
`[Data] ${layerId} cancelled-enable final cleanup error:`,
@@ -924,7 +950,8 @@ export class LayerLifecycle {
let cleanupConfirmed = false;
try {
cleanupConfirmed =
(await entry.module.disable(this.viewer)) !== false;
(await entry.module.disable(this.viewer, this._moduleContext())) !==
false;
} catch (cleanupError) {
console.warn(
`[Data] ${layerId} failed-enable cleanup error:`,
@@ -950,7 +977,10 @@ export class LayerLifecycle {
if (!entry.initialized) {
this._setVisibilityIntentPhase(entry, intentEpoch, 'init');
try {
const initialized = await entry.module.init(this.viewer, { signal });
const initialized = await entry.module.init(
this.viewer,
this._moduleContext(signal),
);
if (initialized === false)
throw lifecycleRejectedError(layerId, 'init');
entry.initialized = true;
@@ -990,7 +1020,10 @@ export class LayerLifecycle {
entry.lifecycleUncertain = false;
this._setVisibilityIntentPhase(entry, intentEpoch, 'enable');
try {
const enabled = await entry.module.enable(this.viewer, { signal });
const enabled = await entry.module.enable(
this.viewer,
this._moduleContext(signal),
);
if (enabled === false) throw lifecycleRejectedError(layerId, 'enable');
} catch (e) {
if (signal?.aborted || isAbortError(e)) {
@@ -1006,7 +1039,10 @@ export class LayerLifecycle {
// First update immediately
this._setVisibilityIntentPhase(entry, intentEpoch, 'update');
try {
const updated = await entry.module.update(this.viewer, { signal });
const updated = await entry.module.update(
this.viewer,
this._moduleContext(signal),
);
if (updated === false) throw lifecycleRejectedError(layerId, 'update');
} catch (e) {
if (signal?.aborted || isAbortError(e)) {
@@ -2146,7 +2182,10 @@ export class LayerLifecycle {
entry.latestQueuedAbsoluteIntent = null;
if (entry.enabled) {
try {
const disabled = await entry.module.disable(this.viewer);
const disabled = await entry.module.disable(
this.viewer,
this._moduleContext(),
);
if (disabled === false)
throw lifecycleRejectedError(layerId, 'destroy-disable');
} catch (e) {
@@ -2165,7 +2204,10 @@ export class LayerLifecycle {
}
if (typeof entry.module.destroy === 'function') {
try {
const destroyed = await entry.module.destroy(this.viewer);
const destroyed = await entry.module.destroy(
this.viewer,
this._moduleContext(),
);
if (destroyed === false)
throw lifecycleRejectedError(layerId, 'destroy');
} catch (e) {
+48
View File
@@ -0,0 +1,48 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { LayerLifecycle } from './lifecycle.js';
import { createFakeEngine } from '../globe/testing/fakeEngine.js';
// A layer module that records the second argument of every lifecycle call.
function recordingLayer(id) {
const calls = [];
const record = (name) => (_viewer, context) => {
calls.push([name, context]);
return true;
};
return {
calls,
module: {
id,
name: id,
icon: '',
source: 'test',
init: record('init'),
enable: record('enable'),
update: record('update'),
disable: record('disable'),
destroy: record('destroy'),
},
};
}
test('every layer module call gets { signal, engine }, also with no viewer', async () => {
const engine = createFakeEngine({ kind: 'navara' });
const lifecycle = new LayerLifecycle(null, { engine });
assert.equal(lifecycle.engine, engine);
const layer = recordingLayer('probe');
lifecycle.register(layer.module);
lifecycle.finalizeRegistrations([
{ id: 'probe', disposition: 'enabled-only', token: 'z' },
]);
await lifecycle.setEnabled('probe', true, { origin: 'user' });
await lifecycle.setEnabled('probe', false, { origin: 'user' });
await lifecycle.destroyAll();
const names = layer.calls.map(([name]) => name);
for (const name of ['init', 'enable', 'disable', 'destroy'])
assert.ok(names.includes(name), `${name} was called: ${names}`);
for (const [name, context] of layer.calls) {
assert.equal(context?.engine, engine, `${name} got the engine`);
assert.ok('signal' in context, `${name} got a signal slot`);
}
});