@yarkivaev/scada 2.6.40 → 2.6.41

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 (79) hide show
  1. package/README.md +13 -768
  2. package/package.json +3 -1
  3. package/src/infrastructure/streams/README.md +12 -5
  4. package/supervisor-engine/src/main/scala/scada/supervisor/core/Condition.scala +33 -0
  5. package/supervisor-engine/src/main/scala/scada/supervisor/core/CyclePhases.scala +65 -0
  6. package/supervisor-engine/src/main/scala/scada/supervisor/core/Decision.scala +67 -0
  7. package/supervisor-engine/src/main/scala/scada/supervisor/core/Emission.scala +19 -0
  8. package/supervisor-engine/src/main/scala/scada/supervisor/core/MachineConfig.scala +21 -0
  9. package/supervisor-engine/src/main/scala/scada/supervisor/core/MachineId.scala +18 -0
  10. package/supervisor-engine/src/main/scala/scada/supervisor/core/MachineMode.scala +4 -0
  11. package/supervisor-engine/src/main/scala/scada/supervisor/core/Params.scala +15 -0
  12. package/supervisor-engine/src/main/scala/scada/supervisor/core/Reading.scala +11 -0
  13. package/supervisor-engine/src/main/scala/scada/supervisor/core/Segment.scala +28 -0
  14. package/supervisor-engine/src/main/scala/scada/supervisor/core/SegmentDef.scala +14 -0
  15. package/supervisor-engine/src/main/scala/scada/supervisor/core/Segmentation.scala +137 -0
  16. package/supervisor-engine/src/main/scala/scada/supervisor/core/Segments.scala +41 -0
  17. package/supervisor-engine/src/main/scala/scada/supervisor/core/SplitFollow.scala +50 -0
  18. package/supervisor-engine/src/main/scala/scada/supervisor/core/SplitPieces.scala +102 -0
  19. package/supervisor-engine/src/main/scala/scada/supervisor/core/Supervisor.scala +66 -0
  20. package/supervisor-engine/src/main/scala/scada/supervisor/core/TagDef.scala +12 -0
  21. package/supervisor-engine/src/main/scala/scada/supervisor/core/TaggedSegment.scala +19 -0
  22. package/supervisor-engine/src/main/scala/scada/supervisor/core/Tagging.scala +42 -0
  23. package/supervisor-engine/src/main/scala/scada/supervisor/core/Timestamp.scala +26 -0
  24. package/supervisor-engine/src/main/scala/scada/supervisor/infra/checkpoint/Checkpoint.scala +61 -0
  25. package/supervisor-engine/src/main/scala/scada/supervisor/infra/checkpoint/ClickhouseReadingsCheckpoint.scala +76 -0
  26. package/supervisor-engine/src/main/scala/scada/supervisor/infra/checkpoint/SupervisorSinkCheckpoint.scala +141 -0
  27. package/supervisor-engine/src/main/scala/scada/supervisor/infra/config/AppConfig.scala +132 -0
  28. package/supervisor-engine/src/main/scala/scada/supervisor/infra/config/ConfigLoad.scala +202 -0
  29. package/supervisor-engine/src/main/scala/scada/supervisor/infra/config/ConfigProfile.scala +13 -0
  30. package/supervisor-engine/src/main/scala/scada/supervisor/infra/mqtt/Mqtt.scala +92 -0
  31. package/supervisor-engine/src/main/scala/scada/supervisor/infra/mqtt/Sessions.scala +18 -0
  32. package/supervisor-engine/src/main/scala/scada/supervisor/infra/state/AtomicStateFile.scala +24 -0
  33. package/supervisor-engine/src/main/scala/scada/supervisor/infra/state/CheckpointSegments.scala +59 -0
  34. package/supervisor-engine/src/main/scala/scada/supervisor/infra/state/SegmentStatePolicy.scala +18 -0
  35. package/supervisor-engine/src/main/scala/scada/supervisor/infra/state/Segments.scala +91 -0
  36. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/ClassifyQueue.scala +37 -0
  37. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/DecisionMessage.scala +49 -0
  38. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/DurableStomp.scala +27 -0
  39. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/SegmentMessage.scala +57 -0
  40. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/SegmentWirePolicy.scala +18 -0
  41. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/SplitFamily.scala +39 -0
  42. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompConnection.scala +106 -0
  43. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompDecisions.scala +43 -0
  44. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompFrame.scala +67 -0
  45. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompMachineDecisions.scala +16 -0
  46. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompQueue.scala +30 -0
  47. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompReadings.scala +29 -0
  48. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompSegments.scala +115 -0
  49. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ClassifierCursors.scala +58 -0
  50. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ClassifyHistory.scala +92 -0
  51. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ClassifyStreams.scala +67 -0
  52. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/Close.scala +23 -0
  53. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/EngineApp.scala +4 -0
  54. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/HealthServer.scala +38 -0
  55. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/HistoryBus.scala +67 -0
  56. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/HistoryClient.scala +23 -0
  57. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/HistoryRun.scala +86 -0
  58. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/LocalHistory.scala +256 -0
  59. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ObservationLead.scala +26 -0
  60. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/Orphans.scala +26 -0
  61. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/PendingIsland.scala +37 -0
  62. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/RuntimeProfile.scala +32 -0
  63. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/Seeding.scala +105 -0
  64. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/SupervisorRuntime.scala +266 -0
  65. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/WriterEpoch.scala +16 -0
  66. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/WriterGate.scala +35 -0
  67. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/WriterLease.scala +218 -0
  68. package/supervisor-engine/vendor/gaps-and-islands/LICENSE +21 -0
  69. package/supervisor-engine/vendor/gaps-and-islands/UPSTREAM +4 -0
  70. package/supervisor-engine/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/Island.scala +40 -0
  71. package/supervisor-engine/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandEvent.scala +55 -0
  72. package/supervisor-engine/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandsFlow.scala +127 -0
  73. package/supervisor-engine/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandsPolicy.scala +105 -0
  74. package/supervisor-engine/vendor/temporal-streams/LICENSE +21 -0
  75. package/supervisor-engine/vendor/temporal-streams/UPSTREAM +3 -0
  76. package/supervisor-engine/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/History.scala +30 -0
  77. package/supervisor-engine/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/LocalStreams.scala +27 -0
  78. package/supervisor-engine/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/Overlay.scala +15 -0
  79. package/supervisor-engine/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/Worker.scala +21 -0
package/README.md CHANGED
@@ -1,778 +1,23 @@
1
- # scada
1
+ # SCADA
2
2
 
3
- Generic industrial monitoring domain, state persistence, and HTTP APIs (`@yarkivaev/scada`).
3
+ `@yarkivaev/scada` provides the collector runtime, Scala Supervisor engine, state sink and plant API for industrial monitoring.
4
4
 
5
- This package is plant-agnostic: it defines `plant` → `shop` → `machine` hierarchy, timeline and alerts, sensor read ports, STOMP ingest pipelines, and PostgreSQL/ClickHouse adapters. Plant-specific routes, sensors, HMI strings, and tag taxonomies live in downstream plant packages.
5
+ - [Quick-start guide](docs/quick-start.md) — install the package and run a local API.
6
+ - [Documentation](docs/README.md) — installation, architecture, collection, operations and reference.
6
7
 
7
- `analyticsMcp` is a stateless Streamable HTTP MCP server. The plant package supplies a `namespaceTree` (path, kind, silence, source topic), read ports, and the tag catalog already used by `plantApi({ tagCatalog })`. Tools address nodes by path. `query_postgres` is registered only when a standby query port is supplied. Each SQL engine runs one query at a time. Each call writes one JSON line to the injected journal. `GET /metrics` exposes call counts and in-flight reads.
8
+ ## Architecture
8
9
 
9
- Resources: `plant://topology`, `plant://bindings`, `plant://tags`, `plant://schema/postgres`, `plant://schema/clickhouse`. Column lists live in the schema resources, not here.
10
+ ![A collector publishes readings to RabbitMQ. Supervisor classifies the readings into segments, the state sink writes to PostgreSQL, and the site exposes the plant API.](docs/architecture/diagrams/single-edge-site.svg)
10
11
 
