@yarkivaev/scada 2.3.52 → 2.3.54

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.3.52",
3
+ "version": "2.3.54",
4
4
  "description": "SCADA domain objects, state persistence, and plant monitoring",
5
5
  "repository": {
6
6
  "type": "git",
@@ -12,12 +12,16 @@ import simulationRoute from '../infrastructure/http/plant/routes/simulationRoute
12
12
  import catalogRoute from '../infrastructure/http/plant/routes/catalogRoute.js';
13
13
  import { routes } from '@yarkivaev/simple-server';
14
14
 
15
+ function pass(_id, rows) {
16
+ return rows;
17
+ }
18
+
15
19
  /**
16
20
  * Composable plant HTTP API factory.
17
21
  *
18
22
  * @param {string} basePath - base URL path
19
23
  * @param {object} plant - plant domain object with operations (optional kindSources at construction)
20
- * @param {object} [config] - clock, extraRoutes, requestTimeoutMs, heartbeat
24
+ * @param {object} [config] - clock, extraRoutes, requestTimeoutMs, heartbeat, decorateTimeline
21
25
  * @returns {object} routes with list() and handle()
22
26
  *
23
27
  * @example
@@ -30,6 +34,7 @@ export default function plantApi(basePath, plant, config) {
30
34
  return new Date();
31
35
  });
32
36
  const extra = opts.extraRoutes || [];
37
+ const decorate = opts.decorateTimeline || pass;
33
38
  const routeList = [
34
39
  ...catalogRoute(basePath, opts.tagCatalog),
35
40
  ...machineRoute(basePath, plant),
@@ -37,8 +42,8 @@ export default function plantApi(basePath, plant, config) {
37
42
  ...measurementRoute(basePath, plant, time),
38
43
  ...alertStream(basePath, plant, time),
39
44
  ...alertRoute(basePath, plant),
40
- ...timelineRoute(basePath, plant, opts.timelineOperator),
41
- ...timelineStream(basePath, plant, time),
45
+ ...timelineRoute(basePath, plant, opts.timelineOperator, decorate),
46
+ ...timelineStream(basePath, plant, time, decorate),
42
47
  ...operationRoute(basePath, plant, opts.timelineOperator, opts.operationDecisions, opts.owners),
43
48
  ...operationStream(basePath, plant, time),
44
49
  ...heartbeatStream(basePath, time, opts.heartbeat),
@@ -72,7 +72,7 @@ async function initStomp(stomp, translations, requirePool) {
72
72
  * Multi-kind operations come from plant.operations built with kindSources
73
73
  * (e.g. plantOperations(persistence, { temp })).
74
74
  *
75
- * @param {object} config - port, basePath, plantFactory, extraRoutes, translations, stomp, requirePool
75
+ * @param {object} config - port, basePath, plantFactory, extraRoutes, translations, stomp, requirePool, decorateTimeline
76
76
  * @returns {Promise<object>} server, plant, api, segments
77
77
  *
78
78
  * @example
@@ -95,7 +95,8 @@ export default async function plantServer(config) {
95
95
  extraRoutes: extra,
96
96
  timelineOperator: config.timelineOperator,
97
97
  operationDecisions: config.operationDecisions,
98
- owners: config.owners
98
+ owners: config.owners,
99
+ decorateTimeline: config.decorateTimeline
99
100
  });
100
101
  const server = http.createServer((req, res) => {
101
102
  return api.handle(req, res);
@@ -142,7 +142,7 @@ function siteExtraRoutes(catalog, extraRoutes) {
142
142
  /**
143
143
  * Unified site process: supervisor-sink HTTP, plant API, and optional MQTT ingest.
144
144
  *
145
- * @param {object} config - port, basePath, translations, requirePool, plantFactory, extraRoutes, operatorCatalog, kindSources, streams, env
145
+ * @param {object} config - port, basePath, translations, requirePool, plantFactory, extraRoutes, operatorCatalog, kindSources, streams, env, decorateTimeline
146
146
  * @returns {Promise<object>} sink, plant, mqtt pipeline
147
147
  *
148
148
  * @example
@@ -185,7 +185,8 @@ export default async function siteServer(config) {
185
185
  extraRoutes: siteExtraRoutes(catalog, config.extraRoutes),
186
186
  timelineOperator: timelineOperatorFromEnv(catalog, env, config),
187
187
  operationDecisions: catalog.decisions,
188
- owners: config.owners
188
+ owners: config.owners,
189
+ decorateTimeline: config.decorateTimeline
189
190
  });
190
191
  return { sink, plant, mqtt, telemetry, operationSync, operatorsSync: catalog.sync };
191
192
  }
@@ -2,7 +2,8 @@ import machineInPlant from '../../../../application/machineInPlant.js';
2
2
  import operationJson from '../json/operationJson.js';
3
3
  import timelineOperator from '../timelineOperator.js';
4
4
  import operationWrites from './operationWrites.js';
5
- import { jsonResponse, route } from '@yarkivaev/simple-server';
5
+ import httpOperations from '../../../messaging/ownership/httpOperations.js';
6
+ import { jsonResponse, route, sendRouteError } from '@yarkivaev/simple-server';
6
7
 
7
8
  function parseRange(query) {
8
9
  const range = {};
@@ -29,11 +30,31 @@ function resolveKinds(query) {
29
30
  return undefined;
30
31
  }
31
32
 
33
+ function edgePort(owners, machineId) {
34
+ if (!owners || typeof owners.resolve !== 'function') {
35
+ return undefined;
36
+ }
37
+ const owner = owners.resolve(machineId);
38
+ if (!owner || owner.kind !== 'edge') {
39
+ return undefined;
40
+ }
41
+ return httpOperations(owner, machineId);
42
+ }
43
+
44
+ async function listLocal(plant, machineId, query) {
45
+ const rows = await plant.operations.listForMachine(
46
+ machineId,
47
+ resolveKinds(query),
48
+ parseRange(query)
49
+ );
50
+ return { items: rows.map(operationJson) };
51
+ }
52
+
32
53
  /**
33
54
  * Operations REST routes for machine-scoped reads and writes.
34
55
  *
35
56
  * Writes resolve operator via timelineOperator and stamp payload.operator.
36
- * Edge-owned machines proxy create/update/delete to the owning plant API
57
+ * Edge-owned machines proxy list/create/update/delete to the owning plant API
37
58
  * (no local upsert or decision insert). Optional owners registry mirrors timeline.
38
59
  *
39
60
  * @param {string} basePath - base URL path
@@ -60,12 +81,16 @@ export default function operationRoute(basePath, plant, operatorOptions, decisio
60
81
  jsonResponse({ items: [] }).send(res);
61
82
  return;
62
83
  }
63
- const rows = await plant.operations.listForMachine(
64
- params.machineId,
65
- resolveKinds(query),
66
- parseRange(query)
67
- );
68
- jsonResponse({ items: rows.map(operationJson) }).send(res);
84
+ try {
85
+ const port = edgePort(owners, params.machineId);
86
+ const listed = port
87
+ ? await port.list(query)
88
+ : await listLocal(plant, params.machineId, query);
89
+ const items = Array.isArray(listed && listed.items) ? listed.items : [];
90
+ jsonResponse({ items }).send(res);
91
+ } catch (err) {
92
+ sendRouteError(res, err);
93
+ }
69
94
  }),
70
95
  route('POST', `${basePath}/machines/:machineId/operations`, async (req, res, params) => {
71
96
  await writes.writeCreate(params.machineId, req, res);
@@ -9,12 +9,16 @@ async function handleOperatorWrite(gate, parsed, write) {
9
9
  await write(audit);
10
10
  }
11
11
 
12
- async function rejectUnknownTags(timeline, parsed, machineId, res) {
12
+ async function rejectUnknownTags(timeline, parsed, machineId, res, decorate) {
13
13
  if (typeof timeline.rowAt !== 'function') {
14
14
  return false;
15
15
  }
16
16
  const row = await timeline.rowAt(new Date(parsed.start));
17
- if (!row || allowedSegmentTags(row.options, row.tags, parsed.tags)) {
17
+ if (!row) {
18
+ return false;
19
+ }
20
+ const [gated] = await decorate(machineId, [row]);
21
+ if (allowedSegmentTags(gated.options, gated.tags, parsed.tags)) {
18
22
  return false;
19
23
  }
20
24
  errorResponse('BAD_REQUEST', `Tag is not in segment options for ${machineId}`, 400).send(res);
@@ -41,12 +45,13 @@ async function respondToRequest(gate, timeline, requestId, req, res) {
41
45
  * @param {string} basePath - base URL path
42
46
  * @param {object} plant - plant domain object
43
47
  * @param {object} [operatorOptions] - provider, requireOperator, defaultUser
48
+ * @param {function} decorate - (machineId, rows) => rows, applied before JSON and PATCH gate
44
49
  * @returns {array} route objects
45
50
  *
46
51
  * @example
47
52
  * timelineRoute('/api/v1', plant, { provider, requireOperator: true, defaultUser: 'hmi-kiosk' });
48
53
  */
49
- export default function timelineRoute(basePath, plant, operatorOptions) {
54
+ export default function timelineRoute(basePath, plant, operatorOptions, decorate) {
50
55
  const gate = timelineOperator(operatorOptions);
51
56
  return [
52
57
  route('GET', `${basePath}/machines/:machineId/segments`, async (req, res, params, query) => {
@@ -62,7 +67,7 @@ export default function timelineRoute(basePath, plant, operatorOptions) {
62
67
  if (query.to) {
63
68
  options.to = query.to;
64
69
  }
65
- const rows = await result.machine.timeline.list(options);
70
+ const rows = await decorate(params.machineId, await result.machine.timeline.list(options));
66
71
  jsonResponse({ items: rows.map(segmentJson) }).send(res);
67
72
  }),
68
73
  route('PATCH', `${basePath}/machines/:machineId/segments`, async (req, res, params) => {
@@ -74,7 +79,7 @@ export default function timelineRoute(basePath, plant, operatorOptions) {
74
79
  try {
75
80
  const raw = await readBody(req);
76
81
  const parsed = JSON.parse(raw);
77
- if (await rejectUnknownTags(result.machine.timeline, parsed, params.machineId, res)) {
82
+ if (await rejectUnknownTags(result.machine.timeline, parsed, params.machineId, res, decorate)) {
78
83
  return;
79
84
  }
80
85
  await handleOperatorWrite(gate, parsed, async (audit) => {
@@ -94,7 +99,7 @@ export default function timelineRoute(basePath, plant, operatorOptions) {
94
99
  jsonResponse({ items: [] }).send(res);
95
100
  return;
96
101
  }
97
- const rows = await result.machine.timeline.pending();
102
+ const rows = await decorate(params.machineId, await result.machine.timeline.pending());
98
103
  const items = rows.map(({ id, name, start_time: startTime, end_time: endTime, duration, options }) => {
99
104
  return {
100
105
  id,
@@ -22,18 +22,53 @@ function segmentPayload(segment) {
22
22
  return data;
23
23
  }
24
24
 
25
+ async function emitSegment(sse, event, decorate, machineId) {
26
+ if (event.type === 'created' && event.segment) {
27
+ const [row] = await decorate(machineId, [event.segment]);
28
+ sse.emit('segment_created', segmentPayload(row));
29
+ return;
30
+ }
31
+ if (event.type === 'resolved' && event.segment) {
32
+ const [row] = await decorate(machineId, [event.segment]);
33
+ sse.emit('segment_resolved', segmentPayload(row));
34
+ }
35
+ }
36
+
37
+ async function emitRequest(sse, event, decorate, machineId) {
38
+ if (event.type === 'created' && event.request) {
39
+ const [row] = await decorate(machineId, [event.request]);
40
+ const start = row.start_time || row.startTime;
41
+ const end = row.end_time || row.endTime;
42
+ sse.emit('request_created', {
43
+ id: row.id,
44
+ segment: {
45
+ name: row.name,
46
+ start: start.toISOString(),
47
+ end: end.toISOString(),
48
+ duration: row.duration
49
+ },
50
+ options: row.options
51
+ });
52
+ return;
53
+ }
54
+ if (event.type === 'resolved' && event.request) {
55
+ sse.emit('request_resolved', { id: event.request.id });
56
+ }
57
+ }
58
+
25
59
  /**
26
60
  * Timeline SSE routes for segments and label requests.
27
61
  *
28
62
  * @param {string} basePath - base URL path
29
63
  * @param {object} plant - plant domain object
30
64
  * @param {function} clock - time provider
65
+ * @param {function} decorate - (machineId, rows) => rows
31
66
  * @returns {array} route objects
32
67
  *
33
68
  * @example
34
69
  * timelineStream('/api/v1', plant, clock);
35
70
  */
36
- export default function timelineStream(basePath, plant, clock) {
71
+ export default function timelineStream(basePath, plant, clock, decorate) {
37
72
  return [
38
73
  route('GET', `${basePath}/machines/:machineId/segments/stream`, (req, res, params) => {
39
74
  const sse = sseResponse(res, clock);
@@ -44,11 +79,7 @@ export default function timelineStream(basePath, plant, clock) {
44
79
  return;
45
80
  }
46
81
  const subscription = result.machine.timeline.stream((event) => {
47
- if (event.type === 'created' && event.segment) {
48
- sse.emit('segment_created', segmentPayload(event.segment));
49
- } else if (event.type === 'resolved' && event.segment) {
50
- sse.emit('segment_resolved', segmentPayload(event.segment));
51
- }
82
+ return emitSegment(sse, event, decorate, params.machineId);
52
83
  });
53
84
  const heartbeat = setInterval(() => {
54
85
  sse.heartbeat();
@@ -67,23 +98,7 @@ export default function timelineStream(basePath, plant, clock) {
67
98
  return;
68
99
  }
69
100
  const subscription = result.machine.timeline.stream((event) => {
70
- if (event.type === 'created' && event.request) {
71
- const reqItem = event.request;
72
- const start = reqItem.start_time || reqItem.startTime;
73
- const end = reqItem.end_time || reqItem.endTime;
74
- sse.emit('request_created', {
75
- id: reqItem.id,
76
- segment: {
77
- name: reqItem.name,
78
- start: start.toISOString(),
79
- end: end.toISOString(),
80
- duration: reqItem.duration
81
- },
82
- options: reqItem.options
83
- });
84
- } else if (event.type === 'resolved' && event.request) {
85
- sse.emit('request_resolved', { id: event.request.id });
86
- }
101
+ return emitRequest(sse, event, decorate, params.machineId);
87
102
  });
88
103
  const heartbeat = setInterval(() => {
89
104
  sse.heartbeat();
@@ -2,6 +2,18 @@ function trimBase(url) {
2
2
  return String(url).replace(/\/$/u, '');
3
3
  }
4
4
 
5
+ function listPath(root, query) {
6
+ const params = new URLSearchParams();
7
+ Object.keys(query || {}).forEach((name) => {
8
+ const value = query[name];
9
+ if (value !== undefined && value !== null && value !== '') {
10
+ params.set(name, String(value));
11
+ }
12
+ });
13
+ const suffix = params.toString();
14
+ return suffix.length > 0 ? `${root}?${suffix}` : root;
15
+ }
16
+
5
17
  function authHeaders(token) {
6
18
  const headers = { 'Content-Type': 'application/json' };
7
19
  if (token) {
@@ -33,65 +45,77 @@ async function readJson(res) {
33
45
  return JSON.parse(text);
34
46
  }
35
47
 
48
+ function ownerContext(site, machineId) {
49
+ return {
50
+ base: trimBase(site.baseUrl),
51
+ fetcher: site.fetch || fetch,
52
+ token: site.token,
53
+ machineId
54
+ };
55
+ }
56
+
57
+ async function send(ctx, method, path, body) {
58
+ const url = `${ctx.base}${path}`;
59
+ let res;
60
+ try {
61
+ res = await ctx.fetcher(url, {
62
+ method,
63
+ headers: authHeaders(ctx.token),
64
+ body: body === undefined ? undefined : JSON.stringify(body)
65
+ });
66
+ } catch (cause) {
67
+ throw ownerError(
68
+ `owner operations unreachable for ${ctx.machineId}: ${cause.message}`,
69
+ 'SERVICE_UNAVAILABLE',
70
+ 503,
71
+ cause
72
+ );
73
+ }
74
+ if (!res.ok) {
75
+ throw ownerError(
76
+ `owner operations ${method} ${path} for ${ctx.machineId} failed: ${res.status} ${await readError(res)}`,
77
+ 'BAD_GATEWAY',
78
+ 502
79
+ );
80
+ }
81
+ return readJson(res);
82
+ }
83
+
36
84
  /**
37
- * HTTP operations write port that proxies create/update/delete to an edge plant API.
85
+ * HTTP operations port that proxies list/create/update/delete to an edge plant API.
38
86
  *
39
87
  * Matches the owning-edge contract: central never upserts locally for edge machines.
40
88
  * Failures surface as route errors (503 unreachable, 502 non-ok).
41
89
  *
42
90
  * @param {object} site - edge owner with baseUrl and optional token/fetch
43
91
  * @param {string} machineId - machine identifier
44
- * @returns {object} operations write port
92
+ * @returns {object} operations port
45
93
  *
46
94
  * @example
47
95
  * const port = httpOperations({ baseUrl: 'http://edge/api/v1' }, 'm2');
48
96
  * await port.create({ kind: 'load', payload: {}, operatorId: 2 });
49
97
  */
50
98
  export default function httpOperations(site, machineId) {
51
- const base = trimBase(site.baseUrl);
52
- const fetcher = site.fetch || fetch;
53
- async function send(method, path, body) {
54
- const url = `${base}${path}`;
55
- let res;
56
- try {
57
- res = await fetcher(url, {
58
- method,
59
- headers: authHeaders(site.token),
60
- body: body === undefined ? undefined : JSON.stringify(body)
61
- });
62
- } catch (cause) {
63
- throw ownerError(
64
- `owner operations unreachable for ${machineId}: ${cause.message}`,
65
- 'SERVICE_UNAVAILABLE',
66
- 503,
67
- cause
68
- );
69
- }
70
- if (!res.ok) {
71
- throw ownerError(
72
- `owner operations ${method} ${path} for ${machineId} failed: ${res.status} ${await readError(res)}`,
73
- 'BAD_GATEWAY',
74
- 502
75
- );
76
- }
77
- return readJson(res);
78
- }
99
+ const ctx = ownerContext(site, machineId);
79
100
  const root = `/machines/${encodeURIComponent(machineId)}/operations`;
80
101
  return Object.freeze({
102
+ list(query) {
103
+ return send(ctx, 'GET', listPath(root, query));
104
+ },
81
105
  create(body) {
82
- return send('POST', root, body);
106
+ return send(ctx, 'POST', root, body);
83
107
  },
84
108
  createMany(body) {
85
- return send('POST', `${root}/batch`, body);
109
+ return send(ctx, 'POST', `${root}/batch`, body);
86
110
  },
87
111
  update(key, body) {
88
- return send('PUT', `${root}/${encodeURIComponent(key)}`, body);
112
+ return send(ctx, 'PUT', `${root}/${encodeURIComponent(key)}`, body);
89
113
  },
90
114
  remove(key, body) {
91
- return send('DELETE', `${root}/${encodeURIComponent(key)}`, body);
115
+ return send(ctx, 'DELETE', `${root}/${encodeURIComponent(key)}`, body);
92
116
  },
93
117
  decisions(key) {
94
- return send('GET', `${root}/${encodeURIComponent(key)}/decisions`).then((body) => {
118
+ return send(ctx, 'GET', `${root}/${encodeURIComponent(key)}/decisions`).then((body) => {
95
119
  return Array.isArray(body && body.items) ? body.items : [];
96
120
  });
97
121
  }