@yarkivaev/scada 2.5.7 → 2.6.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/README.md +136 -2
- package/charts/scada/templates/_helpers.tpl +18 -3
- package/charts/scada/templates/postgres.yaml +6 -0
- package/charts/scada/templates/rabbitmq-config.yaml +5 -1
- package/charts/scada/templates/rabbitmq.yaml +12 -1
- package/charts/scada/templates/supervisor-sink.yaml +5 -0
- package/charts/scada/values.schema.json +46 -1
- package/charts/scada/values.yaml +7 -0
- package/db/migrations/E0005__historical_telemetry_grants.sql +5 -0
- package/db/migrations/E0006__historical_telemetry.sql +64 -0
- package/db/migrations/E0007__metric_receipts.sql +7 -0
- package/db/migrations/E0008__metric_receipts_grants.sql +1 -0
- package/db/migrations/E0009__history_continuation.sql +20 -0
- package/db/migrations/E0010__history_admissions.sql +8 -0
- package/db/migrations/E0011__history_classifier_checkpoints.sql +18 -0
- package/db/migrations/E0012__external_history_grants.sql +4 -0
- package/db/migrations/E0013__history_staged_corrections.sql +104 -0
- package/db/migrations/E0014__history_correction_grants.sql +5 -0
- package/db/migrations/E0015__history_retention_frontier.sql +7 -0
- package/db/migrations/E0016__history_retention_grants.sql +1 -0
- package/index.js +7 -0
- package/package.json +5 -3
- package/src/application/control/agent.js +61 -0
- package/src/application/control/catalog.js +22 -0
- package/src/application/control/controlClient.js +75 -0
- package/src/application/control/controlStore.js +55 -0
- package/src/application/control/controller.js +22 -0
- package/src/application/control/executionSnapshot.js +32 -0
- package/src/application/control/index.js +7 -0
- package/src/application/control/localAssignment.js +13 -0
- package/src/application/control/schedule.js +103 -0
- package/src/application/control/snapshotFile.js +24 -0
- package/src/application/foldedMetricsSink.js +1 -0
- package/src/application/mcp/mcpResources.js +1 -1
- package/src/application/mcp/mcpSchema.js +8 -3
- package/src/application/runtime/additionalAdapters.js +13 -9
- package/src/application/runtime/deliveryQueue.js +62 -0
- package/src/application/runtime/deliverySessions.js +28 -0
- package/src/application/runtime/modbusDelivery.js +36 -0
- package/src/application/runtime/pipelineAdapters.js +12 -8
- package/src/application/runtime/queuedDelivery.js +25 -0
- package/src/application/runtime/runCollector.js +34 -3
- package/src/application/runtime/runtime.js +2 -2
- package/src/application/runtime/runtimeHealth.js +1 -1
- package/src/application/runtime/runtimeServices.js +6 -2
- package/src/application/runtime/streamTask.js +13 -4
- package/src/application/runtime/taskContext.js +1 -0
- package/src/application/runtime/taskSlot.js +2 -2
- package/src/application/runtime/telemetrySink.js +18 -0
- package/src/application/siteServer.js +19 -4
- package/src/application/siteTelemetry.js +2 -2
- package/src/application/supervisorSink.js +32 -12
- package/src/application/sync/siteSyncBind.js +2 -2
- package/src/bin/controller.js +8 -0
- package/src/infrastructure/http/edge/edgeApi.js +2 -0
- package/src/infrastructure/http/edge/routes/history/historyRoutes.js +33 -0
- package/src/infrastructure/http/plant/routes/measurementRead.js +3 -0
- package/src/infrastructure/ingest/db/migrate.js +16 -0
- package/src/infrastructure/ingest/db/migrationProfile.js +6 -1
- package/src/infrastructure/ingest/db/retainMetricReceipts.js +8 -0
- package/src/infrastructure/ingest/db/runRetention.js +2 -0
- package/src/infrastructure/ingest/mqtt/metricsTransformer.js +11 -2
- package/src/infrastructure/ingest/mqtt/modbusMqtt.js +1 -1
- package/src/infrastructure/ingest/mqtt/modbusPublish.js +2 -0
- package/src/infrastructure/ingest/mqtt/mqttMetrics.js +1 -1
- package/src/infrastructure/ingest/telemetry/amqpMetricsIngest.js +7 -3
- package/src/infrastructure/ingest/telemetry/centralEnvelope.js +46 -0
- package/src/infrastructure/ingest/telemetry/centralMetricsSink.js +64 -0
- package/src/infrastructure/ingest/telemetry/centralPoint.js +14 -0
- package/src/infrastructure/ingest/telemetry/centralPolicy.js +51 -0
- package/src/infrastructure/ingest/telemetry/centralQueueSession.js +29 -0
- package/src/infrastructure/ingest/telemetry/centralTelemetryPreflight.js +31 -0
- package/src/infrastructure/ingest/telemetry/foldingSink.js +3 -0
- package/src/infrastructure/ingest/telemetry/historyTelemetry.js +32 -0
- package/src/infrastructure/persistence/clickhouse/canonicalMetrics.js +26 -0
- package/src/infrastructure/persistence/clickhouse/changes.js +4 -2
- package/src/infrastructure/persistence/clickhouse/connection.js +6 -8
- package/src/infrastructure/persistence/clickhouse/holds.js +10 -7
- package/src/infrastructure/persistence/clickhouse/latest.js +1 -1
- package/src/infrastructure/persistence/clickhouse/metricsQuery.js +70 -0
- package/src/infrastructure/persistence/clickhouse/metricsRelation.js +110 -0
- package/src/infrastructure/persistence/clickhouse/nativeMetricPoints.js +26 -0
- package/src/infrastructure/persistence/clickhouse/nativeMetricsAdmission.js +91 -0
- package/src/infrastructure/persistence/clickhouse/nativeMetricsClock.js +9 -0
- package/src/infrastructure/persistence/clickhouse/nativeMetricsCompaction.js +82 -0
- package/src/infrastructure/persistence/clickhouse/nativeMetricsInsert.js +31 -0
- package/src/infrastructure/persistence/clickhouse/nativeMetricsOwnership.js +8 -0
- package/src/infrastructure/persistence/clickhouse/nativeMetricsSchema.js +44 -0
- package/src/infrastructure/persistence/clickhouse/pollTopicCursors.js +3 -1
- package/src/infrastructure/persistence/clickhouse/rises.js +4 -2
- package/src/infrastructure/persistence/clickhouse/samples.js +10 -0
- package/src/infrastructure/persistence/clickhouse/sensor.js +4 -0
- package/src/infrastructure/persistence/clickhouse/series.js +38 -21
- package/src/infrastructure/persistence/pg/history.js +169 -0
- package/src/infrastructure/persistence/pg/historyAdmission.js +81 -0
- package/src/infrastructure/persistence/pg/historyCheckpoint.js +56 -0
- package/src/infrastructure/persistence/pg/historyConfigure.js +28 -0
- package/src/infrastructure/persistence/pg/historyContext.js +65 -0
- package/src/infrastructure/persistence/pg/historyCorrection.js +34 -0
- package/src/infrastructure/persistence/pg/historyObservations.js +56 -0
- package/src/infrastructure/persistence/pg/historySeed.js +27 -0
- package/src/infrastructure/persistence/pg/metrics.js +5 -4
- package/src/infrastructure/persistence/pg/metricsInsertSql.js +12 -0
- package/src/infrastructure/persistence/runtime/deliverySpool.js +124 -0
- package/src/infrastructure/persistence/stateDataFromPool.js +2 -0
- package/src/infrastructure/streams/amqpSink/session.js +6 -0
- package/src/infrastructure/streams/amqpSource.js +17 -4
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import deliverySpool from '../../infrastructure/persistence/runtime/deliverySpool.js';
|
|
2
|
+
import deliverySessions from './deliverySessions.js';
|
|
3
|
+
|
|
4
|
+
function confirmed(event) {
|
|
5
|
+
return { ...event, options: { ...event.options, persistent: true, mandatory: true, messageId: event.eventId } };
|
|
6
|
+
}
|
|
7
|
+
/* eslint max-lines-per-function: ["error", 60] */
|
|
8
|
+
/** Node-owned queue: removing a source does not remove its destination descriptors or receipts. */
|
|
9
|
+
export default function deliveryQueue(directory, options) {
|
|
10
|
+
const spool = deliverySpool(directory, options);
|
|
11
|
+
const sessions = deliverySessions(options.factory, options.writeTimeoutMs);
|
|
12
|
+
let chain = Promise.resolve();
|
|
13
|
+
const state = { pending: 0, draining: false, closed: false };
|
|
14
|
+
function serialized(action) {
|
|
15
|
+
if (state.pending >= (options.maxOperations ?? 32)) { return Promise.reject(new Error('Delivery operation capacity exceeded')); }
|
|
16
|
+
state.pending += 1;
|
|
17
|
+
const result = chain.then(action).finally(() => { state.pending -= 1; });
|
|
18
|
+
chain = result.catch(() => {
|
|
19
|
+
// Individual callers receive rejection; preserve serialization.
|
|
20
|
+
});
|
|
21
|
+
return result;
|
|
22
|
+
}
|
|
23
|
+
async function send(record, id) {
|
|
24
|
+
if (state.closed) { throw new Error('Delivery queue closed'); }
|
|
25
|
+
const descriptor = record.event.destinations.find((item) => { return item.id === id; });
|
|
26
|
+
await sessions.write(descriptor, confirmed(record.event.observation));
|
|
27
|
+
await serialized(() => { return spool.ack(record.event.eventId, id); });
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
return {
|
|
31
|
+
open() { return serialized(() => { return spool.open(); }); },
|
|
32
|
+
accept(event, destinations) {
|
|
33
|
+
if (state.closed) { return Promise.reject(new Error('Delivery queue closed')); }
|
|
34
|
+
if (!destinations?.length || destinations.some((item) => { return item.type !== 'amqp'; })) {
|
|
35
|
+
return Promise.reject(new TypeError('Queued delivery requires confirmed AMQP destinations'));
|
|
36
|
+
}
|
|
37
|
+
// Snapshot before asynchronous I/O; callers may reuse buffers/objects.
|
|
38
|
+
const envelope = JSON.parse(JSON.stringify({ eventId: event.eventId, observation: event, destinations }));
|
|
39
|
+
return serialized(() => { return spool.append(envelope, destinations.map((item) => { return item.id; })); });
|
|
40
|
+
},
|
|
41
|
+
async drain() {
|
|
42
|
+
if (state.draining || state.closed) { return { delivered: 0, failed: 0 }; }
|
|
43
|
+
state.draining = true;
|
|
44
|
+
const result = { delivered: 0, failed: 0 };
|
|
45
|
+
try {
|
|
46
|
+
const rows = await serialized(() => { return spool.pending(options.batchSize ?? 100); });
|
|
47
|
+
for (const row of rows) {
|
|
48
|
+
for (const id of row.remaining) {
|
|
49
|
+
// Recipients fail independently; continue draining other destinations.
|
|
50
|
+
// eslint-disable-next-line no-await-in-loop, max-depth
|
|
51
|
+
try { await send(row, id); result.delivered += 1; } catch (error) {
|
|
52
|
+
result.failed += 1; options.onError?.(error);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return result;
|
|
57
|
+
} finally { Object.assign(state, { draining: false }); }
|
|
58
|
+
},
|
|
59
|
+
close() { state.closed = true; return sessions.close(); },
|
|
60
|
+
status() { return spool.status(); }
|
|
61
|
+
};
|
|
62
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import deadline from './deadline.js';
|
|
2
|
+
|
|
3
|
+
/** Bounded reusable AMQP connections, independent of collector task lifecycles. */
|
|
4
|
+
export default function deliverySessions(factory, timeoutMs = 10000) {
|
|
5
|
+
const sessions = new Map();
|
|
6
|
+
return {
|
|
7
|
+
async write(descriptor, event) {
|
|
8
|
+
const key = JSON.stringify(descriptor);
|
|
9
|
+
let sink = sessions.get(key);
|
|
10
|
+
if (!sink) {
|
|
11
|
+
if (sessions.size >= 64) { throw new Error('Delivery session capacity exceeded'); }
|
|
12
|
+
sink = factory(descriptor); sessions.set(key, sink);
|
|
13
|
+
try { await deadline(() => { return sink.start?.(); }, timeoutMs); } catch (error) {
|
|
14
|
+
sessions.delete(key);
|
|
15
|
+
await deadline(() => { return sink.stop?.(); }, timeoutMs).catch(() => {
|
|
16
|
+
// Original failure propagates.
|
|
17
|
+
});
|
|
18
|
+
throw error;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
await deadline(() => { return sink.write([event]); }, timeoutMs);
|
|
22
|
+
},
|
|
23
|
+
async close() {
|
|
24
|
+
await Promise.allSettled(Array.from(sessions.values(), (sink) => { return deadline(() => { return sink.stop?.(); }, timeoutMs); }));
|
|
25
|
+
sessions.clear();
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import modbusPublish from '../../infrastructure/ingest/mqtt/modbusPublish.js';
|
|
3
|
+
|
|
4
|
+
function runtimeConfig(spec,context) {
|
|
5
|
+
return {...spec.config,onFatal(error) {
|
|
6
|
+
context.report?.({state:'failed',fatal:true,reason:error.code??error.name});
|
|
7
|
+
spec.config.onFatal?.(error);
|
|
8
|
+
}};
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** Preserve the telemetry wire contract while moving durable buffering ahead of the network. */
|
|
12
|
+
export default function modbusDelivery(spec, context, publish = modbusPublish) {
|
|
13
|
+
const config=runtimeConfig(spec,context);
|
|
14
|
+
if (spec.delivery !== 'spooled') { return publish(spec.url, config); }
|
|
15
|
+
if (!context.deliveryQueue || !spec.sinks?.length || spec.sinks.some((sink) => { return sink.type !== 'amqp'; })) {
|
|
16
|
+
throw new TypeError('Spooled Modbus requires node queue and AMQP destinations');
|
|
17
|
+
}
|
|
18
|
+
const output = {
|
|
19
|
+
start() { return Promise.resolve(); },
|
|
20
|
+
stop() { return Promise.resolve(); },
|
|
21
|
+
async write(records) {
|
|
22
|
+
context.signal?.throwIfAborted();
|
|
23
|
+
context.report?.({ state: 'running', read: 1 });
|
|
24
|
+
for (const record of records) {
|
|
25
|
+
const routingKey = record.topic.replaceAll('/', '.');
|
|
26
|
+
const destinations = spec.sinks.filter((sink) => { return !sink.routingKeyPrefix || routingKey.startsWith(sink.routingKeyPrefix); });
|
|
27
|
+
if (!destinations.length) { throw new Error('No matching Modbus telemetry recipient'); }
|
|
28
|
+
// Retain each decoded observation durably before completing source acceptance.
|
|
29
|
+
// eslint-disable-next-line no-await-in-loop
|
|
30
|
+
await context.deliveryQueue.accept({ eventId: record.eventId ?? randomUUID(),
|
|
31
|
+
exchange: 'scada.telemetry', routingKey, body: Buffer.from(record.payload) }, destinations);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
return publish(spec.url, { ...config, size: 1, output });
|
|
36
|
+
}
|
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { mqttSink } from '../../infrastructure/streams/index.js';
|
|
2
|
+
import telemetrySink, { validateTelemetryPolicy } from './telemetrySink.js';
|
|
2
3
|
import activityTracking from '../../infrastructure/ingest/activity/activityTracking.js';
|
|
3
4
|
import amqpMetricsIngest from '../../infrastructure/ingest/telemetry/amqpMetricsIngest.js';
|
|
4
5
|
import amqpMqttRelay from '../../infrastructure/ingest/telemetry/amqpMqttRelay.js';
|
|
5
|
-
import
|
|
6
|
+
import modbusDelivery from './modbusDelivery.js';
|
|
6
7
|
import mqttMetrics from '../../infrastructure/ingest/mqtt/mqttMetrics.js';
|
|
7
8
|
import { parseModbusDeviceSpec } from '../../infrastructure/ingest/mqtt/modbusDeviceSpec.js';
|
|
8
9
|
import compositeLifecycle from './compositeLifecycle.js';
|
|
@@ -11,7 +12,9 @@ import resolveSecrets from './resolveSecrets.js';
|
|
|
11
12
|
function configured(spec, context) {
|
|
12
13
|
const options = { maxRecords: spec.limits?.maxRecords, maxBytes: spec.limits?.maxBytes, budget: context.budget };
|
|
13
14
|
const defined = Object.fromEntries(Object.entries(options).filter(([, value]) => { return value !== undefined; }));
|
|
14
|
-
|
|
15
|
+
const { sinks, ...source } = spec;
|
|
16
|
+
return { ...resolveSecrets(source, context.secrets),
|
|
17
|
+
...(sinks !== undefined && { sinks: structuredClone(sinks) }),
|
|
15
18
|
config: { ...resolveSecrets(spec.config, context.secrets), ...defined },
|
|
16
19
|
options: { ...resolveSecrets(spec.options, context.secrets), ...defined } };
|
|
17
20
|
}
|
|
@@ -19,6 +22,7 @@ function adapter(factory, required, resourceKeys = () => { return []; }) {
|
|
|
19
22
|
return {
|
|
20
23
|
validate(spec) {
|
|
21
24
|
required.forEach((key) => { if (!spec[key]) { throw new TypeError(`Missing pipeline ${key}`); } });
|
|
25
|
+
validateTelemetryPolicy(spec);
|
|
22
26
|
},
|
|
23
27
|
resources(spec) { return resourceKeys(spec); },
|
|
24
28
|
create(spec, context) {
|
|
@@ -46,14 +50,14 @@ function modbusResources(spec) {
|
|
|
46
50
|
return [...new Set(paths)];
|
|
47
51
|
}
|
|
48
52
|
function metrics(spec, factory) {
|
|
49
|
-
const sink =
|
|
50
|
-
return compositeLifecycle({ outputs: [sink
|
|
53
|
+
const sink = telemetrySink(spec);
|
|
54
|
+
return compositeLifecycle({ outputs: [{ start() { return sink.start?.(); }, async stop() {
|
|
55
|
+
await sink.stop();
|
|
56
|
+
} }], inputs: [factory(sink)] });
|
|
51
57
|
}
|
|
52
58
|
export default function pipelineAdapters() {
|
|
53
59
|
return new Map([
|
|
54
|
-
['modbus', adapter((spec, context) => { return
|
|
55
|
-
context.report?.({ state: 'failed', fatal: true, reason: error.code ?? error.name });
|
|
56
|
-
} }); }, ['url', 'config'], modbusResources)],
|
|
60
|
+
['modbus', adapter((spec, context) => { return modbusDelivery(spec, context); }, ['url', 'config'], modbusResources)],
|
|
57
61
|
['activity', adapter((spec) => { return activityTracking(spec.lokiUrl, spec.clickhouseUrl, spec.query, spec.config); }, ['lokiUrl', 'clickhouseUrl', 'query', 'config'])],
|
|
58
62
|
['amqp-relay', adapter((spec) => { return amqpMqttRelay(spec.url, spec.queue, mqttSink(spec.mqttUrl, spec.options), spec.options); }, ['url', 'queue', 'mqttUrl'])],
|
|
59
63
|
['amqp-metrics', adapter((spec) => { return metrics(spec, (sink) => { return amqpMetricsIngest(spec.url, spec.queue, sink, spec.options); }); }, ['url', 'queue', 'clickhouseUrl', 'table'])],
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import deliveryQueue from './deliveryQueue.js';
|
|
2
|
+
import { sinks } from './streamPorts.js';
|
|
3
|
+
|
|
4
|
+
/** Configured once per node; queue draining outlives any individual assignment. */
|
|
5
|
+
export default function queuedDelivery(env, secrets, supplied) {
|
|
6
|
+
let timer;
|
|
7
|
+
let stopped = false;
|
|
8
|
+
const queue = supplied ?? (env.COLLECTOR_SPOOL_DIR ? deliveryQueue(env.COLLECTOR_SPOOL_DIR, {
|
|
9
|
+
maxBytes: Number(env.COLLECTOR_SPOOL_MAX_BYTES), maxRecords: Number(env.COLLECTOR_SPOOL_MAX_RECORDS ?? 100000), factory(spec) { return sinks().get(spec.type)(spec, { secrets }); },
|
|
10
|
+
onError(error) { process.stderr.write(`Collector delivery delayed: ${error.message}\n`); }
|
|
11
|
+
}) : undefined);
|
|
12
|
+
async function tick() {
|
|
13
|
+
if (stopped || !queue) { return; }
|
|
14
|
+
try {
|
|
15
|
+
if (queue.status?.().ready === false) { await queue.open(); }
|
|
16
|
+
await queue.drain();
|
|
17
|
+
} catch (error) { process.stderr.write(`Collector spool: ${error.message}\n`); }
|
|
18
|
+
if (!stopped) { timer = setTimeout(tick, 1000); timer.unref(); }
|
|
19
|
+
}
|
|
20
|
+
return {
|
|
21
|
+
queue,
|
|
22
|
+
async open() { if (queue) { await queue.open(); timer = setTimeout(tick, 0); timer.unref(); } },
|
|
23
|
+
stop() { stopped = true; clearTimeout(timer); return queue?.close?.(); }
|
|
24
|
+
};
|
|
25
|
+
}
|
|
@@ -3,6 +3,10 @@ import collectorSignals from './collectorSignals.js';
|
|
|
3
3
|
import createRuntime from './runtime.js';
|
|
4
4
|
import runtimeServices from './runtimeServices.js';
|
|
5
5
|
import runtimeHealth from './runtimeHealth.js';
|
|
6
|
+
import deadline from './deadline.js';
|
|
7
|
+
import assignmentAgent from '../control/agent.js';
|
|
8
|
+
import controlStore from '../control/controlStore.js';
|
|
9
|
+
import { clientFromEnv } from '../control/controlClient.js';
|
|
6
10
|
|
|
7
11
|
async function apply(runtime, document) {
|
|
8
12
|
for (const removal of document.removals ?? []) {
|
|
@@ -16,11 +20,33 @@ async function apply(runtime, document) {
|
|
|
16
20
|
await runtime.apply(input);
|
|
17
21
|
}
|
|
18
22
|
}
|
|
23
|
+
function healthView(runtime, state) {
|
|
24
|
+
return { status() {
|
|
25
|
+
const status = runtime.status();
|
|
26
|
+
return { ...status, stopping: status.stopping || state.stopped, fatal: status.fatal || state.failed,
|
|
27
|
+
initialized: state.initialized && (!state.agent || state.agent.status().appliedGeneration !== null) };
|
|
28
|
+
} };
|
|
29
|
+
}
|
|
30
|
+
async function initialize(collector, owned, state, { env, registry }) {
|
|
31
|
+
const { runtime } = collector;
|
|
32
|
+
await owned.open?.();
|
|
33
|
+
if (state.stopped) { throw new Error('Collector stopped during recovery'); }
|
|
34
|
+
if (env.COLLECTOR_CONTROL_ENDPOINTS) {
|
|
35
|
+
const store = controlStore(clientFromEnv(env, 'COLLECTOR_CONTROL'), env.COLLECTOR_CONTROL_PREFIX);
|
|
36
|
+
state.agent = assignmentAgent({ nodeId: env.COLLECTOR_NODE_ID, file: env.COLLECTOR_ASSIGNMENT_FILE, store, runtime,
|
|
37
|
+
validate(document) { return validateManifest(document, registry); },
|
|
38
|
+
onError(error) { process.stderr.write(`collector control: ${error.name}\n`); } });
|
|
39
|
+
await state.agent.start({ waitForInitialTick: false });
|
|
40
|
+
} else { await collector.reload(); }
|
|
41
|
+
if (state.stopped) { throw new Error('Collector stopped during recovery'); }
|
|
42
|
+
state.initialized = true;
|
|
43
|
+
}
|
|
19
44
|
/** Local executable host. The external agent can instead use createRuntime directly. */
|
|
45
|
+
// eslint-disable-next-line max-statements
|
|
20
46
|
export default async function runCollector({ registry, env = process.env, argv = process.argv.slice(2), signals = true, manifestReader = readManifest, ...services }) {
|
|
21
47
|
const owned = runtimeServices(env, services);
|
|
22
48
|
const runtime = createRuntime({ registry, ...owned });
|
|
23
|
-
const state = { health: null, reloading: false, stopped: false, detach: null };
|
|
49
|
+
const state = { initialized: false, failed: false, health: null, reloading: false, stopped: false, detach: null, agent: null };
|
|
24
50
|
const collector = {
|
|
25
51
|
runtime,
|
|
26
52
|
async reload() {
|
|
@@ -35,14 +61,19 @@ export default async function runCollector({ registry, env = process.env, argv =
|
|
|
35
61
|
async stop() {
|
|
36
62
|
state.stopped = true;
|
|
37
63
|
state.detach?.();
|
|
64
|
+
await state.agent?.stop();
|
|
38
65
|
try { await runtime.stop(); } finally { await Promise.all([owned.close(), state.health?.stop()]); }
|
|
39
66
|
}
|
|
40
67
|
};
|
|
41
68
|
if (signals) { state.detach = collectorSignals(collector); }
|
|
42
69
|
try {
|
|
43
|
-
|
|
44
|
-
|
|
70
|
+
if (env.COLLECTOR_HEALTH_PORT) { Object.assign(state, { health: await runtimeHealth(healthView(runtime, state), {
|
|
71
|
+
port: Number(env.COLLECTOR_HEALTH_PORT), host: env.COLLECTOR_HEALTH_HOST ?? '127.0.0.1' }) }); }
|
|
72
|
+
const recoveryMs = Number(env.COLLECTOR_RECOVERY_TIMEOUT_MS ?? 900000);
|
|
73
|
+
if (!Number.isSafeInteger(recoveryMs) || recoveryMs < 1) { throw new TypeError('Positive collector recovery timeout required'); }
|
|
74
|
+
await deadline(() => { return initialize(collector, owned, state, { env, registry }); }, recoveryMs);
|
|
45
75
|
} catch (error) {
|
|
76
|
+
Object.assign(state, { failed: true });
|
|
46
77
|
try { await collector.stop(); } catch (cleanup) { throw new AggregateError([error, cleanup], 'Collector startup cleanup failed'); }
|
|
47
78
|
throw error;
|
|
48
79
|
}
|
|
@@ -35,7 +35,7 @@ function duplicate(slot, request) {
|
|
|
35
35
|
}
|
|
36
36
|
if (request.generation !== slot.generation) { return false; }
|
|
37
37
|
if (slot.specHash !== request.specHash) { throw new Error('assignment conflict'); }
|
|
38
|
-
return
|
|
38
|
+
return slot.state !== 'failed';
|
|
39
39
|
}
|
|
40
40
|
async function apply(ctx, input, slot) {
|
|
41
41
|
if (ctx.fatal || ctx.stopping) { throw new Error('Runtime stopping or fatal'); }
|
|
@@ -75,7 +75,7 @@ export default function createRuntime(options) {
|
|
|
75
75
|
maxTasks: positive(options.maxTasks ?? 1000), maxPending: positive(options.maxPending ?? 100),
|
|
76
76
|
stopTimeoutMs: positive(options.stopTimeoutMs ?? 10000), startTimeoutMs: positive(options.startTimeoutMs ?? 10000),
|
|
77
77
|
budget: taskBudget(options.budgets ?? { maxBytes: 16777216, maxRecords: 16384 }),
|
|
78
|
-
services: { stateStore: options.stateStore, secrets: options.secrets, report: options.report } };
|
|
78
|
+
services: { stateStore: options.stateStore, secrets: options.secrets, report: options.report, deliveryQueue: options.deliveryQueue } };
|
|
79
79
|
if (!(ctx.registry instanceof Map)) { throw new TypeError('registry must be a Map'); }
|
|
80
80
|
return {
|
|
81
81
|
apply(input) { return enqueue(ctx, input, (slot) => { return apply(ctx, input, slot); }); },
|
|
@@ -4,7 +4,7 @@ import { monitorEventLoopDelay } from 'node:perf_hooks';
|
|
|
4
4
|
function response(runtime, histogram, request, result) {
|
|
5
5
|
if (!['/live', '/ready', '/status'].includes(request.url)) { result.writeHead(404).end(); return; }
|
|
6
6
|
const state = runtime.status();
|
|
7
|
-
const ready = !state.fatal && !state.stopping && !state.tasks.some((task) => {
|
|
7
|
+
const ready = state.initialized !== false && !state.fatal && !state.stopping && !state.tasks.some((task) => {
|
|
8
8
|
return task.state === 'failed' || ['failed', 'degraded'].includes(task.health);
|
|
9
9
|
});
|
|
10
10
|
const body = request.url === '/status' ? { ...state, memory: process.memoryUsage(), eventLoopP99Ms: histogram.percentile(99) / 1e6 } : { ready };
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import pg from 'pg';
|
|
2
2
|
import taskStatePg from '../../infrastructure/persistence/runtime/taskStatePg.js';
|
|
3
3
|
import deadline from './deadline.js';
|
|
4
|
+
import queuedDelivery from './queuedDelivery.js';
|
|
4
5
|
|
|
5
6
|
/** Storage is optional for live-only tasks and mandatory for durable adapters. */
|
|
6
7
|
export default function runtimeServices(env, supplied) {
|
|
@@ -8,8 +9,11 @@ export default function runtimeServices(env, supplied) {
|
|
|
8
9
|
connectionString: env.COLLECTOR_STATE_URL, max: 4, connectionTimeoutMillis: 5000,
|
|
9
10
|
query_timeout: 10000, statement_timeout: 10000, idleTimeoutMillis: 30000
|
|
10
11
|
}) : null;
|
|
11
|
-
|
|
12
|
+
const secrets = supplied.secrets ?? { get(name) { return env[name]; } };
|
|
13
|
+
const delivery = queuedDelivery(env, secrets, supplied.deliveryQueue);
|
|
14
|
+
return { ...supplied, secrets, deliveryQueue: delivery.queue,
|
|
15
|
+
open() { return delivery.open(); },
|
|
12
16
|
stateStore: supplied.stateStore ?? (pool ? taskStatePg(pool) : undefined),
|
|
13
|
-
close() {
|
|
17
|
+
async close() { await delivery.stop(); if (pool) { await deadline(() => { return pool.end(); }, 10000); } }
|
|
14
18
|
};
|
|
15
19
|
}
|
|
@@ -1,13 +1,16 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
1
2
|
import taskState from './taskState.js';
|
|
2
3
|
import deadline from './deadline.js';
|
|
3
4
|
import budgetedSink from './budgetedSink.js';
|
|
4
5
|
|
|
6
|
+
// eslint-disable-next-line max-statements
|
|
5
7
|
function validate(spec, ports) {
|
|
6
8
|
if (!ports.sources.has(spec.source?.type)) { throw new TypeError('Unknown stream source'); }
|
|
7
9
|
if (!Array.isArray(spec.sinks) || !spec.sinks.length || spec.sinks.some((sink) => { return !ports.sinks.has(sink.type); })) {
|
|
8
10
|
throw new TypeError('Unknown stream sink');
|
|
9
11
|
}
|
|
10
|
-
if (!['live', 'durable'].includes(spec.delivery)) { throw new TypeError('Explicit delivery policy required'); }
|
|
12
|
+
if (!['live', 'durable', 'spooled'].includes(spec.delivery)) { throw new TypeError('Explicit delivery policy required'); }
|
|
13
|
+
if (spec.delivery === 'spooled' && spec.sinks.some((sink) => { return sink.type !== 'amqp'; })) { throw new TypeError('Spooled delivery requires AMQP'); }
|
|
11
14
|
const names = spec.sinks.map((sink, index) => { return sink.id ?? String(index); });
|
|
12
15
|
if (new Set(names).size !== names.length) { throw new TypeError('Duplicate sink id'); }
|
|
13
16
|
if (spec.delivery === 'durable' && spec.sinks.some((sink) => { return sink.type === 'mqtt' && ![1, 2].includes(sink.options?.qos); })) {
|
|
@@ -26,6 +29,7 @@ async function durable(bag, value) {
|
|
|
26
29
|
await bag.state.resume(bag.sinks);
|
|
27
30
|
if (pending?.event.eventId !== value.eventId) { await bag.state.deliver(value, bag.sinks, value.checkpoint ?? null); }
|
|
28
31
|
}
|
|
32
|
+
// eslint-disable-next-line max-statements
|
|
29
33
|
async function accept(bag, record) {
|
|
30
34
|
bag.context.signal.throwIfAborted();
|
|
31
35
|
if (bag.stopped) { throw new Error('Stream stopped'); }
|
|
@@ -33,8 +37,11 @@ async function accept(bag, record) {
|
|
|
33
37
|
try {
|
|
34
38
|
const value = bag.transform ? await bag.transform(record) : record;
|
|
35
39
|
bag.context.signal.throwIfAborted();
|
|
40
|
+
bag.context.report?.({ state: 'running', read: 1 });
|
|
36
41
|
if (value === null) { return; }
|
|
37
|
-
if (bag.
|
|
42
|
+
if (bag.queued) {
|
|
43
|
+
await bag.context.deliveryQueue.accept({ ...value, eventId: value.eventId ?? randomUUID() }, bag.destinations);
|
|
44
|
+
} else if (bag.state) { await durable(bag, value); }
|
|
38
45
|
else {
|
|
39
46
|
await Promise.all(Object.values(bag.sinks).map((sink) => {
|
|
40
47
|
bag.context.signal.throwIfAborted();
|
|
@@ -86,10 +93,12 @@ function recipient(spec, stream, context, ports) {
|
|
|
86
93
|
}
|
|
87
94
|
function create(spec, context, ports) {
|
|
88
95
|
if (spec.delivery === 'durable' && !context.stateStore) { throw new TypeError('Durable stateStore required'); }
|
|
89
|
-
|
|
96
|
+
if (spec.delivery === 'spooled' && !context.deliveryQueue) { throw new TypeError('Node deliveryQueue required'); }
|
|
97
|
+
const sinks = spec.delivery === 'spooled' ? {} : Object.fromEntries(spec.sinks.map((sink, index) => {
|
|
90
98
|
return [sink.id ?? String(index), budgetedSink(recipient(sink, spec, context, ports), context.budget, false)];
|
|
91
99
|
}));
|
|
92
|
-
const bag = { sinks, context,
|
|
100
|
+
const bag = { sinks, context, queued: spec.delivery === 'spooled',
|
|
101
|
+
destinations: spec.sinks.map((sink, index) => { return { ...sink, id: sink.id ?? String(index) }; }), stopped: false, timeoutMs: spec.writeTimeoutMs ?? 10000,
|
|
93
102
|
transform: ports.transforms.get(spec.transform),
|
|
94
103
|
state: spec.delivery === 'durable' ? taskState(context.stateStore, { ...spec, taskId: context.taskId, signal: context.signal }) : null };
|
|
95
104
|
bag.source = ports.sources.get(spec.source.type)(spec.source, { accept(record) { return accept(bag, record); } }, context);
|
|
@@ -10,6 +10,7 @@ export default function taskContext(slot, request, ctx) {
|
|
|
10
10
|
if (controller.signal.aborted) { return; }
|
|
11
11
|
slot.health = event.state;
|
|
12
12
|
if (event.fatal === true) { ctx.fatal = true; }
|
|
13
|
+
if (event.read) { slot.lastRead = Date.now(); }
|
|
13
14
|
if (event.delivered) { slot.lastDelivery = Date.now(); }
|
|
14
15
|
try { ctx.services.report?.({ taskId: slot.taskId, generation: slot.generation, ...event }); } catch {
|
|
15
16
|
// Observability cannot interrupt collection.
|
|
@@ -24,7 +24,7 @@ function validateTask(task) {
|
|
|
24
24
|
}
|
|
25
25
|
export async function launch(slot, request, ctx, resources) {
|
|
26
26
|
ctx.claims.acquire(slot.taskId, resources);
|
|
27
|
-
Object.assign(slot, { generation: request.generation, specHash: request.specHash, removed: false, state: 'starting', reason: null });
|
|
27
|
+
Object.assign(slot, { generation: request.generation, specHash: request.specHash, removed: false, state: 'starting', reason: null, health: 'unknown', lastRead: null, lastDelivery: null });
|
|
28
28
|
slot.controller = new AbortController();
|
|
29
29
|
const context = taskContext(slot, request, ctx);
|
|
30
30
|
try {
|
|
@@ -42,5 +42,5 @@ export async function launch(slot, request, ctx, resources) {
|
|
|
42
42
|
}
|
|
43
43
|
export function view(slot) {
|
|
44
44
|
return { taskId: slot.taskId, generation: slot.generation, specHash: slot.specHash,
|
|
45
|
-
state: slot.state, health: slot.health ?? 'unknown', lastDelivery: slot.lastDelivery ?? null, reason: slot.reason ?? null };
|
|
45
|
+
state: slot.state, health: slot.health ?? 'unknown', lastRead: slot.lastRead ?? null, lastDelivery: slot.lastDelivery ?? null, reason: slot.reason ?? null };
|
|
46
46
|
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { clickhouseSink } from '../../infrastructure/streams/index.js';
|
|
2
|
+
import centralMetricsSink from '../../infrastructure/ingest/telemetry/centralMetricsSink.js';
|
|
3
|
+
import centralPolicy from '../../infrastructure/ingest/telemetry/centralPolicy.js';
|
|
4
|
+
|
|
5
|
+
export function validateTelemetryPolicy(spec) {
|
|
6
|
+
if (!spec.telemetryPolicy) { return; }
|
|
7
|
+
centralPolicy(spec.telemetryPolicy);
|
|
8
|
+
if ((centralPolicy(spec.telemetryPolicy).enabled && !spec.telemetryAmqp) || (spec.table && spec.table !== 'scada.metrics')) {
|
|
9
|
+
throw new TypeError('Central telemetry policy requires telemetryAmqp and scada.metrics table');
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
/** One central policy path shared by all portable ClickHouse ingest adapters. */
|
|
13
|
+
export default function telemetrySink(spec) {
|
|
14
|
+
validateTelemetryPolicy(spec);
|
|
15
|
+
const url = spec.clickhouse ?? spec.clickhouseUrl;
|
|
16
|
+
if (!spec.telemetryPolicy && spec.table && spec.table !== 'scada.metrics') { return clickhouseSink(url,spec.table); }
|
|
17
|
+
return centralMetricsSink({ CLICKHOUSE_URL: url, AMQP_URL: spec.telemetryAmqp, CENTRAL_TELEMETRY_POLICY: spec.telemetryPolicy ? JSON.stringify(spec.telemetryPolicy) : undefined });
|
|
18
|
+
}
|
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
import
|
|
1
|
+
import centralMetricsSink from '../infrastructure/ingest/telemetry/centralMetricsSink.js';
|
|
2
|
+
import centralTelemetryPreflight from '../infrastructure/ingest/telemetry/centralTelemetryPreflight.js';
|
|
3
|
+
import centralPolicy from '../infrastructure/ingest/telemetry/centralPolicy.js';
|
|
2
4
|
import supervisorSink from './supervisorSink.js';
|
|
3
5
|
import plantServer from './plantServer.js';
|
|
4
6
|
import plantOperations from './plantOperations.js';
|
|
@@ -44,10 +46,11 @@ function mqttSinkForProfile(sink, env) {
|
|
|
44
46
|
if (!url) {
|
|
45
47
|
throw new Error('CLICKHOUSE_URL or CLICKHOUSE_HOST is required for central MQTT metrics');
|
|
46
48
|
}
|
|
47
|
-
return
|
|
49
|
+
return centralMetricsSink(env);
|
|
48
50
|
}
|
|
49
51
|
|
|
50
52
|
function startMqtt(sink, env) {
|
|
53
|
+
if (env.HISTORY_AMQP_ENABLED === 'true' && env.SINK_DB_PROFILE !== 'central') { return undefined; }
|
|
51
54
|
if (!env.MQTT_URL || !env.MQTT_TOPICS) {
|
|
52
55
|
return undefined;
|
|
53
56
|
}
|
|
@@ -109,6 +112,18 @@ function siteExtraRoutes(catalog, extraRoutes, syncRoutes) {
|
|
|
109
112
|
};
|
|
110
113
|
}
|
|
111
114
|
|
|
115
|
+
function startCentralArchive(env) {
|
|
116
|
+
if (env.SINK_DB_PROFILE !== 'central' || !centralPolicy(env.CENTRAL_TELEMETRY_POLICY ?? {}).enabled) { return undefined; }
|
|
117
|
+
const archive = centralMetricsSink(env);
|
|
118
|
+
void archive.start().catch(() => { return undefined; });
|
|
119
|
+
return archive;
|
|
120
|
+
}
|
|
121
|
+
async function runSiteSink(sink, http, env) {
|
|
122
|
+
await sink.run(http);
|
|
123
|
+
if (env.SINK_DB_PROFILE === 'central') { await centralTelemetryPreflight(env); }
|
|
124
|
+
return startCentralArchive(env);
|
|
125
|
+
}
|
|
126
|
+
|
|
112
127
|
/**
|
|
113
128
|
* Unified site process: supervisor-sink HTTP, plant API, and optional MQTT ingest.
|
|
114
129
|
*
|
|
@@ -132,7 +147,7 @@ export default async function siteServer(config) {
|
|
|
132
147
|
pool: sink.pool,
|
|
133
148
|
runRetention
|
|
134
149
|
});
|
|
135
|
-
await sink
|
|
150
|
+
const centralTelemetry = await runSiteSink(sink, http, env);
|
|
136
151
|
const mqtt = startCollection(config, () => { return startMqtt(sink, env); });
|
|
137
152
|
const telemetry = startCollection(config, () => { return startTelemetryIngest(
|
|
138
153
|
env,
|
|
@@ -161,5 +176,5 @@ export default async function siteServer(config) {
|
|
|
161
176
|
owners: config.owners,
|
|
162
177
|
decorateTimeline: config.decorateTimeline
|
|
163
178
|
});
|
|
164
|
-
return { sink, plant, mqtt, telemetry, operationSync, operatorsSync: catalog.sync };
|
|
179
|
+
return { sink, sinkHttp:http, plant, mqtt, telemetry, centralTelemetry, operationSync, operatorsSync: catalog.sync };
|
|
165
180
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import
|
|
1
|
+
import centralMetricsSink from '../infrastructure/ingest/telemetry/centralMetricsSink.js';
|
|
2
2
|
import amqpMetricsIngest from '../infrastructure/ingest/telemetry/amqpMetricsIngest.js';
|
|
3
3
|
import foldedMetricsSink from './foldedMetricsSink.js';
|
|
4
4
|
import bindSilentStreams from './bindSilentStreams.js';
|
|
@@ -62,7 +62,7 @@ export default function startTelemetryIngest(env, streams, batchConfig, pool, de
|
|
|
62
62
|
if (!url) {
|
|
63
63
|
throw new Error('CLICKHOUSE_URL or CLICKHOUSE_HOST is required for AMQP telemetry ingest');
|
|
64
64
|
}
|
|
65
|
-
const sink = foldedMetricsSink(
|
|
65
|
+
const sink = foldedMetricsSink(centralMetricsSink(env), pool, devices);
|
|
66
66
|
const onSeen = bindSilentStreams(streams, sink);
|
|
67
67
|
const ingest = startAmqpMetrics(env, sink, onSeen, batchConfig);
|
|
68
68
|
if (streams) {
|
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
import ingestHealth from './ingestHealth.js';
|
|
2
2
|
import segmentTransactionConfig from './segmentTransactionConfig.js';
|
|
3
3
|
import segmentBatchStats from './segmentBatchStats.js';
|
|
4
|
+
import historyTelemetry from '../infrastructure/ingest/telemetry/historyTelemetry.js';
|
|
4
5
|
import segmentPipeline, {
|
|
5
6
|
segmentsIngestDestination
|
|
6
7
|
} from '../infrastructure/ingest/pipelines/segmentPipeline.js';
|
|
7
8
|
import decisionPipeline from '../infrastructure/ingest/pipelines/decisionPipeline.js';
|
|
8
9
|
import alertPipeline from '../infrastructure/ingest/pipelines/alertPipeline.js';
|
|
9
|
-
import migrate, { migratePrivileged } from '../infrastructure/ingest/db/migrate.js';
|
|
10
|
+
import migrate, { migratePrivileged, verifyMigrations } from '../infrastructure/ingest/db/migrate.js';
|
|
10
11
|
import stateDataFromPool from '../infrastructure/persistence/stateDataFromPool.js';
|
|
11
12
|
import { parseRequestTimeoutMs } from '../infrastructure/ingest/parseRequestTimeoutMs.js';
|
|
12
13
|
import pg from 'pg';
|
|
@@ -38,6 +39,13 @@ function historyRepair(value) {
|
|
|
38
39
|
return value === 'true';
|
|
39
40
|
}
|
|
40
41
|
|
|
42
|
+
function migrationMode(value = 'apply') {
|
|
43
|
+
if (!['apply', 'verify'].includes(value)) {
|
|
44
|
+
throw new TypeError('SUPERVISOR_MIGRATIONS must be apply or verify');
|
|
45
|
+
}
|
|
46
|
+
return value;
|
|
47
|
+
}
|
|
48
|
+
|
|
41
49
|
export function readDeploymentConfig(env) {
|
|
42
50
|
const root = path.join(appRoot, '../..');
|
|
43
51
|
const prefetch = Number(env.STOMP_PREFETCH || '128');
|
|
@@ -50,6 +58,7 @@ export function readDeploymentConfig(env) {
|
|
|
50
58
|
stomp: env.STOMP_URL,
|
|
51
59
|
postgres: env.POSTGRES_URL,
|
|
52
60
|
postgresAdmin: env.POSTGRES_ADMIN_URL,
|
|
61
|
+
migrationsMode: migrationMode(env.SUPERVISOR_MIGRATIONS),
|
|
53
62
|
apiPort: parseInt(
|
|
54
63
|
env.STATE_HTTP_PORT || env.INTERNAL_API_PORT || '8081',
|
|
55
64
|
10
|
|
@@ -92,6 +101,23 @@ function startPipelines(cfg, pool, health) {
|
|
|
92
101
|
return Promise.all(pipelines.map((pipeline) => { return pipeline.start(); }));
|
|
93
102
|
}
|
|
94
103
|
|
|
104
|
+
async function prepareDatabase(cfg, pool) {
|
|
105
|
+
if (cfg.migrationsMode === 'verify') {
|
|
106
|
+
await verifyMigrations(pool, cfg.migrationsDir, cfg.sinkDbProfile);
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
if (!cfg.postgresAdmin) {
|
|
110
|
+
throw new Error('POSTGRES_ADMIN_URL is required for supervisor-sink database migrations');
|
|
111
|
+
}
|
|
112
|
+
const adminPool = holdClient(new pg.Pool({ connectionString: cfg.postgresAdmin }));
|
|
113
|
+
try {
|
|
114
|
+
await migrate(adminPool, cfg.migrationsDir, cfg.sinkDbProfile);
|
|
115
|
+
await migratePrivileged(adminPool, cfg.migrationsDir, cfg.sinkDbProfile);
|
|
116
|
+
} finally {
|
|
117
|
+
await adminPool.end();
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
95
121
|
/**
|
|
96
122
|
* Wires STOMP pipelines, migrations, and state data access from env config.
|
|
97
123
|
* HTTP binding uses edgeApi (metrics, checkpoint, retention).
|
|
@@ -106,10 +132,12 @@ export default function supervisorSink(env = process.env, options = {}) {
|
|
|
106
132
|
if (cfg.pipeline.transactions.enabled) { cfg.pipeline.onBatch = segmentBatchStats(cfg.pipeline.transactions.statsIntervalMs); }
|
|
107
133
|
const pool = holdClient(new pg.Pool({ connectionString: cfg.postgres, max: cfg.dbPoolMax }));
|
|
108
134
|
const metricsEnabled = cfg.sinkDbProfile === 'edge';
|
|
109
|
-
const data = stateDataFromPool(pool, { metricsEnabled });
|
|
135
|
+
const data = stateDataFromPool(pool, { metricsEnabled, historyRetentionDays: Number(env.HISTORY_RETENTION_DAYS ?? 30) });
|
|
110
136
|
const dataAccess = options.stateData ? options.stateData(data, pool) : data;
|
|
137
|
+
const localTelemetry = historyTelemetry(env, pool);
|
|
111
138
|
return {
|
|
112
139
|
health: () => {return health.status()},
|
|
140
|
+
historyTelemetry: localTelemetry,
|
|
113
141
|
apiPort: cfg.apiPort,
|
|
114
142
|
apiToken: cfg.apiToken,
|
|
115
143
|
sinkDbProfile: cfg.sinkDbProfile,
|
|
@@ -120,16 +148,8 @@ export default function supervisorSink(env = process.env, options = {}) {
|
|
|
120
148
|
pool,
|
|
121
149
|
dataAccess,
|
|
122
150
|
async run(httpServer) {
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
}
|
|
126
|
-
const adminPool = holdClient(new pg.Pool({ connectionString: cfg.postgresAdmin }));
|
|
127
|
-
try {
|
|
128
|
-
await migrate(adminPool, cfg.migrationsDir, cfg.sinkDbProfile);
|
|
129
|
-
await migratePrivileged(adminPool, cfg.migrationsDir, cfg.sinkDbProfile);
|
|
130
|
-
} finally {
|
|
131
|
-
await adminPool.end();
|
|
132
|
-
}
|
|
151
|
+
await prepareDatabase(cfg, pool);
|
|
152
|
+
await localTelemetry?.start();
|
|
133
153
|
if (cfg.pipelines) {
|
|
134
154
|
await startPipelines(cfg, pool, health);
|
|
135
155
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import
|
|
1
|
+
import centralMetricsSink from '../../infrastructure/ingest/telemetry/centralMetricsSink.js';
|
|
2
2
|
import { jobRoutes, jobs } from '@yarkivaev/simple-server';
|
|
3
3
|
import exportQuery from '../export/exportQuery.js';
|
|
4
4
|
import scadaClient from '../../infrastructure/client/scadaClient.js';
|
|
@@ -39,7 +39,7 @@ function metricsOf(sink, env) {
|
|
|
39
39
|
if (!url) {
|
|
40
40
|
return undefined;
|
|
41
41
|
}
|
|
42
|
-
return
|
|
42
|
+
return centralMetricsSink(env);
|
|
43
43
|
}
|
|
44
44
|
|
|
45
45
|
function queryFor(site) {
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { clientFromEnv, controller, controlStore } from '../application/control/index.js';
|
|
3
|
+
try {
|
|
4
|
+
if (!process.env.CONTROL_NODE_ID) { throw new Error('CONTROL_NODE_ID required'); }
|
|
5
|
+
const store = controlStore(clientFromEnv(process.env), process.env.CONTROL_PREFIX);
|
|
6
|
+
const host = controller(store, process.env.CONTROL_NODE_ID, { clockSkewMs: Number(process.env.CONTROL_CLOCK_SKEW_MS ?? 5000), replacementDelayMs: Number(process.env.CONTROL_REPLACEMENT_DELAY_MS ?? 30000), onError(error) { process.stderr.write(`controller: ${error.name}\n`); } });
|
|
7
|
+
for (const signal of ['SIGTERM', 'SIGINT']) { process.once(signal, () => { void host.stop(); }); }
|
|
8
|
+
} catch (error) { process.stderr.write(`controller: ${error.name}\n`); process.exitCode = 1; }
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import http from 'http';
|
|
2
2
|
import ingestHealthRoutes from './routes/ingestHealthRoutes.js';
|
|
3
|
+
import historyRoutes from './routes/history/historyRoutes.js';
|
|
3
4
|
import checkpointRoutes from './routes/checkpoint/checkpointRoutes.js';
|
|
4
5
|
import metricsRoutes from './routes/metrics/metricsRoutes.js';
|
|
5
6
|
import retentionRoutes from './routes/retention/retentionRoutes.js';
|
|
@@ -28,6 +29,7 @@ export function createEdgeApi(dataAccess, options) {
|
|
|
28
29
|
return routes([
|
|
29
30
|
...(opt.health ? ingestHealthRoutes(opt.health) : []),
|
|
30
31
|
...admin,
|
|
32
|
+
...historyRoutes(token, dataAccess.history),
|
|
31
33
|
...checkpointRoutes(token, checkpoints),
|
|
32
34
|
...metricRoutes
|
|
33
35
|
], { requestTimeoutMs: opt.requestTimeoutMs });
|