@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
@@ -0,0 +1,51 @@
1
+ function keys(value, allowed) {
2
+ if (!value || typeof value !== 'object' || Array.isArray(value)
3
+ || Object.keys(value).some((key) => { return !allowed.includes(key); })) {
4
+ throw new TypeError('Invalid central telemetry policy');
5
+ }
6
+ }
7
+ function positive(value, name, maximum = Number.MAX_SAFE_INTEGER) {
8
+ if (!Number.isSafeInteger(value) || value < 1 || value > maximum) { throw new TypeError(`Invalid central policy ${name}`); }
9
+ return value;
10
+ }
11
+ const ruleDefaults = { compactWindowMs: 60000, historyWindowMs: 604800000, maxHistoryAgeMs: 2592000000, futureSkewMs: 300000, maxGapMs: 30000 };
12
+ export const CENTRAL_RULE_FIELDS = Object.keys(ruleDefaults);
13
+ export function centralRule(value, fallback = ruleDefaults) {
14
+ keys(value, [...CENTRAL_RULE_FIELDS, 'topic']);
15
+ const rule = Object.fromEntries(CENTRAL_RULE_FIELDS.map((key) => { return [key, value[key] === undefined ? fallback[key] : value[key]]; }));
16
+ for (const [key, number] of Object.entries(rule)) {
17
+ let minimum = Math.max(1, rule.compactWindowMs);
18
+ if (key === 'maxGapMs') { minimum = 1; }
19
+ if (['compactWindowMs', 'futureSkewMs'].includes(key)) { minimum = 0; }
20
+ const maximum = key === 'compactWindowMs' ? 3600000 : Number.MAX_SAFE_INTEGER;
21
+ if (!Number.isSafeInteger(number) || number < minimum || number > maximum) { throw new TypeError(`Invalid central policy ${key}`); }
22
+ }
23
+ return rule;
24
+ }
25
+ /** Native point storage with a bounded immutable archive. */
26
+ export default function centralPolicy(input = {}) {
27
+ const config = typeof input === 'string' ? JSON.parse(input) : input;
28
+ keys(config, ['enabled', 'default', 'topics', 'queue', 'queueMaxBytes', 'maxPendingBatches', 'batchSize']);
29
+ if (config.enabled !== undefined && typeof config.enabled !== 'boolean') { throw new TypeError('Invalid central policy enabled'); }
30
+ keys(config.default ?? {}, CENTRAL_RULE_FIELDS);
31
+ const defaults = centralRule(config.default ?? {});
32
+ if (!Array.isArray(config.topics ?? [])) { throw new TypeError('Invalid central policy topics'); }
33
+ const topics = new Map();
34
+ (config.topics ?? []).forEach((entry) => {
35
+ keys(entry, ['topic', ...CENTRAL_RULE_FIELDS]);
36
+ if (typeof entry.topic !== 'string' || !entry.topic || entry.topic.length > 1024
37
+ // eslint-disable-next-line no-control-regex
38
+ || /[\s\u0000-\u001f\u007f#+*]/u.test(entry.topic) || topics.has(entry.topic)) {
39
+ throw new TypeError('Invalid or duplicate central policy topic');
40
+ }
41
+ topics.set(entry.topic, centralRule(entry, defaults));
42
+ });
43
+ const queue = config.queue ?? 'scada.telemetry.canonical';
44
+ if (typeof queue !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,254}$/u.test(queue) || queue.startsWith('amq.')) {
45
+ throw new TypeError('Invalid central policy queue');
46
+ }
47
+ return { enabled: config.enabled === true, queue, forTopic(topic) { return topics.get(topic) ?? defaults; },
48
+ queueMaxBytes: positive(config.queueMaxBytes ?? 1073741824, 'queue bytes'),
49
+ maxPendingBatches: positive(config.maxPendingBatches ?? 100000, 'pending batches', 2147483647),
50
+ batchSize: positive(config.batchSize ?? 500, 'batch size', 1000) };
51
+ }
@@ -0,0 +1,29 @@
1
+ /* eslint-disable no-await-in-loop */
2
+ import amqpSource from '../../streams/amqpSource.js';
3
+ import { decodeBatch, MAX_BATCH_BYTES } from './centralEnvelope.js';
4
+
5
+ export function centralQueueOptions(policy) {
6
+ return {durable:true,autoDelete:false,arguments:{
7
+ 'x-queue-type':'classic','x-single-active-consumer':true,'x-max-length':policy.maxPendingBatches,
8
+ 'x-max-length-bytes':policy.queueMaxBytes,'x-overflow':'reject-publish'
9
+ }};
10
+ }
11
+
12
+ /** One unacknowledged envelope prevents a later conflict overtaking a failed head. */
13
+ export default function centralQueueSession(settings, projection, diagnostics) {
14
+ return amqpSource(settings.url, settings.queue, {
15
+ async accept(delivery) {
16
+ while(delivery.active()) {
17
+ try {
18
+ const { records, admittedAt, batchId } = decodeBatch(delivery.content,settings.target);
19
+ await projection.write(records,{admittedAt,batchId,active:delivery.active});
20
+ diagnostics.accepted?.();return;
21
+ } catch(error) {
22
+ diagnostics.failed(error);
23
+ await new Promise((resolve) => {setTimeout(resolve,250);});
24
+ }
25
+ }
26
+ }
27
+ }, { queueOptions:settings.queueOptions,prefetch:1,exclusive:false,maxMessageBytes:MAX_BATCH_BYTES,maxPendingBytes:MAX_BATCH_BYTES,
28
+ preserveOnCapacity:true,stopTimeoutMs:120000,onError:diagnostics.failed,...(settings.connect&&{connect:settings.connect}) });
29
+ }
@@ -0,0 +1,31 @@
1
+ import { createClient } from '@clickhouse/client';
2
+ import amqp from 'amqplib';
3
+ import centralPolicy from './centralPolicy.js';
4
+
5
+ async function queueExists(url,queue) {
6
+ const connection = await amqp.connect(url,{timeout:5000});
7
+ const channel = await connection.createChannel();
8
+ channel.on('error',() => { return undefined; });
9
+ try {
10
+ try { await channel.checkQueue(queue); return true; }
11
+ catch (error) { if (error.code !== 404) { throw error; } return false; }
12
+ } finally { await connection.close(); }
13
+ }
14
+ async function activated(url) {
15
+ const client = createClient({url,request_timeout:10000});
16
+ try {
17
+ const result = await client.query({query:"SELECT name FROM system.tables WHERE database='scada' AND name IN ('metrics_points_v4','metrics_points_v3','metrics_compact_v2','metrics_canonical')",format:'JSONEachRow'});
18
+ return (await result.json()).length>0;
19
+ } finally { await client.close(); }
20
+ }
21
+ /** A persistent queue or table pins activation even before the first insertion. */
22
+ export default async function centralTelemetryPreflight(env) {
23
+ const policy = centralPolicy(env.CENTRAL_TELEMETRY_POLICY ?? {});
24
+ if (policy.enabled) { return; }
25
+ if (env.CENTRAL_TELEMETRY_POLICY && !env.AMQP_URL) { throw new Error('Disabled explicit central policy requires AMQP_URL to check canonical activation'); }
26
+ const url = env.CLICKHOUSE_URL || (env.CLICKHOUSE_HOST ? `http://${env.CLICKHOUSE_HOST}:8123` : undefined);
27
+ if (!url) { return; }
28
+ if (await activated(url) || (env.AMQP_URL && await queueExists(env.AMQP_URL,policy.queue))) {
29
+ throw new Error('Central telemetry policy cannot be disabled after canonical queue or table activation');
30
+ }
31
+ }
@@ -12,6 +12,9 @@
12
12
  */
