@yarkivaev/scada 2.5.8 → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/README.md +83 -0
  2. package/db/migrations/E0005__historical_telemetry_grants.sql +5 -0
  3. package/db/migrations/E0006__historical_telemetry.sql +64 -0
  4. package/db/migrations/E0007__metric_receipts.sql +7 -0
  5. package/db/migrations/E0008__metric_receipts_grants.sql +1 -0
  6. package/db/migrations/E0009__history_continuation.sql +20 -0
  7. package/db/migrations/E0010__history_admissions.sql +8 -0
  8. package/db/migrations/E0011__history_classifier_checkpoints.sql +18 -0
  9. package/db/migrations/E0012__external_history_grants.sql +4 -0
  10. package/db/migrations/E0013__history_staged_corrections.sql +104 -0
  11. package/db/migrations/E0014__history_correction_grants.sql +5 -0
  12. package/db/migrations/E0015__history_retention_frontier.sql +7 -0
  13. package/db/migrations/E0016__history_retention_grants.sql +1 -0
  14. package/index.js +7 -0
  15. package/package.json +5 -3
  16. package/src/application/control/agent.js +61 -0
  17. package/src/application/control/catalog.js +22 -0
  18. package/src/application/control/controlClient.js +75 -0
  19. package/src/application/control/controlStore.js +55 -0
  20. package/src/application/control/controller.js +22 -0
  21. package/src/application/control/executionSnapshot.js +32 -0
  22. package/src/application/control/index.js +7 -0
  23. package/src/application/control/localAssignment.js +13 -0
  24. package/src/application/control/schedule.js +103 -0
  25. package/src/application/control/snapshotFile.js +24 -0
  26. package/src/application/foldedMetricsSink.js +1 -0
  27. package/src/application/mcp/mcpResources.js +1 -1
  28. package/src/application/mcp/mcpSchema.js +8 -3
  29. package/src/application/runtime/additionalAdapters.js +13 -9
  30. package/src/application/runtime/deliveryQueue.js +62 -0
  31. package/src/application/runtime/deliverySessions.js +28 -0
  32. package/src/application/runtime/modbusDelivery.js +36 -0
  33. package/src/application/runtime/pipelineAdapters.js +12 -8
  34. package/src/application/runtime/queuedDelivery.js +25 -0
  35. package/src/application/runtime/runCollector.js +34 -3
  36. package/src/application/runtime/runtime.js +2 -2
  37. package/src/application/runtime/runtimeHealth.js +1 -1
  38. package/src/application/runtime/runtimeServices.js +6 -2
  39. package/src/application/runtime/streamTask.js +13 -4
  40. package/src/application/runtime/taskContext.js +1 -0
  41. package/src/application/runtime/taskSlot.js +2 -2
  42. package/src/application/runtime/telemetrySink.js +18 -0
  43. package/src/application/siteServer.js +19 -4
  44. package/src/application/siteTelemetry.js +2 -2
  45. package/src/application/supervisorSink.js +5 -1
  46. package/src/application/sync/siteSyncBind.js +2 -2
  47. package/src/bin/controller.js +8 -0
  48. package/src/infrastructure/http/edge/edgeApi.js +2 -0
  49. package/src/infrastructure/http/edge/routes/history/historyRoutes.js +33 -0
  50. package/src/infrastructure/http/plant/routes/measurementRead.js +3 -0
  51. package/src/infrastructure/ingest/db/migrationProfile.js +6 -1
  52. package/src/infrastructure/ingest/db/retainMetricReceipts.js +8 -0
  53. package/src/infrastructure/ingest/db/runRetention.js +2 -0
  54. package/src/infrastructure/ingest/mqtt/metricsTransformer.js +11 -2
  55. package/src/infrastructure/ingest/mqtt/modbusMqtt.js +1 -1
  56. package/src/infrastructure/ingest/mqtt/modbusPublish.js +2 -0
  57. package/src/infrastructure/ingest/mqtt/mqttMetrics.js +1 -1
  58. package/src/infrastructure/ingest/telemetry/amqpMetricsIngest.js +7 -3
  59. package/src/infrastructure/ingest/telemetry/centralEnvelope.js +46 -0
  60. package/src/infrastructure/ingest/telemetry/centralMetricsSink.js +64 -0
  61. package/src/infrastructure/ingest/telemetry/centralPoint.js +14 -0
  62. package/src/infrastructure/ingest/telemetry/centralPolicy.js +51 -0
  63. package/src/infrastructure/ingest/telemetry/centralQueueSession.js +29 -0
  64. package/src/infrastructure/ingest/telemetry/centralTelemetryPreflight.js +31 -0
  65. package/src/infrastructure/ingest/telemetry/foldingSink.js +3 -0
  66. package/src/infrastructure/ingest/telemetry/historyTelemetry.js +32 -0
  67. package/src/infrastructure/persistence/clickhouse/canonicalMetrics.js +26 -0
  68. package/src/infrastructure/persistence/clickhouse/changes.js +4 -2
  69. package/src/infrastructure/persistence/clickhouse/connection.js +6 -8
  70. package/src/infrastructure/persistence/clickhouse/holds.js +10 -7
  71. package/src/infrastructure/persistence/clickhouse/latest.js +1 -1
  72. package/src/infrastructure/persistence/clickhouse/metricsQuery.js +70 -0
  73. package/src/infrastructure/persistence/clickhouse/metricsRelation.js +110 -0
  74. package/src/infrastructure/persistence/clickhouse/nativeMetricPoints.js +26 -0
  75. package/src/infrastructure/persistence/clickhouse/nativeMetricsAdmission.js +91 -0
  76. package/src/infrastructure/persistence/clickhouse/nativeMetricsClock.js +9 -0
  77. package/src/infrastructure/persistence/clickhouse/nativeMetricsCompaction.js +82 -0
  78. package/src/infrastructure/persistence/clickhouse/nativeMetricsInsert.js +31 -0
  79. package/src/infrastructure/persistence/clickhouse/nativeMetricsOwnership.js +8 -0
  80. package/src/infrastructure/persistence/clickhouse/nativeMetricsSchema.js +44 -0
  81. package/src/infrastructure/persistence/clickhouse/pollTopicCursors.js +3 -1
  82. package/src/infrastructure/persistence/clickhouse/rises.js +4 -2
  83. package/src/infrastructure/persistence/clickhouse/samples.js +10 -0
  84. package/src/infrastructure/persistence/clickhouse/sensor.js +4 -0
  85. package/src/infrastructure/persistence/clickhouse/series.js +38 -21
  86. package/src/infrastructure/persistence/pg/history.js +169 -0
  87. package/src/infrastructure/persistence/pg/historyAdmission.js +81 -0
  88. package/src/infrastructure/persistence/pg/historyCheckpoint.js +56 -0
  89. package/src/infrastructure/persistence/pg/historyConfigure.js +28 -0
  90. package/src/infrastructure/persistence/pg/historyContext.js +65 -0
  91. package/src/infrastructure/persistence/pg/historyCorrection.js +34 -0
  92. package/src/infrastructure/persistence/pg/historyObservations.js +56 -0
  93. package/src/infrastructure/persistence/pg/historySeed.js +27 -0
  94. package/src/infrastructure/persistence/pg/metrics.js +5 -4
  95. package/src/infrastructure/persistence/pg/metricsInsertSql.js +12 -0
  96. package/src/infrastructure/persistence/runtime/deliverySpool.js +124 -0
  97. package/src/infrastructure/persistence/stateDataFromPool.js +2 -0
  98. package/src/infrastructure/streams/amqpSink/session.js +6 -0
  99. package/src/infrastructure/streams/amqpSource.js +17 -4
