@yarkivaev/scada 2.5.8 → 2.6.1

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.
Files changed (104) hide show
  1. package/README.md +95 -0
  2. package/db/migrations/E0005__historical_telemetry_grants.sql +5 -0
  3. package/db/migrations/E0006__historical_telemetry.sql +64 -0
  4. package/db/migrations/E0007__metric_receipts.sql +7 -0
  5. package/db/migrations/E0008__metric_receipts_grants.sql +1 -0
  6. package/db/migrations/E0009__history_continuation.sql +20 -0
  7. package/db/migrations/E0010__history_admissions.sql +8 -0
  8. package/db/migrations/E0011__history_classifier_checkpoints.sql +18 -0
  9. package/db/migrations/E0012__external_history_grants.sql +4 -0
  10. package/db/migrations/E0013__history_staged_corrections.sql +104 -0
  11. package/db/migrations/E0014__history_correction_grants.sql +5 -0
  12. package/db/migrations/E0015__history_retention_frontier.sql +7 -0
  13. package/db/migrations/E0016__history_retention_grants.sql +1 -0
  14. package/index.js +7 -0
  15. package/package.json +5 -3
  16. package/src/application/control/agent.js +61 -0
  17. package/src/application/control/catalog.js +22 -0
  18. package/src/application/control/controlClient.js +75 -0
  19. package/src/application/control/controlStore.js +55 -0
  20. package/src/application/control/controller.js +22 -0
  21. package/src/application/control/executionSnapshot.js +32 -0
  22. package/src/application/control/index.js +7 -0
  23. package/src/application/control/localAssignment.js +13 -0
  24. package/src/application/control/schedule.js +103 -0
  25. package/src/application/control/snapshotFile.js +24 -0
  26. package/src/application/foldedMetricsSink.js +1 -0
  27. package/src/application/mcp/mcpResources.js +1 -1
  28. package/src/application/mcp/mcpSchema.js +8 -3
  29. package/src/application/runtime/additionalAdapters.js +13 -9
  30. package/src/application/runtime/deliveryQueue.js +80 -0
  31. package/src/application/runtime/deliverySessions.js +28 -0
  32. package/src/application/runtime/modbusDelivery.js +36 -0
  33. package/src/application/runtime/pipelineAdapters.js +12 -8
  34. package/src/application/runtime/queuedDelivery.js +25 -0
  35. package/src/application/runtime/runCollector.js +34 -3
  36. package/src/application/runtime/runtime.js +2 -2
  37. package/src/application/runtime/runtimeHealth.js +1 -1
  38. package/src/application/runtime/runtimeServices.js +6 -2
  39. package/src/application/runtime/streamTask.js +13 -4
  40. package/src/application/runtime/taskContext.js +1 -0
  41. package/src/application/runtime/taskSlot.js +2 -2
  42. package/src/application/runtime/telemetrySink.js +18 -0
  43. package/src/application/siteServer.js +19 -4
  44. package/src/application/siteTelemetry.js +2 -2
  45. package/src/application/supervisorSink.js +5 -1
  46. package/src/application/sync/siteSyncBind.js +2 -2
  47. package/src/bin/controller.js +8 -0
  48. package/src/infrastructure/http/edge/edgeApi.js +2 -0
  49. package/src/infrastructure/http/edge/routes/history/historyRoutes.js +33 -0
  50. package/src/infrastructure/http/plant/routes/measurementRead.js +3 -0
  51. package/src/infrastructure/ingest/db/migrationProfile.js +6 -1
  52. package/src/infrastructure/ingest/db/retainMetricReceipts.js +8 -0
  53. package/src/infrastructure/ingest/db/runRetention.js +2 -0
  54. package/src/infrastructure/ingest/mqtt/metricsTransformer.js +11 -2
  55. package/src/infrastructure/ingest/mqtt/modbusMqtt.js +1 -1
  56. package/src/infrastructure/ingest/mqtt/modbusPublish.js +2 -0
  57. package/src/infrastructure/ingest/mqtt/mqttMetrics.js +1 -1
  58. package/src/infrastructure/ingest/telemetry/amqpMetricsIngest.js +7 -3
  59. package/src/infrastructure/ingest/telemetry/centralEnvelope.js +46 -0
  60. package/src/infrastructure/ingest/telemetry/centralMetricsSink.js +64 -0
  61. package/src/infrastructure/ingest/telemetry/centralPoint.js +14 -0
  62. package/src/infrastructure/ingest/telemetry/centralPolicy.js +51 -0
  63. package/src/infrastructure/ingest/telemetry/centralQueueSession.js +29 -0
  64. package/src/infrastructure/ingest/telemetry/centralTelemetryPreflight.js +31 -0
  65. package/src/infrastructure/ingest/telemetry/foldingSink.js +3 -0
  66. package/src/infrastructure/ingest/telemetry/historyTelemetry.js +32 -0
  67. package/src/infrastructure/persistence/clickhouse/canonicalMetrics.js +26 -0
  68. package/src/infrastructure/persistence/clickhouse/changes.js +4 -2
  69. package/src/infrastructure/persistence/clickhouse/connection.js +6 -8
  70. package/src/infrastructure/persistence/clickhouse/holds.js +10 -7
  71. package/src/infrastructure/persistence/clickhouse/latest.js +1 -1
  72. package/src/infrastructure/persistence/clickhouse/metricsQuery.js +70 -0
  73. package/src/infrastructure/persistence/clickhouse/metricsRelation.js +110 -0
  74. package/src/infrastructure/persistence/clickhouse/nativeMetricPoints.js +26 -0
  75. package/src/infrastructure/persistence/clickhouse/nativeMetricsAdmission.js +91 -0
  76. package/src/infrastructure/persistence/clickhouse/nativeMetricsClock.js +9 -0
  77. package/src/infrastructure/persistence/clickhouse/nativeMetricsCompaction.js +82 -0
  78. package/src/infrastructure/persistence/clickhouse/nativeMetricsInsert.js +31 -0
  79. package/src/infrastructure/persistence/clickhouse/nativeMetricsOwnership.js +8 -0
  80. package/src/infrastructure/persistence/clickhouse/nativeMetricsSchema.js +44 -0
  81. package/src/infrastructure/persistence/clickhouse/pollTopicCursors.js +3 -1
  82. package/src/infrastructure/persistence/clickhouse/rises.js +4 -2
  83. package/src/infrastructure/persistence/clickhouse/samples.js +10 -0
  84. package/src/infrastructure/persistence/clickhouse/sensor.js +4 -0
  85. package/src/infrastructure/persistence/clickhouse/series.js +38 -21
  86. package/src/infrastructure/persistence/pg/history.js +169 -0
  87. package/src/infrastructure/persistence/pg/historyAdmission.js +81 -0
  88. package/src/infrastructure/persistence/pg/historyCheckpoint.js +56 -0
  89. package/src/infrastructure/persistence/pg/historyConfigure.js +28 -0
  90. package/src/infrastructure/persistence/pg/historyContext.js +65 -0
  91. package/src/infrastructure/persistence/pg/historyCorrection.js +34 -0
  92. package/src/infrastructure/persistence/pg/historyObservations.js +56 -0
  93. package/src/infrastructure/persistence/pg/historySeed.js +27 -0
  94. package/src/infrastructure/persistence/pg/metrics.js +5 -4
  95. package/src/infrastructure/persistence/pg/metricsInsertSql.js +12 -0
  96. package/src/infrastructure/persistence/runtime/deliverySpool.js +57 -0
  97. package/src/infrastructure/persistence/runtime/spoolCodec.js +41 -0
  98. package/src/infrastructure/persistence/runtime/spoolDatabase.js +69 -0
  99. package/src/infrastructure/persistence/runtime/spoolFormat.js +37 -0
  100. package/src/infrastructure/persistence/runtime/spoolMigration.js +66 -0
  101. package/src/infrastructure/persistence/runtime/spoolRecords.js +50 -0
  102. package/src/infrastructure/persistence/stateDataFromPool.js +2 -0
  103. package/src/infrastructure/streams/amqpSink/session.js +6 -0
  104. package/src/infrastructure/streams/amqpSource.js +17 -4
