@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
@@ -0,0 +1,66 @@
1
+ import { open, opendir, unlink } from 'node:fs/promises';
2
+ import { constants } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { decoded, digest, encoded, revive } from './spoolCodec.js';
5
+ import { insert } from './spoolRecords.js';
6
+
7
+ async function load(directory, name, limits) {
8
+ const handle = await open(path.join(directory, name), constants.O_RDONLY + constants.O_NOFOLLOW);
9
+ try {
10
+ const info = await handle.stat();
11
+ if (!info.isFile()) { throw new Error('Spool requires regular legacy file'); }
12
+ if (info.size > limits.maxBytes) { throw new Error('Spool capacity exceeded by legacy file'); }
13
+ if (info.size > limits.legacyMigrationMaxBytes) { throw new Error('Legacy migration record capacity exceeded: legacyMigrationMaxBytes'); }
14
+ const buffer = Buffer.alloc(info.size + 1);
15
+ let offset = 0;
16
+ while (offset < buffer.length) {
17
+ // The read itself is bounded even if a noncompliant writer grows the file after stat.
18
+ // eslint-disable-next-line no-await-in-loop
19
+ const { bytesRead } = await handle.read(buffer, offset, buffer.length - offset, null);
20
+ if (!bytesRead) { break; }
21
+ offset += bytesRead;
22
+ }
23
+ if (offset !== info.size) { throw new Error('Corrupt spool legacy file changed while reading'); }
24
+ return buffer.subarray(0, offset).toString('utf8');
25
+ } finally { await handle.close(); }
26
+ }
27
+ function verify(db, value) {
28
+ const row = db.prepare('SELECT * FROM events WHERE id=?').get(value.id);
29
+ if (!row || row.fingerprint !== value.fingerprint || row.remaining !== value.remaining
30
+ || encoded(decoded(row, db).event, JSON.parse(row.recipients), JSON.parse(row.remaining)).fingerprint !== value.fingerprint) {
31
+ throw new Error('Legacy import verification failed');
32
+ }
33
+ }
34
+ /* eslint max-statements: ["error", 20] */
35
+ async function migrateFile(directory, name, db, limits) {
36
+ const text = await load(directory, name, limits);
37
+ const record = JSON.parse(text, revive);
38
+ if (!Array.isArray(record.remaining)) { throw new Error('Corrupt spool receipt state'); }
39
+ const value = encoded(record.event, record.recipients, record.remaining);
40
+ if (`${digest(record.event.eventId)}.json` !== name) { throw new Error('Corrupt spool record filename'); }
41
+ const hash = digest(text);
42
+ db.transaction(() => {
43
+ const imported = db.prepare('SELECT digest FROM imports WHERE name=?').get(name);
44
+ if (imported && imported.digest !== hash) { throw new Error('Conflicting legacy import'); }
45
+ insert(db, value, limits.maxBytes, limits.maxRecords);
46
+ db.prepare('INSERT OR IGNORE INTO imports VALUES (?,?,?)').run(name, hash, value.id);
47
+ })();
48
+ verify(db, value);
49
+ // Verify source unchanged after commit before unlink; owner excludes compliant concurrent writers.
50
+ if (digest(await load(directory, name, limits)) !== hash) { throw new Error('Legacy import source changed'); }
51
+ await unlink(path.join(directory, name));
52
+ const handle = await open(directory, 'r');
53
+ try { await handle.sync(); } finally { await handle.close(); }
54
+ }
55
+ export default async function spoolMigration(directory, db, limits) {
56
+ const files = await opendir(directory);
57
+ for await (const file of files) {
58
+ if (/^[a-f0-9]{64}\.json$/u.test(file.name)) {
59
+ if (!file.isFile()) { throw new Error('Spool requires regular legacy file; symlink refused'); }
60
+ // Bound migration memory independently of legacy directory size.
61
+ await migrateFile(directory, file.name, db, limits);
62
+ }
63
+ }
64
+ // Import ledger is no longer needed once every original is durably removed.
65
+ db.prepare('DELETE FROM imports').run();
66
+ }
@@ -0,0 +1,50 @@
1
+ import { capacity, counters } from './spoolDatabase.js';
2
+ import { decoded, encoded } from './spoolCodec.js';
3
+
4
+ export function insert(db, value, maxBytes, maxRecords) {
5
+ const existing = db.prepare('SELECT fingerprint FROM events WHERE id=?').get(value.id);
6
+ if (existing) {
7
+ if (existing.fingerprint !== value.fingerprint) { throw new Error('Conflicting event identity'); }
8
+ return;
9
+ }
10
+ const totals = counters(db);
11
+ if (totals.records >= maxRecords) { throw new Error('Spool record capacity exceeded'); }
12
+ if (totals.bytes + value.bytes > maxBytes) { throw new Error('Spool capacity exceeded'); }
13
+ for (const descriptor of value.destinations ?? []) {
14
+ db.prepare('INSERT INTO destinations VALUES (?,?,1) ON CONFLICT(id) DO UPDATE SET refs=refs+1').run(descriptor.id, descriptor.json);
15
+ }
16
+ db.prepare('INSERT INTO events VALUES (@id,@fingerprint,@payload,@destinations,@recipients,@remaining,@bytes,@sequence)').run({
17
+ ...value, destinations: value.destinations ? JSON.stringify(value.destinations.map((item) => { return item.id; })) : null,
18
+ sequence: totals.sequence + 1
19
+ });
20
+ db.prepare('UPDATE counters SET bytes=bytes+?,records=records+1,sequence=sequence+1 WHERE id=1').run(value.bytes);
21
+ }
22
+ function remove(db, row) {
23
+ db.prepare('DELETE FROM events WHERE id=?').run(row.id);
24
+ db.prepare('UPDATE counters SET bytes=bytes-?,records=records-1 WHERE id=1').run(row.bytes);
25
+ for (const id of JSON.parse(row.destinations ?? '[]')) {
26
+ db.prepare('UPDATE destinations SET refs=refs-1 WHERE id=?').run(id);
27
+ db.prepare('DELETE FROM destinations WHERE id=? AND refs=0').run(id);
28
+ }
29
+ }
30
+ export function acknowledge(db, id, recipient) {
31
+ const row = db.prepare('SELECT * FROM events WHERE id=?').get(id);
32
+ if (!row) { return; }
33
+ if (!JSON.parse(row.recipients).includes(recipient)) { throw new Error('Unknown recipient'); }
34
+ const remaining = JSON.parse(row.remaining).filter((item) => { return item !== recipient; });
35
+ if (!remaining.length) { remove(db, row); return; }
36
+ const record = decoded(row, db);
37
+ const value = encoded(record.event, JSON.parse(row.recipients), remaining);
38
+ db.prepare('UPDATE events SET remaining=?,bytes=? WHERE id=?').run(value.remaining, value.bytes, id);
39
+ db.prepare('UPDATE counters SET bytes=bytes+? WHERE id=1').run(value.bytes - row.bytes);
40
+ }
41
+ export function pending(db, limit) {
42
+ const rows = db.prepare('SELECT * FROM events ORDER BY sequence LIMIT ?').all(limit);
43
+ let { sequence } = counters(db);
44
+ for (const row of rows) {
45
+ sequence += 1; db.prepare('UPDATE events SET sequence=? WHERE id=?').run(sequence, row.id);
46
+ }
47
+ db.prepare('UPDATE counters SET sequence=? WHERE id=1').run(sequence);
48
+ return rows.map((row) => { return decoded(row, db); });
49
+ }
50
+ export function admission(db, maxBytes, maxRecords) { return capacity(db, maxBytes, maxRecords); }
@@ -1,3 +1,4 @@
1
+ import historyPg from './pg/history.js';
1
2
  import alertsStatePg from './pg/alerts.js';
