@yarkivaev/scada 2.6.5 → 2.6.7

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.5",
3
+ "version": "2.6.7",
4
4
  "description": "SCADA domain objects, state persistence, and plant monitoring",
5
5
  "repository": {
6
6
  "type": "git",
@@ -12,7 +12,9 @@ export default function validateCatalog(catalog) {
12
12
  for (const task of catalog.tasks) {
13
13
  if (typeof task.taskId !== 'string' || tasks.has(task.taskId) || !task.spec?.adapter || !Number.isSafeInteger(task.copies ?? 2) || (task.copies ?? 2) < 1
14
14
  || !Number.isFinite(task.cost ?? 1) || (task.cost ?? 1) <= 0 || (task.pinnedNode && !nodes.has(task.pinnedNode))
15
- || (task.eligibleNodes && (!Array.isArray(task.eligibleNodes) || task.eligibleNodes.some((id) => { return !nodes.has(id); })))) {
15
+ || (task.eligibleNodes && (!Array.isArray(task.eligibleNodes) || task.eligibleNodes.some((id) => { return !nodes.has(id); })))
16
+ || (task.preference && (!Array.isArray(task.preference) || new Set(task.preference).size !== task.preference.length || task.preference.some((id) => { return !nodes.has(id) || (task.eligibleNodes && !task.eligibleNodes.includes(id)); })))
17
+ || (task.near && (!Array.isArray(task.near) || new Set(task.near).size !== task.near.length || task.near.some((id) => { return !identifier.test(id); })))) {
16
18
  throw new TypeError('Invalid control task');
17
19
  }
18
20
  if ((task.spec.adapter === 'serial' || String(task.spec.from ?? '').startsWith('rtu:')) && !task.pinnedNode) { throw new TypeError('Serial task requires pinnedNode'); }
@@ -7,12 +7,42 @@ function clockSkew(value) {
7
7
  if (!Number.isFinite(value) || value <= 0) { throw new TypeError('Positive finite clock skew bound required'); }
8
8
  }
9
9
  function copies(task) { return task.pinnedNode ? 1 : task.copies ?? 2; }
10
+ function preferenceRank(task, id) {
11
+ if (!task.preference) { return 0; }
12
+ const index = task.preference.indexOf(id);
13
+ return index < 0 ? task.preference.length : index;
14
+ }
15
+ function hasCache(task, node) {
16
+ if (!task.near?.length) { return 0; }
17
+ const held = new Set(node.assignments.map((row) => { return row.taskId; }));
18
+ return task.near.some((id) => { return held.has(id); }) ? 0 : 1;
19
+ }
20
+ function byPlace(task) {
21
+ return (left, right) => {
22
+ return hasCache(task, left) - hasCache(task, right) || preferenceRank(task, left.id) - preferenceRank(task, right.id) || left.load / left.capacity - right.load / right.capacity || left.id.localeCompare(right.id);
23
+ };
24
+ }
10
25
  function freshRead(report, input, { now, freshnessMs, controlEpoch, clockSkewMs }) {
11
26
  return inEpoch(report, controlEpoch) && report?.tasks?.some((row) => {
12
27
  return row.taskId === input.taskId && row.generation === input.generation && row.state === 'running' && !['degraded', 'failed'].includes(row.health)
13
28
  && Number.isFinite(row.lastRead) && row.lastRead <= now + clockSkewMs && now - row.lastRead <= freshnessMs;
14
29
  });
15
30
  }
31
+ function retain(slots, tasks, owners, observed, timing) {
32
+ for (const task of tasks) {
33
+ const confirmed = owners(task).filter((node) => {
34
+ const input = node.assignments.find((row) => { return row.taskId === task.taskId; });
35
+ return wanted(task, node) && node.assignments.some((row) => { return row.taskId === task.taskId && same(row.spec, task.spec); }) && freshRead(observed.get(node.id), input, timing);
36
+ });
37
+ if (confirmed.length >= copies(task)) {
38
+ const ordered = task.preference ? [...confirmed].sort(byPlace(task)) : confirmed;
39
+ const keep = new Set(ordered.slice(0, copies(task)).map((node) => { return node.id; }));
40
+ slots.filter((node) => { return node.live && !keep.has(node.id); }).forEach((node) => {
41
+ node.assignments = node.assignments.filter((row) => { return row.taskId !== task.taskId; });
42
+ });
43
+ }
44
+ }
45
+ }
16
46
  function failedRead(report, input, controlEpoch) {
17
47
  return input && inEpoch(report, controlEpoch) && report?.tasks?.some((row) => {
18
48
  return row.taskId === input.taskId && row.generation === input.generation && row.state === 'failed';
@@ -64,7 +94,7 @@ export default function schedule(catalog, reports, current, { now = Date.now(),
64
94
  const assignments = previous.assignments.filter((row) => { return !live(node.id) || taskMap.has(row.taskId); });
65
95
  return { ...node, previous, assignments: [...assignments], live: live(node.id), load: assignments.reduce((total, row) => { return total + (taskMap.get(row.taskId)?.cost ?? 1); }, 0) };
66
96
  });
67
- const tasks = [...catalog.tasks].sort((a, b) => { return Number(Boolean(b.pinnedNode)) - Number(Boolean(a.pinnedNode)) || a.taskId.localeCompare(b.taskId); });
97
+ const tasks = [...catalog.tasks].sort((a, b) => { return Number(Boolean(b.pinnedNode)) - Number(Boolean(a.pinnedNode)) || Number(Boolean(a.near?.length)) - Number(Boolean(b.near?.length)) || a.taskId.localeCompare(b.taskId); });
68
98
  function owners(task) {
69
99
  return slots.filter((node) => {
70
100
  const input = node.assignments.find((row) => { return row.taskId === task.taskId; });
@@ -81,7 +111,7 @@ export default function schedule(catalog, reports, current, { now = Date.now(),
81
111
  const surviving = active.some((node) => { return freshRead(observed.get(node.id), node.assignments.find((row) => { return row.taskId === task.taskId; }), { now, freshnessMs, controlEpoch, clockSkewMs }); });
82
112
  const waiting = surviving && missing.some((node) => { return now - (observed.get(node.id)?.receivedAt ?? 0) < replacementDelayMs; });
83
113
  const candidates = slots.filter((node) => { return node.live && wanted(task, node) && !active.includes(node) && !node.assignments.some((row) => { return row.taskId === task.taskId; }) && node.load + (task.cost ?? 1) <= node.capacity; });
84
- candidates.sort((a, b) => { return a.load / a.capacity - b.load / b.capacity || a.id.localeCompare(b.id); });
114
+ candidates.sort(byPlace(task));
85
115
  if (active.length <= round && active.length < copies(task) && !waiting && candidates.length) {
86
116
  const node = candidates[0];
87
117
  node.assignments.push({ taskId: task.taskId, specVersion: 1, generation: 0, assignedAt: now, spec: task.spec });
@@ -89,15 +119,6 @@ export default function schedule(catalog, reports, current, { now = Date.now(),
89
119
  }
90
120
  }
91
121
  }
92
- for (const task of tasks) {
93
- const active = owners(task);
94
- const confirmed = active.filter((node) => { return wanted(task, node) && node.assignments.some((row) => { return row.taskId === task.taskId && same(row.spec, task.spec); }) && freshRead(observed.get(node.id), node.assignments.find((row) => { return row.taskId === task.taskId; }), { now, freshnessMs, controlEpoch, clockSkewMs }); });
95
- if (confirmed.length >= copies(task)) {
96
- const keep = new Set(confirmed.slice(0, copies(task)).map((node) => { return node.id; }));
97
- slots.filter((node) => { return node.live && !keep.has(node.id); }).forEach((node) => {
98
- node.assignments = node.assignments.filter((row) => { return row.taskId !== task.taskId; });
99
- });
100
- }
101
- }
122
+ retain(slots, tasks, owners, observed, { now, freshnessMs, controlEpoch, clockSkewMs });
102
123
  return snapshots(slots, taskMap, catalog, observed, { now, freshnessMs, clockSkewMs });
103
124
  }
@@ -1,4 +1,6 @@
1
1
  import nativeHistoryBounds, {nativeTailProtocol} from './historyNativeBounds.js';
2
+ import historyAbsorb from './historyAbsorb.js';
3
+ import historyFence from './historyFence.js';
2
4
  import retainMetricReceipts from '../../ingest/db/retainMetricReceipts.js';
3
5
  import historyContext from './historyContext.js';
4
6
  import historyAdmission, {assertHistoryReady} from './historyAdmission.js';
@@ -105,6 +107,7 @@ function commit(pool, machine, workId, segments, {base, observationSource,timeSc
105
107
  SELECT machine,kind,start_time,name,end_time,duration,tags,properties,resolved FROM segments
106
108
  WHERE machine=$1 AND start_time<=$3 AND end_time>=$2
107
109
  ON CONFLICT(machine,kind,start_time,name) DO UPDATE SET end_time=greatest(history_annotations.end_time,EXCLUDED.end_time),duration=EXCLUDED.duration,tags=EXCLUDED.tags,properties=EXCLUDED.properties,resolved=EXCLUDED.resolved`, [machine,new Date((latest?.context.page.from ?? base.from)/timeScale),new Date((latest?.context.page.until ?? base.until)/timeScale)]);
110
+ await historyAbsorb(client, machine, segments);
108
111
  for (const item of segments) {
109
112
  // Only computed fields change. User cuts/labels must be applied by caller before commit.
110
113
  // eslint-disable-next-line no-await-in-loop
@@ -166,7 +169,9 @@ export default function historyPg(pool, { retentionDays = 30, now = Date.now, ob
166
169
  async work(machine) {
167
170
  machineName(machine);
168
171
  if (observationSource) { try { await assertHistoryReady(pool,machine); } catch (error) { if (error.statusCode===409) { return {items:[]}; } throw error; } }
169
- const result = await pool.query('SELECT id,token,machine AS "streamId",from_ms AS "from",until_ms AS "until",cursor_ms AS cursor,end_ms AS end FROM history_work WHERE machine=$1 ORDER BY until_ms DESC,created_at,id LIMIT 8', [machine]);
172
+ const fence = observationSource ? null : await historyFence(pool, machine);
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]);
170
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) }; }) };
171
176
  },
172
177
  commit(machine, workId, segments, base) { return commit(pool, machine, workId, segments, {base, observationSource,timeScale}); }
@@ -0,0 +1,18 @@
1
+ function mark(item) {
2
+ return typeof item.tags === 'string' ? item.tags : JSON.stringify(item.tags ?? null);
3
+ }
4
+
5
+ /** Drop same-name same-tag starts strictly inside a segment this commit already covers. */
6
+ export default async function historyAbsorb(client, machine, segments) {
7
+ const covered = segments.filter((item) => { return item.start_time && item.end_time && item.name; }).map((item) => {
8
+ return { name: item.name, start_time: item.start_time, end_time: item.end_time, tags: mark(item) };
9
+ });
10
+ if (!covered.length) { return 0; }
11
+ const removed = await client.query(`DELETE FROM segments AS stored WHERE stored.machine=$1 AND stored.kind='phase' AND EXISTS (
12
+ SELECT 1 FROM json_array_elements($2::json) AS item
13
+ WHERE stored.name=item->>'name'
14
+ AND stored.start_time > (item->>'start_time')::timestamptz
15
+ AND stored.start_time < (item->>'end_time')::timestamptz
16
+ AND coalesce(stored.tags,'') = coalesce(item->>'tags',''))`, [machine, JSON.stringify(covered)]);
17
+ return removed.rowCount;
18
+ }
@@ -2,6 +2,7 @@ import { createHash } from 'node:crypto';
2
2
  import historySeed from './historySeed.js';
3
3
  import historyObservationsPg from './historyObservations.js';
4
4
  import {classifierClaim,classifierPage,classifierSeed} from './historyCheckpoint.js';
5
+ import historyFence from './historyFence.js';
5
6
 
6
7
  function bounded(rows) {
7
8
  if (rows.length>10000) { throw new Error('History context capacity exceeded; retain work for bounded refinement'); }
@@ -33,7 +34,9 @@ export default async function historyContext(pool,machine,from,until,{padding,cu
33
34
  const right = classifierKey && envelope!==null ? envelope : Math.max(envelope ?? until,await source.boundary(machine,from,until,padding));
34
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)]);
35
36
  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
+ 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);
38
+ const fence = !classifierKey && timeScale===1 ? await historyFence(pool, machine) : null;
39
+ const end = fence!==null && until<fence ? Math.min(extended, fence-1) : extended;
37
40
  if(classifierKey && claim && envelope===null){
38
41
  await pool.query('UPDATE history_work SET end_ms=$3 WHERE id=$1 AND machine=$2',[workId,machine,end]);
39
42
  range.end=end;
@@ -0,0 +1,6 @@
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]);
5
+ return Number(result.rows[0].open_ms);
6
+ }
@@ -12,7 +12,7 @@ export default async function historySeed(pool, machine, before, maxGap, {observ
12
12
  SELECT DISTINCT time_ms FROM history_observations WHERE machine=$1 AND time_ms<$2
13
13
  ), gaps AS (
14
14
  SELECT time_ms,time_ms-lag(time_ms) OVER (ORDER BY time_ms) AS gap FROM times
15
- ), boundary AS (
15
+ ), boundary AS MATERIALIZED (
16
16
  SELECT COALESCE(max(time_ms) FILTER (WHERE gap>$3),min(time_ms)) AS at FROM gaps
17
17
  ) SELECT DISTINCT ON (channel) channel,time_ms AS time,value,boundary.at AS since FROM history_observations,boundary
18
18
  WHERE machine=$1 AND time_ms>=boundary.at AND time_ms<$2 ORDER BY channel,time_ms DESC`, [machine,before,maxGap]);