@@ -0,0 +1,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
- 'INSERT INTO metrics (topic, ts, value) SELECT * FROM unnest($1::text[], $2::timestamptz[], $3::float8[])',
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
+ }
@@ -0,0 +1,124 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { mkdir, open, opendir, readFile, rename, stat, unlink } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+
5
+ function filename(id) { return `${createHash('sha256').update(id).digest('hex')}.json`; }
6
+ async function syncDirectory(directory) {
7
+ const handle = await open(directory, 'r');
8
+ try { await handle.sync(); } finally { await handle.close(); }
9
+ }
10
+ async function replace(directory, name, value) {
11
+ const temporary = path.join(directory, `${name}.${randomUUID()}.tmp`);
12
+ const handle = await open(temporary, 'wx', 0o600);
13
+ try { await handle.writeFile(value); await handle.sync(); } finally { await handle.close(); }
14
+ await rename(temporary, path.join(directory, name));
15
+ await syncDirectory(directory);
16
+ }
17
+ function revive(key, value) {
18
+ return value?.type === 'Buffer' && Array.isArray(value.data) ? Buffer.from(value.data) : value;
19
+ }
20
+ async function restore(directory, entries, maxRecords, load) {
21
+ let bytes = 0;
22
+ const files = await opendir(directory);
23
+ for await (const file of files) {
24
+ const { name } = file;
25
+ if (/^[a-f0-9]{64}\.json$/u.test(name)) {
26
+ if (entries.size >= maxRecords) { throw new Error('Spool record capacity exceeded during recovery'); }
27
+ // Read one committed entry at a time; memory never holds the directory listing.
28
+ const record = await load(name);
29
+ if (typeof record.event?.eventId !== 'string' || filename(record.event.eventId) !== name
30
+ || !Array.isArray(record.remaining) || !Array.isArray(record.recipients)) { throw new Error('Corrupt spool record'); }
31
+ const { size } = await stat(path.join(directory, name));
32
+ entries.set(record.event.eventId, { name, size }); bytes += size;
33
+ }
34
+ }
35
+ return bytes;
36
+ }
37
+ /* eslint max-lines-per-function: ["error", 100], max-statements: ["error", 25] */
38
+ /** Single writer on a persistent local volume. Failed/ambiguous acknowledgements retain data. */
39
+ export default function deliverySpool(directory, { maxBytes, maxRecords = 100000 } = {}) {
40
+ if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) { throw new TypeError('Explicit positive spool maxBytes required'); }
41
+ if (!Number.isSafeInteger(maxRecords) || maxRecords <= 0) { throw new TypeError('Positive safe spool maxRecords required'); }
42
+ const entries = new Map();
43
+ const state = { bytes: 0, ready: false, busy: false };
44
+ async function exclusive(action) {
45
+ if (state.busy) { throw new Error('Spool operation in progress'); }
46
+ state.busy = true;
47
+ try { return await action(); } finally { Object.assign(state, { busy: false }); }
48
+ }
49
+ function current() { if (!state.ready) { throw new Error('Spool not opened'); } }
50
+ async function load(name) { return JSON.parse(await readFile(path.join(directory, name), 'utf8'), revive); }
51
+ return {
52
+ open() {
53
+ return exclusive(async () => {
54
+ Object.assign(state, { ready: false }); entries.clear(); state.bytes = 0;
55
+ await mkdir(directory, { recursive: true, mode: 0o700 });
56
+ const bytes = await restore(directory, entries, maxRecords, load);
57
+ Object.assign(state, { bytes });
58
+ Object.assign(state, { ready: true });
59
+ });
60
+ },
61
+ append(event, recipients) {
62
+ return exclusive(async () => {
63
+ current();
64
+ if (typeof event.eventId !== 'string' || !event.eventId || !Array.isArray(recipients) || !recipients.length
65
+ || recipients.some((item) => { return typeof item !== 'string' || !item; })
66
+ || new Set(recipients).size !== recipients.length) { throw new TypeError('Event identity and unique recipients required'); }
67
+ const existing = entries.get(event.eventId);
68
+ if (existing) {
69
+ const saved = await load(existing.name);
70
+ if (JSON.stringify(saved.event) !== JSON.stringify(event) || JSON.stringify(saved.recipients) !== JSON.stringify(recipients)) {
71
+ throw new Error('Conflicting event identity');
72
+ }
73
+ return;
74
+ }
75
+ if (entries.size >= maxRecords) { throw new Error('Spool record capacity exceeded'); }
76
+ const value = JSON.stringify({ event, recipients, remaining: recipients });
77
+ const size = Buffer.byteLength(value);
78
+ if (state.bytes + size > maxBytes) { throw new Error('Spool capacity exceeded'); }
79
+ const name = filename(event.eventId);
80
+ // Reserve against ambiguous fsync outcomes; reopen reconciles actual files.
81
+ entries.set(event.eventId, { name, size }); state.bytes += size;
82
+ try { await replace(directory, name, value); } catch (error) { Object.assign(state, { ready: false }); throw error; }
83
+ });
84
+ },
85
+ ack(eventId, recipient) {
86
+ return exclusive(async () => {
87
+ current();
88
+ const entry = entries.get(eventId);
89
+ if (!entry) { return; }
90
+ const saved = await load(entry.name);
91
+ if (!saved.recipients.includes(recipient)) { throw new Error('Unknown recipient'); }
92
+ const remaining = saved.remaining.filter((item) => { return item !== recipient; });
93
+ if (remaining.length === saved.remaining.length) { return; }
94
+ try {
95
+ if (remaining.length === 0) {
96
+ await unlink(path.join(directory, entry.name)); await syncDirectory(directory);
97
+ entries.delete(eventId); state.bytes -= entry.size;
98
+ } else {
99
+ const value = JSON.stringify({ ...saved, remaining });
100
+ await replace(directory, entry.name, value);
101
+ const size = Buffer.byteLength(value); state.bytes += size - entry.size; entry.size = size;
102
+ }
103
+ } catch (error) { Object.assign(state, { ready: false }); throw error; }
104
+ });
105
+ },
106
+ pending(limit = 100) {
107
+ return exclusive(async () => {
108
+ current();
109
+ if (!Number.isSafeInteger(limit) || limit <= 0) { throw new TypeError('Positive pending limit required'); }
110
+ const rows = [];
111
+ for (const entry of Array.from(entries.values()).slice(0, limit)) {
112
+ // Read sequentially to bound decoded records in memory.
113
+ // eslint-disable-next-line no-await-in-loop
114
+ const { event, remaining } = await load(entry.name);
115
+ rows.push({ event, remaining });
116
+ // Rotate the window so an offline recipient cannot starve later destinations.
117
+ entries.delete(event.eventId); entries.set(event.eventId, entry);
118
+ }
119
+ return rows;
120
+ });
121
+ },
122
+ status() { return { bytes: state.bytes, maxBytes, recordLimit: maxRecords, pending: entries.size, ready: state.ready }; }
123
+ };
124
+ }
@@ -1,3 +1,4 @@
1
+ import historyPg from './pg/history.js';
1
2
  import alertsStatePg from './pg/alerts.js';