2
3
  import checkpointStatePg from './pg/checkpoints.js';
3
4
  import metricsStateDisabled from './memory/metricsDisabled.js';
@@ -12,6 +13,7 @@ export default function stateDataFromPool(pool, options = {}) {
12
13
  segments: segmentStatePg(pool),
13
14
  alerts: alertsStatePg(pool),
14
15
  metrics,
16
+ history: metricsEnabled ? historyPg(pool, { retentionDays: options.historyRetentionDays ?? 30 }) : undefined,
15
17
  checkpoints: checkpointStatePg(pool, metricsEnabled),
16
18
  operations: operationStatePg(pool)
17
19
  };
@@ -53,6 +53,12 @@ async function configure(state, live) {
53
53
  await Promise.all((state.options.exchanges || []).map((item) => {
54
54
  return live.channel.assertExchange(item.name, item.type || 'topic', item.options || {durable: true});
55
55
  }));
56
+ await Promise.all((state.options.queues || []).map((item) => {
57
+ return live.channel.assertQueue(item.name, item.options || { durable: true, autoDelete: false });
58
+ }));
59
+ await Promise.all((state.options.bindings || []).map((item) => {
60
+ return live.channel.bindQueue(item.queue, item.exchange, item.pattern, item.args);
61
+ }));
56
62
  }
