@yarkivaev/scada 2.18.0 → 2.19.0

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.
Files changed (86) hide show
  1. package/index.js +13 -0
  2. package/package.json +4 -2
  3. package/src/application/cycleTimelineFetch.js +56 -0
  4. package/src/application/deploy/edgeDescriptors.js +31 -0
  5. package/src/application/deploy/fieldbusSourcePlan.js +79 -0
  6. package/src/application/deploy/plantBindingProfile.js +24 -0
  7. package/src/application/deploy/topologyGraph.js +81 -0
  8. package/src/application/edgeOperatorCatalog.js +9 -7
  9. package/src/application/mcp/analyticsMcpPort.js +20 -0
  10. package/src/application/mcp/analyticsNamespaceNodes.js +29 -0
  11. package/src/application/mcp/analyticsTextContent.js +13 -0
  12. package/src/application/mcp/plantReadPorts.js +168 -0
  13. package/src/application/mcp/textContentCatalog.js +7 -0
  14. package/src/application/operationPrefixes.js +67 -0
  15. package/src/application/operatorCatalogView.js +8 -0
  16. package/src/application/projectPlantShops.js +17 -0
  17. package/src/application/runtime/collectorDslManifest.js +44 -0
  18. package/src/application/runtime/collectorLaunch.js +34 -0
  19. package/src/application/runtime/collectorOptions.js +21 -0
  20. package/src/application/runtime/controlDeliveryEnvironment.js +19 -0
  21. package/src/application/runtime/embeddedCollectors.js +6 -0
  22. package/src/application/runtime/index.js +7 -1
  23. package/src/application/runtime/pagedDelivery.js +87 -0
  24. package/src/application/runtime/resolveSecrets.js +9 -0
  25. package/src/application/siteOperatorCatalog.js +8 -7
  26. package/src/application/siteRuntime/checkpointedOperationPoll.js +77 -0
  27. package/src/application/siteRuntime/cutoverOperations.js +25 -0
  28. package/src/application/siteRuntime/databaseMigrations.js +27 -0
  29. package/src/application/siteRuntime/edgeMetricsStore.js +35 -0
  30. package/src/application/siteRuntime/history.js +29 -0
  31. package/src/application/siteRuntime/index.js +16 -0
  32. package/src/application/siteRuntime/measurementTopic.js +9 -0
  33. package/src/application/siteRuntime/operationFederation.js +15 -0
  34. package/src/application/siteRuntime/operationSnapshot.js +18 -0
  35. package/src/application/siteRuntime/operatorField.js +49 -0
  36. package/src/application/siteRuntime/operatorUpdates.js +37 -0
  37. package/src/application/siteRuntime/telemetry.js +31 -0
  38. package/src/application/siteRuntime/telemetryBackfillCommand.js +64 -0
  39. package/src/application/timelineMetrics.js +36 -0
  40. package/src/domain/timeline/cyclePhases.js +191 -0
  41. package/src/infrastructure/deploy/brokerFleetPolicy.js +91 -0
  42. package/src/infrastructure/deploy/configuredArchivePlan.js +25 -0
  43. package/src/infrastructure/deploy/configuredBrokerRoutes.js +34 -0
  44. package/src/infrastructure/deploy/configuredClassification.js +74 -0
  45. package/src/infrastructure/deploy/configuredControlPlane.js +116 -0
  46. package/src/infrastructure/deploy/configuredDeploymentCredentials.js +45 -0
  47. package/src/infrastructure/deploy/configuredEtcdInventory.js +30 -0
  48. package/src/infrastructure/deploy/configuredRuntimeCapabilities.js +14 -0
  49. package/src/infrastructure/deploy/configuredSiteAssets.js +50 -0
  50. package/src/infrastructure/deploy/configuredStagedDeployment.js +48 -0
  51. package/src/infrastructure/deploy/highAvailability/configuredBrokerReconciliation.js +21 -0
  52. package/src/infrastructure/deploy/highAvailability/index.js +1 -0
  53. package/src/infrastructure/deploy/index.js +19 -0
  54. package/src/infrastructure/deploy/mixedStoreHistory.js +27 -0
  55. package/src/infrastructure/deploy/publicBrokerPlan.js +15 -0
  56. package/src/infrastructure/deploy/siteBrokerDefinitions.js +97 -0
  57. package/src/infrastructure/deploy/stagedSitePlan.js +132 -0
  58. package/src/infrastructure/deploy/supervisedServicePlan.js +82 -0
  59. package/src/infrastructure/http/edge/attachClassify.js +30 -0
  60. package/src/infrastructure/http/edge/classifyProxy.js +72 -0
  61. package/src/infrastructure/http/edge/classifyRecord.js +32 -0
  62. package/src/infrastructure/http/edge/classifyRouting.js +14 -0
  63. package/src/infrastructure/http/edge/siteAccess.js +7 -0
  64. package/src/infrastructure/http/edge/writeGuard.js +84 -0
  65. package/src/infrastructure/http/plant/routes/machineOperationList.js +18 -0
  66. package/src/infrastructure/http/plant/routes/operationRoute.js +2 -11
  67. package/src/infrastructure/http/plant/routes/operatorRoute.js +25 -0
  68. package/src/infrastructure/http/plant/streams/operationStream.js +25 -37
  69. package/src/infrastructure/ingest/mqtt/modbusDeviceSpec.js +5 -28
  70. package/src/infrastructure/ingest/mqtt/registerPoint.js +2 -2
  71. package/src/infrastructure/mdmesh/adminReconciliation.js +19 -0
  72. package/src/infrastructure/mdmesh/bootstrapMdmeshCredentials.js +4 -4
  73. package/src/infrastructure/mdmesh/controllerOperation.js +17 -0
  74. package/src/infrastructure/mdmesh/index.js +3 -0
  75. package/src/infrastructure/mdmesh/publishApk.js +30 -0
  76. package/src/infrastructure/persistence/clickhouse/metricBursts.js +73 -0
  77. package/src/infrastructure/persistence/pg/cyclePhaseQuery.js +168 -0
  78. package/src/infrastructure/persistence/pg/cyclePrior.js +96 -0
  79. package/src/infrastructure/persistence/pg/operatorFieldStore.js +50 -0
  80. package/src/infrastructure/streams/boundedTextFrames.js +27 -0
  81. package/src/infrastructure/streams/framedSerialSource.js +25 -0
  82. package/src/infrastructure/streams/index.js +5 -0
  83. package/src/infrastructure/streams/namedSerialDevices.js +26 -0
  84. package/src/infrastructure/streams/serialLine.js +26 -0
  85. package/src/infrastructure/streams/watchCurrentReading.js +31 -0
  86. package/src/infrastructure/streams/windowPublication.js +73 -0
