@yarkivaev/scada 2.6.18 → 2.6.20

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.
@@ -0,0 +1,74 @@
1
+ -- A later correction window must not close a live covering.
2
+ CREATE OR REPLACE FUNCTION history_apply_correction(p_work UUID,p_machine TEXT,p_scale INTEGER,p_converged BOOLEAN)
3
+ RETURNS INTEGER LANGUAGE plpgsql AS $$
4
+ DECLARE w history_work%ROWTYPE; item history_corrections%ROWTYPE; owner history_annotations%ROWTYPE;
5
+ tail segments%ROWTYPE; lo TIMESTAMPTZ; hi TIMESTAMPTZ; a TIMESTAMPTZ; b TIMESTAMPTZ;
6
+ incoming JSONB; inherited JSONB; endpoint_cut BOOLEAN; inserted INTEGER := 0; keys TEXT[] := ARRAY['casting','cadence_rule','cadence_threshold_ms','casting_detected_at','source_interrupted'];
7
+ BEGIN
8
+ SELECT * INTO STRICT w FROM history_work WHERE id=p_work AND machine=p_machine;
9
+ IF p_converged THEN
10
+ FOR item IN SELECT * FROM history_corrections WHERE work_id=w.id AND generation=w.generation AND duration=0 LOOP
11
+ SELECT * INTO tail FROM segments WHERE machine=p_machine AND kind=item.kind AND name=item.name
12
+ AND start_time<=item.end_time AND end_time>item.end_time ORDER BY end_time DESC LIMIT 1;
13
+ IF FOUND THEN
14
+ UPDATE history_corrections SET end_time=tail.end_time,
15
+ duration=CASE WHEN tail.duration=0 THEN 0 ELSE extract(epoch FROM tail.end_time-item.start_time) END
16
+ WHERE work_id=w.id AND generation=w.generation AND kind=item.kind AND start_time=item.start_time;
17
+ END IF;
18
+ END LOOP;
19
+ END IF;
20
+ lo := 'epoch'::timestamptz+(w.correction_from/p_scale)*interval '1 millisecond';
21
+ hi := 'epoch'::timestamptz+(w.correction_until/p_scale)*interval '1 millisecond';
22
+ SELECT least(lo,COALESCE(min(start_time),lo)),greatest(hi,COALESCE(max(end_time),hi)) INTO lo,hi
23
+ FROM history_corrections WHERE work_id=w.id AND generation=w.generation;
24
+ INSERT INTO history_annotations(machine,kind,start_time,name,end_time,duration,tags,properties,resolved,consumed)
25
+ SELECT machine,kind,start_time,name,end_time,duration,tags,properties,resolved,consumed FROM segments
26
+ WHERE machine=p_machine AND kind='phase' AND start_time<=hi AND end_time>=lo
27
+ ON CONFLICT(machine,kind,start_time,name) DO UPDATE SET end_time=greatest(history_annotations.end_time,EXCLUDED.end_time),
28
+ duration=EXCLUDED.duration,tags=EXCLUDED.tags,properties=EXCLUDED.properties,resolved=EXCLUDED.resolved,consumed=EXCLUDED.consumed;
29
+ UPDATE segments SET end_time=lo,duration=greatest(0,extract(epoch FROM lo-start_time)),updated_at=clock_timestamp()
30
+ WHERE machine=p_machine AND kind='phase' AND start_time<lo AND end_time>lo AND duration>0;
31
+ DELETE FROM segments WHERE machine=p_machine AND kind='phase' AND start_time>=lo
32
+ AND (start_time<hi OR (start_time=hi AND end_time=hi));
33
+ FOR item IN SELECT * FROM history_corrections WHERE work_id=w.id AND generation=w.generation ORDER BY start_time LOOP
34
+ SELECT EXISTS(SELECT 1 FROM history_annotations WHERE machine=p_machine AND kind=item.kind AND name=item.name
35
+ AND start_time=item.end_time AND end_time=item.end_time) INTO endpoint_cut;
36
+ a := item.start_time;
37
+ FOR b IN SELECT cut FROM (
38
+ SELECT start_time AS cut FROM history_annotations WHERE machine=p_machine AND kind=item.kind
39
+ AND start_time>item.start_time AND start_time<item.end_time
40
+ UNION SELECT item.end_time
41
+ ) boundaries ORDER BY cut LOOP
42
+ SELECT * INTO owner FROM history_annotations WHERE machine=p_machine AND kind=item.kind AND name=item.name
43
+ AND start_time<=a AND start_time<=item.end_time AND end_time>=item.start_time ORDER BY start_time DESC LIMIT 1;
44
+ IF NOT FOUND THEN
45
+ SELECT * INTO owner FROM history_annotations WHERE machine=p_machine AND kind=item.kind AND name=item.name
46
+ AND start_time>a AND start_time<=item.end_time AND end_time>=item.start_time ORDER BY start_time LIMIT 1;
47
+ END IF;
48
+ incoming := COALESCE(NULLIF(NULLIF(item.properties,''),'null')::jsonb,'{}'::jsonb);
49
+ inherited := COALESCE(NULLIF(NULLIF(owner.properties,''),'null')::jsonb,'{}'::jsonb);
50
+ IF jsonb_typeof(incoming)<>'object' THEN incoming:='{}'::jsonb; END IF;
51
+ IF jsonb_typeof(inherited)<>'object' THEN inherited:='{}'::jsonb; END IF;
52
+ INSERT INTO segments(machine,kind,name,start_time,end_time,duration,options,tags,properties,resolved,consumed,updated_at)
53
+ VALUES(p_machine,item.kind,item.name,a,b,CASE WHEN item.duration=0 AND b=item.end_time AND NOT endpoint_cut THEN 0 ELSE extract(epoch FROM b-a) END,
54
+ item.options,COALESCE(owner.tags,item.tags),(incoming||(inherited-keys))::text,COALESCE(owner.resolved,item.resolved),COALESCE(owner.consumed,true),clock_timestamp())
55
+ ON CONFLICT(machine,kind,start_time) DO UPDATE SET name=EXCLUDED.name,end_time=EXCLUDED.end_time,duration=EXCLUDED.duration,
56
+ options=EXCLUDED.options,tags=EXCLUDED.tags,properties=EXCLUDED.properties,resolved=EXCLUDED.resolved,consumed=EXCLUDED.consumed,updated_at=EXCLUDED.updated_at;
57
+ inserted:=inserted+1; a:=b;
58
+ END LOOP;
59
+ IF item.start_time<item.end_time AND endpoint_cut THEN
60
+ SELECT * INTO owner FROM history_annotations WHERE machine=p_machine AND kind=item.kind AND name=item.name AND start_time=item.end_time;
61
+ incoming := COALESCE(NULLIF(NULLIF(item.properties,''),'null')::jsonb,'{}'::jsonb);
62
+ inherited := COALESCE(NULLIF(NULLIF(owner.properties,''),'null')::jsonb,'{}'::jsonb);
63
+ IF jsonb_typeof(incoming)<>'object' THEN incoming:='{}'::jsonb; END IF;
64
+ IF jsonb_typeof(inherited)<>'object' THEN inherited:='{}'::jsonb; END IF;
65
+ INSERT INTO segments(machine,kind,name,start_time,end_time,duration,options,tags,properties,resolved,consumed)
66
+ VALUES(p_machine,item.kind,item.name,item.end_time,item.end_time,0,item.options,owner.tags,(incoming||(inherited-keys))::text,owner.resolved,COALESCE(owner.consumed,true))
67
+ ON CONFLICT(machine,kind,start_time) DO NOTHING;
68
+ END IF;
69
+ END LOOP;
70
+ INSERT INTO history_checkpoints(machine,classifier_key,time_ms,state,valid)
71
+ SELECT machine,classifier_key,time_ms,state,true FROM history_staged_checkpoints WHERE work_id=w.id AND generation=w.generation
72
+ ON CONFLICT(machine,classifier_key,time_ms) DO UPDATE SET state=EXCLUDED.state,valid=true;
73
+ RETURN inserted;
74
+ END $$;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yarkivaev/scada",
3
- "version": "2.6.18",
3
+ "version": "2.6.20",
4
4
  "description": "SCADA domain objects, state persistence, and plant monitoring",
