@yarkivaev/scada 2.5.8 → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/README.md +83 -0
  2. package/db/migrations/E0005__historical_telemetry_grants.sql +5 -0
  3. package/db/migrations/E0006__historical_telemetry.sql +64 -0
  4. package/db/migrations/E0007__metric_receipts.sql +7 -0
  5. package/db/migrations/E0008__metric_receipts_grants.sql +1 -0
  6. package/db/migrations/E0009__history_continuation.sql +20 -0
  7. package/db/migrations/E0010__history_admissions.sql +8 -0
  8. package/db/migrations/E0011__history_classifier_checkpoints.sql +18 -0
  9. package/db/migrations/E0012__external_history_grants.sql +4 -0
  10. package/db/migrations/E0013__history_staged_corrections.sql +104 -0
  11. package/db/migrations/E0014__history_correction_grants.sql +5 -0
  12. package/db/migrations/E0015__history_retention_frontier.sql +7 -0
  13. package/db/migrations/E0016__history_retention_grants.sql +1 -0
  14. package/index.js +7 -0
  15. package/package.json +5 -3
  16. package/src/application/control/agent.js +61 -0
  17. package/src/application/control/catalog.js +22 -0
  18. package/src/application/control/controlClient.js +75 -0
  19. package/src/application/control/controlStore.js +55 -0
  20. package/src/application/control/controller.js +22 -0
  21. package/src/application/control/executionSnapshot.js +32 -0
  22. package/src/application/control/index.js +7 -0
  23. package/src/application/control/localAssignment.js +13 -0
  24. package/src/application/control/schedule.js +103 -0
  25. package/src/application/control/snapshotFile.js +24 -0
  26. package/src/application/foldedMetricsSink.js +1 -0
  27. package/src/application/mcp/mcpResources.js +1 -1
  28. package/src/application/mcp/mcpSchema.js +8 -3
  29. package/src/application/runtime/additionalAdapters.js +13 -9
  30. package/src/application/runtime/deliveryQueue.js +62 -0
  31. package/src/application/runtime/deliverySessions.js +28 -0
  32. package/src/application/runtime/modbusDelivery.js +36 -0
  33. package/src/application/runtime/pipelineAdapters.js +12 -8
  34. package/src/application/runtime/queuedDelivery.js +25 -0
  35. package/src/application/runtime/runCollector.js +34 -3
  36. package/src/application/runtime/runtime.js +2 -2
  37. package/src/application/runtime/runtimeHealth.js +1 -1
  38. package/src/application/runtime/runtimeServices.js +6 -2
  39. package/src/application/runtime/streamTask.js +13 -4
  40. package/src/application/runtime/taskContext.js +1 -0
  41. package/src/application/runtime/taskSlot.js +2 -2
  42. package/src/application/runtime/telemetrySink.js +18 -0
  43. package/src/application/siteServer.js +19 -4
  44. package/src/application/siteTelemetry.js +2 -2
  45. package/src/application/supervisorSink.js +5 -1
  46. package/src/application/sync/siteSyncBind.js +2 -2
  47. package/src/bin/controller.js +8 -0
  48. package/src/infrastructure/http/edge/edgeApi.js +2 -0
  49. package/src/infrastructure/http/edge/routes/history/historyRoutes.js +33 -0
  50. package/src/infrastructure/http/plant/routes/measurementRead.js +3 -0
  51. package/src/infrastructure/ingest/db/migrationProfile.js +6 -1
  52. package/src/infrastructure/ingest/db/retainMetricReceipts.js +8 -0
  53. package/src/infrastructure/ingest/db/runRetention.js +2 -0
  54. package/src/infrastructure/ingest/mqtt/metricsTransformer.js +11 -2
  55. package/src/infrastructure/ingest/mqtt/modbusMqtt.js +1 -1
  56. package/src/infrastructure/ingest/mqtt/modbusPublish.js +2 -0
  57. package/src/infrastructure/ingest/mqtt/mqttMetrics.js +1 -1
  58. package/src/infrastructure/ingest/telemetry/amqpMetricsIngest.js +7 -3
  59. package/src/infrastructure/ingest/telemetry/centralEnvelope.js +46 -0
  60. package/src/infrastructure/ingest/telemetry/centralMetricsSink.js +64 -0
  61. package/src/infrastructure/ingest/telemetry/centralPoint.js +14 -0
  62. package/src/infrastructure/ingest/telemetry/centralPolicy.js +51 -0
  63. package/src/infrastructure/ingest/telemetry/centralQueueSession.js +29 -0
  64. package/src/infrastructure/ingest/telemetry/centralTelemetryPreflight.js +31 -0
  65. package/src/infrastructure/ingest/telemetry/foldingSink.js +3 -0
  66. package/src/infrastructure/ingest/telemetry/historyTelemetry.js +32 -0
  67. package/src/infrastructure/persistence/clickhouse/canonicalMetrics.js +26 -0
  68. package/src/infrastructure/persistence/clickhouse/changes.js +4 -2
  69. package/src/infrastructure/persistence/clickhouse/connection.js +6 -8
  70. package/src/infrastructure/persistence/clickhouse/holds.js +10 -7
  71. package/src/infrastructure/persistence/clickhouse/latest.js +1 -1
  72. package/src/infrastructure/persistence/clickhouse/metricsQuery.js +70 -0
  73. package/src/infrastructure/persistence/clickhouse/metricsRelation.js +110 -0
  74. package/src/infrastructure/persistence/clickhouse/nativeMetricPoints.js +26 -0
  75. package/src/infrastructure/persistence/clickhouse/nativeMetricsAdmission.js +91 -0
  76. package/src/infrastructure/persistence/clickhouse/nativeMetricsClock.js +9 -0
  77. package/src/infrastructure/persistence/clickhouse/nativeMetricsCompaction.js +82 -0
  78. package/src/infrastructure/persistence/clickhouse/nativeMetricsInsert.js +31 -0
  79. package/src/infrastructure/persistence/clickhouse/nativeMetricsOwnership.js +8 -0
  80. package/src/infrastructure/persistence/clickhouse/nativeMetricsSchema.js +44 -0
  81. package/src/infrastructure/persistence/clickhouse/pollTopicCursors.js +3 -1
  82. package/src/infrastructure/persistence/clickhouse/rises.js +4 -2
  83. package/src/infrastructure/persistence/clickhouse/samples.js +10 -0
  84. package/src/infrastructure/persistence/clickhouse/sensor.js +4 -0
  85. package/src/infrastructure/persistence/clickhouse/series.js +38 -21
  86. package/src/infrastructure/persistence/pg/history.js +169 -0
  87. package/src/infrastructure/persistence/pg/historyAdmission.js +81 -0
  88. package/src/infrastructure/persistence/pg/historyCheckpoint.js +56 -0
  89. package/src/infrastructure/persistence/pg/historyConfigure.js +28 -0
  90. package/src/infrastructure/persistence/pg/historyContext.js +65 -0
  91. package/src/infrastructure/persistence/pg/historyCorrection.js +34 -0
  92. package/src/infrastructure/persistence/pg/historyObservations.js +56 -0
  93. package/src/infrastructure/persistence/pg/historySeed.js +27 -0
  94. package/src/infrastructure/persistence/pg/metrics.js +5 -4
  95. package/src/infrastructure/persistence/pg/metricsInsertSql.js +12 -0
  96. package/src/infrastructure/persistence/runtime/deliverySpool.js +124 -0
  97. package/src/infrastructure/persistence/stateDataFromPool.js +2 -0
  98. package/src/infrastructure/streams/amqpSink/session.js +6 -0
  99. package/src/infrastructure/streams/amqpSource.js +17 -4