@@ -0,0 +1,73 @@
1
+ /* eslint camelcase: off */
2
+ import { rawMetricsRange } from './metricsRelation.js';
3
+
4
+ function formatDateTime(value) {
5
+ return value.toISOString().replace('Z', '').replace('T', ' ');
6
+ }
7
+
8
+ /** Find peak samples in topic bursts using only retained raw observations. */
9
+ export const metricBurstSql = `
10
+ SELECT
11
+ topic,
12
+ peak,
13
+ occurred_at
14
+ FROM (
15
+ SELECT
16
+ topic,
17
+ max(value) AS peak,
18
+ argMax(ts, value) AS occurred_at,
19
+ max(ts) AS ended_at,
20
+ count() AS points
21
+ FROM (
22
+ SELECT
23
+ topic,
24
+ ts,
25
+ value,
26
+ sum(is_start) OVER (
27
+ PARTITION BY topic
28
+ ORDER BY ts
29
+ ROWS UNBOUNDED PRECEDING
30
+ ) AS burst_id
31
+ FROM (
32
+ SELECT
33
+ topic,
34
+ ts,
35
+ value,
36
+ if(
37
+ dateDiff(
38
+ 'second',
39
+ lagInFrame(ts) OVER (
40
+ PARTITION BY topic
41
+ ORDER BY ts
42
+ ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING
43
+ ),
44
+ ts
45
+ ) > {gapSeconds:UInt32},
46
+ toUInt8(1),
47
+ toUInt8(0)
48
+ ) AS is_start
49
+ FROM ${rawMetricsRange('toUnixTimestamp64Milli({rangeFrom:DateTime64(3)})', 'toUnixTimestamp64Milli({rangeTo:DateTime64(3)})')}
50
+ WHERE topic IN {topics:Array(String)}
51
+ AND ts >= {rangeFrom:DateTime64(3)}
52
+ AND ts <= {rangeTo:DateTime64(3)}
53
+ )
54
+ )
55
+ GROUP BY topic, burst_id
56
+ )
57
+ WHERE points >= {minPoints:UInt32}
58
+ AND peak >= {minPeak:Float64}
59
+ AND dateDiff('second', ended_at, now64(3)) > {gapSeconds:UInt32}
60
+ ORDER BY topic, occurred_at
61
+ `;
62
+
63
+ /** Bounded peak queries across topics. The quiet window excludes incomplete bursts. */
64
+ export default function metricBursts(connection, { gapSeconds, minPoints, minPeak }) {
65
+ if (typeof connection?.query !== 'function') { throw new TypeError('ClickHouse connection with query() is required for metric bursts'); }
66
+ return {
67
+ list(topics, { from, to }) {
68
+ return connection.query(metricBurstSql, {
69
+ topics, rangeFrom: formatDateTime(from), rangeTo: formatDateTime(to), gapSeconds, minPoints, minPeak
70
+ });
71
+ }
72
+ };
73
+ }
@@ -0,0 +1,168 @@
1
+ /**
2
+ * Asks Postgres for the cycle phase at each off-segment start.
3
+ * The (machine, kind, start_time) index walks backward to the nearest
4
+ * cycle anchor and returns one phase id per instant, not the history.
5
+ *
6
+ * @param {object} pool - pg pool
7
+ * @param {string} machineId - machine id
8
+ * @param {Array<object>} rows - window rows, including ones not stored yet
9
+ * @param {object} anchors - start id and stop ids
10
+ * @param {Array<string>} enters - phase enter ids
11
+ * @returns {Promise<Map<number, string>>} start epoch ms to phase id
12
+ *
13
+ * @example
14
+ * const phases = await cyclePhaseQuery(pool, 'meter-a', rows, anchors, enters);
15
+ */
16
+ const phaseSql = `WITH incoming AS (
17
+ SELECT u.start_time, u.tags
18
+ FROM unnest($2::timestamptz[], $3::text[]) AS u(start_time, tags)
19
+ ), ask AS (
20
+ SELECT DISTINCT asked.moment
21
+ FROM unnest($4::timestamptz[]) AS asked(moment)
22
+ ), bounds AS (
23
+ SELECT min(moment) AS oldest, max(moment) AS newest FROM ask
24
+ ), stored_anchor AS (
25
+ SELECT hit.start_time, hit.tags
26
+ FROM bounds
27
+ LEFT JOIN LATERAL (
28
+ SELECT s.start_time, s.tags
29
+ FROM segments s
30
+ WHERE s.machine = $1 AND s.kind = 'phase' AND s.start_time < bounds.oldest
31
+ AND EXISTS (
32
+ SELECT 1 FROM unnest($9::text[]) AS needle
33
+ WHERE position(needle in s.tags) > 0
34
+ )
35
+ ORDER BY s.start_time DESC
36
+ LIMIT 1
37
+ ) hit ON true
38
+ ), memory_anchor AS (
39
+ SELECT i.start_time, i.tags
40
+ FROM incoming i
41
+ CROSS JOIN bounds
42
+ WHERE i.start_time < bounds.oldest
43
+ AND EXISTS (
44
+ SELECT 1 FROM unnest($9::text[]) AS needle
45
+ WHERE position(needle in i.tags) > 0
46
+ )
47
+ ORDER BY i.start_time DESC
48
+ LIMIT 1
49
+ ), anchor AS (
50
+ SELECT picked.start_time, picked.tags
51
+ FROM (
52
+ SELECT start_time, tags FROM stored_anchor WHERE start_time IS NOT NULL
53
+ UNION ALL
54
+ SELECT start_time, tags FROM memory_anchor
55
+ ) AS picked
56
+ ORDER BY picked.start_time DESC
57
+ LIMIT 1
58
+ ), events AS (
59
+ SELECT start_time, tags FROM anchor
60
+ UNION ALL
61
+ SELECT s.start_time, s.tags
62
+ FROM segments s
63
+ WHERE s.machine = $1 AND s.kind = 'phase'
64
+ AND s.start_time < (SELECT newest FROM bounds)
65
+ AND s.start_time >= COALESCE((SELECT start_time FROM anchor), (SELECT oldest FROM bounds))
66
+ AND ((SELECT start_time FROM anchor) IS NULL OR s.start_time > (SELECT start_time FROM anchor))
67
+ AND NOT EXISTS (
68
+ SELECT 1 FROM incoming i WHERE i.start_time = s.start_time
69
+ )
70
+ AND EXISTS (
71
+ SELECT 1 FROM unnest($8::text[]) AS needle
72
+ WHERE position(needle in s.tags) > 0
73
+ )
74
+ UNION ALL
75
+ SELECT i.start_time, i.tags
76
+ FROM incoming i
77
+ WHERE i.start_time < (SELECT newest FROM bounds)
78
+ AND i.start_time >= COALESCE((SELECT start_time FROM anchor), (SELECT oldest FROM bounds))
79
+ AND ((SELECT start_time FROM anchor) IS NULL OR i.start_time > (SELECT start_time FROM anchor))
80
+ AND EXISTS (
81
+ SELECT 1 FROM unnest($8::text[]) AS needle
82
+ WHERE position(needle in i.tags) > 0
83
+ )
84
+ ), expanded AS (
85
+ SELECT e.start_time, t.ord, t.elem
86
+ FROM events e
87
+ CROSS JOIN LATERAL jsonb_array_elements_text(
88
+ CASE
89
+ WHEN e.tags IS NOT NULL AND left(btrim(e.tags), 1) = '[' THEN e.tags::jsonb
90
+ ELSE '[]'::jsonb
91
+ END
92
+ ) WITH ORDINALITY AS t(elem, ord)
93
+ WHERE t.elem = $5 OR t.elem = ANY($6::text[]) OR t.elem = ANY($7::text[])
94
+ )
95
+ SELECT ask.moment,
96
+ CASE
97
+ WHEN anchor_hit.elem IS NULL OR anchor_hit.elem <> $5 THEN 'idle'
98
+ WHEN enter_hit.elem IS NULL THEN $5
99
+ ELSE enter_hit.elem
100
+ END AS phase
101
+ FROM ask
102
+ LEFT JOIN LATERAL (
103
+ SELECT e.elem, e.start_time, e.ord
104
+ FROM expanded e
105
+ WHERE e.start_time < ask.moment
106
+ AND (e.elem = $5 OR e.elem = ANY($6::text[]))
107
+ ORDER BY e.start_time DESC, e.ord DESC
108
+ LIMIT 1
109
+ ) anchor_hit ON true
110
+ LEFT JOIN LATERAL (
111
+ SELECT e.elem
112
+ FROM expanded e
113
+ WHERE anchor_hit.elem = $5
114
+ AND e.start_time < ask.moment
115
+ AND (e.start_time > anchor_hit.start_time OR (e.start_time = anchor_hit.start_time AND e.ord > anchor_hit.ord))
116
+ AND e.elem = ANY($7::text[])
117
+ ORDER BY e.start_time DESC, e.ord DESC
118
+ LIMIT 1
119
+ ) enter_hit ON true`;
120
+
121
+ function momentOf(row) {
122
+ const raw = row.start || row.start_time || row.startTime;
123
+ return raw instanceof Date ? raw : new Date(raw);
124
+ }
125
+
126
+ function tagText(tags) {
127
+ if (Array.isArray(tags)) {
128
+ return JSON.stringify(tags);
129
+ }
130
+ if (typeof tags === 'string' && tags.startsWith('[')) {
131
+ return tags;
132
+ }
133
+ return '[]';
134
+ }
135
+
136
+ function quoted(ids) {
137
+ return ids.map((id) => {
138
+ return `"${id}"`;
139
+ });
140
+ }
141
+
142
+ export default async function cyclePhaseQuery(pool, machineId, rows, anchors, enters) {
143
+ const offs = rows.filter((row) => {
144
+ return row.name === 'off';
145
+ });
146
+ if (offs.length === 0) {
147
+ return new Map();
148
+ }
149
+ const anchorIds = [anchors.start, ...anchors.stops];
150
+ const result = await pool.query(phaseSql, [
151
+ machineId,
152
+ rows.map(momentOf),
153
+ rows.map((row) => {
154
+ return tagText(row.tags);
155
+ }),
156
+ offs.map(momentOf),
157
+ anchors.start,
158
+ anchors.stops,
159
+ enters,
160
+ quoted([...anchorIds, ...enters]),
161
+ quoted(anchorIds)
162
+ ]);
163
+ const found = new Map();
164
+ result.rows.forEach((row) => {
165
+ found.set(new Date(row.moment).getTime(), row.phase);
166
+ });
167
+ return found;
168
+ }
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Reads tag ids from a persisted segment row.
3
+ *
4
+ * @param {object} row - row with tags array or JSON string
5
+ * @returns {Array<string>} tag ids
6
+ */
7
+ function tagList(row) {
8
+ const raw = row.tags;
9
+ if (Array.isArray(raw)) {
10
+ return raw;
11
+ }
12
+ if (typeof raw === 'string' && raw.length > 0) {
13
+ return JSON.parse(raw);
14
+ }
15
+ return [];
16
+ }
17
+
18
+ /**
19
+ * Whether a row carries a cycle start or stop anchor.
20
+ *
21
+ * @param {object} row - persisted segment
22
+ * @param {object} anchors - start and stops
23
+ * @returns {boolean} true when the row resets the cycle
24
+ */
25
+ function resets(row, anchors) {
26
+ return tagList(row).some((id) => {
27
+ return id === anchors.start || anchors.stops.includes(id);
28
+ });
29
+ }
30
+
31
+ /**
32
+ * Copies rows until a cycle reset, inclusive.
33
+ *
34
+ * @param {Array<object>} rows - newest-first page
35
+ * @param {object} anchors - start and stops
36
+ * @param {Array<object>} collected - accumulator
37
+ * @returns {boolean} true when a reset was included
38
+ */
39
+ function take(rows, anchors, collected) {
40
+ for (let i = 0; i < rows.length; i += 1) {
41
+ collected.push(rows[i]);
42
+ if (resets(rows[i], anchors)) {
43
+ return true;
44
+ }
45
+ }
46
+ return false;
47
+ }
48
+
49
+ /**
50
+ * Reads one index page and continues while the reset is still older.
51
+ *
52
+ * @param {object} pool - pg pool
53
+ * @param {string} machineId - machine id
54
+ * @param {Date} bound - exclusive start bound
55
+ * @param {object} anchors - start and stops
56
+ * @param {Array<object>} collected - newest-first accumulator
57
+ * @returns {Promise<Array<object>>} newest-first rows through the reset
58
+ */
59
+ async function page(pool, machineId, bound, anchors, collected) {
60
+ const size = 200;
61
+ const result = await pool.query(
62
+ `SELECT name, start_time, tags
63
+ FROM segments
64
+ WHERE machine = $1 AND kind = 'phase' AND start_time < $2
65
+ ORDER BY start_time DESC
66
+ LIMIT $3`,
67
+ [machineId, bound, size]
68
+ );
69
+ const found = take(result.rows, anchors, collected);
70
+ const oldest = result.rows[result.rows.length - 1];
71
+ const next = oldest ? new Date(oldest.start_time) : bound;
72
+ if (found || result.rows.length < size || next.getTime() >= bound.getTime()) {
73
+ return collected;
74
+ }
75
+ return page(pool, machineId, next, anchors, collected);
76
+ }
77
+
78
+ /**
79
+ * Loads earlier off-segment tags until the last cycle start or stop.
80
+ * Pages through the (machine, kind, start_time) index so a long history
81
+ * does not enter the site process in one result.
82
+ *
83
+ * @param {object} pool - pg pool
84
+ * @param {string} machineId - machine id
85
+ * @param {Date|number|string} before - exclusive start bound
86
+ * @param {object} anchors - start and stops
87
+ * @returns {Promise<Array<object>>} chronological prior rows
88
+ *
89
+ * @example
90
+ * await cyclePrior(pool, 'meter-a', start, anchors)
91
+ */
92
+ export default async function cyclePrior(pool, machineId, before, anchors) {
93
+ const collected = [];
94
+ await page(pool, machineId, new Date(before), anchors, collected);
95
+ return collected.reverse();
96
+ }
@@ -0,0 +1,50 @@
1
+ function identifier(name) {
2
+ if (typeof name !== 'string' || !/^[a-z_][a-z0-9_]*$/u.test(name)) {
3
+ throw new TypeError('Invalid PostgreSQL identifier');
4
+ }
5
+ return name;
6
+ }
7
+
8
+ function relation(schema, table) {
9
+ return `${identifier(schema)}.${identifier(table)}`;
10
+ }
11
+
12
+ /** Store one installation-specific field without extending shared operator identities. */
13
+ export default function operatorFieldStore(pool, { schema, table, key = 'operator_id', field }) {
14
+ const name = relation(schema, table);
15
+ const id = identifier(key);
16
+ const column = identifier(field);
17
+ async function put(operator, value) {
18
+ await pool.query(`INSERT INTO ${name} (${id}, ${column}) VALUES ($1, $2)
19
+ ON CONFLICT (${id}) DO UPDATE SET ${column} = EXCLUDED.${column}`, [operator, value]);
20
+ }
21
+ return Object.freeze({
22
+ put,
23
+ update: put,
24
+ async remove(operator) { await pool.query(`DELETE FROM ${name} WHERE ${id} = $1`, [operator]); },
25
+ async getMap(ids) {
26
+ if (!ids.length) { return new Map(); }
27
+ const result = await pool.query(`SELECT ${id}, ${column} FROM ${name} WHERE ${id} = ANY($1::bigint[])`, [ids]);
28
+ return new Map(result.rows.map((row) => { return [Number(row[id]), row[column]]; }));
29
+ }
30
+ });
31
+ }
32
+
33
+ function normalized(value) { return value.replace(/\s+/gu, ''); }
34
+
35
+ /** Verify declaration shape and runtime SELECT access without reading business records. */
36
+ export async function verifyPostgresRelation(pool, { schema, table, columns, constraints }) {
37
+ const name = relation(schema, table);
38
+ const actualColumns = await pool.query(`SELECT attname, atttypid::regtype::text AS type, attnotnull
39
+ FROM pg_attribute WHERE attrelid = '${name}'::regclass AND attnum > 0 AND NOT attisdropped ORDER BY attnum`);
40
+ if (JSON.stringify(actualColumns.rows) !== JSON.stringify(columns)) { throw new Error(`Incompatible ${table} columns`); }
41
+ const actualConstraints = await pool.query(`SELECT pg_get_constraintdef(oid) AS definition, convalidated
42
+ FROM pg_constraint WHERE conrelid = '${name}'::regclass`);
43
+ const definitions = new Set(actualConstraints.rows.filter(({ convalidated: validated }) => { return validated; })
44
+ .map(({ definition }) => { return normalized(definition); }));
45
+ if (actualConstraints.rows.length !== constraints.length ||
46
+ constraints.some((definition) => { return !definitions.has(normalized(definition)); })) {
47
+ throw new Error(`Incompatible ${table} constraints`);
48
+ }
49
+ await pool.query(`SELECT ${columns.map(({ attname }) => { return identifier(attname); }).join(', ')} FROM ${name} LIMIT 0`);
50
+ }
@@ -0,0 +1,27 @@
1
+ function validate(accumulated, { start, end, maxBytes, label }) {
2
+ if (typeof accumulated !== 'string') { throw new Error(`${label} accumulator must be a string`); }
3
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || accumulated.length > maxBytes) {
4
+ throw new Error(`${label} frame capacity exceeded`);
5
+ }
6
+ if (typeof start !== 'string' || !start || typeof end !== 'string' || !end) { throw new TypeError('Frame delimiters are required'); }
7
+ }
8
+
9
+ /** Separate delimited frames while preserving incomplete bytes for the next read. */
10
+ export default function boundedTextFrames(accumulated, { start, end, maxBytes = 4096, accept, label = 'Serial' }) {
11
+ validate(accumulated, { start, end, maxBytes, label });
12
+ const messages = [];
13
+ let position = 0;
14
+ let open = accumulated.indexOf(start, position);
15
+ while (open >= 0) {
16
+ const close = accumulated.indexOf(end, open + start.length);
17
+ if (close < 0) { break; }
18
+ const frame = accumulated.slice(open, close);
19
+ if (!accept || accept(frame)) { messages.push(frame); }
20
+ position = close + end.length;
21
+ open = accumulated.indexOf(start, position);
22
+ }
23
+ return {
24
+ messages() { return messages; },
25
+ remainder() { return accumulated.slice(position); }
26
+ };
27
+ }
@@ -0,0 +1,25 @@
1
+ import { intervalSource } from '@yarkivaev/source-to-sink';
2
+ import serialSource from './serialSource.js';
3
+
4
+ /** Assemble framed serial input and periodic flushing using a caller-supplied decoder. */
5
+ export default function framedSerialSource(devices, { extract, accept, flush }, { openPort, intervalMs, onError, deviceKey = ({ path }) => { return path; } }) {
6
+ const buffers = new Map();
7
+ const serial = serialSource(devices, {
8
+ accept({ device, chunk }) {
9
+ const key = deviceKey(device);
10
+ const accumulated = (buffers.get(key) ?? '') + chunk.toString('ascii');
11
+ buffers.delete(key);
12
+ const extraction = extract(accumulated);
13
+ buffers.set(key, extraction.remainder());
14
+ return extraction.messages().reduce(async (previous, frame) => {
15
+ await previous;
16
+ await accept(device, frame);
17
+ }, Promise.resolve());
18
+ }
19
+ }, { openPort, onError });
20
+ const periodic = intervalSource(intervalMs, { accept() { return flush(); } }, { onError });
21
+ return {
22
+ async start() { await serial.start(); await periodic.start(); },
23
+ async stop() { try { await serial.stop(); } finally { await periodic.stop(); } }
24
+ };
25
+ }
@@ -13,3 +13,8 @@ export { default as amqpSink } from './amqpSink.js';
13
13
  export { default as amqpSource } from './amqpSource.js';
