@yarkivaev/scada 2.5.8 → 2.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +95 -0
- package/db/migrations/E0005__historical_telemetry_grants.sql +5 -0
- package/db/migrations/E0006__historical_telemetry.sql +64 -0
- package/db/migrations/E0007__metric_receipts.sql +7 -0
- package/db/migrations/E0008__metric_receipts_grants.sql +1 -0
- package/db/migrations/E0009__history_continuation.sql +20 -0
- package/db/migrations/E0010__history_admissions.sql +8 -0
- package/db/migrations/E0011__history_classifier_checkpoints.sql +18 -0
- package/db/migrations/E0012__external_history_grants.sql +4 -0
- package/db/migrations/E0013__history_staged_corrections.sql +104 -0
- package/db/migrations/E0014__history_correction_grants.sql +5 -0
- package/db/migrations/E0015__history_retention_frontier.sql +7 -0
- package/db/migrations/E0016__history_retention_grants.sql +1 -0
- package/index.js +7 -0
- package/package.json +5 -3
- package/src/application/control/agent.js +61 -0
- package/src/application/control/catalog.js +22 -0
- package/src/application/control/controlClient.js +75 -0
- package/src/application/control/controlStore.js +55 -0
- package/src/application/control/controller.js +22 -0
- package/src/application/control/executionSnapshot.js +32 -0
- package/src/application/control/index.js +7 -0
- package/src/application/control/localAssignment.js +13 -0
- package/src/application/control/schedule.js +103 -0
- package/src/application/control/snapshotFile.js +24 -0
- package/src/application/foldedMetricsSink.js +1 -0
- package/src/application/mcp/mcpResources.js +1 -1
- package/src/application/mcp/mcpSchema.js +8 -3
- package/src/application/runtime/additionalAdapters.js +13 -9
- package/src/application/runtime/deliveryQueue.js +80 -0
- package/src/application/runtime/deliverySessions.js +28 -0
- package/src/application/runtime/modbusDelivery.js +36 -0
- package/src/application/runtime/pipelineAdapters.js +12 -8
- package/src/application/runtime/queuedDelivery.js +25 -0
- package/src/application/runtime/runCollector.js +34 -3
- package/src/application/runtime/runtime.js +2 -2
- package/src/application/runtime/runtimeHealth.js +1 -1
- package/src/application/runtime/runtimeServices.js +6 -2
- package/src/application/runtime/streamTask.js +13 -4
- package/src/application/runtime/taskContext.js +1 -0
- package/src/application/runtime/taskSlot.js +2 -2
- package/src/application/runtime/telemetrySink.js +18 -0
- package/src/application/siteServer.js +19 -4
- package/src/application/siteTelemetry.js +2 -2
- package/src/application/supervisorSink.js +5 -1
- package/src/application/sync/siteSyncBind.js +2 -2
- package/src/bin/controller.js +8 -0
- package/src/infrastructure/http/edge/edgeApi.js +2 -0
- package/src/infrastructure/http/edge/routes/history/historyRoutes.js +33 -0
- package/src/infrastructure/http/plant/routes/measurementRead.js +3 -0
- package/src/infrastructure/ingest/db/migrationProfile.js +6 -1
- package/src/infrastructure/ingest/db/retainMetricReceipts.js +8 -0
- package/src/infrastructure/ingest/db/runRetention.js +2 -0
- package/src/infrastructure/ingest/mqtt/metricsTransformer.js +11 -2
- package/src/infrastructure/ingest/mqtt/modbusMqtt.js +1 -1
- package/src/infrastructure/ingest/mqtt/modbusPublish.js +2 -0
- package/src/infrastructure/ingest/mqtt/mqttMetrics.js +1 -1
- package/src/infrastructure/ingest/telemetry/amqpMetricsIngest.js +7 -3
- package/src/infrastructure/ingest/telemetry/centralEnvelope.js +46 -0
- package/src/infrastructure/ingest/telemetry/centralMetricsSink.js +64 -0
- package/src/infrastructure/ingest/telemetry/centralPoint.js +14 -0
- package/src/infrastructure/ingest/telemetry/centralPolicy.js +51 -0
- package/src/infrastructure/ingest/telemetry/centralQueueSession.js +29 -0
- package/src/infrastructure/ingest/telemetry/centralTelemetryPreflight.js +31 -0
- package/src/infrastructure/ingest/telemetry/foldingSink.js +3 -0
- package/src/infrastructure/ingest/telemetry/historyTelemetry.js +32 -0
- package/src/infrastructure/persistence/clickhouse/canonicalMetrics.js +26 -0
- package/src/infrastructure/persistence/clickhouse/changes.js +4 -2
- package/src/infrastructure/persistence/clickhouse/connection.js +6 -8
- package/src/infrastructure/persistence/clickhouse/holds.js +10 -7
- package/src/infrastructure/persistence/clickhouse/latest.js +1 -1
- package/src/infrastructure/persistence/clickhouse/metricsQuery.js +70 -0
- package/src/infrastructure/persistence/clickhouse/metricsRelation.js +110 -0
- package/src/infrastructure/persistence/clickhouse/nativeMetricPoints.js +26 -0
- package/src/infrastructure/persistence/clickhouse/nativeMetricsAdmission.js +91 -0
- package/src/infrastructure/persistence/clickhouse/nativeMetricsClock.js +9 -0
- package/src/infrastructure/persistence/clickhouse/nativeMetricsCompaction.js +82 -0
- package/src/infrastructure/persistence/clickhouse/nativeMetricsInsert.js +31 -0
- package/src/infrastructure/persistence/clickhouse/nativeMetricsOwnership.js +8 -0
- package/src/infrastructure/persistence/clickhouse/nativeMetricsSchema.js +44 -0
- package/src/infrastructure/persistence/clickhouse/pollTopicCursors.js +3 -1
- package/src/infrastructure/persistence/clickhouse/rises.js +4 -2
- package/src/infrastructure/persistence/clickhouse/samples.js +10 -0
- package/src/infrastructure/persistence/clickhouse/sensor.js +4 -0
- package/src/infrastructure/persistence/clickhouse/series.js +38 -21
- package/src/infrastructure/persistence/pg/history.js +169 -0
- package/src/infrastructure/persistence/pg/historyAdmission.js +81 -0
- package/src/infrastructure/persistence/pg/historyCheckpoint.js +56 -0
- package/src/infrastructure/persistence/pg/historyConfigure.js +28 -0
- package/src/infrastructure/persistence/pg/historyContext.js +65 -0
- package/src/infrastructure/persistence/pg/historyCorrection.js +34 -0
- package/src/infrastructure/persistence/pg/historyObservations.js +56 -0
- package/src/infrastructure/persistence/pg/historySeed.js +27 -0
- package/src/infrastructure/persistence/pg/metrics.js +5 -4
- package/src/infrastructure/persistence/pg/metricsInsertSql.js +12 -0
- package/src/infrastructure/persistence/runtime/deliverySpool.js +57 -0
- package/src/infrastructure/persistence/runtime/spoolCodec.js +41 -0
- package/src/infrastructure/persistence/runtime/spoolDatabase.js +69 -0
- package/src/infrastructure/persistence/runtime/spoolFormat.js +37 -0
- package/src/infrastructure/persistence/runtime/spoolMigration.js +66 -0
- package/src/infrastructure/persistence/runtime/spoolRecords.js +50 -0
- package/src/infrastructure/persistence/stateDataFromPool.js +2 -0
- package/src/infrastructure/streams/amqpSink/session.js +6 -0
- package/src/infrastructure/streams/amqpSource.js +17 -4
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { clickhouseSink } from '../../streams/index.js';
|
|
2
|
+
import centralQueueSession, { centralQueueOptions } from './centralQueueSession.js';
|
|
3
|
+
import amqpSink from '../../streams/amqpSink.js';
|
|
4
|
+
import centralPolicy from './centralPolicy.js';
|
|
5
|
+
import centralPoint from './centralPoint.js';
|
|
6
|
+
import canonicalMetrics from '../../persistence/clickhouse/canonicalMetrics.js';
|
|
7
|
+
import centralTelemetryPreflight from './centralTelemetryPreflight.js';
|
|
8
|
+
import { admissionDomain, encodeBatch, targetIdentity } from './centralEnvelope.js';
|
|
9
|
+
/* eslint-disable no-await-in-loop */
|
|
10
|
+
|
|
11
|
+
function legacySink(env,url) {
|
|
12
|
+
const raw = clickhouseSink(url,'scada.metrics');
|
|
13
|
+
return {start() {return centralTelemetryPreflight(env);},async write(records,context) {
|
|
14
|
+
await centralTelemetryPreflight(env);return raw.write(records,context);
|
|
15
|
+
},stop() {return raw.stop();}};
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** All producers use one durable SAC queue; only its serialized head writes CH. */
|
|
19
|
+
export default function centralMetricsSink(env) {
|
|
20
|
+
const policy = centralPolicy(env.CENTRAL_TELEMETRY_POLICY ?? {});
|
|
21
|
+
const url = env.CLICKHOUSE_URL || (env.CLICKHOUSE_HOST ? `http://${env.CLICKHOUSE_HOST}:8123` : undefined);
|
|
22
|
+
if (!policy.enabled) { return legacySink(env,url); }
|
|
23
|
+
if (!env.AMQP_URL) { throw new TypeError('Enabled central telemetry policy requires AMQP_URL'); }
|
|
24
|
+
const target = targetIdentity(url);
|
|
25
|
+
const projection = canonicalMetrics(url, admissionDomain(env.AMQP_URL, policy.queue, target));
|
|
26
|
+
const queueOptions = centralQueueOptions(policy);
|
|
27
|
+
const state = { stopped: false, opening: null, error: null };
|
|
28
|
+
function failure(error) {
|
|
29
|
+
if (state.error?.message !== error.message) { process.stderr.write(`[scada] central admission blocked: ${error.message}\n`); }
|
|
30
|
+
state.error = error;
|
|
31
|
+
}
|
|
32
|
+
const publisher = amqpSink(env.AMQP_URL, { queues: [{ name: policy.queue, options: queueOptions }], onError: failure });
|
|
33
|
+
const source = centralQueueSession({url:env.AMQP_URL,queue:policy.queue,queueOptions,target},projection,{
|
|
34
|
+
failed:failure,accepted() { state.error = null; }
|
|
35
|
+
});
|
|
36
|
+
function start() {
|
|
37
|
+
if (state.stopped) { return Promise.reject(new Error('Central telemetry sink stopped')); }
|
|
38
|
+
state.opening ??= Promise.all([publisher.start(), source.start()]).catch((error) => { state.opening = null; throw error; });
|
|
39
|
+
return state.opening;
|
|
40
|
+
}
|
|
41
|
+
return {
|
|
42
|
+
requireTimestamp: true, start,
|
|
43
|
+
async write(records, context) {
|
|
44
|
+
const points = records.map(centralPoint);
|
|
45
|
+
const messages = [];
|
|
46
|
+
for (let index = 0; index < points.length; index += policy.batchSize) {
|
|
47
|
+
messages.push({ exchange: '', routingKey: policy.queue,
|
|
48
|
+
body: encodeBatch(points.slice(index, index + policy.batchSize), policy, target),
|
|
49
|
+
options: { persistent: true, mandatory: true, contentType: 'application/json' } });
|
|
50
|
+
}
|
|
51
|
+
await start();
|
|
52
|
+
// Confirms establish the durable admission order. ACK source only afterwards.
|
|
53
|
+
for (const message of messages) { await publisher.write([message], context); }
|
|
54
|
+
},
|
|
55
|
+
status() { return { connected: publisher.active(), error: state.error?.message ?? null }; },
|
|
56
|
+
async stop() {
|
|
57
|
+
if (state.stopped) { return; }
|
|
58
|
+
state.stopped = true;
|
|
59
|
+
await state.opening?.catch(() => { return undefined; });
|
|
60
|
+
await Promise.allSettled([source.stop(), publisher.stop()]);
|
|
61
|
+
await projection.stop();
|
|
62
|
+
}
|
|
63
|
+
};
|
|
64
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/** Reject invalid identity before storing any part of a batch. */
|
|
2
|
+
export default function centralMetricPoint(record) {
|
|
3
|
+
let ts = record.ts instanceof Date ? record.ts.getTime() : record.ts;
|
|
4
|
+
if (typeof ts === 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/u.test(ts)) {
|
|
5
|
+
const parsed = Date.parse(ts);
|
|
6
|
+
if (Number.isFinite(parsed) && new Date(parsed).toISOString() === ts) { ts = parsed; }
|
|
7
|
+
}
|
|
8
|
+
if (typeof record.topic !== 'string' || !record.topic || record.topic.length > 1024
|
|
9
|
+
|| !Number.isSafeInteger(ts) || ts < -2208988800000 || ts > 10413791999999 || !Number.isFinite(record.value)) {
|
|
10
|
+
throw new TypeError('Central telemetry requires a logical topic, original millisecond timestamp and finite value');
|
|
11
|
+
}
|
|
12
|
+
return { topic: record.topic, ts, value: record.value };
|
|
13
|
+
}
|
|
14
|
+
|
|
@@ -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.
|
|
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
|
|
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
|
-
|
|
44
|
-
|
|
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
|
|
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
|
-
|
|
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
|
|
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(
|
|
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.
|
|
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
|
+
}
|