package/README.md CHANGED
@@ -636,6 +636,81 @@ Silent Modbus backup sources use `MX210/<device>` freshness identities. AMQP tel
636
636
 
637
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
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
+
639
714
  ### Broker credential Secrets
640
715
 
641
716
  Set `rabbitmq.definitionsSecret` to a separately provisioned Secret with the key
@@ -647,3 +722,11 @@ to false only after all MQTT clients have authenticated credentials. A frozen
647
722
  broker PodTemplate cannot adopt these mounts: unfreeze it for a controlled
648
723
  restart while preserving the claim. Definitions import does not delete an
649
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.
@@ -0,0 +1,5 @@
1
+ -- Review-only migration source. Applied only during a separately authorized deployment.
2
+ GRANT SELECT, INSERT, DELETE ON history_observations TO supervisor_sink;
3
+ GRANT SELECT, INSERT, UPDATE, DELETE ON history_work TO supervisor_sink;
4
+ GRANT SELECT, INSERT, DELETE ON history_topics TO supervisor_sink;
5
+ GRANT SELECT, INSERT, UPDATE ON history_annotations TO supervisor_sink;
@@ -0,0 +1,64 @@
1
+ CREATE TABLE IF NOT EXISTS history_observations (
2
+ machine TEXT NOT NULL,
3
+ channel TEXT NOT NULL,
4
+ time_ms BIGINT NOT NULL,
5
+ event_id TEXT NOT NULL,
6
+ value DOUBLE PRECISION NOT NULL,
7
+ received_at TIMESTAMPTZ NOT NULL DEFAULT now(),
8
+ PRIMARY KEY (machine, channel, time_ms),
9
+ UNIQUE (machine, event_id)
10
+ );
11
+ CREATE INDEX IF NOT EXISTS history_observations_time ON history_observations(machine,time_ms);
12
+ CREATE TABLE IF NOT EXISTS history_work (
13
+ id UUID PRIMARY KEY,
14
+ token UUID NOT NULL DEFAULT gen_random_uuid(),
15
+ machine TEXT NOT NULL,
16
+ from_ms BIGINT NOT NULL,
17
+ until_ms BIGINT NOT NULL,
18
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
19
+ );
20
+ CREATE INDEX IF NOT EXISTS history_work_machine ON history_work(machine, created_at);
21
+ CREATE TABLE IF NOT EXISTS history_annotations (
22
+ machine TEXT NOT NULL,
23
+ kind TEXT NOT NULL,
24
+ start_time TIMESTAMPTZ NOT NULL,
25
+ name TEXT NOT NULL,
26
+ end_time TIMESTAMPTZ,
27
+ duration DOUBLE PRECISION,
28
+ tags TEXT,
29
+ properties TEXT,
30
+ resolved BOOLEAN,
31
+ PRIMARY KEY(machine,kind,start_time,name)
32
+ );
33
+ CREATE TABLE IF NOT EXISTS history_topics (
34
+ machine TEXT NOT NULL,
35
+ topic TEXT NOT NULL,
36
+ channel TEXT NOT NULL,
37
+ bucket_ms BIGINT NOT NULL DEFAULT 30000 CHECK(bucket_ms > 0),
38
+ retention_days INTEGER NOT NULL DEFAULT 30 CHECK(retention_days > 0),
39
+ PRIMARY KEY(machine,topic)
40
+ );
41
+ CREATE OR REPLACE FUNCTION history_from_metric() RETURNS TRIGGER LANGUAGE plpgsql AS $$
42
+ DECLARE mapping RECORD; moment BIGINT; inserted INTEGER;
43
+ BEGIN
44
+ moment := floor(extract(epoch FROM NEW.ts)*1000)::bigint;
45
+ FOR mapping IN SELECT * FROM history_topics WHERE topic=NEW.topic LOOP
46
+ PERFORM pg_advisory_xact_lock(hashtextextended('history:'||mapping.machine,0));
47
+ INSERT INTO history_observations(machine,channel,time_ms,event_id,value)
48
+ VALUES(mapping.machine,mapping.channel,moment,md5(NEW.topic||':'||moment::text||':'||NEW.value::text),NEW.value)
49
+ ON CONFLICT DO NOTHING;
50
+ GET DIAGNOSTICS inserted = ROW_COUNT;
51
+ IF inserted > 0 AND NEW.ts >= now()-make_interval(days => mapping.retention_days) THEN
52
+ INSERT INTO history_work(id,machine,from_ms,until_ms)
53
+ VALUES(md5(mapping.machine||':'||(moment/mapping.bucket_ms)::text)::uuid,mapping.machine,moment,moment)
54
+ ON CONFLICT(id) DO UPDATE SET token=gen_random_uuid(),from_ms=least(history_work.from_ms,excluded.from_ms),until_ms=greatest(history_work.until_ms,excluded.until_ms);
55
+ END IF;
56
+ END LOOP;
57
+ RETURN NEW;
58
+ END $$;
59
+ DO $$ BEGIN
60
+ IF to_regclass('metrics') IS NOT NULL THEN
61
+ DROP TRIGGER IF EXISTS metrics_history ON metrics;
62
+ CREATE TRIGGER metrics_history AFTER INSERT ON metrics FOR EACH ROW EXECUTE FUNCTION history_from_metric();
63
+ END IF;
64
+ END $$;
@@ -0,0 +1,7 @@
1
+ -- Opt-in first-write-wins receipts survive receiver restart and raw metric retention.
2
+ CREATE TABLE IF NOT EXISTS metric_receipts (
3
+ topic TEXT NOT NULL,
4
+ ts TIMESTAMPTZ NOT NULL,
5
+ value DOUBLE PRECISION NOT NULL,
6
+ PRIMARY KEY(topic,ts)
7
+ );
@@ -0,0 +1 @@
1
+ GRANT SELECT, INSERT, DELETE ON metric_receipts TO supervisor_sink;
@@ -0,0 +1,20 @@
1
+ ALTER TABLE history_work ADD COLUMN IF NOT EXISTS cursor_ms BIGINT;
2
+ ALTER TABLE history_work ADD COLUMN IF NOT EXISTS end_ms BIGINT;
3
+ CREATE OR REPLACE FUNCTION history_from_metric() RETURNS TRIGGER LANGUAGE plpgsql AS $$
4
+ DECLARE mapping RECORD; moment BIGINT; inserted INTEGER;
5
+ BEGIN
6
+ moment := floor(extract(epoch FROM NEW.ts)*1000)::bigint;
7
+ FOR mapping IN SELECT * FROM history_topics WHERE topic=NEW.topic LOOP
8
+ PERFORM pg_advisory_xact_lock(hashtextextended('history:'||mapping.machine,0));
9
+ INSERT INTO history_observations(machine,channel,time_ms,event_id,value)
10
+ VALUES(mapping.machine,mapping.channel,moment,md5(NEW.topic||':'||moment::text||':'||NEW.value::text),NEW.value)
11
+ ON CONFLICT DO NOTHING;
12
+ GET DIAGNOSTICS inserted = ROW_COUNT;
13
+ IF inserted > 0 AND NEW.ts >= now()-make_interval(days => mapping.retention_days) THEN
14
+ INSERT INTO history_work(id,machine,from_ms,until_ms)
15
+ VALUES(md5(mapping.machine||':'||(moment/mapping.bucket_ms)::text)::uuid,mapping.machine,moment,moment)
16
+ ON CONFLICT(id) DO UPDATE SET token=gen_random_uuid(),cursor_ms=NULL,end_ms=NULL,from_ms=least(history_work.from_ms,excluded.from_ms),until_ms=greatest(history_work.until_ms,excluded.until_ms);
17
+ END IF;
18
+ END LOOP;
19
+ RETURN NEW;
20
+ END $$;
@@ -0,0 +1,8 @@
1
+ -- Temporary cross-database barriers contain identity/range only, never numeric payloads.
2
+ CREATE TABLE IF NOT EXISTS history_admissions (
3
+ event_id TEXT PRIMARY KEY,
4
+ topic TEXT NOT NULL,
5
+ time_ms BIGINT NOT NULL,
6
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
7
+ );
8
+ CREATE INDEX IF NOT EXISTS history_admissions_topic ON history_admissions(topic,time_ms);
@@ -0,0 +1,18 @@
1
+ CREATE TABLE IF NOT EXISTS history_classifiers (
2
+ machine TEXT PRIMARY KEY,
3
+ classifier_key TEXT NOT NULL
4
+ );
5
+ CREATE TABLE IF NOT EXISTS history_checkpoints (
6
+ machine TEXT NOT NULL,
7
+ classifier_key TEXT NOT NULL,
8
+ time_ms BIGINT NOT NULL,
9
+ state JSONB NOT NULL,
10
+ valid BOOLEAN NOT NULL DEFAULT true,
11
+ PRIMARY KEY(machine,classifier_key,time_ms)
12
+ );
13
+ -- Persistent source identity prevents interpreting legacy millisecond work as microseconds.
14
+ CREATE TABLE IF NOT EXISTS history_sources (
15
+ machine TEXT PRIMARY KEY,
16
+ source_id TEXT NOT NULL,
17
+ time_scale INTEGER NOT NULL CHECK(time_scale IN (1,1000))
18
+ );
@@ -0,0 +1,4 @@
1
+ GRANT SELECT, INSERT, DELETE ON history_admissions TO supervisor_sink;
2
+ GRANT SELECT, INSERT, UPDATE, DELETE ON history_classifiers TO supervisor_sink;
3
+ GRANT SELECT, INSERT, UPDATE, DELETE ON history_checkpoints TO supervisor_sink;
4
+ GRANT SELECT, INSERT ON history_sources TO supervisor_sink;
@@ -0,0 +1,104 @@
1
+ ALTER TABLE history_annotations ADD COLUMN IF NOT EXISTS consumed BOOLEAN DEFAULT true;
2
+ ALTER TABLE history_work ADD COLUMN IF NOT EXISTS generation UUID NOT NULL DEFAULT gen_random_uuid();
3
+ ALTER TABLE history_work ADD COLUMN IF NOT EXISTS correction_from BIGINT;
4
+ ALTER TABLE history_work ADD COLUMN IF NOT EXISTS correction_until BIGINT;
5
+ ALTER TABLE history_work ADD COLUMN IF NOT EXISTS classifier_checkpoint JSONB;
6
+ ALTER TABLE history_work ADD COLUMN IF NOT EXISTS started BOOLEAN NOT NULL DEFAULT false;
7
+ CREATE TABLE IF NOT EXISTS history_corrections (
8
+ work_id UUID NOT NULL REFERENCES history_work(id) ON DELETE CASCADE,
9
+ generation UUID NOT NULL,
10
+ machine TEXT NOT NULL,
11
+ kind TEXT NOT NULL,
12
+ name TEXT NOT NULL,
13
+ start_time TIMESTAMPTZ NOT NULL,
14
+ end_time TIMESTAMPTZ NOT NULL,
15
+ duration DOUBLE PRECISION NOT NULL,
16
+ options TEXT, tags TEXT, properties TEXT, resolved BOOLEAN,
17
+ PRIMARY KEY(work_id,generation,kind,start_time)
18
+ );
19
+ CREATE TABLE IF NOT EXISTS history_staged_checkpoints (
20
+ work_id UUID NOT NULL REFERENCES history_work(id) ON DELETE CASCADE,
21
+ generation UUID NOT NULL,
22
+ machine TEXT NOT NULL,
23
+ classifier_key TEXT NOT NULL,
24
+ time_ms BIGINT NOT NULL,
25
+ state JSONB NOT NULL,
26
+ PRIMARY KEY(work_id,generation,classifier_key,time_ms)
27
+ );
28
+ CREATE INDEX IF NOT EXISTS history_annotations_semantic ON history_annotations(machine,kind,name,start_time);
29
+
30
+ -- Invoker privileges, transactional caller fencing and original annotation extents are preserved.
31
+ CREATE OR REPLACE FUNCTION history_apply_correction(p_work UUID,p_machine TEXT,p_scale INTEGER,p_converged BOOLEAN)
32
+ RETURNS INTEGER LANGUAGE plpgsql AS $$
33
+ DECLARE w history_work%ROWTYPE; item history_corrections%ROWTYPE; owner history_annotations%ROWTYPE;
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'];
36
+ BEGIN
37
+ SELECT * INTO STRICT w FROM history_work WHERE id=p_work AND machine=p_machine;
38
+ IF p_converged THEN
39
+ FOR item IN SELECT * FROM history_corrections WHERE work_id=w.id AND generation=w.generation AND duration=0 LOOP
40
+ SELECT * INTO tail FROM segments WHERE machine=p_machine AND kind=item.kind AND name=item.name
41
+ AND start_time<=item.end_time AND end_time>item.end_time ORDER BY end_time DESC LIMIT 1;
42
+ IF FOUND THEN
43
+ UPDATE history_corrections SET end_time=tail.end_time,
44
+ duration=CASE WHEN tail.duration=0 THEN 0 ELSE extract(epoch FROM tail.end_time-item.start_time) END
45
+ WHERE work_id=w.id AND generation=w.generation AND kind=item.kind AND start_time=item.start_time;
46
+ END IF;
47
+ END LOOP;
48
+ END IF;
49
+ lo := 'epoch'::timestamptz+(w.correction_from/p_scale)*interval '1 millisecond';
50
+ hi := 'epoch'::timestamptz+(w.correction_until/p_scale)*interval '1 millisecond';
51
+ SELECT least(lo,COALESCE(min(start_time),lo)),greatest(hi,COALESCE(max(end_time),hi)) INTO lo,hi
52
+ FROM history_corrections WHERE work_id=w.id AND generation=w.generation;
53
+ INSERT INTO history_annotations(machine,kind,start_time,name,end_time,duration,tags,properties,resolved,consumed)
54
+ SELECT machine,kind,start_time,name,end_time,duration,tags,properties,resolved,consumed FROM segments
55
+ WHERE machine=p_machine AND kind='phase' AND start_time<=hi AND end_time>=lo
56
+ ON CONFLICT(machine,kind,start_time,name) DO UPDATE SET end_time=greatest(history_annotations.end_time,EXCLUDED.end_time),
57
+ duration=EXCLUDED.duration,tags=EXCLUDED.tags,properties=EXCLUDED.properties,resolved=EXCLUDED.resolved,consumed=EXCLUDED.consumed;
58
+ UPDATE segments SET end_time=lo,duration=greatest(0,extract(epoch FROM lo-start_time)),updated_at=clock_timestamp()
59
+ WHERE machine=p_machine AND kind='phase' AND start_time<lo AND end_time>lo;
60
+ DELETE FROM segments WHERE machine=p_machine AND kind='phase' AND start_time>=lo
61
+ AND (start_time<hi OR (start_time=hi AND end_time=hi));
62
+ FOR item IN SELECT * FROM history_corrections WHERE work_id=w.id AND generation=w.generation ORDER BY start_time LOOP
63
+ SELECT EXISTS(SELECT 1 FROM history_annotations WHERE machine=p_machine AND kind=item.kind AND name=item.name
64
+ AND start_time=item.end_time AND end_time=item.end_time) INTO endpoint_cut;
65
+ a := item.start_time;
66
+ FOR b IN SELECT cut FROM (
67
+ SELECT start_time AS cut FROM history_annotations WHERE machine=p_machine AND kind=item.kind
68
+ AND start_time>item.start_time AND start_time<item.end_time
69
+ UNION SELECT item.end_time
70
+ ) boundaries ORDER BY cut LOOP
71
+ SELECT * INTO owner FROM history_annotations WHERE machine=p_machine AND kind=item.kind AND name=item.name
72
+ AND start_time<=a AND start_time<=item.end_time AND end_time>=item.start_time ORDER BY start_time DESC LIMIT 1;
73
+ IF NOT FOUND THEN
74
+ SELECT * INTO owner FROM history_annotations WHERE machine=p_machine AND kind=item.kind AND name=item.name
75
+ AND start_time>a AND start_time<=item.end_time AND end_time>=item.start_time ORDER BY start_time LIMIT 1;
76
+ END IF;
77
+ incoming := COALESCE(NULLIF(NULLIF(item.properties,''),'null')::jsonb,'{}'::jsonb);
78
+ inherited := COALESCE(NULLIF(NULLIF(owner.properties,''),'null')::jsonb,'{}'::jsonb);
79
+ IF jsonb_typeof(incoming)<>'object' THEN incoming:='{}'::jsonb; END IF;
80
+ IF jsonb_typeof(inherited)<>'object' THEN inherited:='{}'::jsonb; END IF;
81
+ INSERT INTO segments(machine,kind,name,start_time,end_time,duration,options,tags,properties,resolved,consumed,updated_at)
82
+ 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,
83
+ item.options,COALESCE(owner.tags,item.tags),(incoming||(inherited-keys))::text,COALESCE(owner.resolved,item.resolved),COALESCE(owner.consumed,true),clock_timestamp())
84
+ ON CONFLICT(machine,kind,start_time) DO UPDATE SET name=EXCLUDED.name,end_time=EXCLUDED.end_time,duration=EXCLUDED.duration,
85
+ options=EXCLUDED.options,tags=EXCLUDED.tags,properties=EXCLUDED.properties,resolved=EXCLUDED.resolved,consumed=EXCLUDED.consumed,updated_at=EXCLUDED.updated_at;
86
+ inserted:=inserted+1; a:=b;
87
+ END LOOP;
88
+ -- A real user cut at the final singleton is retained; ordinary heartbeat ends are not cuts.
89
+ IF item.start_time<item.end_time AND endpoint_cut THEN
90
+ SELECT * INTO owner FROM history_annotations WHERE machine=p_machine AND kind=item.kind AND name=item.name AND start_time=item.end_time;
91
+ incoming := COALESCE(NULLIF(NULLIF(item.properties,''),'null')::jsonb,'{}'::jsonb);
92
+ inherited := COALESCE(NULLIF(NULLIF(owner.properties,''),'null')::jsonb,'{}'::jsonb);
93
+ IF jsonb_typeof(incoming)<>'object' THEN incoming:='{}'::jsonb; END IF;
94
+ IF jsonb_typeof(inherited)<>'object' THEN inherited:='{}'::jsonb; END IF;
95
+ INSERT INTO segments(machine,kind,name,start_time,end_time,duration,options,tags,properties,resolved,consumed)
96
+ 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))
97
+ ON CONFLICT(machine,kind,start_time) DO NOTHING;
98
+ END IF;
99
+ END LOOP;
100
+ INSERT INTO history_checkpoints(machine,classifier_key,time_ms,state,valid)
101
+ SELECT machine,classifier_key,time_ms,state,true FROM history_staged_checkpoints WHERE work_id=w.id AND generation=w.generation
102
+ ON CONFLICT(machine,classifier_key,time_ms) DO UPDATE SET state=EXCLUDED.state,valid=true;
103
+ RETURN inserted;
104
+ END $$;
@@ -0,0 +1,5 @@
1
+ GRANT SELECT, INSERT, UPDATE, DELETE ON history_corrections TO supervisor_sink;
2
+ GRANT SELECT, INSERT, UPDATE, DELETE ON history_staged_checkpoints TO supervisor_sink;
3
+ GRANT SELECT, INSERT, UPDATE, DELETE ON segments TO supervisor_sink;
4
+ REVOKE ALL ON FUNCTION history_apply_correction(UUID,TEXT,INTEGER,BOOLEAN) FROM PUBLIC;
5
+ GRANT EXECUTE ON FUNCTION history_apply_correction(UUID,TEXT,INTEGER,BOOLEAN) TO supervisor_sink;
@@ -0,0 +1,7 @@
1
+ -- O(number of raw backends), never a registry of measurements.
2
+ CREATE TABLE IF NOT EXISTS history_retention (
3
+ source_id TEXT PRIMARY KEY,
4
+ retained_from BIGINT NOT NULL
5
+ );
6
+ ALTER TABLE history_admissions ADD COLUMN IF NOT EXISTS admitted_at BIGINT;
7
+ ALTER TABLE history_annotations ADD COLUMN IF NOT EXISTS consumed BOOLEAN DEFAULT true;
@@ -0,0 +1 @@
1
+ GRANT SELECT, INSERT, UPDATE ON history_retention TO supervisor_sink;
package/index.js CHANGED
@@ -46,6 +46,11 @@ export { default as pgTimeline } from './src/infrastructure/persistence/pg/timel
46
46
  export { default as pgAlerts } from './src/infrastructure/persistence/pg/alerts.js';