2
3
  import checkpointStatePg from './pg/checkpoints.js';
3
4
  import metricsStateDisabled from './memory/metricsDisabled.js';
@@ -12,6 +13,7 @@ export default function stateDataFromPool(pool, options = {}) {
12
13
  segments: segmentStatePg(pool),
13
14
  alerts: alertsStatePg(pool),
14
15
  metrics,
16
+ history: metricsEnabled ? historyPg(pool, { retentionDays: options.historyRetentionDays ?? 30 }) : undefined,
15
17
  checkpoints: checkpointStatePg(pool, metricsEnabled),
16
18
  operations: operationStatePg(pool)
17
19
  };
@@ -53,6 +53,12 @@ async function configure(state, live) {
53
53
  await Promise.all((state.options.exchanges || []).map((item) => {
54
54
  return live.channel.assertExchange(item.name, item.type || 'topic', item.options || {durable: true});
55
55
  }));
56
+ await Promise.all((state.options.queues || []).map((item) => {
57
+ return live.channel.assertQueue(item.name, item.options || { durable: true, autoDelete: false });
58
+ }));
59
+ await Promise.all((state.options.bindings || []).map((item) => {
60
+ return live.channel.bindQueue(item.queue, item.exchange, item.pattern, item.args);
61
+ }));
56
62
  }