5
5
  "repository": {
6
6
  "type": "git",
@@ -7,7 +7,11 @@ export async function classifierClaim(pool,machine,{workId,workToken,from,until,
7
7
  if(!workId){return null;}
8
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
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;}
10
+ const stored=row && (row.cursor_ms===null?null:Number(row.cursor_ms));
11
+ const bound=row && (row.end_ms===null?null:Number(row.end_ms));
12
+ if(!row || Number(row.from_ms)!==from || Number(row.until_ms)!==until || stored!==cursor || (end!==null && bound!==end)){
13
+ const error=new Error('History work claim changed');error.statusCode=409;throw error;
14
+ }
11
15
  return row;
12
16
  }
13
17
  export async function classifierSeed(pool,machine,before,key,{claim,cursor}={}) {
@@ -1,4 +1,4 @@
1
- import { createHash } from 'node:crypto';
1
+ import historyRevision from './historyRevision.js';
2
2
  import historySeed from './historySeed.js';
3
3
  import historyObservationsPg from './historyObservations.js';
4
4
  import {classifierClaim,classifierPage,classifierSeed} from './historyCheckpoint.js';
@@ -24,6 +24,8 @@ export default async function historyContext(pool,machine,from,until,{padding,cu
24
24
  const range = { from,until,paddingMs:padding,cursor,end:envelope,...(classifierKey && {classifierKey}),...(timeScale!==1 && {timeScale}),...(workId && {workId,workToken}) };
25
25
  if ((cursor !== null && !Number.isSafeInteger(cursor)) || (envelope !== null && !Number.isSafeInteger(envelope))) { throw new TypeError('Invalid history cursor'); }
26
26
  const claim=await classifierClaim(pool,machine,{workId,workToken,from,until,cursor,end:envelope});
27
+ const held=claim && envelope===null && claim.end_ms!==null ? Number(claim.end_ms) : envelope;
28
+ if (held!==null && envelope===null) { range.end=held; }
27
29
  if (from<cutoff && !claim) {
28
30
  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]);
29
31
  if (!pending.rowCount) { return {available:false,items:[],segments:[],annotations:[],context:range}; }
@@ -31,13 +33,14 @@ export default async function historyContext(pool,machine,from,until,{padding,cu
31
33
  const classifier=classifierKey ? await classifierSeed(pool,machine,cursor ?? from,classifierKey,{claim,cursor}) : null;
32
34
  let left = cursor ?? from-padding;
33
35
  if (classifierKey && cursor===null) { left=classifier ? classifier.at+1 : await source.start(machine); }
34
- const right = classifierKey && envelope!==null ? envelope : Math.max(envelope ?? until,await source.boundary(machine,from,until,padding));
35
- 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)]);
36
- const tail=classifierKey ? await pool.query("SELECT max(end_time) AS end_time FROM segments WHERE machine=$1 AND kind='phase'",[machine]) : null;
37
- const extended = 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);
36
+ const right = classifierKey && held!==null ? held : Math.max(held ?? until,await source.boundary(machine,from,until,padding));
37
+ const previous = await pool.query(`SELECT kind,name,start_time,end_time,duration FROM segments WHERE machine=$1 AND kind='phase' AND start_time<=$2 ORDER BY start_time DESC LIMIT 1`,[machine,new Date(right/timeScale)]);
38
+ const prior=previous.rows.at(-1);
39
+ const edge=classifierKey && prior && Number(prior.duration)===0 ? right : await segmentBoundary(pool,machine,right,previous.rows,timeScale);
40
+ const extended = classifierKey && held!==null ? held : Math.max(held ?? right,edge);
38
41
  const fence = !classifierKey && timeScale===1 ? await historyFence(pool, machine) : null;
39
42
  const end = fence!==null && until<fence ? Math.min(extended, fence-1) : extended;
40
- if(classifierKey && claim && envelope===null){
43
+ if(classifierKey && claim && held===null){
41
44
  await pool.query('UPDATE history_work SET end_ms=$3 WHERE id=$1 AND machine=$2',[workId,machine,end]);
42
45
  range.end=end;
43
46
  }
@@ -64,5 +67,5 @@ export default async function historyContext(pool,machine,from,until,{padding,cu
64
67
  const last = observations.items.at(-1)?.time;
65
68
  const rightClosed = next === null && last !== undefined && segments.rows.some((row) => { return row.duration>0 && new Date(row.end_time).getTime()*timeScale>=last; });
66
69
  const snapshot = { page,initial,...(classifierKey && {classifierSeed:classifier}),annotations:annotations.rows,segments:segments.rows,...observations,rightClosed };
67
- return { ...snapshot,available:true,revision:createHash('sha256').update(JSON.stringify(snapshot)).digest('hex'),context:range };
70
+ return { ...snapshot,available:true,revision:historyRevision(snapshot, until, timeScale),context:range };
68
71
  }
@@ -0,0 +1,34 @@
1
+ import { createHash } from 'node:crypto';
2
+
3
+ function closedContinuity(rows, until) {
4
+ return (rows ?? []).flatMap((row) => {
5
+ const from = Number(row.from);
6
+ if (from > until) { return []; }
7
+ return [{ from, until: Math.min(Number(row.until), until) }];
8
+ });
9
+ }
10
+ function frozen(until, timeScale, row) {
11
+ if (!row?.end_time) { return row; }
12
+ const edge = new Date(row.end_time).getTime() * timeScale;
13
+ if (edge <= until) { return row; }
14
+ return { ...row, end_time: new Date(until / timeScale) };
15
+ }
16
+
17
+ /**
18
+ * Closed-page identity. Observations after until cannot change the claim.
19
+ *
20
+ * {{{
21
+ * historyRevision({ items, segments, annotations, continuity }, until, timeScale)
22
+ * }}}
23
+ */
24
+ export default function historyRevision(snapshot, until, timeScale = 1) {
25
+ if (!Number.isSafeInteger(until)) { throw new TypeError('Closed history until required'); }
26
+ const items = (snapshot.items ?? []).filter((row) => { return Number(row.time) <= until; });
27
+ return createHash('sha256').update(JSON.stringify({
28
+ initial: snapshot.initial,
29
+ annotations: (snapshot.annotations ?? []).map((row) => { return frozen(until, timeScale, row); }),
30
+ segments: (snapshot.segments ?? []).map((row) => { return frozen(until, timeScale, row); }),
31
+ items,
32
+ continuity: closedContinuity(snapshot.continuity, until)
33
+ })).digest('hex');
34
+ }