11
- ```javascript
12
- import { analyticsMcp, namespaceTree, tagCatalog } from '@yarkivaev/scada';
12
+ - **Collect near the equipment.** `scada-collector` runs device and stream adapters and delivers readings to their configured destinations.
13
+ - **Process readings with plant rules.** [Supervisor](supervisor-engine/README.md) turns telemetry into timeline segments. The [state sink](docs/architecture/README.md#state-sink) persists segments, decisions and alerts, and the site API serves them to clients.
14
+ - **Keep plant state local.** An edge site can store its metrics and state in PostgreSQL. A central site can archive selected metrics from multiple edge sites in ClickHouse.
15
+ - **Manage placement separately.** Agents can run from local manifests. An optional `scada-controller` assigns work through etcd, and agents can continue running saved assignments during a control-plane outage.
13
16
 
14
- const mcp = analyticsMcp({
15
- tree: namespaceTree(nodes),
16
- catalog: tagCatalog(),
17
- tokens: { secret: 'analyst' },
18
- journal(line) { process.stdout.write(line); },
19
- ports: {
20
- measurements, segments, operations, alerts, state, samples, cursor, queryClickhouse
21
- },
22
- extend(server) { /* plant tools, resources, prompts */ }
23
- });
24
- await mcp.listen(0, '127.0.0.1');
25
- ```
26
-
27
- `ports.queryPostgres` registers `query_postgres`. `extend(server)` may add plant tools. `POST /mcp` requires `Authorization: Bearer`. Coverage spans add the overlapping timeline segment name as `phase`. The process journal is stdout only; `activityTracking` still writes Loki HTTP access into `activity.http_access`, not `activity.mcp_calls`.
28
-
29
- Repository: `https://github.com/yarkivaev/scada`
30
-
31
- ## Install
32
-
33
- ```bash
34
- npm install @yarkivaev/scada
35
- ```
36
-
37
- Node.js 22+, ES modules.
38
-
39
- ## Quick start
40
-
41
- ```javascript
42
- import { plantApi, metricsPlant, clickhouseConnection } from '@yarkivaev/scada';
43
-
44
- const p = await metricsPlant(
45
- [{ device: 'device-1', machine: 'm1' }],
46
- {
47
- connection: () => clickhouseConnection(process.env.CLICKHOUSE_HOST),
48
- buildSensors: (conn, entry) => ({ /* sensor factories */ }),
49
- shopFactory: (entries, ctx) => { /* return shop */ }
50
- }
51
- );
52
-
53
- const api = plantApi('/api/v1', p);
54
- ```
55
-
56
- For a full deployable process, use `siteServer` or the `supervisor-sink` binary (see below). Plant packages wrap these with site-specific routes and sensors.
57
-
58
- ## Layout
59
-
60
- ```
61
- scada/
62
- src/
63
- domain/ business objects and ingest policies (no I/O)
64
- application/ composition roots (plantApi, supervisorSink, siteServer)
65
- infrastructure/ adapters (http, persistence, messaging, ingest, client)
66
- bin/ process entry points
67
- test/ mirrors src/ (domain/, infrastructure/, helpers/)
68
- db/migrations/ PostgreSQL schema (profile-specific prefixes)
69
- index.js public API facade
70
- ```
71
-
72
- ## Three layers
73
-
74
- | Layer | Role | Examples |
75
- |-------|------|----------|
76
- | **domain/** | Pure business logic, no imports from infrastructure | `plant`, `shop`, `machine`, `timeline`, `alerts`, `segment/dispatch` |
77
- | **application/** | Wires domain + infrastructure into runnable units | `plantApi`, `metricsPlant`, `supervisorSink`, `siteServer` |
78
- | **infrastructure/** | I/O adapters behind narrow ports | `persistence/pg`, `http/plant`, `http/edge`, `messaging/stomp`, `ingest` |
79
-
80
- Dependency rules:
81
-
82
- - `domain/` imports `domain/` only
83
- - `application/` composes `domain/` + `infrastructure/`
84
- - HTTP routes receive injected `plant` objects; storage backends are swappable behind the same port shape
85
-
86
- ## Data flow
87
-
88
- **Central plant API** (read path):
89
-
90
- ```
91
- ClickHouse ← mqttMetrics / amqpMetricsIngest
92
- PostgreSQL ← STOMP alerts (via plantServer)
93
- plantApi → REST + SSE → frontend / @yarkivaev/scada/client
94
- ```
95
-
96
- `GET /api/v1/topology` returns `{ plant, nodes, links }` from `plant.topology()` or a shop/machine/sensor walk, then paints `status` from live `sensor.current()` freshness (`ok` / `degraded` / `down`). Nodes without a matching sensor stay `unknown`. `GET /infra` serves a generic SVG of that graph. Optional node `inspect: { host, port }` is reached same-origin at `/infra/inspect/:id` (CDP `Host` is loopback).
97
-
98
- **Supervisor-sink** (write path):
99
-
100
- ```
101
- STOMP (`/queue/scada.segments.ingest`, `/exchange/scada.alerts`, `/exchange/scada.user_decisions`)
102
- → ingest/codecs → domain/segment → ingest/sinks → PostgreSQL
103
- edgeApi (:8081) ← metrics batch, checkpoints, retention (edge profile)
104
- ```
105
-
106
- **Edge site** (`siteServer`): runs supervisor-sink HTTP, plant API, and optional MQTT ingest in one process. Metrics land in PostgreSQL on edge; on central they go to ClickHouse.
107
-
108
- ## Split family
109
-
110
- One `off` phase can be replaced by contiguous pieces. There is no parent row and no nested segment. Each piece is a normal `segments` row: `kind = phase`, `name = off`, at most one tag. An empty tag is SQL NULL. The family key is `properties.split_of`, the original start in epoch milliseconds. The first piece keeps that `start_time`, so the existing unique key `(machine, kind, start_time)` still identifies it.
111
-
112
- A later edit sends the whole family again. `timeline.respond` / `PATCH /segments` take `{ splits: [{ start, end, tag, open }] }` addressed by the original start. The supervisor publishes one STOMP body, `type: split-family`, with `origin` in epoch millis and the pieces. The sink deletes family starts the new cut does not use, then upserts the pieces, in one transaction.
113
-
114
- The replacement must keep the original start and, for a closed off, the latest end of the stored family. Removing every piece but one therefore restores those bounds. `splits: []` is refused before any delete, and the stored family stays. A piece may be any positive length. Only the tail of a still-open off may have `duration = 0`. A duration-0 heartbeat does not extend a closed piece that already has `split_of`.
115
-
116
- `C0007` grants `DELETE` on `segments` to `supervisor_sink` on the privileged admin path. The sink role does not run that grant itself. Central previously revoked this privilege (`C0002`).
117
-
118
- ## Public exports
119
-
120
- Main entry (`import { … } from '@yarkivaev/scada'`):
121
-
122
- | Export | Purpose |
123
- |--------|---------|
124
- | `plant`, `shop`, `machine` | Domain hierarchy |
125
- | `timeline`, `alerts`, `alert`, `acknowledgedAlert` | Timeline and alerting |
126
- | `plantApi`, `plantServer`, `siteServer`, `topologyFromPlant`, `topologyHealth` | HTTP composition and topology graph |
127
-
128
- | `exportQuery`, `exportStream`, `exportSink`, `exportJob` | Generic export ports over plantApi / `@yarkivaev/scada/client` |
129
- | `siteSync`, `siteSyncSites`, `siteSyncBind` | Pull kinds from an allowlisted remote plantApi into local persistence |
130
- | `metricsPlant`, `shopWithTimeline`, `machineInPlant` | Plant wiring helpers |
131
- | `supervisorSink`, `readDeploymentConfig` | STOMP ingest + PG persistence |
132
- | `edgeApi`, `stateHttpClient`, `metricsSensor` | Edge HTTP read/write |
133
- | `clickhouseConnection`, `clickhouseSensor`, `pgMetricsSensor` | Metric storage |
134
- | `pgTimeline`, `pgAlerts`, `stateDataFromPool`, `stateDataFromMemory` | State ports |
135
- | `stompTimeline`, `stompAlerts`, `userDecisions` | STOMP messaging |
136
- | `machineOwners`, `ownerTimeline`, `httpTimeline`, `httpOperations` | Owner-routed timeline and operations write (local or edge HTTP) |
137
- | `mqttMetrics`, `modbusMqtt`, `modbusPublish`, `activityTracking`, `amqpMetricsIngest` | Ingest pipelines |
138
- | `analyticsMcp`, `namespaceTree`, `coverageSpans`, `coverageOverlay`, `coverageCursor`, `sqlGuard` | Analytics MCP, path index, coverage spans, timeline-name overlay, checkpoint-or-sample cursor, read-only SQL guard |
139
-
140
- Subpath exports:
141
-
142
- - `@yarkivaev/scada/client` — browser/Node HTTP+SSE client (`scadaClient`, `machineClient`) plus re-exported export ports
143
- - `@yarkivaev/scada/stateDataFake` — in-memory state backends for tests
144
- - `@yarkivaev/scada/startTestEdgeApi` — ephemeral edge API for integration tests
145
-
146
- ## Export ports
147
-
148
- Generic read/stream/write contract for outbound jobs. Read side uses existing `plantApi` / `@yarkivaev/scada/client` only (no direct DB). Destination adapters and plant maps live in plant packages, not here. Do not put export into `edgeApi`.
149
-
150
- ```javascript
151
- import { exportQuery, exportStream, exportSink, exportJob } from '@yarkivaev/scada';
152
- import { scadaClient } from '@yarkivaev/scada/client';
153
-
154
- const client = scadaClient(baseUrl, fetch, EventSource);
155
- const query = exportQuery(client);
156
- const stream = exportStream(client);
157
- const sink = exportSink({
158
- write(records) { return destination.write(records); },
159
- send(artifact) { return destination.send(artifact); }
160
- });
161
- const job = exportJob({ query, transform: (rows) => rows, sink });
162
- await job.run({ kind: 'segments', machine: 'furnace-α', from, to });
163
- ```
164
-
165
- `POST /api/v1/sync` on any `siteServer` pulls `segments` / `operations` / `measurements` / `alerts` from `SYNC_SITES` / `EDGE_SITES` / `CENTRAL_PLANT_URL`. Body: `{ site, from, to, machines?, kinds? }`. Optional `SYNC_TOKEN`. Does not republish to RabbitMQ.
166
-
167
- ```javascript
168
- import { siteSync } from '@yarkivaev/scada';
169
-
170
- await siteSync({ sites, queryFor, targets }).run({
171
- site: 'edge-icht-1',
172
- from,
173
- to,
174
- kinds: ['segments']
175
- });
176
- ```
177
-
178
- Downstream plant packages should pin a released tag (e.g. `#v2.3.46`).
179
-
180
- Alert and HMI copy are inject-only: pass `translations` into `siteServer` / `plantServer` / `alertPipeline` config, and override `TAG_CATALOG_PATH` or `plantApi({ tagCatalog })` for site taxonomy. Defaults ship empty or English stubs.
181
-
182
- ## Binaries
183
-
184
- | Binary | Role |
185
- |--------|------|
186
- | `supervisor-sink` | STOMP → PostgreSQL ingest + edge HTTP API (`STATE_HTTP_PORT`, default 8081) |
187
- | `modbus-to-mqtt` | Poll Modbus and publish `STREAM` + `MAPPING` document paths (`src/bin/modbus-to-mqtt.js`) |
188
-
189
- Full plant API with site-specific routes: plant packages call `siteServer` from this package.
190
-
191
- ## Sensor port
192
-
193
- All sensor implementations expose the same interface:
194
-
195
- ```javascript
196
- { name(), current(), measurements(range, step), stream(since, step, callback, clock?) }
197
- ```
198
-
199
- Implementations: `clickhouseSensor` (central; live `stream()` batches many topics into one ClickHouse query per tick), `pgMetricsSensor` / `metricsSensor` (edge HTTP or PG).
200
-
201
- ## Database migrations
202
-
203
- SQL files in `db/migrations/` use profile prefixes:
204
-
205
- | Prefix | Applies to |
206
- |--------|------------|
207
- | `V*` | Both central and edge |
208
- | `E*` | Edge only (metrics tables, retention) |
209
- | `C*` | Central only (central privileges, including segment DELETE) |
210
-
211
- Set `SINK_DB_PROFILE=central|edge`. By default, migrations run at supervisor-sink
212
- startup via `POSTGRES_ADMIN_URL` (`SUPERVISOR_MIGRATIONS=apply`).
213
-
214
- After a separate administrative bootstrap has applied the image's complete
215
- migration set, set `SUPERVISOR_MIGRATIONS=verify` and remove `POSTGRES_ADMIN_URL`
216
- from the runtime container. Startup then uses only `POSTGRES_URL` to SELECT the
217
- recorded versions in `public.schema_migrations`. It checks shared and selected
218
- profile migrations, including privileged migrations, before starting consumers or
219
- HTTP. An absent/inaccessible registry or any missing migration stops startup;
220
- it never creates the registry or falls back to administrative credentials.
221
- Collector task-state migration remains separately opt-in, as in apply mode.
222
- This verifies migration records, not schema checksums or effective DML privileges.
223
-
224
- The restricted runtime role needs database CONNECT, public schema USAGE,
225
- `GRANT SELECT ON public.schema_migrations TO <runtime_role>`, and the DML/sequence
226
- grants required by its enabled pipelines and APIs. It needs no schema CREATE,
227
- registry INSERT, table ownership or elevated role attributes for verification.
228
- Do not mount an administrative Secret into verify-mode runtime containers.
229
- Complete each image's bootstrap and role grants before switching it; retain the
230
- administrative identity only in the separate migration job. Use the exact main
231
- commit whose mandatory checks passed before releasing a new image.
232
-
233
- For chart-managed PostgreSQL, select this boundary with:
234
-
235
- ```yaml
236
- postgres:
237
- migrationsMode: verify
238
- secret: postgres-bootstrap
239
- runtimeSecret: postgres-runtime
240
- ```
241
-
242
- `runtimeSecret` must differ from the bootstrap Secret and contain the restricted
243
- connection string under `url`. The chart injects it as POSTGRES_URL, sets
244
- SUPERVISOR_MIGRATIONS=verify, and omits POSTGRES_ADMIN_URL from both application
245
- containers. Bootstrap credentials remain on PostgreSQL. Apply mode keeps the
246
- legacy adminUrl reference; an optional runtimeSecret can separately supply its
247
- POSTGRES_URL. With postgres.enabled=false, explicit application env values
248
- continue to configure external databases without generated PostgreSQL settings.
249
- Do not add administrative credentials through env/envFrom when selecting verify.
250
-
251
- ## Environment (supervisor-sink / siteServer)
252
-
253
- | Variable | Purpose |
254
- |----------|---------|
255
- | `STOMP_URL` | RabbitMQ STOMP broker |
256
- | `POSTGRES_URL` | Application DB user (`supervisor_sink`) |
257
- | `POSTGRES_ADMIN_URL` | Admin user for apply-mode migrations; omit in verify mode |
258
- | `SUPERVISOR_MIGRATIONS` | `apply` (default) or `verify`; other values fail startup |
259
- | `SINK_DB_PROFILE` | `central` or `edge` |
260
- | `SINK_PIPELINES` | `false` skips STOMP segment, decision, and alert consumers. The site container sets this and a `supervisor-sink` container keeps the default |
261
- | `SEGMENT_REPAIR_HISTORY_ON_START` | `false` preserves closed historical boundaries at ingest startup. Omitted or `true` retains the existing same-name gap repair. Live ingest and silent-open handling remain active. |
262
- | `STATE_HTTP_PORT` / `STATE_HTTP_TOKEN` | Edge internal API |
263
- | `MQTT_URL`, `MQTT_TOPICS` | Optional metrics ingest |
264
- | `CLICKHOUSE_URL` | Central metrics sink |
265
- | `PORT` | Plant API port (siteServer, default 3000) |
266
-
267
- ## Deploy
268
-
269
- The deployment DSL is specified in [docs/deploy.md](docs/deploy.md). A flow is `from` and `name`. An object listed on a node is state that node is responsible for. Profile, cluster, and modules are implementation. One Helm release of `charts/scada` is one cluster, cut from that document.
270
-
271
- ## Testing
272
-
273
- ```bash
274
- npm test # all Mocha unit tests
275
- npm test -- --grep "pattern" # filter by name
276
- npm run test:deep # domain + ingest (integration needs Docker)
277
- npm run coverage
278
- npm run lint
279
- npm run lint:eo # Elegant Objects naming audit
280
- ```
281
-
282
- Tests mirror `src/` under `test/`. Use fakes instead of mocks; one assertion per test. Integration tests under `test/infrastructure/**/integration/` use testcontainers.
283
-
284
- For HTTP/state tests without PostgreSQL:
285
-
286
- ```javascript
287
- import stateDataFake from '@yarkivaev/scada/stateDataFake';
288
- ```
289
-
290
- ## Design conventions
291
-
292
- - Factory functions returning frozen objects — no classes, no inheritance
293
- - ESLint limits: `max-lines: 200`, `max-lines-per-function: 50`, `no-console`, `no-inline-comments`
294
- - Docblocks on every module; method bodies without blank lines
295
- - See `CLAUDE.md` for layer rules and ingest sandwich diagram
17
+ For high availability, run collector copies on eligible nodes, prepare a standby Supervisor and persist historical work so another worker can resume it. See [High availability](docs/architecture/high-availability.md) for the guarantees and their prerequisites.
296
18
 
297
19
  ## Package boundary
298
20
 
299
- **Hard rule:** this package is factory-agnostic. It must not contain Sokol melting/bath domain, chem-analysis UI, HMI copy (e.g. Болото), `weight_after` fold semantics, or plant-specific sensors/routes. Those belong in `sokol-scada` (or another plant package).
300
-
301
- Opaque operation `kind` strings and generic ports (`latestForMachine`, list/upsert/stream) are allowed; never treat a kind as a first-class domain type here.
302
-
303
- | This package (`@yarkivaev/scada`) | Downstream plant package (`sokol-scada`, …) |
304
- |------------------------|--------------------------|
305
- | Generic plant, shop, machine, timeline, alerts, operations ports | Melting bath, chem, cycles HMI, site sensors |
306
- | Empty/injectable alert `translations` | Localized rule messages |
307
- | Opaque operation `kind` strings | Site kinds (`bath`, `chem`, …) and fold/prefix logic |
308
- | `plantApi`, `siteServer`, `supervisorSink` | Site bins, routes, `bathSensor`, reports |
309
- | Export ports `Query` / `Stream` / `Sink` / `Job` | Export jobs + destination adapters |
310
- | ClickHouse + PG adapters | Plant wiring (`sokolPlant` / `edgePlant`) |
311
-
312
- ### Stream transport ownership
313
-
314
- `@yarkivaev/source-to-sink` owns reusable Node.js sources, sinks and transport
315
- lifecycle: serial input, Modbus polling,
316
- MQTT/STOMP messaging, AMQP consumption and confirmed publishing, and serialized
317
- periodic ticks. SCADA composes these primitives with generic codecs, domain ports
318
- and persistence adapters. Plant packages supply source mappings, payload formats,
319
- queries, routing and plant-specific behavior.
320
-
321
- The SCADA AMQP telemetry, MQTT relay and operation-sync pipelines use
322
- `amqpSource`. It acknowledges after collector acceptance, requeues failures by
323
- default, and avoids settling explicitly acknowledged or rejected deliveries twice.
324
- Shutdown cancels consumption, drains accepted work and settlements, then closes
325
- the channel and connection. Reconnect and restart wait for that drain.
326
- `durableConsume` remains a compatibility facade over the shared AMQP session.
327
- Collectors that batch records acknowledge acceptance into that collector; this is
328
- not a guarantee that a later batch has already reached persistent storage.
329
-
330
- `intervalSource` schedules operator-cache synchronization, stale-open-segment
331
- sweeps, silent-stream reconciliation, PostgreSQL metric streams and the shared
332
- ClickHouse stream hub. Polls do not overlap; metric streams await subscribers
333
- before advancing their cursors. HTTP keepalive timers and domain coalescing
334
- windows remain owned by their respective adapters and domain policies.
335
-
336
- Depend on a pinned version (`"@yarkivaev/scada": "…#v2.3.46"`), not a local path, in downstream packages.
337
-
338
- ## CI/CD
339
-
340
- GitHub Actions via `yarkivaev/npm-workflows` (lint, test, version check). This repo publishes an npm package only; container images are built in downstream deploy repos.
341
-
342
- ### Ingest delivery and quarantine
343
-
344
- `STOMP_PREFETCH` sets a positive, bounded segment delivery window (default 128).
345
- `SEGMENTS_DEAD_LETTER_ENABLED=true` opts into rejecting malformed segment records
346
- without requeue; transient persistence failures are retried. Enable this only with
347
- a durable DLQ and routing policy. In the deployment DSL, configure
348
- `profiles.<profile>.modules.message_bus.dead_letter.queue: scada.ingest.dlq`.
349
- The scada chart declares the queue and applies an ingest-only dead-letter policy,
350
- without changing existing queue arguments. The profile `env` is passed to both
351
- site-server and supervisor-sink. DLQ records retain the original body and RabbitMQ
352
- `x-death` metadata for inspection and deliberate replay; they are not auto-expired.
353
-
354
- ### Deploy a node with named processes
355
-
356
- A profile can expose deployment coordinates in `target`, set
357
- `apps.scada.site.enabled` and `apps.scada.sink.enabled` independently, and
358
- provide RabbitMQ chart settings in `modules.message_bus.chart`. The
359
- `releases(document, cluster)` projection returns the target and chart values.
360
- The default profile still renders the existing site and sink.
361
-
362
- `subscriptions(expandedDocument, sourceId)` returns the outgoing server
363
- subscriptions as `{ from, to, name, api? }`. It combines sender `fan_out` and
364
- receiver `fan_in` declarations, keeping each expanded stream path and any
365
- explicit service selected by the receiver. Declaring the same subscription on
366
- both sides produces a single row.
367
-
368
- Use `collectorProcesses(machines, describe, project)` to derive workloads from
369
- the selected server's source rows. For each row, `describe(row)` returns a
370
- process name, command and optional environment and resources. Rows with the
371
- same name must describe the same process. `project(descriptor, rows)` converts
372
- its sources into adapter-specific environment variables and host devices. Process
373
- order follows the first occurrence of each name in the source rows.
374
- The packaged `charts/scada` chart renders the resulting `processes` as
375
- named Deployments. A configured broker claim name selects a standalone PVC.
376
- The default storage mode uses StatefulSet claim templates.
377
-
378
- `executeRelease(plan, action)` renders the chart or runs check, diff, adopt
379
- and apply against the explicitly supplied Kubernetes context and namespace.
380
- During `adopt`, the legacy client-side manager migrates the resources first.
381
- The release's server-side manager then applies the same rendered manifest before
382
- the executor waits for the workloads. This restores declared fields that a
383
- legacy three-way merge can drop, such as an environment entry whose name was
384
- duplicated in the old last-applied annotation. Each apply gets its own server
385
- dry-run. `check-adoption` previews the client-side phase only. The server-side
386
- phase must run against the migrated state. An ownership conflict stops adoption
387
- before rollout waits and the afterReady hook. Resolve the field ownership and
388
- rerun `apply` after the client-side migration has completed.
389
- A caller can supply prerequisites, rollout resources and an afterReady hook.
390
- The RabbitMQ definitions builder and management reconciler are exported as
391
- `@yarkivaev/scada/rabbitmq/definitions` and `@yarkivaev/scada/rabbitmq/reconcile`.
392
- The caller supplies the vhost, connection settings and ownership policy for
393
- retired routes. Reconciliation retains stored queues.
394
-
395
- ### Collect multiple OPC UA endpoints
396
-
397
- `@yarkivaev/scada/opcua` exports `opcuaConnections(connections, publish, options)`
398
- and `validateConnections(connections)`. The same entry point exports
399
- `opcuaSource(connections, collector, options)` for source-to-sink composition;
400
- the collector accepts `{ channel, value }`. SCADA owns the OPC UA runtime and
401
- its `node-opcua` dependency; source-to-sink contains no OPC UA implementation.
402
- Offline deployment planners should import
403
- `validateConnections` from `@yarkivaev/scada/opcua/config`; this entry point never
404
- loads the network library or its startup diagnostics. Each connection has a unique `url`,
405
- positive `publishMs` and `heartbeatMs`, and `channels` with explicit, unique
406
- `nodeId` values. Additional channel metadata is opaque to this library.
407
-
408
- ```js
409
- import opcuaConnections from '@yarkivaev/scada/opcua';
410
-
411
- const collector = opcuaConnections([
412
- { url: 'opc.tcp://192.0.2.10:4840', publishMs: 100, heartbeatMs: 1000,
413
- channels: [{ nodeId: 'ns=1;s=temperature', topic: 'line/temperature' }] }
414
- ], (channel, value) => publish(channel.topic, value));
415
- await collector.start();
416
- // On process shutdown:
417
- await collector.stop();
418
- ```
419
-
420
- Each endpoint owns its client, session and subscription. An unavailable endpoint
421
- retries independently while others continue. Start schedules these workers; it
422
- does not wait for every server to be available. Samples are delivered only with
423
- Good quality, both on change and through serialized fresh heartbeat reads.
424
- The caller owns value conversion, routing, timestamps and destination transport.
425
- Options `retryMs`, `connectTimeoutMs` and `requestTimeoutMs` bound retry timing and
426
- network requests; `onError(error, connection)` receives connection diagnostics.
427
- Do not replicate a collector with the same sources to distribute load: assign
428
- disjoint source sets to separate instances instead.
429
-
430
- A release can replace old collectors using
431
- `retirements: [{ workload: 'deployment/old-reader', selector: 'app=old-reader' }]`.
432
- For apply/adopt, the executor validates the new manifests first, foreground-deletes
433
- only these explicit Deployments, and verifies that no selected old pods remain
434
- before applying the replacement. This trades a collection gap for no overlap.
435
- The caller must bind each selector to its old Deployment; no namespace-wide prune
436
- is performed. Render/check/diff do not delete anything. An optional process `image`
437
- overrides the release image, so unrelated collectors can retain their pinned runtime.
438
-
439
- ## Universal collector runtime
440
-
441
- `scada-collector manifest.json` (or `scada-collector -` for stdin) runs all
442
- registered adapters inside one Node.js process. Every instance has the same
443
- registry; assignments select its work. `COLLECTOR_MANIFEST` accepts inline JSON;
444
- `COLLECTOR_MANIFEST_PATH` selects a file. SIGHUP reconciles the file, SIGTERM/SIGINT
445
- perform bounded shutdown. No cluster scheduler, lease service or network control
446
- API is included. HTTP request handlers and their process-local read models remain
447
- owned by the HTTP application; use `COLLECTOR_MODE=external` to disable its
448
- transferable background collection before assigning that work elsewhere.
449
-
450
- ```js
451
- import { createRegistry, createRuntime } from '@yarkivaev/scada/runtime';
452
- const runtime = createRuntime({ registry: createRegistry() });
453
- await runtime.apply({ taskId: 'line-reader', generation: 1, specVersion: 1,
454
- spec: { adapter: 'modbus', url: 'mqtt://broker', config: {
455
- addresses: ['tcp://127.0.0.1:502'], streams: [], maps: [], interval: 5
456
- } } });
457
- await runtime.remove({ taskId: 'line-reader', generation: 2 });
458
- await runtime.stop();
459
- ```
460
-
461
- Adapters include `stream` (registered source/transform/sinks), `modbus`,
462
- `activity`, `amqp-relay`, `amqp-metrics`, `mqtt-metrics`, `operation-sync`,
463
- `amqp-pg-metrics`, `mqtt-pg-metrics`, `silent-streams` and `stomp-ingest`. Plant packages extend the
464
- registry with domain-specific adapters; OPC UA belongs here, not in
465
- source-to-sink. Constructors do not open connections. A task owns independent
466
- connections and must close them in `stop()`. Factories are trusted code, not
467
- arbitrary scripts supplied in manifests.
468
-
469
- Assignments have stable task IDs, externally supplied integer generations and
470
- `specVersion: 1`. An optional `specHash` is checked against canonical JSON.
471
- Identical repeats are idempotent; conflicting/stale generations are rejected.
472
- Replacement waits for the previous owner to stop. Removed IDs retain bounded
473
- in-memory tombstones. Cleanup timeout quarantines resources and marks the
474
- runtime fatal; it never authorizes a second owner. Generation and PostgreSQL CAS
475
- are local/conflict safeguards, **not distributed fencing**. The external agent
476
- must establish cross-node ownership and provide current assignments after restart.
477
-
478
- Secrets can be references such as `{ "$secret": "AMQP_URL" }`, resolved by the
479
- host immediately before adapter construction. Status excludes configuration and
480
- exception messages. Optional `COLLECTOR_HEALTH_PORT` and
481
- `COLLECTOR_HEALTH_HOST` (default `127.0.0.1`) expose read-only `/live`, `/ready`
482
- and `/status`. Readiness rejects failed or degraded tasks as well as runtime
483
- shutdown. Fatal cleanup or an uncertain MQTT acceptance/write timeout makes
484
- liveness fail; configure an external restart policy. Transient MQTT errors mark
485
- the task degraded until broker reconnect; terminal timeouts require a fresh
486
- executor after the old process drains its IO. A blocked event loop cannot answer
487
- an external probe; synchronous infinite loops/native crashes still affect the
488
- entire process. No hard CPU or native-memory isolation is claimed.
489
-
490
- The process defaults to 16 MiB / 16,384 buffered records, each task to 1 MiB /
491
- 1,024, with bounded control admission and start/stop deadlines. Adapter-owned
492
- buffers and actual sink promises reserve capacity; driver/internal allocations
493
- and transient JSON decoding are not a hard RSS limit. Configure capacities for
494
- all simultaneously retained pipeline stages. MQTT and Loki collectors flush
495
- individual accepted records because their source delivery is sequential;
496
- AMQP pipelines retain bounded timed batching. Timeout is not proof that a remote
497
- side effect did not happen.
498
-
499
- `stream` requires explicit `delivery: "live" | "durable"`. Durable streams need
500
- `stateVersion`, `compatibilityKey`, stable `eventId` and a shared state store.
501
- Durable payloads and checkpoints use JSON; encode binary explicitly as strings.
502
- They persist an outbox and each recipient acknowledgement before advancing the
503
- checkpoint. MQTT requires QoS 1/2; AMQP sets persistent/mandatory publication and
504
- checks returned messages. Broker confirmation does not prove downstream business
505
- processing. An uncertain send can repeat with the same event ID; receivers must
506
- deduplicate. Sources with a non-null checkpoint must implement `restore()`;
507
- unsupported restoration fails closed. Live telemetry cannot replay downtime.
508
- Loki fails a saturated page rather than silently advancing across truncated data.
509
-
510
- `mqtt-pg-metrics` uses `{ mqtt, postgres, topic, options, limits }`. URLs may be
511
- secret references; `options.clientId` and `options.sessionExpiryInterval` preserve
512
- an existing persistent MQTT session. Records use the existing numeric/JSON metric
513
- decoder and are acknowledged after PostgreSQL writes. Runtime limits bound accepted
514
- records and bytes; a one-record budget works without reserving the record twice.
515
-
516
- The `modbus` adapter also accepts `config.plans`, one non-empty `[{ point, topic }]`
517
- array per device. For example, `plans: [[{ point: 'holding:4000:cdab',
518
- topic: 'existing/device/voltage' }]]` publishes that exact wire topic. Points must
519
- use `holding:<integer>[:abcd|cdab]` within the 16-bit register address range.
520
- Explicit plans replace `maps`; mixing the two or repeating a topic is rejected.
521
- All devices still share one poll window.
522
-
523
- Collector state is optional for live-only assignments. Ordinary supervisor-sink
524
- business migrations skip collector state and never delete an existing state table.
525
- Call `migrate(pool, migrationsDir, profile, { runtimeState: true })` only when
526
- explicitly enabling task-state storage, or apply its SQL separately.
527
- The runner accepts `COLLECTOR_STATE_URL` for PostgreSQL. Apply
528
- `db/migrations/V0009__collector_task_state.sql` explicitly and grant the service
529
- role access before starting stateful assignments; the runner never runs schema
530
- migrations or falls back to local disk. The storage must be reachable from every
531
- eligible node. The built-in store rejects unsupported ownership tokens rather
532
- than pretending to enforce an external fencing protocol.
533
-
534
- The coordinated review branches require new source-to-sink/scada package releases
535
- before dependency installation can reproduce all runtime tests. Stable release/pin
536
- updates and deployment remain separate steps. Unit, transport,
537
- state recovery and mixed-runtime tests do not constitute a 24-hour production
538
- soak or prove cluster-wide exactly-once effects.
539
-
540
- ## Streaming package boundary
541
-
542
- `@yarkivaev/source-to-sink` 2.x contains only protocol-independent composition
543
- primitives with no runtime dependencies. Protocol/storage implementations and
544
- their integration tests live in `src/infrastructure/streams` and are exported as
545
- `@yarkivaev/scada/streams`. This includes AMQP, MQTT, STOMP, serial, Modbus, Loki,
546
- PostgreSQL, ClickHouse and SQLite; OPC UA stays in `@yarkivaev/scada/opcua`.
547
- Plant-specific transformations stay in the plant package.
548
-
549
- ## Segment transaction batches
550
-
551
- `supervisor-sink` can read a plant policy from `SEGMENTS_TX_POLICY_FILE` (JSON).
552
- Without a policy or `SEGMENTS_TX_*` settings, existing deployments keep their current behaviour.
553
- Environment values override every policy field, so a ConfigMap update and a Recreate restart
554
- of the same image can tune persistence without an application release.
555
-
556
- | Policy field | Environment override | Default when enabled | Meaning |
557
- | --- | --- | --- | --- |
558
- | `enabled` | `SEGMENTS_TX_ENABLED` | `true` | Explicit `false` disables batching and bypasses an obsolete policy path. |
559
- | `maxMessages` | `SEGMENTS_TX_MAX_MESSAGES` | 32 | Original deliveries per transaction, capped by STOMP prefetch. |
560
- | `maxBytes` | `SEGMENTS_TX_MAX_BYTES` | 1048576 | Batch payload byte target; a transport-valid oversized delivery runs alone. |
561
- | `maxWaitMs` | `SEGMENTS_TX_MAX_WAIT_MS` | 100 | Age after which a partial batch becomes eligible to write. |
562
- | `completedSegments` | `SEGMENTS_TX_COMPLETED_SEGMENTS` | 1 | Flush after this many distinct completed segment keys; `0` disables this trigger. |
563
- | `concurrency` | `SEGMENTS_TX_CONCURRENCY` | 2 | Concurrent transactions for independent machines. |
564
- | `timeoutMs` | `SEGMENTS_TX_TIMEOUT_MS` | 10000 | Bounds connection acquisition, statements and COMMIT for a transaction. |
565
- | `statsIntervalMs` | `SEGMENTS_TX_STATS_INTERVAL_MS` | 10000 | Aggregate transaction log interval; `0` disables it. |
566
-
567
- `SEGMENTS_DB_POOL_MAX` controls the owned pool (default 10); transaction concurrency must fit it.
568
- `STOMP_PREFETCH`, `STOMP_MAX_MESSAGE_BYTES`, `STOMP_MAX_PENDING_BYTES`,
569
- `STOMP_ACCEPT_TIMEOUT_MS` and `STOMP_STOP_TIMEOUT_MS` remain independently configurable.
570
- The pending-byte lease remains held until actual commit or rejection. Prefetch, byte limits
571
- and the partial-batch timer prevent waiting indefinitely for a long segment's end.
572
-
573
- Each machine retains FIFO command order and every input command, including pending snapshots,
574
- terminal transitions, retags and split families. This preserves orphan-close and continuation
575
- side effects. Different machines can progress independently.
576
- Every receipt is acknowledged only after its batch commits. A confirmed permanent row error
577
- rolls the batch back and isolates commands into individual transactions. Uncertain COMMIT,
578
- connection failure or timeout fences the subscription; RabbitMQ retains unacknowledged deliveries
579
- for idempotent replay. WAL durability remains enabled.
580
-
581
- `[segment-transactions]` JSON logs contain committed message/record counts, COMMIT and rollback
582
- counts, SQL-call count, and maximum transaction/wait durations. They contain no payloads or tags.
583
- Compare these counters with RabbitMQ ACK/drain rates and process memory when tuning. More messages
584
- per batch reduce COMMIT frequency; the number of SQL writes still depends on command semantics.
585
-
586
- ## Ordered release stages
587
-
588
- `executeStages(stages, action = 'render', execute?)` runs ordered generic release
589
- plans. For `apply`/`adopt`, every stage is preflighted before the first mutation;
590
- each rollout and `afterReady`/`beforeApply` gate must finish before the next stage.
591
- Read-only actions do not invoke mutation gates. A plan may declare exact Deployment
592
- `retirements: [{ workload: 'deployment/old-reader', selector: 'app=old-reader' }]`
593
- and `podsAbsentBeforeApply` selectors to fence old readers before a replacement.
594
- Retirement waits for foreground deletion and verifies no matching pods remain;
595
- failures stop execution. Context, namespace and field manager remain explicit.
596
-
597
- The application chart accepts existing PostgreSQL/RabbitMQ claims, secret-backed
598
- environment values, `envFrom`, config volumes, probes and extra Kubernetes objects.
599
- PostgreSQL honors the root `pullSecret`. Existing claims are referenced without
600
- creating or deleting storage; plant packages supply their precise deployment values.
601
-
602
- ### Per-server module configuration
603
-
604
- A server may override its profile's `modules`. Maps merge recursively; omitted
605
- fields are inherited, arrays replace, and null removes an inherited key.
606
- `state_store.pgdata` selects PostgreSQL's existing data directory and takes
607
- precedence over the compatible `state_store.chart.data` setting.
608
-
609
- ```yaml
610
- servers:
611
- - id: cell-a
612
- modules:
613
- state_store:
614
- pgdata: /var/lib/postgresql/data/pgdata
615
- profile:
616
- id: cell
617
- variables:
618
- cluster: cell-a
619
- ```
620
-
621
- This changes the selected server only; it does not mutate the shared profile.
622
-
623
- The optional `mdmesh` module projects `chart` settings into `releases(...).scada.mdmesh`,
624
- with its explicit `namespace` and `enabled` (default `true`) taking precedence.
625
- It uses the same profile inheritance and server overrides. A consuming application
626
- owns the MDMesh chart and deployment; the generic application chart does not install it.
627
- An optional root `hmi` catalog passes through reading, includes, expansion, and release
628
- projection as `releases(...).hmi` without interpretation. Catalog validation belongs
629
- to the consuming application.
630
-
631
- ### Central backup freshness
632
-
633
- Silent Modbus backup sources use `MX210/<device>` freshness identities. AMQP telemetry tracks `<source-family>/<device>`, so cooling for a device cannot hide missing MX210 electrical samples. Measurement topic paths are unchanged. Custom freshness callbacks must pass the source’s full identity to `seen()`.
634
-
635
- ### MQTT publisher recovery
636
-
637
- An unexpected MQTT publisher close/offline/error retires the session and notifies `onFatal` once. Intentional `stop()` does not notify failure. Modbus runtime tasks propagate publisher failure to collector `/ready` and `/live` (503). Run the collector under its liveness supervisor: it must retire the failed executor and create a fresh one, which reconnects after the broker returns. Uncertain publications are not automatically replayed. Broker restart regression covers failed health, old poll cleanup, and confirmed fresh measurements from the replacement executor.
638
-
639
- ### Central canonical telemetry, version 4
640
-
641
- `CENTRAL_TELEMETRY_POLICY` is generated by the deployment DSL. Runtime capability
642
- `centralTelemetryVersion === 4` rejects old bitmap/PG review configurations.
643
- There is no PostgreSQL telemetry registry and no bitmap/custom aggregate storage.
644
-
645
- All protected AMQP/MQTT/sync/external adapters publish immutable, bounded batches
646
- to ONE durable RabbitMQ SAC queue, prefetch1, persistent mandatory confirms,
647
- reject-publish overflow, no TTL/priorities. A failed unacked head is held in place.
648
- Its frozen central `admittedAt` and per-topic policy survive retries. The worker
649
- uses synchronous ClickHouse inserts and commits its bounded metadata counter
650
- only after point/rejection writes, before source ACK.
651
-
652
- Central point admission and endpoint publication use RowBinary to preserve Float64 values and UInt128 revisions exactly. The writer drains the complete synchronous ClickHouse response before committing the admission cursor.
653
-
654
- Ordinary `scada.metrics_points_v4` rows use ReplacingMergeTree(revision), keyed by
655
- (topic, original millisecond timestamp). Last durable admission wins, including
656
- array order within a batch. The user removed the previous first-value rule.
657
- Native versions prevent delayed old INSERTs overtaking a newer admitted value;
658
- FINAL reads are correct before background merges too.
659
-
660
- Default policy fields (all overridable for exact topics):
661
-
662
- - compactWindowMs:60000; zero disables physical thinning.
663
- - maxGapMs:30000; positive maximum interval in the merged sensor stream; exact-topic overrides are supported.
664
- - historyWindowMs:604800000; seven days behind this topic's latest valid point.
665
- - maxHistoryAgeMs:2592000000; thirty-day calendar cap at central admission.
666
- - futureSkewMs:300000; far-future source clocks are rejected before watermarking.
667
-
668
- A topic's sealed frontier advances monotonically, only at complete-window
669
- boundaries. Previous production history seeds the initial watermark. A longer
670
- configured window never reopens sealed history. Too-old/future observations go
671
- to separately named TTL-bounded diagnostics before ACK and never alter canonical
672
- history. No automatic old-history update, addition or deletion is accepted.
673
-
674
- Recent observations retain all original timestamps. In a sealed constant-value
675
- window, observations are split into continuity islands: a gap strictly greater than frozen maxGapMs starts a new island; equality remains continuous. Each island retains its first/last observations; a singleton stays once. In a window with
676
- ANY different value, EVERY canonical point is retained, including short spikes,
677
- returns and oscillations. There is no average, value tolerance or time rounding
678
- that can hide an observed differing value. Overlapping policies/legacy windows
679
- are conservatively retained.
680
-
681
- Native background DELETE mutations physically remove equal interior points.
682
- Two ordinary retained endpoint rows carry explicit constant-span/revision
683
- certificates: an older differing INSERT cannot resurrect a deleted superseded
684
- interior. Complete endpoint proofs are durable before deletion, with a read grace
685
- on publication. Cleanup limits pending mutations; failures retain extra rows
686
- and retry, never lose canonical values. This reduces actual stored observations,
687
- not merely a SELECT result. There is no forever-full hidden raw copy.
688
-
689
- `scada.metrics_read` is the canonical relation; `metrics_raw_read` exposes retained
690
- point rows and cannot reconstruct deleted timestamps. Level changes/edges remain
691
- available. Density-sensitive counts/minPoints use bounded
692
- `clickhouseMetricsRawRange`, which explicitly rejects sealed constant ranges with
693
- `SCADA_HISTORY_DENSITY_UNAVAILABLE` instead of silently computing from endpoints.
694
- Graphs may clip constant coverage using derived display vertices, which are not
695
- original observations. Edge raw history and local classifications are untouched.
696
-
697
- Legacy scada.metrics stays readable and unchanged with precedence on overlapping
698
- keys. Only missing additive schema falls back; permission/schema failures surface.
699
- One authoritative read-after-write ClickHouse target is required. Serving reads
700
- through lagging asynchronous replicas is unsupported. Atomic table comments pin
701
- broker/vhost/queue/target; an independent domain cannot race the same data. Existing
702
- v1/v2/v3 review schemas/envelopes require an explicit migration, not silent reuse.
703
- Disable after activation and immutable queue argument changes fail closed.
704
-
705
- No merge, deployment, running-database migration, package/image publication or
706
- release is performed by opening or updating this PR.
707
-
708
- Native v4 persists each observation's frozen `max_gap_ms`. Certificates prove continuous coverage for one island, so deletion and repeated cleanup never turn a certified interval into a false gap or join separate islands. Interleaved collectors are merged by logical topic and timestamp before detecting gaps. Mixed-value windows remain entirely retained. Chart downsampling groups by continuity before time buckets and emits explicit null separators; native numeric points carry `continuous` metadata so consumers do not infer false gaps from sparse certified endpoints. Holds may use certificates when requested gap is at least the stored threshold; stricter raw-density requests remain explicitly unavailable.
709
-
710
- Older unpublished v3 native tables/envelopes require an explicit migration and are rejected; erased gap evidence cannot be recovered from their endpoints. No automatic upgrade or production migration runs in these PRs. Ordinary legacy `scada.metrics` remains readable and unmodified.
711
-
712
- HTTP and display MCP results preserve continuity metadata and null separators. `sensor.samples(range)` uses the exact-density guard and returns actual observations for coverage analytics; unsupported raw readers fail explicitly. Two-point unthinned islands retain exact density. Frontends show isolated observations, and peak analytics ignore null separators.
713
-
714
- ### Broker credential Secrets
715
-
716
- Set `rabbitmq.definitionsSecret` to a separately provisioned Secret with the key
717
- `definitions.json`; the chart then omits definitions from its ConfigMap. Set
718
- `rabbitmq.runtimeSecret` for `AMQP_URL`, `STOMP_LOGIN` and `STOMP_PASSCODE`.
719
- Other clients can reference the same or narrower Secrets explicitly. Anonymous
720
- MQTT remains compatible by default; set `rabbitmq.extraConfig["mqtt.allow_anonymous"]`
721
- to false only after all MQTT clients have authenticated credentials. A frozen
722
- broker PodTemplate cannot adopt these mounts: unfreeze it for a controlled
723
- restart while preserving the claim. Definitions import does not delete an
724
- existing guest user; retire it explicitly after all dependent clients reconnect.
725
-
726
- ### Collector recovery and durable delivery references
727
-
728
- Collector health opens before local spool recovery; `/live` remains responsive and `/ready` stays negative until recovery and a saved/initial assignment are applied. Cached assignments start without waiting for the first network reconciliation. `COLLECTOR_RECOVERY_TIMEOUT_MS` defaults to 900000 and bounds local initialization; exceeding it terminates startup for the external supervisor. Validate recovery duration against measured queue capacity before activation.
729
-
730
- Spooled destination descriptors retain secret references. Draining a recovered queue resolves the current secret for each logical recipient, so credential rotation does not freeze a password in queued observations. Source connection credentials are still resolved at resource construction. Scheduler updates preserve a potentially working replica until another matching reader reports fresh progress, except explicit current-generation failure.
731
-
732
- Central canonical ingestion propagates the receiver session ownership predicate through schema initialization and admission. It checks ownership again after authoritative state/clock reads and before writes; a lost session cannot allocate a newer revision from a delayed SELECT. Already submitted old-revision inserts remain safe under canonical winner ordering.
733
-
734
-
735
- Collector delivery storage uses version1 SQLite with WAL and synchronous FULL. Acceptance and recipient acknowledgements return after commit. Event payloads are compressed; destination descriptors (including raw Secret references) are interned and retained until their last pending event is confirmed. Startup validates canonical counters and rebuilds a disposable disk-backed recipient replay index from event metadata; it does not decode every observation or build an in-memory backlog. Recovery therefore includes linear metadata IO and must be qualified at the configured capacity. Replay interleaves bounded indexed pages across immutable destination descriptors, so a large offline-only prefix cannot hide a healthy destination. The reserved private `replay-index.sqlite` and its sidecars are disposable: every open rebuilds them under exclusive ownership, including after corruption or a rollback to an older runtime. They never provide acceptance or acknowledgement evidence; canonical format version1 remains unchanged.
736
-
737
- `maxBytes` limits the logical UTF-8 JSON size of `{event, recipients, remaining}`; it does not describe disk allocation. `maxRecords` independently limits retained observations. SQLite pages, indexes and WAL require additional capacity planning. Canonical and replay page caches are each 2 MiB; automatic checkpoints run every 256 WAL pages and keep at most 1 MiB after checkpoint. A single large transaction may temporarily exceed that checkpoint target. Deleted pages are reused by later observations; database files retain their high-water allocation. Do not delete/vacuum an active spool to reclaim space.
738
-
739
- Only one process may own a spool directory on a local filesystem with SQLite WAL/locking semantics. Stop an older JSON-based collector before upgrading; its writer does not participate in the new ownership lock. The spool directory must remain private to the collector. Call `close()` before reopening it elsewhere; a killed process releases its SQLite ownership lock automatically. Queue shutdown waits for accepted operations and its current drain before closing sessions and storage. Legacy committed SHA256-named JSON records import one at a time: commit and verify the exact event/receipts before unlinking and syncing the directory. An interrupted import reconciles on the next open; corrupt, ambiguous or over-limit files fail startup and remain recoverable. Unrelated files are untouched and symlinked committed records and symlinked/hard-linked SQLite main files or sidecars are rejected. Existing databases must match the versioned schema and contain valid counters; ambiguous state is rejected rather than repaired. Correct the underlying file/capacity problem before retrying recovery; never discard pending files to make readiness green.
740
-
741
- Use `node --expose-gc scripts/measure-delivery-spool.mjs FIXTURE.json 120000` with actual adapter `{event,destinations}` samples to measure a target environment. The benchmark reports logical/compressed/page/index bytes, heap/RSS, recovery, append/drain and page reuse separately; its sink stand-in does not measure broker latency.
742
-
743
-
744
- `legacyMigrationMaxBytes` is a separate positive safe-integer option on `deliverySpool()` / `deliveryQueue()`, defaulting to **16 MiB per committed legacy JSON file**. The queue-wide `maxBytes` may be many GiB; it does not increase this migration allocation budget. Recovery checks both limits from the open file descriptor before allocating or reading its body, including the post-commit verification read. A file exceeding either limit stops recovery and remains untouched. For a legitimate larger legacy record, raise `legacyMigrationMaxBytes` explicitly within the collector's available memory budget and retry; parsing, serialization and compression require additional memory beyond the read buffer. This option applies only to legacy JSON migration. Newly appended generic events and existing SQLite records keep their existing logical queue/record-cap semantics.
745
-
746
- ### Durable queue group commit
747
-
748
- `deliverySpool.mutateMany(operations)` adds ordered append/receipt mutations to one WAL/FULL outer transaction. Entries are `{kind:'append', event, recipients}` or `{kind:'ack', eventId, recipient}`. The returned array contains `{ok:true}` or `{ok:false,error}` for each entry, and becomes available only after COMMIT. Validation, identity and capacity errors roll back that entry's savepoint; SQLite or COMMIT errors reject the entire call and fail the spool closed. Existing `append()` and `ack()` still perform immediate durable single-operation calls. Format version1 and legacy recovery are unchanged.
749
-
750
- `deliveryQueue()` accumulates frozen operations before its database serialization barrier. Defaults are `groupCommit: {maxRecords:64, maxBytes:1048576, maxDelayMs:25}`, `maxOperations:128` and `maxPendingBytes:4194304`. Limits must be positive safe integers; the delay may be zero and cannot exceed the platform timer range. Every submitted operation must fit both byte limits. Increase these explicit options within the process memory budget for larger generic envelopes. A full operation window waits for a released slot before snapshot construction; oversized serialized inputs are still rejected before decoding their queue snapshot. Count and bytes remain reserved through the actual grouped operation, including an in-flight commit, even if an upstream caller stops waiting.
751
-
752
- No observation is merged, sampled or discarded by batching. An `accept()` promise succeeds only after durable commit. A sparse group flushes on its timer; capacity thresholds, reads and close force earlier flushing. The delay bounds the coalescing window, not disk latency or end-to-end completion. Queue status retains durable `pending`/`bytes` and adds `queuedOperations`, `queuedBytes` and `drainFull` diagnostics.
753
-
754
- The positive safe-integer `maxInFlight` option defaults to32. A drain initiates at most that many publications concurrently, in stored order per logical AMQP session. All concurrent writers await the same session opening; one mandatory return does not retire independent confirms. Receipt admission and serialized publication bytes are reserved before network publication, then the receipt is queued only after its individual mandatory confirmation. The retained publication bytes count toward `maxPendingBytes`, separately from receipt mutation bytes counted toward the group byte limit. Confirmed receipts accumulate in a bounded window; `drain()` counts them delivered only after their FULL commit. Graceful close rejects new source submissions, flushes existing submissions, waits for the active drain and its receipts, then closes sessions and persistence. Caller write deadlines abort the actual AMQP writer and retire its session. A caller timeout alone does not release a publication slot or its prospective ACK reservation; late actual success still commits its receipt, and late callbacks from an aborted AMQP generation cannot ACK a retry. The64-entry session pool reuses least-recently-used fully settled idle sessions, including after descriptor or credential-reference rotation; active or reserved sessions are never evicted. A custom factory that ignores both AbortSignal and stop remains fenced and bounded until actual settlement. Close fails after its bounded session wait and retains spool ownership if that work cannot quiesce; retry close after settlement. The existing crash-after-confirm/before-local-receipt replay contract remains unchanged.
755
-
756
- Healthy full drain pages with durable progress continue on subsequent event-loop turns; after four pages the scheduler pauses 25 ms. Pages with healthy durable progress continue even if a different recipient failed. A failed immutable destination descriptor has a10s monotonic retry cooldown (`failureCooldownMs`, nonnegative safe integer, default10000; zero disables), tracked in a bounded128-entry map; other destinations remain eligible. Empty or zero-progress pages back off1s. This removes the former 100-event/s scheduling ceiling without spinning on an offline recipient. Actual append and online catch-up throughput still require qualification on the target filesystem; a serial producer awaiting every individual acceptance cannot benefit from concurrent group formation.
757
-
758
- ### Bounded native history commits
759
-
760
- Native history receivers advertise `nativeTailProtocol: preserve-known-suffix-v1`
761
- on configuration. Workers must negotiate this before starting. A computed
762
- terminal anchor must not clip an existing segment whose known end lies beyond
763
- the observed page. An unchanged exterior anchor can be omitted entirely.
764
-
765
- An exterior row requires `context.nativeTailMode` with that protocol and a
766
- `preserveSuffix` object identifying a current segment by `kind`, `name`,
767
- `start_time`, and `end_time`. Under the existing context revision lock, the
768
- receiver checks its class, extent and current ownership. Archive-only rows
769
- cannot justify exterior changes. Changing a current segment inside the page
770
- must retain any unobserved suffix, potentially as a piece starting one
771
- millisecond after the page end; unseen cut collisions fail atomically.
772
- Conservative page-boundary cuts remain protected, so a paged transition can
773
- leave additional adjacent same-class pieces. No new exterior observations or
774
- classes are inferred. A rejected commit leaves both projection and work intact.
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).
775
22
 
776
- Applicable children carry operator metadata and `consumed`; existing rows keep
777
- their stored consumed state. This native protocol is separate from the staged
778
- stateful correction protocol used with external raw observation stores.
23
+ [MIT license](LICENSE)