@yarkivaev/scada 2.5.7 → 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.
- package/README.md +136 -2
- package/charts/scada/templates/_helpers.tpl +18 -3
- package/charts/scada/templates/postgres.yaml +6 -0
- package/charts/scada/templates/rabbitmq-config.yaml +5 -1
- package/charts/scada/templates/rabbitmq.yaml +12 -1
- package/charts/scada/templates/supervisor-sink.yaml +5 -0
- package/charts/scada/values.schema.json +46 -1
- package/charts/scada/values.yaml +7 -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 +62 -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 +32 -12
- 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/migrate.js +16 -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 +124 -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,33 @@
|
|
|
1
|
+
import { errorResponse, jsonResponse, readBody, route } from '@yarkivaev/simple-server';
|
|
2
|
+
import { hasAccess, sendForbidden } from '../../stateAccess.js';
|
|
3
|
+
|
|
4
|
+
function endpoint(method, suffix, token, action) {
|
|
5
|
+
// eslint-disable-next-line max-statements
|
|
6
|
+
return route(method, `/v1/history/${suffix}`, async (req, res, params, query) => {
|
|
7
|
+
if (!hasAccess(req, token)) { sendForbidden(res); return; }
|
|
8
|
+
let input;
|
|
9
|
+
try {
|
|
10
|
+
input = method === 'GET' ? query : JSON.parse(await readBody(req));
|
|
11
|
+
if (typeof input.machine !== 'string' || !input.machine) { throw new TypeError('machine required'); }
|
|
12
|
+
} catch (error) { errorResponse('BAD_REQUEST', error.message, 400).send(res); return; }
|
|
13
|
+
try { jsonResponse(await action(input)).send(res); } catch (error) {
|
|
14
|
+
if (error.statusCode === 409) { errorResponse('CONFLICT', error.message, 409).send(res); return; }
|
|
15
|
+
if (error instanceof TypeError) { errorResponse('BAD_REQUEST', error.message, 400).send(res); return; }
|
|
16
|
+
throw error;
|
|
17
|
+
}
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
/** Uses the existing checkpoint API authentication and persistence lifecycle. */
|
|
21
|
+
export default function historyRoutes(token, history) {
|
|
22
|
+
if (!history) { return []; }
|
|
23
|
+
return [
|
|
24
|
+
endpoint('POST', 'config', token, (input) => { return history.configure(input.machine, input.topics, input.bucketMs, input.classifierKey); }),
|
|
25
|
+
endpoint('POST', 'purge', token, () => { return history.purge(); }),
|
|
26
|
+
endpoint('POST', 'observations', token, (input) => { return history.accept(input.machine, input.observations); }),
|
|
27
|
+
endpoint('GET', 'work', token, (input) => { return history.work(input.machine); }),
|
|
28
|
+
endpoint('GET', 'context', token, (input) => {
|
|
29
|
+
return history.context(input.machine, Number(input.from), Number(input.until), input.paddingMs === undefined ? 60000 : Number(input.paddingMs), {classifierKey:input.classifierKey,workId:input.workId,workToken:input.workToken,cursor:input.cursor === undefined ? null : Number(input.cursor),end:input.end === undefined ? null : Number(input.end)});
|
|
30
|
+
}),
|
|
31
|
+
endpoint('POST', 'commit', token, (input) => { return history.commit(input.machine, input.workId, input.segments, input.context); })
|
|
32
|
+
];
|
|
33
|
+
}
|
|
@@ -35,6 +35,9 @@ export function measurementItem(key, sensor, rows) {
|
|
|
35
35
|
timestamp: row.timestamp.toISOString(),
|
|
36
36
|
value: row.value
|
|
37
37
|
};
|
|
38
|
+
if (typeof row.continuous === 'boolean') {
|
|
39
|
+
point.continuous = row.continuous;
|
|
40
|
+
}
|
|
38
41
|
if (row.until) {
|
|
39
42
|
point.until = row.until.toISOString();
|
|
40
43
|
}
|
|
@@ -78,3 +78,19 @@ export async function migratePrivileged(pool, migrationsDir, profile = 'central'
|
|
|
78
78
|
await ensureMigrationsTable(pool);
|
|
79
79
|
await applyMigrationFiles(pool, migrationsDir, profile, true);
|
|
80
80
|
}
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
/** Checks the complete selected migration manifest without DDL or writes. */
|
|
84
|
+
export async function verifyMigrations(pool, migrationsDir, profile = 'edge', options = {}) {
|
|
85
|
+
const expected = (await fs.readdir(migrationsDir)).filter((name) => {
|
|
86
|
+
return migrationSelected(name, profile, false, options)
|
|
87
|
+
|| migrationSelected(name, profile, true, options);
|
|
88
|
+
}).sort();
|
|
89
|
+
const { rows } = await pool.query(
|
|
90
|
+
'SELECT version FROM public.schema_migrations WHERE version = ANY($1::text[])',
|
|
91
|
+
[expected]
|
|
92
|
+
);
|
|
93
|
+
const applied = new Set(rows.map(({ version }) => { return version; }));
|
|
94
|
+
const missing = expected.filter((name) => { return !applied.has(name); });
|
|
95
|
+
if (missing.length) { throw new Error(`Missing database migrations: ${missing.join(', ')}`); }
|
|
96
|
+
}
|
|
@@ -23,7 +23,12 @@ const privilegedOnly = new Set([
|
|
|
23
23
|
'C0007__central_segment_replace_delete.sql',
|
|
24
24
|
'E0002__edge_retention_delete.sql',
|
|
25
25
|
'E0003__edge_operations_grants.sql',
|
|
26
|
-
'E0004__edge_operations_delete.sql'
|
|
26
|
+
'E0004__edge_operations_delete.sql',
|
|
27
|
+
'E0005__historical_telemetry_grants.sql',
|
|
28
|
+
'E0008__metric_receipts_grants.sql',
|
|
29
|
+
'E0012__external_history_grants.sql',
|
|
30
|
+
'E0014__history_correction_grants.sql',
|
|
31
|
+
'E0016__history_retention_grants.sql'
|
|
27
32
|
]);
|
|
28
33
|
|
|
29
34
|
/**
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** Forget a first choice only once both its history window and its raw metric are gone. */
|
|
2
|
+
export default async function retainMetricReceipts(pool, days) {
|
|
3
|
+
const table = await pool.query("SELECT to_regclass('metric_receipts') AS receipts");
|
|
4
|
+
if (!table.rows?.[0]?.receipts) { return; }
|
|
5
|
+
await pool.query(`DELETE FROM metric_receipts r
|
|
6
|
+
WHERE r.ts < NOW() - make_interval(days => greatest($1::integer, COALESCE((SELECT max(retention_days) FROM history_topics),30)))
|
|
7
|
+
AND NOT EXISTS(SELECT 1 FROM metrics m WHERE m.topic=r.topic AND m.ts=r.ts)`, [days]);
|
|
8
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import retainMetricReceipts from './retainMetricReceipts.js';
|
|
1
2
|
function intervalFor(days) {
|
|
2
3
|
return `${days} days`;
|
|
3
4
|
}
|
|
@@ -53,6 +54,7 @@ async function vacuumTables(pool) {
|
|
|
53
54
|
*/
|
|
54
55
|
export default async function runRetention(pool, days) {
|
|
55
56
|
const deleted = await deleteStale(pool, days);
|
|
57
|
+
await retainMetricReceipts(pool, days);
|
|
56
58
|
await vacuumTables(pool);
|
|
57
59
|
return { retentionDays: days, deleted };
|
|
58
60
|
}
|
|
@@ -14,7 +14,14 @@
|
|
|
14
14
|
* @param {object} [log] - Logger with warn() method
|
|
15
15
|
* @returns {object} Transformer with accept() method
|
|
16
16
|
*/
|
|
17
|
-
|
|
17
|
+
function validateTimestamp(parsed, options) {
|
|
18
|
+
if (options.requireTimestamp && (!parsed || typeof parsed !== 'object'
|
|
19
|
+
|| !Number.isSafeInteger(parsed.ts) || !Number.isFinite(parsed.value))) {
|
|
20
|
+
throw new TypeError('Central telemetry requires original timestamp and finite value');
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export default function metricsCodec(collector, log = console, options = {}) {
|
|
18
25
|
if (!collector || typeof collector.accept !== 'function') {
|
|
19
26
|
throw new Error('Collector must have an accept() method');
|
|
20
27
|
}
|
|
@@ -29,9 +36,11 @@ export default function metricsCodec(collector, log = console) {
|
|
|
29
36
|
try {
|
|
30
37
|
parsed = JSON.parse(raw.payload);
|
|
31
38
|
} catch {
|
|
39
|
+
if (options.requireTimestamp) { throw new TypeError('Invalid central telemetry JSON'); }
|
|
32
40
|
log.warn(`Cannot resolve payload on ${raw.topic}: not valid JSON`);
|
|
33
41
|
return undefined;
|
|
34
42
|
}
|
|
43
|
+
validateTimestamp(parsed, options);
|
|
35
44
|
if (typeof parsed === 'number') {
|
|
36
45
|
return collector.accept({
|
|
37
46
|
topic: raw.topic,
|
|
@@ -42,7 +51,7 @@ export default function metricsCodec(collector, log = console) {
|
|
|
42
51
|
if (typeof parsed === 'object' && parsed !== null && typeof parsed.value === 'number') {
|
|
43
52
|
return collector.accept({
|
|
44
53
|
topic: raw.topic,
|
|
45
|
-
ts: parsed.ts
|
|
54
|
+
ts: parsed.ts ?? Date.now(),
|
|
46
55
|
value: parsed.value
|
|
47
56
|
});
|
|
48
57
|
}
|
|
@@ -175,7 +175,7 @@ function buildSources(devices, config, collector, clk) {
|
|
|
175
175
|
export default function modbusMqtt(mqtt, devices, config) {
|
|
176
176
|
assertModbusMqttArgs(mqtt, devices, config);
|
|
177
177
|
const clk = clock();
|
|
178
|
-
const sink = mqttSink(mqtt, {
|
|
178
|
+
const sink = config.output ?? mqttSink(mqtt, {
|
|
179
179
|
clientId: config.clientId || 'scada-modbus',
|
|
180
180
|
qos: 1,
|
|
181
181
|
onFatal: config.onFatal
|
|
@@ -290,6 +290,8 @@ export default function modbusPublish(mqtt, config) {
|
|
|
290
290
|
return modbusMqtt(mqtt, specs, {
|
|
291
291
|
budget: config.budget,
|
|
292
292
|
onFatal: config.onFatal,
|
|
293
|
+
output: config.output,
|
|
294
|
+
size: config.size,
|
|
293
295
|
maxRecords: config.maxRecords,
|
|
294
296
|
maxBytes: config.maxBytes,
|
|
295
297
|
writeTimeoutMs: config.writeTimeoutMs,
|
|
@@ -51,7 +51,7 @@ export default function mqttMetrics(mqtt, sink, topic, config) {
|
|
|
51
51
|
// the batch would reject every message at a one-record runtime budget.
|
|
52
52
|
const { budget, ...batchConfig } = config;
|
|
53
53
|
const collector = ingestBatch(sink, { ...batchConfig, size: 1 });
|
|
54
|
-
const transformer = metricsCodec(collector);
|
|
54
|
+
const transformer = metricsCodec(collector, console, { requireTimestamp: sink.requireTimestamp === true });
|
|
55
55
|
const source = mqttSource(mqtt, topic, transformer, {
|
|
56
56
|
budget,
|
|
57
57
|
onError: config.onError,
|
|
@@ -14,13 +14,17 @@ import streamNameFromTopic from './streamNameFromTopic.js';
|
|
|
14
14
|
*/
|
|
15
15
|
export function acceptTelemetryDeliver(codec, fields, content, onSeen) {
|
|
16
16
|
const record = deliverToMqttRecord(fields, content);
|
|
17
|
-
|
|
17
|
+
function seen() {
|
|
18
|
+
if (typeof onSeen !== 'function') { return; }
|
|
18
19
|
const name = streamNameFromTopic(record.topic);
|
|
19
20
|
if (name) {
|
|
20
21
|
onSeen(name);
|
|
21
22
|
}
|
|
22
23
|
}
|
|
23
|
-
|
|
24
|
+
const accepted = codec.accept({ topic: record.topic, payload: record.payload.toString() });
|
|
25
|
+
if (accepted?.then) { return accepted.then((value) => { seen(); return value; }); }
|
|
26
|
+
seen();
|
|
27
|
+
return accepted;
|
|
24
28
|
}
|
|
25
29
|
|
|
26
30
|
/**
|
|
@@ -60,7 +64,7 @@ export default function amqpMetricsIngest(amqpUrl, queue, sink, options = {}) {
|
|
|
60
64
|
// A larger batch can never fill and would throttle ingestion to the flush timer.
|
|
61
65
|
const size = Math.min(options.size ?? 100, prefetch);
|
|
62
66
|
const collector = ingestBatch(sink, { ...options, size });
|
|
63
|
-
const codec = metricsCodec(collector);
|
|
67
|
+
const codec = metricsCodec(collector, console, { requireTimestamp: sink.requireTimestamp === true });
|
|
64
68
|
const session = amqpSource(amqpUrl, queue, {
|
|
65
69
|
accept(delivery) {
|
|
66
70
|
return acceptTelemetryDeliver(codec, delivery.fields, delivery.content, options.onSeen);
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import centralPoint from './centralPoint.js';
|
|
3
|
+
import { CENTRAL_RULE_FIELDS, centralRule } from './centralPolicy.js';
|
|
4
|
+
|
|
5
|
+
export const MAX_BATCH_BYTES = 2097152;
|
|
6
|
+
function digest(value) { return createHash('sha256').update(value).digest('hex'); }
|
|
7
|
+
function address(value, protocols) {
|
|
8
|
+
const url = new URL(value);
|
|
9
|
+
if (!protocols.includes(url.protocol)) { throw new TypeError('Invalid central admission endpoint'); }
|
|
10
|
+
const ports = { 'amqp:': '5672', 'amqps:': '5671', 'http:': '80', 'https:': '443' };
|
|
11
|
+
const path = url.protocol.startsWith('amqp') ? decodeURIComponent(url.pathname.slice(1) || '/') : url.pathname;
|
|
12
|
+
return `${url.protocol}//${url.hostname.toLowerCase()}:${url.port || ports[url.protocol]}/${path}`;
|
|
13
|
+
}
|
|
14
|
+
export function targetIdentity(url) { return digest(address(url, ['http:', 'https:'])); }
|
|
15
|
+
export function admissionDomain(url, queue, target) {
|
|
16
|
+
return digest(`${address(url, ['amqp:', 'amqps:'])}|${queue}|${target}`);
|
|
17
|
+
}
|
|
18
|
+
function keys(value, allowed) {
|
|
19
|
+
if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).some((key) => { return !allowed.includes(key); })) {
|
|
20
|
+
throw new TypeError('Invalid central admission envelope');
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
function observation(value) {
|
|
24
|
+
keys(value, ['topic', 'ts', 'value', ...CENTRAL_RULE_FIELDS]);
|
|
25
|
+
if (CENTRAL_RULE_FIELDS.some((key) => { return value[key] === undefined; })) { throw new TypeError('Missing frozen central policy'); }
|
|
26
|
+
const rule = centralRule(Object.fromEntries(CENTRAL_RULE_FIELDS.map((key) => { return [key, value[key]]; })));
|
|
27
|
+
return { ...centralPoint(value), ...rule };
|
|
28
|
+
}
|
|
29
|
+
export function encodeBatch(records, policy, target) {
|
|
30
|
+
if (!Array.isArray(records) || !records.length || records.length > 1000) { throw new TypeError('Invalid central batch length'); }
|
|
31
|
+
const body = JSON.stringify({ version: 4, target, admittedAt: Date.now(), records: records.map((record) => {
|
|
32
|
+
const point = centralPoint(record);
|
|
33
|
+
return { ...point, ...centralRule(policy.forTopic(point.topic)) };
|
|
34
|
+
}) });
|
|
35
|
+
if (Buffer.byteLength(body) > MAX_BATCH_BYTES) { throw new TypeError('Central batch byte capacity exceeded'); }
|
|
36
|
+
return body;
|
|
37
|
+
}
|
|
38
|
+
export function decodeBatch(content, target) {
|
|
39
|
+
if (Buffer.byteLength(content) > MAX_BATCH_BYTES) { throw new TypeError('Central batch byte capacity exceeded'); }
|
|
40
|
+
const batch = JSON.parse(content.toString());
|
|
41
|
+
keys(batch, ['version', 'target', 'admittedAt', 'records']);
|
|
42
|
+
if (batch.version !== 4 || batch.target !== target) { throw new TypeError('Invalid central envelope version or target'); }
|
|
43
|
+
if (!Array.isArray(batch.records) || !batch.records.length || batch.records.length > 1000) { throw new TypeError('Invalid central batch length'); }
|
|
44
|
+
if (!Number.isSafeInteger(batch.admittedAt) || batch.admittedAt < 0) { throw new TypeError('Invalid central admission time'); }
|
|
45
|
+
return { records: batch.records.map(observation), admittedAt: batch.admittedAt, batchId: digest(content) };
|
|
46
|
+
}
|
|
@@ -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 }
|