@yarkivaev/scada 2.12.2 → 2.14.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.
Files changed (133) hide show
  1. package/README.md +1 -1
  2. package/db/migrations/E0013__history_staged_corrections.sql +1 -1
  3. package/db/migrations/E0017__history_live_covering.sql +1 -1
  4. package/db/migrations/E0025__history_processor_properties.sql +76 -0
  5. package/db/migrations/E0026__history_processor_properties_grants.sql +1 -0
  6. package/index.js +43 -2
  7. package/package.json +3 -2
  8. package/src/application/control/controlClient.js +1 -1
  9. package/src/application/control/createOnlyJSON.js +50 -0
  10. package/src/application/control/index.js +2 -0
  11. package/src/application/control/jsonAssignments.js +30 -0
  12. package/src/application/foldedMetricsSink.js +1 -1
  13. package/src/application/mcp/loadMetricSeries.js +69 -0
  14. package/src/application/mcp/locateMachineMetric.js +25 -0
  15. package/src/application/mcp/metricQueryPorts.js +78 -0
  16. package/src/application/mcp/parseBearerTokens.js +43 -0
  17. package/src/application/runtime/assignment.js +4 -1
  18. package/src/application/runtime/collectorStartup.js +23 -0
  19. package/src/application/runtime/index.js +2 -0
  20. package/src/application/runtime/runCollector.js +46 -9
  21. package/src/application/runtime/runtimeServices.js +20 -2
  22. package/src/application/runtime/spoolHistory.js +12 -12
  23. package/src/application/runtime/spoolSurface.js +2 -2
  24. package/src/application/runtime/spooledOutput.js +27 -0
  25. package/src/application/siteServer.js +2 -2
  26. package/src/application/supervisorSink.js +5 -6
  27. package/src/application/sync/publishingOperations.js +52 -0
  28. package/src/application/sync/siteSync.js +1 -1
  29. package/src/application/sync/siteSyncRows.js +1 -1
  30. package/src/application/sync/siteSyncSites.js +1 -1
  31. package/src/application/telemetry/telemetryBackfill.js +127 -0
  32. package/src/application/timelineOperatorFromEnv.js +1 -1
  33. package/src/domain/ingest/telemetryTimestamp.js +7 -0
  34. package/src/domain/segment/dispatch.js +19 -17
  35. package/src/domain/segment/historyFold.js +2 -1
  36. package/src/domain/segment/intervalFold.js +1 -1
  37. package/src/domain/segment/segmentContinue.js +1 -1
  38. package/src/infrastructure/catalog/tagCatalog.js +7 -11
  39. package/src/infrastructure/deploy/applyWhenChanged.js +15 -0
  40. package/src/infrastructure/deploy/deploymentKube.js +35 -0
  41. package/src/infrastructure/deploy/executeKubeSeed.js +24 -0
  42. package/src/infrastructure/deploy/executeRelease.js +8 -11
  43. package/src/infrastructure/deploy/operatePostgresMaintenance.js +85 -0
  44. package/src/infrastructure/deploy/postgresMaintenancePlan.js +54 -0
  45. package/src/infrastructure/deploy/postgresRestoreObjects.js +73 -0
  46. package/src/infrastructure/deploy/preflightKubeStorage.js +76 -0
  47. package/src/infrastructure/deploy/prepareKubePrerequisites.js +95 -0
  48. package/src/infrastructure/deploy/verifyCollectorCoverage.js +43 -0
  49. package/src/infrastructure/deploy/verifyPeerBrokerPerimeter.js +24 -0
  50. package/src/infrastructure/http/plant/json/decisionJson.js +1 -1
  51. package/src/infrastructure/http/plant/routes/timelineRoute.js +1 -1
  52. package/src/infrastructure/http/plant/timelineOperator.js +2 -2
  53. package/src/infrastructure/ingest/db/migrationProfile.js +2 -1
  54. package/src/infrastructure/ingest/mysql40/byteReader.js +51 -0
  55. package/src/infrastructure/ingest/mysql40/mysql40.js +116 -0
  56. package/src/infrastructure/ingest/mysql40/packets.js +72 -0
  57. package/src/infrastructure/ingest/mysql40/resultRows.js +92 -0
  58. package/src/infrastructure/ingest/mysql40/scramble.js +89 -0
  59. package/src/infrastructure/ingest/pipelines/segmentPipeline.js +38 -14
  60. package/src/infrastructure/ingest/sinks/contiguousPhases.js +1 -1
  61. package/src/infrastructure/ingest/sinks/continuedSegments.js +9 -8
  62. package/src/infrastructure/ingest/sinks/decisionSegment.js +1 -1
  63. package/src/infrastructure/ingest/sinks/foldingSegments.js +16 -10
  64. package/src/infrastructure/ingest/sinks/{foldCastingPhases.js → repairPhaseOverlaps.js} +17 -29
  65. package/src/infrastructure/ingest/sinks/retagSink.js +1 -1
  66. package/src/infrastructure/ingest/sinks/userDecisionSink.js +1 -1
  67. package/src/infrastructure/ingest/telemetry/edgeTelemetryRuntime.js +83 -0
  68. package/src/infrastructure/ingest/telemetry/historyTelemetryMetrics.js +15 -0
  69. package/src/infrastructure/ingest/telemetry/opcuaLocate.js +2 -2
  70. package/src/infrastructure/ingest/telemetry/replayStoredTelemetry.js +125 -0
  71. package/src/infrastructure/ingest/telemetry/telemetryIngest.js +52 -0
  72. package/src/infrastructure/ingest/telemetry/telemetryReplay.js +15 -0
  73. package/src/infrastructure/management/kubeServiceAccount.js +43 -0
  74. package/src/infrastructure/management/kubectlPortForward.js +27 -0
  75. package/src/infrastructure/mdmesh/hmiApplication.js +64 -0
  76. package/src/infrastructure/mdmesh/hmiControl.js +85 -0
  77. package/src/infrastructure/mdmesh/hmiFile.js +69 -0
  78. package/src/infrastructure/mdmesh/hmiMonitor.js +53 -0
  79. package/src/infrastructure/mdmesh/hmiReconcile.js +170 -0
  80. package/src/infrastructure/mdmesh/hmiRuntime.js +33 -0
  81. package/src/infrastructure/mdmesh/index.js +7 -0
  82. package/src/infrastructure/mdmesh/mdmeshClient.js +72 -0
  83. package/src/infrastructure/messaging/ownership/edgeSitesFromEnv.js +137 -0
  84. package/src/infrastructure/messaging/rabbitmq/reconcile.js +71 -12
  85. package/src/infrastructure/messaging/stomp/retagBody.js +1 -1
  86. package/src/infrastructure/messaging/stomp/segmentRetags.js +1 -1
  87. package/src/infrastructure/opcua/health.js +91 -0
  88. package/src/infrastructure/opcua/index.js +1 -0
  89. package/src/infrastructure/persistence/clickhouse/historyObservations.js +149 -0
  90. package/src/infrastructure/persistence/clickhouse/historyRetention.js +94 -0
  91. package/src/infrastructure/persistence/clickhouse/historySourceIdentity.js +34 -0
  92. package/src/infrastructure/persistence/clickhouse/insertMetricRows.js +19 -0
  93. package/src/infrastructure/persistence/clickhouse/jsonMetrics.js +26 -0
  94. package/src/infrastructure/persistence/clickhouse/localHistory.js +51 -0
  95. package/src/infrastructure/persistence/clickhouse/metricsState.js +92 -0
  96. package/src/infrastructure/persistence/clickhouse/rowBinary.js +38 -0
  97. package/src/infrastructure/persistence/clickhouse/telemetryTarget.js +41 -0
  98. package/src/infrastructure/persistence/pg/checkpoints.js +35 -9
  99. package/src/infrastructure/persistence/pg/history.js +74 -56
  100. package/src/infrastructure/persistence/pg/historyContext.js +34 -17
  101. package/src/infrastructure/persistence/pg/historyCorrection.js +5 -2
  102. package/src/infrastructure/persistence/pg/historyFence.js +1 -1
  103. package/src/infrastructure/persistence/pg/historyNativeBounds.js +31 -0
  104. package/src/infrastructure/persistence/pg/historyPurge.js +26 -0
  105. package/src/infrastructure/persistence/pg/historySeed.js +3 -3
  106. package/src/infrastructure/persistence/pg/historySession.js +15 -0
  107. package/src/infrastructure/persistence/pg/intervalFoldPg.js +1 -1
  108. package/src/infrastructure/persistence/pg/prepareRuntimeRole.js +67 -0
  109. package/src/infrastructure/persistence/pg/telemetrySource.js +64 -0
  110. package/src/infrastructure/persistence/postgresPool.js +6 -1
  111. package/src/infrastructure/persistence/runtime/taskStateSqlite.js +37 -0
  112. package/src/infrastructure/persistence/stateDataFromPool.js +16 -2
  113. package/src/infrastructure/replication/canonicalJSON.js +15 -0
  114. package/src/infrastructure/replication/postgresSnapshotReplica.js +129 -0
  115. package/src/infrastructure/replication/postgresSnapshotRuntime.js +40 -0
  116. package/src/infrastructure/replication/snapshotSync.js +61 -0
  117. package/src/infrastructure/replication/tableSnapshotFormat.js +50 -0
  118. package/src/infrastructure/streams/modbusSource.js +1 -1
  119. package/src/infrastructure/streams/stompSend.js +1 -1
  120. package/src/infrastructure/sync/operationAmqp.js +26 -0
  121. package/src/infrastructure/sync/operationEvent.js +10 -0
  122. package/src/infrastructure/tls/mirrorTLSSecret.js +37 -0
  123. package/src/infrastructure/tls/mutualJSON.js +79 -0
  124. package/src/infrastructure/tls/tlsMaterial.js +57 -0
  125. package/stream-processing/src/main/scala/scada/processing/infra/state/AtomicStateFile.scala +7 -0
  126. package/stream-processing/src/main/scala/scada/processing/infra/state/StateJournal.scala +22 -0
  127. package/stream-processing/src/main/scala/scada/processing/runtime/HistoryClient.scala +10 -1
  128. package/stream-processing/src/main/scala/scada/processing/runtime/LiveWorker.scala +70 -0
  129. package/stream-processing/src/main/scala/scada/processing/runtime/LocalHistory.scala +2 -8
  130. package/stream-processing/src/main/scala/scada/processing/runtime/StatefulHistory.scala +108 -0
  131. package/stream-processing/src/main/scala/scada/processing/runtime/TimelinePublication.scala +43 -0
  132. package/stream-processing/src/main/scala/scada/processing/runtime/WorkerStores.scala +43 -0
  133. package/src/infrastructure/catalog/tag-catalog.json +0 -27