47
47
  export { default as pgOperations } from './src/infrastructure/persistence/pg/operations.js';
48
48
  export { default as clickhouseConnection } from './src/infrastructure/persistence/clickhouse/connection.js';
49
+ export { rawMetricsRange as clickhouseMetricsRawRange } from './src/infrastructure/persistence/clickhouse/metricsRelation.js';
50
+ export { rawMetricsRelation as clickhouseMetricsRawRelation } from './src/infrastructure/persistence/clickhouse/metricsRelation.js';
51
+ export { default as clickhouseMetricsRelation } from './src/infrastructure/persistence/clickhouse/metricsRelation.js';
52
+ export const centralTelemetryVersion = 4;
53
+ export { default as centralTelemetryPolicy } from './src/infrastructure/ingest/telemetry/centralPolicy.js';
49
54
  export { default as clickhouseSensor } from './src/infrastructure/persistence/clickhouse/sensor.js';
50
55
  export { default as postgresPool } from './src/infrastructure/persistence/postgresPool.js';
51
56
  export { metricsSinkFromPool as pgMetricsSink } from './src/infrastructure/persistence/pg/metrics.js';
@@ -107,3 +112,5 @@ export { default as executeRelease } from './src/infrastructure/deploy/executeRe
107
112
  export { default as collectorProcesses } from './src/application/deploy/collectorProcesses.js';
