@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,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
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import {createHash} from 'node:crypto';
|
|
2
|
+
|
|
3
|
+
function normalized(records,{timestamp,timeScale}) {
|
|
4
|
+
if (!Array.isArray(records) || !records.length || records.length>10000) { throw new TypeError('Bounded telemetry admissions required'); }
|
|
5
|
+
return records.map(({topic,ts,value}) => {
|
|
6
|
+
const time=timestamp ? timestamp(ts) : (ts instanceof Date ? ts.getTime() : ts)*timeScale;
|
|
7
|
+
if (typeof topic!=='string' || !topic || !Number.isSafeInteger(time) || !Number.isFinite(value)) { throw new TypeError('Original integer timestamp and finite admission value required'); }
|
|
8
|
+
const binary=Buffer.alloc(8); binary.writeDoubleLE(value);
|
|
9
|
+
return {topic,time,id:createHash('sha256').update(`${Buffer.byteLength(topic)}:${topic}:${time}:`).update(binary).digest('hex')};
|
|
10
|
+
}).sort((a,b) => { return a.id.localeCompare(b.id); });
|
|
11
|
+
}
|
|
12
|
+
async function mapped(client,records) {
|
|
13
|
+
const result=await client.query(`SELECT t.machine,t.topic,t.bucket_ms,t.retention_days,COALESCE(r.retained_from,-9007199254740991) AS retained_from
|
|
14
|
+
FROM history_topics t LEFT JOIN history_sources s ON s.machine=t.machine LEFT JOIN history_retention r ON r.source_id=s.source_id
|
|
15
|
+
WHERE t.topic=ANY($1::text[]) ORDER BY t.machine,t.topic`,[[...new Set(records.map(({topic}) => {return topic;}))]]);
|
|
16
|
+
return result.rows;
|
|
17
|
+
}
|
|
18
|
+
async function locks(client,mappings) {
|
|
19
|
+
for (const machine of [...new Set(mappings.map((row) => {return row.machine;}))].sort()) {
|
|
20
|
+
// eslint-disable-next-line no-await-in-loop
|
|
21
|
+
await client.query('SELECT pg_advisory_xact_lock(hashtextextended($1,0))',[`history:${machine}`]);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
async function transaction(pool,records,action,options) {
|
|
25
|
+
const items=normalized(records,options);
|
|
26
|
+
const client=await pool.connect();
|
|
27
|
+
try {
|
|
28
|
+
await client.query('BEGIN');
|
|
29
|
+
await client.query("SELECT pg_advisory_xact_lock(hashtextextended('history:configuration',0))");
|
|
30
|
+
const mappings=await mapped(client,items);
|
|
31
|
+
await locks(client,mappings);
|
|
32
|
+
await action(client,items,mappings);
|
|
33
|
+
await client.query('COMMIT');
|
|
34
|
+
} catch (error) { await client.query('ROLLBACK'); throw error; } finally { client.release(); }
|
|
35
|
+
}
|
|
36
|
+
export async function assertHistoryReady(pool,machine) {
|
|
37
|
+
const result=await pool.query('SELECT 1 FROM history_admissions a JOIN history_topics t ON t.topic=a.topic WHERE t.machine=$1 LIMIT 1',[machine]);
|
|
38
|
+
if (result.rowCount) { const error=new Error('Unfinished external telemetry admission'); error.statusCode=409; throw error; }
|
|
39
|
+
}
|
|
40
|
+
async function enqueue(client,mapping,row) {
|
|
41
|
+
const pending=await client.query('SELECT id FROM history_work WHERE machine=$1 AND cursor_ms IS NULL AND end_ms IS NULL AND floor(from_ms::numeric/$2)=floor($3::numeric/$2) ORDER BY created_at LIMIT 1',[mapping.machine,mapping.bucket_ms,row.time]);
|
|
42
|
+
if(pending.rowCount){
|
|
43
|
+
await client.query('UPDATE history_work SET token=gen_random_uuid(),generation=gen_random_uuid(),started=false,classifier_checkpoint=NULL,correction_from=NULL,correction_until=NULL,from_ms=least(from_ms,$2),until_ms=greatest(until_ms,$2) WHERE id=$1',[pending.rows[0].id,row.time]);
|
|
44
|
+
}else{await client.query('INSERT INTO history_work(id,machine,from_ms,until_ms) VALUES(gen_random_uuid(),$1,$2,$2)',[mapping.machine,row.time]);}
|
|
45
|
+
}
|
|
46
|
+
/** Durable queue redelivery owns payload recovery. Barriers never expire on a timer. */
|
|
47
|
+
export default function historyAdmission(pool,{now=Date.now,timeScale=1,timestamp}={}) {
|
|
48
|
+
return {
|
|
49
|
+
prepare(records) {
|
|
50
|
+
return transaction(pool,records,async (client,items) => {
|
|
51
|
+
for (const row of items) {
|
|
52
|
+
// eslint-disable-next-line no-await-in-loop
|
|
53
|
+
await client.query('INSERT INTO history_admissions(event_id,topic,time_ms,admitted_at) VALUES($1,$2,$3,$4) ON CONFLICT DO NOTHING',[row.id,row.topic,row.time,now()]);
|
|
54
|
+
}
|
|
55
|
+
},{timeScale,timestamp});
|
|
56
|
+
},
|
|
57
|
+
complete(records) {
|
|
58
|
+
return transaction(pool,records,async (client,items,mappings) => {
|
|
59
|
+
const ids=[...new Set(items.map(({id}) => {return id;}))];
|
|
60
|
+
const prepared=await client.query('SELECT event_id,COALESCE(admitted_at,extract(epoch FROM created_at)*$2)::bigint AS admitted_at FROM history_admissions WHERE event_id=ANY($1::text[]) ORDER BY event_id',[ids,1000*timeScale]);
|
|
61
|
+
if (prepared.rowCount!==ids.length) { throw new TypeError('Durable prepare required before admission completion'); }
|
|
62
|
+
const admitted=new Map(prepared.rows.map(row=>{return [row.event_id,Number(row.admitted_at)];}));
|
|
63
|
+
for (const mapping of mappings) {
|
|
64
|
+
const eligible=items.filter(row=>{return row.topic===mapping.topic && row.time>=Math.max(Number(mapping.retained_from),admitted.get(row.id)-mapping.retention_days*86400000*timeScale);});
|
|
65
|
+
const times=eligible.map(({time}) => {return time;});
|
|
66
|
+
if (times.length) {
|
|
67
|
+
// eslint-disable-next-line no-await-in-loop
|
|
68
|
+
await client.query('UPDATE history_checkpoints SET valid=false WHERE machine=$1 AND time_ms>=$2',[mapping.machine,Math.min(...times)]);
|
|
69
|
+
// eslint-disable-next-line no-await-in-loop
|
|
70
|
+
await client.query('UPDATE history_work SET token=gen_random_uuid(),cursor_ms=NULL,end_ms=NULL,generation=gen_random_uuid(),classifier_checkpoint=NULL,correction_from=NULL,correction_until=NULL,started=false WHERE machine=$1 AND cursor_ms>$2',[mapping.machine,Math.min(...times)]);
|
|
71
|
+
}
|
|
72
|
+
for (const row of eligible) {
|
|
73
|
+
// eslint-disable-next-line no-await-in-loop
|
|
74
|
+
await enqueue(client,mapping,row);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
await client.query('DELETE FROM history_admissions WHERE event_id=ANY($1::text[])',[items.map(({id}) => {return id;})]);
|
|
78
|
+
},{timeScale,timestamp});
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
export async function assertClassifier(pool,machine,key) {
|
|
2
|
+
if (typeof key!=='string' || !key || key.length>200) { throw new TypeError('Bounded classifier identity required'); }
|
|
3
|
+
const current=await pool.query('SELECT classifier_key FROM history_classifiers WHERE machine=$1',[machine]);
|
|
4
|
+
if (current.rows[0]?.classifier_key!==key) {const error=new Error('History classifier changed');error.statusCode=409;throw error;}
|
|
5
|
+
}
|
|
6
|
+
export async function classifierClaim(pool,machine,{workId,workToken,from,until,cursor,end}) {
|
|
7
|
+
if(!workId){return null;}
|
|
8
|
+
const result=await pool.query('SELECT classifier_checkpoint,started,from_ms,until_ms,cursor_ms,end_ms FROM history_work WHERE id=$1 AND machine=$2 AND token=$3',[workId,machine,workToken]);
|
|
9
|
+
const row=result.rows[0];
|
|
10
|
+
if(!row || Number(row.from_ms)!==from || Number(row.until_ms)!==until || (row.cursor_ms===null?null:Number(row.cursor_ms))!==cursor || (row.end_ms===null?null:Number(row.end_ms))!==end){const error=new Error('History work claim changed');error.statusCode=409;throw error;}
|
|
11
|
+
return row;
|
|
12
|
+
}
|
|
13
|
+
export async function classifierSeed(pool,machine,before,key,{claim,cursor}={}) {
|
|
14
|
+
await assertClassifier(pool,machine,key);
|
|
15
|
+
if(claim && cursor!==null){
|
|
16
|
+
const checkpoint=claim.classifier_checkpoint;
|
|
17
|
+
if(!checkpoint || checkpoint.key!==key){throw new Error('Durable classifier continuation checkpoint required');}
|
|
18
|
+
return {at:checkpoint.at,state:checkpoint.state};
|
|
19
|
+
}
|
|
20
|
+
const result=await pool.query('SELECT time_ms,state FROM history_checkpoints WHERE machine=$1 AND classifier_key=$2 AND valid AND time_ms<$3 ORDER BY time_ms DESC LIMIT 1',[machine,key,before]);
|
|
21
|
+
return result.rowCount ? {at:Number(result.rows[0].time_ms),state:result.rows[0].state} : null;
|
|
22
|
+
}
|
|
23
|
+
export async function classifierPage(pool,machine,page,key) {
|
|
24
|
+
const target=await pool.query('SELECT time_ms FROM history_checkpoints WHERE machine=$1 AND classifier_key=$2 AND time_ms BETWEEN $3 AND $4 ORDER BY time_ms LIMIT 1',[machine,key,page.from,page.until]);
|
|
25
|
+
if (!target.rowCount || Number(target.rows[0].time_ms)===page.until) { return page; }
|
|
26
|
+
const until=Number(target.rows[0].time_ms);
|
|
27
|
+
return {...page,until,next:until+1};
|
|
28
|
+
}
|
|
29
|
+
/** Checkpoints are committed in the same transaction as segments and the work cursor. */
|
|
30
|
+
export async function saveCheckpoint(client,machine,checkpoint,context,work) {
|
|
31
|
+
if (!checkpoint) {return false;}
|
|
32
|
+
const {key,at,state}=checkpoint;
|
|
33
|
+
if (!context || key!==context.context.classifierKey || !Number.isSafeInteger(at) || at!==context.items.at(-1)?.time
|
|
34
|
+
|| !state || typeof state!=='object' || Array.isArray(state) || Buffer.byteLength(JSON.stringify(state))>1048576) {
|
|
35
|
+
throw new TypeError('Invalid bounded classifier checkpoint');
|
|
36
|
+
}
|
|
37
|
+
await assertClassifier(client,machine,key);
|
|
38
|
+
const result=await client.query('SELECT 1 FROM history_checkpoints WHERE machine=$1 AND classifier_key=$2 AND time_ms=$3 AND state=$4::jsonb',[machine,key,at,JSON.stringify(state)]);
|
|
39
|
+
if(work){
|
|
40
|
+
await client.query('INSERT INTO history_staged_checkpoints(work_id,generation,machine,classifier_key,time_ms,state) VALUES($1,$2,$3,$4,$5,$6) ON CONFLICT(work_id,generation,classifier_key,time_ms) DO UPDATE SET state=EXCLUDED.state',[work.id,work.generation,machine,key,at,JSON.stringify(state)]);
|
|
41
|
+
await client.query('UPDATE history_work SET classifier_checkpoint=$2 WHERE id=$1',[work.id,JSON.stringify(checkpoint)]);
|
|
42
|
+
} else {
|
|
43
|
+
await client.query('INSERT INTO history_checkpoints(machine,classifier_key,time_ms,state,valid) VALUES($1,$2,$3,$4,true) ON CONFLICT(machine,classifier_key,time_ms) DO UPDATE SET state=EXCLUDED.state,valid=true',[machine,key,at,JSON.stringify(state)]);
|
|
44
|
+
}
|
|
45
|
+
return result.rowCount>0 && at>=context.context.until;
|
|
46
|
+
}
|
|
47
|
+
export async function configureClassifier(client,machine,key,source) {
|
|
48
|
+
if (key===undefined) {return;}
|
|
49
|
+
if (typeof key!=='string' || !key || key.length>200) { throw new TypeError('Bounded classifier identity required'); }
|
|
50
|
+
const old=await client.query('SELECT classifier_key FROM history_classifiers WHERE machine=$1',[machine]);
|
|
51
|
+
await client.query('INSERT INTO history_classifiers(machine,classifier_key) VALUES($1,$2) ON CONFLICT(machine) DO UPDATE SET classifier_key=EXCLUDED.classifier_key',[machine,key]);
|
|
52
|
+
if (old.rows[0]?.classifier_key===key) {return;}
|
|
53
|
+
await client.query('DELETE FROM history_checkpoints WHERE machine=$1',[machine]);
|
|
54
|
+
await client.query('UPDATE history_work SET token=gen_random_uuid(),cursor_ms=NULL,end_ms=NULL,generation=gen_random_uuid(),classifier_checkpoint=NULL,correction_from=NULL,correction_until=NULL,started=false WHERE machine=$1',[machine]);
|
|
55
|
+
if (source?.registered) { await source.registered(machine,[],{reset:true}); }
|
|
56
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/** First registration/new topics import existing durable telemetry before enabling history polling. */
|
|
2
|
+
export default async function historyConfigure(client,machine,topics,bucketMs,{retentionDays,observations}) {
|
|
3
|
+
const previous = await client.query('SELECT topic FROM history_topics WHERE machine=$1',[machine]);
|
|
4
|
+
const known = new Set(previous.rows.map((row) => { return row.topic; }));
|
|
5
|
+
await client.query('DELETE FROM history_topics WHERE machine=$1',[machine]);
|
|
6
|
+
for (const item of topics) {
|
|
7
|
+
if (typeof item.topic !== 'string' || !item.topic || typeof item.channel !== 'string' || !item.channel) { throw new TypeError('Invalid history topic'); }
|
|
8
|
+
// eslint-disable-next-line no-await-in-loop
|
|
9
|
+
await client.query('INSERT INTO history_topics(machine,topic,channel,bucket_ms,retention_days) VALUES($1,$2,$3,$4,$5)',[machine,item.topic,item.channel,bucketMs,retentionDays]);
|
|
10
|
+
}
|
|
11
|
+
const added = topics.filter((item) => { return !known.has(item.topic); }).map((item) => { return item.topic; });
|
|
12
|
+
if (observations?.registered) {
|
|
13
|
+
await observations.registered(machine,added,{bucketMs,retentionDays});
|
|
14
|
+
} else if (added.length) {
|
|
15
|
+
await client.query(`WITH imported AS (
|
|
16
|
+
INSERT INTO history_observations(machine,channel,time_ms,event_id,value)
|
|
17
|
+
SELECT $1,t.channel,floor(extract(epoch FROM m.ts)*1000)::bigint,
|
|
18
|
+
md5(m.topic||':'||floor(extract(epoch FROM m.ts)*1000)::bigint::text||':'||m.value::text),m.value
|
|
19
|
+
FROM metrics m JOIN history_topics t ON t.machine=$1 AND t.topic=m.topic
|
|
20
|
+
WHERE m.topic=ANY($2::text[]) AND m.ts>=now()-make_interval(days=>$3)
|
|
21
|
+
ORDER BY m.ts,m.ctid ON CONFLICT DO NOTHING RETURNING time_ms
|
|
22
|
+
) INSERT INTO history_work(id,machine,from_ms,until_ms)
|
|
23
|
+
SELECT md5($1||':'||(time_ms/$4)::text)::uuid,$1,min(time_ms),max(time_ms) FROM imported GROUP BY time_ms/$4
|
|
24
|
+
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)`,
|
|
25
|
+
[machine,added,retentionDays,bucketMs]);
|
|
26
|
+
}
|
|
27
|
+
return {configured:topics.length};
|
|
28
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import historySeed from './historySeed.js';
|
|
3
|
+
import historyObservationsPg from './historyObservations.js';
|
|
4
|
+
import {classifierClaim,classifierPage,classifierSeed} from './historyCheckpoint.js';
|
|
5
|
+
|
|
6
|
+
function bounded(rows) {
|
|
7
|
+
if (rows.length>10000) { throw new Error('History context capacity exceeded; retain work for bounded refinement'); }
|
|
8
|
+
return rows;
|
|
9
|
+
}
|
|
10
|
+
async function segmentBoundary(pool,machine,right,segments,timeScale) {
|
|
11
|
+
const last = segments.at(-1);
|
|
12
|
+
if (!last) { return right; }
|
|
13
|
+
const following = await pool.query(`SELECT start_time FROM segments WHERE machine=$1 AND kind=$2 AND start_time>$3 AND name<>$4 ORDER BY start_time LIMIT 1`,[machine,last.kind,last.start_time,last.name]);
|
|
14
|
+
const stop = following.rows[0]?.start_time;
|
|
15
|
+
if (stop) { return Math.max(right,new Date(stop).getTime()*timeScale); }
|
|
16
|
+
const tail = await pool.query(`SELECT max(end_time) AS end_time FROM segments WHERE machine=$1 AND kind=$2 AND start_time>=$3`,[machine,last.kind,last.start_time]);
|
|
17
|
+
return Math.max(right,new Date(tail.rows[0].end_time ?? last.end_time).getTime()*timeScale);
|
|
18
|
+
}
|
|
19
|
+
/** Read a finite dependency envelope in stored history, compacting unchanged heartbeat observations. */
|
|
20
|
+
// eslint-disable-next-line max-statements
|
|
21
|
+
export default async function historyContext(pool,machine,from,until,{padding,cutoff,cursor = null,end: envelope = null,observations: source = historyObservationsPg(pool),classifierKey,timeScale=1,workId,workToken}) {
|
|
22
|
+
if (![from,until,padding].every(Number.isSafeInteger) || from>until || padding<0 || padding>86400000*timeScale) { throw new TypeError('Invalid history range'); }
|
|
23
|
+
const range = { from,until,paddingMs:padding,cursor,end:envelope,...(classifierKey && {classifierKey}),...(timeScale!==1 && {timeScale}),...(workId && {workId,workToken}) };
|
|
24
|
+
if ((cursor !== null && !Number.isSafeInteger(cursor)) || (envelope !== null && !Number.isSafeInteger(envelope))) { throw new TypeError('Invalid history cursor'); }
|
|
25
|
+
const claim=await classifierClaim(pool,machine,{workId,workToken,from,until,cursor,end:envelope});
|
|
26
|
+
if (from<cutoff && !claim) {
|
|
27
|
+
const pending = cursor === null || envelope === null ? {rowCount:0} : await pool.query(`SELECT 1 FROM history_work WHERE machine=$1 AND from_ms=$2 AND until_ms=$3 AND cursor_ms=$4 AND end_ms=$5 LIMIT 1`,[machine,from,until,cursor,envelope]);
|
|
28
|
+
if (!pending.rowCount) { return {available:false,items:[],segments:[],annotations:[],context:range}; }
|
|
29
|
+
}
|
|
30
|
+
const classifier=classifierKey ? await classifierSeed(pool,machine,cursor ?? from,classifierKey,{claim,cursor}) : null;
|
|
31
|
+
let left = cursor ?? from-padding;
|
|
32
|
+
if (classifierKey && cursor===null) { left=classifier ? classifier.at+1 : await source.start(machine); }
|
|
33
|
+
const right = classifierKey && envelope!==null ? envelope : Math.max(envelope ?? until,await source.boundary(machine,from,until,padding));
|
|
34
|
+
const previous = await pool.query(`SELECT kind,name,start_time,end_time FROM segments WHERE machine=$1 AND kind='phase' AND start_time<=$2 ORDER BY start_time DESC LIMIT 1`,[machine,new Date(right/timeScale)]);
|
|
35
|
+
const tail=classifierKey ? await pool.query("SELECT max(end_time) AS end_time FROM segments WHERE machine=$1 AND kind='phase'",[machine]) : null;
|
|
36
|
+
const end = classifierKey && envelope!==null ? envelope : Math.max(envelope ?? right,await segmentBoundary(pool,machine,right,previous.rows,timeScale),tail?.rows[0]?.end_time ? new Date(tail.rows[0].end_time).getTime()*timeScale : -Infinity);
|
|
37
|
+
if(classifierKey && claim && envelope===null){
|
|
38
|
+
await pool.query('UPDATE history_work SET end_ms=$3 WHERE id=$1 AND machine=$2',[workId,machine,end]);
|
|
39
|
+
range.end=end;
|
|
40
|
+
}
|
|
41
|
+
// Fetch timestamp keys only, then read at most 250 complete groups. Never fetch the raw dependency tail.
|
|
42
|
+
const rawPage = await source.page(machine,left,end);
|
|
43
|
+
const page=classifierKey ? await classifierPage(pool,machine,rawPage,classifierKey) : rawPage;
|
|
44
|
+
const {next,until:pageEnd} = page;
|
|
45
|
+
range.page = page;
|
|
46
|
+
const segments = await pool.query(`SELECT kind,name,start_time,end_time,duration,options,tags,properties,resolved,consumed FROM segments
|
|
47
|
+
WHERE machine=$1 AND kind='phase' AND start_time<=$3 AND (end_time>=$2 OR (duration=0 AND start_time>=$2)) ORDER BY start_time LIMIT 10001`,[machine,new Date(left/timeScale),new Date(pageEnd/timeScale)]);
|
|
48
|
+
bounded(segments.rows);
|
|
49
|
+
const observations = await source.read(machine,left,pageEnd,padding);
|
|
50
|
+
const annotations = await pool.query(`SELECT a.kind,a.name,a.start_time,a.end_time,a.duration,
|
|
51
|
+
CASE WHEN s.machine IS NOT NULL THEN s.tags ELSE a.tags END AS tags,
|
|
52
|
+
CASE WHEN s.machine IS NOT NULL THEN s.properties ELSE a.properties END AS properties,
|
|
53
|
+
CASE WHEN s.machine IS NOT NULL THEN s.resolved ELSE a.resolved END AS resolved
|
|
54
|
+
FROM history_annotations a LEFT JOIN segments s ON s.machine=a.machine AND s.kind=a.kind AND s.start_time=a.start_time AND s.name=a.name
|
|
55
|
+
WHERE a.machine=$1 AND a.kind='phase' AND a.start_time<=$3 AND a.end_time>=$2
|
|
56
|
+
AND (COALESCE(a.tags,'') NOT IN ('','null','[]') OR COALESCE(a.properties,'') NOT IN ('','null','{}')) ORDER BY a.start_time,a.name LIMIT 10001`,
|
|
57
|
+
[machine,new Date(left/timeScale),new Date(pageEnd/timeScale)]);
|
|
58
|
+
bounded(annotations.rows);
|
|
59
|
+
const initial = classifierKey ? null : await historySeed(pool,machine,left,padding,{observations:source,timeScale});
|
|
60
|
+
if (initial?.segment && !segments.rows.some((row) => { return row.start_time.getTime() === initial.segment.start_time.getTime(); })) { segments.rows.unshift(initial.segment); }
|
|
61
|
+
const last = observations.items.at(-1)?.time;
|
|
62
|
+
const rightClosed = next === null && last !== undefined && segments.rows.some((row) => { return row.duration>0 && new Date(row.end_time).getTime()*timeScale>=last; });
|
|
63
|
+
const snapshot = { page,initial,...(classifierKey && {classifierSeed:classifier}),annotations:annotations.rows,segments:segments.rows,...observations,rightClosed };
|
|
64
|
+
return { ...snapshot,available:true,revision:createHash('sha256').update(JSON.stringify(snapshot)).digest('hex'),context:range };
|
|
65
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import {saveCheckpoint} from './historyCheckpoint.js';
|
|
2
|
+
|
|
3
|
+
function encoded(value){return typeof value==='string'?value:JSON.stringify(value ?? null);}
|
|
4
|
+
async function canConverge(client,machine,work,until) {
|
|
5
|
+
const result=await client.query(`SELECT NOT EXISTS(SELECT 1 FROM segments s WHERE s.machine=$1 AND s.kind='phase'
|
|
6
|
+
AND s.start_time<=$4 AND s.end_time>$4 AND NOT EXISTS(
|
|
7
|
+
SELECT 1 FROM history_corrections c WHERE c.work_id=$2 AND c.generation=$3 AND c.name=s.name
|
|
8
|
+
AND c.start_time<=$4 AND c.end_time>=$4 AND c.duration=0)) AS safe`,[machine,work.id,work.generation,until]);
|
|
9
|
+
return result.rows[0].safe;
|
|
10
|
+
}
|
|
11
|
+
async function writeCorrections(client,machine,work,segments) {
|
|
12
|
+
for(const item of segments){
|
|
13
|
+
if((item.kind ?? 'phase')!=='phase' || !Number.isFinite(item.duration) || item.duration<0 || new Date(item.start_time)>new Date(item.end_time)){throw new TypeError('Valid phase correction required');}
|
|
14
|
+
// eslint-disable-next-line no-await-in-loop
|
|
15
|
+
await client.query(`INSERT INTO history_corrections(work_id,generation,machine,kind,name,start_time,end_time,duration,options,tags,properties,resolved)
|
|
16
|
+
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12) ON CONFLICT(work_id,generation,kind,start_time) DO UPDATE
|
|
17
|
+
SET name=EXCLUDED.name,end_time=EXCLUDED.end_time,duration=EXCLUDED.duration,options=EXCLUDED.options,tags=EXCLUDED.tags,properties=EXCLUDED.properties,resolved=EXCLUDED.resolved`,
|
|
18
|
+
[work.id,work.generation,machine,'phase',item.name,item.start_time,item.end_time,item.duration,encoded(item.options),encoded(item.tags),encoded(item.properties),item.resolved ?? true]);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
/** Staged results stay invisible until their finite dependency has completed or converged. */
|
|
22
|
+
export default async function historyCorrection(client,machine,work,segments,{base,context,timeScale}) {
|
|
23
|
+
if(!context?.context.classifierKey || !base.workId || base.workId!==work.id){throw new TypeError('Claimed classifier context required for staged correction');}
|
|
24
|
+
if(context.items.length && !base.checkpoint){throw new TypeError('Classifier checkpoint required for a nonempty correction page');}
|
|
25
|
+
await writeCorrections(client,machine,work,segments);
|
|
26
|
+
const from=(context.classifierSeed?Math.ceil(context.page.from/timeScale):Math.round(context.page.from/timeScale))*timeScale;
|
|
27
|
+
await client.query(`UPDATE history_work SET correction_from=least(correction_from,$3),correction_until=greatest(correction_until,$4),started=true WHERE id=$1 AND machine=$2`,
|
|
28
|
+
[work.id,machine,from,Math.round(context.page.until/timeScale)*timeScale]);
|
|
29
|
+
const matches=await saveCheckpoint(client,machine,base.checkpoint,context,work);
|
|
30
|
+
const converged=matches && await canConverge(client,machine,work,new Date(Math.round(context.page.until/timeScale)));
|
|
31
|
+
const finished=context.page.next===null || converged;
|
|
32
|
+
if(finished){await client.query('SELECT history_apply_correction($1,$2,$3,$4)',[work.id,machine,timeScale,converged]);}
|
|
33
|
+
return finished?{next:null}:context.page;
|
|
34
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
function bounded(rows) {
|
|
2
|
+
if (rows.length>10000) { throw new Error('History context capacity exceeded; retain work for bounded refinement'); }
|
|
3
|
+
return rows;
|
|
4
|
+
}
|
|
5
|
+
async function boundary(pool,machine,from,until,padding) {
|
|
6
|
+
const range = await pool.query(`WITH changed AS (
|
|
7
|
+
SELECT DISTINCT channel FROM history_observations WHERE machine=$1 AND time_ms<=greatest($2::bigint,$3::bigint)
|
|
8
|
+
), latest AS (SELECT max(time_ms) AS at FROM history_observations WHERE machine=$1)
|
|
9
|
+
SELECT greatest($3::bigint+$4::bigint,COALESCE(max(COALESCE(
|
|
10
|
+
(SELECT min(time_ms) FROM history_observations h WHERE h.machine=$1 AND h.channel=c.channel AND h.time_ms>$3),latest.at)), $3)) AS until
|
|
11
|
+
FROM changed c CROSS JOIN latest`, [machine,from,until,padding]);
|
|
12
|
+
return Number(range.rows[0].until);
|
|
13
|
+
}
|
|
14
|
+
const runs = `WITH timeline AS (
|
|
15
|
+
SELECT DISTINCT time_ms FROM history_observations WHERE machine=$1 AND time_ms BETWEEN $2 AND $3
|
|
16
|
+
), breaks AS (SELECT time_ms,lag(time_ms) OVER(ORDER BY time_ms) AS prior FROM timeline),
|
|
17
|
+
numbered AS (SELECT time_ms,sum(CASE WHEN prior IS NULL OR time_ms-prior>$4 THEN 1 ELSE 0 END) OVER(ORDER BY time_ms) AS run FROM breaks),
|
|
18
|
+
runs AS (SELECT min(time_ms) AS first,max(time_ms) AS last FROM numbered GROUP BY run)`;
|
|
19
|
+
async function compact(pool,machine,left,right,padding) {
|
|
20
|
+
const continuity = await pool.query(`${runs} SELECT first,last FROM runs ORDER BY first LIMIT 10001`, [machine,left,right,padding]);
|
|
21
|
+
bounded(continuity.rows);
|
|
22
|
+
const points = await pool.query(`${runs}, points AS (
|
|
23
|
+
SELECT event_id AS "eventId",channel,h.time_ms AS time,value,
|
|
24
|
+
lag(value) OVER(PARTITION BY channel,n.run ORDER BY h.time_ms) AS previous,
|
|
25
|
+
row_number() OVER(PARTITION BY channel,n.run ORDER BY h.time_ms DESC) AS reverse
|
|
26
|
+
FROM history_observations h JOIN numbered n ON n.time_ms=h.time_ms WHERE h.machine=$1 AND h.time_ms BETWEEN $2 AND $3
|
|
27
|
+
) SELECT "eventId",channel,time,value FROM points
|
|
28
|
+
WHERE previous IS DISTINCT FROM value OR reverse=1 OR time IN (SELECT first FROM runs UNION SELECT last FROM runs)
|
|
29
|
+
OR time IN (SELECT b.prior FROM breaks b JOIN points p ON p.time=b.time_ms WHERE p.previous IS DISTINCT FROM p.value)
|
|
30
|
+
ORDER BY time,channel LIMIT 10001`, [machine,left,right,padding]);
|
|
31
|
+
if (points.rows.length>10000) { throw new Error('History context exceeds bounded semantic changes; split classification work'); }
|
|
32
|
+
return { items: points.rows.map((row) => { return { ...row,time:Number(row.time) }; }),
|
|
33
|
+
continuity:continuity.rows.map((row) => { return {from:Number(row.first),until:Number(row.last)}; }) };
|
|
34
|
+
}
|
|
35
|
+
async function pageRange(pool,machine,left,end) {
|
|
36
|
+
const times = await pool.query(`SELECT time_ms,count(*) AS size FROM history_observations WHERE machine=$1 AND time_ms BETWEEN $2 AND $3 GROUP BY time_ms ORDER BY time_ms LIMIT 251`,[machine,left,end]);
|
|
37
|
+
let size=0;
|
|
38
|
+
const selected=[];
|
|
39
|
+
for (const row of times.rows) {
|
|
40
|
+
if (selected.length===250 || size+Number(row.size)>10000) { break; }
|
|
41
|
+
selected.push(row);
|
|
42
|
+
size+=Number(row.size);
|
|
43
|
+
}
|
|
44
|
+
if (times.rows.length && !selected.length) { throw new Error('One history timestamp group exceeds bounded context capacity'); }
|
|
45
|
+
const next=times.rows[selected.length] ? Number(times.rows[selected.length].time_ms) : null;
|
|
46
|
+
return {from:left,until:next===null ? end : Number(selected.at(-1).time_ms),next,end};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** PostgreSQL implementation of the bounded raw-observation source. */
|
|
50
|
+
export default function historyObservationsPg(pool) {
|
|
51
|
+
return {
|
|
52
|
+
boundary(machine,from,until,padding) { return boundary(pool,machine,from,until,padding); },
|
|
53
|
+
page(machine,left,end) { return pageRange(pool,machine,left,end); },
|
|
54
|
+
read(machine,left,right,padding) { return compact(pool,machine,left,right,padding); }
|
|
55
|
+
};
|
|
56
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/** Complete carried parameters at the left context boundary within the last continuous run. */
|
|
2
|
+
export default async function historySeed(pool, machine, before, maxGap, {observations,timeScale=1}={}) {
|
|
3
|
+
const external = observations?.seed ? await observations.seed(machine,before,maxGap) : undefined;
|
|
4
|
+
if (external === null) { return null; }
|
|
5
|
+
if (external !== undefined) {
|
|
6
|
+
const prior = await pool.query(`SELECT kind,name,start_time,end_time,duration,options,tags,properties,resolved FROM segments
|
|
7
|
+
WHERE machine=$1 AND kind='phase' AND start_time<=$2 AND (end_time >= $3 OR (duration=0 AND start_time >= $3)) ORDER BY start_time DESC LIMIT 1`,
|
|
8
|
+
[machine,new Date(external.time/timeScale),new Date(external.since/timeScale)]);
|
|
9
|
+
return {...external,segment:prior.rows[0] ?? null};
|
|
10
|
+
}
|
|
11
|
+
const result = await pool.query(`WITH times AS (
|
|
12
|
+
SELECT DISTINCT time_ms FROM history_observations WHERE machine=$1 AND time_ms<$2
|
|
13
|
+
), gaps AS (
|
|
14
|
+
SELECT time_ms,time_ms-lag(time_ms) OVER (ORDER BY time_ms) AS gap FROM times
|
|
15
|
+
), boundary AS (
|
|
16
|
+
SELECT COALESCE(max(time_ms) FILTER (WHERE gap>$3),min(time_ms)) AS at FROM gaps
|
|
17
|
+
) SELECT DISTINCT ON (channel) channel,time_ms AS time,value,boundary.at AS since FROM history_observations,boundary
|
|
18
|
+
WHERE machine=$1 AND time_ms>=boundary.at AND time_ms<$2 ORDER BY channel,time_ms DESC`, [machine,before,maxGap]);
|
|
19
|
+
if (!result.rows.length) { return null; }
|
|
20
|
+
const time = Math.max(...result.rows.map((row) => { return Number(row.time); }));
|
|
21
|
+
const since = Number(result.rows[0].since);
|
|
22
|
+
const prior = await pool.query(`SELECT kind,name,start_time,end_time,duration,options,tags,properties,resolved FROM segments
|
|
23
|
+
WHERE machine=$1 AND kind='phase' AND start_time<=$2 AND (end_time >= $3 OR (duration=0 AND start_time >= $3)) ORDER BY start_time DESC LIMIT 1`,
|
|
24
|
+
[machine,new Date(time),new Date(since)]);
|
|
25
|
+
return { since, segment: prior.rows[0] ?? null, time: Math.max(...result.rows.map((row) => { return Number(row.time); })),
|
|
26
|
+
values: Object.fromEntries(result.rows.map((row) => { return [row.channel,row.value]; })) };
|
|
27
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import metricsInsertSql from './metricsInsertSql.js';
|
|
1
2
|
import risesSql from './risesSql.js';
|
|
2
3
|
import changesSql from './changesSql.js';
|
|
3
4
|
import holdsSql from './holdsSql.js';
|
|
@@ -14,7 +15,7 @@ async function pollRows(pool, topic, afterIso, untilIso) {
|
|
|
14
15
|
});
|
|
15
16
|
}
|
|
16
17
|
|
|
17
|
-
export default function metricsStatePg(pool) {
|
|
18
|
+
export default function metricsStatePg(pool, { firstWins = false } = {}) {
|
|
18
19
|
return {
|
|
19
20
|
async latestForTopic(topic) {
|
|
20
21
|
const result = await pool.query(
|
|
@@ -55,7 +56,7 @@ export default function metricsStatePg(pool) {
|
|
|
55
56
|
return row.value;
|
|
56
57
|
});
|
|
57
58
|
await pool.query(
|
|
58
|
-
|
|
59
|
+
metricsInsertSql(firstWins),
|
|
59
60
|
[topics, tss, values]
|
|
60
61
|
);
|
|
61
62
|
}
|
|
@@ -68,8 +69,8 @@ export default function metricsStatePg(pool) {
|
|
|
68
69
|
* @param {object} pool - PostgreSQL pool
|
|
69
70
|
* @returns {object} sink with write(records)
|
|
70
71
|
*/
|
|
71
|
-
export function metricsSinkFromPool(pool) {
|
|
72
|
-
const metrics = metricsStatePg(pool);
|
|
72
|
+
export function metricsSinkFromPool(pool, options = {}) {
|
|
73
|
+
const metrics = metricsStatePg(pool, options);
|
|
73
74
|
return {
|
|
74
75
|
async write(records) {
|
|
75
76
|
if (records.length === 0) {
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** First-wins receipt and raw metric commit in the same statement, including history triggers. */
|
|
2
|
+
export default function metricsInsertSql(firstWins) {
|
|
3
|
+
return firstWins ? `WITH incoming AS (
|
|
4
|
+
SELECT DISTINCT ON (topic,ts) topic,ts,value FROM unnest($1::text[], $2::timestamptz[], $3::float8[]) WITH ORDINALITY AS rows(topic,ts,value,position) ORDER BY topic,ts,position
|
|
5
|
+
), accepted AS (
|
|
6
|
+
INSERT INTO metric_receipts(topic,ts,value)
|
|
7
|
+
SELECT i.topic,i.ts,COALESCE((SELECT m.value FROM metrics m WHERE m.topic=i.topic AND m.ts=i.ts LIMIT 1),i.value) FROM incoming i
|
|
8
|
+
ON CONFLICT(topic,ts) DO NOTHING RETURNING topic,ts,value
|
|
9
|
+
) INSERT INTO metrics(topic,ts,value) SELECT a.topic,a.ts,a.value FROM accepted a
|
|
10
|
+
WHERE NOT EXISTS(SELECT 1 FROM metrics m WHERE m.topic=a.topic AND m.ts=a.ts)`
|
|
11
|
+
: 'INSERT INTO metrics (topic, ts, value) SELECT * FROM unnest($1::text[], $2::timestamptz[], $3::float8[])';
|
|
12
|
+
}
|