57
63
  async function current(state, live) {
58
64
  if (live.epoch !== state.epoch || !state.wanted) {
@@ -1,3 +1,4 @@
1
+ /* eslint-disable no-await-in-loop */
1
2
  import amqpSession from './amqpSource/session.js';
2
3
  import budgetAccept from './budgetAccept.js';
3
4
 
@@ -14,6 +15,7 @@ function deliveryFor(channel, message, options) {
14
15
  let settled = false;
15
16
  return {
16
17
  content: message.content, fields: message.fields, properties: message.properties,
18
+ active() {return !settled && options.active();},
17
19
  ack() {
18
20
  if (!settled && options.active()) { channel.ack(message); settled = true; }
19
21
  },
@@ -48,6 +50,16 @@ function consume(channel, collector, options) {
48
50
  }
49
51
  };
50
52
  }
53
+ async function rejectCapacity(channel,message,options) {
54
+ reportFailure(options,new Error(options.preserveOnCapacity ? 'AMQP payload capacity exceeded; retained for retry' : 'AMQP payload capacity exceeded; rejected without requeue'));
55
+ if (options.preserveOnCapacity) {
56
+ // Never NACK a canonical head into the ready queue behind later data.
57
+ while(options.active()) {await new Promise((resolve) => {setTimeout(resolve,250);});}
58
+ return;
59
+ }
60
+ try {channel.nack(message,false,false);}
61
+ catch(error) {reportFailure(options,error);}
62
+ }
51
63
  function trackedConsume(channel, collector, options, pending) {
52
64
  const accept = consume(channel, collector, options);
53
65
  const state = { bytes: 0 };
@@ -55,9 +67,7 @@ function trackedConsume(channel, collector, options, pending) {
55
67
  if (!options.active()) { return Promise.resolve(); }
56
68
  const bytes = message?.content?.length ?? 0;
57
69
  if (bytes > options.maxMessageBytes || state.bytes + bytes > options.maxPendingBytes) {
58
- try { channel.nack(message, false, false); } catch (error) { reportFailure(options, error); }
59
- reportFailure(options, new Error('AMQP payload capacity exceeded; rejected without requeue'));
60
- return Promise.resolve();
70
+ return rejectCapacity(channel,message,options);
61
71
  }
62
72
  state.bytes += bytes;
63
73
  const delivery = accept(message);
@@ -86,8 +96,11 @@ export default function amqpSource(url, queue, collector, options = {}) {
86
96
  const state = {};
87
97
  const session = amqpSession(url, async (channel) => {
88
98
  const generation = state.session.generation();
99
+ const live = {closed:false};
100
+ channel.on('close',() => {live.closed=true;});
101
+ channel.on('error',() => {live.closed=true;});
89
102
  const config = { ...settings, active() {
90
- return state.session.active() && state.session.generation() === generation;
103
+ return !live.closed && state.session.active() && state.session.generation() === generation;
91
104
  } };
92
105
  const name = await topology(channel, queue, settings);
93
106
  const result = await channel.consume(name, trackedConsume(channel, collector, config, pending), { noAck: false, ...(settings.exclusive ? { exclusive: true } : {}) });