57
63
  async function current(state, live) {
58
64
  if (live.epoch !== state.epoch || !state.wanted) {
@@ -1,3 +1,4 @@
1
+ /* eslint-disable no-await-in-loop */
1
2
  import amqpSession from './amqpSource/session.js';
2
3
  import budgetAccept from './budgetAccept.js';
3
4
 
@@ -14,6 +15,7 @@ function deliveryFor(channel, message, options) {
14
15
  let settled = false;
15
16
  return {
16
17
  content: message.content, fields: message.fields, properties: message.properties,
18
+ active() {return !settled && options.active();},
17
19
  ack() {
18
20
  if (!settled && options.active()) { channel.ack(message); settled = true; }
19
21
  },
@@ -48,6 +50,16 @@ function consume(channel, collector, options) {
48
50
  }
49
51
  };
50
52
  }
53
+ async function rejectCapacity(channel,message,options) {
54
+ reportFailure(options,new Error(options.preserveOnCapacity ? 'AMQP payload capacity exceeded; retained for retry' : 'AMQP payload capacity exceeded; rejected without requeue'));
55
+ if (options.preserveOnCapacity) {
56
+ // Never NACK a canonical head into the ready queue behind later data.
57
+ while(options.active()) {await new Promise((resolve) => {setTimeout(resolve,250);});}
58
+ return;
59
+ }
60
+ try {channel.nack(message,false,false);}
61
+ catch(error) {reportFailure(options,error);}
62
+ }
51
63
  function trackedConsume(channel, collector, options, pending) {
52
64
  const accept = consume(channel, collector, options);
53
65
  const state = { bytes: 0 };
@@ -55,9 +67,7 @@ function trackedConsume(channel, collector, options, pending) {
55
67
  if (!options.active()) { return Promise.resolve(); }
56
68
  const bytes = message?.content?.length ?? 0;
57
69
  if (bytes > options.maxMessageBytes || state.bytes + bytes > options.maxPendingBytes) {
58
- try { channel.nack(message, false, false); } catch (error) { reportFailure(options, error); }
59
- reportFailure(options, new Error('AMQP payload capacity exceeded; rejected without requeue'));
60
- return Promise.resolve();
70
+ return rejectCapacity(channel,message,options);
61
71
  }
62
72
  state.bytes += bytes;
63
73
  const delivery = accept(message);
@@ -86,8 +96,11 @@ export default function amqpSource(url, queue, collector, options = {}) {
86
96
  const state = {};
87
97
  const session = amqpSession(url, async (channel) => {
88
98
  const generation = state.session.generation();
99
+ const live = {closed:false};
100
+ channel.on('close',() => {live.closed=true;});
101
+ channel.on('error',() => {live.closed=true;});
89
102
  const config = { ...settings, active() {
90
- return state.session.active() && state.session.generation() === generation;
103
+ return !live.closed && state.session.active() && state.session.generation() === generation;
91
104
  } };
92
105
  const name = await topology(channel, queue, settings);
93
106
  const result = await channel.consume(name, trackedConsume(channel, collector, config, pending), { noAck: false, ...(settings.exclusive ? { exclusive: true } : {}) });