@@ -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
- await collector.reload();
44
- if (env.COLLECTOR_HEALTH_PORT) { state.health = await runtimeHealth(runtime, { port: Number(env.COLLECTOR_HEALTH_PORT), host: env.COLLECTOR_HEALTH_HOST ?? '127.0.0.1' }); }
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 true;
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
- return { ...supplied, secrets: supplied.secrets ?? { get(name) { return env[name]; } },
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() { return pool ? deadline(() => { return pool.end(); }, 10000) : Promise.resolve(); }
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.state) { await durable(bag, value); }
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
- const sinks = Object.fromEntries(spec.sinks.map((sink, index) => {
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, stopped: false, timeoutMs: spec.writeTimeoutMs ?? 10000,
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 { clickhouseSink } from '../infrastructure/streams/index.js';
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 clickhouseSink(url, 'scada.metrics');
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.run(http);
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 { clickhouseSink } from '../infrastructure/streams/index.js';
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(clickhouseSink(url, 'scada.metrics'), pool, devices);
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,6 +1,7 @@
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';
@@ -131,10 +132,12 @@ export default function supervisorSink(env = process.env, options = {}) {
131
132
  if (cfg.pipeline.transactions.enabled) { cfg.pipeline.onBatch = segmentBatchStats(cfg.pipeline.transactions.statsIntervalMs); }
132
133
  const pool = holdClient(new pg.Pool({ connectionString: cfg.postgres, max: cfg.dbPoolMax }));
133
134
  const metricsEnabled = cfg.sinkDbProfile === 'edge';
134
- const data = stateDataFromPool(pool, { metricsEnabled });
135
+ const data = stateDataFromPool(pool, { metricsEnabled, historyRetentionDays: Number(env.HISTORY_RETENTION_DAYS ?? 30) });
135
136
  const dataAccess = options.stateData ? options.stateData(data, pool) : data;
137
+ const localTelemetry = historyTelemetry(env, pool);
136
138
  return {
137
139
  health: () => {return health.status()},
140
+ historyTelemetry: localTelemetry,
138
141
  apiPort: cfg.apiPort,
139
142
  apiToken: cfg.apiToken,
140
143
  sinkDbProfile: cfg.sinkDbProfile,
@@ -146,6 +149,7 @@ export default function supervisorSink(env = process.env, options = {}) {
146
149
  dataAccess,
147
150
  async run(httpServer) {
148
151
  await prepareDatabase(cfg, pool);
152
+ await localTelemetry?.start();
149
153
  if (cfg.pipelines) {
150
154
  await startPipelines(cfg, pool, health);
151
155
  }
@@ -1,4 +1,4 @@
1
- import { clickhouseSink } from '../../infrastructure/streams/index.js';
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 clickhouseSink(url, 'scada.metrics');
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 });
@@ -0,0 +1,33 @@
1
+ import { errorResponse, jsonResponse, readBody, route } from '@yarkivaev/simple-server';
2
+ import { hasAccess, sendForbidden } from '../../stateAccess.js';
3
+
4
+ function endpoint(method, suffix, token, action) {
5
+ // eslint-disable-next-line max-statements
6
+ return route(method, `/v1/history/${suffix}`, async (req, res, params, query) => {
7
+ if (!hasAccess(req, token)) { sendForbidden(res); return; }
8
+ let input;
9
+ try {
10
+ input = method === 'GET' ? query : JSON.parse(await readBody(req));
11
+ if (typeof input.machine !== 'string' || !input.machine) { throw new TypeError('machine required'); }
12
+ } catch (error) { errorResponse('BAD_REQUEST', error.message, 400).send(res); return; }
13
+ try { jsonResponse(await action(input)).send(res); } catch (error) {
14
+ if (error.statusCode === 409) { errorResponse('CONFLICT', error.message, 409).send(res); return; }
15
+ if (error instanceof TypeError) { errorResponse('BAD_REQUEST', error.message, 400).send(res); return; }
16
+ throw error;
17
+ }
18
+ });
19
+ }
20
+ /** Uses the existing checkpoint API authentication and persistence lifecycle. */
21
+ export default function historyRoutes(token, history) {
22
+ if (!history) { return []; }
23
+ return [
24
+ endpoint('POST', 'config', token, (input) => { return history.configure(input.machine, input.topics, input.bucketMs, input.classifierKey); }),
25
+ endpoint('POST', 'purge', token, () => { return history.purge(); }),
26
+ endpoint('POST', 'observations', token, (input) => { return history.accept(input.machine, input.observations); }),
27
+ endpoint('GET', 'work', token, (input) => { return history.work(input.machine); }),
28
+ endpoint('GET', 'context', token, (input) => {
29
+ return history.context(input.machine, Number(input.from), Number(input.until), input.paddingMs === undefined ? 60000 : Number(input.paddingMs), {classifierKey:input.classifierKey,workId:input.workId,workToken:input.workToken,cursor:input.cursor === undefined ? null : Number(input.cursor),end:input.end === undefined ? null : Number(input.end)});
30
+ }),
31
+ endpoint('POST', 'commit', token, (input) => { return history.commit(input.machine, input.workId, input.segments, input.context); })
32
+ ];
33
+ }
@@ -35,6 +35,9 @@ export function measurementItem(key, sensor, rows) {
35
35
  timestamp: row.timestamp.toISOString(),
36
36
  value: row.value
37
37
  };
38
+ if (typeof row.continuous === 'boolean') {
39
+ point.continuous = row.continuous;
40
+ }
38
41
  if (row.until) {
39
42
  point.until = row.until.toISOString();
40
43
  }
@@ -23,7 +23,12 @@ const privilegedOnly = new Set([
23
23
  'C0007__central_segment_replace_delete.sql',
24
24
  'E0002__edge_retention_delete.sql',
25
25
  'E0003__edge_operations_grants.sql',
26
- 'E0004__edge_operations_delete.sql'
26
+ 'E0004__edge_operations_delete.sql',
27
+ 'E0005__historical_telemetry_grants.sql',
28
+ 'E0008__metric_receipts_grants.sql',
29
+ 'E0012__external_history_grants.sql',
30
+ 'E0014__history_correction_grants.sql',
31
+ 'E0016__history_retention_grants.sql'
27
32
  ]);
28
33
 
29
34
  /**
@@ -0,0 +1,8 @@
1
+ /** Forget a first choice only once both its history window and its raw metric are gone. */
2
+ export default async function retainMetricReceipts(pool, days) {
3
+ const table = await pool.query("SELECT to_regclass('metric_receipts') AS receipts");
4
+ if (!table.rows?.[0]?.receipts) { return; }
5
+ await pool.query(`DELETE FROM metric_receipts r
6
+ WHERE r.ts < NOW() - make_interval(days => greatest($1::integer, COALESCE((SELECT max(retention_days) FROM history_topics),30)))
7
+ AND NOT EXISTS(SELECT 1 FROM metrics m WHERE m.topic=r.topic AND m.ts=r.ts)`, [days]);
8
+ }
@@ -1,3 +1,4 @@
1
+ import retainMetricReceipts from './retainMetricReceipts.js';
1
2
  function intervalFor(days) {
2
3
  return `${days} days`;
3
4
  }
@@ -53,6 +54,7 @@ async function vacuumTables(pool) {
53
54
  */
54
55
  export default async function runRetention(pool, days) {
55
56
  const deleted = await deleteStale(pool, days);
57
+ await retainMetricReceipts(pool, days);
56
58
  await vacuumTables(pool);
57
59
  return { retentionDays: days, deleted };
58
60
  }
@@ -14,7 +14,14 @@
14
14
  * @param {object} [log] - Logger with warn() method
15
15
  * @returns {object} Transformer with accept() method
16
16
  */
17
- export default function metricsCodec(collector, log = console) {
17
+ function validateTimestamp(parsed, options) {
18
+ if (options.requireTimestamp && (!parsed || typeof parsed !== 'object'
19
+ || !Number.isSafeInteger(parsed.ts) || !Number.isFinite(parsed.value))) {
20
+ throw new TypeError('Central telemetry requires original timestamp and finite value');
21
+ }
22
+ }
23
+
24
+ export default function metricsCodec(collector, log = console, options = {}) {
18
25
  if (!collector || typeof collector.accept !== 'function') {
19
26
  throw new Error('Collector must have an accept() method');
20
27
  }
@@ -29,9 +36,11 @@ export default function metricsCodec(collector, log = console) {
29
36
  try {
30
37
  parsed = JSON.parse(raw.payload);
31
38
  } catch {
39
+ if (options.requireTimestamp) { throw new TypeError('Invalid central telemetry JSON'); }
32
40
  log.warn(`Cannot resolve payload on ${raw.topic}: not valid JSON`);
33
41
  return undefined;
34
42
  }
43
+ validateTimestamp(parsed, options);
35
44
  if (typeof parsed === 'number') {
36
45
  return collector.accept({
37
46
  topic: raw.topic,
@@ -42,7 +51,7 @@ export default function metricsCodec(collector, log = console) {
42
51
  if (typeof parsed === 'object' && parsed !== null && typeof parsed.value === 'number') {
43
52
  return collector.accept({
44
53
  topic: raw.topic,
45
- ts: parsed.ts || Date.now(),
54
+ ts: parsed.ts ?? Date.now(),
46
55
  value: parsed.value
47
56
  });
48
57
  }
@@ -175,7 +175,7 @@ function buildSources(devices, config, collector, clk) {
175
175
  export default function modbusMqtt(mqtt, devices, config) {
176
176
  assertModbusMqttArgs(mqtt, devices, config);
177
177
  const clk = clock();
178
- const sink = mqttSink(mqtt, {
178
+ const sink = config.output ?? mqttSink(mqtt, {
179
179
  clientId: config.clientId || 'scada-modbus',
180
180
  qos: 1,
181
181
  onFatal: config.onFatal
@@ -290,6 +290,8 @@ export default function modbusPublish(mqtt, config) {
290
290
  return modbusMqtt(mqtt, specs, {
291
291
  budget: config.budget,
292
292
  onFatal: config.onFatal,
293
+ output: config.output,
294
+ size: config.size,
293
295
  maxRecords: config.maxRecords,
294
296
  maxBytes: config.maxBytes,
295
297
  writeTimeoutMs: config.writeTimeoutMs,
@@ -51,7 +51,7 @@ export default function mqttMetrics(mqtt, sink, topic, config) {
51
51
  // the batch would reject every message at a one-record runtime budget.
52
52
  const { budget, ...batchConfig } = config;
53
53
  const collector = ingestBatch(sink, { ...batchConfig, size: 1 });
54
- const transformer = metricsCodec(collector);
54
+ const transformer = metricsCodec(collector, console, { requireTimestamp: sink.requireTimestamp === true });
55
55
  const source = mqttSource(mqtt, topic, transformer, {
56
56
  budget,
57
57
  onError: config.onError,
@@ -14,13 +14,17 @@ import streamNameFromTopic from './streamNameFromTopic.js';
14
14
  */
15
15
  export function acceptTelemetryDeliver(codec, fields, content, onSeen) {
16
16
  const record = deliverToMqttRecord(fields, content);
17
- if (typeof onSeen === 'function') {
17
+ function seen() {
18
+ if (typeof onSeen !== 'function') { return; }
18
19
  const name = streamNameFromTopic(record.topic);
19
20
  if (name) {
20
21
  onSeen(name);
21
22
  }
22
23
  }
23
- return codec.accept({ topic: record.topic, payload: record.payload.toString() });
24
+ const accepted = codec.accept({ topic: record.topic, payload: record.payload.toString() });
25
+ if (accepted?.then) { return accepted.then((value) => { seen(); return value; }); }
26
+ seen();
27
+ return accepted;
24
28
  }
25
29
 
26
30
  /**
@@ -60,7 +64,7 @@ export default function amqpMetricsIngest(amqpUrl, queue, sink, options = {}) {
60
64
  // A larger batch can never fill and would throttle ingestion to the flush timer.
61
65
  const size = Math.min(options.size ?? 100, prefetch);
62
66
  const collector = ingestBatch(sink, { ...options, size });
63
- const codec = metricsCodec(collector);
67
+ const codec = metricsCodec(collector, console, { requireTimestamp: sink.requireTimestamp === true });
64
68
  const session = amqpSource(amqpUrl, queue, {
65
69
  accept(delivery) {
66
70
  return acceptTelemetryDeliver(codec, delivery.fields, delivery.content, options.onSeen);
@@ -0,0 +1,46 @@
1
+ import { createHash } from 'node:crypto';
2
+ import centralPoint from './centralPoint.js';
3
+ import { CENTRAL_RULE_FIELDS, centralRule } from './centralPolicy.js';
4
+
5
+ export const MAX_BATCH_BYTES = 2097152;
6
+ function digest(value) { return createHash('sha256').update(value).digest('hex'); }
7
+ function address(value, protocols) {
8
+ const url = new URL(value);
9
+ if (!protocols.includes(url.protocol)) { throw new TypeError('Invalid central admission endpoint'); }
10
+ const ports = { 'amqp:': '5672', 'amqps:': '5671', 'http:': '80', 'https:': '443' };
11
+ const path = url.protocol.startsWith('amqp') ? decodeURIComponent(url.pathname.slice(1) || '/') : url.pathname;
12
+ return `${url.protocol}//${url.hostname.toLowerCase()}:${url.port || ports[url.protocol]}/${path}`;
13
+ }
14
+ export function targetIdentity(url) { return digest(address(url, ['http:', 'https:'])); }
15
+ export function admissionDomain(url, queue, target) {
16
+ return digest(`${address(url, ['amqp:', 'amqps:'])}|${queue}|${target}`);
17
+ }
18
+ function keys(value, allowed) {
19
+ if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).some((key) => { return !allowed.includes(key); })) {
20
+ throw new TypeError('Invalid central admission envelope');
21
+ }
22
+ }
23
+ function observation(value) {
24
+ keys(value, ['topic', 'ts', 'value', ...CENTRAL_RULE_FIELDS]);
25
+ if (CENTRAL_RULE_FIELDS.some((key) => { return value[key] === undefined; })) { throw new TypeError('Missing frozen central policy'); }
26
+ const rule = centralRule(Object.fromEntries(CENTRAL_RULE_FIELDS.map((key) => { return [key, value[key]]; })));
27
+ return { ...centralPoint(value), ...rule };
28
+ }
29
+ export function encodeBatch(records, policy, target) {
30
+ if (!Array.isArray(records) || !records.length || records.length > 1000) { throw new TypeError('Invalid central batch length'); }
31
+ const body = JSON.stringify({ version: 4, target, admittedAt: Date.now(), records: records.map((record) => {
32
+ const point = centralPoint(record);
33
+ return { ...point, ...centralRule(policy.forTopic(point.topic)) };
34
+ }) });
35
+ if (Buffer.byteLength(body) > MAX_BATCH_BYTES) { throw new TypeError('Central batch byte capacity exceeded'); }
36
+ return body;
37
+ }
38
+ export function decodeBatch(content, target) {
39
+ if (Buffer.byteLength(content) > MAX_BATCH_BYTES) { throw new TypeError('Central batch byte capacity exceeded'); }
40
+ const batch = JSON.parse(content.toString());
41
+ keys(batch, ['version', 'target', 'admittedAt', 'records']);
42
+ if (batch.version !== 4 || batch.target !== target) { throw new TypeError('Invalid central envelope version or target'); }
43
+ if (!Array.isArray(batch.records) || !batch.records.length || batch.records.length > 1000) { throw new TypeError('Invalid central batch length'); }
44
+ if (!Number.isSafeInteger(batch.admittedAt) || batch.admittedAt < 0) { throw new TypeError('Invalid central admission time'); }
45
+ return { records: batch.records.map(observation), admittedAt: batch.admittedAt, batchId: digest(content) };
46
+ }