108
113
 
109
114
  export { default as executeStages } from './src/infrastructure/deploy/executeStages.js';
115
+
116
+ export { default as historyPg, historyProtocol } from './src/infrastructure/persistence/pg/history.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yarkivaev/scada",
3
- "version": "2.5.8",
3
+ "version": "2.6.0",
4
4
  "description": "SCADA domain objects, state persistence, and plant monitoring",
5
5
  "repository": {
6
6
  "type": "git",
@@ -19,12 +19,14 @@
19
19
  "./opcua": "./src/infrastructure/opcua/index.js",
20
20
  "./opcua/config": "./src/infrastructure/opcua/config.js",
21
21
  "./runtime": "./src/application/runtime/index.js",
22
- "./streams": "./src/infrastructure/streams/index.js"
22
+ "./streams": "./src/infrastructure/streams/index.js",
23
+ "./control": "./src/application/control/index.js"
23
24
  },
24
25
  "bin": {
25
26
  "modbus-to-mqtt": "./src/bin/modbus-to-mqtt.js",
26
27
  "supervisor-sink": "./src/bin/supervisor-sink.js",
27
- "scada-collector": "./src/bin/collector.js"
28
+ "scada-collector": "./src/bin/collector.js",
29
+ "scada-controller": "./src/bin/controller.js"
28
30
  },