14
14
  export { default as amqpSession } from './amqpSource/session.js';
15
15
  export { default as serialSource } from './serialSource.js';
16
+ export { default as framedSerialSource } from './framedSerialSource.js';
17
+ export { default as namedSerialDevices } from './namedSerialDevices.js';
18
+ export { default as boundedTextFrames } from './boundedTextFrames.js';
19
+ export { default as windowPublication } from './windowPublication.js';
20
+ export { default as watchCurrentReading } from './watchCurrentReading.js';
@@ -0,0 +1,26 @@
1
+ import serialLine from './serialLine.js';
2
+
3
+ const lineFormat = /^[0-9][NOE][0-9]$/u;
4
+
5
+ function parse(spec, label) {
6
+ const parts = spec.split(':');
7
+ if (parts.length < 4) {
8
+ throw new Error(`${label} device spec must be machine:path:baud:line, got ${spec}`);
9
+ }
10
+ const [name] = parts;
11
+ const line = parts.at(-1);
12
+ const baudRate = Number(parts.at(-2));
13
+ const path = parts.slice(1, -2).join(':');
14
+ if (!name || !path || !Number.isFinite(baudRate) || baudRate <= 0 || !lineFormat.test(line)) {
15
+ throw new Error(`${label} device spec is invalid: ${spec}`);
16
+ }
17
+ return { name, path, baudRate, ...serialLine(line) };
18
+ }
19
+
20
+ /** Parse comma-separated named serial devices with optional colons in their paths. */
21
+ export default function namedSerialDevices(raw, { variable, label }) {
22
+ if (typeof raw !== 'string' || raw.trim().length === 0) {
23
+ throw new Error(`${variable} must be a non-empty string`);
24
+ }
25
+ return raw.split(',').map((item) => { return parse(item.trim(), label); });
26
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Parses serial line format such as 8N1 into serial options.
3
+ *
4
+ * @param {string} line - Data bits, parity letter, stop bits (e.g. 8N1)
5
+ * @returns {object} dataBits, parity, stopBits
6
+ */
7
+ export default function serialLine(line) {
8
+ if (typeof line !== 'string' || line.length !== 3) {
9
+ throw new Error(`Serial line format must be three characters such as 8N1, got: ${line}`);
10
+ }
11
+ const dataBits = parseInt(line.charAt(0), 10);
12
+ const parityLetter = line.charAt(1).toUpperCase();
13
+ const stopBits = parseInt(line.charAt(2), 10);
14
+ let parity = '';
15
+ if (parityLetter === 'N') {
16
+ parity = 'none';
17
+ } else if (parityLetter === 'E') {
18
+ parity = 'even';
19
+ } else if (parityLetter === 'O') {
20
+ parity = 'odd';
21
+ }
22
+ if (parity.length === 0 || Number.isNaN(dataBits) || Number.isNaN(stopBits)) {
23
+ throw new Error(`Serial line format must be such as 8N1, got: ${line}`);
24
+ }
25
+ return { dataBits, parity, stopBits };
26
+ }
@@ -0,0 +1,31 @@
1
+ import { intervalSource } from '@yarkivaev/source-to-sink';
2
+
3
+ /** Poll the current reading for value changes and refresh on optional invalidation events. */
4
+ export default function watchCurrentReading({ read, intervalMs, onReading, subscribe }) {
5
+ let active = true;
6
+ let lastValue;
7
+ async function emit(force) {
8
+ try {
9
+ const { timestamp, value, unit } = await read();
10
+ if (!active || (!force && lastValue === value)) { return; }
11
+ lastValue = value;
12
+ await onReading({ timestamp, value, unit });
13
+ } catch {
14
+ // A read failure leaves the watch available for the next refresh.
15
+ }
16
+ }
17
+
18
+ const poll = intervalSource(intervalMs, { accept() { return emit(false); } });
19
+ const subscription = subscribe?.(() => {
20
+ if (active) { void emit(true); }
21
+ });
22
+ void poll.start();
23
+ return {
24
+ cancel() {
25
+ if (!active) { return; }
26
+ active = false;
27
+ void poll.stop().catch(() => { return undefined; });
28
+ subscription?.cancel();
29
+ }
30
+ };
31
+ }
@@ -0,0 +1,73 @@
1
+ async function flush(windows, pending, poster, clock, options) {
2
+ // Drain older operations before sealing more samples; failed delivery applies backpressure.
3
+ async function drain() {
4
+ await [...pending.values()].reduce(async (previous, item) => {
5
+ await previous;
6
+ await poster(item);
7
+ pending.delete(item.key);
8
+ await options.persist?.();
9
+ }, Promise.resolve());
10
+ }
11
+ await drain();
12
+ const backup = Object.fromEntries(Object.entries(windows).map(([key, window]) => { return [key, window.snapshot?.()]; }));
13
+ const items = Object.values(windows).flatMap((window) => { return window.seal(clock()); });
14
+ if (items.length > options.maxPending) {
15
+ Object.entries(windows).forEach(([key, window]) => { window.restore?.(backup[key]); });
16
+ throw new Error(`${options.label} pending capacity exceeded`);
17
+ }
18
+ items.forEach((item) => { pending.set(item.key, item); });
19
+ await options.persist?.();
20
+ await drain();
21
+ }
22
+
23
+
24
+ function validate(windows, poster, clock, { parse, name, label, maxPending }) {
25
+ if (!windows || typeof windows !== 'object') { throw new Error(`${name} requires a windows map`); }
26
+ if (typeof poster !== 'function') { throw new Error(`${name} requires a poster function`); }
27
+ if (typeof clock !== 'function') { throw new Error(`${name} requires a clock function`); }
28
+ if (typeof parse !== 'function') { throw new TypeError(`${name} requires a frame parser`); }
29
+ if (!Number.isSafeInteger(maxPending) || maxPending < 1) { throw new TypeError(`Invalid ${label} pending capacity`); }
30
+ }
31
+
32
+ /** Feed decoded observations into per-source windows and publish their sealed events in order. */
33
+ export default function windowPublication(windows, poster, clock, {
34
+ parse, persist, restorePending = structuredClone, maxPending = 1000, label = 'Window publisher', name = 'windowPublication',
35
+ missingWindow = (source) => { return `no window for source ${source}`; }
36
+ }) {
37
+ validate(windows, poster, clock, { parse, name, label, maxPending });
38
+ const pending = new Map();
39
+ const lifecycle = { flushing: false };
40
+ return {
41
+ accept(machine, frame) {
42
+ const window = windows[machine];
43
+ if (!window) {
44
+ throw new Error(missingWindow(machine));
45
+ }
46
+ const value = parse(frame);
47
+ if (value === undefined) {
48
+ return;
49
+ }
50
+ window.accept({ ts: clock(), value });
51
+ },
52
+ snapshot() {
53
+ return { version: 1, windows: Object.fromEntries(Object.entries(windows).map(([machine, window]) => {
54
+ return [machine, window.snapshot()];
55
+ })), pending: structuredClone([...pending.values()]) };
56
+ },
57
+ restore(saved) {
58
+ if (saved?.version !== 1 || !Array.isArray(saved.pending) || saved.pending.length > maxPending
59
+ || Object.keys(saved.windows ?? {}).sort().join() !== Object.keys(windows).sort().join()) {
60
+ throw new Error(`${label} watch state incompatible or capacity exceeded`);
61
+ }
62
+ Object.entries(windows).forEach(([machine, window]) => { window.restore(saved.windows[machine]); });
63
+ pending.clear();
64
+ saved.pending.forEach((item) => { pending.set(item.key, restorePending(item)); });
65
+ },
66
+ async flush() {
67
+ if (lifecycle.flushing) { throw new Error(`${label} flush already running`); }
68
+ lifecycle.flushing = true;
69
+ try { await flush(windows, pending, poster, clock, { persist, maxPending, label }); }
70
+ finally { Object.assign(lifecycle, { flushing: false }); }
71
+ }
72
+ };
73
+ }