@yarkivaev/scada 2.13.0 → 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/index.js +29 -0
- 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/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/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/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/telemetry/edgeTelemetryRuntime.js +83 -0
- package/src/infrastructure/ingest/telemetry/replayStoredTelemetry.js +125 -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/opcua/health.js +91 -0
- package/src/infrastructure/opcua/index.js +1 -0
- package/src/infrastructure/persistence/pg/prepareRuntimeRole.js +67 -0
- 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/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/index.js
CHANGED
|
@@ -129,3 +129,32 @@ export { default as postgresTelemetrySource } from './src/infrastructure/persist
|
|
|
129
129
|
export { default as clickhouseTelemetryTarget, assertClickhouseBackfillMode } from './src/infrastructure/persistence/clickhouse/telemetryTarget.js';
|
|
130
130
|
export { default as clickhouseMetricsState } from './src/infrastructure/persistence/clickhouse/metricsState.js';
|
|
131
131
|
export { default as historyTelemetryMetrics } from './src/infrastructure/ingest/telemetry/historyTelemetryMetrics.js';
|
|
132
|
+
|
|
133
|
+
export { default as applyWhenChanged } from './src/infrastructure/deploy/applyWhenChanged.js';
|
|
134
|
+
export { deploymentKube, readKube, verifyKubeNode, preserveKubeRestart } from './src/infrastructure/deploy/deploymentKube.js';
|
|
135
|
+
export { default as preflightKubeStorage } from './src/infrastructure/deploy/preflightKubeStorage.js';
|
|
136
|
+
export { default as postgresMaintenancePlan } from './src/infrastructure/deploy/postgresMaintenancePlan.js';
|
|
137
|
+
export { default as postgresRestoreObjects } from './src/infrastructure/deploy/postgresRestoreObjects.js';
|
|
138
|
+
export { default as operatePostgresMaintenance } from './src/infrastructure/deploy/operatePostgresMaintenance.js';
|
|
139
|
+
export { fetchMutualJSON, readMutualTLS, serveMutualTLS } from './src/infrastructure/tls/mutualJSON.js';
|
|
140
|
+
export { readTLSMaterial, sealTLSMaterial, tlsMaterialLimit, validateTLSMaterial } from './src/infrastructure/tls/tlsMaterial.js';
|
|
141
|
+
export { kubernetesTLSAPI, mirrorTLSSecret } from './src/infrastructure/tls/mirrorTLSSecret.js';
|
|
142
|
+
export { tableSnapshotFormat, tableSnapshotLimit } from './src/infrastructure/replication/tableSnapshotFormat.js';
|
|
143
|
+
export { postgresSnapshotReplica } from './src/infrastructure/replication/postgresSnapshotReplica.js';
|
|
144
|
+
export { snapshotSync } from './src/infrastructure/replication/snapshotSync.js';
|
|
145
|
+
export { default as verifyCollectorCoverage } from './src/infrastructure/deploy/verifyCollectorCoverage.js';
|
|
146
|
+
export { default as verifyPeerBrokerPerimeter } from './src/infrastructure/deploy/verifyPeerBrokerPerimeter.js';
|
|
147
|
+
export { default as mysql40 } from './src/infrastructure/ingest/mysql40/mysql40.js';
|
|
148
|
+
export { default as prepareRuntimeRole } from './src/infrastructure/persistence/pg/prepareRuntimeRole.js';
|
|
149
|
+
export { kubectlPortForward } from './src/infrastructure/management/kubectlPortForward.js';
|
|
150
|
+
export { default as replayStoredTelemetry } from './src/infrastructure/ingest/telemetry/replayStoredTelemetry.js';
|
|
151
|
+
export { followPostgresSnapshot, servePostgresSnapshot } from './src/infrastructure/replication/postgresSnapshotRuntime.js';
|
|
152
|
+
export { default as edgeSitesFromEnv } from './src/infrastructure/messaging/ownership/edgeSitesFromEnv.js';
|
|
153
|
+
export { default as locateMachineMetric } from './src/application/mcp/locateMachineMetric.js';
|
|
154
|
+
export { default as loadMetricSeries } from './src/application/mcp/loadMetricSeries.js';
|
|
155
|
+
export { default as parseBearerTokens } from './src/application/mcp/parseBearerTokens.js';
|
|
156
|
+
export { clickhousePort, cursorPort, postgresPort } from './src/application/mcp/metricQueryPorts.js';
|
|
157
|
+
export { default as prepareKubePrerequisites } from './src/infrastructure/deploy/prepareKubePrerequisites.js';
|
|
158
|
+
export { default as executeKubeSeed } from './src/infrastructure/deploy/executeKubeSeed.js';
|
|
159
|
+
export { default as edgeTelemetryRuntime } from './src/infrastructure/ingest/telemetry/edgeTelemetryRuntime.js';
|
|
160
|
+
export { default as kubeServiceAccount } from './src/infrastructure/management/kubeServiceAccount.js';
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@yarkivaev/scada",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.14.0",
|
|
4
4
|
"description": "SCADA domain objects, state persistence, and plant monitoring",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -20,7 +20,8 @@
|
|
|
20
20
|
"./opcua/config": "./src/infrastructure/opcua/config.js",
|
|
21
21
|
"./runtime": "./src/application/runtime/index.js",
|
|
22
22
|
"./streams": "./src/infrastructure/streams/index.js",
|
|
23
|
-
"./control": "./src/application/control/index.js"
|
|
23
|
+
"./control": "./src/application/control/index.js",
|
|
24
|
+
"./mdmesh": "./src/infrastructure/mdmesh/index.js"
|
|
24
25
|
},
|
|
25
26
|
"bin": {
|
|
26
27
|
"modbus-to-mqtt": "./src/bin/modbus-to-mqtt.js",
|
|
@@ -71,5 +71,5 @@ export function clientFromEnv(env, prefix = 'CONTROL') {
|
|
|
71
71
|
for (const [name, key] of [['CA', 'ca'], ['CERT', 'cert'], ['KEY', 'key']]) {
|
|
72
72
|
if (env[`${prefix}_${name}`]) { tls[key] = readFileSync(env[`${prefix}_${name}`]); }
|
|
73
73
|
}
|
|
74
|
-
return controlClient({ endpoints: (env[`${prefix}_ENDPOINTS`] ?? '').split(',').filter(Boolean), tls, username: env[`${prefix}_USERNAME`], password: env[`${prefix}_PASSWORD`] });
|
|
74
|
+
return controlClient({ endpoints: (env[`${prefix}_ENDPOINTS`] ?? '').split(',').map((endpoint) => { return endpoint.trim(); }).filter(Boolean), tls, username: env[`${prefix}_USERNAME`], password: env[`${prefix}_PASSWORD`] });
|
|
75
75
|
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
function encode(value) {
|
|
2
|
+
return Buffer.from(value).toString('base64');
|
|
3
|
+
}
|
|
4
|
+
|
|
5
|
+
function decode(value) {
|
|
6
|
+
return Buffer.from(value, 'base64').toString('utf8');
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
function rangeEnd(prefix) {
|
|
10
|
+
const bytes = Buffer.from(prefix);
|
|
11
|
+
let index = bytes.length - 1;
|
|
12
|
+
while (index >= 0 && bytes[index] === 255) {
|
|
13
|
+
index -= 1;
|
|
14
|
+
}
|
|
15
|
+
if (index < 0) {
|
|
16
|
+
return encode(Buffer.of(0));
|
|
17
|
+
}
|
|
18
|
+
bytes[index] += 1;
|
|
19
|
+
return encode(bytes.subarray(0, index + 1));
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Stores the first JSON value written for each key under a caller-owned prefix. */
|
|
23
|
+
export default function createOnlyJSON(call, prefix) {
|
|
24
|
+
if (typeof prefix !== 'string' || !prefix) {
|
|
25
|
+
throw new TypeError('A nonempty key prefix is required');
|
|
26
|
+
}
|
|
27
|
+
const end = rangeEnd(prefix);
|
|
28
|
+
return {
|
|
29
|
+
async reserve(id, record) {
|
|
30
|
+
const key = encode(`${prefix}${id}`);
|
|
31
|
+
const body = await call('/v3/kv/txn', {
|
|
32
|
+
compare: [{ key, target: 'VERSION', result: 'EQUAL', version: '0' }],
|
|
33
|
+
success: [{ requestPut: { key, value: encode(JSON.stringify(record)) } }],
|
|
34
|
+
failure: [{ requestRange: { key } }]
|
|
35
|
+
});
|
|
36
|
+
if (body.succeeded === true) {
|
|
37
|
+
return { won: true, record };
|
|
38
|
+
}
|
|
39
|
+
const response = body.responses?.[0];
|
|
40
|
+
const existing = (response?.response_range ?? response?.responseRange)?.kvs?.[0]?.value;
|
|
41
|
+
return { won: false, record: existing ? JSON.parse(decode(existing)) : record };
|
|
42
|
+
},
|
|
43
|
+
async list() {
|
|
44
|
+
const body = await call('/v3/kv/range', { key: encode(prefix), rangeEnd: end });
|
|
45
|
+
return (body.kvs ?? []).map(({ key, value }) => {
|
|
46
|
+
return { id: decode(key).slice(prefix.length), record: JSON.parse(decode(value)) };
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
}
|
|
@@ -5,3 +5,5 @@ export { default as schedule } from './schedule.js';
|
|
|
5
5
|
export { default as assignmentAgent } from './agent.js';
|
|
6
6
|
export { default as controller, reconcile } from './controller.js';
|
|
7
7
|
export function publishCatalog(store, catalog, expectedRevision) { return store.publish(catalog, expectedRevision); }
|
|
8
|
+
export { default as createOnlyJSON } from './createOnlyJSON.js';
|
|
9
|
+
export { default as jsonAssignments } from './jsonAssignments.js';
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
function encoded(value) {
|
|
2
|
+
return Buffer.from(value).toString('base64');
|
|
3
|
+
}
|
|
4
|
+
|
|
5
|
+
function put(key, value) {
|
|
6
|
+
return { key: encoded(key), value: encoded(JSON.stringify(value)) };
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/** Writes independent application records under a caller-owned assignment prefix. */
|
|
10
|
+
export default function jsonAssignments(call, prefix) {
|
|
11
|
+
function key(id) {
|
|
12
|
+
return `${prefix.replace(/\/$/u, '')}/assignments/${id}`;
|
|
13
|
+
}
|
|
14
|
+
return {
|
|
15
|
+
write(id, value) {
|
|
16
|
+
return call('/v3/kv/put', put(key(id), value));
|
|
17
|
+
},
|
|
18
|
+
async compareAndSet(id, revision, value) {
|
|
19
|
+
const path = key(id);
|
|
20
|
+
const version = revision ? { target: 'MOD', 'mod_revision': String(revision) }
|
|
21
|
+
: { target: 'VERSION', version: '0' };
|
|
22
|
+
const result = await call('/v3/kv/txn', {
|
|
23
|
+
compare: [{ key: encoded(path), result: 'EQUAL', ...version }],
|
|
24
|
+
success: [{ 'request_put': put(path, value) }],
|
|
25
|
+
failure: []
|
|
26
|
+
});
|
|
27
|
+
return result?.succeeded === true;
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import locate from './locateMachineMetric.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Reads a sensor series for one measurement mode.
|
|
5
|
+
*
|
|
6
|
+
* @param {object} sensor - plant sensor
|
|
7
|
+
* @param {object} args - from, to, step, mode
|
|
8
|
+
* @returns {Promise<Array>} series rows
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* seriesOf(sensor, { from, to, step: 60 });
|
|
12
|
+
*/
|
|
13
|
+
function seriesOf(sensor, args) {
|
|
14
|
+
const range = { end: new Date(args.to), start: new Date(args.from) };
|
|
15
|
+
const step = args.step * 1000;
|
|
16
|
+
if (args.mode === 'samples') {
|
|
17
|
+
if (typeof sensor.samples !== 'function') {
|
|
18
|
+
throw Object.assign(new Error('Historical raw density is unavailable: this sensor does not support raw samples'), { code: 'SCADA_HISTORY_DENSITY_UNAVAILABLE', status: 409, statusCode: 409 });
|
|
19
|
+
}
|
|
20
|
+
return sensor.samples(range);
|
|
21
|
+
}
|
|
22
|
+
if (args.mode === 'rises') {
|
|
23
|
+
return sensor.rises(range);
|
|
24
|
+
}
|
|
25
|
+
if (args.mode === 'changes') {
|
|
26
|
+
return sensor.changes(range);
|
|
27
|
+
}
|
|
28
|
+
if (args.mode === 'holds') {
|
|
29
|
+
return sensor.holds(range, step);
|
|
30
|
+
}
|
|
31
|
+
return sensor.measurements(range, step);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Maps a sensor row to a coverage or measurement point.
|
|
36
|
+
*
|
|
37
|
+
* @param {object} row - sensor sample
|
|
38
|
+
* @returns {object} point with ts
|
|
39
|
+
*
|
|
40
|
+
* @example
|
|
41
|
+
* pointOf({ timestamp: new Date(), value: 1 });
|
|
42
|
+
*/
|
|
43
|
+
function pointOf(row) {
|
|
44
|
+
const stamp = row.timestamp instanceof Date ? row.timestamp.toISOString() : row.timestamp;
|
|
45
|
+
const point = { ts: stamp, value: row.value };
|
|
46
|
+
if (typeof row.continuous === 'boolean') { point.continuous = row.continuous; }
|
|
47
|
+
return point;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Loads points for one namespace path.
|
|
52
|
+
*
|
|
53
|
+
* @param {object} plant - plant hierarchy
|
|
54
|
+
* @param {string} path - namespace path
|
|
55
|
+
* @param {object} args - from, to, step, mode
|
|
56
|
+
* @returns {Promise<Array>} points
|
|
57
|
+
*
|
|
58
|
+
* @example
|
|
59
|
+
* loadSeries(plant, 'site/unit/power', args);
|
|
60
|
+
*/
|
|
61
|
+
export default async function loadSeries(plant, path, args) {
|
|
62
|
+
const found = locate(plant, path);
|
|
63
|
+
const sensor = found.metric ? found.machine.sensors[found.metric] : undefined;
|
|
64
|
+
if (!sensor) {
|
|
65
|
+
return [];
|
|
66
|
+
}
|
|
67
|
+
const rows = await seriesOf(sensor, args);
|
|
68
|
+
return rows.map(pointOf);
|
|
69
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import machineInPlant from '../machineInPlant.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Finds a plant machine from a namespace path or a bare machine id.
|
|
5
|
+
*
|
|
6
|
+
* @param {object} plant - plant hierarchy
|
|
7
|
+
* @param {string} path - namespace path or machine id
|
|
8
|
+
* @returns {object} machine and optional metric key
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* locate(plant, 'fixture/site/pump/power').metric;
|
|
12
|
+
*/
|
|
13
|
+
export default function locate(plant, path) {
|
|
14
|
+
const parts = path.split('/');
|
|
15
|
+
for (let index = parts.length - 1; index >= 0; index -= 1) {
|
|
16
|
+
const found = machineInPlant(plant, parts[index]);
|
|
17
|
+
if (found) {
|
|
18
|
+
return {
|
|
19
|
+
machine: found.machine,
|
|
20
|
+
metric: index === parts.length - 1 ? '' : parts[parts.length - 1]
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
throw new Error(`Namespace machine is missing: ${path}`);
|
|
25
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import coverageCursor from './coverageCursor.js';
|
|
2
|
+
import locate from './locateMachineMetric.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Wraps a ClickHouse connection as the query_clickhouse port.
|
|
6
|
+
*
|
|
7
|
+
* @param {object} connection - clickhouseConnection
|
|
8
|
+
* @returns {Function} SQL port
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* clickhousePort(connection)('SELECT 1');
|
|
12
|
+
*/
|
|
13
|
+
export function clickhousePort(connection) {
|
|
14
|
+
return function queryClickhouse(sql) {
|
|
15
|
+
return connection.query(sql);
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Wraps a Postgres pool as the query_postgres port.
|
|
21
|
+
*
|
|
22
|
+
* @param {object} pool - pg pool
|
|
23
|
+
* @returns {Function} SQL port
|
|
24
|
+
*
|
|
25
|
+
* @example
|
|
26
|
+
* postgresPort(pool)('SELECT 1');
|
|
27
|
+
*/
|
|
28
|
+
export function postgresPort(pool) {
|
|
29
|
+
return function queryPostgres(sql) {
|
|
30
|
+
return pool.query(sql).then((result) => {
|
|
31
|
+
return result.rows;
|
|
32
|
+
});
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Latest sensor instants for the machine or metric on a path.
|
|
38
|
+
*
|
|
39
|
+
* @param {object} site - plant hierarchy
|
|
40
|
+
* @param {object} args - path
|
|
41
|
+
* @returns {Promise<Array>} samples with ts
|
|
42
|
+
*
|
|
43
|
+
* @example
|
|
44
|
+
* latestSamples(site, { path: 'site/unit/power' });
|
|
45
|
+
*/
|
|
46
|
+
async function latestSamples(site, args) {
|
|
47
|
+
const found = locate(site, args.path);
|
|
48
|
+
if (found.metric && found.machine.sensors[found.metric]) {
|
|
49
|
+
const row = await found.machine.sensors[found.metric].current();
|
|
50
|
+
return row.found ? [{ ts: row.timestamp }] : [];
|
|
51
|
+
}
|
|
52
|
+
const keys = Object.keys(found.machine.sensors || {});
|
|
53
|
+
const rows = await Promise.all(keys.map(async (key) => {
|
|
54
|
+
const row = await found.machine.sensors[key].current();
|
|
55
|
+
return row.found ? { ts: row.timestamp } : null;
|
|
56
|
+
}));
|
|
57
|
+
return rows.filter(Boolean);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Coverage cursor: ingest checkpoint, else latest ClickHouse sample.
|
|
62
|
+
*
|
|
63
|
+
* @param {object|undefined} pool - pg pool
|
|
64
|
+
* @param {object} site - plant hierarchy
|
|
65
|
+
* @returns {Function} cursor port
|
|
66
|
+
*
|
|
67
|
+
* @example
|
|
68
|
+
* cursorPort(pool, site)({ path: 'site/unit' });
|
|
69
|
+
*/
|
|
70
|
+
export function cursorPort(pool, site) {
|
|
71
|
+
const bound = coverageCursor(pool, (args) => {
|
|
72
|
+
return latestSamples(site, args);
|
|
73
|
+
});
|
|
74
|
+
return function cursor(args) {
|
|
75
|
+
const found = locate(site, args.path);
|
|
76
|
+
return bound({ machine: found.machine.name(), path: args.path });
|
|
77
|
+
};
|
|
78
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reads a JSON bearer-to-name map when the env value is an object.
|
|
3
|
+
*
|
|
4
|
+
* @param {string} raw - ANALYTICS_MCP_TOKEN value
|
|
5
|
+
* @returns {object|undefined} map or undefined when the value is a single token
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* parsedMap('{"secret":"analyst"}').analyst;
|
|
9
|
+
*/
|
|
10
|
+
function parsedMap(raw) {
|
|
11
|
+
if (!raw.startsWith('{')) {
|
|
12
|
+
return undefined;
|
|
13
|
+
}
|
|
14
|
+
const parsed = JSON.parse(raw);
|
|
15
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
|
16
|
+
return parsed;
|
|
17
|
+
}
|
|
18
|
+
return undefined;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Builds the analyticsMcp bearer map from ANALYTICS_MCP_TOKEN.
|
|
23
|
+
*
|
|
24
|
+
* A JSON object is bearer → caller name. A single token becomes one named
|
|
25
|
+
* caller `agent`.
|
|
26
|
+
*
|
|
27
|
+
* @param {string} raw - environment value
|
|
28
|
+
* @returns {object} token to caller name
|
|
29
|
+
*
|
|
30
|
+
* @example
|
|
31
|
+
* mcpTokens('fixture-token')['fixture-token'];
|
|
32
|
+
*/
|
|
33
|
+
export default function mcpTokens(raw) {
|
|
34
|
+
if (typeof raw !== 'string' || raw.length === 0) {
|
|
35
|
+
throw new Error('ANALYTICS_MCP_TOKEN is missing');
|
|
36
|
+
}
|
|
37
|
+
const trimmed = raw.trim();
|
|
38
|
+
const mapped = parsedMap(trimmed);
|
|
39
|
+
if (mapped) {
|
|
40
|
+
return mapped;
|
|
41
|
+
}
|
|
42
|
+
return { [trimmed]: 'agent' };
|
|
43
|
+
}
|
|
@@ -7,6 +7,9 @@ function canonical(value) {
|
|
|
7
7
|
}
|
|
8
8
|
return value;
|
|
9
9
|
}
|
|
10
|
+
export function taskSpecHash(spec) {
|
|
11
|
+
return createHash('sha256').update(JSON.stringify(canonical(spec))).digest('hex');
|
|
12
|
+
}
|
|
10
13
|
export function identity(input) {
|
|
11
14
|
if (!input || typeof input.taskId !== 'string' || !/^[\w./:-]{1,200}$/u.test(input.taskId)) {
|
|
12
15
|
throw new TypeError('Invalid taskId');
|
|
@@ -24,7 +27,7 @@ export default function assignment(input, registry) {
|
|
|
24
27
|
});
|
|
25
28
|
const adapter = registry.get(spec.adapter);
|
|
26
29
|
if (!adapter) { throw new TypeError('Unknown task adapter'); }
|
|
27
|
-
const hash =
|
|
30
|
+
const hash = taskSpecHash(spec);
|
|
28
31
|
if (input.specHash && input.specHash !== hash) { throw new TypeError('Invalid specHash'); }
|
|
29
32
|
return { ...input, spec, specHash: hash, adapter };
|
|
30
33
|
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/** Skip kubectl apply when server-side diff reports the live objects already match. */
|
|
2
|
+
export default function applyWhenChanged(execute) {
|
|
3
|
+
return (program, args, options) => {
|
|
4
|
+
if (program !== 'kubectl' || !args.includes('apply') || args.includes('--dry-run=server')) {
|
|
5
|
+
return execute(program, args, options);
|
|
6
|
+
}
|
|
7
|
+
try {
|
|
8
|
+
execute(program, args.map((arg) => { return arg === 'apply' ? 'diff' : arg; }), options);
|
|
9
|
+
return '';
|
|
10
|
+
} catch (error) {
|
|
11
|
+
if (error.status !== 1) { throw error; }
|
|
12
|
+
return execute(program, args, options);
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
|
|
3
|
+
/** Bind every command to an explicit Kubernetes context and namespace. */
|
|
4
|
+
export function deploymentKube({ context, namespace }, execute = execFileSync, options = {}) {
|
|
5
|
+
if (![context, namespace].every((value) => { return typeof value === 'string' && value.trim(); })) {
|
|
6
|
+
throw new TypeError('Kubernetes context and namespace are required');
|
|
7
|
+
}
|
|
8
|
+
return (args, input, capture = false) => {
|
|
9
|
+
return execute('kubectl', ['--context', context, '--namespace', namespace, ...args],
|
|
10
|
+
{ input, encoding: 'utf8', stdio: ['pipe', capture ? 'pipe' : 'inherit', 'inherit'], ...options });
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function readKube(kube, resource, output = 'json') {
|
|
15
|
+
return String(kube(['get', resource, '-o', output], undefined, true)).trim();
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Verify an operation is aimed at the only node in a single-node installation. */
|
|
19
|
+
export function verifyKubeNode(kube, address, name) {
|
|
20
|
+
const { items } = JSON.parse(readKube(kube, 'nodes'));
|
|
21
|
+
const node = items?.[0];
|
|
22
|
+
if (items?.length !== 1 || (name !== undefined && node.metadata?.name !== name)
|
|
23
|
+
|| !node.status?.addresses?.some((row) => { return row.type === 'InternalIP' && row.address === address; })) {
|
|
24
|
+
throw new Error('Kubernetes node identity differs from the selected deployment target');
|
|
25
|
+
}
|
|
26
|
+
return node;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function preserveKubeRestart(kube, workload, annotations, namespace) {
|
|
30
|
+
const prefix = namespace ? ['--namespace', namespace] : [];
|
|
31
|
+
const raw = String(kube([...prefix, 'get', workload, '--ignore-not-found', '-o', 'json'], undefined, true) ?? '').trim();
|
|
32
|
+
const key = 'kubectl.kubernetes.io/restartedAt';
|
|
33
|
+
const restart = raw.startsWith('{') && JSON.parse(raw).spec?.template?.metadata?.annotations?.[key];
|
|
34
|
+
return restart ? { ...annotations, [key]: restart } : annotations;
|
|
35
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { deploymentKube, readKube, verifyKubeNode } from './deploymentKube.js';
|
|
2
|
+
|
|
3
|
+
function verifyDestination(kube, target, allowedPods) {
|
|
4
|
+
verifyKubeNode(kube, target.nodeAddress);
|
|
5
|
+
const { items } = JSON.parse(readKube(kube, 'pods'));
|
|
6
|
+
if (items.some((pod) => { return !['Succeeded', 'Failed'].includes(pod.status?.phase) && !allowedPods.includes(pod.metadata.name); })) {
|
|
7
|
+
throw new Error('Stop all application writers before history seed');
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** Complete all bounded exports before writing to a verified, quiescent destination. */
|
|
12
|
+
export default function executeKubeSeed({ source, destination, transfers, allowedPods }, execute) {
|
|
13
|
+
if (source.context === destination.context) { throw new Error('Separate exact source and destination required'); }
|
|
14
|
+
const options = { timeout: 120000, stdio: ['pipe', 'pipe', 'pipe'] };
|
|
15
|
+
const origin = deploymentKube(source, execute, { ...options, encoding: null, maxBuffer: 64 * 1024 * 1024 });
|
|
16
|
+
const receiver = deploymentKube(destination, execute, { ...options, maxBuffer: 1024 * 1024 });
|
|
17
|
+
verifyDestination(receiver, destination, allowedPods);
|
|
18
|
+
const exports = transfers.map(({ read }) => { return origin(['exec', ...read]); });
|
|
19
|
+
verifyDestination(receiver, destination, allowedPods);
|
|
20
|
+
return transfers.map(({ name, write }, index) => {
|
|
21
|
+
receiver(['exec', '-i', ...write], exports[index]);
|
|
22
|
+
return name;
|
|
23
|
+
});
|
|
24
|
+
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import { deploymentKube } from './deploymentKube.js';
|
|
2
3
|
|
|
3
4
|
/** Retire only explicit Deployments with a single exact app label selector. */
|
|
4
5
|
function validateRetirements(plan) {
|
|
@@ -34,14 +35,6 @@ function validate(plan, action) {
|
|
|
34
35
|
});
|
|
35
36
|
}
|
|
36
37
|
|
|
37
|
-
/** Every Kubernetes command, including the post-rollout hook, shares this target. */
|
|
38
|
-
function kubeAt(plan, execute) {
|
|
39
|
-
return (args, input, capture = false) => {
|
|
40
|
-
return execute('kubectl', ['--context', plan.context, '--namespace', plan.namespace, ...args],
|
|
41
|
-
{ input, encoding: 'utf8', stdio: ['pipe', capture ? 'pipe' : 'inherit', 'inherit'] });
|
|
42
|
-
};
|
|
43
|
-
}
|
|
44
|
-
|
|
45
38
|
function applyWith(kube, manifests, flags, checkOnly) {
|
|
46
39
|
const args = ['apply', ...flags, '-f', '-'];
|
|
47
40
|
kube([...args, '--dry-run=server'], manifests);
|
|
@@ -99,6 +92,11 @@ function applyRelease(plan, action, kube, manifests) {
|
|
|
99
92
|
return '';
|
|
100
93
|
}
|
|
101
94
|
|
|
95
|
+
export function renderRelease(plan, execute = execFileSync) {
|
|
96
|
+
return execute('helm', ['template', plan.release, plan.chart, '--namespace', plan.namespace, '-f', '-'],
|
|
97
|
+
{ input: JSON.stringify(plan.values), encoding: 'utf8' });
|
|
98
|
+
}
|
|
99
|
+
|
|
102
100
|
/**
|
|
103
101
|
* Renders a Helm release and executes the selected kubectl action synchronously.
|
|
104
102
|
* Supply chart, release, namespace and values. Cluster actions additionally require
|
|
@@ -112,10 +110,9 @@ function applyRelease(plan, action, kube, manifests) {
|
|
|
112
110
|
*/
|
|
113
111
|
export default function executeRelease(plan, action = 'render', execute = execFileSync) {
|
|
114
112
|
validate(plan, action);
|
|
115
|
-
const manifests =
|
|
116
|
-
{ input: JSON.stringify(plan.values), encoding: 'utf8' });
|
|
113
|
+
const manifests = renderRelease(plan, execute);
|
|
117
114
|
if (action === 'render') { return manifests; }
|
|
118
|
-
const kube =
|
|
115
|
+
const kube = deploymentKube(plan, execute);
|
|
119
116
|
for (const resource of plan.prerequisites || []) { kube(['get', resource, '-o', 'name']); }
|
|
120
117
|
if (action === 'diff') {
|
|
121
118
|
return kube(['diff', '--server-side', `--field-manager=${plan.fieldManager}`, '-f', '-'], manifests);
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { deploymentKube, readKube, verifyKubeNode } from './deploymentKube.js';
|
|
2
|
+
import postgresRestoreObjects from './postgresRestoreObjects.js';
|
|
3
|
+
|
|
4
|
+
function jobState(job) {
|
|
5
|
+
if (!job) { throw new Error('Restore verification job disappeared'); }
|
|
6
|
+
if (job.status?.succeeded > 0) { return 'complete'; }
|
|
7
|
+
if (job.status?.conditions?.some((condition) => { return condition.type === 'Failed' && condition.status === 'True'; })
|
|
8
|
+
|| (job.status?.failed > 0 && !job.status?.active)) {
|
|
9
|
+
throw new Error('Restore attempt failed; use a new attempt number and fresh scratch storage');
|
|
10
|
+
}
|
|
11
|
+
return 'running';
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function waitVerification(plan, kube, initial) {
|
|
15
|
+
const deadline = Date.now() + 1800000;
|
|
16
|
+
let job = initial;
|
|
17
|
+
while (Date.now() < deadline) {
|
|
18
|
+
if (jobState(job) === 'complete') { return; }
|
|
19
|
+
try {
|
|
20
|
+
kube(['wait', '--for=condition=complete', `job/${plan.verificationName}`, '--timeout=10s']);
|
|
21
|
+
} catch {
|
|
22
|
+
// Check for a terminal Failed state after each short wait.
|
|
23
|
+
}
|
|
24
|
+
job = JSON.parse(readKube(kube, `job/${plan.verificationName}`));
|
|
25
|
+
}
|
|
26
|
+
throw new Error('Restore attempt did not finish in 30 minutes');
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function optionalResource(kube, resource) {
|
|
30
|
+
return JSON.parse(kube(['get', resource, '--ignore-not-found', '-o', 'json']) || 'null');
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function createVerification(plan, pod, kube) {
|
|
34
|
+
if (optionalResource(kube, `persistentvolumeclaim/${plan.verificationName}`)) {
|
|
35
|
+
throw new Error('Restore scratch already exists; use a new attempt number');
|
|
36
|
+
}
|
|
37
|
+
const image = pod.status?.containerStatuses?.[0]?.imageID?.replace(/^docker-pullable:\/\//u, '');
|
|
38
|
+
if (!image?.includes('@sha256:')) { throw new Error('Exact PostgreSQL image digest required'); }
|
|
39
|
+
const items = postgresRestoreObjects(plan, pod.spec.nodeName, image);
|
|
40
|
+
kube(['apply', '--server-side', `--field-manager=${plan.fieldManager}`, '-f', '-'], JSON.stringify({ apiVersion: 'v1', kind: 'List', items }));
|
|
41
|
+
return JSON.parse(readKube(kube, `job/${plan.verificationName}`));
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function verification(plan, pod, kube) {
|
|
45
|
+
const existing = optionalResource(kube, `job/${plan.verificationName}`);
|
|
46
|
+
if (existing && !Object.entries(plan.labels).every(([key, value]) => { return existing.metadata.labels?.[key] === value; })) {
|
|
47
|
+
throw new Error('Restore job ownership differs');
|
|
48
|
+
}
|
|
49
|
+
waitVerification(plan, kube, existing ?? createVerification(plan, pod, kube));
|
|
50
|
+
const log = kube(['logs', `job/${plan.verificationName}`]);
|
|
51
|
+
if (!log.includes('RESTORE_VERIFIED')) { throw new Error('Restore did not report success'); }
|
|
52
|
+
const counts = JSON.parse(log.split('\n').find((line) => { return line.startsWith('{'); }));
|
|
53
|
+
return { target: plan.context, backupId: plan.backupId, verified: true, counts };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function targetPod(plan, kube) {
|
|
57
|
+
const pod = JSON.parse(readKube(kube, `pod/${plan.pod}`));
|
|
58
|
+
if (!pod.spec?.nodeName) { throw new Error('Database pod node identity is missing'); }
|
|
59
|
+
verifyKubeNode(kube, plan.nodeAddress, pod.spec.nodeName);
|
|
60
|
+
if (!pod.spec.volumes?.some((volume) => { return volume.persistentVolumeClaim?.claimName === plan.claim; })) {
|
|
61
|
+
throw new Error('Database claim identity differs from the selected deployment target');
|
|
62
|
+
}
|
|
63
|
+
return pod;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function status(plan, pod) {
|
|
67
|
+
const ready = pod.status.containerStatuses.every((row) => { return row.ready; });
|
|
68
|
+
const claims = pod.spec.volumes.flatMap((row) => { return row.persistentVolumeClaim ? [row.persistentVolumeClaim.claimName] : []; });
|
|
69
|
+
return { target: plan.context, backupId: plan.backupId, ready, claims };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Backup or verify a backup using the selected cluster, workload and claim. */
|
|
73
|
+
export default function operatePostgresMaintenance(plan, action, execute) {
|
|
74
|
+
if (!['plan', 'backup', 'verify-restore', 'status'].includes(action)) { throw new TypeError('Unknown edge data action'); }
|
|
75
|
+
if (action === 'plan') { return plan; }
|
|
76
|
+
if (!plan.enabled) { throw new Error(`${plan.context} deployment disabled: target is offline`); }
|
|
77
|
+
const kube = deploymentKube(plan, execute, { timeout: 1900000, stdio: ['pipe', 'pipe', 'pipe'] });
|
|
78
|
+
const pod = targetPod(plan, kube);
|
|
79
|
+
if (action === 'backup') {
|
|
80
|
+
kube(['exec', plan.pod, '--', ...plan.backupCommand]);
|
|
81
|
+
return { target: plan.context, backupId: plan.backupId, complete: true };
|
|
82
|
+
}
|
|
83
|
+
if (action === 'verify-restore') { return verification(plan, pod, kube); }
|
|
84
|
+
return status(plan, pod);
|
|
85
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
function quote(value) {
|
|
2
|
+
return `'${value.replaceAll("'", "'\"'\"'")}'`;
|
|
3
|
+
}
|
|
4
|
+
|
|
5
|
+
function backupCommand({ directory, database, backupRoot, osUser, runAs }) {
|
|
6
|
+
const script = `set -eu
|
|
7
|
+
umask 077
|
|
8
|
+
backup=${quote(directory)}
|
|
9
|
+
mkdir -p "$backup"
|
|
10
|
+
cd "$backup"
|
|
11
|
+
lock="$backup/.lock"
|
|
12
|
+
if ! mkdir "$lock" 2>/dev/null; then echo 'Backup already in progress' >&2; exit 75; fi
|
|
13
|
+
trap 'rmdir "$lock"' EXIT
|
|
14
|
+
if [ -f complete ]; then sha256sum -c complete; exit 0; fi
|
|
15
|
+
export PGPASSWORD="$POSTGRES_PASSWORD"
|
|
16
|
+
pg_dumpall -U "$POSTGRES_USER" --globals-only > roles.sql.partial
|
|
17
|
+
pg_dump -U "$POSTGRES_USER" -d ${quote(database)} --format=custom --file=${database}.dump.partial
|
|
18
|
+
mv roles.sql.partial roles.sql
|
|
19
|
+
mv ${database}.dump.partial ${database}.dump
|
|
20
|
+
sha256sum roles.sql ${database}.dump > complete.partial
|
|
21
|
+
mv complete.partial complete
|
|
22
|
+
sha256sum -c complete
|
|
23
|
+
`;
|
|
24
|
+
return ['sh', '-ceu', `set -eu; umask 077; mkdir -p ${quote(directory)}; chown ${osUser}:${osUser} ${quote(backupRoot)} ${quote(directory)}; exec ${runAs} ${osUser} sh -ceu ${quote(script)}`];
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function dbBackupPlan(plan, backupId) {
|
|
28
|
+
const backupRoot = `${plan.dataMount}/${plan.backupSubdirectory}`;
|
|
29
|
+
const directory = `${backupRoot}/${backupId}`;
|
|
30
|
+
return { directory, backupCommand: backupCommand({ ...plan, directory, backupRoot }) };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function validatePlan(plan, backupId, attempt) {
|
|
34
|
+
if (!Number.isSafeInteger(attempt) || attempt < 1 || attempt > 999) {
|
|
35
|
+
throw new TypeError('Restore attempt must be 1 through 999');
|
|
36
|
+
}
|
|
37
|
+
if (!/^\d{8}-[a-z0-9][a-z0-9-]{0,29}$/u.test(backupId ?? '')) { throw new TypeError('Safe dated backup id required'); }
|
|
38
|
+
for (const value of [plan.database, plan.restoreRole, plan.osUser]) {
|
|
39
|
+
if (!/^[a-z_][a-z0-9_]*$/u.test(value ?? '')) { throw new TypeError('A simple database and operating system user are required'); }
|
|
40
|
+
}
|
|
41
|
+
if (!/^[a-z][a-z0-9-]*$/u.test(plan.runAs ?? '')) { throw new TypeError('A postgres user-switch command is required'); }
|
|
42
|
+
if (!/^\/(?:[a-zA-Z0-9_-]+\/)*[a-zA-Z0-9_-]+$/u.test(plan.dataMount ?? '')
|
|
43
|
+
|| !/^[a-z0-9-]+$/u.test(plan.backupSubdirectory ?? '')) {
|
|
44
|
+
throw new TypeError('PostgreSQL maintenance requires a data mount and backup subdirectory');
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Add a safe, immutable dated operation ID to a caller-selected database target. */
|
|
49
|
+
export default function postgresMaintenancePlan(plan, backupId, attempt = 1) {
|
|
50
|
+
validatePlan(plan, backupId, attempt);
|
|
51
|
+
const verificationName = `${plan.verificationNamePrefix}-${backupId}${attempt === 1 ? '' : `-r${attempt}`}`;
|
|
52
|
+
const labels = { ...plan.restoreLabels, [plan.backupLabel]: backupId };
|
|
53
|
+
return { ...plan, ...dbBackupPlan(plan, backupId), backupId, verificationName, labels };
|
|
54
|
+
}
|