29
31
  "scripts": {
30
32
  "test": "mocha --exit 'test/**/test*.js'",
@@ -0,0 +1,61 @@
1
+ import executionSnapshot, { remoteSnapshot, remoteStatus } from './executionSnapshot.js';
2
+ import localAssignment from './localAssignment.js';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { checkSnapshot, loadSnapshot, saveSnapshot } from './snapshotFile.js';
5
+ async function applyTasks(runtime,snapshot,nodeId,onError) {
6
+ const ids=new Set(snapshot.assignments.map((row)=>{return row.taskId;}));
7
+ const removals=runtime.status().tasks.filter((row)=>{return !ids.has(row.taskId);});
8
+ const operations=[...removals.map((row)=>{return ()=>{return runtime.remove({taskId:row.taskId,generation:Math.max(snapshot.localGeneration,row.generation??0)});};}),
9
+ ...snapshot.assignments.map((row)=>{return ()=>{return runtime.apply(localAssignment({...row,generation:snapshot.executionGenerations[row.taskId]},nodeId));};})];
10
+ let applied=true;
11
+ for (const operation of operations) {
12
+ // One unavailable source must not prevent independent assignments from starting.
13
+ // eslint-disable-next-line no-await-in-loop
14
+ try {await operation();} catch(error) {applied=false; onError(error);}
15
+ }
16
+ return applied;
17
+ }
18
+ /** Control connectivity never determines whether the saved assignment may execute. */
19
+ export default function assignmentAgent({ nodeId, file, store, runtime, validate, intervalMs = 5000, onError = () => {
20
+ // Optional diagnostic sink.
21
+ } }) {
22
+ if (!nodeId || !file) { throw new TypeError('Control node id and assignment file required'); }
23
+ const state = { desired: null, appliedGeneration: null, stopped: false, timer: null, pending: null, sequence: 0, bootId: randomUUID() };
24
+ // Serialized by tick and startup; mutations cannot overlap.
25
+ /* eslint-disable require-atomic-updates */
26
+ async function reconcile(input, restored = false) {
27
+ checkSnapshot(input);
28
+ await validate(remoteSnapshot(input));
29
+ const snapshot = executionSnapshot(input, state.desired, runtime.status().tasks, restored);
30
+ if (snapshot !== state.desired) {
31
+ await saveSnapshot(file, snapshot);
32
+ state.desired = snapshot;
33
+ }
34
+ const applied=await applyTasks(runtime,snapshot,nodeId,onError);
35
+ state.appliedGeneration=applied?snapshot.generation:null;
36
+ }
37
+ async function once() {
38
+ if (state.stopped) { return; }
39
+ let snapshot=state.desired;
40
+ try {snapshot=await store.assignment(nodeId)??snapshot;} catch(error) {onError(error);}
41
+ try {if(!state.stopped&&snapshot){await reconcile(snapshot);}} catch(error) {onError(error);}
42
+ try {
43
+ if (!state.stopped) { state.sequence += 1; await store.report(nodeId, { nodeId, bootId: state.bootId, sequence: state.sequence, receivedAt: Date.now(), receivedGeneration: state.desired?.generation ?? null, appliedGeneration: state.appliedGeneration, controlEpoch: state.desired?.controlEpoch ?? 'initial', ...remoteStatus(runtime.status(), state.desired) }); }
44
+ } catch (error) { onError(error); }
45
+ }
46
+ function tick() {
47
+ state.pending ??= once().finally(() => { state.pending = null; });
48
+ return state.pending;
49
+ }
50
+ return {
51
+ tick,
52
+ status() { return { hasAssignment: Boolean(state.desired), appliedGeneration: state.appliedGeneration }; },
53
+ async start({ waitForInitialTick = true } = {}) {
54
+ const saved = await loadSnapshot(file);
55
+ if (saved) { await reconcile(saved, true); }
56
+ if (waitForInitialTick) { await tick(); } else { void tick().catch(onError); }
57
+ state.timer = setInterval(() => { void tick(); }, intervalMs);
58
+ },
59
+ async stop() { state.stopped = true; clearInterval(state.timer); await state.pending; }
60
+ };
61
+ }
@@ -0,0 +1,22 @@
1
+ const identifier = /^[\w.:-]{1,200}$/u;
2
+ export default function validateCatalog(catalog) {
3
+ if (!catalog || typeof catalog.version !== 'string' || (catalog.controlEpoch !== undefined && (typeof catalog.controlEpoch !== 'string' || !catalog.controlEpoch.length)) || !Array.isArray(catalog.nodes) || !Array.isArray(catalog.tasks)) {
4
+ throw new TypeError('Invalid control catalog');
5
+ }
6
+ const nodes = new Set();
7
+ for (const node of catalog.nodes) {
8
+ if (typeof node.id !== 'string' || !identifier.test(node.id) || nodes.has(node.id) || !Number.isFinite(node.capacity) || node.capacity <= 0) { throw new TypeError('Invalid control node'); }
9
+ nodes.add(node.id);
10
+ }
11
+ const tasks = new Set();
12
+ for (const task of catalog.tasks) {
13
+ if (typeof task.taskId !== 'string' || tasks.has(task.taskId) || !task.spec?.adapter || !Number.isSafeInteger(task.copies ?? 2) || (task.copies ?? 2) < 1
14
+ || !Number.isFinite(task.cost ?? 1) || (task.cost ?? 1) <= 0 || (task.pinnedNode && !nodes.has(task.pinnedNode))
15
+ || (task.eligibleNodes && (!Array.isArray(task.eligibleNodes) || task.eligibleNodes.some((id) => { return !nodes.has(id); })))) {
16
+ throw new TypeError('Invalid control task');
17
+ }
18
+ if ((task.spec.adapter === 'serial' || String(task.spec.from ?? '').startsWith('rtu:')) && !task.pinnedNode) { throw new TypeError('Serial task requires pinnedNode'); }
19
+ tasks.add(task.taskId);
20
+ }
21
+ return catalog;
22
+ }
@@ -0,0 +1,75 @@
1
+ import http from 'node:http';
2
+ import https from 'node:https';
3
+ import { readFileSync } from 'node:fs';
4
+ function request(endpoint, route, body, options) {
5
+ return new Promise((resolve, reject) => {
6
+ const target = new URL(route, endpoint);
7
+ const transport = target.protocol === 'https:' ? https : http;
8
+ const req = transport.request(target, { method: 'POST', ...options.tls, headers: { 'content-type': 'application/json', ...(options.token && { Authorization: options.token }) } }, (res) => {
9
+ const chunks = [];
10
+ let bytes = 0;
11
+ res.on('data', (chunk) => {
12
+ bytes += chunk.length;
13
+ if (bytes > options.maxBytes) { req.destroy(new Error('Control response capacity exceeded')); } else { chunks.push(chunk); }
14
+ });
15
+ res.on('error', reject);
16
+ res.on('end', () => {
17
+ try {
18
+ const value = JSON.parse(Buffer.concat(chunks).toString());
19
+ if (res.statusCode !== 200 || value.error) { const error = new Error('Control request rejected'); error.gatewayCode = value.code; error.statusCode = res.statusCode; reject(error); } else { resolve(value); }
20
+ } catch { reject(new Error('Invalid control response')); }
21
+ });
22
+ });
23
+ const timer = setTimeout(() => { req.destroy(new Error('Control request deadline')); }, options.timeoutMs);
24
+ req.on('error', reject);
25
+ req.on('close', () => { clearTimeout(timer); });
26
+ req.end(JSON.stringify(body));
27
+ });
28
+ }
29
+ function authenticated(send, username, password) {
30
+ const state = { token: null, expiresAt: 0, pending: null };
31
+ function token() {
32
+ if (state.token && Date.now() < state.expiresAt) { return state.token; }
33
+ state.pending ??= send('/v3/auth/authenticate', { name: username, password }).then((result) => {
34
+ if (typeof result.token !== 'string' || !result.token) { throw new Error('Control authentication rejected'); }
35
+ Object.assign(state, { token: result.token, expiresAt: Date.now() + 60000 });
36
+ return result.token;
37
+ }).finally(() => { state.pending = null; });
38
+ return state.pending;
39
+ }
40
+ return async (route, body) => {
41
+ const current = await token();
42
+ try { return await send(route, body, current); } catch (error) {
43
+ if (Number(error.gatewayCode) !== 16 && error.statusCode !== 401) { throw error; }
44
+ if (state.token === current) { Object.assign(state, { token: null, expiresAt: 0 }); }
45
+ return send(route, body, await token());
46
+ }
47
+ };
48
+ }
49
+ export default function controlClient({ endpoints, timeoutMs = 2000, maxBytes = 8388608, tls = {}, username, password }) {
50
+ if (!Array.isArray(endpoints) || !endpoints.length || endpoints.some((endpoint) => { return !['http:', 'https:'].includes(new URL(endpoint).protocol); })) { throw new TypeError('Control endpoints required'); }
51
+ if ((username !== undefined || password !== undefined) && (typeof username !== 'string' || !username || typeof password !== 'string' || !password)) {
52
+ throw new TypeError('Complete control credentials required');
53
+ }
54
+ let cursor = 0;
55
+ async function send(route, body, token) {
56
+ for (let index = 0; index < endpoints.length; index += 1) {
57
+ try {
58
+ // eslint-disable-next-line no-await-in-loop
59
+ return await request(endpoints[cursor], route, body, { timeoutMs, maxBytes, tls, token });
60
+ } catch (error) {
61
+ cursor = (cursor + 1) % endpoints.length;
62
+ if (index === endpoints.length - 1) { throw error; }
63
+ }
64
+ }
65
+ throw new Error('No control endpoints');
66
+ }
67
+ return username === undefined ? send : authenticated(send, username, password);
68
+ }
69
+ export function clientFromEnv(env, prefix = 'CONTROL') {
70
+ const tls = {};
71
+ for (const [name, key] of [['CA', 'ca'], ['CERT', 'cert'], ['KEY', 'key']]) {
72
+ if (env[`${prefix}_${name}`]) { tls[key] = readFileSync(env[`${prefix}_${name}`]); }
73
+ }
74
+ return controlClient({ endpoints: (env[`${prefix}_ENDPOINTS`] ?? '').split(',').filter(Boolean), tls, username: env[`${prefix}_USERNAME`], password: env[`${prefix}_PASSWORD`] });
75
+ }
@@ -0,0 +1,55 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import validateCatalog from './catalog.js';
3
+ function encoded(value) { return Buffer.from(value).toString('base64'); }
4
+ function decoded(value) { return Buffer.from(value, 'base64').toString(); }
5
+ function put(key, value, lease) { return { request_put: { key: encoded(key), value: encoded(JSON.stringify(value)), ...(lease && { lease }) } }; }
6
+ function revision(key, value) { return { key: encoded(key), target: 'MOD', result: 'EQUAL', mod_revision: String(value) }; }
7
+ export default function controlStore(call, prefix = '/scada/control') {
8
+ const root = prefix.replace(/\/$/u, '');
9
+ const lock = `${root}/leader`;
10
+ const session = randomUUID();
11
+ async function range(key) { const result = await call('/v3/kv/range', { key: encoded(key) }); return result.kvs?.[0] ?? null; }
12
+ return {
13
+ async acquire() {
14
+ const grant = await call('/v3/lease/grant', { TTL: '15' });
15
+ const previous = await range(lock);
16
+ const own = previous && decoded(previous.value) === JSON.stringify(session);
17
+ const compare = own ? revision(lock, previous.mod_revision) : { key: encoded(lock), target: 'VERSION', result: 'EQUAL', version: '0' };
18
+ const result = await call('/v3/kv/txn', { compare: [compare], success: [put(lock, session, grant.ID)], failure: [] });
19
+ return result.succeeded ? { session, lease: grant.ID } : null;
20
+ },
21
+ async read() {
22
+ const result = await call('/v3/kv/range', { key: encoded(`${root}/`), range_end: encoded(`${root}0`) });
23
+ const view = { catalog: null, reports: [], assignments: {}, revisions: {} };
24
+ for (const row of result.kvs ?? []) {
25
+ const key = decoded(row.key).slice(root.length + 1);
26
+ const value = JSON.parse(decoded(row.value));
27
+ view.revisions[key] = row.mod_revision;
28
+ if (key === 'catalog') { view.catalog = value; }
29
+ if (key.startsWith('reports/')) { view.reports.push(value); }
30
+ if (key.startsWith('assignments/')) { view.assignments[key.slice(12)] = value; }
31
+ }
32
+ return view;
33
+ },
34
+ async commit(token, view, assignments) {
35
+ const compare = [{ key: encoded(lock), target: 'VALUE', result: 'EQUAL', value: encoded(JSON.stringify(token.session)) },
36
+ { key: encoded(lock), target: 'LEASE', result: 'EQUAL', lease: token.lease },
37
+ ...Object.entries(view.revisions).filter(([key]) => { return key !== 'leader'; }).map(([key, value]) => { return revision(`${root}/${key}`, value); })];
38
+ const changes = Object.entries(assignments).filter(([id, value]) => { return JSON.stringify(value) !== JSON.stringify(view.assignments[id]); });
39
+ if (!changes.length) { return true; }
40
+ const result = await call('/v3/kv/txn', { compare, success: changes.map(([id, value]) => { return put(`${root}/assignments/${id}`, value); }), failure: [] });
41
+ return Boolean(result.succeeded);
42
+ },
43
+ async assignment(id) { const row = await range(`${root}/assignments/${id}`); return row ? JSON.parse(decoded(row.value)) : null; },
44
+ report(id, value) { return call('/v3/kv/put', put(`${root}/reports/${id}`, value).request_put); },
45
+ async publish(catalog, expectedRevision) {
46
+ validateCatalog(catalog);
47
+ const key = `${root}/catalog`;
48
+ const existing = await range(key);
49
+ const expected = expectedRevision ?? existing?.mod_revision ?? '0';
50
+ const result = await call('/v3/kv/txn', { compare: [revision(key, expected)], success: [put(key, catalog)], failure: [] });
51
+ if (!result.succeeded) { throw new Error('Catalog publication conflict'); }
52
+ return { accepted: true, revision: result.header.revision, catalogVersion: catalog.version };
53
+ }
54
+ };
55
+ }