@yarkivaev/scada 2.6.12 → 2.6.16

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.12",
3
+ "version": "2.6.16",
4
4
  "description": "SCADA domain objects, state persistence, and plant monitoring",
5
5
  "repository": {
6
6
  "type": "git",
@@ -91,6 +91,10 @@ export default function deliveryQueue(directory, options) {
91
91
  })().catch((error) => { state.closing = null; throw error; });
92
92
  return state.closing;
93
93
  },
94
+ peek(limit = 1000) {
95
+ if (state.closed) { return Promise.reject(new Error('Delivery queue closed')); }
96
+ return commands.barrier(() => { return spool.peek(limit); });
97
+ },
94
98
  status() {
95
99
  const usage = commands.status();
96
100
  return { ...spool.status(), queuedOperations: usage.operations, queuedBytes: usage.bytes, drainFull: state.full };
@@ -3,6 +3,7 @@ import collectorSignals from './collectorSignals.js';
3
3
  import createRuntime from './runtime.js';
4
4
  import runtimeServices from './runtimeServices.js';
5
5
  import runtimeHealth from './runtimeHealth.js';
6
+ import spoolSurface from './spoolSurface.js';
6
7
  import deadline from './deadline.js';
7
8
  import assignmentAgent from '../control/agent.js';
8
9
  import controlStore from '../control/controlStore.js';
@@ -68,7 +69,8 @@ export default async function runCollector({ registry, env = process.env, argv =
68
69
  if (signals) { state.detach = collectorSignals(collector); }
69
70
  try {
70
71
  if (env.COLLECTOR_HEALTH_PORT) { Object.assign(state, { health: await runtimeHealth(healthView(runtime, state), {
71
- port: Number(env.COLLECTOR_HEALTH_PORT), host: env.COLLECTOR_HEALTH_HOST ?? '127.0.0.1' }) }); }
72
+ port: Number(env.COLLECTOR_HEALTH_PORT), host: env.COLLECTOR_HEALTH_HOST ?? '127.0.0.1',
73
+ handle: spoolSurface(owned.deliveryQueue, env.STATE_HTTP_TOKEN) }) }); }
72
74
  const recoveryMs = Number(env.COLLECTOR_RECOVERY_TIMEOUT_MS ?? 900000);
73
75
  if (!Number.isSafeInteger(recoveryMs) || recoveryMs < 1) { throw new TypeError('Positive collector recovery timeout required'); }
74
76
  await deadline(() => { return initialize(collector, owned, state, { env, registry }); }, recoveryMs);
@@ -1,7 +1,8 @@
1
1
  import { createServer } from 'node:http';
2
2
  import { monitorEventLoopDelay } from 'node:perf_hooks';
3
3
 
