@yarkivaev/scada 2.6.7 → 2.6.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yarkivaev/scada",
3
- "version": "2.6.7",
3
+ "version": "2.6.10",
4
4
  "description": "SCADA domain objects, state persistence, and plant monitoring",
5
5
  "repository": {
6
6
  "type": "git",
@@ -29,7 +29,8 @@ function familyRecord(parsed) {
29
29
  export function decodeSegment(raw) {
30
30
  try {
31
31
  const parsed = JSON.parse(raw.payload);
32
- return parsed.type === 'split-family' ? familyRecord(parsed) : segmentNormalize(parsed);
32
+ if (parsed.type === 'split-family') { return familyRecord(parsed); }
33
+ return segmentNormalize(parsed);
33
34
  } catch (error) {
34
35
  error.permanent = true;
35
36
  throw error;
@@ -6,9 +6,8 @@ import userDecisionSink from '../sinks/userDecisionSink.js';
6
6
  /**
7
7
  * Pipeline for logging operator tag decisions from RabbitMQ to PostgreSQL.
8
8
  *
9
- * Subscribes to the user_decisions STOMP exchange and inserts each received
10
- * decision into the user_decisions audit table. Decisions carry machine,
11
- * start timestamp, operator identity, and full JSON payload.
9
+ * Subscribes to the user_decisions queue, applies each decision to segments,
10
+ * and appends the same payload to the user_decisions audit table.
12
11
  *
13
12
  * @example
14
13
  * const pipeline = decisionPipeline(
@@ -21,7 +21,7 @@ export const segmentColumns = ['machine', 'kind', 'name', 'start_time', 'end_tim
21
21
  export const segmentConflict = ['machine', 'kind', 'start_time'];
22
22
  export const segmentUpdateColumns = ['name', 'end_time', 'duration', 'options', 'resolved', 'updated_at'];
23
23
  export const splitUpdateColumns = ['name', 'end_time', 'duration', 'tags', 'options', 'properties', 'resolved'];
24
- export const segmentUpdateWhere = '(segments.duration = 0 OR EXCLUDED.duration > 0 OR EXCLUDED.end_time > segments.end_time) AND NOT (segments.duration > 0 AND EXCLUDED.duration = 0 AND COALESCE(segments.properties, \'\') LIKE \'%"split_of"%\')';
24
+ export const segmentUpdateWhere = '(segments.duration = 0 OR EXCLUDED.duration > 0 OR EXCLUDED.end_time > segments.end_time) AND NOT (segments.duration > 0 AND EXCLUDED.duration = 0 AND COALESCE(segments.properties, \'\') LIKE \'%"split_of"%\' AND EXISTS (SELECT 1 FROM segments AS kin WHERE kin.machine = segments.machine AND kin.kind = segments.kind AND kin.start_time > segments.start_time AND COALESCE(kin.properties, \'\') LIKE \'%"split_of"%\'))';
25
25
  export const segmentsIngestDestination = '/queue/scada.segments.ingest';
26
26
 
27
27
  export { default as segmentDispatch } from '../../../domain/segment/dispatch.js';
@@ -0,0 +1,49 @@
1
+ import { checkSplit, familyCover, loadFamily, replaceSplit, splitRows } from '../../../domain/segment/splitFamily.js';
2
+
3
+ function piece(raw) {
4
+ return {
5
+ start: new Date(Number(raw.start) * 1000),
6
+ end: new Date(Number(raw.end) * 1000),
7
+ tag: raw.tag || '',
8
+ open: Boolean(raw.open)
9
+ };
10
+ }
11
+
12
+ async function applySplit(pool, machine, start, splits) {
13
+ const family = await loadFamily(pool, machine, start);
14
+ if (family.length === 0) {
15
+ return;
16
+ }
17
+ const ordered = checkSplit(familyCover(family), splits.map(piece));
18
+ const [first] = ordered;
19
+ await replaceSplit(pool, { machine, origin: first.start.getTime(), pieces: splitRows(machine, ordered) });
20
+ }
21
+
22
+ /**
23
+ * Applies one operator decision to the segment rows it names.
24
+ * A tag list replaces the stored tags, including an empty list.
25
+ * A split rewrites the off family and keeps each piece tag.
26
+ *
27
+ * @param {object} pool - pg pool
28
+ * @param {string} machine - machine id
29
+ * @param {string} startTime - segment start as an ISO timestamp
30
+ * @param {string} payload - raw user_decisions JSON
31
+ * @returns {Promise<void>}
32
+ *
33
+ * @example
34
+ * await applyDecision(pool, 'icht2', '2026-11-17T07:17:09.930Z', '{"tags":["to_ladle"]}');
35
+ */
36
+ export async function applyDecision(pool, machine, startTime, payload) {
37
+ const body = JSON.parse(payload);
38
+ if (Array.isArray(body.splits)) {
39
+ await applySplit(pool, machine, new Date(startTime), body.splits);
40
+ return;
41
+ }
42
+ if (!Array.isArray(body.tags)) {
43
+ return;
44
+ }
45
+ await pool.query(
46
+ 'UPDATE segments SET tags = $1, properties = $2 WHERE machine = $3 AND start_time = $4 AND kind = \'phase\'',
47
+ [JSON.stringify(body.tags), JSON.stringify(body.properties || {}), machine, startTime]
48
+ );
49
+ }
@@ -1,10 +1,11 @@
1
1
  import processingErrorLog from '../processingErrorLog.js';
2
+ import { applyDecision } from './decisionSegment.js';
2
3
 
3
4
  /**
4
- * Sink for inserting user tag decisions into the user_decisions audit table.
5
+ * Sink for operator decisions from the user_decisions queue.
5
6
  *
6
- * Each accepted record is persisted with machine, start_time, username,
7
- * operator_id, decided_at, and the full raw JSON payload.
7
+ * The decision is applied to segments first, then appended to the audit table.
8
+ * A tag list replaces stored tags. A split rewrites the matching off family.
8
9
  *
9
10
  * @example
10
11
  * const sink = userDecisionSink(pool);
@@ -22,12 +23,13 @@ export default function userDecisionSink(pool) {
22
23
  }
23
24
  return {
24
25
  /**
25
- * Inserts a user decision record into the user_decisions table.
26
+ * Applies the decision to segments, then inserts the audit row.
26
27
  *
27
28
  * @param {object} record - machine, startTime, username, operatorId, decidedAt, payload
28
29
  */
29
30
  async accept({ machine, startTime, username, operatorId, decidedAt, payload }) {
30
31
  try {
32
+ await applyDecision(pool, machine, startTime, payload);
31
33
  await pool.query(
32
34
  'INSERT INTO user_decisions (machine, start_time, username, operator_id, decided_at, payload) VALUES ($1, $2, $3, $4, $5, $6)',
33
35
  [machine, startTime, username, operatorId ?? null, decidedAt, payload]
@@ -169,9 +169,9 @@ export default function historyPg(pool, { retentionDays = 30, now = Date.now, ob
169
169
  async work(machine) {
170
170
  machineName(machine);
171
171
  if (observationSource) { try { await assertHistoryReady(pool,machine); } catch (error) { if (error.statusCode===409) { return {items:[]}; } throw error; } }
172
- const fence = observationSource ? null : await historyFence(pool, machine);
172
+ const fence = await historyFence(pool, machine, timeScale);
173
173
  const result = await pool.query(`SELECT id,token,machine AS "streamId",from_ms AS "from",until_ms AS "until",cursor_ms AS cursor,end_ms AS end
174
- FROM history_work WHERE machine=$1 ${fence === null ? '' : 'AND until_ms < $2'} ORDER BY until_ms DESC,created_at,id LIMIT 8`, fence === null ? [machine] : [machine, fence]);
174
+ FROM history_work WHERE machine=$1 AND until_ms < $2 ORDER BY until_ms DESC,created_at,id LIMIT 8`, [machine, fence]);
175
175
  return { items: result.rows.map((row) => { return { ...row, from: Number(row.from), until: Number(row.until),cursor:row.cursor === null ? null : Number(row.cursor),end:row.end === null ? null : Number(row.end) }; }) };
176
176
  },
177
177
  commit(machine, workId, segments, base) { return commit(pool, machine, workId, segments, {base, observationSource,timeScale}); }
@@ -37,6 +37,10 @@ export async function assertHistoryReady(pool,machine) {
37
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
38
  if (result.rowCount) { const error=new Error('Unfinished external telemetry admission'); error.statusCode=409; throw error; }
39
39
  }
40
+ async function stamp(client,machine,time) {
41
+ await client.query('DELETE FROM history_observations WHERE machine=$1 AND channel=$2 AND time_ms<$3',[machine,'lead',time]);
42
+ await client.query('INSERT INTO history_observations(machine,channel,time_ms,event_id,value) VALUES($1,$2,$3,$4,0) ON CONFLICT DO NOTHING',[machine,'lead',time,`lead:${machine}:${time}`]);
43
+ }
40
44
  async function enqueue(client,mapping,row) {
41
45
  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
46
  if(pending.rowCount){
@@ -68,6 +72,8 @@ export default function historyAdmission(pool,{now=Date.now,timeScale=1,timestam
68
72
  await client.query('UPDATE history_checkpoints SET valid=false WHERE machine=$1 AND time_ms>=$2',[mapping.machine,Math.min(...times)]);
69
73
  // eslint-disable-next-line no-await-in-loop
70
74
  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)]);
75
+ // eslint-disable-next-line no-await-in-loop
76
+ await stamp(client,mapping.machine,Math.floor(Math.max(...times)/timeScale));
71
77
  }
72
78
  for (const row of eligible) {
73
79
  // eslint-disable-next-line no-await-in-loop
@@ -1,6 +1,7 @@
1
- /** Start of the furnace bucket that can still receive observations, in milliseconds. */
2
- export default async function historyFence(pool, machine) {
3
- const result = await pool.query(`SELECT floor(extract(epoch FROM clock_timestamp())*1000 / bucket) * bucket AS open_ms
4
- FROM (SELECT COALESCE((SELECT bucket_ms FROM history_topics WHERE machine=$1 LIMIT 1), 30000) AS bucket) sizes`, [machine]);
1
+ /** Start of the furnace bucket that can still receive observations, in the work time unit. */
2
+ export default async function historyFence(pool, machine, timeScale = 1) {
3
+ if (![1, 1000].includes(timeScale)) { throw new TypeError('External history supports millisecond or microsecond coordinates'); }
4
+ const result = await pool.query(`SELECT floor(extract(epoch FROM clock_timestamp()) * 1000 * $2 / bucket) * bucket AS open_ms
5
+ FROM (SELECT COALESCE((SELECT bucket_ms FROM history_topics WHERE machine=$1 LIMIT 1), 30000 * $2) AS bucket) sizes`, [machine, timeScale]);
5
6
  return Number(result.rows[0].open_ms);
6
7
  }