@yarkivaev/scada 2.18.0 → 2.20.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.
- package/index.js +17 -0
- package/package.json +4 -2
- package/src/application/cycleTimelineFetch.js +56 -0
- package/src/application/deploy/collectorProcesses.js +1 -0
- package/src/application/deploy/collectorSourcePlan.js +41 -0
- package/src/application/deploy/compileCollectorTasks.js +2 -2
- package/src/application/deploy/edgeDescriptors.js +31 -0
- package/src/application/deploy/fieldbusSourcePlan.js +93 -0
- package/src/application/deploy/plantBindingProfile.js +24 -0
- package/src/application/deploy/topologyGraph.js +81 -0
- package/src/application/edgeOperatorCatalog.js +9 -7
- package/src/application/mcp/analyticsMcpPort.js +20 -0
- package/src/application/mcp/analyticsNamespaceNodes.js +29 -0
- package/src/application/mcp/analyticsTextContent.js +13 -0
- package/src/application/mcp/plantReadPorts.js +168 -0
- package/src/application/mcp/textContentCatalog.js +7 -0
- package/src/application/operationPrefixes.js +67 -0
- package/src/application/operatorCatalogView.js +8 -0
- package/src/application/projectPlantShops.js +17 -0
- package/src/application/runtime/collectorDslManifest.js +44 -0
- package/src/application/runtime/collectorLaunch.js +34 -0
- package/src/application/runtime/collectorOptions.js +21 -0
- package/src/application/runtime/controlDeliveryEnvironment.js +19 -0
- package/src/application/runtime/embeddedCollectors.js +6 -0
- package/src/application/runtime/index.js +7 -1
- package/src/application/runtime/pagedDelivery.js +87 -0
- package/src/application/runtime/resolveSecrets.js +9 -0
- package/src/application/siteOperatorCatalog.js +8 -7
- package/src/application/siteRuntime/checkpointedOperationPoll.js +77 -0
- package/src/application/siteRuntime/cutoverOperations.js +25 -0
- package/src/application/siteRuntime/databaseMigrations.js +27 -0
- package/src/application/siteRuntime/edgeMetricsStore.js +35 -0
- package/src/application/siteRuntime/history.js +29 -0
- package/src/application/siteRuntime/index.js +16 -0
- package/src/application/siteRuntime/measurementTopic.js +9 -0
- package/src/application/siteRuntime/operationFederation.js +15 -0
- package/src/application/siteRuntime/operationSnapshot.js +18 -0
- package/src/application/siteRuntime/operatorField.js +49 -0
- package/src/application/siteRuntime/operatorUpdates.js +37 -0
- package/src/application/siteRuntime/telemetry.js +31 -0
- package/src/application/siteRuntime/telemetryBackfillCommand.js +64 -0
- package/src/application/timelineMetrics.js +36 -0
- package/src/domain/timeline/cyclePhases.js +191 -0
- package/src/domain/timeline/taggedCycleWindows.js +17 -0
- package/src/domain/timeline/taggedSegment.js +47 -0
- package/src/domain/timeline/taggedTimeline.js +98 -0
- package/src/domain/timeline/timelineSegment.js +25 -0
- package/src/infrastructure/deploy/brokerFleetPolicy.js +91 -0
- package/src/infrastructure/deploy/configuredArchivePlan.js +25 -0
- package/src/infrastructure/deploy/configuredBrokerRoutes.js +34 -0
- package/src/infrastructure/deploy/configuredClassification.js +74 -0
- package/src/infrastructure/deploy/configuredCollectorChartDeployment.js +22 -0
- package/src/infrastructure/deploy/configuredControlPlane.js +116 -0
- package/src/infrastructure/deploy/configuredDeploymentCredentials.js +45 -0
- package/src/infrastructure/deploy/configuredEtcdInventory.js +30 -0
- package/src/infrastructure/deploy/configuredRuntimeCapabilities.js +14 -0
- package/src/infrastructure/deploy/configuredSiteAssets.js +50 -0
- package/src/infrastructure/deploy/configuredStagedDeployment.js +48 -0
- package/src/infrastructure/deploy/controlPlaneCli.js +17 -0
- package/src/infrastructure/deploy/highAvailability/configuredBrokerReconciliation.js +21 -0
- package/src/infrastructure/deploy/highAvailability/historyWatermark.js +2 -2
- package/src/infrastructure/deploy/highAvailability/index.js +3 -1
- package/src/infrastructure/deploy/highAvailability/replicaHistoryStore.js +7 -0
- package/src/infrastructure/deploy/index.js +22 -1
- package/src/infrastructure/deploy/mixedStoreHistory.js +27 -0
- package/src/infrastructure/deploy/publicBrokerPlan.js +15 -0
- package/src/infrastructure/deploy/siteBrokerDefinitions.js +97 -0
- package/src/infrastructure/deploy/stagedSitePlan.js +132 -0
- package/src/infrastructure/deploy/supervisedServicePlan.js +82 -0
- package/src/infrastructure/http/edge/attachClassify.js +30 -0
- package/src/infrastructure/http/edge/classifyProxy.js +72 -0
- package/src/infrastructure/http/edge/classifyRecord.js +32 -0
- package/src/infrastructure/http/edge/classifyRouting.js +14 -0
- package/src/infrastructure/http/edge/siteAccess.js +7 -0
- package/src/infrastructure/http/edge/writeGuard.js +84 -0
- package/src/infrastructure/http/plant/routes/machineOperationList.js +18 -0
- package/src/infrastructure/http/plant/routes/operationRoute.js +2 -11
- package/src/infrastructure/http/plant/routes/operatorRoute.js +25 -0
- package/src/infrastructure/http/plant/streams/operationStream.js +25 -37
- package/src/infrastructure/ingest/mqtt/modbusDeviceSpec.js +5 -28
- package/src/infrastructure/ingest/mqtt/registerPoint.js +2 -2
- package/src/infrastructure/mdmesh/adminReconciliation.js +19 -0
- package/src/infrastructure/mdmesh/bootstrapMdmeshCredentials.js +4 -4
- package/src/infrastructure/mdmesh/controllerOperation.js +17 -0
- package/src/infrastructure/mdmesh/index.js +3 -0
- package/src/infrastructure/mdmesh/publishApk.js +30 -0
- package/src/infrastructure/persistence/clickhouse/metricBursts.js +73 -0
- package/src/infrastructure/persistence/pg/cyclePhaseQuery.js +168 -0
- package/src/infrastructure/persistence/pg/cyclePrior.js +96 -0
- package/src/infrastructure/persistence/pg/operatorFieldStore.js +50 -0
- package/src/infrastructure/streams/boundedTextFrames.js +27 -0
- package/src/infrastructure/streams/framedSerialSource.js +25 -0
- package/src/infrastructure/streams/index.js +6 -0
- package/src/infrastructure/streams/namedSerialDevices.js +26 -0
- package/src/infrastructure/streams/pollSnapshot.js +11 -0
- package/src/infrastructure/streams/serialLine.js +26 -0
- package/src/infrastructure/streams/watchCurrentReading.js +31 -0
- package/src/infrastructure/streams/windowPublication.js +73 -0
|
@@ -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,9 @@ 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';
|
|
21
|
+
export { default as pollSnapshot } from './pollSnapshot.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,11 @@
|
|
|
1
|
+
/** Periodically read and apply a snapshot, with at most one poll in flight. */
|
|
2
|
+
export default function pollSnapshot({ read, apply, onError, intervalMs }) {
|
|
3
|
+
let running = false;
|
|
4
|
+
const timer = setInterval(() => {
|
|
5
|
+
if (running) { return; }
|
|
6
|
+
running = true;
|
|
7
|
+
Promise.resolve().then(read).then(apply).catch(onError).finally(() => { running = false; });
|
|
8
|
+
}, intervalMs);
|
|
9
|
+
timer.unref();
|
|
10
|
+
return { stop() { clearInterval(timer); } };
|
|
11
|
+
}
|
|
@@ -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
|
+
}
|