@yarkivaev/scada 2.6.6 → 2.6.8

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.6",
3
+ "version": "2.6.8",
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
  }
@@ -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';
@@ -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
  }