4
- function response(runtime, histogram, request, result) {
4
+ function response(runtime, histogram, request, result, handle) {
5
+ if (handle?.(request, result)) { return; }
5
6
  if (!['/live', '/ready', '/status'].includes(request.url)) { result.writeHead(404).end(); return; }
6
7
  const state = runtime.status();
7
8
  const ready = state.initialized !== false && !state.fatal && !state.stopping && !state.tasks.some((task) => {
@@ -12,10 +13,10 @@ function response(runtime, histogram, request, result) {
12
13
  result.end(JSON.stringify(body));
13
14
  }
14
15
  /** Read-only health surface. A blocked event loop cannot answer an external probe. */
15
- export default async function runtimeHealth(runtime, { port, host = '127.0.0.1' }) {
16
+ export default async function runtimeHealth(runtime, { port, host = '127.0.0.1', handle = null }) {
16
17
  if (!Number.isInteger(port) || port < 0 || port > 65535) { throw new TypeError('Invalid health port'); }
17
18
  const histogram = monitorEventLoopDelay({ resolution: 20 });
18
- const server = createServer((request, result) => { response(runtime, histogram, request, result); });
19
+ const server = createServer((request, result) => { response(runtime, histogram, request, result, handle); });
19
20
  server.requestTimeout = 2000;
20
21
  server.headersTimeout = 2000;
21
22
  await new Promise((resolve, reject) => { server.once('error', reject); server.listen(port, host, resolve); });
@@ -0,0 +1,76 @@
1
+ /**
2
+ * HistoryRun and SupervisorSinkCheckpoint view of undelivered collector samples.
3
+ *
4
+ * {{{
5
+ * spoolHistory({ peek() { return []; } }).work('icht2')
6
+ * }}}
7
+ */
8
+
9
+ import { nativeTailProtocol } from '../../infrastructure/persistence/pg/historyNativeBounds.js';
10
+ import { randomUUID } from 'node:crypto';
11
+
12
+ function machineOf(key) {
13
+ const match = /icht-?(?<n>\d)/iu.exec(String(key).replaceAll('/', '.'));
14
+ return match ? `icht${match.groups.n}` : null;
15
+ }
16
+ function channelOf(key) {
17
+ const parts = String(key).replaceAll('/', '.').split('.');
18
+ return parts.at(-2) ?? key;
19
+ }
20
+ function sample(record) {
21
+ const key = record.routingKey ?? record.topic;
22
+ const raw = record.body ? JSON.parse(Buffer.isBuffer(record.body) ? record.body.toString() : record.body) : record;
23
+ const time = Number(raw.ts ?? raw.time ?? raw.timestamp);
24
+ const value = Number(raw.value);
25
+ if (!key || !Number.isFinite(time) || !Number.isFinite(value)) { return []; }
26
+ return [{ eventId: record.eventId ?? `${key}:${time}`, channel: channelOf(key), topic: key.replaceAll('.', '/'),
27
+ time, timestamp: time / 1000, value, machine: machineOf(key) }];
28
+ }
29
+ function unpack(event) {
30
+ const payload = event.observation ?? event;
31
+ if (Array.isArray(payload.records)) { return payload.records.flatMap(sample); }
32
+ return sample({ ...payload, eventId: payload.eventId ?? event.eventId });
33
+ }
34
+
35
+ /** Collector spool as a checkpoint and history receiver. */
36
+ export default function spoolHistory(queue) {
37
+ async function rows() {
38
+ if (!queue?.peek) { return []; }
39
+ const listed = await queue.peek(1000);
40
+ return listed.flatMap((item) => { return unpack(item.event ?? item); });
41
+ }
42
+ async function owned(machine) {
43
+ return (await rows()).filter((row) => { return row.machine === machine; });
44
+ }
45
+ return {
46
+ async replayCursor(machine) {
47
+ const times = (await owned(machine)).map((row) => { return row.timestamp; });
48
+ return times.length ? Math.min(...times) : 0;
49
+ },
50
+ pendingSegments() { return Promise.resolve([]); },
51
+ segment() { return Promise.resolve(null); },
52
+ cyclePrior() { return Promise.resolve([]); },
53
+ async readings(topics, from) {
54
+ const wanted = new Set(topics);
55
+ return (await rows()).filter((row) => { return row.timestamp >= from && (!wanted.size || wanted.has(row.topic)); })
56
+ .map((row) => { return { topic: row.topic, timestamp: row.timestamp, value: row.value }; });
57
+ },
58
+ configure() { return Promise.resolve({ nativeTailProtocol }); },
59
+ purge() { return Promise.resolve({}); },
60
+ accept() { return Promise.resolve({ inserted: 0 }); },
61
+ async work(machine) {
62
+ const items = await owned(machine);
63
+ if (!items.length) { return { items: [] }; }
64
+ const times = items.map((row) => { return row.time; });
65
+ return { items: [{ id: randomUUID(), token: randomUUID(), from: Math.min(...times), until: Math.max(...times) }] };
66
+ },
67
+ async context(machine, from, until) {
68
+ const items = (await owned(machine)).filter((row) => { return row.time >= from && row.time <= until; })
69
+ .map((row) => { return { eventId: row.eventId, channel: row.channel, time: row.time, value: row.value }; });
70
+ return { available: true, revision: 'spool', nativeTailMode: nativeTailProtocol,
71
+ context: { from, until }, items, segments: [], annotations: [],
72
+ continuity: items.length ? [{ from: items[0].time, until: items.at(-1).time }] : [] };
73
+ },
74
+ commit() { return Promise.resolve({}); }
75
+ };
76
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Mounts SupervisorSinkCheckpoint and HistoryRun routes on the collector health port.
3
+ *
4
+ * {{{
5
+ * spoolSurface(queue, token)
6
+ * }}}
7
+ */
8
+
9
+ import { routes } from '@yarkivaev/simple-server';
10
+ import checkpointRoutes from '../../infrastructure/http/edge/routes/checkpoint/checkpointRoutes.js';
11
+ import historyRoutes from '../../infrastructure/http/edge/routes/history/historyRoutes.js';
12
+ import spoolHistory from './spoolHistory.js';
13
+
14
+ /** True when the request was a spool history or checkpoint path. */
15
+ export default function spoolSurface(queue, token) {
16
+ if (!queue) { return null; }
17
+ const history = spoolHistory(queue);
18
+ const api = routes([...checkpointRoutes(token ?? null, history), ...historyRoutes(token ?? null, history)]);
19
+ return (request, result) => {
20
+ if (!request.url?.startsWith('/v1/')) { return false; }
21
+ void api.handle(request, result);
22
+ return true;
23
+ };
24
+ }
@@ -1,7 +1,8 @@
1
1
  /**
2
2
  * Pulls a later fragment of the same segment back onto the previous row
3
3
  * when the uncovered gap is still inside the segmentation continuity budget.
4
- * A supervisor restart then does not open a hole where metric samples continued.
4
+ * An overlapping island that starts before the pending heartbeat end stays
5
+ * one segment instead of a second heating.
5
6
  *
6
7
  * @param {number} budgetSeconds - maximum uncovered gap that stays one segment
7
8
  * @returns {function} apply(record, prior) -> record
@@ -19,8 +20,12 @@ export default function segmentContinue(budgetSeconds) {
19
20
  if (priorStart === record.start_time) {
20
21
  return record;
21
22
  }
22
- const gap = Date.parse(record.start_time) - Date.parse(prior.end_time);
23
- if (gap < 0 || gap > budgetSeconds * 1000) {
23
+ const incomingMs = Date.parse(record.start_time);
24
+ if (incomingMs < Date.parse(priorStart)) {
25
+ return record;
26
+ }
27
+ const gap = incomingMs - Date.parse(prior.end_time);
28
+ if (gap > budgetSeconds * 1000) {
24
29
  return record;
25
30
  }
26
31
  const startMs = Date.parse(priorStart);
@@ -2,16 +2,18 @@
2
2
  * Maps a timeline segment row to REST JSON shape.
3
3
  *
4
4
  * @param {object} row - segment with start_time, end_time, duration
5
+ * @param {function} [clock] - paints duration-zero end as now when provided
5
6
  * @returns {object} JSON-serializable segment
6
7
  *
7
8
  * @example
8
9
  * segmentJson({ name: 'on', start_time: new Date(), end_time: new Date(), duration: 60 });
9
10
  */
10
- export default function segmentJson(row) {
11
+ export default function segmentJson(row, clock) {
12
+ const live = row.duration === 0 && typeof clock === 'function';
11
13
  const mapped = {
12
14
  name: row.name,
13
15
  start: row.start_time.toISOString(),
14
- end: row.duration === 0 ? new Date().toISOString() : row.end_time.toISOString(),
16
+ end: live ? clock().toISOString() : row.end_time.toISOString(),
15
17
  duration: row.duration
16
18
  };
17
19
  if (row.kind) {
@@ -28,3 +30,31 @@ export default function segmentJson(row) {
28
30
  }
29
31
  return mapped;
30
32
  }
33
+
34
+ /**
35
+ * Maps GET /segments rows so only the last duration-zero end is painted as now.
36
+ *
37
+ * @param {object[]} rows - timeline rows
38
+ * @param {function} [clock] - now source for the live pending row
39
+ * @returns {object[]} JSON-serializable segments
40
+ *
41
+ * @example
42
+ * segmentItems(rows);
43
+ */
44
+ export function segmentItems(rows, clock = () => {
45
+ return new Date();
46
+ }) {
47
+ const last = rows.reduce((index, row, i) => {
48
+ return row.duration === 0 ? i : index;
49
+ }, -1);
50
+ return rows.map((row, i) => {
51
+ if (i === last) {
52
+ return segmentJson(row, clock);
53
+ }
54
+ if (row.duration !== 0) {
55
+ return segmentJson(row);
56
+ }
57
+ const elapsed = Math.max(1, (Date.parse(row.end_time) - Date.parse(row.start_time)) / 1000);
58
+ return segmentJson({ ...row, duration: elapsed });
59
+ });
60
+ }
@@ -1,6 +1,6 @@
1
1
  import machineInPlant from '../../../../application/machineInPlant.js';
2
2
  import allowedSegmentTags from '../allowedSegmentTags.js';
3
- import segmentJson from '../json/segmentJson.js';
3
+ import { segmentItems } from '../json/segmentJson.js';
4
4
  import timelineOperator from '../timelineOperator.js';
5
5
  import { errorResponse, jsonResponse, readBody, route, sendRouteError } from '@yarkivaev/simple-server';
6
6
 
@@ -97,7 +97,7 @@ export default function timelineRoute(basePath, plant, operatorOptions, decorate
97
97
  });
98
98
  }
99
99
  const rows = await decorate(params.machineId, await result.machine.timeline.list(options));
100
- jsonResponse({ items: rows.map(segmentJson) }).send(res);
100
+ jsonResponse({ items: segmentItems(rows) }).send(res);
101
101
  }),
102
102
  route('PATCH', `${basePath}/machines/:machineId/segments`, async (req, res, params) => {
103
103
  const result = machineInPlant(plant, params.machineId);
@@ -98,10 +98,11 @@ export default function segmentPipeline(stomp, postgres, pool, config) {
98
98
  destination,
99
99
  async start() {
100
100
  if (settings.repairHistoryOnStart !== false) {
101
- const repair = abutSegments(pool, budget);
102
- void repair.catch((error) => {
101
+ try {
102
+ await abutSegments(pool, budget);
103
+ } catch (error) {
103
104
  processingErrorLog('abut_segments', error, { budgetSeconds: budget });
104
- });
105
+ }
105
106
  }
106
107
  await source.start();
107
108
  await silence.start();
@@ -1,18 +1,4 @@
1
- /**
2
- * Closes uncovered time between adjacent same-name segments that stayed
3
- * inside the continuity budget. Existing restart fragments then meet on
4
- * the timeline without deleting rows.
5
- *
6
- * @param {object} pool - pg pool
7
- * @param {number} budgetSeconds - maximum gap that still counts as continuous
8
- * @returns {Promise<void>}
9
- *
10
- * @example
11
- * await abutSegments(pool, 30);
12
- */
13
- export default async function abutSegments(pool, budgetSeconds) {
14
- await pool.query(
15
- `UPDATE segments AS left_row
1
+ const GAP_SQL = `UPDATE segments AS left_row
16
2
  SET end_time = next_row.next_start,
17
3
  duration = EXTRACT(EPOCH FROM (next_row.next_start - left_row.start_time))
18
4
  FROM (
@@ -27,7 +13,65 @@ export default async function abutSegments(pool, budgetSeconds) {
27
13
  AND left_row.duration > 0
28
14
  AND left_row.name = next_row.next_name
29
15
  AND next_row.next_start > left_row.end_time
30
- AND next_row.next_start - left_row.end_time <= make_interval(secs => $1)`,
31
- [budgetSeconds]
32
- );
16
+ AND next_row.next_start - left_row.end_time <= make_interval(secs => $1)`;
17
+
18
+ const ABSORB_SQL = `UPDATE segments AS left_row
19
+ SET end_time = CASE
20
+ WHEN next_row.next_duration = 0 THEN next_row.next_end
21
+ WHEN next_row.next_end > left_row.end_time THEN next_row.next_end
22
+ ELSE left_row.end_time
23
+ END,
24
+ duration = CASE
25
+ WHEN next_row.next_duration = 0 THEN 0
26
+ ELSE EXTRACT(EPOCH FROM (
27
+ CASE
28
+ WHEN next_row.next_end > left_row.end_time THEN next_row.next_end
29
+ ELSE left_row.end_time
30
+ END - left_row.start_time
31
+ ))
32
+ END
33
+ FROM (
34
+ SELECT machine, kind, start_time, name, end_time, duration,
35
+ lead(start_time) OVER (PARTITION BY machine, kind ORDER BY start_time) AS next_start,
36
+ lead(name) OVER (PARTITION BY machine, kind ORDER BY start_time) AS next_name,
37
+ lead(end_time) OVER (PARTITION BY machine, kind ORDER BY start_time) AS next_end,
38
+ lead(duration) OVER (PARTITION BY machine, kind ORDER BY start_time) AS next_duration
39
+ FROM segments
40
+ ) AS next_row
41
+ WHERE left_row.machine = next_row.machine
42
+ AND left_row.kind = next_row.kind
43
+ AND left_row.start_time = next_row.start_time
44
+ AND left_row.name = next_row.next_name
45
+ AND next_row.next_start > left_row.start_time
46
+ AND next_row.next_start <= left_row.end_time + make_interval(secs => $1)`;
47
+
48
+ const COLLAPSE_SQL = `DELETE FROM segments AS later
49
+ USING (
50
+ SELECT machine, kind, name, end_time,
51
+ lead(start_time) OVER (PARTITION BY machine, kind ORDER BY start_time) AS next_start,
52
+ lead(name) OVER (PARTITION BY machine, kind ORDER BY start_time) AS next_name
53
+ FROM segments
54
+ ) AS pair
55
+ WHERE later.machine = pair.machine
56
+ AND later.kind = pair.kind
57
+ AND later.start_time = pair.next_start
58
+ AND pair.name = pair.next_name
59
+ AND pair.next_start <= pair.end_time + make_interval(secs => $1)`;
60
+
61
+ /**
62
+ * Closes uncovered time between adjacent same-name segments that stayed
63
+ * inside the continuity budget, then collapses the later overlapping
64
+ * same-name fragment into the earlier start.
65
+ *
66
+ * @param {object} pool - pg pool
67
+ * @param {number} budgetSeconds - maximum gap that still counts as continuous
68
+ * @returns {Promise<void>}
69
+ *
70
+ * @example
71
+ * await abutSegments(pool, 30);
72
+ */
73
+ export default async function abutSegments(pool, budgetSeconds) {
74
+ await pool.query(GAP_SQL, [budgetSeconds]);
75
+ await pool.query(ABSORB_SQL, [budgetSeconds]);
76
+ await pool.query(COLLAPSE_SQL, [budgetSeconds]);
33
77
  }
@@ -1,5 +1,5 @@
1
1
  import { capacity, checkpoint, counters, database } from './spoolDatabase.js';
2
- import { pending } from './spoolRecords.js';
2
+ import { listed, pending } from './spoolRecords.js';
3
3
  import { pendingFair } from './spoolReplay.js';
4
4
  import spoolMutations from './spoolMutations.js';
5
5
  import spoolMigration from './spoolMigration.js';
@@ -62,6 +62,12 @@ export default function deliverySpool(directory, { maxBytes, maxRecords = 100000
62
62
  return commit(() => { return pendingFair(state.db, limit, blocked); });
63
63
  });
64
64
  },
65
+ peek(limit = 1000) {
66
+ return exclusive(() => {
67
+ if (!Number.isSafeInteger(limit) || limit <= 0) { throw new TypeError('Positive peek limit required'); }
68
+ return listed(state.db, limit);
69
+ });
70
+ },
65
71
  close() {
66
72
  return exclusive(() => {
67
73
  try { if (state.db) { checkpoint(state.db); } } finally { release(); }
@@ -50,4 +50,7 @@ export function pending(db, limit) {
50
50
  db.prepare('UPDATE counters SET sequence=? WHERE id=1').run(sequence);
51
51
  return rows.map((row) => { return decoded(row, db); });
52
52
  }
53
+ export function listed(db, limit) {
54
+ return db.prepare('SELECT * FROM events ORDER BY sequence LIMIT ?').all(limit).map((row) => { return decoded(row, db); });
55
+ }
53
56
  export function admission(db, maxBytes, maxRecords) { return capacity(db, maxBytes, maxRecords); }