@yarkivaev/scada 2.12.2 → 2.14.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/README.md +1 -1
- package/db/migrations/E0013__history_staged_corrections.sql +1 -1
- package/db/migrations/E0017__history_live_covering.sql +1 -1
- package/db/migrations/E0025__history_processor_properties.sql +76 -0
- package/db/migrations/E0026__history_processor_properties_grants.sql +1 -0
- package/index.js +43 -2
- package/package.json +3 -2
- package/src/application/control/controlClient.js +1 -1
- package/src/application/control/createOnlyJSON.js +50 -0
- package/src/application/control/index.js +2 -0
- package/src/application/control/jsonAssignments.js +30 -0
- package/src/application/foldedMetricsSink.js +1 -1
- package/src/application/mcp/loadMetricSeries.js +69 -0
- package/src/application/mcp/locateMachineMetric.js +25 -0
- package/src/application/mcp/metricQueryPorts.js +78 -0
- package/src/application/mcp/parseBearerTokens.js +43 -0
- package/src/application/runtime/assignment.js +4 -1
- package/src/application/runtime/collectorStartup.js +23 -0
- package/src/application/runtime/index.js +2 -0
- package/src/application/runtime/runCollector.js +46 -9
- package/src/application/runtime/runtimeServices.js +20 -2
- package/src/application/runtime/spoolHistory.js +12 -12
- package/src/application/runtime/spoolSurface.js +2 -2
- package/src/application/runtime/spooledOutput.js +27 -0
- package/src/application/siteServer.js +2 -2
- package/src/application/supervisorSink.js +5 -6
- package/src/application/sync/publishingOperations.js +52 -0
- package/src/application/sync/siteSync.js +1 -1
- package/src/application/sync/siteSyncRows.js +1 -1
- package/src/application/sync/siteSyncSites.js +1 -1
- package/src/application/telemetry/telemetryBackfill.js +127 -0
- package/src/application/timelineOperatorFromEnv.js +1 -1
- package/src/domain/ingest/telemetryTimestamp.js +7 -0
- package/src/domain/segment/dispatch.js +19 -17
- package/src/domain/segment/historyFold.js +2 -1
- package/src/domain/segment/intervalFold.js +1 -1
- package/src/domain/segment/segmentContinue.js +1 -1
- package/src/infrastructure/catalog/tagCatalog.js +7 -11
- package/src/infrastructure/deploy/applyWhenChanged.js +15 -0
- package/src/infrastructure/deploy/deploymentKube.js +35 -0
- package/src/infrastructure/deploy/executeKubeSeed.js +24 -0
- package/src/infrastructure/deploy/executeRelease.js +8 -11
- package/src/infrastructure/deploy/operatePostgresMaintenance.js +85 -0
- package/src/infrastructure/deploy/postgresMaintenancePlan.js +54 -0
- package/src/infrastructure/deploy/postgresRestoreObjects.js +73 -0
- package/src/infrastructure/deploy/preflightKubeStorage.js +76 -0
- package/src/infrastructure/deploy/prepareKubePrerequisites.js +95 -0
- package/src/infrastructure/deploy/verifyCollectorCoverage.js +43 -0
- package/src/infrastructure/deploy/verifyPeerBrokerPerimeter.js +24 -0
- package/src/infrastructure/http/plant/json/decisionJson.js +1 -1
- package/src/infrastructure/http/plant/routes/timelineRoute.js +1 -1
- package/src/infrastructure/http/plant/timelineOperator.js +2 -2
- package/src/infrastructure/ingest/db/migrationProfile.js +2 -1
- package/src/infrastructure/ingest/mysql40/byteReader.js +51 -0
- package/src/infrastructure/ingest/mysql40/mysql40.js +116 -0
- package/src/infrastructure/ingest/mysql40/packets.js +72 -0
- package/src/infrastructure/ingest/mysql40/resultRows.js +92 -0
- package/src/infrastructure/ingest/mysql40/scramble.js +89 -0
- package/src/infrastructure/ingest/pipelines/segmentPipeline.js +38 -14
- package/src/infrastructure/ingest/sinks/contiguousPhases.js +1 -1
- package/src/infrastructure/ingest/sinks/continuedSegments.js +9 -8
- package/src/infrastructure/ingest/sinks/decisionSegment.js +1 -1
- package/src/infrastructure/ingest/sinks/foldingSegments.js +16 -10
- package/src/infrastructure/ingest/sinks/{foldCastingPhases.js → repairPhaseOverlaps.js} +17 -29
- package/src/infrastructure/ingest/sinks/retagSink.js +1 -1
- package/src/infrastructure/ingest/sinks/userDecisionSink.js +1 -1
- package/src/infrastructure/ingest/telemetry/edgeTelemetryRuntime.js +83 -0
- package/src/infrastructure/ingest/telemetry/historyTelemetryMetrics.js +15 -0
- package/src/infrastructure/ingest/telemetry/opcuaLocate.js +2 -2
- package/src/infrastructure/ingest/telemetry/replayStoredTelemetry.js +125 -0
- package/src/infrastructure/ingest/telemetry/telemetryIngest.js +52 -0
- package/src/infrastructure/ingest/telemetry/telemetryReplay.js +15 -0
- package/src/infrastructure/management/kubeServiceAccount.js +43 -0
- package/src/infrastructure/management/kubectlPortForward.js +27 -0
- package/src/infrastructure/mdmesh/hmiApplication.js +64 -0
- package/src/infrastructure/mdmesh/hmiControl.js +85 -0
- package/src/infrastructure/mdmesh/hmiFile.js +69 -0
- package/src/infrastructure/mdmesh/hmiMonitor.js +53 -0
- package/src/infrastructure/mdmesh/hmiReconcile.js +170 -0
- package/src/infrastructure/mdmesh/hmiRuntime.js +33 -0
- package/src/infrastructure/mdmesh/index.js +7 -0
- package/src/infrastructure/mdmesh/mdmeshClient.js +72 -0
- package/src/infrastructure/messaging/ownership/edgeSitesFromEnv.js +137 -0
- package/src/infrastructure/messaging/rabbitmq/reconcile.js +71 -12
- package/src/infrastructure/messaging/stomp/retagBody.js +1 -1
- package/src/infrastructure/messaging/stomp/segmentRetags.js +1 -1
- package/src/infrastructure/opcua/health.js +91 -0
- package/src/infrastructure/opcua/index.js +1 -0
- package/src/infrastructure/persistence/clickhouse/historyObservations.js +149 -0
- package/src/infrastructure/persistence/clickhouse/historyRetention.js +94 -0
- package/src/infrastructure/persistence/clickhouse/historySourceIdentity.js +34 -0
- package/src/infrastructure/persistence/clickhouse/insertMetricRows.js +19 -0
- package/src/infrastructure/persistence/clickhouse/jsonMetrics.js +26 -0
- package/src/infrastructure/persistence/clickhouse/localHistory.js +51 -0
- package/src/infrastructure/persistence/clickhouse/metricsState.js +92 -0
- package/src/infrastructure/persistence/clickhouse/rowBinary.js +38 -0
- package/src/infrastructure/persistence/clickhouse/telemetryTarget.js +41 -0
- package/src/infrastructure/persistence/pg/checkpoints.js +35 -9
- package/src/infrastructure/persistence/pg/history.js +74 -56
- package/src/infrastructure/persistence/pg/historyContext.js +34 -17
- package/src/infrastructure/persistence/pg/historyCorrection.js +5 -2
- package/src/infrastructure/persistence/pg/historyFence.js +1 -1
- package/src/infrastructure/persistence/pg/historyNativeBounds.js +31 -0
- package/src/infrastructure/persistence/pg/historyPurge.js +26 -0
- package/src/infrastructure/persistence/pg/historySeed.js +3 -3
- package/src/infrastructure/persistence/pg/historySession.js +15 -0
- package/src/infrastructure/persistence/pg/intervalFoldPg.js +1 -1
- package/src/infrastructure/persistence/pg/prepareRuntimeRole.js +67 -0
- package/src/infrastructure/persistence/pg/telemetrySource.js +64 -0
- package/src/infrastructure/persistence/postgresPool.js +6 -1
- package/src/infrastructure/persistence/runtime/taskStateSqlite.js +37 -0
- package/src/infrastructure/persistence/stateDataFromPool.js +16 -2
- package/src/infrastructure/replication/canonicalJSON.js +15 -0
- package/src/infrastructure/replication/postgresSnapshotReplica.js +129 -0
- package/src/infrastructure/replication/postgresSnapshotRuntime.js +40 -0
- package/src/infrastructure/replication/snapshotSync.js +61 -0
- package/src/infrastructure/replication/tableSnapshotFormat.js +50 -0
- package/src/infrastructure/streams/modbusSource.js +1 -1
- package/src/infrastructure/streams/stompSend.js +1 -1
- package/src/infrastructure/sync/operationAmqp.js +26 -0
- package/src/infrastructure/sync/operationEvent.js +10 -0
- package/src/infrastructure/tls/mirrorTLSSecret.js +37 -0
- package/src/infrastructure/tls/mutualJSON.js +79 -0
- package/src/infrastructure/tls/tlsMaterial.js +57 -0
- package/stream-processing/src/main/scala/scada/processing/infra/state/AtomicStateFile.scala +7 -0
- package/stream-processing/src/main/scala/scada/processing/infra/state/StateJournal.scala +22 -0
- package/stream-processing/src/main/scala/scada/processing/runtime/HistoryClient.scala +10 -1
- package/stream-processing/src/main/scala/scada/processing/runtime/LiveWorker.scala +70 -0
- package/stream-processing/src/main/scala/scada/processing/runtime/LocalHistory.scala +2 -8
- package/stream-processing/src/main/scala/scada/processing/runtime/StatefulHistory.scala +108 -0
- package/stream-processing/src/main/scala/scada/processing/runtime/TimelinePublication.scala +43 -0
- package/stream-processing/src/main/scala/scada/processing/runtime/WorkerStores.scala +43 -0
- package/src/infrastructure/catalog/tag-catalog.json +0 -27
|
@@ -21,7 +21,7 @@ function anonymousName(body, cfg) {
|
|
|
21
21
|
if (typeof key === 'string' && Object.hasOwn(map, key)) {
|
|
22
22
|
return map[key];
|
|
23
23
|
}
|
|
24
|
-
return cfg.defaultUser || '
|
|
24
|
+
return cfg.defaultUser || 'anonymous';
|
|
25
25
|
}
|
|
26
26
|
|
|
27
27
|
/**
|
|
@@ -32,7 +32,7 @@ function anonymousName(body, cfg) {
|
|
|
32
32
|
*
|
|
33
33
|
* @example
|
|
34
34
|
* const gate = timelineOperator({
|
|
35
|
-
* provider, requireOperator: true, defaultUser: '
|
|
35
|
+
* provider, requireOperator: true, defaultUser: 'example-workstation',
|
|
36
36
|
* anonymousUsers: { hmi: 'Anonymous HMI user' }
|
|
37
37
|
* });
|
|
38
38
|
* const audit = await gate.resolve({ operatorId: 2 });
|
|
@@ -33,7 +33,8 @@ const privilegedOnly = new Set([
|
|
|
33
33
|
'E0019__segment_write_fence.sql',
|
|
34
34
|
'E0020__segment_write_fence_grants.sql',
|
|
35
35
|
'E0022__history_replica_outbox_grants.sql',
|
|
36
|
-
'E0024__timeline_replica_origin_grants.sql'
|
|
36
|
+
'E0024__timeline_replica_origin_grants.sql',
|
|
37
|
+
'E0026__history_processor_properties_grants.sql'
|
|
37
38
|
]);
|
|
38
39
|
|
|
39
40
|
/**
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
function fail(state, error) {
|
|
2
|
+
state.failure ??= error;
|
|
3
|
+
clearTimeout(state.timer);
|
|
4
|
+
state.pending = Buffer.alloc(0);
|
|
5
|
+
if (state.job) { state.job.reject(state.failure); state.job = null; }
|
|
6
|
+
}
|
|
7
|
+
function pump(state) {
|
|
8
|
+
if (!state.job || state.pending.length < state.job.need) { return; }
|
|
9
|
+
const current = state.job;
|
|
10
|
+
state.job = null;
|
|
11
|
+
clearTimeout(state.timer);
|
|
12
|
+
const body = state.pending.subarray(0, current.need);
|
|
13
|
+
state.pending = state.pending.subarray(current.need);
|
|
14
|
+
current.resolve(body);
|
|
15
|
+
}
|
|
16
|
+
function bind(socket, state, maxBytes) {
|
|
17
|
+
socket.on('data', (chunk) => {
|
|
18
|
+
if (state.failure) { return; }
|
|
19
|
+
if (state.pending.length + chunk.length > maxBytes) {
|
|
20
|
+
fail(state, new Error('MySQL 4.0 buffer capacity exceeded'));
|
|
21
|
+
socket.destroy?.();
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
state.pending = Buffer.concat([state.pending, chunk]);
|
|
25
|
+
pump(state);
|
|
26
|
+
});
|
|
27
|
+
socket.on('error', (error) => { fail(state, error); });
|
|
28
|
+
socket.once('end', () => { fail(state, new Error('MySQL 4.0 socket closed')); });
|
|
29
|
+
socket.once('close', () => { fail(state, new Error('MySQL 4.0 socket closed')); });
|
|
30
|
+
}
|
|
31
|
+
/** Bounded one-packet reader; a failed connection is never reused. */
|
|
32
|
+
export default function socketBytes(socket, { maxBytes = 1048576, timeoutMs = 10000 } = {}) {
|
|
33
|
+
if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || !Number.isFinite(timeoutMs) || timeoutMs <= 0) {
|
|
34
|
+
throw new TypeError('Invalid MySQL 4.0 reader limits');
|
|
35
|
+
}
|
|
36
|
+
const state = { pending: Buffer.alloc(0), job: null, failure: null, timer: null };
|
|
37
|
+
bind(socket, state, maxBytes);
|
|
38
|
+
return function take(need) {
|
|
39
|
+
if (state.failure) { return Promise.reject(state.failure); }
|
|
40
|
+
if (state.job) { return Promise.reject(new Error('MySQL 4.0 read is already waiting')); }
|
|
41
|
+
if (!Number.isSafeInteger(need) || need < 0 || need > maxBytes) { return Promise.reject(new Error('MySQL 4.0 packet capacity exceeded')); }
|
|
42
|
+
return new Promise((resolve, reject) => {
|
|
43
|
+
state.job = { need, resolve, reject };
|
|
44
|
+
state.timer = setTimeout(() => {
|
|
45
|
+
fail(state, new Error('MySQL 4.0 read timed out'));
|
|
46
|
+
socket.destroy?.();
|
|
47
|
+
}, timeoutMs);
|
|
48
|
+
pump(state);
|
|
49
|
+
});
|
|
50
|
+
};
|
|
51
|
+
}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Read-only client for MySQL 4.0.
|
|
3
|
+
*
|
|
4
|
+
* Older servers can close connections that send a 4.1 handshake.
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
* const db = mysql40({ host: '127.0.0.1', port: 3306, user: 'reader', password: 'secret', database: 'monitoring' });
|
|
8
|
+
* await db.query('SELECT 1');
|
|
9
|
+
*/
|
|
10
|
+
import scramble from './scramble.js';
|
|
11
|
+
import resultRows from './resultRows.js';
|
|
12
|
+
import { connect, frame, packet, reader } from './packets.js';
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Client auth packet for protocol 4.0.
|
|
16
|
+
*
|
|
17
|
+
* @param {Buffer} salt - 8-byte scramble
|
|
18
|
+
* @param {object} options - user, password, database
|
|
19
|
+
* @returns {Buffer} handshake response
|
|
20
|
+
*/
|
|
21
|
+
function login(salt, options) {
|
|
22
|
+
const scrambled = scramble(salt, Buffer.from(options.password));
|
|
23
|
+
return Buffer.concat([
|
|
24
|
+
Buffer.from([0x0d, 0x20, 0xff, 0xff, 0xff]),
|
|
25
|
+
Buffer.from(`${options.user}\0`),
|
|
26
|
+
scrambled,
|
|
27
|
+
Buffer.from(`\0${options.database}\0`)
|
|
28
|
+
]);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Salt from a protocol-10 greeting.
|
|
33
|
+
*
|
|
34
|
+
* @param {Buffer} greeting - server greeting
|
|
35
|
+
* @returns {Buffer} 8-byte salt
|
|
36
|
+
*/
|
|
37
|
+
function saltOf(greeting) {
|
|
38
|
+
const end = greeting.indexOf(0, 1);
|
|
39
|
+
return greeting.subarray(end + 5, end + 13);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Collects packets until a short 0xfe marker, then one past it is not included.
|
|
44
|
+
*
|
|
45
|
+
* @param {function(number): Promise<Buffer>} take - byte reader
|
|
46
|
+
* @param {Buffer[]} found - packets so far
|
|
47
|
+
* @param {number} eofs - short 0xfe packets seen
|
|
48
|
+
* @returns {Promise<Buffer[]>} result packets
|
|
49
|
+
*/
|
|
50
|
+
async function gather(take, limits) {
|
|
51
|
+
const found = [];
|
|
52
|
+
let eofs = 0;
|
|
53
|
+
let bytes = 0;
|
|
54
|
+
while (eofs < 2) {
|
|
55
|
+
// Packet order is defined by the MySQL wire protocol.
|
|
56
|
+
// eslint-disable-next-line no-await-in-loop
|
|
57
|
+
const body = await packet(take);
|
|
58
|
+
bytes += body.length;
|
|
59
|
+
if (found.length >= limits.maxPackets || bytes > limits.maxResponseBytes) { throw new Error('MySQL 4.0 response capacity exceeded'); }
|
|
60
|
+
if (body[0] === 255) { throw new Error(`MySQL 4.0 query failed ${body.toString('latin1', 3)}`); }
|
|
61
|
+
if (body.length < 9 && body[0] === 254) { eofs += 1; }
|
|
62
|
+
found.push(body);
|
|
63
|
+
}
|
|
64
|
+
return found;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Authenticates and runs one SELECT.
|
|
69
|
+
*
|
|
70
|
+
* @param {import('node:net').Socket} socket - connected socket
|
|
71
|
+
* @param {object} options - login options
|
|
72
|
+
* @param {string} sql - SELECT statement
|
|
73
|
+
* @returns {Promise<Array<object>>} rows
|
|
74
|
+
*/
|
|
75
|
+
async function ask(socket, options, sql) {
|
|
76
|
+
const take = reader(socket, options);
|
|
77
|
+
const greeting = await packet(take);
|
|
78
|
+
socket.write(frame(1, login(saltOf(greeting), options)));
|
|
79
|
+
const reply = await packet(take);
|
|
80
|
+
if (reply[0] === 255) {
|
|
81
|
+
throw new Error(`MySQL 4.0 login failed ${reply.toString('latin1', 3)}`);
|
|
82
|
+
}
|
|
83
|
+
socket.write(frame(0, Buffer.concat([Buffer.from([3]), Buffer.from(sql)])));
|
|
84
|
+
return resultRows(await gather(take, options));
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Opens a short-lived read-only session per query.
|
|
89
|
+
*
|
|
90
|
+
* @param {{ host: string, port: number, user: string, password: string, database: string }} options - connection
|
|
91
|
+
* @returns {{ query: function(string): Promise<Array<object>> }} client
|
|
92
|
+
*/
|
|
93
|
+
export default function mysql40(config) {
|
|
94
|
+
const options = { maxPackets: 10000, maxResponseBytes: 1048576, ...config };
|
|
95
|
+
if (![options.maxPackets, options.maxResponseBytes].every((value) => { return Number.isSafeInteger(value) && value > 0; })) {
|
|
96
|
+
throw new TypeError('Invalid MySQL 4.0 response limits');
|
|
97
|
+
}
|
|
98
|
+
return {
|
|
99
|
+
async query(sql) {
|
|
100
|
+
if (!sql.startsWith('SELECT ')) {
|
|
101
|
+
throw new Error(`MySQL 4.0 query is not a read ${sql.slice(0, 24)}`);
|
|
102
|
+
}
|
|
103
|
+
options.signal?.throwIfAborted();
|
|
104
|
+
const socket = await connect(options.host, options.port, options);
|
|
105
|
+
function abort() { socket.destroy(new Error('MySQL 4.0 aborted')); }
|
|
106
|
+
options.signal?.addEventListener('abort', abort, { once: true });
|
|
107
|
+
try {
|
|
108
|
+
options.signal?.throwIfAborted();
|
|
109
|
+
return await ask(socket, options, sql);
|
|
110
|
+
} finally {
|
|
111
|
+
options.signal?.removeEventListener('abort', abort);
|
|
112
|
+
socket.destroy();
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
};
|
|
116
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Packet reader for the MySQL 4.0 wire protocol.
|
|
3
|
+
*
|
|
4
|
+
* One read is outstanding at a time. Callers sequence packets
|
|
5
|
+
* with recursion instead of an await loop.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* const take = reader(socket);
|
|
9
|
+
* const body = await packet(take);
|
|
10
|
+
*/
|
|
11
|
+
import net from 'node:net';
|
|
12
|
+
import byteReader from './byteReader.js';
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Opens a TCP connection.
|
|
16
|
+
*
|
|
17
|
+
* @param {string} host - database host
|
|
18
|
+
* @param {number} port - database port
|
|
19
|
+
* @returns {Promise<import('node:net').Socket>} connected socket
|
|
20
|
+
*/
|
|
21
|
+
export function connect(host, port, { signal, timeoutMs = 10000 } = {}) {
|
|
22
|
+
signal?.throwIfAborted();
|
|
23
|
+
return new Promise((resolve, reject) => {
|
|
24
|
+
const socket = net.connect({ host, port });
|
|
25
|
+
const timer = setTimeout(() => { socket.destroy(new Error('MySQL 4.0 connect timed out')); }, timeoutMs);
|
|
26
|
+
function abort() { socket.destroy(signal.reason ?? new Error('MySQL 4.0 aborted')); }
|
|
27
|
+
function cleanup() { clearTimeout(timer); signal?.removeEventListener('abort', abort); }
|
|
28
|
+
socket.once('connect', () => { cleanup(); resolve(socket); });
|
|
29
|
+
socket.once('error', (error) => { cleanup(); reject(error); });
|
|
30
|
+
socket.once('close', () => { cleanup(); reject(new Error('MySQL 4.0 closed before connect')); });
|
|
31
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Frames a client packet.
|
|
37
|
+
*
|
|
38
|
+
* @param {number} seq - packet sequence
|
|
39
|
+
* @param {Buffer} body - payload
|
|
40
|
+
* @returns {Buffer} header plus body
|
|
41
|
+
*/
|
|
42
|
+
export function frame(seq, body) {
|
|
43
|
+
const head = Buffer.from([
|
|
44
|
+
body.length % 256,
|
|
45
|
+
Math.floor(body.length / 256) % 256,
|
|
46
|
+
Math.floor(body.length / 65536) % 256,
|
|
47
|
+
seq
|
|
48
|
+
]);
|
|
49
|
+
return Buffer.concat([head, body]);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Creates a one-at-a-time byte reader.
|
|
54
|
+
*
|
|
55
|
+
* @param {import('node:net').Socket} socket - open socket
|
|
56
|
+
* @returns {function(number): Promise<Buffer>} take(count)
|
|
57
|
+
*/
|
|
58
|
+
export function reader(socket, options = {}) {
|
|
59
|
+
return byteReader(socket, options);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Reads one length-prefixed packet.
|
|
64
|
+
*
|
|
65
|
+
* @param {function(number): Promise<Buffer>} take - byte reader
|
|
66
|
+
* @returns {Promise<Buffer>} packet body
|
|
67
|
+
*/
|
|
68
|
+
export async function packet(take) {
|
|
69
|
+
const head = await take(4);
|
|
70
|
+
const length = head[0] + (head[1] * 256) + (head[2] * 65536);
|
|
71
|
+
return take(length);
|
|
72
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Parses a MySQL 4.0 text result set.
|
|
3
|
+
*
|
|
4
|
+
* Field names are the second length-coded string. Rows are length-coded
|
|
5
|
+
* strings, and a short 0xfe packet ends the fields and the rows.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* resultRows([Buffer.from([1]), namePacket, Buffer.from([0xfe])]);
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Reads a length-coded integer.
|
|
13
|
+
*
|
|
14
|
+
* @param {Buffer} buf - packet
|
|
15
|
+
* @param {number} index - offset
|
|
16
|
+
* @returns {{ value: number|null, index: number }} decoded value
|
|
17
|
+
*/
|
|
18
|
+
function lenenc(buf, index) {
|
|
19
|
+
const head = buf[index];
|
|
20
|
+
if (head < 251) {
|
|
21
|
+
return { value: head, index: index + 1 };
|
|
22
|
+
}
|
|
23
|
+
if (head === 251) {
|
|
24
|
+
return { value: null, index: index + 1 };
|
|
25
|
+
}
|
|
26
|
+
if (head === 252) {
|
|
27
|
+
return { value: buf[index + 1] + (buf[index + 2] * 256), index: index + 3 };
|
|
28
|
+
}
|
|
29
|
+
const wide = buf[index + 1] + (buf[index + 2] * 256) + (buf[index + 3] * 65536);
|
|
30
|
+
return { value: wide, index: index + 4 };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Reads a length-coded string as raw Latin-1 bytes.
|
|
35
|
+
*
|
|
36
|
+
* @param {Buffer} buf - packet
|
|
37
|
+
* @param {number} index - offset
|
|
38
|
+
* @returns {{ value: string|null, index: number }} decoded text
|
|
39
|
+
*/
|
|
40
|
+
function text(buf, index) {
|
|
41
|
+
const size = lenenc(buf, index);
|
|
42
|
+
if (size.value === null) {
|
|
43
|
+
return { value: null, index: size.index };
|
|
44
|
+
}
|
|
45
|
+
const end = size.index + size.value;
|
|
46
|
+
return { value: buf.toString('latin1', size.index, end), index: end };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Field name from a 4.0 column packet.
|
|
51
|
+
*
|
|
52
|
+
* @param {Buffer} packet - column definition
|
|
53
|
+
* @returns {string} column name
|
|
54
|
+
*/
|
|
55
|
+
function fieldName(packet) {
|
|
56
|
+
const table = text(packet, 0);
|
|
57
|
+
return text(packet, table.index).value;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Whether a packet is the end-of-fields or end-of-rows marker.
|
|
62
|
+
*
|
|
63
|
+
* @param {Buffer} packet - protocol packet
|
|
64
|
+
* @returns {boolean} true for a short 0xfe packet
|
|
65
|
+
*/
|
|
66
|
+
function eof(packet) {
|
|
67
|
+
return packet.length < 9 && packet[0] === 254;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Splits packets into column names and row objects.
|
|
72
|
+
*
|
|
73
|
+
* @param {Buffer[]} packets - result packets, field count first
|
|
74
|
+
* @returns {Array<object>} rows
|
|
75
|
+
*/
|
|
76
|
+
export default function resultRows(packets) {
|
|
77
|
+
const head = packets[0];
|
|
78
|
+
if (head[0] === 255) {
|
|
79
|
+
throw new Error(`MySQL 4.0 query failed ${head.toString('latin1', 3)}`);
|
|
80
|
+
}
|
|
81
|
+
const count = head[0];
|
|
82
|
+
const names = packets.slice(1, 1 + count).map(fieldName);
|
|
83
|
+
const body = packets.slice(2 + count);
|
|
84
|
+
return body.filter((packet) => {
|
|
85
|
+
return !eof(packet);
|
|
86
|
+
}).map((packet) => {
|
|
87
|
+
return names.reduce((row, name) => {
|
|
88
|
+
const cell = text(packet, row.index);
|
|
89
|
+
return { index: cell.index, values: { ...row.values, [name]: cell.value } };
|
|
90
|
+
}, { index: 0, values: {} }).values;
|
|
91
|
+
});
|
|
92
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MySQL 4.0 old-password scramble.
|
|
3
|
+
*
|
|
4
|
+
* The mix matches the server's 32-bit unsigned arithmetic.
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
* scramble(Buffer.from('12345678'), Buffer.from('secret'));
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Keeps a value inside unsigned 32 bits.
|
|
12
|
+
*
|
|
13
|
+
* @param {number} value - intermediate mix
|
|
14
|
+
* @returns {number} unsigned 32-bit value
|
|
15
|
+
*/
|
|
16
|
+
function mask(value) {
|
|
17
|
+
const wrapped = value % 4294967296;
|
|
18
|
+
return wrapped < 0 ? wrapped + 4294967296 : wrapped;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Xors two unsigned 32-bit values without bitwise operators.
|
|
23
|
+
*
|
|
24
|
+
* @param {number} left - first value
|
|
25
|
+
* @param {number} right - second value
|
|
26
|
+
* @returns {number} xor
|
|
27
|
+
*/
|
|
28
|
+
function xor(left, right) {
|
|
29
|
+
let out = 0;
|
|
30
|
+
let bit = 1;
|
|
31
|
+
let low = mask(left);
|
|
32
|
+
let high = mask(right);
|
|
33
|
+
for (let i = 0; i < 32; i += 1) {
|
|
34
|
+
if ((low % 2) !== (high % 2)) {
|
|
35
|
+
out += bit;
|
|
36
|
+
}
|
|
37
|
+
low = Math.floor(low / 2);
|
|
38
|
+
high = Math.floor(high / 2);
|
|
39
|
+
bit *= 2;
|
|
40
|
+
}
|
|
41
|
+
return out;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Hashes a password or salt the way MySQL 4.0 does.
|
|
46
|
+
*
|
|
47
|
+
* @param {Buffer} password - raw bytes, spaces skipped
|
|
48
|
+
* @returns {number[]} two masked halves
|
|
49
|
+
*/
|
|
50
|
+
function mix(password) {
|
|
51
|
+
let nr = 1345345333;
|
|
52
|
+
let add = 7;
|
|
53
|
+
let nr2 = 305419889;
|
|
54
|
+
for (const byte of password) {
|
|
55
|
+
if (byte !== 32 && byte !== 9) {
|
|
56
|
+
const mixed = mask((((nr % 64) + add) * byte) + mask(nr * 256));
|
|
57
|
+
nr = xor(nr, mixed);
|
|
58
|
+
nr2 = mask(nr2 + xor(mask(nr2 * 256), nr));
|
|
59
|
+
add += byte;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return [nr % 2147483648, nr2 % 2147483648];
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Scrambles an 8-byte salt with the account password.
|
|
67
|
+
*
|
|
68
|
+
* @param {Buffer} message - server salt
|
|
69
|
+
* @param {Buffer} password - account password
|
|
70
|
+
* @returns {Buffer} 8-byte reply
|
|
71
|
+
*/
|
|
72
|
+
export default function scramble(message, password) {
|
|
73
|
+
const pass = mix(password);
|
|
74
|
+
const salt = mix(message);
|
|
75
|
+
let seed1 = xor(pass[0], salt[0]) % 1073741824;
|
|
76
|
+
let seed2 = xor(pass[1], salt[1]) % 1073741824;
|
|
77
|
+
const out = [];
|
|
78
|
+
const span = 1073741823;
|
|
79
|
+
for (let i = 0; i < message.length; i += 1) {
|
|
80
|
+
seed1 = ((seed1 * 3) + seed2) % span;
|
|
81
|
+
seed2 = (seed1 + seed2 + 33) % span;
|
|
82
|
+
out.push(Math.floor((seed1 / span) * 31) + 64);
|
|
83
|
+
}
|
|
84
|
+
seed1 = ((seed1 * 3) + seed2) % span;
|
|
85
|
+
const extra = Math.floor((seed1 / span) * 31);
|
|
86
|
+
return Buffer.from(out.map((item) => {
|
|
87
|
+
return xor(item, extra);
|
|
88
|
+
}));
|
|
89
|
+
}
|
|
@@ -13,7 +13,7 @@ import segmentCodec from '../codecs/segmentCodec.js';
|
|
|
13
13
|
import processingErrorLog from '../processingErrorLog.js';
|
|
14
14
|
import silentOpenWatch from '../silentOpenWatch.js';
|
|
15
15
|
import abutSegments from '../sinks/abutSegments.js';
|
|
16
|
-
import
|
|
16
|
+
import repairPhaseOverlaps from '../sinks/repairPhaseOverlaps.js';
|
|
17
17
|
import closeOrphanOpen from '../sinks/closeOrphanOpen.js';
|
|
18
18
|
import closeSilentOpen from '../sinks/closeSilentOpen.js';
|
|
19
19
|
import continuedSegments from '../sinks/continuedSegments.js';
|
|
@@ -26,6 +26,7 @@ export const segmentConflict = ['machine', 'kind', 'start_time'];
|
|
|
26
26
|
export const segmentUpdateColumns = ['name', 'end_time', 'duration', 'options', 'resolved', 'updated_at'];
|
|
27
27
|
export const splitUpdateColumns = ['name', 'end_time', 'duration', 'tags', 'options', 'properties', 'resolved'];
|
|
28
28
|
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"%\')) AND (NOT EXISTS (SELECT 1 FROM segments AS later WHERE later.machine = segments.machine AND later.kind = segments.kind AND later.start_time > segments.start_time) OR (segments.duration > 0 AND EXCLUDED.duration = segments.duration AND EXCLUDED.name = segments.name AND EXCLUDED.end_time = segments.end_time))';
|
|
29
|
+
const coveringSegmentUpdateWhere = '(segments.duration = 0 OR EXCLUDED.duration > 0 OR EXCLUDED.end_time > segments.end_time) AND NOT (EXCLUDED.duration = 0 AND 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"%\')) AND NOT EXISTS (SELECT 1 FROM segments AS later WHERE later.machine = segments.machine AND later.kind = segments.kind AND later.start_time > segments.start_time)';
|
|
29
30
|
export const segmentsIngestDestination = '/queue/scada.segments.ingest';
|
|
30
31
|
|
|
31
32
|
export { default as segmentDispatch } from '../../../domain/segment/dispatch.js';
|
|
@@ -37,13 +38,15 @@ export { default as segmentDispatch } from '../../../domain/segment/dispatch.js'
|
|
|
37
38
|
* @param {object} pool - shared pg pool
|
|
38
39
|
* @returns {{ segmentSink: object, splitSink: object }}
|
|
39
40
|
*/
|
|
40
|
-
function segmentSinks(postgres, pool) {
|
|
41
|
-
const
|
|
41
|
+
function segmentSinks(postgres, pool, policy) {
|
|
42
|
+
const updateWhere = policy.preserveCoverage ? coveringSegmentUpdateWhere : segmentUpdateWhere;
|
|
43
|
+
const shared = { pool, conflict: segmentConflict, updateWhere };
|
|
44
|
+
const update = policy.preserveCoverage ? [...segmentUpdateColumns, 'properties'] : segmentUpdateColumns;
|
|
42
45
|
return {
|
|
43
46
|
segmentSink: foldingSegments(postgresSink(postgres, 'segments', segmentColumns,
|
|
44
|
-
{ ...shared, update
|
|
47
|
+
{ ...shared, update }), pool, policy),
|
|
45
48
|
splitSink: foldingSegments(postgresSink(postgres, 'segments', segmentColumns,
|
|
46
|
-
{ ...shared, update: splitUpdateColumns }), pool)
|
|
49
|
+
{ ...shared, update: splitUpdateColumns }), pool, policy)
|
|
47
50
|
};
|
|
48
51
|
}
|
|
49
52
|
|
|
@@ -52,6 +55,11 @@ function pipelineSettings(config) {
|
|
|
52
55
|
if (settings.repairHistoryOnStart !== undefined && typeof settings.repairHistoryOnStart !== 'boolean') {
|
|
53
56
|
throw new TypeError('repairHistoryOnStart must be boolean');
|
|
54
57
|
}
|
|
58
|
+
const { phaseRepairMachines } = settings;
|
|
59
|
+
if (phaseRepairMachines !== undefined && (!Array.isArray(phaseRepairMachines)
|
|
60
|
+
|| phaseRepairMachines.some((machine) => { return typeof machine !== 'string' || !machine.trim(); }))) {
|
|
61
|
+
throw new TypeError('phaseRepairMachines must be an array of machine ids');
|
|
62
|
+
}
|
|
55
63
|
return settings;
|
|
56
64
|
}
|
|
57
65
|
|
|
@@ -63,18 +71,34 @@ async function repairHistory(pool, budget, protectedTracks) {
|
|
|
63
71
|
}
|
|
64
72
|
}
|
|
65
73
|
|
|
66
|
-
function
|
|
67
|
-
|
|
68
|
-
processingErrorLog('
|
|
74
|
+
function repairConfiguredPhases(pool, settings, protectedTracks) {
|
|
75
|
+
repairPhaseOverlaps(pool, settings.phaseRepairMachines, protectedTracks, settings).catch((error) => {
|
|
76
|
+
processingErrorLog('repair_phase_overlaps', error, {});
|
|
69
77
|
});
|
|
70
78
|
}
|
|
71
79
|
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
80
|
+
function phasePolicy({ preserveCoverage, authoritativeProperty }) {
|
|
81
|
+
if (authoritativeProperty !== undefined && (typeof authoritativeProperty?.key !== 'string'
|
|
82
|
+
|| !authoritativeProperty.key || typeof authoritativeProperty.value !== 'string')) {
|
|
83
|
+
throw new TypeError('authoritativeProperty must specify a property key and string value');
|
|
84
|
+
}
|
|
85
|
+
return {
|
|
86
|
+
preserveCoverage,
|
|
87
|
+
isAuthoritative(row) {
|
|
88
|
+
if (!authoritativeProperty) { return false; }
|
|
89
|
+
const properties = typeof row.properties === 'string' ? JSON.parse(row.properties) : row.properties;
|
|
90
|
+
return properties?.[authoritativeProperty.key] === authoritativeProperty.value;
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function segmentRecipient(postgres, pool, config) {
|
|
96
|
+
const policy = phasePolicy(config);
|
|
97
|
+
const { segmentSink, splitSink } = segmentSinks(postgres, pool, policy);
|
|
98
|
+
const continued = continuedSegments(segmentSink, pool, silenceBudget(config.segmentWindow || 15), policy);
|
|
75
99
|
const dispatch = contiguousPhases(pool, config.phaseAnchors,
|
|
76
|
-
segmentDispatch(continued, retagSink(pool), splitSink, closeOrphanOpen(pool), pool));
|
|
77
|
-
return fencedSegments(pool,dispatch,config);
|
|
100
|
+
segmentDispatch(continued, retagSink(pool), splitSink, closeOrphanOpen(pool), pool, policy));
|
|
101
|
+
return fencedSegments(pool, dispatch, config);
|
|
78
102
|
}
|
|
79
103
|
|
|
80
104
|
/**
|
|
@@ -129,7 +153,7 @@ export default function segmentPipeline(stomp, postgres, pool, config, recipient
|
|
|
129
153
|
await source.start();
|
|
130
154
|
await silence.start();
|
|
131
155
|
if (settings.repairHistoryOnStart !== false) {
|
|
132
|
-
|
|
156
|
+
repairConfiguredPhases(pool, settings, protectedTracks);
|
|
133
157
|
}
|
|
134
158
|
},
|
|
135
159
|
stop() {
|
|
@@ -138,7 +138,7 @@ export default function contiguousPhases(pool, anchors, dispatch) {
|
|
|
138
138
|
throw invalid('An anchored phase track cannot change geometry via split-family');
|
|
139
139
|
}
|
|
140
140
|
if (row.type === 'split') {
|
|
141
|
-
//
|
|
141
|
+
// Legacy publishers send a compatibility split before each authoritative segment.
|
|
142
142
|
return Promise.resolve();
|
|
143
143
|
}
|
|
144
144
|
const anchor = anchors.get(row.machine);
|
|
@@ -7,17 +7,18 @@ function pointed(record) {
|
|
|
7
7
|
return { ...record, end_time: record.start_time };
|
|
8
8
|
}
|
|
9
9
|
|
|
10
|
-
function behind(record, prior) {
|
|
11
|
-
return record.duration === 0 && Boolean(prior) && prior.name !== record.name
|
|
10
|
+
function behind(record, prior, preserveCoverage) {
|
|
11
|
+
return (preserveCoverage || record.duration === 0) && Boolean(prior) && prior.name !== record.name
|
|
12
12
|
&& Date.parse(record.start_time) < Date.parse(prior.start_time);
|
|
13
13
|
}
|
|
14
14
|
|
|
15
|
-
function placed(record, prior, apply) {
|
|
16
|
-
if (behind(record, prior)) {
|
|
15
|
+
function placed(record, prior, apply, preserveCoverage) {
|
|
16
|
+
if (behind(record, prior, preserveCoverage)) {
|
|
17
17
|
const start = new Date(prior.end_time).toISOString();
|
|
18
18
|
return { ...record, start_time: start, end_time: start, duration: 0 };
|
|
19
19
|
}
|
|
20
|
-
|
|
20
|
+
const row = apply(record, prior);
|
|
21
|
+
return preserveCoverage ? row : pointed(row);
|
|
21
22
|
}
|
|
22
23
|
|
|
23
24
|
/**
|
|
@@ -69,7 +70,7 @@ async function reopenContinuation(client, record, prior, next) {
|
|
|
69
70
|
* const sink = continuedSegments(segmentSink, pool, 30);
|
|
70
71
|
* await sink.write([record], client);
|
|
71
72
|
*/
|
|
72
|
-
export default function continuedSegments(inner, pool, budgetSeconds) {
|
|
73
|
+
export default function continuedSegments(inner, pool, budgetSeconds, { preserveCoverage = false, isAuthoritative = () => { return false; } } = {}) {
|
|
73
74
|
const apply = segmentContinue(budgetSeconds);
|
|
74
75
|
return {
|
|
75
76
|
async write(records, client) {
|
|
@@ -81,8 +82,8 @@ export default function continuedSegments(inner, pool, budgetSeconds) {
|
|
|
81
82
|
seen.set(key, await latest(runner, record));
|
|
82
83
|
}
|
|
83
84
|
const previous = seen.get(key);
|
|
84
|
-
const row = placed(record, previous, apply);
|
|
85
|
-
await reopenContinuation(client, record, previous, row);
|
|
85
|
+
const row = isAuthoritative(record) ? record : placed(record, previous, apply, preserveCoverage);
|
|
86
|
+
if (!preserveCoverage) { await reopenContinuation(client, record, previous, row); }
|
|
86
87
|
seen.set(key, row);
|
|
87
88
|
rows.push(row);
|
|
88
89
|
return { rows, seen };
|
|
@@ -31,7 +31,7 @@ async function applySplit(pool, machine, start, splits) {
|
|
|
31
31
|
* @returns {Promise<void>}
|
|
32
32
|
*
|
|
33
33
|
* @example
|
|
34
|
-
* await applyDecision(pool, '
|
|
34
|
+
* await applyDecision(pool, 'drive2', '2026-11-17T07:17:09.930Z', '{"tags":["inspection"]}');
|
|
35
35
|
*/
|
|
36
36
|
export async function applyDecision(pool, machine, startTime, payload) {
|
|
37
37
|
const body = JSON.parse(payload);
|