package/README.md CHANGED
@@ -18,6 +18,6 @@ For high availability, agents can run collector copies and Stream Worker candida
18
18
 
19
19
  ## Package boundary
20
20
 
21
- SCADA owns the shared collection and processing engines, storage and APIs. Plant packages such as `sokol-scada` supply the deployment DSL, device mappings, business rules, routes and HMI. See the [package boundary](docs/architecture/package-boundary.md).
21
+ SCADA owns the shared collection and processing engines, storage and APIs. Plant applications supply the deployment DSL, device mappings, business rules, routes and HMI. See the [package boundary](docs/architecture/package-boundary.md).
22
22
 
23
23
  [MIT license](LICENSE)
@@ -32,7 +32,7 @@ CREATE OR REPLACE FUNCTION history_apply_correction(p_work UUID,p_machine TEXT,p
32
32
  RETURNS INTEGER LANGUAGE plpgsql AS $$
33
33
  DECLARE w history_work%ROWTYPE; item history_corrections%ROWTYPE; owner history_annotations%ROWTYPE;
34
34
  tail segments%ROWTYPE; lo TIMESTAMPTZ; hi TIMESTAMPTZ; a TIMESTAMPTZ; b TIMESTAMPTZ;
35
- incoming JSONB; inherited JSONB; endpoint_cut BOOLEAN; inserted INTEGER := 0; keys TEXT[] := ARRAY['casting','cadence_rule','cadence_threshold_ms','casting_detected_at','source_interrupted'];
35
+ incoming JSONB; inherited JSONB; endpoint_cut BOOLEAN; inserted INTEGER := 0; keys TEXT[] := ARRAY[]::TEXT[];
36
36
  BEGIN
37
37
  SELECT * INTO STRICT w FROM history_work WHERE id=p_work AND machine=p_machine;
38
38
  IF p_converged THEN
@@ -3,7 +3,7 @@ CREATE OR REPLACE FUNCTION history_apply_correction(p_work UUID,p_machine TEXT,p
3
3
  RETURNS INTEGER LANGUAGE plpgsql AS $$
4
4
  DECLARE w history_work%ROWTYPE; item history_corrections%ROWTYPE; owner history_annotations%ROWTYPE;
5
5
  tail segments%ROWTYPE; lo TIMESTAMPTZ; hi TIMESTAMPTZ; a TIMESTAMPTZ; b TIMESTAMPTZ;
6
- incoming JSONB; inherited JSONB; endpoint_cut BOOLEAN; inserted INTEGER := 0; keys TEXT[] := ARRAY['casting','cadence_rule','cadence_threshold_ms','casting_detected_at','source_interrupted'];
6
+ incoming JSONB; inherited JSONB; endpoint_cut BOOLEAN; inserted INTEGER := 0; keys TEXT[] := ARRAY[]::TEXT[];
7
7
  BEGIN
8
8
  SELECT * INTO STRICT w FROM history_work WHERE id=p_work AND machine=p_machine;
9
9
  IF p_converged THEN
@@ -0,0 +1,76 @@
1
+ -- The caller declares processor-owned fields for each correction transaction.
2
+ -- Keep the four-argument function for clients deployed before this migration.
3
+ CREATE OR REPLACE FUNCTION history_apply_correction(p_work UUID,p_machine TEXT,p_scale INTEGER,p_converged BOOLEAN,p_processor_properties TEXT[])
4
+ RETURNS INTEGER LANGUAGE plpgsql AS $$
5
+ DECLARE w history_work%ROWTYPE; item history_corrections%ROWTYPE; owner history_annotations%ROWTYPE;
6
+ tail segments%ROWTYPE; lo TIMESTAMPTZ; hi TIMESTAMPTZ; a TIMESTAMPTZ; b TIMESTAMPTZ;
7
+ incoming JSONB; inherited JSONB; endpoint_cut BOOLEAN; inserted INTEGER := 0; keys TEXT[] := COALESCE(p_processor_properties, ARRAY[]::TEXT[]);
8
+ BEGIN
9
+ SELECT * INTO STRICT w FROM history_work WHERE id=p_work AND machine=p_machine;
10
+ IF p_converged THEN
11
+ FOR item IN SELECT * FROM history_corrections WHERE work_id=w.id AND generation=w.generation AND duration=0 LOOP
12
+ SELECT * INTO tail FROM segments WHERE machine=p_machine AND kind=item.kind AND name=item.name
13
+ AND start_time<=item.end_time AND end_time>item.end_time ORDER BY end_time DESC LIMIT 1;
14
+ IF FOUND THEN
15
+ UPDATE history_corrections SET end_time=tail.end_time,
16
+ duration=CASE WHEN tail.duration=0 THEN 0 ELSE extract(epoch FROM tail.end_time-item.start_time) END
17
+ WHERE work_id=w.id AND generation=w.generation AND kind=item.kind AND start_time=item.start_time;
18
+ END IF;
19
+ END LOOP;
20
+ END IF;
21
+ lo := 'epoch'::timestamptz+(w.correction_from/p_scale)*interval '1 millisecond';
22
+ hi := 'epoch'::timestamptz+(w.correction_until/p_scale)*interval '1 millisecond';
23
+ SELECT least(lo,COALESCE(min(start_time),lo)),greatest(hi,COALESCE(max(end_time),hi)) INTO lo,hi
24
+ FROM history_corrections WHERE work_id=w.id AND generation=w.generation;
25
+ INSERT INTO history_annotations(machine,kind,start_time,name,end_time,duration,tags,properties,resolved,consumed)
26
+ SELECT machine,kind,start_time,name,end_time,duration,tags,properties,resolved,consumed FROM segments
27
+ WHERE machine=p_machine AND kind='phase' AND start_time<=hi AND end_time>=lo
28
+ ON CONFLICT(machine,kind,start_time,name) DO UPDATE SET end_time=greatest(history_annotations.end_time,EXCLUDED.end_time),
29
+ duration=EXCLUDED.duration,tags=EXCLUDED.tags,properties=EXCLUDED.properties,resolved=EXCLUDED.resolved,consumed=EXCLUDED.consumed;
30
+ UPDATE segments SET end_time=lo,duration=greatest(0,extract(epoch FROM lo-start_time)),updated_at=clock_timestamp()
31
+ WHERE machine=p_machine AND kind='phase' AND start_time<lo AND end_time>lo AND duration>0;
32
+ DELETE FROM segments WHERE machine=p_machine AND kind='phase' AND start_time>=lo
33
+ AND (start_time<hi OR (start_time=hi AND end_time=hi));
34
+ FOR item IN SELECT * FROM history_corrections WHERE work_id=w.id AND generation=w.generation ORDER BY start_time LOOP
35
+ SELECT EXISTS(SELECT 1 FROM history_annotations WHERE machine=p_machine AND kind=item.kind AND name=item.name
36
+ AND start_time=item.end_time AND end_time=item.end_time) INTO endpoint_cut;
37
+ a := item.start_time;
38
+ FOR b IN SELECT cut FROM (
39
+ SELECT start_time AS cut FROM history_annotations WHERE machine=p_machine AND kind=item.kind
40
+ AND start_time>item.start_time AND start_time<item.end_time
41
+ UNION SELECT item.end_time
42
+ ) boundaries ORDER BY cut LOOP
43
+ SELECT * INTO owner FROM history_annotations WHERE machine=p_machine AND kind=item.kind AND name=item.name
44
+ AND start_time<=a AND start_time<=item.end_time AND end_time>=item.start_time ORDER BY start_time DESC LIMIT 1;
45
+ IF NOT FOUND THEN
46
+ SELECT * INTO owner FROM history_annotations WHERE machine=p_machine AND kind=item.kind AND name=item.name
47
+ AND start_time>a AND start_time<=item.end_time AND end_time>=item.start_time ORDER BY start_time LIMIT 1;
48
+ END IF;
49
+ incoming := COALESCE(NULLIF(NULLIF(item.properties,''),'null')::jsonb,'{}'::jsonb);
50
+ inherited := COALESCE(NULLIF(NULLIF(owner.properties,''),'null')::jsonb,'{}'::jsonb);
51
+ IF jsonb_typeof(incoming)<>'object' THEN incoming:='{}'::jsonb; END IF;
52
+ IF jsonb_typeof(inherited)<>'object' THEN inherited:='{}'::jsonb; END IF;
53
+ INSERT INTO segments(machine,kind,name,start_time,end_time,duration,options,tags,properties,resolved,consumed,updated_at)
54
+ VALUES(p_machine,item.kind,item.name,a,b,CASE WHEN item.duration=0 AND b=item.end_time AND NOT endpoint_cut THEN 0 ELSE extract(epoch FROM b-a) END,
55
+ item.options,COALESCE(owner.tags,item.tags),(incoming||(inherited-keys))::text,COALESCE(owner.resolved,item.resolved),COALESCE(owner.consumed,true),clock_timestamp())
56
+ ON CONFLICT(machine,kind,start_time) DO UPDATE SET name=EXCLUDED.name,end_time=EXCLUDED.end_time,duration=EXCLUDED.duration,
57
+ options=EXCLUDED.options,tags=EXCLUDED.tags,properties=EXCLUDED.properties,resolved=EXCLUDED.resolved,consumed=EXCLUDED.consumed,updated_at=EXCLUDED.updated_at;
58
+ inserted:=inserted+1; a:=b;
59
+ END LOOP;
60
+ IF item.start_time<item.end_time AND endpoint_cut THEN
61
+ SELECT * INTO owner FROM history_annotations WHERE machine=p_machine AND kind=item.kind AND name=item.name AND start_time=item.end_time;
62
+ incoming := COALESCE(NULLIF(NULLIF(item.properties,''),'null')::jsonb,'{}'::jsonb);
63
+ inherited := COALESCE(NULLIF(NULLIF(owner.properties,''),'null')::jsonb,'{}'::jsonb);
64
+ IF jsonb_typeof(incoming)<>'object' THEN incoming:='{}'::jsonb; END IF;
65
+ IF jsonb_typeof(inherited)<>'object' THEN inherited:='{}'::jsonb; END IF;
66
+ INSERT INTO segments(machine,kind,name,start_time,end_time,duration,options,tags,properties,resolved,consumed)
67
+ VALUES(p_machine,item.kind,item.name,item.end_time,item.end_time,0,item.options,owner.tags,(incoming||(inherited-keys))::text,owner.resolved,COALESCE(owner.consumed,true))
68
+ ON CONFLICT(machine,kind,start_time) DO NOTHING;
69
+ END IF;
70
+ END LOOP;
71
+ INSERT INTO history_checkpoints(machine,classifier_key,time_ms,state,valid)
72
+ SELECT machine,classifier_key,time_ms,state,true FROM history_staged_checkpoints WHERE work_id=w.id AND generation=w.generation
73
+ ON CONFLICT(machine,classifier_key,time_ms) DO UPDATE SET state=EXCLUDED.state,valid=true;
74
+ RETURN inserted;
75
+ END $$;
76
+ REVOKE ALL ON FUNCTION history_apply_correction(UUID,TEXT,INTEGER,BOOLEAN,TEXT[]) FROM PUBLIC;
@@ -0,0 +1 @@
1
+ GRANT EXECUTE ON FUNCTION history_apply_correction(UUID,TEXT,INTEGER,BOOLEAN,TEXT[]) TO supervisor_sink;
package/index.js CHANGED
@@ -52,7 +52,7 @@ export { default as clickhouseMetricsRelation } from './src/infrastructure/persi
52
52
  export const centralTelemetryVersion = 4;
53
53
  export { default as centralTelemetryPolicy } from './src/infrastructure/ingest/telemetry/centralPolicy.js';
54
54
  export { default as clickhouseSensor } from './src/infrastructure/persistence/clickhouse/sensor.js';
55
- export { default as postgresPool } from './src/infrastructure/persistence/postgresPool.js';
55
+ export { default as postgresPool, holdClient as holdPostgresClient, openPostgresPool } from './src/infrastructure/persistence/postgresPool.js';
56
56
  export { metricsSinkFromPool as pgMetricsSink } from './src/infrastructure/persistence/pg/metrics.js';
57
57
  export { pgMetricsSensor } from './src/infrastructure/persistence/metricsSensor.js';
58
58
  export { default as stompTimeline } from './src/infrastructure/messaging/stomp/timeline.js';
@@ -61,7 +61,7 @@ export { default as machineOwners } from './src/infrastructure/messaging/ownersh
61
61
  export { default as httpTimeline } from './src/infrastructure/messaging/ownership/httpTimeline.js';
62
62
  export { default as httpOperations } from './src/infrastructure/messaging/ownership/httpOperations.js';
63
63
  export { default as ownerTimeline } from './src/infrastructure/messaging/ownership/ownerTimeline.js';
64
- export { default as stateDataFromPool } from './src/infrastructure/persistence/stateDataFromPool.js';
64
+ export { default as stateDataFromPool, withTelemetryState } from './src/infrastructure/persistence/stateDataFromPool.js';
65
65
  export { default as stateDataFromMemory } from './src/infrastructure/persistence/stateDataFromMemory.js';
66
66
  export { default as stateDataFake } from './src/infrastructure/persistence/stateDataFromMemory.js';
67
67
  export { default as supervisorSink, readDeploymentConfig } from './src/application/supervisorSink.js';
@@ -82,6 +82,9 @@ export { default as activityTracking } from './src/infrastructure/ingest/activit
82
82
  export { default as amqpMetricsIngest } from './src/infrastructure/ingest/telemetry/amqpMetricsIngest.js';
83
83
  export { default as amqpMqttRelay } from './src/infrastructure/ingest/telemetry/amqpMqttRelay.js';
84
84
  export { default as operationSyncIngest } from './src/infrastructure/sync/operationSyncIngest.js';
85
+ export { default as operationEvent } from './src/infrastructure/sync/operationEvent.js';
86
+ export { default as operationAmqp } from './src/infrastructure/sync/operationAmqp.js';
87
+ export { default as publishingOperations } from './src/application/sync/publishingOperations.js';
85
88
  export { default as ingestCheckpointMemory, ingestCheckpointPg } from './src/infrastructure/ingest/ingestCheckpoint.js';
86
89
  export { default as bindSilentStreams } from './src/application/bindSilentStreams.js';
87
90
  export { default as exportQuery } from './src/application/export/exportQuery.js';
@@ -114,6 +117,44 @@ export { default as collectorProcesses } from './src/application/deploy/collecto
114
117
  export { default as executeStages } from './src/infrastructure/deploy/executeStages.js';
115
118
 
116
119
  export { default as historyPg, historyProtocol } from './src/infrastructure/persistence/pg/history.js';
120
+ export { default as clickhouseLocalHistory, clickhouseHistoryComment } from './src/infrastructure/persistence/clickhouse/localHistory.js';
117
121
  export { historyReplicaProtocol } from './src/infrastructure/persistence/pg/historyReplicaOutbox.js';
118
122
 
119
123
  export { historyWriteFence } from './src/infrastructure/persistence/pg/segmentWriteFence.js';
124
+ export { default as telemetryBackfill } from './src/application/telemetry/telemetryBackfill.js';
125
+ export { default as telemetryIngest } from './src/infrastructure/ingest/telemetry/telemetryIngest.js';
126
+ export { default as telemetryReplay } from './src/infrastructure/ingest/telemetry/telemetryReplay.js';
127
+ export { default as clickhouseJsonMetrics } from './src/infrastructure/persistence/clickhouse/jsonMetrics.js';
128
+ export { default as postgresTelemetrySource } from './src/infrastructure/persistence/pg/telemetrySource.js';
129
+ export { default as clickhouseTelemetryTarget, assertClickhouseBackfillMode } from './src/infrastructure/persistence/clickhouse/telemetryTarget.js';
130
+ export { default as clickhouseMetricsState } from './src/infrastructure/persistence/clickhouse/metricsState.js';
131
+ export { default as historyTelemetryMetrics } from './src/infrastructure/ingest/telemetry/historyTelemetryMetrics.js';
132
+
133
+ export { default as applyWhenChanged } from './src/infrastructure/deploy/applyWhenChanged.js';
134
+ export { deploymentKube, readKube, verifyKubeNode, preserveKubeRestart } from './src/infrastructure/deploy/deploymentKube.js';
135
+ export { default as preflightKubeStorage } from './src/infrastructure/deploy/preflightKubeStorage.js';
136
+ export { default as postgresMaintenancePlan } from './src/infrastructure/deploy/postgresMaintenancePlan.js';
137
+ export { default as postgresRestoreObjects } from './src/infrastructure/deploy/postgresRestoreObjects.js';
138
+ export { default as operatePostgresMaintenance } from './src/infrastructure/deploy/operatePostgresMaintenance.js';
139
+ export { fetchMutualJSON, readMutualTLS, serveMutualTLS } from './src/infrastructure/tls/mutualJSON.js';
140
+ export { readTLSMaterial, sealTLSMaterial, tlsMaterialLimit, validateTLSMaterial } from './src/infrastructure/tls/tlsMaterial.js';
141
+ export { kubernetesTLSAPI, mirrorTLSSecret } from './src/infrastructure/tls/mirrorTLSSecret.js';
142
+ export { tableSnapshotFormat, tableSnapshotLimit } from './src/infrastructure/replication/tableSnapshotFormat.js';
143
+ export { postgresSnapshotReplica } from './src/infrastructure/replication/postgresSnapshotReplica.js';
144
+ export { snapshotSync } from './src/infrastructure/replication/snapshotSync.js';
145
+ export { default as verifyCollectorCoverage } from './src/infrastructure/deploy/verifyCollectorCoverage.js';
146
+ export { default as verifyPeerBrokerPerimeter } from './src/infrastructure/deploy/verifyPeerBrokerPerimeter.js';
147
+ export { default as mysql40 } from './src/infrastructure/ingest/mysql40/mysql40.js';
148
+ export { default as prepareRuntimeRole } from './src/infrastructure/persistence/pg/prepareRuntimeRole.js';
149
+ export { kubectlPortForward } from './src/infrastructure/management/kubectlPortForward.js';
150
+ export { default as replayStoredTelemetry } from './src/infrastructure/ingest/telemetry/replayStoredTelemetry.js';
151
+ export { followPostgresSnapshot, servePostgresSnapshot } from './src/infrastructure/replication/postgresSnapshotRuntime.js';
152
+ export { default as edgeSitesFromEnv } from './src/infrastructure/messaging/ownership/edgeSitesFromEnv.js';
153
+ export { default as locateMachineMetric } from './src/application/mcp/locateMachineMetric.js';
154
+ export { default as loadMetricSeries } from './src/application/mcp/loadMetricSeries.js';
155
+ export { default as parseBearerTokens } from './src/application/mcp/parseBearerTokens.js';
156
+ export { clickhousePort, cursorPort, postgresPort } from './src/application/mcp/metricQueryPorts.js';
157
+ export { default as prepareKubePrerequisites } from './src/infrastructure/deploy/prepareKubePrerequisites.js';
158
+ export { default as executeKubeSeed } from './src/infrastructure/deploy/executeKubeSeed.js';
159
+ export { default as edgeTelemetryRuntime } from './src/infrastructure/ingest/telemetry/edgeTelemetryRuntime.js';
160
+ export { default as kubeServiceAccount } from './src/infrastructure/management/kubeServiceAccount.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yarkivaev/scada",
3
- "version": "2.12.2",
3
+ "version": "2.14.0",
4
4
  "description": "SCADA domain objects, state persistence, and plant monitoring",
5
5
  "repository": {
6
6
  "type": "git",
@@ -20,7 +20,8 @@
20
20
  "./opcua/config": "./src/infrastructure/opcua/config.js",
21
21
  "./runtime": "./src/application/runtime/index.js",
22
22
  "./streams": "./src/infrastructure/streams/index.js",
23
- "./control": "./src/application/control/index.js"
23
+ "./control": "./src/application/control/index.js",
24
+ "./mdmesh": "./src/infrastructure/mdmesh/index.js"
24
25
  },
25
26
  "bin": {
26
27
  "modbus-to-mqtt": "./src/bin/modbus-to-mqtt.js",
@@ -71,5 +71,5 @@ export function clientFromEnv(env, prefix = 'CONTROL') {
71
71
  for (const [name, key] of [['CA', 'ca'], ['CERT', 'cert'], ['KEY', 'key']]) {
72
72
  if (env[`${prefix}_${name}`]) { tls[key] = readFileSync(env[`${prefix}_${name}`]); }
73
73
  }
74
- return controlClient({ endpoints: (env[`${prefix}_ENDPOINTS`] ?? '').split(',').filter(Boolean), tls, username: env[`${prefix}_USERNAME`], password: env[`${prefix}_PASSWORD`] });
74
+ return controlClient({ endpoints: (env[`${prefix}_ENDPOINTS`] ?? '').split(',').map((endpoint) => { return endpoint.trim(); }).filter(Boolean), tls, username: env[`${prefix}_USERNAME`], password: env[`${prefix}_PASSWORD`] });
75
75
  }
@@ -0,0 +1,50 @@
1
+ function encode(value) {
2
+ return Buffer.from(value).toString('base64');
3
+ }
4
+
5
+ function decode(value) {
6
+ return Buffer.from(value, 'base64').toString('utf8');
7
+ }
8
+
9
+ function rangeEnd(prefix) {
10
+ const bytes = Buffer.from(prefix);
11
+ let index = bytes.length - 1;
12
+ while (index >= 0 && bytes[index] === 255) {
13
+ index -= 1;
14
+ }
15
+ if (index < 0) {
16
+ return encode(Buffer.of(0));
17
+ }
18
+ bytes[index] += 1;
19
+ return encode(bytes.subarray(0, index + 1));
20
+ }
21
+
22
+ /** Stores the first JSON value written for each key under a caller-owned prefix. */
23
+ export default function createOnlyJSON(call, prefix) {
24
+ if (typeof prefix !== 'string' || !prefix) {
25
+ throw new TypeError('A nonempty key prefix is required');
26
+ }
27
+ const end = rangeEnd(prefix);
28
+ return {
29
+ async reserve(id, record) {
30
+ const key = encode(`${prefix}${id}`);
31
+ const body = await call('/v3/kv/txn', {
32
+ compare: [{ key, target: 'VERSION', result: 'EQUAL', version: '0' }],
33
+ success: [{ requestPut: { key, value: encode(JSON.stringify(record)) } }],
34
+ failure: [{ requestRange: { key } }]
35
+ });
36
+ if (body.succeeded === true) {
37
+ return { won: true, record };
38
+ }
39
+ const response = body.responses?.[0];
40
+ const existing = (response?.response_range ?? response?.responseRange)?.kvs?.[0]?.value;
41
+ return { won: false, record: existing ? JSON.parse(decode(existing)) : record };
42
+ },
43
+ async list() {
44
+ const body = await call('/v3/kv/range', { key: encode(prefix), rangeEnd: end });
45
+ return (body.kvs ?? []).map(({ key, value }) => {
46
+ return { id: decode(key).slice(prefix.length), record: JSON.parse(decode(value)) };
47
+ });
48
+ }
49
+ };
50
+ }
@@ -5,3 +5,5 @@ export { default as schedule } from './schedule.js';
5
5
  export { default as assignmentAgent } from './agent.js';
6
6
  export { default as controller, reconcile } from './controller.js';
7
7
  export function publishCatalog(store, catalog, expectedRevision) { return store.publish(catalog, expectedRevision); }
8
+ export { default as createOnlyJSON } from './createOnlyJSON.js';
9
+ export { default as jsonAssignments } from './jsonAssignments.js';
@@ -0,0 +1,30 @@
1
+ function encoded(value) {
2
+ return Buffer.from(value).toString('base64');
3
+ }
4
+
5
+ function put(key, value) {
6
+ return { key: encoded(key), value: encoded(JSON.stringify(value)) };
7
+ }
8
+
9
+ /** Writes independent application records under a caller-owned assignment prefix. */
10
+ export default function jsonAssignments(call, prefix) {
11
+ function key(id) {
12
+ return `${prefix.replace(/\/$/u, '')}/assignments/${id}`;
13
+ }
14
+ return {
15
+ write(id, value) {
16
+ return call('/v3/kv/put', put(key(id), value));
17
+ },
18
+ async compareAndSet(id, revision, value) {
19
+ const path = key(id);
20
+ const version = revision ? { target: 'MOD', 'mod_revision': String(revision) }
21
+ : { target: 'VERSION', version: '0' };
22
+ const result = await call('/v3/kv/txn', {
23
+ compare: [{ key: encoded(path), result: 'EQUAL', ...version }],
24
+ success: [{ 'request_put': put(path, value) }],
25
+ failure: []
26
+ });
27
+ return result?.succeeded === true;
28
+ }
29
+ };
30
+ }
@@ -12,7 +12,7 @@ import opcuaLocate from '../infrastructure/ingest/telemetry/opcuaLocate.js';
12
12
  * @returns {object} sink
13
13
  *
14
14
  * @example
15
- * const sink = foldedMetricsSink(pgMetrics, pool, { 'tlc-cm8': 'cm8' });
15
+ * const sink = foldedMetricsSink(pgMetrics, pool, { 'tlc-line-8': 'line-8' });
16
16
  */
17
17
  export default function foldedMetricsSink(inner, pool, devices) {
18
18
  if (!devices || Object.keys(devices).length === 0) {
@@ -0,0 +1,69 @@
1
+ import locate from './locateMachineMetric.js';
2
+
3
+ /**
4
+ * Reads a sensor series for one measurement mode.
5
+ *
6
+ * @param {object} sensor - plant sensor
7
+ * @param {object} args - from, to, step, mode
8
+ * @returns {Promise<Array>} series rows
9
+ *
10
+ * @example
11
+ * seriesOf(sensor, { from, to, step: 60 });
12
+ */
13
+ function seriesOf(sensor, args) {
14
+ const range = { end: new Date(args.to), start: new Date(args.from) };
15
+ const step = args.step * 1000;
16
+ if (args.mode === 'samples') {
17
+ if (typeof sensor.samples !== 'function') {
18
+ throw Object.assign(new Error('Historical raw density is unavailable: this sensor does not support raw samples'), { code: 'SCADA_HISTORY_DENSITY_UNAVAILABLE', status: 409, statusCode: 409 });
19
+ }
20
+ return sensor.samples(range);
21
+ }
22
+ if (args.mode === 'rises') {
23
+ return sensor.rises(range);
24
+ }
25
+ if (args.mode === 'changes') {
26
+ return sensor.changes(range);
27
+ }
28
+ if (args.mode === 'holds') {
29
+ return sensor.holds(range, step);
30
+ }
31
+ return sensor.measurements(range, step);
32
+ }
33
+
34
+ /**
35
+ * Maps a sensor row to a coverage or measurement point.
36
+ *
37
+ * @param {object} row - sensor sample
38
+ * @returns {object} point with ts
39
+ *
40
+ * @example
41
+ * pointOf({ timestamp: new Date(), value: 1 });
42
+ */
43
+ function pointOf(row) {
44
+ const stamp = row.timestamp instanceof Date ? row.timestamp.toISOString() : row.timestamp;
45
+ const point = { ts: stamp, value: row.value };
46
+ if (typeof row.continuous === 'boolean') { point.continuous = row.continuous; }
47
+ return point;
48
+ }
49
+
50
+ /**
51
+ * Loads points for one namespace path.
52
+ *
53
+ * @param {object} plant - plant hierarchy
54
+ * @param {string} path - namespace path
55
+ * @param {object} args - from, to, step, mode
56
+ * @returns {Promise<Array>} points
57
+ *
58
+ * @example
59
+ * loadSeries(plant, 'site/unit/power', args);
60
+ */
61
+ export default async function loadSeries(plant, path, args) {
62
+ const found = locate(plant, path);
63
+ const sensor = found.metric ? found.machine.sensors[found.metric] : undefined;
64
+ if (!sensor) {
65
+ return [];
66
+ }
67
+ const rows = await seriesOf(sensor, args);
68
+ return rows.map(pointOf);
69
+ }
@@ -0,0 +1,25 @@
1
+ import machineInPlant from '../machineInPlant.js';
2
+
3
+ /**
4
+ * Finds a plant machine from a namespace path or a bare machine id.
5
+ *
6
+ * @param {object} plant - plant hierarchy
7
+ * @param {string} path - namespace path or machine id
8
+ * @returns {object} machine and optional metric key
9
+ *
10
+ * @example
11
+ * locate(plant, 'fixture/site/pump/power').metric;
12
+ */
13
+ export default function locate(plant, path) {
14
+ const parts = path.split('/');
15
+ for (let index = parts.length - 1; index >= 0; index -= 1) {
16
+ const found = machineInPlant(plant, parts[index]);
17
+ if (found) {
18
+ return {
19
+ machine: found.machine,
20
+ metric: index === parts.length - 1 ? '' : parts[parts.length - 1]
21
+ };
22
+ }
23
+ }
24
+ throw new Error(`Namespace machine is missing: ${path}`);
25
+ }
@@ -0,0 +1,78 @@
1
+ import coverageCursor from './coverageCursor.js';
2
+ import locate from './locateMachineMetric.js';
3
+
4
+ /**
5
+ * Wraps a ClickHouse connection as the query_clickhouse port.
6
+ *
7
+ * @param {object} connection - clickhouseConnection
8
+ * @returns {Function} SQL port
9
+ *
10
+ * @example
11
+ * clickhousePort(connection)('SELECT 1');
12
+ */
13
+ export function clickhousePort(connection) {
14
+ return function queryClickhouse(sql) {
15
+ return connection.query(sql);
16
+ };
17
+ }
18
+
19
+ /**
20
+ * Wraps a Postgres pool as the query_postgres port.
21
+ *
22
+ * @param {object} pool - pg pool
23
+ * @returns {Function} SQL port
24
+ *
25
+ * @example
26
+ * postgresPort(pool)('SELECT 1');
27
+ */
28
+ export function postgresPort(pool) {
29
+ return function queryPostgres(sql) {
30
+ return pool.query(sql).then((result) => {
31
+ return result.rows;
32
+ });
33
+ };
34
+ }
35
+
36
+ /**
37
+ * Latest sensor instants for the machine or metric on a path.
38
+ *
39
+ * @param {object} site - plant hierarchy
40
+ * @param {object} args - path
41
+ * @returns {Promise<Array>} samples with ts
42
+ *
43
+ * @example
44
+ * latestSamples(site, { path: 'site/unit/power' });
45
+ */
46
+ async function latestSamples(site, args) {
47
+ const found = locate(site, args.path);
48
+ if (found.metric && found.machine.sensors[found.metric]) {
49
+ const row = await found.machine.sensors[found.metric].current();
50
+ return row.found ? [{ ts: row.timestamp }] : [];
51
+ }
52
+ const keys = Object.keys(found.machine.sensors || {});
53
+ const rows = await Promise.all(keys.map(async (key) => {
54
+ const row = await found.machine.sensors[key].current();
55
+ return row.found ? { ts: row.timestamp } : null;
56
+ }));
57
+ return rows.filter(Boolean);
58
+ }
59
+
60
+ /**
61
+ * Coverage cursor: ingest checkpoint, else latest ClickHouse sample.
62
+ *
63
+ * @param {object|undefined} pool - pg pool
64
+ * @param {object} site - plant hierarchy
65
+ * @returns {Function} cursor port
66
+ *
67
+ * @example
68
+ * cursorPort(pool, site)({ path: 'site/unit' });
69
+ */
70
+ export function cursorPort(pool, site) {
71
+ const bound = coverageCursor(pool, (args) => {
72
+ return latestSamples(site, args);
73
+ });
74
+ return function cursor(args) {
75
+ const found = locate(site, args.path);
76
+ return bound({ machine: found.machine.name(), path: args.path });
77
+ };
78
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Reads a JSON bearer-to-name map when the env value is an object.
3
+ *
4
+ * @param {string} raw - ANALYTICS_MCP_TOKEN value
5
+ * @returns {object|undefined} map or undefined when the value is a single token
6
+ *
7
+ * @example
8
+ * parsedMap('{"secret":"analyst"}').analyst;
9
+ */
10
+ function parsedMap(raw) {
11
+ if (!raw.startsWith('{')) {
12
+ return undefined;
13
+ }
14
+ const parsed = JSON.parse(raw);
15
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
16
+ return parsed;
17
+ }
18
+ return undefined;
19
+ }
20
+
21
+ /**
22
+ * Builds the analyticsMcp bearer map from ANALYTICS_MCP_TOKEN.
23
+ *
24
+ * A JSON object is bearer → caller name. A single token becomes one named
25
+ * caller `agent`.
26
+ *
27
+ * @param {string} raw - environment value
28
+ * @returns {object} token to caller name
29
+ *
30
+ * @example
31
+ * mcpTokens('fixture-token')['fixture-token'];
32
+ */
33
+ export default function mcpTokens(raw) {
34
+ if (typeof raw !== 'string' || raw.length === 0) {
35
+ throw new Error('ANALYTICS_MCP_TOKEN is missing');
36
+ }
37
+ const trimmed = raw.trim();
38
+ const mapped = parsedMap(trimmed);
39
+ if (mapped) {
40
+ return mapped;
41
+ }
42
+ return { [trimmed]: 'agent' };
43
+ }
@@ -7,6 +7,9 @@ function canonical(value) {
7
7
  }
8
8
  return value;
9
9
  }
10
+ export function taskSpecHash(spec) {
11
+ return createHash('sha256').update(JSON.stringify(canonical(spec))).digest('hex');
12
+ }
10
13
  export function identity(input) {
11
14
  if (!input || typeof input.taskId !== 'string' || !/^[\w./:-]{1,200}$/u.test(input.taskId)) {
12
15
  throw new TypeError('Invalid taskId');
@@ -24,7 +27,7 @@ export default function assignment(input, registry) {
24
27
  });
25
28
  const adapter = registry.get(spec.adapter);
26
29
  if (!adapter) { throw new TypeError('Unknown task adapter'); }
27
- const hash = createHash('sha256').update(JSON.stringify(canonical(spec))).digest('hex');
30
+ const hash = taskSpecHash(spec);
28
31
  if (input.specHash && input.specHash !== hash) { throw new TypeError('Invalid specHash'); }
29
32
  return { ...input, spec, specHash: hash, adapter };
30
33
  }
@@ -0,0 +1,23 @@
1
+ import { createServer } from 'node:http';
2
+
3
+ /** Starts only after local recovery. The readiness endpoint tracks individual tasks. */
4
+ export default async function collectorStartup(runtime, { port, host }) {
5
+ const server = createServer((request, response) => {
6
+ if (request.url !== '/startup') { response.writeHead(404).end(); return; }
7
+ const state = runtime.status();
8
+ const ready = !state.fatal && !state.stopping;
9
+ response.writeHead(ready ? 200 : 503, { 'content-type': 'application/json', 'cache-control': 'no-store' });
10
+ response.end(JSON.stringify({ localRecoveryComplete: ready }));
11
+ });
12
+ server.requestTimeout = 2000;
13
+ server.headersTimeout = 2000;
14
+ await new Promise((resolve, reject) => { server.once('error', reject); server.listen(port, host, resolve); });
15
+ let closing;
16
+ return { stop() {
17
+ closing ??= new Promise((resolve, reject) => {
18
+ server.closeAllConnections();
19
+ server.close(error => { if (error) { reject(error); } else { resolve(); } });
20
+ });
21
+ return closing;
22
+ } };
23
+ }
@@ -8,3 +8,5 @@ export { default as taskQueue } from './taskQueue.js';
8
8
  export { default as createRegistry } from './createRegistry.js';
9
9
  export { default as resolveSecrets } from './resolveSecrets.js';
10
10
  export { default as taskStatePg } from '../../infrastructure/persistence/runtime/taskStatePg.js';
11
+ export { default as taskStateSqlite } from '../../infrastructure/persistence/runtime/taskStateSqlite.js';
12
+ export { default as spooledOutput, amqpDestinations } from './spooledOutput.js';