@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.
Files changed (104) hide show
  1. package/README.md +95 -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 +80 -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 +57 -0
  97. package/src/infrastructure/persistence/runtime/spoolCodec.js +41 -0
  98. package/src/infrastructure/persistence/runtime/spoolDatabase.js +69 -0
  99. package/src/infrastructure/persistence/runtime/spoolFormat.js +37 -0
  100. package/src/infrastructure/persistence/runtime/spoolMigration.js +66 -0
  101. package/src/infrastructure/persistence/runtime/spoolRecords.js +50 -0
  102. package/src/infrastructure/persistence/stateDataFromPool.js +2 -0
  103. package/src/infrastructure/streams/amqpSink/session.js +6 -0
  104. package/src/infrastructure/streams/amqpSource.js +17 -4
@@ -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
- '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,57 @@
1
+ import { capacity, checkpoint, counters, database } from './spoolDatabase.js';
2
+ import { acknowledge, insert, pending } from './spoolRecords.js';
3
+ import { encoded } from './spoolCodec.js';
4
+ import spoolMigration from './spoolMigration.js';
5
+
6
+ /* eslint max-lines-per-function: ["error", 100], max-statements: ["error", 25] */
7
+ /** Single owner, bounded cache and indexed reads. Caps count logical JSON bytes, not allocated pages. */
8
+ export default function deliverySpool(directory, { maxBytes, maxRecords = 100000, legacyMigrationMaxBytes = 16 * 1024 * 1024 } = {}) {
9
+ if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) { throw new TypeError('Explicit positive spool maxBytes required'); }
10
+ if (!Number.isSafeInteger(maxRecords) || maxRecords <= 0) { throw new TypeError('Positive safe spool maxRecords required'); }
11
+ if (!Number.isSafeInteger(legacyMigrationMaxBytes) || legacyMigrationMaxBytes <= 0) { throw new TypeError('Positive safe legacyMigrationMaxBytes required'); }
12
+ const state = { db: null, owner: null, ready: false, busy: false, bytes: 0, records: 0 };
13
+ function release() {
14
+ state.ready = false;
15
+ try { state.db?.close(); } finally { state.owner?.close(); state.db = null; state.owner = null; }
16
+ }
17
+ function refresh() {
18
+ const totals = counters(state.db); state.bytes = totals.bytes; state.records = totals.records;
19
+ }
20
+ async function exclusive(action, requireReady = true) {
21
+ if (state.busy) { throw new Error('Spool operation in progress'); }
22
+ if (requireReady && !state.ready) { throw new Error('Spool not opened'); }
23
+ state.busy = true;
24
+ try { return await action(); } finally { Object.assign(state, { busy:false }); }
25
+ }
26
+ function commit(action) {
27
+ try { const result = state.db.transaction(action)(); refresh(); return result; }
28
+ catch (error) { if (error.code?.startsWith('SQLITE_')) { release(); } throw error; }
29
+ }
30
+ return {
31
+ open() {
32
+ return exclusive(async () => {
33
+ if (state.ready) { return; }
34
+ try {
35
+ Object.assign(state, await database(directory));
36
+ capacity(state.db, maxBytes, maxRecords);
37
+ await spoolMigration(directory, state.db, { maxBytes, maxRecords, legacyMigrationMaxBytes });
38
+ refresh(); Object.assign(state, { ready:true });
39
+ } catch (error) { release(); throw error; }
40
+ }, false);
41
+ },
42
+ append(event, recipients) { return exclusive(() => { return commit(() => { insert(state.db, encoded(event, recipients), maxBytes, maxRecords); }); }); },
43
+ ack(eventId, recipient) { return exclusive(() => { return commit(() => { acknowledge(state.db, eventId, recipient); }); }); },
44
+ pending(limit = 100) {
45
+ return exclusive(() => {
46
+ if (!Number.isSafeInteger(limit) || limit <= 0) { throw new TypeError('Positive pending limit required'); }
47
+ return commit(() => { return pending(state.db, limit); });
48
+ });
49
+ },
50
+ close() {
51
+ return exclusive(() => {
52
+ try { if (state.db) { checkpoint(state.db); } } finally { release(); }
53
+ }, false);
54
+ },
55
+ status() { return { bytes: state.bytes, maxBytes, recordLimit: maxRecords, pending: state.records, ready: state.ready }; }
56
+ };
57
+ }
@@ -0,0 +1,41 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { deflateSync, inflateSync } from 'node:zlib';
3
+
4
+ export function digest(value) { return createHash('sha256').update(value).digest('hex'); }
5
+ export function revive(key, value) {
6
+ return value?.type === 'Buffer' && Array.isArray(value.data) ? Buffer.from(value.data) : value;
7
+ }
8
+ export function validate(event, recipients, remaining = recipients) {
9
+ if (typeof event?.eventId !== 'string' || !event.eventId || !Array.isArray(recipients) || !recipients.length
10
+ || recipients.some((item) => { return typeof item !== 'string' || !item; })
11
+ || new Set(recipients).size !== recipients.length || !Array.isArray(remaining) || !remaining.length
12
+ || new Set(remaining).size !== remaining.length || remaining.some((item) => { return !recipients.includes(item); })) {
13
+ throw new TypeError('Event identity and unique recipients required; corrupt spool record');
14
+ }
15
+ }
16
+ export function encoded(event, recipients, remaining = recipients) {
17
+ validate(event, recipients, remaining);
18
+ const original = JSON.stringify(event);
19
+ const snapshot = JSON.parse(original);
20
+ const destinations = Array.isArray(snapshot.destinations) ? snapshot.destinations.map((item) => {
21
+ const json = JSON.stringify(item); return { id: digest(json), json };
22
+ }) : null;
23
+ if (destinations) { snapshot.destinations = []; }
24
+ return {
25
+ id: event.eventId, fingerprint: digest(JSON.stringify({ event, recipients })),
26
+ payload: deflateSync(JSON.stringify(snapshot)), destinations,
27
+ recipients: JSON.stringify(recipients), remaining: JSON.stringify(remaining),
28
+ bytes: Buffer.byteLength(JSON.stringify({ event, recipients, remaining }))
29
+ };
30
+ }
31
+ export function decoded(row, db) {
32
+ const event = JSON.parse(inflateSync(row.payload).toString(), revive);
33
+ if (row.destinations !== null) {
34
+ event.destinations = JSON.parse(row.destinations).map((id) => {
35
+ const descriptor = db.prepare('SELECT json FROM destinations WHERE id = ?').get(id);
36
+ if (!descriptor) { throw new Error('Corrupt spool destination'); }
37
+ return JSON.parse(descriptor.json, revive);
38
+ });
39
+ }
40
+ return { event, remaining: JSON.parse(row.remaining) };
41
+ }
@@ -0,0 +1,69 @@
1
+ import Database from 'better-sqlite3';
2
+ import path from 'node:path';
3
+ import { lstat, mkdir, open } from 'node:fs/promises';
4
+ import { constants } from 'node:fs';
5
+ import { format, initialize } from './spoolFormat.js';
6
+
7
+ // POSIX closes release this process's advisory locks for an inode, even from unrelated descriptors.
8
+ // Reserve directory identity before opening ANY owner descriptor, including rejected contenders.
9
+ const registry = Symbol.for('@yarkivaev/scada/delivery-spool-owners');
10
+ globalThis[registry] ??= new Set();
11
+ const owners = globalThis[registry];
12
+ const files = ['owner.sqlite', 'delivery.sqlite'].flatMap((name) => { return [name, `${name}-journal`, `${name}-wal`, `${name}-shm`]; });
13
+ export async function regular(file) {
14
+ try {
15
+ const info = await lstat(file);
16
+ if (!info.isFile() || info.nlink !== 1) { throw new Error('Spool requires private regular files; symlink/hardlink refused'); }
17
+ } catch (error) { if (error.code !== 'ENOENT') { throw error; } }
18
+ }
19
+ async function privateFile(file) {
20
+ const handle = await open(file, constants.O_RDWR + constants.O_CREAT + constants.O_NOFOLLOW, 0o600);
21
+ try {
22
+ const info = await handle.stat();
23
+ if (!info.isFile() || info.nlink !== 1) { throw new Error('Spool requires a private regular file'); }
24
+ await handle.chmod(0o600);
25
+ } finally { await handle.close(); }
26
+ }
27
+ export function counters(db) { return db.prepare('SELECT bytes, records, sequence FROM counters WHERE id=1').get(); }
28
+ export function capacity(db, maxBytes, maxRecords) {
29
+ const totals = counters(db);
30
+ if (totals.records > maxRecords) { throw new Error('Spool record capacity exceeded'); }
31
+ if (totals.bytes > maxBytes) { throw new Error('Spool capacity exceeded'); }
32
+ return totals;
33
+ }
34
+ async function reservation(directory) {
35
+ await mkdir(directory, { recursive: true, mode: 0o700 });
36
+ const info = await lstat(directory, { bigint: true });
37
+ if (!info.isDirectory() || info.isSymbolicLink()) { throw new Error('Spool directory symlink refused'); }
38
+ const key = `${info.dev}:${info.ino}`;
39
+ if (owners.has(key)) { throw new Error('Spool already has an owner'); }
40
+ owners.add(key); return key;
41
+ }
42
+ /* eslint max-statements: ["error", 30] */
43
+ export async function database(directory) {
44
+ const key = await reservation(directory);
45
+ let owner;
46
+ let db;
47
+ try {
48
+ for (const suffix of files) {
49
+ // Check all main files and SQLite sidecars before SQLite can modify an alias.
50
+ // eslint-disable-next-line no-await-in-loop
51
+ await regular(path.join(directory, suffix));
52
+ }
53
+ await privateFile(path.join(directory, 'owner.sqlite'));
54
+ owner = new Database(path.join(directory, 'owner.sqlite'), { timeout: 0 });
55
+ owner.exec('BEGIN EXCLUSIVE; CREATE TABLE IF NOT EXISTS owner (id INTEGER)');
56
+ await privateFile(path.join(directory, 'delivery.sqlite'));
57
+ db = new Database(path.join(directory, 'delivery.sqlite'), { timeout: 0 });
58
+ const existing = format(db);
59
+ db.pragma('journal_mode = WAL'); db.pragma('synchronous = FULL');
60
+ db.pragma('cache_size = -2048'); db.pragma('wal_autocheckpoint = 256');
61
+ db.pragma('journal_size_limit = 1048576'); db.pragma('secure_delete = FAST');
62
+ if (!existing) { initialize(db); }
63
+ return { db, owner: { close() { try { owner.close(); } finally { owners.delete(key); } } } };
64
+ } catch (error) {
65
+ try { db?.close(); } finally { try { owner?.close(); } finally { owners.delete(key); } }
66
+ throw error;
67
+ }
68
+ }
69
+ export function checkpoint(db) { db.pragma('wal_checkpoint(TRUNCATE)'); }
@@ -0,0 +1,37 @@
1
+ const statements = [
2
+ 'CREATE TABLE counters (id INTEGER PRIMARY KEY CHECK(id=1), bytes INTEGER NOT NULL, records INTEGER NOT NULL, sequence INTEGER NOT NULL)',
3
+ 'CREATE TABLE destinations (id TEXT PRIMARY KEY, json TEXT NOT NULL, refs INTEGER NOT NULL)',
4
+ `CREATE TABLE events (id TEXT PRIMARY KEY, fingerprint TEXT NOT NULL, payload BLOB NOT NULL,
5
+ destinations TEXT, recipients TEXT NOT NULL, remaining TEXT NOT NULL, bytes INTEGER NOT NULL, sequence INTEGER NOT NULL)`,
6
+ 'CREATE INDEX event_sequence ON events(sequence)',
7
+ 'CREATE TABLE imports (name TEXT PRIMARY KEY, digest TEXT NOT NULL, event_id TEXT NOT NULL)'
8
+ ];
9
+ function metadata(db) {
10
+ return db.prepare("SELECT type,name,sql FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%' ORDER BY name LIMIT 6").all();
11
+ }
12
+ function validCounters(db) {
13
+ const rows = db.prepare('SELECT id,bytes,records,sequence FROM counters LIMIT 2').all();
14
+ const row = rows[0];
15
+ return rows.length === 1 && row.id === 1
16
+ && [row.bytes, row.records, row.sequence].every((value) => { return Number.isSafeInteger(value) && value >= 0; })
17
+ && row.sequence >= row.records && row.bytes >= row.records
18
+ && (row.records === 0) === (row.bytes === 0)
19
+ && (row.records > 0) === Boolean(db.prepare('SELECT 1 FROM events LIMIT 1').get());
20
+ }
21
+ /** Validate bounded metadata before changing existing data or journal settings. Never repair ambiguous storage. */
22
+ export function format(db) {
23
+ const version = db.pragma('user_version', { simple: true });
24
+ const schema = metadata(db);
25
+ if (version === 0 && schema.length === 0) { return false; }
26
+ if (version !== 1) { throw new Error('Unsupported spool format version or nonempty database'); }
27
+ const expected = statements.map((sql) => { return sql.replaceAll(/\s+/gu, ' '); }).sort();
28
+ const actual = schema.map((row) => { return row.sql.replaceAll(/\s+/gu, ' '); }).sort();
29
+ if (JSON.stringify(actual) !== JSON.stringify(expected) || !validCounters(db)) { throw new Error('Corrupt spool format or counters'); }
30
+ return true;
31
+ }
32
+ export function initialize(db) {
33
+ db.transaction(() => {
34
+ db.exec(statements.join(';'));
35
+ db.prepare('INSERT INTO counters VALUES (1,0,0,0)').run(); db.pragma('user_version=1');
36
+ })();
37
+ }