@yarkivaev/scada 2.17.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 +14 -2
- package/package.json +5 -2
- package/src/application/cycleTimelineFetch.js +56 -0
- package/src/application/deploy/collectorSourcePlan.js +97 -0
- package/src/application/deploy/compileCollectorTasks.js +31 -0
- package/src/application/deploy/compileControlCatalog.js +66 -0
- package/src/application/deploy/controlPlan.js +16 -0
- package/src/application/deploy/controlPlaneConfiguration.js +62 -0
- package/src/application/deploy/controlReaderSpecs.js +37 -0
- package/src/application/deploy/edgeDescriptors.js +31 -0
- package/src/application/deploy/fieldbusSourcePlan.js +79 -0
- package/src/application/deploy/liveReleaseOverlay.js +17 -0
- package/src/application/deploy/plantBindingProfile.js +24 -0
- package/src/application/deploy/projectControlPlane.js +48 -0
- package/src/application/deploy/projectTopology.js +41 -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/brokerReplicaTopology.js +34 -12
- package/src/infrastructure/deploy/brokerSecurity.js +89 -0
- package/src/infrastructure/deploy/brokerSecurityInput.js +85 -0
- package/src/infrastructure/deploy/brokerTopology.js +125 -0
- package/src/infrastructure/deploy/centralTelemetry.js +51 -0
- package/src/infrastructure/deploy/clickhouseTelemetryPolicy.js +64 -0
- package/src/infrastructure/deploy/collectorChartPlan.js +68 -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/configuredHistorySeed.js +54 -0
- package/src/infrastructure/deploy/configuredPostgresMaintenance.js +23 -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/databaseSecurity.js +39 -0
- package/src/infrastructure/deploy/deploymentRecovery.js +49 -0
- package/src/infrastructure/deploy/deploymentTemplate.js +67 -0
- package/src/infrastructure/deploy/executeConfiguredChartDeployment.js +65 -0
- package/src/infrastructure/deploy/executeManagedDeployment.js +46 -0
- package/src/infrastructure/deploy/highAvailability/brokerOwnership.js +19 -0
- package/src/infrastructure/deploy/highAvailability/catalogReconciler.js +61 -0
- package/src/infrastructure/deploy/highAvailability/classifyFederation.js +57 -0
- package/src/infrastructure/deploy/highAvailability/classifyGate.js +114 -0
- package/src/infrastructure/deploy/highAvailability/classifyLoop.js +139 -0
- package/src/infrastructure/deploy/highAvailability/classifyShovels.js +70 -0
- package/src/infrastructure/deploy/highAvailability/classifyWatermark.js +45 -0
- package/src/infrastructure/deploy/highAvailability/compileClassifierRules.js +21 -0
- package/src/infrastructure/deploy/highAvailability/configuredBrokerReconciliation.js +21 -0
- package/src/infrastructure/deploy/highAvailability/controllerReconcile.js +14 -0
- package/src/infrastructure/deploy/highAvailability/historyReceiver.js +49 -0
- package/src/infrastructure/deploy/highAvailability/historyWatermark.js +42 -0
- package/src/infrastructure/deploy/highAvailability/index.js +15 -0
- package/src/infrastructure/deploy/highAvailability/reconcileBrokerThroughController.js +18 -0
- package/src/infrastructure/deploy/highAvailability/reconciliationBundle.js +28 -0
- package/src/infrastructure/deploy/highAvailability/segmentAdmit.js +24 -0
- package/src/infrastructure/deploy/highAvailability/segmentPublish.js +27 -0
- package/src/infrastructure/deploy/highAvailability/supervisorReplica.js +36 -0
- package/src/infrastructure/deploy/index.js +46 -2
- package/src/infrastructure/deploy/mixedStoreHistory.js +27 -0
- package/src/infrastructure/deploy/projectClassification.js +42 -0
- package/src/infrastructure/deploy/publicBrokerPlan.js +15 -0
- package/src/infrastructure/deploy/securityPolicy.js +16 -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/ingest/telemetry/centralPolicy.js +29 -8
- package/src/infrastructure/management/kiosk/kioskDeployment.js +60 -0
- package/src/infrastructure/mdmesh/adminReconciliation.js +19 -0
- package/src/infrastructure/mdmesh/bootstrapMdmeshCredentials.js +47 -0
- package/src/infrastructure/mdmesh/controllerOperation.js +17 -0
- package/src/infrastructure/mdmesh/index.js +5 -0
- package/src/infrastructure/mdmesh/mdmeshServerRelease.js +58 -0
- package/src/infrastructure/mdmesh/publishApk.js +30 -0
- package/src/infrastructure/messaging/rabbitmq/definitions.js +12 -6
- package/src/infrastructure/opcua/projectSources.js +36 -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,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
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import operator from '../../domain/operator/operator.js';
|
|
2
|
+
import centralOperators from '../../infrastructure/operators/centralOperators.js';
|
|
3
|
+
import edgeOperators from '../../infrastructure/operators/edgeOperators.js';
|
|
4
|
+
import operatorExtras, { operatorIdentityKeys } from '../../infrastructure/operators/operatorExtras.js';
|
|
5
|
+
|
|
6
|
+
/** Add PATCH support for catalog-owned operator fields. */
|
|
7
|
+
export function centralOperatorsUpdate(client, basePath) {
|
|
8
|
+
return Object.freeze({
|
|
9
|
+
...centralOperators(client, basePath),
|
|
10
|
+
async update(id, fields) {
|
|
11
|
+
const row = await client.patchJson(`${basePath}/operators/${id}`, fields);
|
|
12
|
+
if (row.id === undefined || row.id === null) { throw new Error('central operators item missing id'); }
|
|
13
|
+
return {
|
|
14
|
+
...operator(row.id, row.cardUid, row.firstName, row.lastName, row.displayName),
|
|
15
|
+
...operatorExtras(row, operatorIdentityKeys())
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Forward operator changes to central and refresh the local materialized catalog. */
|
|
22
|
+
export function edgeOperatorsUpdate(cache, source) {
|
|
23
|
+
return Object.freeze({
|
|
24
|
+
...edgeOperators(cache, source),
|
|
25
|
+
async update(id, fields) {
|
|
26
|
+
if (typeof source?.update !== 'function') {
|
|
27
|
+
const error = new Error('CENTRAL_PLANT_URL is required for edge operator update');
|
|
28
|
+
error.routeCode = 'SERVICE_UNAVAILABLE';
|
|
29
|
+
error.routeStatus = 503;
|
|
30
|
+
throw error;
|
|
31
|
+
}
|
|
32
|
+
const updated = await source.update(id, fields);
|
|
33
|
+
cache.replace(await source.pull());
|
|
34
|
+
return updated;
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { createClient } from '@clickhouse/client';
|
|
2
|
+
import telemetryIngest from '../../infrastructure/ingest/telemetry/telemetryIngest.js';
|
|
3
|
+
import amqpMetricsIngest from '../../infrastructure/ingest/telemetry/amqpMetricsIngest.js';
|
|
4
|
+
import clickhouseJsonMetrics from '../../infrastructure/persistence/clickhouse/jsonMetrics.js';
|
|
5
|
+
|
|
6
|
+
/** Restart an ingest process after an uncertain storage write and report delivery failures. */
|
|
7
|
+
export function processTelemetryIngest(url, queue, metrics, {
|
|
8
|
+
halt = () => { process.exit(1); },
|
|
9
|
+
report = (error) => { process.stderr.write(`Telemetry delivery failed: ${error.message}\n`); },
|
|
10
|
+
...options
|
|
11
|
+
} = {}) {
|
|
12
|
+
return telemetryIngest(url, queue, metrics, { ...options, halt, report });
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Start a dedicated RabbitMQ to ClickHouse ingest using the supplied queue and admission policy. */
|
|
16
|
+
export function centralTelemetryIngest(env, { defaultQueue, admission }, { metrics, ingest = processTelemetryIngest } = {}) {
|
|
17
|
+
if (!env.CLICKHOUSE_URL) { throw new Error('CLICKHOUSE_URL is required'); }
|
|
18
|
+
if (!env.AMQP_URL) { throw new Error('AMQP_URL is required'); }
|
|
19
|
+
const sink = metrics ? metrics(env.CLICKHOUSE_URL) : clickhouseJsonMetrics(
|
|
20
|
+
createClient({ url: env.CLICKHOUSE_URL, 'request_timeout': 60000 }), admission
|
|
21
|
+
);
|
|
22
|
+
const writer = ingest(env.AMQP_URL, env.AMQP_QUEUE || defaultQueue, sink, {
|
|
23
|
+
size: 256, prefetch: 512, maxWaitMs: 1000, writeTimeoutMs: 45000
|
|
24
|
+
});
|
|
25
|
+
return Promise.resolve(writer.start()).then(() => { return writer; });
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Accept deliveries in order with one message in flight to prevent retry overtaking. */
|
|
29
|
+
export function orderedMetricsIngest(url, queue, sink) {
|
|
30
|
+
return amqpMetricsIngest(url, queue, sink, { prefetch: 1, size: 1, maxWaitMs: 250, exclusive: true, writeTimeoutMs: 45000 });
|
|
31
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import pg from 'pg';
|
|
2
|
+
import { createClient } from '@clickhouse/client';
|
|
3
|
+
import telemetryBackfill from '../telemetry/telemetryBackfill.js';
|
|
4
|
+
import postgresTelemetrySource from '../../infrastructure/persistence/pg/telemetrySource.js';
|
|
5
|
+
import clickhouseTelemetryTarget, { assertClickhouseBackfillMode } from '../../infrastructure/persistence/clickhouse/telemetryTarget.js';
|
|
6
|
+
|
|
7
|
+
const readonly = '-c default_transaction_read_only=on -c statement_timeout=120000 -c timezone=UTC';
|
|
8
|
+
|
|
9
|
+
function required(env, name) {
|
|
10
|
+
if (!env[name]) { throw new Error(`${name} is required`); }
|
|
11
|
+
return env[name];
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function publicError(env, error) {
|
|
15
|
+
let { message } = error;
|
|
16
|
+
for (const name of ['SOURCE_POSTGRES_URL', 'CLICKHOUSE_URL', 'CLICKHOUSE_PASSWORD']) {
|
|
17
|
+
if (env[name]) { message = message.split(env[name]).join('[redacted]'); }
|
|
18
|
+
}
|
|
19
|
+
return { error: message, ...(error.report ? { report: error.report } : {}) };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function options(env, value, usage) {
|
|
23
|
+
const source = new URL(required(env, 'SOURCE_POSTGRES_URL'));
|
|
24
|
+
source.searchParams.set('options', readonly);
|
|
25
|
+
const url = required(env, 'CLICKHOUSE_URL');
|
|
26
|
+
const mode = (value || 'copy').toLowerCase();
|
|
27
|
+
if (!['copy', 'verify', 'repair'].includes(mode)) { throw new Error(`Usage: ${usage} copy|verify|repair`); }
|
|
28
|
+
return {
|
|
29
|
+
postgres: { connectionString: source.toString(), max: 1, options: readonly, 'query_timeout': 125000, connectionTimeoutMillis: 15000 },
|
|
30
|
+
clickhouse: { url, username: env.CLICKHOUSE_USER || 'default', password: env.CLICKHOUSE_PASSWORD || '',
|
|
31
|
+
'request_timeout': 125000, 'clickhouse_settings': { 'insert_deduplicate': 0 } },
|
|
32
|
+
mode, from: env.SOURCE_FROM || '1970-01-01T00:00:00Z', pageSize: Number(env.SOURCE_PAGE_SIZE || 20000)
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
async function runBackfill(source, client, config, admission) {
|
|
37
|
+
const target = clickhouseTelemetryTarget(client, admission);
|
|
38
|
+
const report = await telemetryBackfill({ source, target }, {
|
|
39
|
+
mode: config.mode, pageSize: config.pageSize,
|
|
40
|
+
onProgress(progress) { process.stderr.write(`${JSON.stringify({ progress })}\n`); }
|
|
41
|
+
});
|
|
42
|
+
process.stdout.write(`${JSON.stringify(report)}\n`);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Run the resumable PostgreSQL to ClickHouse backfill with read-only source credentials. */
|
|
46
|
+
export default async function telemetryBackfillCommand(env, argument, { admission, usage = 'telemetry-backfill' } = {}) {
|
|
47
|
+
let pool;
|
|
48
|
+
let client;
|
|
49
|
+
let source;
|
|
50
|
+
try {
|
|
51
|
+
const config = options(env, argument, usage);
|
|
52
|
+
pool = new pg.Pool(config.postgres);
|
|
53
|
+
client = createClient(config.clickhouse);
|
|
54
|
+
await assertClickhouseBackfillMode(client, config.mode);
|
|
55
|
+
source = postgresTelemetrySource(pool, { from: config.from });
|
|
56
|
+
await runBackfill(source, client, config, admission);
|
|
57
|
+
} catch (error) {
|
|
58
|
+
process.stderr.write(`${JSON.stringify(publicError(env, error))}\n`);
|
|
59
|
+
process.exitCode = 1;
|
|
60
|
+
} finally {
|
|
61
|
+
try { await source?.close(); }
|
|
62
|
+
finally { await Promise.allSettled([pool?.end(), client?.close()]); }
|
|
63
|
+
}
|
|
64
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/** Convert persistence timestamps into timeline inputs, projecting an open end at the supplied clock. */
|
|
2
|
+
export function timelineSegments(rows, now) {
|
|
3
|
+
return rows.map((row) => {
|
|
4
|
+
return { name: row.name, start: row.start_time.toISOString(),
|
|
5
|
+
end: (row.duration === 0 ? now : row.end_time).toISOString(),
|
|
6
|
+
duration: row.duration, tags: row.tags, options: row.options, properties: row.properties };
|
|
7
|
+
});
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/** Bounds spanning a set of half-open measurement windows. */
|
|
11
|
+
export function measurementBounds(items, windowFor) {
|
|
12
|
+
if (!items.length) { return null; }
|
|
13
|
+
let start = Number.POSITIVE_INFINITY;
|
|
14
|
+
let end = Number.NEGATIVE_INFINITY;
|
|
15
|
+
for (const item of items) {
|
|
16
|
+
const { start: lower, end: upper } = windowFor(item);
|
|
17
|
+
if (lower < start) { start = lower; }
|
|
18
|
+
if (upper > end) { end = upper; }
|
|
19
|
+
}
|
|
20
|
+
return { start: new Date(start), end: new Date(end) };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Add optional scaled peaks from half-open measurement windows. */
|
|
24
|
+
export function measurementPeaks(items, samples, { field, scale = 1, windowFor }) {
|
|
25
|
+
return items.map((item) => {
|
|
26
|
+
const { start, end } = windowFor(item);
|
|
27
|
+
let peak = Number.NEGATIVE_INFINITY;
|
|
28
|
+
for (const sample of samples) {
|
|
29
|
+
const stamp = new Date(sample.timestamp).getTime();
|
|
30
|
+
if (Number.isFinite(sample.value) && stamp >= start && stamp < end) {
|
|
31
|
+
peak = Math.max(peak, sample.value);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
return { ...item, ...(peak !== Number.NEGATIVE_INFINITY && { [field]: peak * scale }) };
|
|
35
|
+
});
|
|
36
|
+
}
|