@yarkivaev/scada 2.18.0 → 2.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.js +13 -0
- package/package.json +4 -2
- package/src/application/cycleTimelineFetch.js +56 -0
- package/src/application/deploy/edgeDescriptors.js +31 -0
- package/src/application/deploy/fieldbusSourcePlan.js +79 -0
- package/src/application/deploy/plantBindingProfile.js +24 -0
- package/src/application/deploy/topologyGraph.js +81 -0
- package/src/application/edgeOperatorCatalog.js +9 -7
- package/src/application/mcp/analyticsMcpPort.js +20 -0
- package/src/application/mcp/analyticsNamespaceNodes.js +29 -0
- package/src/application/mcp/analyticsTextContent.js +13 -0
- package/src/application/mcp/plantReadPorts.js +168 -0
- package/src/application/mcp/textContentCatalog.js +7 -0
- package/src/application/operationPrefixes.js +67 -0
- package/src/application/operatorCatalogView.js +8 -0
- package/src/application/projectPlantShops.js +17 -0
- package/src/application/runtime/collectorDslManifest.js +44 -0
- package/src/application/runtime/collectorLaunch.js +34 -0
- package/src/application/runtime/collectorOptions.js +21 -0
- package/src/application/runtime/controlDeliveryEnvironment.js +19 -0
- package/src/application/runtime/embeddedCollectors.js +6 -0
- package/src/application/runtime/index.js +7 -1
- package/src/application/runtime/pagedDelivery.js +87 -0
- package/src/application/runtime/resolveSecrets.js +9 -0
- package/src/application/siteOperatorCatalog.js +8 -7
- package/src/application/siteRuntime/checkpointedOperationPoll.js +77 -0
- package/src/application/siteRuntime/cutoverOperations.js +25 -0
- package/src/application/siteRuntime/databaseMigrations.js +27 -0
- package/src/application/siteRuntime/edgeMetricsStore.js +35 -0
- package/src/application/siteRuntime/history.js +29 -0
- package/src/application/siteRuntime/index.js +16 -0
- package/src/application/siteRuntime/measurementTopic.js +9 -0
- package/src/application/siteRuntime/operationFederation.js +15 -0
- package/src/application/siteRuntime/operationSnapshot.js +18 -0
- package/src/application/siteRuntime/operatorField.js +49 -0
- package/src/application/siteRuntime/operatorUpdates.js +37 -0
- package/src/application/siteRuntime/telemetry.js +31 -0
- package/src/application/siteRuntime/telemetryBackfillCommand.js +64 -0
- package/src/application/timelineMetrics.js +36 -0
- package/src/domain/timeline/cyclePhases.js +191 -0
- package/src/infrastructure/deploy/brokerFleetPolicy.js +91 -0
- package/src/infrastructure/deploy/configuredArchivePlan.js +25 -0
- package/src/infrastructure/deploy/configuredBrokerRoutes.js +34 -0
- package/src/infrastructure/deploy/configuredClassification.js +74 -0
- package/src/infrastructure/deploy/configuredControlPlane.js +116 -0
- package/src/infrastructure/deploy/configuredDeploymentCredentials.js +45 -0
- package/src/infrastructure/deploy/configuredEtcdInventory.js +30 -0
- package/src/infrastructure/deploy/configuredRuntimeCapabilities.js +14 -0
- package/src/infrastructure/deploy/configuredSiteAssets.js +50 -0
- package/src/infrastructure/deploy/configuredStagedDeployment.js +48 -0
- package/src/infrastructure/deploy/highAvailability/configuredBrokerReconciliation.js +21 -0
- package/src/infrastructure/deploy/highAvailability/index.js +1 -0
- package/src/infrastructure/deploy/index.js +19 -0
- package/src/infrastructure/deploy/mixedStoreHistory.js +27 -0
- package/src/infrastructure/deploy/publicBrokerPlan.js +15 -0
- package/src/infrastructure/deploy/siteBrokerDefinitions.js +97 -0
- package/src/infrastructure/deploy/stagedSitePlan.js +132 -0
- package/src/infrastructure/deploy/supervisedServicePlan.js +82 -0
- package/src/infrastructure/http/edge/attachClassify.js +30 -0
- package/src/infrastructure/http/edge/classifyProxy.js +72 -0
- package/src/infrastructure/http/edge/classifyRecord.js +32 -0
- package/src/infrastructure/http/edge/classifyRouting.js +14 -0
- package/src/infrastructure/http/edge/siteAccess.js +7 -0
- package/src/infrastructure/http/edge/writeGuard.js +84 -0
- package/src/infrastructure/http/plant/routes/machineOperationList.js +18 -0
- package/src/infrastructure/http/plant/routes/operationRoute.js +2 -11
- package/src/infrastructure/http/plant/routes/operatorRoute.js +25 -0
- package/src/infrastructure/http/plant/streams/operationStream.js +25 -37
- package/src/infrastructure/ingest/mqtt/modbusDeviceSpec.js +5 -28
- package/src/infrastructure/ingest/mqtt/registerPoint.js +2 -2
- package/src/infrastructure/mdmesh/adminReconciliation.js +19 -0
- package/src/infrastructure/mdmesh/bootstrapMdmeshCredentials.js +4 -4
- package/src/infrastructure/mdmesh/controllerOperation.js +17 -0
- package/src/infrastructure/mdmesh/index.js +3 -0
- package/src/infrastructure/mdmesh/publishApk.js +30 -0
- package/src/infrastructure/persistence/clickhouse/metricBursts.js +73 -0
- package/src/infrastructure/persistence/pg/cyclePhaseQuery.js +168 -0
- package/src/infrastructure/persistence/pg/cyclePrior.js +96 -0
- package/src/infrastructure/persistence/pg/operatorFieldStore.js +50 -0
- package/src/infrastructure/streams/boundedTextFrames.js +27 -0
- package/src/infrastructure/streams/framedSerialSource.js +25 -0
- package/src/infrastructure/streams/index.js +5 -0
- package/src/infrastructure/streams/namedSerialDevices.js +26 -0
- package/src/infrastructure/streams/serialLine.js +26 -0
- package/src/infrastructure/streams/watchCurrentReading.js +31 -0
- package/src/infrastructure/streams/windowPublication.js +73 -0
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import initialized from '../domain/shared/initialized.js';
|
|
2
|
+
import plant from '../domain/plant/plant.js';
|
|
3
|
+
|
|
4
|
+
/** Group machine descriptors and assemble shops with application-provided sensors and site options. */
|
|
5
|
+
export default function projectPlantShops(machines, { defaultShop, sensors, shop, extras }) {
|
|
6
|
+
const groups = new Map();
|
|
7
|
+
for (const entry of machines) {
|
|
8
|
+
const name = entry.shop || defaultShop;
|
|
9
|
+
if (!groups.has(name)) { groups.set(name, []); }
|
|
10
|
+
groups.get(name).push(entry);
|
|
11
|
+
}
|
|
12
|
+
const shops = Object.fromEntries([...groups].map(([name, entries]) => {
|
|
13
|
+
const items = entries.map((entry) => { return { name: entry.machine, kind: entry.kind, sensors: sensors(entry) }; });
|
|
14
|
+
return [name, shop(items, name)];
|
|
15
|
+
}));
|
|
16
|
+
return plant(initialized(shops, Object.values), extras());
|
|
17
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import compileCollectorTasks from '../deploy/compileCollectorTasks.js';
|
|
3
|
+
import readDeploymentDocument from '../deploy/readDeploymentDocument.js';
|
|
4
|
+
|
|
5
|
+
function jobs(document, options) {
|
|
6
|
+
if (!options.tasks.length) { throw new TypeError('Named collector DSL requires explicit --task selection'); }
|
|
7
|
+
if (options.cluster || options.stream || options.adapter) { throw new TypeError('Named tasks cannot combine device selectors'); }
|
|
8
|
+
const available = new Set(document.collectorTasks.map((task) => { return task.taskId; }));
|
|
9
|
+
options.tasks.forEach((id) => { if (!available.has(id) && !options.previousIds.has(id)) { throw new TypeError(`Unknown collector task ${id}`); } });
|
|
10
|
+
const collectorTasks = document.collectorTasks.filter((task) => { return options.tasks.includes(task.taskId); });
|
|
11
|
+
return compileCollectorTasks({ collectorTasks }, {}, options.generation).map((task) => {
|
|
12
|
+
if (task.spec.delivery !== 'durable' || task.spec.compatibilityKey) { return task; }
|
|
13
|
+
const compatibilityKey = createHash('sha256').update(JSON.stringify({ adapter: task.spec.adapter, source: task.spec.source, transform: task.spec.transform, stateVersion: task.spec.stateVersion })).digest('hex');
|
|
14
|
+
return { ...task, spec: { ...task.spec, compatibilityKey } };
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
function execution(document, options) {
|
|
18
|
+
const selected = (document.collectorTasks ?? []).filter((task) => { return options.tasks.includes(task.taskId); });
|
|
19
|
+
const finite = selected.filter((task) => { return task.execution?.mode === 'once'; });
|
|
20
|
+
if (!finite.length) { return undefined; }
|
|
21
|
+
if (selected.length !== 1) { throw new TypeError('Run one-shot tasks separately from other assignments'); }
|
|
22
|
+
const { startTimeoutMs } = finite[0].execution;
|
|
23
|
+
if (!Number.isSafeInteger(startTimeoutMs) || startTimeoutMs < 1) { throw new TypeError('One-shot task requires a bounded startTimeoutMs'); }
|
|
24
|
+
return { mode: 'once', startTimeoutMs };
|
|
25
|
+
}
|
|
26
|
+
function retirements(assignments, status, generation) {
|
|
27
|
+
const desired = new Set(assignments.map((task) => { return task.taskId; }));
|
|
28
|
+
const retired = status.tasks.filter((task) => { return task.state !== 'stopped' && !desired.has(task.taskId); });
|
|
29
|
+
if (retired.some((task) => { return generation <= task.generation; })) { throw new TypeError('Increment DSL generation before retiring assignments'); }
|
|
30
|
+
return retired.map((task) => { return { taskId: task.taskId, generation }; });
|
|
31
|
+
}
|
|
32
|
+
/** Read declarations on every reconcile and project assignments through the configured deployment ports. */
|
|
33
|
+
export default function collectorDslManifest({ read = readDeploymentDocument, devices, amend = (tasks) => { return tasks; } } = {}) {
|
|
34
|
+
return (options, status = { tasks: [] }) => {
|
|
35
|
+
const document = read(options.file);
|
|
36
|
+
const generation = options.generation ?? document.generation ?? 1;
|
|
37
|
+
if (!Number.isSafeInteger(generation) || generation < 0) { throw new TypeError('Invalid generation'); }
|
|
38
|
+
const selection = { ...options, generation, previousIds: new Set(status.tasks.map((task) => { return task.taskId; })) };
|
|
39
|
+
if (!document.collectorTasks && options.tasks.length) { throw new TypeError('--task requires named collector declarations'); }
|
|
40
|
+
const assignments = amend(document.collectorTasks ? jobs(document, selection) : devices(document, selection), document);
|
|
41
|
+
if (!assignments.length && !status.tasks.length) { throw new TypeError('DSL selection has no collector assignments'); }
|
|
42
|
+
return { assignments, removals: retirements(assignments, status, generation), execution: execution(document, selection) };
|
|
43
|
+
};
|
|
44
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import runCollector from './runCollector.js';
|
|
2
|
+
import collectorOptions from './collectorOptions.js';
|
|
3
|
+
import controlDeliveryEnvironment from './controlDeliveryEnvironment.js';
|
|
4
|
+
|
|
5
|
+
/** Run a live or bounded manifest while preserving the same reload path. */
|
|
6
|
+
export async function collectorLaunch(options, registry, manifest, { run = runCollector, env = process.env } = {}) {
|
|
7
|
+
if (env.COLLECTOR_MANIFEST || env.COLLECTOR_MANIFEST_PATH) { throw new TypeError('Choose DSL or compiled manifest, not both'); }
|
|
8
|
+
const initial = manifest(options);
|
|
9
|
+
if (options.render) {
|
|
10
|
+
for (const { spec } of initial.assignments) {
|
|
11
|
+
// Match runtime validation order and stop on the first invalid assignment.
|
|
12
|
+
// eslint-disable-next-line no-await-in-loop
|
|
13
|
+
await registry.get(spec.adapter).validate(spec);
|
|
14
|
+
}
|
|
15
|
+
return initial;
|
|
16
|
+
}
|
|
17
|
+
const collector = await run({ registry, env, startTimeoutMs: initial.execution?.startTimeoutMs,
|
|
18
|
+
manifestReader(_env, _argv, status) { return manifest(options, status); } });
|
|
19
|
+
if (initial.execution?.mode === 'once') { await collector.stop(); }
|
|
20
|
+
return null;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Run the collector command with the application's registry and manifest bindings. */
|
|
24
|
+
export async function launchCollectorCommand(argv, {
|
|
25
|
+
registry, manifest, delivery, env = process.env, run = runCollector,
|
|
26
|
+
write = (body) => { process.stdout.write(body); }
|
|
27
|
+
}) {
|
|
28
|
+
controlDeliveryEnvironment(env, delivery);
|
|
29
|
+
const adapters = registry();
|
|
30
|
+
if (argv.some((arg) => { return arg.startsWith('--'); })) {
|
|
31
|
+
const result = await collectorLaunch(collectorOptions(argv), adapters, manifest, { run, env });
|
|
32
|
+
if (result) { write(`${JSON.stringify(result, null, 2)}\n`); }
|
|
33
|
+
} else { await run({ registry: adapters, env, argv }); }
|
|
34
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
const flags = new Map([['--dsl', 'file'], ['--cluster', 'cluster'], ['--adapter', 'adapter'], ['--stream', 'stream'], ['--generation', 'generation']]);
|
|
2
|
+
function argument(options, argv, index) {
|
|
3
|
+
const flag = argv[index];
|
|
4
|
+
if (flag === '--render') { options.render = true; return 0; }
|
|
5
|
+
const key = flags.get(flag);
|
|
6
|
+
if (!key && flag !== '--task') { throw new TypeError(`Unknown collector option ${flag}`); }
|
|
7
|
+
const value = argv[index + 1];
|
|
8
|
+
if (!value || value.startsWith('--')) { throw new TypeError(`Missing value for ${flag}`); }
|
|
9
|
+
if (flag === '--task') { options.tasks.push(value); }
|
|
10
|
+
else { options[key] = key === 'generation' ? Number(value) : value; }
|
|
11
|
+
return 1;
|
|
12
|
+
}
|
|
13
|
+
/** Explicit DSL selection; no protocol-specific environment translation. */
|
|
14
|
+
export default function collectorOptions(argv) {
|
|
15
|
+
const options = { tasks: [], render: false };
|
|
16
|
+
for (let index = 0; index < argv.length; index += 1) { index += argument(options, argv, index); }
|
|
17
|
+
if (!options.file) { throw new TypeError('--dsl is required for DSL options'); }
|
|
18
|
+
if (options.generation !== undefined && (!Number.isSafeInteger(options.generation) || options.generation < 0)) { throw new TypeError('Invalid generation'); }
|
|
19
|
+
if (new Set(options.tasks).size !== options.tasks.length) { throw new TypeError('Duplicate task selection'); }
|
|
20
|
+
return options;
|
|
21
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
function peerUrl(endpoint, secret) {
|
|
2
|
+
const target = new URL(endpoint);
|
|
3
|
+
const credentials = new URL(secret);
|
|
4
|
+
if (target.protocol !== 'amqp:' || !['amqp:', 'amqps:'].includes(credentials.protocol)) { throw new TypeError('Invalid control broker endpoint'); }
|
|
5
|
+
if (!credentials.username || decodeURIComponent(credentials.username) === 'guest') { throw new TypeError('Non-guest peer broker credentials required'); }
|
|
6
|
+
if (!target.pathname) { target.pathname = credentials.pathname; }
|
|
7
|
+
target.username = credentials.username;
|
|
8
|
+
target.password = credentials.password;
|
|
9
|
+
return target.toString();
|
|
10
|
+
}
|
|
11
|
+
/** DSL owns broker endpoints; deployment Secrets supply credentials. */
|
|
12
|
+
export default function controlDeliveryEnvironment(env, { secretPrefix = 'AMQP_URL_' } = {}) {
|
|
13
|
+
if (!env.COLLECTOR_BROKER_ENDPOINTS) { return; }
|
|
14
|
+
const endpoints = JSON.parse(env.COLLECTOR_BROKER_ENDPOINTS);
|
|
15
|
+
for (const [name, endpoint] of Object.entries(endpoints)) {
|
|
16
|
+
if (!name.startsWith(secretPrefix) || !/^[A-Z0-9_]+$/u.test(name.slice(secretPrefix.length)) || !Object.hasOwn(env, name) || !env[name]) { throw new TypeError('Missing control delivery credential Secret'); }
|
|
17
|
+
env[name] = peerUrl(endpoint, env[name]);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** Plant API retains its request-scoped federation; autonomous readers have one owner. */
|
|
2
|
+
export default async function embeddedCollectors(mode, starters) {
|
|
3
|
+
if (mode === 'external') { return; }
|
|
4
|
+
if (mode !== undefined && mode !== 'embedded') { throw new TypeError('Unknown collector mode'); }
|
|
5
|
+
await starters.reduce(async (previous, start) => { await previous; await start(); }, Promise.resolve());
|
|
6
|
+
}
|
|
@@ -6,6 +6,12 @@ export { default as compositeLifecycle } from './compositeLifecycle.js';
|
|
|
6
6
|
export { default as runCollector } from './runCollector.js';
|
|
7
7
|
export { default as taskQueue } from './taskQueue.js';
|
|
8
8
|
export { default as createRegistry } from './createRegistry.js';
|
|
9
|
-
export { default as resolveSecrets } from './resolveSecrets.js';
|
|
9
|
+
export { default as resolveSecrets, withCollectorSecrets } from './resolveSecrets.js';
|
|
10
10
|
export { default as taskStatePg } from '../../infrastructure/persistence/runtime/taskStatePg.js';
|
|
11
11
|
export { default as spooledOutput, amqpDestinations } from './spooledOutput.js';
|
|
12
|
+
export { default as collectorOptions } from './collectorOptions.js';
|
|
13
|
+
export { default as collectorDslManifest } from './collectorDslManifest.js';
|
|
14
|
+
export { default as controlDeliveryEnvironment } from './controlDeliveryEnvironment.js';
|
|
15
|
+
export { default as embeddedCollectors } from './embeddedCollectors.js';
|
|
16
|
+
export { collectorLaunch, launchCollectorCommand } from './collectorLaunch.js';
|
|
17
|
+
export { default as pagedDelivery } from './pagedDelivery.js';
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { intervalSource } from '@yarkivaev/source-to-sink';
|
|
2
|
+
import amqpSink from '../../infrastructure/streams/amqpSink.js';
|
|
3
|
+
import compositeLifecycle from './compositeLifecycle.js';
|
|
4
|
+
import taskState from './taskState.js';
|
|
5
|
+
|
|
6
|
+
function validatePending(state, limits, label) {
|
|
7
|
+
const { pending } = state.snapshot();
|
|
8
|
+
if (pending && (Buffer.byteLength(JSON.stringify(pending)) > limits.bytes || pending.event.records.length > limits.records)) {
|
|
9
|
+
throw new Error(`${label} recovered page capacity exceeded`);
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
function telemetry(output, context, binding) {
|
|
13
|
+
const writes = new Map();
|
|
14
|
+
return {
|
|
15
|
+
write(events) {
|
|
16
|
+
const lifecycle = { interrupted: false };
|
|
17
|
+
const operation = events.flatMap((event) => { return event.records; }).reduce(async (previous, record) => {
|
|
18
|
+
await previous;
|
|
19
|
+
context.signal.throwIfAborted();
|
|
20
|
+
if (lifecycle.interrupted) { throw new Error(`${binding.label} publication interrupted`); }
|
|
21
|
+
await binding.publish(output, record);
|
|
22
|
+
}, Promise.resolve());
|
|
23
|
+
writes.set(operation, lifecycle);
|
|
24
|
+
return operation.finally(() => { writes.delete(operation); });
|
|
25
|
+
},
|
|
26
|
+
interrupt() { writes.forEach((lifecycle) => { lifecycle.interrupted = true; }); },
|
|
27
|
+
releaseWhenSettled(release) {
|
|
28
|
+
if (!writes.size) { release(); return; }
|
|
29
|
+
void Promise.allSettled([...writes.keys()]).then(release);
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
function validatePage(value, count, limits, label) {
|
|
34
|
+
if (count > limits.records || Buffer.byteLength(JSON.stringify(value)) > limits.bytes) { throw new Error(`${label} page capacity exceeded`); }
|
|
35
|
+
}
|
|
36
|
+
async function emit({ state, sinks, context, binding }, records, held) {
|
|
37
|
+
for (const record of records) {
|
|
38
|
+
const eventId = `${context.taskId}:${binding.eventPrefix}:${record.eventId}`;
|
|
39
|
+
// eslint-disable-next-line no-await-in-loop
|
|
40
|
+
await state.deliver({ eventId, records: [record] }, sinks, held);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
async function page(bag) {
|
|
44
|
+
const { reader, state, sinks, context, limits, binding } = bag;
|
|
45
|
+
const { label } = binding;
|
|
46
|
+
validatePending(state, limits, label);
|
|
47
|
+
await state.resume(sinks);
|
|
48
|
+
context.signal.throwIfAborted();
|
|
49
|
+
const cursor = await binding.cursor(reader, state, context.signal);
|
|
50
|
+
const rows = await binding.read(reader, cursor, context.signal);
|
|
51
|
+
context.signal.throwIfAborted();
|
|
52
|
+
validatePage(rows, rows.length, limits, label);
|
|
53
|
+
const { records, next } = binding.fold(rows, cursor);
|
|
54
|
+
validatePage(records, records.length, limits, label);
|
|
55
|
+
if (records.length) { await emit(bag, records, cursor); }
|
|
56
|
+
await state.checkpoint(next);
|
|
57
|
+
}
|
|
58
|
+
async function poll(bag) {
|
|
59
|
+
bag.context.signal.throwIfAborted();
|
|
60
|
+
const release = bag.context.budget.reserve(bag.limits);
|
|
61
|
+
try { await page(bag); bag.context.report?.({ read: true }); }
|
|
62
|
+
catch (error) { bag.sinks.telemetry.interrupt(); throw error; }
|
|
63
|
+
finally { bag.sinks.telemetry.releaseWhenSettled(release); }
|
|
64
|
+
}
|
|
65
|
+
function create(spec, context, services, binding) {
|
|
66
|
+
if (!context.stateStore) { throw new TypeError(`${binding.label} requires an in-process stateStore`); }
|
|
67
|
+
const state = taskState(context.stateStore, { ...spec, taskId: context.taskId, signal: context.signal });
|
|
68
|
+
const limits = { bytes: Math.min(spec.source.maxResponseBytes ?? 1048576, spec.limits?.maxBytes ?? 1048576), records: spec.limits?.maxRecords ?? binding.defaultMaxRecords };
|
|
69
|
+
const reader = services.reader({ ...spec.source, maxResponseBytes: limits.bytes, maxBytes: limits.bytes, signal: context.signal });
|
|
70
|
+
const output = services.sink(spec.sink.url, spec.sink.options ?? binding.sinkDefaults);
|
|
71
|
+
const sinks = { telemetry: telemetry(output, context, binding) };
|
|
72
|
+
const source = services.periodic(spec.pollMs ?? 5000, { accept() { return poll({ reader, state, sinks, context, limits, binding }); } }, { immediate: true, acceptTimeoutMs: 2 * ((spec.writeTimeoutMs ?? 10000) + (spec.source.timeoutMs ?? 10000)) + 1000, onError: context.report });
|
|
73
|
+
return compositeLifecycle({ outputs: [{ start() { return state.open(); }, stop() { return Promise.resolve(); } }, output], inputs: [source] });
|
|
74
|
+
}
|
|
75
|
+
/** Run bounded cursor pages with resumable per-record confirmation and cancellation. */
|
|
76
|
+
export default function pagedDelivery(binding, { reader, sink = amqpSink, periodic = intervalSource } = {}) {
|
|
77
|
+
return {
|
|
78
|
+
validate(spec) {
|
|
79
|
+
if (spec.delivery !== 'durable' || !spec.stateVersion || !spec.compatibilityKey) {
|
|
80
|
+
throw new TypeError(`${binding.label} delivery state configuration required`);
|
|
81
|
+
}
|
|
82
|
+
binding.validate(spec);
|
|
83
|
+
},
|
|
84
|
+
resources() { return []; },
|
|
85
|
+
create(spec, context) { return create(spec, context, { reader, sink, periodic }, binding); }
|
|
86
|
+
};
|
|
87
|
+
}
|
|
@@ -10,3 +10,12 @@ export default function resolveSecrets(value, secrets) {
|
|
|
10
10
|
}
|
|
11
11
|
return Object.fromEntries(Object.entries(value).map(([key, item]) => { return [key, resolveSecrets(item, secrets)]; }));
|
|
12
12
|
}
|
|
13
|
+
|
|
14
|
+
/** Resolve source credentials at creation, leaving delivery references for the queue resolver. */
|
|
15
|
+
export function withCollectorSecrets(adapter) {
|
|
16
|
+
return { ...adapter, create(spec, context) {
|
|
17
|
+
const { sinks, ...source } = spec;
|
|
18
|
+
return adapter.create({ ...resolveSecrets(source, context.secrets),
|
|
19
|
+
...(sinks !== undefined && { sinks: structuredClone(sinks) }) }, context);
|
|
20
|
+
} };
|
|
21
|
+
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import operatorsFromPg from '../infrastructure/persistence/pg/operators.js';
|
|
2
2
|
import userDecisionsFromPg from '../infrastructure/persistence/pg/userDecisions.js';
|
|
3
|
-
import
|
|
3
|
+
import operatorCatalogView from './operatorCatalogView.js';
|
|
4
4
|
import decisionRoute from '../infrastructure/http/plant/routes/decisionRoute.js';
|
|
5
5
|
import edgeOperatorCatalog from './edgeOperatorCatalog.js';
|
|
6
6
|
|
|
@@ -12,15 +12,15 @@ import edgeOperatorCatalog from './edgeOperatorCatalog.js';
|
|
|
12
12
|
* @param {object} [owners] - machineOwners registry for edge decision proxy
|
|
13
13
|
* @returns {object} routes, provider, decisions
|
|
14
14
|
*/
|
|
15
|
-
function centralOperatorRoutes(basePath, sink, owners) {
|
|
15
|
+
function centralOperatorRoutes(basePath, sink, owners, extensions) {
|
|
16
16
|
if (sink.sinkDbProfile !== 'central') {
|
|
17
17
|
return { routes: [], provider: undefined, decisions: undefined };
|
|
18
18
|
}
|
|
19
|
-
const provider = operatorsFromPg(sink.pool);
|
|
19
|
+
const { provider, routes } = operatorCatalogView(basePath, operatorsFromPg(sink.pool), extensions);
|
|
20
20
|
const decisions = userDecisionsFromPg(sink.pool);
|
|
21
21
|
return {
|
|
22
22
|
routes: [
|
|
23
|
-
...
|
|
23
|
+
...routes,
|
|
24
24
|
...decisionRoute(basePath, decisions, owners)
|
|
25
25
|
],
|
|
26
26
|
provider,
|
|
@@ -40,12 +40,13 @@ function centralOperatorRoutes(basePath, sink, owners) {
|
|
|
40
40
|
* @example
|
|
41
41
|
* siteOperatorCatalog('/api/v1', sink, process.env, owners);
|
|
42
42
|
*/
|
|
43
|
-
export default function siteOperatorCatalog(basePath, sink, env, owners) {
|
|
43
|
+
export default function siteOperatorCatalog(basePath, sink, env, owners, { decorate, ...options } = {}) {
|
|
44
|
+
const extensions = { ...options, decorate: decorate && ((provider) => { return decorate(provider, sink); }) };
|
|
44
45
|
if (sink.sinkDbProfile === 'central') {
|
|
45
|
-
return { ...centralOperatorRoutes(basePath, sink, owners), sync: undefined };
|
|
46
|
+
return { ...centralOperatorRoutes(basePath, sink, owners, extensions), sync: undefined };
|
|
46
47
|
}
|
|
47
48
|
if (sink.sinkDbProfile === 'edge') {
|
|
48
|
-
const edge = edgeOperatorCatalog(basePath, env);
|
|
49
|
+
const edge = edgeOperatorCatalog(basePath, env, extensions);
|
|
49
50
|
if (!sink.pool) {
|
|
50
51
|
return { ...edge, decisions: undefined };
|
|
51
52
|
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { intervalSource } from '@yarkivaev/source-to-sink';
|
|
2
|
+
import operationAmqp from '../../infrastructure/sync/operationAmqp.js';
|
|
3
|
+
|
|
4
|
+
/** Persist only the canonical operation fields, then publish the supplied event. */
|
|
5
|
+
export function operationEventSink(operations, publish) {
|
|
6
|
+
if (typeof operations?.upsert !== 'function') { throw new Error('Operations port must have an upsert() method'); }
|
|
7
|
+
if (typeof publish !== 'function') { throw new Error('Publish must be a function'); }
|
|
8
|
+
return {
|
|
9
|
+
async accept(item) {
|
|
10
|
+
const { machine, 'occurred_at': occurredAt, kind, key, payload } = item;
|
|
11
|
+
await operations.upsert({ machine, 'occurred_at': occurredAt, kind, key, payload });
|
|
12
|
+
await publish(item);
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
async function consume(deps, transformer, rows, checkpoint) {
|
|
18
|
+
let mark;
|
|
19
|
+
for (const row of rows) {
|
|
20
|
+
deps.signal?.throwIfAborted();
|
|
21
|
+
// eslint-disable-next-line no-await-in-loop -- The checkpoint advances only after the complete ordered page.
|
|
22
|
+
await transformer.accept(row);
|
|
23
|
+
mark = checkpoint(row);
|
|
24
|
+
}
|
|
25
|
+
return mark;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
async function page(deps, transformer, settings, limits) {
|
|
29
|
+
deps.signal?.throwIfAborted();
|
|
30
|
+
const cursor = await deps.checkpoints.read(deps.source, deps.machine);
|
|
31
|
+
deps.signal?.throwIfAborted();
|
|
32
|
+
const rows = await deps.fetchRows(cursor);
|
|
33
|
+
deps.signal?.throwIfAborted();
|
|
34
|
+
if (rows.length > limits.records || Buffer.byteLength(JSON.stringify(rows)) > limits.bytes) {
|
|
35
|
+
throw new Error(settings.capacityError);
|
|
36
|
+
}
|
|
37
|
+
if (!rows.length) { return; }
|
|
38
|
+
const [timestamp, id] = await consume(deps, transformer, rows, settings.checkpoint);
|
|
39
|
+
deps.signal?.throwIfAborted();
|
|
40
|
+
await deps.checkpoints.write(deps.source, deps.machine, timestamp, id);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async function pass(deps, transformer, settings, bridge) {
|
|
44
|
+
const limits = { bytes: deps.limits?.maxBytes ?? 1048576, records: deps.limits?.maxRecords ?? 1000 };
|
|
45
|
+
const release = deps.budget?.reserve(limits);
|
|
46
|
+
try { await page(deps, transformer, settings, limits); }
|
|
47
|
+
finally { release?.(); }
|
|
48
|
+
if (typeof deps.reconcile === 'function') { await deps.reconcile(bridge); }
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Apply one bounded ordered source page at a time and checkpoint only committed work. */
|
|
52
|
+
export default function checkpointedOperationPoll(deps, settings) {
|
|
53
|
+
const session = operationAmqp(deps.amqpUrl);
|
|
54
|
+
const local = !deps.amqpUrl && typeof deps.publish === 'function';
|
|
55
|
+
const bridge = { publish: local ? deps.publish : session.publish };
|
|
56
|
+
const transformer = settings.transform(operationEventSink(deps.operations, (item) => {
|
|
57
|
+
deps.signal?.throwIfAborted();
|
|
58
|
+
return bridge.publish(item);
|
|
59
|
+
}));
|
|
60
|
+
function runOnce() { return pass(deps, transformer, settings, bridge); }
|
|
61
|
+
function connect() { return session.start().catch((error) => { settings.report('amqp', error); }); }
|
|
62
|
+
async function tick() {
|
|
63
|
+
try {
|
|
64
|
+
if (deps.amqpUrl && !session.active()) { await connect(); }
|
|
65
|
+
await runOnce();
|
|
66
|
+
} catch (error) {
|
|
67
|
+
settings.report('poll', error);
|
|
68
|
+
if (deps.amqpUrl && /channel|connection|socket/iu.test(error.message)) { await session.stop(); }
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
const source = intervalSource(deps.pollSeconds * 1000, { accept: tick });
|
|
72
|
+
return {
|
|
73
|
+
runOnce,
|
|
74
|
+
async start() { await connect(); await source.start(); },
|
|
75
|
+
async stop() { await source.stop(); await session.stop(); }
|
|
76
|
+
};
|
|
77
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
function merged(historic, stored) {
|
|
2
|
+
const byKey = new Map([...historic, ...stored].map((row) => { return [row.key, row]; }));
|
|
3
|
+
return [...byKey.values()].sort((left, right) => { return new Date(left.occurred_at) - new Date(right.occurred_at); });
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
/** Query inclusive intervals split at the first instant owned by the authoritative source. */
|
|
7
|
+
export default function cutoverOperations(historic, authoritative, cutover, { kind, label = kind, caller = 'cutoverOperations' } = {}) {
|
|
8
|
+
if (typeof historic?.list !== 'function') { throw new Error(`ClickHouse ${kind} port with list() is required`); }
|
|
9
|
+
if (typeof authoritative?.listForMachine !== 'function') { throw new Error('Postgres operations port with listForMachine() is required'); }
|
|
10
|
+
if (!(cutover instanceof Date) || Number.isNaN(cutover.getTime())) { throw new Error(`${label} must be a valid Date`); }
|
|
11
|
+
return {
|
|
12
|
+
list(machine, range) {
|
|
13
|
+
if (typeof machine !== 'string' || !machine.length) { throw new Error(`machine must be a non-empty string for ${caller}.list`); }
|
|
14
|
+
if (!(range?.from instanceof Date) || !(range?.to instanceof Date)) {
|
|
15
|
+
throw new Error(`range.from and range.to Date are required for machine ${machine}`);
|
|
16
|
+
}
|
|
17
|
+
const { from, to } = range;
|
|
18
|
+
const before = from < cutover ? historic.list(machine, {
|
|
19
|
+
from, to: to < cutover ? to : new Date(cutover.getTime() - 1)
|
|
20
|
+
}) : [];
|
|
21
|
+
const after = to >= cutover ? authoritative.listForMachine(machine, kind, { from: from > cutover ? from : cutover, to }) : [];
|
|
22
|
+
return Promise.all([before, after]).then(([older, newer]) => { return merged(older, newer); });
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { fileURLToPath } from 'node:url';
|
|
2
|
+
import migrate, { verifyMigrations } from '../../infrastructure/ingest/db/migrate.js';
|
|
3
|
+
|
|
4
|
+
const sharedMigrations = fileURLToPath(new URL('../../../db/migrations', import.meta.url));
|
|
5
|
+
|
|
6
|
+
/** Apply shared schema and optional installation-owned migrations in order. */
|
|
7
|
+
export async function migrateSiteDatabase(pool, profile, { directory, shared = true } = {}) {
|
|
8
|
+
if (shared) { await migrate(pool, sharedMigrations, profile); }
|
|
9
|
+
if (directory) { await migrate(pool, directory, profile); }
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** Choose administrative migration or restricted preflight before starting application routes. */
|
|
13
|
+
export async function prepareSiteDatabase(env, poolFactory, { profile, directory, verify, label }) {
|
|
14
|
+
const mode = env.SUPERVISOR_MIGRATIONS ?? 'apply';
|
|
15
|
+
if (!['apply', 'verify'].includes(mode)) { throw new Error('SUPERVISOR_MIGRATIONS must be apply or verify'); }
|
|
16
|
+
const variable = mode === 'verify' ? 'POSTGRES_URL' : 'POSTGRES_ADMIN_URL';
|
|
17
|
+
if (!env[variable]) { throw new Error(`${variable} is required for ${label} migrations`); }
|
|
18
|
+
const pool = poolFactory(env[variable]);
|
|
19
|
+
try {
|
|
20
|
+
if (mode === 'verify') {
|
|
21
|
+
await verifyMigrations(pool, directory, profile);
|
|
22
|
+
await verify?.(pool);
|
|
23
|
+
} else {
|
|
24
|
+
await migrate(pool, directory, profile);
|
|
25
|
+
}
|
|
26
|
+
} finally { await pool.end(); }
|
|
27
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import foldedMetricsSink from '../foldedMetricsSink.js';
|
|
2
|
+
import { metricsSinkFromPool as pgMetricsSink } from '../../infrastructure/persistence/pg/metrics.js';
|
|
3
|
+
|
|
4
|
+
async function save(connection, devices, records, context, begin) {
|
|
5
|
+
context.signal?.throwIfAborted();
|
|
6
|
+
await connection.query(begin);
|
|
7
|
+
await foldedMetricsSink(pgMetricsSink(connection), connection, devices).write(records, context);
|
|
8
|
+
context.signal?.throwIfAborted();
|
|
9
|
+
await connection.query('COMMIT');
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
async function write(pool, devices, records, { context, begin, timeoutMs }) {
|
|
13
|
+
context.signal?.throwIfAborted();
|
|
14
|
+
const client = await pool.connect();
|
|
15
|
+
const connection = { query(text, values) { return client.query({ text, values, 'query_timeout': timeoutMs }); } };
|
|
16
|
+
let fault;
|
|
17
|
+
try {
|
|
18
|
+
await save(connection, devices, records, context, begin);
|
|
19
|
+
} catch (error) {
|
|
20
|
+
fault = error;
|
|
21
|
+
try { await connection.query('ROLLBACK'); }
|
|
22
|
+
catch (rollback) { throw new AggregateError([error, rollback], 'Edge metrics transaction rollback failed'); }
|
|
23
|
+
throw error;
|
|
24
|
+
} finally { client.release(fault); }
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Commit raw telemetry and derived intervals atomically, serializing writers across replicas. */
|
|
28
|
+
export default function edgeMetricsStore(pool, devices, { lockKey = 'scada:edge-metrics', timeoutMs = 4000 } = {}) {
|
|
29
|
+
if (typeof lockKey !== 'string' || !/^[\w.:-]+$/u.test(lockKey) || !Number.isSafeInteger(timeoutMs) || timeoutMs < 1) {
|
|
30
|
+
throw new TypeError('Invalid metrics transaction lock or deadline');
|
|
31
|
+
}
|
|
32
|
+
const deadline = `'${timeoutMs}ms'`;
|
|
33
|
+
const begin = `BEGIN; SET LOCAL statement_timeout=${deadline}; SET LOCAL lock_timeout=${deadline}; SET LOCAL idle_in_transaction_session_timeout=${deadline}; SELECT pg_advisory_xact_lock(hashtextextended('${lockKey}',0))`;
|
|
34
|
+
return { write(records, context = {}) { return write(pool, devices, records, { context, begin, timeoutMs }); } };
|
|
35
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { historyProtocol } from '../../infrastructure/persistence/pg/history.js';
|
|
2
|
+
import { historyReplicaProtocol } from '../../infrastructure/persistence/pg/historyReplicaOutbox.js';
|
|
3
|
+
|
|
4
|
+
/** Collect history capabilities before reading runtime settings or opening connections. */
|
|
5
|
+
export function historyCapabilities(role, requiredProtocol = historyProtocol) {
|
|
6
|
+
const historyProtocols = historyProtocol === requiredProtocol ? [requiredProtocol] : [];
|
|
7
|
+
if (role === 'site' && historyReplicaProtocol) { historyProtocols.push(historyReplicaProtocol); }
|
|
8
|
+
return { role, historyProtocols };
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function capabilityExit(role, requiredProtocol) {
|
|
12
|
+
if (process.argv.includes('--capabilities')) {
|
|
13
|
+
process.stdout.write(`${JSON.stringify(historyCapabilities(role, requiredProtocol))}\n`);
|
|
14
|
+
process.exit(0);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Validate local history settings and mutually exclusive raw receivers. */
|
|
19
|
+
export function historySettings(env, requiredProtocol = historyProtocol, { defaultDays = 30, maxDays = 365 } = {}) {
|
|
20
|
+
if (env.LOCAL_HISTORY_ENABLED === undefined || env.LOCAL_HISTORY_ENABLED === 'false') { return null; }
|
|
21
|
+
if (env.LOCAL_HISTORY_ENABLED !== 'true') { throw new Error('LOCAL_HISTORY_ENABLED must be true or false'); }
|
|
22
|
+
if (historyProtocol !== requiredProtocol) { throw new Error('Matching Core history protocol required'); }
|
|
23
|
+
const retentionDays = Number(env.HISTORY_RETENTION_DAYS ?? defaultDays);
|
|
24
|
+
if (!Number.isSafeInteger(retentionDays) || retentionDays < 1 || retentionDays > maxDays) {
|
|
25
|
+
throw new Error('Invalid local history retention');
|
|
26
|
+
}
|
|
27
|
+
if (env.HISTORY_AMQP_ENABLED === 'true') { throw new Error('ClickHouse history cannot run a second raw PostgreSQL receiver'); }
|
|
28
|
+
return { retentionDays };
|
|
29
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export { centralTelemetryIngest, orderedMetricsIngest, processTelemetryIngest } from './telemetry.js';
|
|
2
|
+
export { default as edgeMetricsStore } from './edgeMetricsStore.js';
|
|
3
|
+
export { capabilityExit, historyCapabilities, historySettings } from './history.js';
|
|
4
|
+
export { default as measurementTopic } from './measurementTopic.js';
|
|
5
|
+
export { default as operationFederation } from './operationFederation.js';
|
|
6
|
+
export { default as migrate, verifyMigrations } from '../../infrastructure/ingest/db/migrate.js';
|
|
7
|
+
export { centralOperatorsUpdate, edgeOperatorsUpdate } from './operatorUpdates.js';
|
|
8
|
+
export { migrateSiteDatabase, prepareSiteDatabase } from './databaseMigrations.js';
|
|
9
|
+
export { default as cutoverOperations } from './cutoverOperations.js';
|
|
10
|
+
export { default as telemetryBackfillCommand } from './telemetryBackfillCommand.js';
|
|
11
|
+
export { default as clickhouseMetricBursts, metricBurstSql } from '../../infrastructure/persistence/clickhouse/metricBursts.js';
|
|
12
|
+
export { default as checkpointedOperationPoll, operationEventSink } from './checkpointedOperationPoll.js';
|
|
13
|
+
export { default as operatorField } from './operatorField.js';
|
|
14
|
+
export { default as reconcileOperationSnapshot } from './operationSnapshot.js';
|
|
15
|
+
export { default as operatorFieldStore, verifyPostgresRelation } from '../../infrastructure/persistence/pg/operatorFieldStore.js';
|
|
16
|
+
export { operatorFieldRoute } from '../../infrastructure/http/plant/routes/operatorRoute.js';
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import paths from '../deploy/paths.js';
|
|
2
|
+
|
|
3
|
+
/** Find the unique namespace path for a measurement of the requested machine. */
|
|
4
|
+
export default function measurementTopic(machine, key, document, listed) {
|
|
5
|
+
const available = Array.isArray(listed) ? listed : paths(document);
|
|
6
|
+
const matches = available.filter((item) => { return item.endsWith(`/${key}`) && item.split('/').includes(machine); });
|
|
7
|
+
if (matches.length !== 1) { throw new Error(`measurement topic unknown key ${key} on ${machine}`); }
|
|
8
|
+
return matches[0];
|
|
9
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import operationAmqp from '../../infrastructure/sync/operationAmqp.js';
|
|
2
|
+
import publishingOperations from '../sync/publishingOperations.js';
|
|
3
|
+
|
|
4
|
+
/** Start and stop confirmed publication of local operation writes. */
|
|
5
|
+
export default function operationFederation(url, { wrap = (operations) => { return operations; }, report } = {}) {
|
|
6
|
+
const session = operationAmqp(url);
|
|
7
|
+
return {
|
|
8
|
+
publish: session.publish,
|
|
9
|
+
wrap(operations) { return wrap(publishingOperations(operations, session.publish)); },
|
|
10
|
+
start() {
|
|
11
|
+
return report ? session.start().catch(report) : session.start();
|
|
12
|
+
},
|
|
13
|
+
stop() { return session.stop(); }
|
|
14
|
+
};
|
|
15
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import publishingOperations from '../sync/publishingOperations.js';
|
|
2
|
+
|
|
3
|
+
/** Apply an authoritative snapshot in order, then remove records absent from it. */
|
|
4
|
+
export default async function reconcileOperationSnapshot({ operations, publish, machine, kind, range }, { rows, key, accept }) {
|
|
5
|
+
for (const row of rows) {
|
|
6
|
+
// eslint-disable-next-line no-await-in-loop -- Preserve source and publication order.
|
|
7
|
+
await accept(row);
|
|
8
|
+
}
|
|
9
|
+
const keys = new Set(rows.map(key).filter((id) => { return typeof id === 'string' && id.length > 0; }));
|
|
10
|
+
const stored = await operations.listForMachine(machine, kind, range);
|
|
11
|
+
const port = publishingOperations(operations, publish);
|
|
12
|
+
for (const row of stored) {
|
|
13
|
+
if (!keys.has(row.key)) {
|
|
14
|
+
// eslint-disable-next-line no-await-in-loop -- Publish each confirmed deletion in store order.
|
|
15
|
+
await port.remove(machine, row.key);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
function notFound(id) {
|
|
2
|
+
const error = new Error(`operator '${id}' not found`);
|
|
3
|
+
error.routeCode = 'NOT_FOUND';
|
|
4
|
+
error.routeStatus = 404;
|
|
5
|
+
return error;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
async function enrich(rows, store, field) {
|
|
9
|
+
if (!store) {
|
|
10
|
+
return rows.map((row) => { return { ...row, [field]: row[field] ?? '' }; });
|
|
11
|
+
}
|
|
12
|
+
const values = await store.getMap(rows.map(({ id }) => { return id; }));
|
|
13
|
+
return rows.map((row) => {
|
|
14
|
+
const value = values.get(Number(row.id));
|
|
15
|
+
return { ...row, [field]: value === undefined ? '' : value };
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
async function assign(base, store, field, id, value) {
|
|
20
|
+
const found = (await base.list()).find((row) => { return Number(row.id) === Number(id); });
|
|
21
|
+
if (!found) { throw notFound(id); }
|
|
22
|
+
if (value === '') { await store.remove(found.id); }
|
|
23
|
+
else { await store.put(found.id, value); }
|
|
24
|
+
return { ...found, [field]: value };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Enrich operator identities with a separately persisted or remotely owned field. */
|
|
28
|
+
export default function operatorField(base, { field, onCreate, onUpdate, store }) {
|
|
29
|
+
return Object.freeze({
|
|
30
|
+
async list() { return enrich(await base.list(), store, field); },
|
|
31
|
+
async create(fields) {
|
|
32
|
+
const value = onCreate(fields[field]);
|
|
33
|
+
const created = await base.create(fields);
|
|
34
|
+
if (store) { await store.put(created.id, value); }
|
|
35
|
+
return { ...created, [field]: store || created[field] === undefined ? value : created[field] };
|
|
36
|
+
},
|
|
37
|
+
async update(id, fields) {
|
|
38
|
+
const value = onUpdate(fields[field]);
|
|
39
|
+
if (typeof base.update === 'function') {
|
|
40
|
+
const updated = await base.update(id, { [field]: value });
|
|
41
|
+
return { ...updated, [field]: updated[field] === undefined ? value : updated[field] };
|
|
42
|
+
}
|
|
43
|
+
if (!store) { throw notFound(id); }
|
|
44
|
+
return assign(base, store, field, id, value);
|
|
45
|
+
},
|
|
46
|
+
enabled() { return base.enabled(); },
|
|
47
|
+
permit(flag) { return base.permit(flag); }
|
|
48
|
+
});
|
|
49
|
+
}
|