@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,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
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import nativeMetricsInsert from './nativeMetricsInsert.js';
|
|
2
|
+
import nativeMetricsClock from './nativeMetricsClock.js';
|
|
3
|
+
import {effectiveNativePoints,nativeMetricCertificateMatches,OBSOLETE_NATIVE_POINT_SQL} from './nativeMetricPoints.js';
|
|
4
|
+
/** One shared definition of window overlap for reads and physical cleanup. */
|
|
5
|
+
export function nativeMetricWindows(sourceSql=effectiveNativePoints()) {
|
|
6
|
+
return `SELECT *,ifNull(window_start<prior_end,0) OR ifNull(window_start+window_ms>next_start,0) AS overlap
|
|
7
|
+
FROM (SELECT *,maxOrNull(window_start+window_ms) OVER (PARTITION BY topic ORDER BY window_start,window_ms,compact_ms,max_gap_ms ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) AS prior_end,
|
|
8
|
+
minOrNull(window_start) OVER (PARTITION BY topic ORDER BY window_start,window_ms,compact_ms,max_gap_ms ROWS BETWEEN 1 FOLLOWING AND 1 FOLLOWING) AS next_start
|
|
9
|
+
FROM (SELECT topic,compact_ms,max_gap_ms,toInt64(floor(toUnixTimestamp64Milli(ts)/toFloat64(if(compact_ms=0,60000,compact_ms))))*toInt64(if(compact_ms=0,60000,compact_ms)) AS window_start,
|
|
10
|
+
toInt64(if(compact_ms=0,60000,compact_ms)) AS window_ms,min(toUnixTimestamp64Milli(ts)) AS first_ms,max(toUnixTimestamp64Milli(ts)) AS last_ms,
|
|
11
|
+
min(value) AS low,max(value) AS high,count() AS n
|
|
12
|
+
FROM (${sourceSql}) GROUP BY topic,compact_ms,max_gap_ms,window_start,window_ms))`;
|
|
13
|
+
}
|
|
14
|
+
/** Full certificates are interval atoms, so deleted density cannot create new gaps. */
|
|
15
|
+
export function nativeMetricIslandPoints(sourceSql=effectiveNativePoints()) {
|
|
16
|
+
const policy='topic,compact_ms,max_gap_ms,window_start,window_ms';
|
|
17
|
+
const island=`${policy},island_id`;
|
|
18
|
+
return `SELECT *,countIf(is_compacted=0 AND point_ms>island_first_ms AND point_ms<island_last_ms) OVER (PARTITION BY ${island}) AS raw_interiors
|
|
19
|
+
FROM (SELECT *,min(atom_first) OVER (PARTITION BY ${island}) AS island_first_ms,
|
|
20
|
+
max(atom_last) OVER (PARTITION BY ${island}) AS island_last_ms,count() OVER (PARTITION BY ${island}) AS island_n
|
|
21
|
+
FROM (SELECT *,sum(if(isNull(prior_atom_end),1,atom_first-prior_atom_end>toInt64(max_gap_ms))) OVER
|
|
22
|
+
(PARTITION BY ${policy} ORDER BY atom_first,point_ms ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS island_id
|
|
23
|
+
FROM (SELECT *,maxOrNull(atom_last) OVER (PARTITION BY ${policy} ORDER BY atom_first,point_ms ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) AS prior_atom_end
|
|
24
|
+
FROM (SELECT *,if(valid_certificate,certificate_first,point_ms) AS atom_first,if(valid_certificate,certificate_last,point_ms) AS atom_last,
|
|
25
|
+
toInt64(if(compact_ms=0,60000,compact_ms)) AS window_ms,
|
|
26
|
+
toInt64(floor(point_ms/toFloat64(if(compact_ms=0,60000,compact_ms))))*toInt64(if(compact_ms=0,60000,compact_ms)) AS window_start
|
|
27
|
+
FROM (SELECT *,is_compacted=1 AND certificate_first<certificate_last AND compact_ms=certificate_compact_ms
|
|
28
|
+
AND max_gap_ms=certificate_max_gap_ms AND value=certificate_value
|
|
29
|
+
AND (point_ms=certificate_first OR point_ms=certificate_last) AS valid_certificate
|
|
30
|
+
FROM (${nativeMetricCertificateMatches(sourceSql,sourceSql)}))))))`;
|
|
31
|
+
}
|
|
32
|
+
/** One row per policy/window continuity island, after merging all collectors. */
|
|
33
|
+
export function nativeMetricIslands(sourceSql=effectiveNativePoints()) {
|
|
34
|
+
return `SELECT topic,compact_ms,max_gap_ms,window_start,window_ms,island_first_ms AS first_ms,island_last_ms AS last_ms,
|
|
35
|
+
max(island_n) AS n,max(raw_interiors) AS raw_interiors FROM (${nativeMetricIslandPoints(sourceSql)})
|
|
36
|
+
GROUP BY topic,compact_ms,max_gap_ms,window_start,window_ms,island_first_ms,island_last_ms`;
|
|
37
|
+
}
|
|
38
|
+
/** Only entirely closed, equal windows without policy or legacy overlaps qualify. */
|
|
39
|
+
export const NATIVE_COMPACTION_WINDOWS_SQL=`WITH spans AS (${nativeMetricWindows()}),islands AS (${nativeMetricIslands()}),
|
|
40
|
+
legacy AS (SELECT topic,min(toUnixTimestamp64Milli(ts)) AS first_ms,max(toUnixTimestamp64Milli(ts)) AS last_ms,count() AS n FROM scada.metrics GROUP BY topic)
|
|
41
|
+
SELECT a.topic AS topic,a.window_start AS window_start,a.window_ms AS window_ms,i.first_ms AS first_ms,i.last_ms AS last_ms,a.low AS value,a.compact_ms AS compact_ms,a.max_gap_ms AS max_gap_ms,state.committed_seq AS committed_seq,
|
|
42
|
+
state.published_at AS published_at
|
|
43
|
+
FROM spans a INNER JOIN islands i ON a.topic=i.topic AND a.compact_ms=i.compact_ms AND a.max_gap_ms=i.max_gap_ms AND a.window_start=i.window_start AND a.window_ms=i.window_ms
|
|
44
|
+
INNER JOIN (SELECT key,closed_before,published_at,committed_seq FROM scada.metrics_state_v4 FINAL) AS state ON state.key=concat('topic:',a.topic)
|
|
45
|
+
LEFT JOIN legacy l ON l.topic=a.topic
|
|
46
|
+
WHERE a.compact_ms>0 AND a.max_gap_ms>0 AND a.low=a.high AND i.n>2 AND i.raw_interiors>0 AND NOT a.overlap AND a.window_start+a.window_ms<=state.closed_before
|
|
47
|
+
AND NOT(l.n>0 AND a.window_start<=l.last_ms AND a.window_start+a.window_ms>l.first_ms)`;
|
|
48
|
+
|
|
49
|
+
function endpointRows(windows,publishedAt) {
|
|
50
|
+
return windows.flatMap(window=>{
|
|
51
|
+
const common={topic:window.topic,value:window.value,compact_ms:window.compact_ms,max_gap_ms:window.max_gap_ms,
|
|
52
|
+
revision:(BigInt(window.committed_seq)*1024n+1000n).toString(),is_compacted:1,
|
|
53
|
+
compact_first:Number(window.first_ms),compact_last:Number(window.last_ms),compacted_at:publishedAt};
|
|
54
|
+
return [window.first_ms,window.last_ms].map(ts=>{return {...common,ts:new Date(Number(ts)).toISOString().replace('T',' ').slice(0,-1)};});
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
async function deleteObsolete(client,windows) {
|
|
58
|
+
if(!windows.length){return;}
|
|
59
|
+
const queryParams={};
|
|
60
|
+
const predicates=windows.map((window,index)=>{
|
|
61
|
+
queryParams[`topic${index}`]=window.topic;queryParams[`first${index}`]=window.certificate_first;queryParams[`last${index}`]=window.certificate_last;queryParams[`fence${index}`]=window.certificate_fence;
|
|
62
|
+
return `(topic={topic${index}:String} AND ts>fromUnixTimestamp64Milli({first${index}:Int64}) AND ts<fromUnixTimestamp64Milli({last${index}:Int64}) AND revision<={fence${index}:UInt128})`;
|
|
63
|
+
});
|
|
64
|
+
await client.command({query:`ALTER TABLE scada.metrics_points_v4 DELETE WHERE ${predicates.join(' OR ')}`,query_params:queryParams,clickhouse_settings:{mutations_sync:1}});
|
|
65
|
+
}
|
|
66
|
+
async function pendingMutations(client) {
|
|
67
|
+
const pending=await client.query({query:"SELECT count() AS n FROM system.mutations WHERE database='scada' AND table='metrics_points_v4' AND NOT is_done",format:'JSONEachRow'});
|
|
68
|
+
return Number((await pending.json())[0]?.n??0);
|
|
69
|
+
}
|
|
70
|
+
/** Certificate publication and physical deletion have separate grace periods. */
|
|
71
|
+
export default async function nativeMetricsCompaction(client,options={}) {
|
|
72
|
+
if(await pendingMutations(client)>=(options.maxPendingMutations??1)){return 0;}
|
|
73
|
+
const now=await nativeMetricsClock(client,options);
|
|
74
|
+
const params={mature:now-(options.compactionGraceMs??120000),limit:options.compactionBatchSize??100};
|
|
75
|
+
const obsolete=await client.query({query:`SELECT DISTINCT topic,certificate_first,certificate_last,certificate_fence FROM (${nativeMetricCertificateMatches()}) WHERE ${OBSOLETE_NATIVE_POINT_SQL} AND certificate_at<={mature:Int64} LIMIT {limit:UInt32}`,query_params:params,format:'JSONEachRow'});
|
|
76
|
+
const stale=await obsolete.json();
|
|
77
|
+
await deleteObsolete(client,stale);
|
|
78
|
+
const candidates=await client.query({query:`SELECT * FROM (${NATIVE_COMPACTION_WINDOWS_SQL}) WHERE published_at<={mature:Int64} LIMIT {limit:UInt32}`,query_params:params,format:'JSONEachRow'});
|
|
79
|
+
const windows=await candidates.json();
|
|
80
|
+
if(windows.length){await nativeMetricsInsert(client,endpointRows(windows,await nativeMetricsClock(client,options)));}
|
|
81
|
+
return stale.length+windows.length;
|
|
82
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import {Readable} from 'node:stream';
|
|
2
|
+
|
|
3
|
+
function lengthPrefix(length) {
|
|
4
|
+
const bytes=[];let remaining=length;
|
|
5
|
+
do{const digit=remaining%128;remaining=Math.floor(remaining/128);bytes.push(digit+(remaining?128:0));}while(remaining);
|
|
6
|
+
return Buffer.from(bytes);
|
|
7
|
+
}
|
|
8
|
+
function scalar(value,method,size) {
|
|
9
|
+
const buffer=Buffer.alloc(size);buffer[method](value);return buffer;
|
|
10
|
+
}
|
|
11
|
+
function revision(value) {
|
|
12
|
+
const number=BigInt(value);const base=2n**64n;
|
|
13
|
+
return Buffer.concat([scalar(number%base,'writeBigUInt64LE',8),scalar(number/base,'writeBigUInt64LE',8)]);
|
|
14
|
+
}
|
|
15
|
+
function record(row) {
|
|
16
|
+
if(!Number.isFinite(row.value)){throw new TypeError('Finite central telemetry value required');}
|
|
17
|
+
const topic=Buffer.from(row.topic,'utf8');
|
|
18
|
+
return Buffer.concat([lengthPrefix(topic.length),topic,
|
|
19
|
+
scalar(BigInt(Date.parse(`${row.ts.replace(' ','T')}Z`)),'writeBigInt64LE',8),
|
|
20
|
+
scalar(row.value,'writeDoubleLE',8),scalar(BigInt(row.compact_ms),'writeBigUInt64LE',8),revision(row.revision),
|
|
21
|
+
scalar(row.is_compacted??0,'writeUInt8',1),
|
|
22
|
+
...['compact_first','compact_last','compacted_at'].map(field=>{return scalar(BigInt(row[field]??0),'writeBigInt64LE',8);}),scalar(BigInt(row.max_gap_ms),'writeBigUInt64LE',8)]);
|
|
23
|
+
}
|
|
24
|
+
/** Preserve Float64 bits and UInt128 revisions for admission and endpoint publication. */
|
|
25
|
+
export default async function nativeMetricsInsert(client,rows) {
|
|
26
|
+
if(!rows.length){return;}
|
|
27
|
+
const response=await client.exec({query:'INSERT INTO scada.metrics_points_v4 (topic,ts,value,compact_ms,revision,is_compacted,compact_first,compact_last,compacted_at,max_gap_ms) FORMAT RowBinary',
|
|
28
|
+
values:Readable.from([Buffer.concat(rows.map(record))],{objectMode:false}),
|
|
29
|
+
clickhouse_settings:{async_insert:0,wait_for_async_insert:1,wait_end_of_query:1}});
|
|
30
|
+
for await(const chunk of response.stream){if(chunk.length){throw new Error('Unexpected ClickHouse central insertion response');}}
|
|
31
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** A former SAC delivery cannot allocate or publish a newer admission. */
|
|
2
|
+
export default function nativeMetricsOwnership({ active } = {}) {
|
|
3
|
+
if (active !== undefined && (typeof active !== 'function' || active() !== true)) {
|
|
4
|
+
const error = new Error('Central admission ownership lost');
|
|
5
|
+
error.code = 'SCADA_ADMISSION_OWNERSHIP_LOST';
|
|
6
|
+
throw error;
|
|
7
|
+
}
|
|
8
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
export const LEGACY_METRICS_SQL=`CREATE TABLE IF NOT EXISTS scada.metrics (
|
|
2
|
+
topic String, ts DateTime64(3), value Float64
|
|
3
|
+
) ENGINE=MergeTree ORDER BY(topic,ts)`;
|
|
4
|
+
export const NATIVE_METRICS_SQL=`CREATE TABLE IF NOT EXISTS scada.metrics_points_v4 (
|
|
5
|
+
topic String, ts DateTime64(3), value Float64, compact_ms UInt64, revision UInt128,
|
|
6
|
+
is_compacted UInt8 DEFAULT 0,compact_first Int64 DEFAULT 0,compact_last Int64 DEFAULT 0,compacted_at Int64 DEFAULT 0,max_gap_ms UInt64
|
|
7
|
+
) ENGINE=ReplacingMergeTree(revision) PARTITION BY toYYYYMM(ts) ORDER BY(topic,ts)`;
|
|
8
|
+
const tables=[
|
|
9
|
+
['metrics_points_v4',NATIVE_METRICS_SQL,'ReplacingMergeTree','topic,ts','toYYYYMM(ts)','topic:String,ts:DateTime64(3),value:Float64,compact_ms:UInt64,revision:UInt128,is_compacted:UInt8,compact_first:Int64,compact_last:Int64,compacted_at:Int64,max_gap_ms:UInt64'],
|
|
10
|
+
['metrics_state_v4',`CREATE TABLE IF NOT EXISTS scada.metrics_state_v4 (
|
|
11
|
+
key String, latest Int64, closed_before Int64, published_at Int64, committed_seq UInt64, revision UInt128
|
|
12
|
+
) ENGINE=ReplacingMergeTree(revision) ORDER BY key`,'ReplacingMergeTree','key','','key:String,latest:Int64,closed_before:Int64,published_at:Int64,committed_seq:UInt64,revision:UInt128'],
|
|
13
|
+
['metrics_rejected_v4',`CREATE TABLE IF NOT EXISTS scada.metrics_rejected_v4 (
|
|
14
|
+
batch_id String,ordinal UInt16,topic String,ts DateTime64(3),value Float64,reason LowCardinality(String),admitted_at DateTime64(3),recorded_at DateTime64(3) DEFAULT now64(3)
|
|
15
|
+
) ENGINE=ReplacingMergeTree ORDER BY(batch_id,ordinal) TTL toDateTime(recorded_at)+INTERVAL 30 DAY`,'ReplacingMergeTree','batch_id,ordinal','','batch_id:String,ordinal:UInt16,topic:String,ts:DateTime64(3),value:Float64,reason:LowCardinality(String),admitted_at:DateTime64(3),recorded_at:DateTime64(3)']
|
|
16
|
+
];
|
|
17
|
+
async function installTable(client,domain,[name,sql,engine,key,partition,columns]) {
|
|
18
|
+
await client.command({query:`${sql} COMMENT 'scada-admission-v4:${domain}'`});
|
|
19
|
+
const response=await client.query({query:'SELECT engine,sorting_key,partition_key,comment,create_table_query FROM system.tables WHERE database=\'scada\' AND name={name:String}',query_params:{name},format:'JSONEachRow'});
|
|
20
|
+
const [table]=await response.json();
|
|
21
|
+
if(table?.comment!==`scada-admission-v4:${domain}`){throw new Error('Central admission domain differs from the existing canonical table');}
|
|
22
|
+
const shape=await client.query({query:"SELECT name,type FROM system.columns WHERE database='scada' AND table={name:String} ORDER BY position",query_params:{name},format:'JSONEachRow'});
|
|
23
|
+
const actual=(await shape.json()).map(column=>{return `${column.name}:${column.type}`}).join(',');
|
|
24
|
+
if(table.engine!==engine||table.sorting_key.replaceAll(' ','')!==key||table.partition_key!==partition||actual!==columns||(name!=='metrics_rejected_v4'&&!table.create_table_query.includes('ReplacingMergeTree(revision)'))){throw new Error('Incompatible central native storage schema');}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Atomic CREATE comments pin domain before any writer can activate. */
|
|
28
|
+
/* Schema DDL is deliberately ordered: pin and validate each table before views. */
|
|
29
|
+
/* eslint-disable no-await-in-loop */
|
|
30
|
+
export default async function nativeMetricsSchema(client,domain,relation,rawRelation) {
|
|
31
|
+
if(!/^[a-f0-9]{64}$/u.test(domain)){throw new TypeError('Invalid central admission domain');}
|
|
32
|
+
await client.command({query:'CREATE DATABASE IF NOT EXISTS scada'});
|
|
33
|
+
const old=await client.query({query:"SELECT name FROM system.tables WHERE database='scada' AND name IN ('metrics_canonical','metrics_compact_v2','metrics_points_v3','metrics_state_v3','metrics_rejected_v3')",format:'JSONEachRow'});
|
|
34
|
+
if((await old.json()).length){throw new Error('Previous canonical storage requires an explicit v4 migration');}
|
|
35
|
+
await client.command({query:LEGACY_METRICS_SQL});
|
|
36
|
+
for(const table of tables){await installTable(client,domain,table);}
|
|
37
|
+
for(const [name,sql] of [['metrics_read',relation],['metrics_raw_read',rawRelation]]){
|
|
38
|
+
const found=await client.query({query:"SELECT engine,create_table_query FROM system.tables WHERE database='scada' AND name={name:String}",query_params:{name},format:'JSONEachRow'});
|
|
39
|
+
const [view]=await found.json();
|
|
40
|
+
if(view&&(view.engine!=='View'||!view.create_table_query.includes('metrics_points_v4'))){throw new Error('Previous canonical read view requires an explicit v4 migration');}
|
|
41
|
+
await client.command({query:`CREATE VIEW IF NOT EXISTS scada.${name} AS SELECT * FROM ${sql}`});
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { metricsRange } from './metricsRelation.js';
|
|
2
|
+
|
|
1
3
|
/**
|
|
2
4
|
* Batched ClickHouse poll for many topic cursors.
|
|
3
5
|
*
|
|
@@ -32,7 +34,7 @@ export default function pollTopicCursors(connection, cursors, until) {
|
|
|
32
34
|
}
|
|
33
35
|
});
|
|
34
36
|
return connection.query(
|
|
35
|
-
`SELECT topic, ts, value FROM
|
|
37
|
+
`SELECT topic, ts, value FROM ${metricsRange('toUnixTimestamp64Milli({since:DateTime64(3)})', 'toUnixTimestamp64Milli({until:DateTime64(3)})')}
|
|
36
38
|
WHERE topic IN {topics:Array(String)}
|
|
37
39
|
AND ts > {since:DateTime64(3)}
|
|
38
40
|
AND ts <= {until:DateTime64(3)}
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { metricsRange } from './metricsRelation.js';
|
|
2
|
+
|
|
1
3
|
/**
|
|
2
4
|
* Prefix sum of 0→1 edges for one ClickHouse metric topic.
|
|
3
5
|
*
|
|
@@ -16,13 +18,13 @@ function formatDateTime(date) {
|
|
|
16
18
|
|
|
17
19
|
const RISES_SQL = `WITH prior AS (
|
|
18
20
|
SELECT ts, value
|
|
19
|
-
FROM scada.
|
|
21
|
+
FROM scada.metrics_read
|
|
20
22
|
WHERE topic = {topic:String} AND ts < {start:DateTime64(3)}
|
|
21
23
|
ORDER BY ts DESC
|
|
22
24
|
LIMIT 1
|
|
23
25
|
), windowed AS (
|
|
24
26
|
SELECT ts, value
|
|
25
|
-
FROM
|
|
27
|
+
FROM ${metricsRange('toUnixTimestamp64Milli({start:DateTime64(3)})', 'toUnixTimestamp64Milli({end:DateTime64(3)})')}
|
|
26
28
|
WHERE topic = {topic:String}
|
|
27
29
|
AND ts >= {start:DateTime64(3)}
|
|
28
30
|
AND ts < {end:DateTime64(3)}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { rawMetricsRange } from './metricsRelation.js';
|
|
2
|
+
|
|
3
|
+
/** Actual observations for density-sensitive consumers; sealed thinning fails explicitly. */
|
|
4
|
+
export default async function clickhouseSamples(connection,topic,range,unit) {
|
|
5
|
+
const rows=await connection.query(`SELECT ts,value FROM ${rawMetricsRange('{since:Int64}','{until:Int64}')}
|
|
6
|
+
WHERE topic={topic:String} AND ts>=fromUnixTimestamp64Milli({since:Int64})
|
|
7
|
+
AND ts<=fromUnixTimestamp64Milli({until:Int64}) ORDER BY ts`,
|
|
8
|
+
{topic,since:range.start.getTime(),until:range.end.getTime()});
|
|
9
|
+
return rows.map(row=>{return {timestamp:new Date(`${row.ts}Z`),value:row.value,unit};});
|
|
10
|
+
}
|
|
@@ -25,6 +25,7 @@ import clickhouseRises from './rises.js';
|
|
|
25
25
|
import clickhouseChanges from './changes.js';
|
|
26
26
|
import clickhouseHolds from './holds.js';
|
|
27
27
|
import clickhouseSeries from './series.js';
|
|
28
|
+
import clickhouseSamples from './samples.js';
|
|
28
29
|
import clickhouseLatest from './latest.js';
|
|
29
30
|
|
|
30
31
|
export default function clickhouseSensor(connection, topic, displayName, unit) {
|
|
@@ -35,6 +36,9 @@ export default function clickhouseSensor(connection, topic, displayName, unit) {
|
|
|
35
36
|
current() {
|
|
36
37
|
return clickhouseLatest(connection, topic, unit);
|
|
37
38
|
},
|
|
39
|
+
samples(range) {
|
|
40
|
+
return clickhouseSamples(connection, topic, range, unit);
|
|
41
|
+
},
|
|
38
42
|
measurements(range, step) {
|
|
39
43
|
return clickhouseSeries(connection, topic, range, step, unit);
|
|
40
44
|
},
|
|
@@ -1,30 +1,47 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
1
|
+
import { chartMetricsRange } from './metricsRelation.js';
|
|
2
|
+
|
|
3
|
+
function seriesPoints(rows,unit) {
|
|
4
|
+
const result=[];
|
|
5
|
+
let prior;
|
|
6
|
+
for (const row of rows) {
|
|
7
|
+
const timestamp=new Date(`${row.ts}Z`);
|
|
8
|
+
const separated=prior && row.segment!==undefined && String(row.segment)!==String(prior.segment);
|
|
9
|
+
if(separated && timestamp.getTime()-prior.timestamp.getTime()>1 && prior.value!==null && row.value!==null) {
|
|
10
|
+
result.push({timestamp:new Date(Math.floor((prior.timestamp.getTime()+timestamp.getTime())/2)),value:null,unit});
|
|
11
|
+
}
|
|
12
|
+
const point={timestamp,value:row.value,unit};
|
|
13
|
+
if(Number(row.native)===1) {point.continuous=Boolean(prior && !separated && prior.value!==null && row.value!==null);}
|
|
14
|
+
result.push(point);
|
|
15
|
+
prior={...row,timestamp};
|
|
16
|
+
}
|
|
17
|
+
return result;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Coarse buckets retain actual island boundaries, including subsecond timestamps. */
|
|
11
21
|
export default async function clickhouseSeries(connection, topic, range, step, unit) {
|
|
12
22
|
const seconds = Math.max(1, Math.floor(step / 1000));
|
|
13
23
|
const start = range.start.toISOString().replace('Z', '').replace('T', ' ');
|
|
14
24
|
const end = range.end.toISOString().replace('Z', '').replace('T', ' ');
|
|
15
25
|
const rows = await connection.query(
|
|
16
|
-
`
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
26
|
+
`WITH points AS (
|
|
27
|
+
SELECT * FROM ${chartMetricsRange('toUnixTimestamp64Milli({start:DateTime64(3)})','toUnixTimestamp64Milli({end:DateTime64(3)})')}
|
|
28
|
+
WHERE topic={topic:String} AND ts>={start:DateTime64(3)} AND ts<={end:DateTime64(3)}
|
|
29
|
+
), prior AS (
|
|
30
|
+
SELECT *,row_number() OVER (ORDER BY ts) AS ordinal,
|
|
31
|
+
lagInFrame(coverage_last_ms,1) OVER (ORDER BY ts) AS prior_last,
|
|
32
|
+
lagInFrame(max_gap_ms,1) OVER (ORDER BY ts) AS prior_gap,
|
|
33
|
+
lagInFrame(native,1) OVER (ORDER BY ts) AS prior_native FROM points
|
|
34
|
+
), segmented AS (
|
|
35
|
+
SELECT *,sum(toUInt8(ordinal=1 OR native!=prior_native OR max_gap_ms!=prior_gap OR max_gap_ms=0
|
|
36
|
+
OR coverage_first_ms>prior_last+toInt64(max_gap_ms))) OVER (ORDER BY ts) AS segment FROM prior
|
|
37
|
+
), buckets AS (
|
|
38
|
+
SELECT segment,native,toStartOfInterval(ts,INTERVAL ${seconds} SECOND) AS bucket,
|
|
39
|
+
min(ts) AS first_ts,max(ts) AS last_ts,argMin(value,ts) AS first_value,argMax(value,ts) AS last_value
|
|
40
|
+
FROM segmented GROUP BY segment,native,bucket
|
|
41
|
+
) SELECT tupleElement(vertex,1) AS ts,tupleElement(vertex,2) AS value,segment,native
|
|
42
|
+
FROM (SELECT segment,native,arrayJoin(arrayDistinct([tuple(first_ts,first_value),tuple(last_ts,last_value)])) AS vertex FROM buckets)
|
|
24
43
|
ORDER BY ts`,
|
|
25
44
|
{ topic, start, end }
|
|
26
45
|
);
|
|
27
|
-
return rows
|
|
28
|
-
return { timestamp: new Date(`${row.ts}Z`), value: row.value, unit };
|
|
29
|
-
});
|
|
46
|
+
return seriesPoints(rows,unit);
|
|
30
47
|
}
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
import retainMetricReceipts from '../../ingest/db/retainMetricReceipts.js';
|
|
2
|
+
import historyContext from './historyContext.js';
|
|
3
|
+
import historyAdmission, {assertHistoryReady} from './historyAdmission.js';
|
|
4
|
+
import {configureClassifier,saveCheckpoint} from './historyCheckpoint.js';
|
|
5
|
+
import historyCorrection from './historyCorrection.js';
|
|
6
|
+
import historyConfigure from './historyConfigure.js';
|
|
7
|
+
|
|
8
|
+
export const historyProtocol = 'stateful-correction-v1';
|
|
9
|
+
|
|
10
|
+
function machineName(machine) {
|
|
11
|
+
if (typeof machine !== 'string' || !machine || machine.length > 200) { throw new TypeError('machine required'); }
|
|
12
|
+
}
|
|
13
|
+
async function transaction(pool, machine, action, topology=false) {
|
|
14
|
+
machineName(machine);
|
|
15
|
+
const client = await pool.connect();
|
|
16
|
+
try {
|
|
17
|
+
await client.query('BEGIN');
|
|
18
|
+
if (topology) {await client.query("SELECT pg_advisory_xact_lock(hashtextextended('history:configuration',0))");}
|
|
19
|
+
await client.query('SELECT pg_advisory_xact_lock(hashtextextended($1, 0))', [`history:${machine}`]);
|
|
20
|
+
const result = await action(client);
|
|
21
|
+
await client.query('COMMIT');
|
|
22
|
+
return result;
|
|
23
|
+
} catch (error) { await client.query('ROLLBACK'); throw error; } finally { client.release(); }
|
|
24
|
+
}
|
|
25
|
+
function observations(items) {
|
|
26
|
+
if (!Array.isArray(items) || items.length > 500) { throw new TypeError('At most 500 observations required'); }
|
|
27
|
+
items.forEach((item) => {
|
|
28
|
+
if (typeof item.eventId !== 'string' || !item.eventId || typeof item.channel !== 'string' || !item.channel
|
|
29
|
+
|| !Number.isSafeInteger(item.time) || !Number.isFinite(item.value)) { throw new TypeError('Invalid observation'); }
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
function accept(pool, machine, items, cutoff) {
|
|
33
|
+
observations(items);
|
|
34
|
+
return transaction(pool, machine, async (client) => {
|
|
35
|
+
const added = [];
|
|
36
|
+
for (const item of items) {
|
|
37
|
+
// First committed observation wins; duplicates cannot mutate history or create work.
|
|
38
|
+
// eslint-disable-next-line no-await-in-loop
|
|
39
|
+
const result = await client.query(`INSERT INTO history_observations(machine,channel,time_ms,event_id,value)
|
|
40
|
+
VALUES($1,$2,$3,$4,$5) ON CONFLICT DO NOTHING RETURNING time_ms`, [machine, item.channel, item.time, item.eventId, item.value]);
|
|
41
|
+
if (result.rowCount && item.time >= cutoff) { added.push(item.time); }
|
|
42
|
+
}
|
|
43
|
+
const configured = await client.query('SELECT bucket_ms FROM history_topics WHERE machine=$1 LIMIT 1', [machine]);
|
|
44
|
+
const bucket = Number(configured.rows[0]?.bucket_ms ?? 30000);
|
|
45
|
+
for (const time of added) {
|
|
46
|
+
// eslint-disable-next-line no-await-in-loop
|
|
47
|
+
await client.query(`INSERT INTO history_work(id,machine,from_ms,until_ms)
|
|
48
|
+
VALUES(md5($1||':'||$2::text)::uuid,$1,$3,$3)
|
|
49
|
+
ON CONFLICT(id) DO UPDATE SET token=gen_random_uuid(),cursor_ms=NULL,end_ms=NULL,from_ms=least(history_work.from_ms,excluded.from_ms),until_ms=greatest(history_work.until_ms,excluded.until_ms)`,
|
|
50
|
+
[machine,Math.floor(time/bucket),time]);
|
|
51
|
+
}
|
|
52
|
+
return { inserted: added.length };
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
function context(pool,machine,from,until,options) {
|
|
56
|
+
machineName(machine);
|
|
57
|
+
return historyContext(pool,machine,from,until,options);
|
|
58
|
+
}
|
|
59
|
+
async function unchanged(client, machine, base, {observationSource,timeScale}) {
|
|
60
|
+
await client.query('LOCK TABLE segments IN SHARE ROW EXCLUSIVE MODE');
|
|
61
|
+
const latest = await context(client, machine, base.from, base.until, { padding: base.paddingMs, cutoff: -Infinity,cursor:base.cursor ?? null,end:base.end ?? null,classifierKey:base.classifierKey,workId:base.workId,workToken:base.workToken,timeScale,observations:observationSource?.(client) });
|
|
62
|
+
if (latest.revision !== base.revision) {
|
|
63
|
+
const error = new Error('History context changed');
|
|
64
|
+
error.statusCode = 409;
|
|
65
|
+
throw error;
|
|
66
|
+
}
|
|
67
|
+
return latest;
|
|
68
|
+
}
|
|
69
|
+
function checkClaim(work, base) {
|
|
70
|
+
if (String(work.token) !== base?.workToken || Number(work.from_ms)<base.from || Number(work.until_ms)>base.until || (work.cursor_ms === null ? null : Number(work.cursor_ms)) !== (base.cursor ?? null) || (work.end_ms === null ? null : Number(work.end_ms)) !== (base.end ?? null)) {
|
|
71
|
+
const error = new Error('History work claim changed');
|
|
72
|
+
error.statusCode=409;
|
|
73
|
+
throw error;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
async function advance(client,machine,workId,page) {
|
|
77
|
+
if (page?.next !== null && page?.next !== undefined) {
|
|
78
|
+
await client.query('UPDATE history_work SET cursor_ms=$3,end_ms=$4,token=gen_random_uuid() WHERE id=$1 AND machine=$2',[workId,machine,page.next,page.end]);
|
|
79
|
+
} else { await client.query('DELETE FROM history_work WHERE id=$1 AND machine=$2', [workId, machine]); }
|
|
80
|
+
}
|
|
81
|
+
function commit(pool, machine, workId, segments, {base, observationSource,timeScale}) {
|
|
82
|
+
if (!Array.isArray(segments) || segments.length > 1000) { throw new TypeError('Bounded segments required'); }
|
|
83
|
+
// eslint-disable-next-line max-statements -- Claim, correction, checkpoint and advancement share one atomic boundary.
|
|
84
|
+
return transaction(pool, machine, async (client) => {
|
|
85
|
+
const work = await client.query(`SELECT id,token,from_ms,until_ms,cursor_ms,end_ms${base?.replace?',generation':''} FROM history_work WHERE id=$1 AND machine=$2 FOR UPDATE`, [workId, machine]);
|
|
86
|
+
if (!work.rowCount) { return { applied: false }; }
|
|
87
|
+
checkClaim(work.rows[0],base);
|
|
88
|
+
if (segments.length && !base?.revision) { throw new TypeError('History context revision required'); }
|
|
89
|
+
if (observationSource) { await assertHistoryReady(client,machine); }
|
|
90
|
+
const latest = base?.revision ? await unchanged(client, machine, base, {observationSource,timeScale}) : null;
|
|
91
|
+
if (latest && segments.some((item) => { return new Date(item.end_time).getTime()>Math.round(latest.context.page.until/timeScale); })) {
|
|
92
|
+
throw new TypeError('Segment extends beyond bounded history page; upgrade history worker');
|
|
93
|
+
}
|
|
94
|
+
if(base?.replace){
|
|
95
|
+
const next=await historyCorrection(client,machine,work.rows[0],segments,{base,context:latest,timeScale});
|
|
96
|
+
await advance(client,machine,workId,next);
|
|
97
|
+
return {applied:true};
|
|
98
|
+
}
|
|
99
|
+
await client.query(`INSERT INTO history_annotations(machine,kind,start_time,name,end_time,duration,tags,properties,resolved)
|
|
100
|
+
SELECT machine,kind,start_time,name,end_time,duration,tags,properties,resolved FROM segments
|
|
101
|
+
WHERE machine=$1 AND start_time<=$3 AND end_time>=$2
|
|
102
|
+
ON CONFLICT(machine,kind,start_time,name) DO UPDATE SET end_time=greatest(history_annotations.end_time,EXCLUDED.end_time),duration=EXCLUDED.duration,tags=EXCLUDED.tags,properties=EXCLUDED.properties,resolved=EXCLUDED.resolved`, [machine,new Date((latest?.context.page.from ?? base.from)/timeScale),new Date((latest?.context.page.until ?? base.until)/timeScale)]);
|
|
103
|
+
for (const item of segments) {
|
|
104
|
+
// Only computed fields change. User cuts/labels must be applied by caller before commit.
|
|
105
|
+
// eslint-disable-next-line no-await-in-loop
|
|
106
|
+
await client.query(`INSERT INTO segments(machine,kind,name,start_time,end_time,duration,options,tags,properties,resolved)
|
|
107
|
+
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10) ON CONFLICT(machine,kind,start_time) DO UPDATE
|
|
108
|
+
SET name=EXCLUDED.name,end_time=EXCLUDED.end_time,duration=EXCLUDED.duration,options=EXCLUDED.options,updated_at=clock_timestamp(),
|
|
109
|
+
tags=CASE WHEN segments.name=EXCLUDED.name THEN segments.tags ELSE EXCLUDED.tags END,
|
|
110
|
+
properties=CASE WHEN segments.name=EXCLUDED.name THEN segments.properties ELSE EXCLUDED.properties END,
|
|
111
|
+
resolved=CASE WHEN segments.name=EXCLUDED.name THEN segments.resolved ELSE EXCLUDED.resolved END`,
|
|
112
|
+
[machine, item.kind ?? 'phase', item.name, item.start_time, item.end_time, item.duration,
|
|
113
|
+
typeof item.options === 'string' ? item.options : JSON.stringify(item.options ?? null),
|
|
114
|
+
typeof item.tags === 'string' ? item.tags : JSON.stringify(item.tags ?? null),
|
|
115
|
+
typeof item.properties === 'string' ? item.properties : JSON.stringify(item.properties ?? null), item.resolved ?? true]);
|
|
116
|
+
}
|
|
117
|
+
const converged=await saveCheckpoint(client,machine,base?.checkpoint,latest);
|
|
118
|
+
await advance(client,machine,workId,converged ? {next:null} : latest?.context.page);
|
|
119
|
+
return { applied: true };
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
/** Local telemetry history and durable classification work; no cross-edge database dependency. */
|
|
123
|
+
export default function historyPg(pool, { retentionDays = 30, now = Date.now, observations: observationSource,timeScale=1,timestamp } = {}) {
|
|
124
|
+
if (![1,1000].includes(timeScale) || (timeScale!==1 && !observationSource)) {throw new TypeError('External history supports millisecond or microsecond coordinates');}
|
|
125
|
+
if (!Number.isSafeInteger(retentionDays) || retentionDays <= 0) { throw new TypeError('Positive retentionDays required'); }
|
|
126
|
+
function cutoff() { return (now() - retentionDays * 86400000)*timeScale; }
|
|
127
|
+
const admission=observationSource ? historyAdmission(pool,{now:()=>{return now()*timeScale;},timeScale,timestamp}) : null;
|
|
128
|
+
return {
|
|
129
|
+
...(admission ?? {}),
|
|
130
|
+
configure(machine, topics, bucketMs = 30000, classifierKey = undefined) {
|
|
131
|
+
if (classifierKey && !observationSource) {throw new TypeError('Stateful classification requires an external observation source');}
|
|
132
|
+
if (!Array.isArray(topics) || topics.length > 500 || !Number.isSafeInteger(bucketMs) || bucketMs <= 0) { throw new TypeError('Invalid history topics'); }
|
|
133
|
+
return transaction(pool,machine,async (client) => {
|
|
134
|
+
const source=observationSource?.(client);
|
|
135
|
+
const result=await historyConfigure(client,machine,topics,bucketMs*timeScale,{retentionDays,observations:source});
|
|
136
|
+
await configureClassifier(client,machine,classifierKey,source);
|
|
137
|
+
return {...result,...((timeScale!==1 || classifierKey) && {timeScale}),...(classifierKey && {classifierProtocol:historyProtocol})};
|
|
138
|
+
},true);
|
|
139
|
+
},
|
|
140
|
+
async purge() {
|
|
141
|
+
const result = await pool.query(`DELETE FROM history_observations o WHERE time_ms < $1
|
|
142
|
+
AND NOT EXISTS (SELECT 1 FROM history_work w WHERE w.machine=o.machine
|
|
143
|
+
AND (o.time_ms BETWEEN w.from_ms-86400000 AND greatest(w.until_ms,COALESCE(w.end_ms,w.until_ms))+86400000
|
|
144
|
+
OR (o.time_ms<w.from_ms-86400000 AND NOT EXISTS (SELECT 1 FROM history_observations anchor
|
|
145
|
+
WHERE anchor.machine=o.machine AND anchor.channel=o.channel AND anchor.time_ms>o.time_ms AND anchor.time_ms<w.from_ms-86400000))))
|
|
146
|
+
AND EXISTS (SELECT 1 FROM history_observations newer WHERE newer.machine=o.machine
|
|
147
|
+
AND newer.channel=o.channel AND newer.time_ms>o.time_ms AND newer.time_ms<$1)`, [cutoff()]);
|
|
148
|
+
await retainMetricReceipts(pool, retentionDays);
|
|
149
|
+
return result.rowCount;
|
|
150
|
+
},
|
|
151
|
+
accept(machine, items) {
|
|
152
|
+
if (observationSource) { throw new TypeError('External observations require durable telemetry admission'); }
|
|
153
|
+
return accept(pool, machine, items, cutoff()); },
|
|
154
|
+
context(machine, from, until, padding = 60000*timeScale, page = {}) {
|
|
155
|
+
async function read(connection){
|
|
156
|
+
if(observationSource){await assertHistoryReady(connection,machine);}
|
|
157
|
+
return context(connection,machine,from,until,{padding,cutoff:cutoff(),...page,timeScale,observations:observationSource?.(connection)});
|
|
158
|
+
}
|
|
159
|
+
return page.classifierKey && page.workId ? transaction(pool,machine,read) : read(pool);
|
|
160
|
+
},
|
|
161
|
+
async work(machine) {
|
|
162
|
+
machineName(machine);
|
|
163
|
+
if (observationSource) { try { await assertHistoryReady(pool,machine); } catch (error) { if (error.statusCode===409) { return {items:[]}; } throw error; } }
|
|
164
|
+
const result = await pool.query('SELECT id,token,machine AS "streamId",from_ms AS "from",until_ms AS "until",cursor_ms AS cursor,end_ms AS end FROM history_work WHERE machine=$1 ORDER BY until_ms DESC,created_at,id LIMIT 8', [machine]);
|
|
165
|
+
return { items: result.rows.map((row) => { return { ...row, from: Number(row.from), until: Number(row.until),cursor:row.cursor === null ? null : Number(row.cursor),end:row.end === null ? null : Number(row.end) }; }) };
|
|
166
|
+
},
|
|
167
|
+
commit(machine, workId, segments, base) { return commit(pool, machine, workId, segments, {base, observationSource,timeScale}); }
|
|
168
|
+
};
|
|
169
|
+
}
|