13
13
  export default function foldingSink(inner, fold, locate) {
14
14
  return {
15
+ requireTimestamp: inner.requireTimestamp,
16
+ start() { return inner.start?.(); },
17
+ status() { return inner.status?.(); },
15
18
  stop() { return inner.stop?.(); },
16
19
  async write(records, context = {}) {
17
20
  context.signal?.throwIfAborted();
@@ -0,0 +1,32 @@
1
+ import amqpSource from '../../streams/amqpSource.js';
2
+ import { metricsSinkFromPool } from '../../persistence/pg/metrics.js';
3
+ import deliverToMqttRecord from './deliverToMqttRecord.js';
4
+
5
+ /** Source acknowledgement follows this promise: telemetry and history work commit first. */
6
+ export async function persistTelemetry(sink, delivery) {
7
+ const record = deliverToMqttRecord(delivery.fields, delivery.content);
8
+ let point;
9
+ try { point = JSON.parse(record.payload.toString()); } catch { throw new TypeError('Invalid local telemetry JSON'); }
10
+ if (!point || !Number.isSafeInteger(point.ts) || !Number.isFinite(point.value)) { throw new TypeError('Invalid local telemetry timestamp or value'); }
11
+ await sink.write([{ topic: record.topic, ts: point.ts, value: point.value }]);
12
+ }
13
+ /** Node-owned receiver; independent of relocatable collectors and MQTT sessions. */
14
+ export default function historyTelemetry(env, pool) {
15
+ if (env.HISTORY_AMQP_ENABLED !== 'true' || env.SINK_DB_PROFILE === 'central') { return undefined; }
16
+ if (env.TELEMETRY_BACKEND === 'clickhouse') { throw new TypeError('ClickHouse telemetry requires the coordinated history receiver'); }
17
+ const url = env.HISTORY_AMQP_URL ?? env.AMQP_URL;
18
+ if (!url) { throw new TypeError('HISTORY_AMQP_URL or AMQP_URL required for durable local telemetry'); }
19
+ if (!env.HISTORY_AMQP_BINDINGS) { throw new TypeError('Explicit local telemetry bindings required'); }
20
+ const bindings = JSON.parse(env.HISTORY_AMQP_BINDINGS);
21
+ if (!Array.isArray(bindings) || !bindings.length || bindings.some((pattern) => { return typeof pattern !== 'string' || !pattern; })) {
22
+ throw new TypeError('Local telemetry binding patterns required');
23
+ }
24
+ const sink = metricsSinkFromPool(pool, { firstWins: true });
25
+ return amqpSource(url, env.HISTORY_AMQP_QUEUE ?? 'scada.telemetry.history', {
26
+ accept(delivery) { return persistTelemetry(sink, delivery); }
27
+ }, {
28
+ prefetch: Number(env.HISTORY_AMQP_PREFETCH ?? 32), queueOptions: { durable: true, autoDelete: false },
29
+ exchanges: [{ name: 'scada.telemetry', type: 'topic', options: { durable: true } }],
30
+ bindings: bindings.map((pattern) => { return { exchange: 'scada.telemetry', pattern }; })
31
+ });
32
+ }
@@ -0,0 +1,26 @@
1
+ import {createClient} from '@clickhouse/client';
2
+ import metricsRelation,{rawMetricsRelation} from './metricsRelation.js';
3
+ import nativeMetricsSchema from './nativeMetricsSchema.js';
4
+ import nativeMetricsOwnership from './nativeMetricsOwnership.js';
5
+ import nativeMetricsAdmission from './nativeMetricsAdmission.js';
6
+ import nativeMetricsCompaction from './nativeMetricsCompaction.js';
7
+ export {LEGACY_METRICS_SQL,NATIVE_METRICS_SQL} from './nativeMetricsSchema.js';
8
+ /** Only the serialized SAC head may use this admission writer. */
9
+ export default function canonicalMetrics(url,domain,options={}) {
10
+ const client=createClient({url,request_timeout:10000});let cleaning;let ready;let timer;
11
+ function runCompaction(){
12
+ cleaning??=nativeMetricsCompaction(client,options).finally(()=>{cleaning=undefined;});
13
+ return cleaning;
14
+ }
15
+ function start(context){
16
+ nativeMetricsOwnership(context);
17
+ ready??=nativeMetricsSchema(client,domain,metricsRelation,rawMetricsRelation).then(()=>{
18
+ nativeMetricsOwnership(context);
19
+ if((options.cleanupIntervalMs??30000)>0){timer=setInterval(()=>{runCompaction().catch(error=>{options.onCleanupError?.(error);});},options.cleanupIntervalMs??30000);timer.unref();}
20
+ }).catch(error=>{ready=undefined;throw error;});
21
+ return ready;
22
+ }
23
+ return {start,async write(records,context){await start(context);nativeMetricsOwnership(context);await nativeMetricsAdmission(client,records,context,options);},
24
+ async runCompaction(){await start();return runCompaction();},
25
+ async stop(){clearInterval(timer);if(cleaning){await Promise.allSettled([cleaning]);}await client.close();}};
26
+ }
@@ -1,3 +1,5 @@
1
+ import { metricsRange } from './metricsRelation.js';
2
+
1
3
  /**
2
4
  * Level changes of one ClickHouse metric, including the sample held at the start.
3
5
  *
@@ -18,13 +20,13 @@ function formatDateTime(date) {
18
20
 
19
21
  const CHANGES_SQL = `WITH prior AS (
20
22
  SELECT ts, value
21
- FROM scada.metrics
23
+ FROM scada.metrics_read
22
24
  WHERE topic = {topic:String} AND ts < {start:DateTime64(3)}
23
25
  ORDER BY ts DESC
24
26
  LIMIT 1
25
27
  ), windowed AS (
26
28
  SELECT ts, value
27
- FROM scada.metrics
29
+ FROM ${metricsRange('toUnixTimestamp64Milli({start:DateTime64(3)})', 'toUnixTimestamp64Milli({end:DateTime64(3)})')}
28
30
  WHERE topic = {topic:String}
29
31
  AND ts >= {start:DateTime64(3)}
30
32
  AND ts <= {end:DateTime64(3)}
@@ -18,11 +18,14 @@
18
18
  */
19
19
  import { createClient } from '@clickhouse/client';
20
20
 
21
+
22
+ import metricsQuery from './metricsQuery.js';
23
+
21
24
  export default async function clickhouseConnection(host, options = {}) {
22
25
  const port = options.port || 8123;
23
26
  const {username} = options;
24
27
  const {password} = options;
25
- const config = { url: `http://${host}:${port}` };
28
+ const config = { url: `http://${host}:${port}`, request_timeout: 10000 };
26
29
  if (username) {
27
30
  config.username = username;
28
31
  config.password = password || '';
@@ -40,13 +43,8 @@ export default async function clickhouseConnection(host, options = {}) {
40
43
  url() {
41
44
  return `http://${host}:${port}`;
42
45
  },
43
- async query(sql, params = {}) {
44
- const result = await client.query({
45
- query: sql,
46
- query_params: params,
47
- format: 'JSONEachRow'
48
- });
49
- return result.json();
46
+ query(sql, params = {}) {
47
+ return metricsQuery(client, sql, params);
50
48
  },
51
49
  async insert(table, rows) {
52
50
  await client.insert({ table, values: rows, format: 'JSONEachRow' });
@@ -1,3 +1,5 @@
1
+ import { holdsMetricsRange } from './metricsRelation.js';
2
+
1
3
  /**
2
4
  * Coverage holds of one ClickHouse metric.
3
5
  *
@@ -19,8 +21,8 @@ function formatDateTime(date) {
19
21
  }
20
22
 
21
23
  const HOLDS_SQL = `WITH windowed AS (
22
- SELECT ts, value
23
- FROM scada.metrics
24
+ SELECT ts, value, coverage_first_ms,coverage_last_ms
25
+ FROM ${holdsMetricsRange('toUnixTimestamp64Milli({start:DateTime64(3)})', 'toUnixTimestamp64Milli({end:DateTime64(3)})','{gap:UInt64}')}
24
26
  WHERE topic = {topic:String}
25
27
  AND ts >= {start:DateTime64(3)}
26
28
  AND ts < {end:DateTime64(3)}
@@ -28,17 +30,18 @@ const HOLDS_SQL = `WITH windowed AS (
28
30
  SELECT
29
31
  ts,
30
32
  value,
31
- lagInFrame(ts, 1) OVER (ORDER BY ts) AS prev_ts,
33
+ coverage_first_ms,coverage_last_ms,
34
+ lagInFrame(coverage_last_ms,1) OVER (ORDER BY ts) AS prev_last_ms,
32
35
  lagInFrame(toNullable(value), 1) OVER (ORDER BY ts) AS prev
33
36
  FROM windowed
34
37
  ), flagged AS (
35
38
  SELECT
36
39
  ts,
37
- value,
40
+ value,coverage_last_ms,
38
41
  if(
39
42
  prev IS NULL
40
43
  OR value != prev
41
- OR toUnixTimestamp64Milli(ts) - toUnixTimestamp64Milli(prev_ts) > {gap:UInt64},
44
+ OR coverage_first_ms - prev_last_ms > toInt64({gap:UInt64}),
42
45
  1,
43
46
  0
44
47
  ) AS fresh
@@ -46,11 +49,11 @@ const HOLDS_SQL = `WITH windowed AS (
46
49
  ), grouped AS (
47
50
  SELECT
48
51
  ts,
49
- value,
52
+ value,coverage_last_ms,
50
53
  sum(fresh) OVER (ORDER BY ts) AS grp
51
54
  FROM flagged
52
55
  )
53
- SELECT min(ts) AS started, max(ts) AS until, any(value) AS value
56
+ SELECT min(ts) AS started, fromUnixTimestamp64Milli(least(max(coverage_last_ms),toUnixTimestamp64Milli({end:DateTime64(3)}))) AS until, any(value) AS value
54
57
  FROM grouped
55
58
  GROUP BY grp
56
59
  ORDER BY started`;
@@ -8,7 +8,7 @@
8
8
  */
9
9
  export default async function clickhouseLatest(connection, topic, unit) {
10
10
  const rows = await connection.query(
11
- `SELECT ts, value FROM scada.metrics
11
+ `SELECT ts, value FROM scada.metrics_read
12
12
  WHERE topic = {topic:String}
13
13
  ORDER BY ts DESC LIMIT 1`,
14
14
  { topic }
@@ -0,0 +1,70 @@
1
+ import metricsRelation, { annotatedPoints, legacyChartRelation, rawMetricsRelation } from './metricsRelation.js';
2
+
3
+ function missing(error, name) {
4
+ return String(error.code) === '60' && String(error.message).includes(name);
5
+ }
6
+ function missingNative(error) {
7
+ return ['metrics_points_v4','metrics_state_v4'].some((name) => { return missing(error,name); });
8
+ }
9
+ async function query(client, sql, params) {
10
+ const result = await client.query({ query: sql, query_params: params, format: 'JSONEachRow' });
11
+ return result.json();
12
+ }
13
+ function densityChecks(sql) {
14
+ const checks = new Map();
15
+ let cleaned = sql;
16
+ for (const [marker, encoded] of sql.matchAll(/\/\*scada-density-range:(?<encoded>[^*]+)\*\//gu)) {
17
+ cleaned = cleaned.replaceAll(marker,'');
18
+ if (!checks.has(encoded)) {
19
+ const {since,until,gap} = JSON.parse(decodeURIComponent(encoded));
20
+ checks.set(encoded,`SELECT DISTINCT topic FROM (${annotatedPoints(since,until)})
21
+ WHERE (empty({scadaDensityTopics:Array(String)}) OR topic IN {scadaDensityTopics:Array(String)})
22
+ AND (valid_certificate OR (compactable AND island_n>2)) AND first_ts<last_ts
23
+ ${gap === undefined ? '' : `AND max_gap_ms>(${gap})`}
24
+ AND toUnixTimestamp64Milli(first_ts)<=(${until}) AND toUnixTimestamp64Milli(last_ts)>=(${since})`);
25
+ }
26
+ }
27
+ return {cleaned,checks:[...checks.values()]};
28
+ }
29
+ async function density(client, sql, params) {
30
+ const {cleaned,checks} = densityChecks(sql);
31
+ if (!checks.length) { return cleaned; }
32
+ // One bounded request protects all ranges; serial checks could outlive cleanup grace.
33
+ let unavailable;
34
+ try {
35
+ unavailable = await query(client,`/*scada-density-check*/SELECT topic FROM (${checks.join(' UNION ALL ')}) LIMIT 1`,
36
+ {...params,scadaDensityTopics:params.topics ?? (params.topic ? [params.topic] : [])});
37
+ } catch (error) {
38
+ if (!missingNative(error)) { throw error; }
39
+ return cleaned;
40
+ }
41
+ if (unavailable.length) {
42
+ const error = new Error('Exact sample density is unavailable in sealed compacted history; use canonical values or persisted classifications');
43
+ Object.assign(error,{code:'SCADA_HISTORY_DENSITY_UNAVAILABLE',status:409,statusCode:409});
44
+ throw error;
45
+ }
46
+ return cleaned;
47
+ }
48
+ async function legacyCompatible(client) {
49
+ const old = await query(client, "SELECT name FROM system.tables WHERE database='scada' AND name IN ('metrics_points_v3','metrics_state_v3','metrics_rejected_v3','metrics_canonical','metrics_compact_v2')", {});
50
+ if (old.some(row=>{return typeof row.name==='string';})) {
51
+ throw new Error('Previous canonical storage requires an explicit v4 migration; native gap evidence is unavailable');
52
+ }
53
+ }
54
+ /** Read-only upgrades precede writer installation; only absent additive schema falls back. */
55
+ export default async function metricsQuery(client, sql, params) {
56
+ const checked = await density(client,sql.replace(/\bscada\.metrics_raw_read\b/giu,rawMetricsRelation).replace(/\bscada\.metrics_read\b/giu,metricsRelation),params);
57
+ try { return await query(client, checked, params); }
58
+ catch (error) {
59
+ for (const [name, relation] of [['metrics_raw_read',rawMetricsRelation],['metrics_read',metricsRelation]]) {
60
+ const pattern = new RegExp(`\\bscada\\.${name}\\b`, 'giu');
61
+ if (missing(error,name) && pattern.test(checked)) { return metricsQuery(client,checked.replace(pattern,relation),params); }
62
+ }
63
+ if (missingNative(error)) {
64
+ let legacy = checked.replace(/\/\*scada-native-chart-range\*\/[\s\S]*?\/\*end-scada-native-chart-range\*\//gu, legacyChartRelation).replace(/\/\*scada-native-range\*\/[\s\S]*?\/\*end-scada-native-range\*\//gu, 'scada.metrics');
65
+ for (const relation of [rawMetricsRelation, metricsRelation]) { legacy = legacy.replaceAll(relation, 'scada.metrics'); }
66
+ if (legacy !== checked) { await legacyCompatible(client); return query(client, legacy, params); }
67
+ }
68
+ throw error;
69
+ }
70
+ }
@@ -0,0 +1,110 @@
1
+ import { nativeMetricIslandPoints, nativeMetricWindows } from './nativeMetricsCompaction.js';
2
+ import { effectiveNativePoints } from './nativeMetricPoints.js';
3
+
4
+ /** Ordinary native point rows. Never reconstruct or invent deleted observations. */
5
+ export const MAX_COMPACT_WINDOW_MS = 3600000;
6
+ function physical(since, until, expand = false) {
7
+ const bounds = since === undefined ? '' : ` WHERE ts>=fromUnixTimestamp64Milli((${since})-${expand ? MAX_COMPACT_WINDOW_MS : 0}) AND ts<=fromUnixTimestamp64Milli((${until})+${expand ? MAX_COMPACT_WINDOW_MS : 0})`;
8
+ return `SELECT topic,ts,value,compact_ms,max_gap_ms,revision,is_compacted,compact_first,compact_last,compacted_at FROM scada.metrics_points_v4 FINAL${bounds}`;
9
+ }
10
+ function stored(since,until,expand=false) {
11
+ return effectiveNativePoints(physical(since,until,expand),physical(since,until,true));
12
+ }
13
+ /** Nearest neighbors add at most two complete-window contexts, independently of maxGapMs. */
14
+ function chartStored(since,until) {
15
+ const source=`SELECT topic,ts,value,compact_ms,max_gap_ms,revision,is_compacted,compact_first,compact_last,compacted_at
16
+ FROM scada.metrics_points_v4 FINAL CROSS JOIN (
17
+ SELECT maxOrNullIf(toUnixTimestamp64Milli(ts),toUnixTimestamp64Milli(ts)<(${since})) AS before_ms,
18
+ minOrNullIf(toUnixTimestamp64Milli(ts),toUnixTimestamp64Milli(ts)>(${until})) AS after_ms
19
+ FROM scada.metrics_points_v4 FINAL WHERE topic={topic:String}
20
+ ) AS neighbors
21
+ WHERE topic={topic:String} AND (
22
+ ts>=fromUnixTimestamp64Milli((${since})-${MAX_COMPACT_WINDOW_MS}) AND ts<=fromUnixTimestamp64Milli((${until})+${MAX_COMPACT_WINDOW_MS})
23
+ OR ts>=fromUnixTimestamp64Milli(before_ms-${MAX_COMPACT_WINDOW_MS}) AND ts<=fromUnixTimestamp64Milli(before_ms+${MAX_COMPACT_WINDOW_MS})
24
+ OR ts>=fromUnixTimestamp64Milli(after_ms-${MAX_COMPACT_WINDOW_MS}) AND ts<=fromUnixTimestamp64Milli(after_ms+${MAX_COMPACT_WINDOW_MS}))`;
25
+ // One FINAL scan with disjunctive bounds returns each physical winner once, even where contexts overlap.
26
+ return effectiveNativePoints(source,source);
27
+ }
28
+ /** Full windows and complete certificates classify continuity before range clipping. */
29
+ export function annotatedPoints(since, until, source=stored(since, until, true)) {
30
+ const fields = ['topic','ts','value','compact_ms','max_gap_ms','window_start','window_ms','point_ms',
31
+ 'island_first_ms','island_last_ms','island_n','valid_certificate','raw_interiors']
32
+ .map(name=>{return `points.${name} AS ${name}`;}).join(',');
33
+ return `SELECT ${fields},
34
+ fromUnixTimestamp64Milli(points.island_first_ms) AS first_ts,fromUnixTimestamp64Milli(points.island_last_ms) AS last_ts,
35
+ w.compact_ms>0 AND w.max_gap_ms>0 AND NOT w.overlap AND ifNull(state.state_exists,0)=1
36
+ AND w.window_start+w.window_ms<=state.closed_before AND w.low=w.high
37
+ AND NOT (legacy.n>0 AND w.window_start<=legacy.last_ms AND w.window_start+w.window_ms>legacy.first_ms) AS compactable
38
+ FROM (${nativeMetricIslandPoints(source)}) AS points
39
+ INNER JOIN (${nativeMetricWindows(source)}) AS w ON points.topic=w.topic AND points.compact_ms=w.compact_ms
40
+ AND points.max_gap_ms=w.max_gap_ms AND points.window_start=w.window_start
41
+ LEFT JOIN (SELECT key,closed_before,1 AS state_exists FROM scada.metrics_state_v4 FINAL WHERE key!='') AS state
42
+ ON state.key=concat('topic:',points.topic)
43
+ LEFT JOIN (SELECT topic,min(toUnixTimestamp64Milli(ts)) AS first_ms,max(toUnixTimestamp64Milli(ts)) AS last_ms,count() AS n
44
+ FROM scada.metrics GROUP BY topic) AS legacy ON legacy.topic=points.topic`;
45
+ }
46
+ function relation(points) {
47
+ return `(SELECT topic,ts,argMin(value,priority) AS value FROM (
48
+ SELECT topic,ts,value,0 AS priority FROM scada.metrics
49
+ UNION ALL SELECT topic,ts,value,1 AS priority FROM (${points})
50
+ ) GROUP BY topic,ts)`;
51
+ }
52
+ function adaptive(since, until) {
53
+ return `SELECT topic,ts,value FROM (${annotatedPoints(since, until)}) WHERE NOT compactable OR ts=first_ts OR ts=last_ts`;
54
+ }
55
+ export const rawMetricsRelation = relation(`SELECT topic,ts,value FROM (${stored()})`);
56
+ export default relation(adaptive());
57
+ /** Public point ranges retain their three-column contract. */
58
+ export function metricsRange(since, until) {
59
+ return `/*scada-native-range*/${relation(adaptive(since, until))}/*end-scada-native-range*/`;
60
+ }
61
+ export function rawMetricsRange(since, until) {
62
+ const guard = encodeURIComponent(JSON.stringify({ since, until }));
63
+ return `/*scada-density-range:${guard}*//*scada-native-range*/${relation(`SELECT topic,ts,value FROM (${stored(since, until)})`)}/*end-scada-native-range*/`;
64
+ }
65
+ /** Legacy observations carry no certified coverage or native continuity promise. */
66
+ export const legacyChartRelation = `(SELECT topic,ts,value,toUnixTimestamp64Milli(ts) AS coverage_first_ms,
67
+ toUnixTimestamp64Milli(ts) AS coverage_last_ms,toUInt64(30000) AS max_gap_ms,toUInt8(0) AS native FROM scada.metrics)`;
68
+ /** Adjacent equal observations certify the short bridge across a storage-window boundary. */
69
+ function constantBridges(annotated,since,until,gap) {
70
+ return `SELECT bridge.topic AS topic,fromUnixTimestamp64Milli(arrayJoin(arrayDistinct([
71
+ greatest(prior_ms,toInt64(${since})),least(point_ms,toInt64(${until}))]))) AS ts,
72
+ value,prior_ms AS coverage_first_ms,point_ms AS coverage_last_ms,max_gap_ms,toUInt8(1) AS native
73
+ FROM (SELECT *,lagInFrame(point_ms,1) OVER (PARTITION BY topic ORDER BY ts) AS prior_ms,
74
+ lagInFrame(value,1) OVER (PARTITION BY topic ORDER BY ts) AS prior_value,
75
+ lagInFrame(compact_ms,1) OVER (PARTITION BY topic ORDER BY ts) AS prior_compact_ms,
76
+ lagInFrame(max_gap_ms,1) OVER (PARTITION BY topic ORDER BY ts) AS prior_gap_ms,
77
+ lagInFrame(window_start,1) OVER (PARTITION BY topic ORDER BY ts) AS prior_window_start
78
+ FROM (${annotated})) AS bridge
79
+ LEFT JOIN (SELECT topic,min(toUnixTimestamp64Milli(ts)) AS first_ms,max(toUnixTimestamp64Milli(ts)) AS last_ms,count() AS n
80
+ FROM scada.metrics GROUP BY topic) AS legacy ON legacy.topic=bridge.topic
81
+ WHERE max_gap_ms>0 AND max_gap_ms=prior_gap_ms AND compact_ms=prior_compact_ms
82
+ AND window_start!=prior_window_start AND value=prior_value AND point_ms>prior_ms
83
+ AND point_ms-prior_ms<=toInt64(max_gap_ms) AND prior_ms<=(${until}) AND point_ms>=(${since})
84
+ AND NOT (legacy.n>0 AND prior_ms<=legacy.last_ms AND point_ms>=legacy.first_ms)
85
+ ${gap===undefined ? '' : `AND point_ms-prior_ms<=toInt64(${gap})`}`;
86
+ }
87
+ /** Display vertices may clip a constant island, never the silence between islands. */
88
+ export function chartMetricsRange(since,until,gap) {
89
+ const annotated=annotatedPoints(since,until,chartStored(since,until));
90
+ const coverage=gap===undefined ? 'compactable' : `compactable AND max_gap_ms<=(${gap})`;
91
+ const columns=`topic,ts,value,if(${coverage},island_first_ms,point_ms) AS coverage_first_ms,if(${coverage},island_last_ms,point_ms) AS coverage_last_ms,max_gap_ms,toUInt8(1) AS native`;
92
+ const points=`SELECT ${columns} FROM (${annotated}) WHERE NOT compactable OR ts=first_ts OR ts=last_ts
93
+ UNION ALL SELECT topic,fromUnixTimestamp64Milli(arrayJoin(arrayDistinct([
94
+ greatest(island_first_ms,toInt64(${since})),least(island_last_ms,toInt64(${until}))]))) AS ts,
95
+ value,island_first_ms AS coverage_first_ms,island_last_ms AS coverage_last_ms,max_gap_ms,toUInt8(1) AS native
96
+ FROM (${annotated}) AS cover WHERE (${coverage}) AND cover.ts=cover.first_ts AND cover.island_first_ms<=(${until}) AND cover.island_last_ms>=(${since})
97
+ UNION ALL ${constantBridges(annotated,since,until,gap)}`;
98
+ return `/*scada-native-chart-range*/(SELECT topic,ts,
99
+ tupleElement(selected,1) AS value,tupleElement(selected,2) AS coverage_first_ms,
100
+ tupleElement(selected,3) AS coverage_last_ms,tupleElement(selected,4) AS max_gap_ms,tupleElement(selected,5) AS native
101
+ FROM (SELECT topic,ts,argMin(tuple(value,coverage_first_ms,coverage_last_ms,max_gap_ms,native),priority) AS selected FROM (
102
+ SELECT *,0 AS priority FROM ${legacyChartRelation}
103
+ UNION ALL SELECT *,1 AS priority FROM (${points})
104
+ ) GROUP BY topic,ts))/*end-scada-native-chart-range*/`;
105
+ }
106
+ /** Gap-sensitive coverage is valid only at or above the frozen continuity threshold. */
107
+ export function holdsMetricsRange(since,until,gap) {
108
+ const guard=encodeURIComponent(JSON.stringify({since,until,gap}));
109
+ return `/*scada-density-range:${guard}*/${chartMetricsRange(since,until,gap)}`;
110
+ }
@@ -0,0 +1,26 @@
1
+ export const NATIVE_PHYSICAL_POINTS_SQL=`SELECT topic,ts,value,compact_ms,max_gap_ms,revision,is_compacted,compact_first,compact_last,compacted_at FROM scada.metrics_points_v4 FINAL`;
2
+
3
+ /** Two ordinary endpoint rows certify a previously proven constant immutable span. */
4
+ export function nativeMetricCertificates(sourceSql=NATIVE_PHYSICAL_POINTS_SQL) {
5
+ return `SELECT topic,compact_first AS first_ms,compact_last AS last_ms,value,
6
+ min(revision) AS fence,max(compacted_at) AS certificate_at,min(compact_ms) AS certificate_compact_ms,min(max_gap_ms) AS certificate_max_gap_ms
7
+ FROM (${sourceSql}) WHERE is_compacted=1
8
+ GROUP BY topic,compact_first,compact_last,value
9
+ HAVING first_ms<last_ms AND uniqExact(ts)=2 AND min(toUnixTimestamp64Milli(ts))=first_ms
10
+ AND max(toUnixTimestamp64Milli(ts))=last_ms AND uniqExact(compact_ms)=1 AND uniqExact(max_gap_ms)=1 AND min(max_gap_ms)>0`;
11
+ }
12
+ /** Certified spans never overlap, so one indexed predecessor match is sufficient. */
13
+ export function nativeMetricCertificateMatches(pointSourceSql=NATIVE_PHYSICAL_POINTS_SQL,certificateSourceSql=NATIVE_PHYSICAL_POINTS_SQL) {
14
+ return `SELECT p.topic AS topic,p.ts AS ts,p.value AS value,p.compact_ms AS compact_ms,p.max_gap_ms AS max_gap_ms,p.revision AS revision,
15
+ p.is_compacted AS is_compacted,p.compact_first AS compact_first,p.compact_last AS compact_last,p.compacted_at AS compacted_at,
16
+ p.point_ms AS point_ms,c.first_ms AS certificate_first,c.last_ms AS certificate_last,c.fence AS certificate_fence,c.certificate_at AS certificate_at,c.certificate_compact_ms AS certificate_compact_ms,c.certificate_max_gap_ms AS certificate_max_gap_ms,c.value AS certificate_value
17
+ FROM (SELECT *,toUnixTimestamp64Milli(ts) AS point_ms FROM (${pointSourceSql})) AS p
18
+ ASOF LEFT JOIN (SELECT * FROM (${nativeMetricCertificates(certificateSourceSql)}) ORDER BY topic,first_ms) AS c
19
+ ON p.topic=c.topic AND p.point_ms>=c.first_ms`;
20
+ }
21
+ export const OBSOLETE_NATIVE_POINT_SQL='point_ms>certificate_first AND point_ms<certificate_last AND revision<=certificate_fence';
22
+ /** A delayed older INSERT cannot resurrect a physically deleted interior winner. */
23
+ export function effectiveNativePoints(pointSourceSql=NATIVE_PHYSICAL_POINTS_SQL,certificateSourceSql=NATIVE_PHYSICAL_POINTS_SQL) {
24
+ return `SELECT topic,ts,value,compact_ms,max_gap_ms,revision,is_compacted,compact_first,compact_last,compacted_at
25
+ FROM (${nativeMetricCertificateMatches(pointSourceSql,certificateSourceSql)}) WHERE NOT(${OBSOLETE_NATIVE_POINT_SQL})`;
26
+ }
@@ -0,0 +1,91 @@
1
+ import nativeMetricsInsert from './nativeMetricsInsert.js';
2
+ import nativeMetricsOwnership from './nativeMetricsOwnership.js';
3
+ import {createHash} from 'node:crypto';
4
+ import nativeMetricsClock from './nativeMetricsClock.js';
5
+ import centralPoint from '../../ingest/telemetry/centralPoint.js';
6
+ import {CENTRAL_RULE_FIELDS,centralRule} from '../../ingest/telemetry/centralPolicy.js';
7
+ const settings={async_insert:0,wait_for_async_insert:1};
8
+
9
+ function normalize(records) {
10
+ return records.map((record,ordinal)=>{
11
+ const policy=centralRule(Object.fromEntries(CENTRAL_RULE_FIELDS.map(key=>{return [key,record[key]];})));
12
+ return {...centralPoint(record),...policy,ordinal};
13
+ });
14
+ }
15
+ function topicStates(points,states,{seq,revision,publishedAt,admittedAt}) {
16
+ const topics=new Map();
17
+ for(const point of points) {
18
+ const old=states.get(`topic:${point.topic}`);
19
+ if(!topics.has(point.topic)){topics.set(point.topic,{key:`topic:${point.topic}`,latest:Number(old?.latest??-2208988800000),closed_before:Number(old?.closed_before??-2208988800000),published_at:Number(old?.published_at??publishedAt),committed_seq:seq.toString(),revision:revision.toString()});}
20
+ const state=topics.get(point.topic);
21
+ if(point.ts<=admittedAt+point.futureSkewMs&&point.ts>=state.closed_before&&point.ts>=admittedAt-point.maxHistoryAgeMs){state.latest=Math.max(state.latest,point.ts);}
22
+ }
23
+ for(const point of points) {
24
+ const state=topics.get(point.topic);
25
+ // Every point's frozen policy participates; never reopen an existing frontier.
26
+ const cutoff=Math.floor(Math.max(state.latest-point.historyWindowMs,admittedAt-point.maxHistoryAgeMs)/(point.compactWindowMs||60000))*(point.compactWindowMs||60000);
27
+ if(cutoff>state.closed_before){state.closed_before=cutoff;state.published_at=null;}
28
+ }
29
+ return topics;
30
+ }
31
+ function admissionRows(points,topics,admittedAt,batchId,seq) {
32
+ const unique=new Map();const rejected=[];
33
+ for(const point of points) {
34
+ let reason=null;
35
+ if(point.ts>admittedAt+point.futureSkewMs){reason='future';}
36
+ else if(point.ts<topics.get(point.topic).closed_before||point.ts<admittedAt-point.maxHistoryAgeMs){reason='too_old';}
37
+ if(reason){rejected.push({batch_id:batchId,ordinal:point.ordinal,topic:point.topic,ts:new Date(point.ts).toISOString().replace('T',' ').slice(0,-1),value:point.value,reason,admitted_at:new Date(admittedAt).toISOString().replace('T',' ').slice(0,-1)});}
38
+ else{unique.set(JSON.stringify([point.topic,point.ts]),{topic:point.topic,ts:new Date(point.ts).toISOString().replace('T',' ').slice(0,-1),value:point.value,compact_ms:point.compactWindowMs,max_gap_ms:point.maxGapMs,revision:((seq*1024n)+BigInt(point.ordinal)).toString()});}
39
+ }
40
+ return {unique,rejected};
41
+ }
42
+
43
+
44
+ async function seedLegacyStates(client,states,points,admittedAt) {
45
+ const topics=[...new Set(points.map(({topic})=>{return topic;}))].filter(topic=>{return !states.has(`topic:${topic}`);});
46
+ if(!topics.length){return;}
47
+ const skews=new Map(points.map(point=>{return [point.topic,point.futureSkewMs];}));
48
+ const futureTimes=topics.map(topic=>{return Math.min(10413791999999,admittedAt+skews.get(topic));});
49
+ const response=await client.query({query:'SELECT topic,max(toUnixTimestamp64Milli(ts)) AS latest FROM scada.metrics WHERE topic IN {topics:Array(String)} AND toUnixTimestamp64Milli(ts)<=arrayElement({futureTimes:Array(Int64)},indexOf({topics:Array(String)},topic)) GROUP BY topic',query_params:{futureTimes,topics},format:'JSONEachRow'});
50
+ for(const row of await response.json()){states.set(`topic:${row.topic}`,{latest:Number(row.latest)});}
51
+ }
52
+ async function committedState(client,points,admittedAt) {
53
+ const response=await client.query({query:'SELECT * FROM scada.metrics_state_v4 FINAL WHERE key IN {keys:Array(String)}',query_params:{keys:['',...new Set(points.map(({topic})=>{return `topic:${topic}`}))]},format:'JSONEachRow'});
54
+ const states=new Map((await response.json()).map(row=>{return [row.key,row]}));
55
+ await seedLegacyStates(client,states,points,admittedAt);
56
+ const seq=BigInt(states.get('')?.committed_seq??0)+1n;
57
+ if(seq>=(2n**64n)){throw new RangeError('Central admission sequence exhausted');}
58
+ return {states,seq};
59
+ }
60
+ async function persist(client,unique,rejected,states,options) {
61
+ nativeMetricsOwnership(options);
62
+ if(unique.size){await nativeMetricsInsert(client,[...unique.values()]);}
63
+ nativeMetricsOwnership(options);
64
+ if(rejected.length){await client.insert({table:'scada.metrics_rejected_v4',values:rejected,format:'JSONEachRow',clickhouse_settings:settings});}
65
+ const publishedAt=await nativeMetricsClock(client,options);
66
+ nativeMetricsOwnership(options);
67
+ for(const state of states){if(state.published_at===null||state.key===''){state.published_at=publishedAt;}}
68
+ await client.insert({table:'scada.metrics_state_v4',values:states,format:'JSONEachRow',clickhouse_settings:settings});
69
+ }
70
+ function admissionContext(points,context,options) {
71
+ const now=options.now??Date.now;
72
+ const admittedAt=context.admittedAt??now();
73
+ const batchId=context.batchId??createHash('sha256').update(JSON.stringify({points,admittedAt})).digest('hex');
74
+ if(!Number.isSafeInteger(admittedAt)||!/^[a-f0-9]{64}$/u.test(batchId)){throw new TypeError('Invalid central admission context');}
75
+ return {now,admittedAt,batchId};
76
+ }
77
+ /** Requires the serialized SAC head and one authoritative read-after-write target. */
78
+ async function nativeMetricsAdmission(client,records,context={},options={}) {
79
+ nativeMetricsOwnership(context);
80
+ if(records.length>1000){throw new TypeError('Central admission head exceeds 1000 points');}
81
+ const points=normalize(records);
82
+ const {now,admittedAt,batchId}=admissionContext(points,context,options);
83
+ if(!points.length){return;}
84
+ const {states,seq}=await committedState(client,points,admittedAt);
85
+ nativeMetricsOwnership(context);
86
+ const topics=topicStates(points,states,{seq,revision:(seq*1024n)+1023n,publishedAt:now(),admittedAt});
87
+ const publishedAt=now();
88
+ const {unique,rejected}=admissionRows(points,topics,admittedAt,batchId,seq);
89
+ await persist(client,unique,rejected,[...topics.values(),{key:'',latest:0,closed_before:0,published_at:publishedAt,committed_seq:seq.toString(),revision:((seq*1024n)+1023n).toString()}],{...options,active:context.active});
90
+ }
91
+ export default nativeMetricsAdmission;
@@ -0,0 +1,9 @@
1
+ /** Publication and standby cleanup share the authoritative target's clock. */
2
+ export default async function nativeMetricsClock(client,options={}) {
3
+ if(options.now){return options.now();}
4
+ const response=await client.query({query:'SELECT toUnixTimestamp64Milli(now64(3)) AS current_ms',format:'JSONEachRow'});
5
+ const [row]=await response.json();
6
+ const value=Number(row?.current_ms);
7
+ if(!Number.isSafeInteger(value)){throw new Error('Invalid authoritative history publication clock');}
8
+ return value;
9
+ }