@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
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/** Start of the
|
|
1
|
+
/** Start of the active bucket that can still receive observations, in the work time unit. */
|
|
2
2
|
export default async function historyFence(pool, machine, timeScale = 1) {
|
|
3
3
|
if (![1, 1000].includes(timeScale)) { throw new TypeError('External history supports millisecond or microsecond coordinates'); }
|
|
4
4
|
const result = await pool.query(`SELECT floor(extract(epoch FROM clock_timestamp()) * 1000 * $2 / bucket) * bucket AS open_ms
|
|
@@ -30,6 +30,37 @@ function retainExterior(segments, current, owners, until) {
|
|
|
30
30
|
}
|
|
31
31
|
}
|
|
32
32
|
}
|
|
33
|
+
/** Replace pages keep only the observed until; the open tail continues through the checkpoint. */
|
|
34
|
+
export function clipReplacePage(segments, latest, timeScale) {
|
|
35
|
+
if (!latest?.context?.page) { return segments; }
|
|
36
|
+
const until = Math.round(latest.context.page.until / timeScale);
|
|
37
|
+
return segments.flatMap((item) => {
|
|
38
|
+
const start = instant(item.start_time);
|
|
39
|
+
const end = instant(item.end_time);
|
|
40
|
+
if (!Number.isFinite(start) || !Number.isFinite(end) || start >= until) { return []; }
|
|
41
|
+
if (end <= until) { return [item]; }
|
|
42
|
+
return [{ ...item, end_time: new Date(until).toISOString(), duration: (until - start) / 1000 }];
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
/** Coalesces overlapping pieces that carry the same classification. */
|
|
46
|
+
export function joinReplacePage(segments) {
|
|
47
|
+
return [...segments].sort((left, right) => { return instant(left.start_time) - instant(right.start_time); })
|
|
48
|
+
.reduce((rows, item) => {
|
|
49
|
+
const prior = rows.at(-1);
|
|
50
|
+
if (!prior || prior.name !== item.name || (prior.kind ?? 'phase') !== (item.kind ?? 'phase')) {
|
|
51
|
+
return [...rows, item];
|
|
52
|
+
}
|
|
53
|
+
const start = instant(prior.start_time);
|
|
54
|
+
const incoming = instant(item.start_time);
|
|
55
|
+
const priorEnd = instant(prior.end_time);
|
|
56
|
+
const end = Math.max(priorEnd, instant(item.end_time));
|
|
57
|
+
if (!Number.isFinite(start) || !Number.isFinite(incoming) || incoming < start || incoming > priorEnd) {
|
|
58
|
+
return [...rows, item];
|
|
59
|
+
}
|
|
60
|
+
return [...rows.slice(0, -1), { ...item, start_time: prior.start_time,
|
|
61
|
+
end_time: new Date(end).toISOString(), duration: (end - start) / 1000 }];
|
|
62
|
+
}, []);
|
|
63
|
+
}
|
|
33
64
|
/** A bounded native correction may carry existing exterior, never classify new exterior. */
|
|
34
65
|
export default function nativeHistoryBounds(segments, latest, base, timeScale) {
|
|
35
66
|
if (!latest) { return []; }
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import retainMetricReceipts from '../../ingest/db/retainMetricReceipts.js';
|
|
2
|
+
import pgHistorySession from './historySession.js';
|
|
3
|
+
|
|
4
|
+
export default function historyPurge(pool, cutoff, retentionDays, batch) {
|
|
5
|
+
if (!batch) {
|
|
6
|
+
return pool.query(`DELETE FROM history_observations o WHERE time_ms < $1
|
|
7
|
+
AND NOT EXISTS (SELECT 1 FROM history_work w WHERE w.machine=o.machine
|
|
8
|
+
AND (o.time_ms BETWEEN w.from_ms-86400000 AND greatest(w.until_ms,COALESCE(w.end_ms,w.until_ms))+86400000
|
|
9
|
+
OR (o.time_ms<w.from_ms-86400000 AND NOT EXISTS (SELECT 1 FROM history_observations anchor
|
|
10
|
+
WHERE anchor.machine=o.machine AND anchor.channel=o.channel AND anchor.time_ms>o.time_ms AND anchor.time_ms<w.from_ms-86400000))))
|
|
11
|
+
AND EXISTS (SELECT 1 FROM history_observations newer WHERE newer.machine=o.machine
|
|
12
|
+
AND newer.channel=o.channel AND newer.time_ms>o.time_ms AND newer.time_ms<$1)`, [cutoff]).then(async (result) => {
|
|
13
|
+
await retainMetricReceipts(pool, retentionDays);
|
|
14
|
+
return result.rowCount;
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
return pgHistorySession(pool, async (client) => {
|
|
18
|
+
const pending = await client.query('SELECT 1 FROM history_work WHERE from_ms < $1 LIMIT 1', [cutoff]);
|
|
19
|
+
if (pending.rowCount) { return { deferred: 'pending work' }; }
|
|
20
|
+
const result = await client.query(`DELETE FROM history_observations WHERE ctid IN (
|
|
21
|
+
SELECT ctid FROM history_observations WHERE time_ms < $1 ORDER BY machine, time_ms LIMIT $2
|
|
22
|
+
)`, [cutoff, batch]);
|
|
23
|
+
await retainMetricReceipts(client, retentionDays);
|
|
24
|
+
return result.rowCount;
|
|
25
|
+
}, 20000);
|
|
26
|
+
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** Complete carried parameters at the left context boundary within the last continuous run. */
|
|
2
|
-
export default async function historySeed(pool, machine, before, maxGap, {observations,timeScale=1}={}) {
|
|
2
|
+
export default async function historySeed(pool, machine, before, maxGap, {observations,timeScale=1,bounded = false}={}) {
|
|
3
3
|
const external = observations?.seed ? await observations.seed(machine,before,maxGap) : undefined;
|
|
4
4
|
if (external === null) { return null; }
|
|
5
5
|
if (external !== undefined) {
|
|
@@ -9,13 +9,13 @@ export default async function historySeed(pool, machine, before, maxGap, {observ
|
|
|
9
9
|
return {...external,segment:prior.rows[0] ?? null};
|
|
10
10
|
}
|
|
11
11
|
const result = await pool.query(`WITH times AS (
|
|
12
|
-
SELECT DISTINCT time_ms FROM history_observations WHERE machine=$1 AND time_ms<$2
|
|
12
|
+
SELECT DISTINCT time_ms FROM history_observations WHERE machine=$1 AND time_ms<$2${bounded ? ' AND time_ms>=$4' : ''}
|
|
13
13
|
), gaps AS (
|
|
14
14
|
SELECT time_ms,time_ms-lag(time_ms) OVER (ORDER BY time_ms) AS gap FROM times
|
|
15
15
|
), boundary AS MATERIALIZED (
|
|
16
16
|
SELECT COALESCE(max(time_ms) FILTER (WHERE gap>$3),min(time_ms)) AS at FROM gaps
|
|
17
17
|
) SELECT DISTINCT ON (channel) channel,time_ms AS time,value,boundary.at AS since FROM history_observations,boundary
|
|
18
|
-
WHERE machine=$1 AND time_ms>=boundary.at AND time_ms<$2 ORDER BY channel,time_ms DESC`, [machine,before,maxGap]);
|
|
18
|
+
WHERE machine=$1 AND time_ms>=boundary.at AND time_ms<$2 ORDER BY channel,time_ms DESC`, [machine,before,maxGap,...(bounded ? [before-maxGap] : [])]);
|
|
19
19
|
if (!result.rows.length) { return null; }
|
|
20
20
|
const time = Math.max(...result.rows.map((row) => { return Number(row.time); }));
|
|
21
21
|
const since = Number(result.rows[0].since);
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/** Owns a history transaction with an optional statement deadline. */
|
|
2
|
+
export default async function historySession(pool, action, timeoutMs, required = false) {
|
|
3
|
+
if (!required && (!timeoutMs || typeof pool.connect !== 'function')) { return action(pool); }
|
|
4
|
+
const client = await pool.connect();
|
|
5
|
+
try {
|
|
6
|
+
await client.query('BEGIN');
|
|
7
|
+
if (timeoutMs) { await client.query("SELECT set_config('statement_timeout', $1, true)", [String(timeoutMs)]); }
|
|
8
|
+
const result = await action(client);
|
|
9
|
+
await client.query('COMMIT');
|
|
10
|
+
return result;
|
|
11
|
+
} catch (error) {
|
|
12
|
+
await client.query('ROLLBACK');
|
|
13
|
+
throw error;
|
|
14
|
+
} finally { client.release(); }
|
|
15
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import pg from 'pg';
|
|
2
|
+
|
|
3
|
+
const protocol = ['postgres:', 'postgresql:'];
|
|
4
|
+
|
|
5
|
+
function addresses(adminUrl, runtimeUrl, { hosts, port = 5432, database, role }) {
|
|
6
|
+
const admin = new URL(adminUrl);
|
|
7
|
+
const runtime = new URL(runtimeUrl);
|
|
8
|
+
for (const address of [admin, runtime]) {
|
|
9
|
+
if (!protocol.includes(address.protocol) || !hosts.includes(address.hostname) ||
|
|
10
|
+
(address.port || '5432') !== String(port) ||
|
|
11
|
+
decodeURIComponent(address.pathname.slice(1)) !== database || !address.password) {
|
|
12
|
+
throw new Error('Runtime role credentials must address the configured PostgreSQL database');
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
if (decodeURIComponent(runtime.username) !== role) {
|
|
16
|
+
throw new Error('Runtime login must use the configured restricted role');
|
|
17
|
+
}
|
|
18
|
+
return { admin, runtime };
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
async function activate(admin, runtime, roleName) {
|
|
22
|
+
const result = await admin.query(
|
|
23
|
+
'SELECT rolcanlogin,rolsuper,rolcreatedb,rolcreaterole,rolreplication,rolbypassrls FROM pg_roles WHERE rolname=$1',
|
|
24
|
+
[roleName]
|
|
25
|
+
);
|
|
26
|
+
const role = result.rows[0];
|
|
27
|
+
if (role && (role.rolsuper || role.rolcreatedb || role.rolcreaterole || role.rolreplication || role.rolbypassrls)) {
|
|
28
|
+
throw new Error('Unexpected privileged runtime role');
|
|
29
|
+
}
|
|
30
|
+
if (role?.rolcanlogin) {
|
|
31
|
+
return false;
|
|
32
|
+
}
|
|
33
|
+
if (!role) {
|
|
34
|
+
const create = await admin.query("SELECT format('CREATE ROLE %I NOLOGIN', $1::text) AS command", [roleName]);
|
|
35
|
+
await admin.query(create.rows[0].command);
|
|
36
|
+
}
|
|
37
|
+
const alter = await admin.query(
|
|
38
|
+
"SELECT format('ALTER ROLE %I LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS PASSWORD %L', $1::text, $2::text) AS command",
|
|
39
|
+
[roleName, decodeURIComponent(runtime.password)]
|
|
40
|
+
);
|
|
41
|
+
await admin.query(alter.rows[0].command);
|
|
42
|
+
return true;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Enables a restricted PostgreSQL login and verifies existing credentials without rotating its password. */
|
|
46
|
+
export default async function prepareRuntimeRole(adminUrl, runtimeUrl, settings) {
|
|
47
|
+
const { role, verify, lockKey } = settings;
|
|
48
|
+
const urls = addresses(adminUrl, runtimeUrl, settings);
|
|
49
|
+
const admin = new pg.Client({ connectionString: urls.admin.href, connectionTimeoutMillis: 5000, 'query_timeout': 10000 });
|
|
50
|
+
try {
|
|
51
|
+
await admin.connect();
|
|
52
|
+
await admin.query('SELECT pg_advisory_lock(hashtextextended($1,0))', [lockKey ?? role]);
|
|
53
|
+
const createdLogin = await activate(admin, urls.runtime, role);
|
|
54
|
+
const application = new pg.Client({ connectionString: urls.runtime.href, connectionTimeoutMillis: 5000, 'query_timeout': 5000 });
|
|
55
|
+
try {
|
|
56
|
+
await application.connect();
|
|
57
|
+
if (verify) {
|
|
58
|
+
await verify(application);
|
|
59
|
+
}
|
|
60
|
+
} finally {
|
|
61
|
+
await application.end();
|
|
62
|
+
}
|
|
63
|
+
return { user: role, createdLogin };
|
|
64
|
+
} finally {
|
|
65
|
+
await admin.end();
|
|
66
|
+
}
|
|
67
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
const timestamp = "to_char(ts AT TIME ZONE 'UTC','YYYY-MM-DD HH24:MI:SS.US')";
|
|
2
|
+
|
|
3
|
+
async function finish(state, command) {
|
|
4
|
+
const { client } = state;
|
|
5
|
+
if (!client) { return; }
|
|
6
|
+
state.client = undefined;
|
|
7
|
+
let fault;
|
|
8
|
+
try {
|
|
9
|
+
await client.query(command);
|
|
10
|
+
} catch (error) {
|
|
11
|
+
fault = error;
|
|
12
|
+
throw error;
|
|
13
|
+
} finally {
|
|
14
|
+
client.release(fault);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
async function declare(pool, state, topic, upper, from) {
|
|
19
|
+
const client = await pool.connect();
|
|
20
|
+
Object.assign(state, { client, topic });
|
|
21
|
+
try {
|
|
22
|
+
await client.query('BEGIN READ ONLY');
|
|
23
|
+
await client.query(
|
|
24
|
+
`DECLARE telemetry_rows NO SCROLL CURSOR FOR SELECT topic,${timestamp} AS ts,value
|
|
25
|
+
FROM metrics WHERE topic=$1 AND ts >= $3::timestamptz AND ts <= $2::timestamptz
|
|
26
|
+
ORDER BY metrics.ts,float8send(value)`,
|
|
27
|
+
[topic, `${upper}+00`, from]
|
|
28
|
+
);
|
|
29
|
+
} catch (error) {
|
|
30
|
+
await finish(state, 'ROLLBACK');
|
|
31
|
+
throw error;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Read a bounded snapshot of each topic, retaining physical duplicates and exact timestamps. */
|
|
36
|
+
export default function postgresTelemetrySource(pool, { from = '1970-01-01T00:00:00Z' } = {}) {
|
|
37
|
+
const state = { client: undefined, topic: undefined };
|
|
38
|
+
return {
|
|
39
|
+
async nextTopic(after) {
|
|
40
|
+
const sql = after === null ? 'SELECT topic FROM metrics ORDER BY topic LIMIT 1'
|
|
41
|
+
: 'SELECT topic FROM metrics WHERE topic > $1 ORDER BY topic LIMIT 1';
|
|
42
|
+
const result = await pool.query(sql, after === null ? [] : [after]);
|
|
43
|
+
return result.rows[0]?.topic ?? null;
|
|
44
|
+
},
|
|
45
|
+
async upper(topic) {
|
|
46
|
+
const result = await pool.query(`SELECT ${timestamp} AS ts FROM metrics WHERE topic=$1 ORDER BY metrics.ts DESC LIMIT 1`, [topic]);
|
|
47
|
+
return result.rows[0]?.ts ?? null;
|
|
48
|
+
},
|
|
49
|
+
async page(topic, _after, upper, size) {
|
|
50
|
+
if (!Number.isSafeInteger(size) || size < 1 || size > 100000) { throw new RangeError('Invalid telemetry page size'); }
|
|
51
|
+
if (!state.client) { await declare(pool, state, topic, upper, from); }
|
|
52
|
+
if (state.topic !== topic) { throw new Error('Source cursor belongs to another topic'); }
|
|
53
|
+
try {
|
|
54
|
+
const result = await state.client.query(`FETCH FORWARD ${size} FROM telemetry_rows`);
|
|
55
|
+
if (result.rows.length === 0) { await finish(state, 'COMMIT'); }
|
|
56
|
+
return result.rows;
|
|
57
|
+
} catch (error) {
|
|
58
|
+
await finish(state, 'ROLLBACK');
|
|
59
|
+
throw error;
|
|
60
|
+
}
|
|
61
|
+
},
|
|
62
|
+
close() { return finish(state, 'ROLLBACK'); }
|
|
63
|
+
};
|
|
64
|
+
}
|
|
@@ -19,6 +19,11 @@ export function holdClient(pool) {
|
|
|
19
19
|
return pool;
|
|
20
20
|
}
|
|
21
21
|
|
|
22
|
+
/** Open a pool for an application-owned connection and handle idle socket errors. */
|
|
23
|
+
export function openPostgresPool(connectionString) {
|
|
24
|
+
return holdClient(new pg.Pool({ connectionString }));
|
|
25
|
+
}
|
|
26
|
+
|
|
22
27
|
/**
|
|
23
28
|
* Creates a PostgreSQL pool for supervisor state reads.
|
|
24
29
|
*
|
|
@@ -39,5 +44,5 @@ export default function postgresPool(options = {}) {
|
|
|
39
44
|
if (!url) {
|
|
40
45
|
return undefined;
|
|
41
46
|
}
|
|
42
|
-
return
|
|
47
|
+
return openPostgresPool(url);
|
|
43
48
|
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import Database from 'better-sqlite3';
|
|
2
|
+
|
|
3
|
+
function documentOf(input) {
|
|
4
|
+
return { taskId: input.taskId, stateVersion: input.stateVersion, compatibilityKey: input.compatibilityKey,
|
|
5
|
+
checkpoint: input.checkpoint, pending: input.pending };
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
function taskState(db, maxBytes) {
|
|
9
|
+
db.exec('CREATE TABLE IF NOT EXISTS collector_task_state (task_id TEXT PRIMARY KEY, version INTEGER NOT NULL, document TEXT NOT NULL)');
|
|
10
|
+
const select = db.prepare('SELECT version, document FROM collector_task_state WHERE task_id = ?');
|
|
11
|
+
const insert = db.prepare('INSERT INTO collector_task_state (task_id, version, document) VALUES (?, 1, ?) ON CONFLICT(task_id) DO NOTHING');
|
|
12
|
+
const update = db.prepare('UPDATE collector_task_state SET version = version + 1, document = ? WHERE task_id = ? AND version = ?');
|
|
13
|
+
return {
|
|
14
|
+
load(taskId) {
|
|
15
|
+
const row = select.get(taskId);
|
|
16
|
+
if (!row) { return Promise.resolve(null); }
|
|
17
|
+
return Promise.resolve({ ...JSON.parse(row.document), version: Number(row.version) });
|
|
18
|
+
},
|
|
19
|
+
commit(input) {
|
|
20
|
+
if (!Number.isSafeInteger(input.expectedVersion) || input.expectedVersion < 0) { throw new TypeError('Invalid expectedVersion'); }
|
|
21
|
+
if (input.ownership !== undefined) { throw new Error('This store has no external ownership integration'); }
|
|
22
|
+
const json = JSON.stringify(documentOf(input));
|
|
23
|
+
if (Buffer.byteLength(json) > maxBytes) { throw new Error('Task state capacity exceeded'); }
|
|
24
|
+
const result = input.expectedVersion === 0 ? insert.run(input.taskId, json) : update.run(json, input.taskId, input.expectedVersion);
|
|
25
|
+
if (!result.changes) { throw new Error('Task state conflict'); }
|
|
26
|
+
return Promise.resolve(input.expectedVersion + 1);
|
|
27
|
+
},
|
|
28
|
+
close() { db.close(); }
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** SQLite CAS store with the same load/commit shape as the PostgreSQL runtime table. */
|
|
33
|
+
export default function taskStateSqlite(file, { maxBytes = 1048576 } = {}) {
|
|
34
|
+
const db = new Database(file);
|
|
35
|
+
try { return taskState(db, maxBytes); }
|
|
36
|
+
catch (error) { db.close(); throw error; }
|
|
37
|
+
}
|
|
@@ -13,8 +13,22 @@ export default function stateDataFromPool(pool, options = {}) {
|
|
|
13
13
|
segments: segmentStatePg(pool),
|
|
14
14
|
alerts: alertsStatePg(pool),
|
|
15
15
|
metrics,
|
|
16
|
-
history: metricsEnabled ? historyPg(pool, { retentionDays: options.historyRetentionDays ?? 30 }) : undefined,
|
|
17
|
-
checkpoints: checkpointStatePg(pool, metricsEnabled),
|
|
16
|
+
history: metricsEnabled ? historyPg(pool, { retentionDays: options.historyRetentionDays ?? 30, ...options.historyPolicy }) : undefined,
|
|
17
|
+
checkpoints: checkpointStatePg(pool, metricsEnabled, options.checkpointPolicy),
|
|
18
18
|
operations: operationStatePg(pool)
|
|
19
19
|
};
|
|
20
20
|
}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
/** Route telemetry and checkpoint readings to the selected backend, preserving business state. */
|
|
24
|
+
export function withTelemetryState(data, metrics, history = data.history) {
|
|
25
|
+
return {
|
|
26
|
+
...data,
|
|
27
|
+
metrics,
|
|
28
|
+
history,
|
|
29
|
+
checkpoints: {
|
|
30
|
+
...data.checkpoints,
|
|
31
|
+
readings(topics, from) { return metrics.readings(topics, from); }
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
|
|
3
|
+
export function canonicalJSON(value) {
|
|
4
|
+
if (Array.isArray(value)) { return `[${value.map(canonicalJSON).join(',')}]`; }
|
|
5
|
+
if (value && typeof value === 'object') {
|
|
6
|
+
return `{${Object.keys(value).sort().map((key) => {
|
|
7
|
+
return `${JSON.stringify(key)}:${canonicalJSON(value[key])}`;
|
|
8
|
+
}).join(',')}}`;
|
|
9
|
+
}
|
|
10
|
+
return JSON.stringify(value);
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function jsonDigest(value) {
|
|
14
|
+
return createHash('sha256').update(canonicalJSON(value)).digest('hex');
|
|
15
|
+
}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { canonicalJSON } from './canonicalJSON.js';
|
|
2
|
+
|
|
3
|
+
function identifier(name) {
|
|
4
|
+
if (typeof name !== 'string' || !name || name.includes('\0')) { throw new Error('Invalid PostgreSQL identifier'); }
|
|
5
|
+
return `"${name.replaceAll('"', '""')}"`;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
async function transaction(pool, begin, operation) {
|
|
9
|
+
const client = await pool.connect();
|
|
10
|
+
try {
|
|
11
|
+
await client.query(begin);
|
|
12
|
+
const result = await operation(client);
|
|
13
|
+
await client.query('COMMIT');
|
|
14
|
+
return result;
|
|
15
|
+
} catch (error) {
|
|
16
|
+
await client.query('ROLLBACK').catch(() => { return undefined; });
|
|
17
|
+
throw error;
|
|
18
|
+
} finally { client.release(); }
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function validateRows(snapshot) {
|
|
22
|
+
snapshot.schema.forEach(({ table, columns }) => {
|
|
23
|
+
const keys = canonicalJSON(columns.map((column) => { return column.name; }).sort());
|
|
24
|
+
if (snapshot.tables[table].some((row) => { return !row || canonicalJSON(Object.keys(row).sort()) !== keys; })) {
|
|
25
|
+
throw new Error('Snapshot columns do not match');
|
|
26
|
+
}
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
async function schemaFor(client, namespace, tables) {
|
|
31
|
+
const result = await client.query(`SELECT c.relname AS "table", a.attname AS name,
|
|
32
|
+
pg_catalog.format_type(a.atttypid,a.atttypmod) AS type, NOT a.attnotnull AS nullable
|
|
33
|
+
FROM pg_catalog.pg_attribute a JOIN pg_catalog.pg_class c ON c.oid=a.attrelid
|
|
34
|
+
JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace
|
|
35
|
+
WHERE n.nspname=$1 AND c.relname=ANY($2::text[]) AND a.attnum>0 AND NOT a.attisdropped
|
|
36
|
+
ORDER BY c.relname,a.attnum`, [namespace, tables]);
|
|
37
|
+
return [...tables].sort().map((table) => {
|
|
38
|
+
return { table, columns: result.rows.filter((row) => { return row.table === table; })
|
|
39
|
+
.map(({ name, type, nullable }) => { return { name, type, nullable }; }) };
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function checkpointStatements(table) {
|
|
44
|
+
return {
|
|
45
|
+
latest: `SELECT hash,exported_at AS "exportedAt",imported_at AS "importedAt" FROM ${table} WHERE id=1`,
|
|
46
|
+
ensure: `CREATE TABLE IF NOT EXISTS ${table}
|
|
47
|
+
(id integer PRIMARY KEY CHECK(id=1), hash text NOT NULL, exported_at timestamptz NOT NULL, imported_at timestamptz NOT NULL)`,
|
|
48
|
+
save: `INSERT INTO ${table} (id,hash,exported_at,imported_at)
|
|
49
|
+
VALUES (1,$1,$2,clock_timestamp()) ON CONFLICT(id) DO UPDATE
|
|
50
|
+
SET hash=EXCLUDED.hash,exported_at=EXCLUDED.exported_at,imported_at=EXCLUDED.imported_at
|
|
51
|
+
RETURNING hash,exported_at AS "exportedAt",imported_at AS "importedAt"`
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function tableReader(client, qualified) {
|
|
56
|
+
return async (table) => {
|
|
57
|
+
if (!qualified.has(table)) { throw new Error('Table outside snapshot schema'); }
|
|
58
|
+
const result = await client.query(`SELECT row_to_json(row) AS value FROM ${qualified.get(table)} row`);
|
|
59
|
+
return result.rows.map((row) => { return row.value; });
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
async function replaceRows(client, snapshot, qualified, { cascade, disableTriggers }) {
|
|
64
|
+
if (disableTriggers) { await client.query('SET LOCAL session_replication_role=replica'); }
|
|
65
|
+
await client.query(`TRUNCATE ${[...qualified.values()].join(',')}${cascade ? ' CASCADE' : ''}`);
|
|
66
|
+
for (const [name, table] of qualified) {
|
|
67
|
+
// Insert in catalog order because later tables can reference earlier tables.
|
|
68
|
+
// eslint-disable-next-line no-await-in-loop
|
|
69
|
+
await client.query(`INSERT INTO ${table} SELECT * FROM json_populate_recordset(NULL::${table}, $1::json)`,
|
|
70
|
+
[JSON.stringify(snapshot.tables[name])]);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Replicate an explicit table catalog and atomically record its checkpoint in PostgreSQL. */
|
|
75
|
+
export function postgresSnapshotReplica({
|
|
76
|
+
namespace = 'public', tables, format, checkpoint, lock, compatible, cascade = false, disableTriggers = false
|
|
77
|
+
}) {
|
|
78
|
+
function qualify(name) { return `${identifier(namespace)}.${identifier(name)}`; }
|
|
79
|
+
if (tables.includes(checkpoint)) { throw new Error('Checkpoint table must be outside snapshot schema'); }
|
|
80
|
+
const qualified = new Map(tables.map((name) => { return [name, qualify(name)]; }));
|
|
81
|
+
const state = checkpointStatements(qualify(checkpoint));
|
|
82
|
+
function schema(client) { return schemaFor(client, namespace, tables); }
|
|
83
|
+
|
|
84
|
+
function exportSnapshot(pool) {
|
|
85
|
+
return transaction(pool, 'BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY', async (client) => {
|
|
86
|
+
await client.query("SET LOCAL TIME ZONE 'UTC'");
|
|
87
|
+
await client.query("SET LOCAL bytea_output='hex'");
|
|
88
|
+
const localSchema = await schema(client);
|
|
89
|
+
const read = tableReader(client, qualified);
|
|
90
|
+
const rows = [];
|
|
91
|
+
for (const name of tables) {
|
|
92
|
+
// The transaction's PostgreSQL client supports one query at a time.
|
|
93
|
+
// eslint-disable-next-line no-await-in-loop
|
|
94
|
+
rows.push([name, await read(name)]);
|
|
95
|
+
}
|
|
96
|
+
return format.seal({ schema: localSchema, tables: Object.fromEntries(rows) });
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function importSnapshot(pool, input) {
|
|
101
|
+
const snapshot = format.validate(input);
|
|
102
|
+
validateRows(snapshot);
|
|
103
|
+
return transaction(pool, 'BEGIN', async (client) => {
|
|
104
|
+
await client.query('SELECT pg_advisory_xact_lock($1::bigint)', [lock]);
|
|
105
|
+
if (canonicalJSON(await schema(client)) !== canonicalJSON(snapshot.schema)
|
|
106
|
+
|| compatible && !await compatible(snapshot, tableReader(client, qualified))) {
|
|
107
|
+
throw new Error('Snapshot does not match the local PostgreSQL schema or identity');
|
|
108
|
+
}
|
|
109
|
+
await client.query(state.ensure);
|
|
110
|
+
const previous = await client.query(state.latest);
|
|
111
|
+
if (previous.rows[0]?.hash !== snapshot.hash) {
|
|
112
|
+
await replaceRows(client, snapshot, qualified, { cascade, disableTriggers });
|
|
113
|
+
}
|
|
114
|
+
const result = await client.query(state.save, [snapshot.hash, snapshot.createdAt]);
|
|
115
|
+
return result.rows[0];
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
async function checkpointFor(pool) {
|
|
120
|
+
const result = await transaction(pool, 'BEGIN', async (client) => {
|
|
121
|
+
await client.query('SELECT pg_advisory_xact_lock($1::bigint)', [lock]);
|
|
122
|
+
await client.query(state.ensure);
|
|
123
|
+
return client.query(state.latest);
|
|
124
|
+
});
|
|
125
|
+
return result.rows[0] || null;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
return { schema, exportSnapshot, importSnapshot, checkpointFor };
|
|
129
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import pg from 'pg';
|
|
2
|
+
|
|
3
|
+
function connect({ connectionString, onDatabaseError, poolOptions }) {
|
|
4
|
+
const pool = new pg.Pool({ connectionString, max: 2, options: '-c statement_timeout=20000', connectionTimeoutMillis: 10000, ...poolOptions });
|
|
5
|
+
pool.on('error', () => { onDatabaseError?.(); });
|
|
6
|
+
return pool;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
function listen(server, { port, host = '127.0.0.1' }, pool, worker) {
|
|
10
|
+
const number = Number(port);
|
|
11
|
+
if (!Number.isSafeInteger(number) || number < 1 || number > 65535) { throw new Error('PostgreSQL snapshot server port is invalid'); }
|
|
12
|
+
server.listen(number, host);
|
|
13
|
+
function close() { server.close(); }
|
|
14
|
+
async function release() {
|
|
15
|
+
process.off('SIGTERM', close);
|
|
16
|
+
process.off('SIGINT', close);
|
|
17
|
+
if (worker) { await worker.stop(); }
|
|
18
|
+
await pool.end();
|
|
19
|
+
}
|
|
20
|
+
server.once('close', () => { void release(); });
|
|
21
|
+
process.once('SIGTERM', close);
|
|
22
|
+
process.once('SIGINT', close);
|
|
23
|
+
return server;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function servePostgresSnapshot(settings, createServer) {
|
|
27
|
+
const pool = connect(settings);
|
|
28
|
+
try { return listen(createServer(pool), settings, pool); }
|
|
29
|
+
catch (error) { void pool.end(); throw error; }
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export async function followPostgresSnapshot(settings, createWorker) {
|
|
33
|
+
const pool = connect(settings);
|
|
34
|
+
try {
|
|
35
|
+
const worker = await createWorker(pool);
|
|
36
|
+
const server = listen(worker.server, settings, pool, worker);
|
|
37
|
+
worker.start();
|
|
38
|
+
return server;
|
|
39
|
+
} catch (error) { await pool.end(); throw error; }
|
|
40
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { writeFile } from 'node:fs/promises';
|
|
2
|
+
import { createServer } from 'node:http';
|
|
3
|
+
|
|
4
|
+
function samples(state) {
|
|
5
|
+
const imported = state.checkpoint ? Date.parse(state.checkpoint.importedAt) / 1000 : 0;
|
|
6
|
+
const exported = state.checkpoint ? Date.parse(state.checkpoint.exportedAt) / 1000 : 0;
|
|
7
|
+
return {
|
|
8
|
+
ready: state.checkpoint ? 1 : 0,
|
|
9
|
+
last_success_timestamp_seconds: imported,
|
|
10
|
+
snapshot_timestamp_seconds: exported,
|
|
11
|
+
snapshot_age_seconds: exported ? Math.max(0, Date.now() / 1000 - exported) : 0,
|
|
12
|
+
sync_errors_total: state.errors,
|
|
13
|
+
last_attempt_success: state.lastAttempt ? 1 : 0,
|
|
14
|
+
tls_renewal_errors_total: state.tlsErrors,
|
|
15
|
+
tls_last_success_timestamp_seconds: state.tlsSuccess
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function status(state, prefix, incoming, response) {
|
|
20
|
+
if (incoming.method !== 'GET') { response.writeHead(405).end(); }
|
|
21
|
+
else if (incoming.url === '/healthz') {
|
|
22
|
+
response.writeHead(state.checkpoint ? 200 : 503, { 'Content-Type': 'application/json' })
|
|
23
|
+
.end(JSON.stringify({ ready: Boolean(state.checkpoint) }));
|
|
24
|
+
} else if (incoming.url === '/metrics') {
|
|
25
|
+
const metrics = Object.entries(samples(state)).map(([name, value]) => { return `${prefix}_${name} ${value}`; });
|
|
26
|
+
response.writeHead(200, { 'Content-Type': 'text/plain; version=0.0.4' }).end(`${metrics.join('\n')}\n`);
|
|
27
|
+
} else { response.writeHead(404).end(); }
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Readiness follows the local checkpoint. Remote failures are reported separately. */
|
|
31
|
+
export async function snapshotSync({
|
|
32
|
+
checkpoint, fetchSnapshot, applySnapshot, renewTLS, stateFile, interval = 60000, metricPrefix = 'snapshot_replica'
|
|
33
|
+
}) {
|
|
34
|
+
if (!/^[a-zA-Z_:][a-zA-Z0-9_:]*$/u.test(metricPrefix)) { throw new Error('Invalid replica metric prefix'); }
|
|
35
|
+
const state = { checkpoint: await checkpoint(), errors: 0, lastAttempt: false, tlsErrors: 0, tlsSuccess: 0 };
|
|
36
|
+
const server = createServer((incoming, response) => { status(state, metricPrefix, incoming, response); });
|
|
37
|
+
let timer;
|
|
38
|
+
let stopped = false;
|
|
39
|
+
let running;
|
|
40
|
+
async function update() {
|
|
41
|
+
try {
|
|
42
|
+
state.checkpoint = await applySnapshot(await fetchSnapshot());
|
|
43
|
+
state.lastAttempt = true;
|
|
44
|
+
if (stateFile) { await writeFile(stateFile, JSON.stringify(state.checkpoint), { mode: 0o600 }); }
|
|
45
|
+
} catch { state.errors += 1; state.lastAttempt = false; }
|
|
46
|
+
}
|
|
47
|
+
async function renewal() {
|
|
48
|
+
try {
|
|
49
|
+
if (renewTLS && await renewTLS()) { state.tlsSuccess = Date.now() / 1000; }
|
|
50
|
+
} catch { state.tlsErrors += 1; }
|
|
51
|
+
}
|
|
52
|
+
async function poll() {
|
|
53
|
+
await Promise.all([update(), renewal()]);
|
|
54
|
+
if (!stopped) { timer = setTimeout(() => { running = poll(); }, interval); }
|
|
55
|
+
}
|
|
56
|
+
return {
|
|
57
|
+
server,
|
|
58
|
+
start() { if (!running && !stopped) { running = poll(); } },
|
|
59
|
+
async stop() { stopped = true; clearTimeout(timer); await running; }
|
|
60
|
+
};
|
|
61
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { canonicalJSON, jsonDigest } from './canonicalJSON.js';
|
|
2
|
+
|
|
3
|
+
export const tableSnapshotLimit = 64 * 1024 * 1024;
|
|
4
|
+
|
|
5
|
+
function compareRows(first, second) {
|
|
6
|
+
const before = canonicalJSON(first);
|
|
7
|
+
const after = canonicalJSON(second);
|
|
8
|
+
if (before < after) { return -1; }
|
|
9
|
+
if (before > after) { return 1; }
|
|
10
|
+
return 0;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function fail() { throw new Error('Table snapshot is invalid or incompatible'); }
|
|
14
|
+
|
|
15
|
+
function tableSet(value, names, sortedNames) {
|
|
16
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)
|
|
17
|
+
|| canonicalJSON(Object.keys(value).sort()) !== sortedNames) { fail(); }
|
|
18
|
+
if (names.some((table) => { return !Array.isArray(value[table]); })) { fail(); }
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function schemaValid(schema, sortedNames) {
|
|
22
|
+
if (!Array.isArray(schema)
|
|
23
|
+
|| canonicalJSON(schema.map((item) => { return item?.table; }).sort()) !== sortedNames) { fail(); }
|
|
24
|
+
if (schema.some((item) => { return !Array.isArray(item.columns) || !item.columns.length
|
|
25
|
+
|| item.columns.some((column) => { return typeof column?.name !== 'string' || typeof column.type !== 'string'
|
|
26
|
+
|| typeof column.nullable !== 'boolean'; }); })) { fail(); }
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Sorts opaque table rows and hashes the content independently of the export timestamp. */
|
|
30
|
+
export function tableSnapshotFormat({ tables: names, format, metadata = () => { return {}; } }) {
|
|
31
|
+
const sortedNames = canonicalJSON([...names].sort());
|
|
32
|
+
function seal({ schema, tables, createdAt = new Date().toISOString() }) {
|
|
33
|
+
tableSet(tables, names, sortedNames);
|
|
34
|
+
schemaValid(schema, sortedNames);
|
|
35
|
+
if (!Number.isFinite(Date.parse(createdAt))) { fail(); }
|
|
36
|
+
const sorted = Object.fromEntries(names.map((name) => {
|
|
37
|
+
return [name, [...tables[name]].sort(compareRows)];
|
|
38
|
+
}));
|
|
39
|
+
const content = { ...metadata(sorted), format, schemaHash: jsonDigest(schema), tables: sorted };
|
|
40
|
+
return { ...content, schema, createdAt, hash: jsonDigest(content) };
|
|
41
|
+
}
|
|
42
|
+
function validate(value, { maxBytes = tableSnapshotLimit } = {}) {
|
|
43
|
+
if (!value || Buffer.byteLength(JSON.stringify(value)) > maxBytes) { fail(); }
|
|
44
|
+
const expected = seal(value);
|
|
45
|
+
const fields = Object.keys(expected).filter((key) => { return !['schema', 'createdAt', 'tables'].includes(key); });
|
|
46
|
+
if (fields.some((key) => { return canonicalJSON(value[key]) !== canonicalJSON(expected[key]); })) { fail(); }
|
|
47
|
+
return expected;
|
|
48
|
+
}
|
|
49
|
+
return { seal, validate };
|
|
50
|
+
}
|
|
@@ -79,7 +79,7 @@ function modbusPollingSource(options) {
|
|
|
79
79
|
* collector via pollingSource.
|
|
80
80
|
*
|
|
81
81
|
* @example
|
|
82
|
-
* const source = modbusSource('192.
|
|
82
|
+
* const source = modbusSource('192.0.2.148', 502, 4000, 14, 5, collector, clock);
|
|
83
83
|
* source.start();
|
|
84
84
|
*
|
|
85
85
|
* @param {string} host - Modbus TCP host address
|
|
@@ -43,7 +43,7 @@ function connectParams(parsed, options) {
|
|
|
43
43
|
*
|
|
44
44
|
* @example
|
|
45
45
|
* await stompSend('stomp://rabbitmq:61613', '/exchange/scada.user_decisions',
|
|
46
|
-
* { machine: '
|
|
46
|
+
* { machine: 'drive2', start: 1700000000, user: 'hmi', tags: ['heating'] },
|
|
47
47
|
* { login: 'guest', passcode: 'guest', host: '/' });
|
|
48
48
|
*
|
|
49
49
|
* @param {string} url - STOMP broker URL
|