@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.
Files changed (60) hide show
  1. package/index.js +29 -0
  2. package/package.json +3 -2
  3. package/src/application/control/controlClient.js +1 -1
  4. package/src/application/control/createOnlyJSON.js +50 -0
  5. package/src/application/control/index.js +2 -0
  6. package/src/application/control/jsonAssignments.js +30 -0
  7. package/src/application/mcp/loadMetricSeries.js +69 -0
  8. package/src/application/mcp/locateMachineMetric.js +25 -0
  9. package/src/application/mcp/metricQueryPorts.js +78 -0
  10. package/src/application/mcp/parseBearerTokens.js +43 -0
  11. package/src/application/runtime/assignment.js +4 -1
  12. package/src/infrastructure/deploy/applyWhenChanged.js +15 -0
  13. package/src/infrastructure/deploy/deploymentKube.js +35 -0
  14. package/src/infrastructure/deploy/executeKubeSeed.js +24 -0
  15. package/src/infrastructure/deploy/executeRelease.js +8 -11
  16. package/src/infrastructure/deploy/operatePostgresMaintenance.js +85 -0
  17. package/src/infrastructure/deploy/postgresMaintenancePlan.js +54 -0
  18. package/src/infrastructure/deploy/postgresRestoreObjects.js +73 -0
  19. package/src/infrastructure/deploy/preflightKubeStorage.js +76 -0
  20. package/src/infrastructure/deploy/prepareKubePrerequisites.js +95 -0
  21. package/src/infrastructure/deploy/verifyCollectorCoverage.js +43 -0
  22. package/src/infrastructure/deploy/verifyPeerBrokerPerimeter.js +24 -0
  23. package/src/infrastructure/ingest/mysql40/byteReader.js +51 -0
  24. package/src/infrastructure/ingest/mysql40/mysql40.js +116 -0
  25. package/src/infrastructure/ingest/mysql40/packets.js +72 -0
  26. package/src/infrastructure/ingest/mysql40/resultRows.js +92 -0
  27. package/src/infrastructure/ingest/mysql40/scramble.js +89 -0
  28. package/src/infrastructure/ingest/telemetry/edgeTelemetryRuntime.js +83 -0
  29. package/src/infrastructure/ingest/telemetry/replayStoredTelemetry.js +125 -0
  30. package/src/infrastructure/management/kubeServiceAccount.js +43 -0
  31. package/src/infrastructure/management/kubectlPortForward.js +27 -0
  32. package/src/infrastructure/mdmesh/hmiApplication.js +64 -0
  33. package/src/infrastructure/mdmesh/hmiControl.js +85 -0
  34. package/src/infrastructure/mdmesh/hmiFile.js +69 -0
  35. package/src/infrastructure/mdmesh/hmiMonitor.js +53 -0
  36. package/src/infrastructure/mdmesh/hmiReconcile.js +170 -0
  37. package/src/infrastructure/mdmesh/hmiRuntime.js +33 -0
  38. package/src/infrastructure/mdmesh/index.js +7 -0
  39. package/src/infrastructure/mdmesh/mdmeshClient.js +72 -0
  40. package/src/infrastructure/messaging/ownership/edgeSitesFromEnv.js +137 -0
  41. package/src/infrastructure/messaging/rabbitmq/reconcile.js +71 -12
  42. package/src/infrastructure/opcua/health.js +91 -0
  43. package/src/infrastructure/opcua/index.js +1 -0
  44. package/src/infrastructure/persistence/pg/prepareRuntimeRole.js +67 -0
  45. package/src/infrastructure/replication/canonicalJSON.js +15 -0
  46. package/src/infrastructure/replication/postgresSnapshotReplica.js +129 -0
  47. package/src/infrastructure/replication/postgresSnapshotRuntime.js +40 -0
  48. package/src/infrastructure/replication/snapshotSync.js +61 -0
  49. package/src/infrastructure/replication/tableSnapshotFormat.js +50 -0
  50. package/src/infrastructure/tls/mirrorTLSSecret.js +37 -0
  51. package/src/infrastructure/tls/mutualJSON.js +79 -0
  52. package/src/infrastructure/tls/tlsMaterial.js +57 -0
  53. package/stream-processing/src/main/scala/scada/processing/infra/state/AtomicStateFile.scala +7 -0
  54. package/stream-processing/src/main/scala/scada/processing/infra/state/StateJournal.scala +22 -0
  55. package/stream-processing/src/main/scala/scada/processing/runtime/HistoryClient.scala +10 -1
  56. package/stream-processing/src/main/scala/scada/processing/runtime/LiveWorker.scala +70 -0
  57. package/stream-processing/src/main/scala/scada/processing/runtime/LocalHistory.scala +2 -8
  58. package/stream-processing/src/main/scala/scada/processing/runtime/StatefulHistory.scala +108 -0
  59. package/stream-processing/src/main/scala/scada/processing/runtime/TimelinePublication.scala +43 -0
  60. package/stream-processing/src/main/scala/scada/processing/runtime/WorkerStores.scala +43 -0
@@ -0,0 +1,73 @@
1
+ function quote(value) {
2
+ return `'${value.replaceAll("'", "'\"'\"'")}'`;
3
+ }
4
+
5
+ /** Runs PostgreSQL with a local socket inside the isolated restore container. */
6
+ function restoreScript({ database, restoreRole, verificationSql }) {
7
+ const verify = verificationSql ? `psql -v ON_ERROR_STOP=1 -At -c ${quote(verificationSql)}` : "printf '{}\\n'";
8
+ return `set -eu
9
+ export PGDATA=/restore/pgdata PGHOST=/tmp PGPORT=55432 PGUSER=${restoreRole} PGDATABASE=${database}
10
+ cd /backup
11
+ sha256sum -c complete >/restore/checksum.log
12
+ initdb -D "$PGDATA" -U ${restoreRole} --auth=trust >/restore/initdb.log
13
+ pg_ctl -D "$PGDATA" -l /restore/postgres.log -o "-p 55432 -k /tmp -c listen_addresses='' -c shared_buffers=16MB -c maintenance_work_mem=32MB -c max_connections=10" -w start
14
+ trap 'pg_ctl -D "$PGDATA" -m fast -w stop >/restore/stop.log' EXIT
15
+ sed '/^CREATE ROLE ${restoreRole};$/d; /^CREATE ROLE "${restoreRole}";$/d' /backup/roles.sql | psql -v ON_ERROR_STOP=1 -d postgres >/restore/roles.log
16
+ createdb ${database}
17
+ pg_restore --exit-on-error --dbname=${database} /backup/${database}.dump 2>/restore/restore-errors.log
18
+ ${verify}
19
+ printf 'RESTORE_VERIFIED\\n'
20
+ `;
21
+ }
22
+
23
+ function verificationContainer(plan, image) {
24
+ return {
25
+ name: 'restore',
26
+ image,
27
+ command: ['/bin/sh', '-ceu', restoreScript(plan)],
28
+ resources: { requests: { cpu: '100m', memory: '256Mi' }, limits: { cpu: '500m', memory: '512Mi' } },
29
+ securityContext: { allowPrivilegeEscalation: false, capabilities: { drop: ['ALL'] } },
30
+ volumeMounts: [
31
+ { name: 'backup', mountPath: '/backup', subPath: `${plan.backupSubdirectory}/${plan.backupId}`, readOnly: true },
32
+ { name: 'scratch', mountPath: '/restore' }
33
+ ]
34
+ };
35
+ }
36
+
37
+ /** An isolated restore job reads the source backup and writes only to fresh scratch. */
38
+ export default function postgresRestoreObjects(plan, nodeName, image) {
39
+ const { verificationName: name, namespace, labels } = plan;
40
+ const metadata = { name, namespace, labels };
41
+ return [
42
+ {
43
+ apiVersion: 'v1', kind: 'PersistentVolumeClaim', metadata,
44
+ spec: { accessModes: ['ReadWriteOnce'], storageClassName: plan.storageClass, resources: { requests: { storage: plan.scratchSize } } }
45
+ },
46
+ {
47
+ apiVersion: 'networking.k8s.io/v1', kind: 'NetworkPolicy', metadata,
48
+ spec: { podSelector: { matchLabels: labels }, policyTypes: ['Ingress', 'Egress'], ingress: [], egress: [] }
49
+ },
50
+ {
51
+ apiVersion: 'batch/v1', kind: 'Job', metadata,
52
+ spec: {
53
+ backoffLimit: 0,
54
+ activeDeadlineSeconds: 1800,
55
+ template: {
56
+ metadata: { labels },
57
+ spec: {
58
+ nodeSelector: { 'kubernetes.io/hostname': nodeName },
59
+ restartPolicy: 'Never',
60
+ automountServiceAccountToken: false,
61
+ imagePullSecrets: plan.imagePullSecrets,
62
+ securityContext: { runAsUser: plan.userId, runAsGroup: plan.groupId, fsGroup: plan.groupId, runAsNonRoot: true },
63
+ containers: [verificationContainer(plan, image)],
64
+ volumes: [
65
+ { name: 'backup', persistentVolumeClaim: { claimName: plan.claim, readOnly: true } },
66
+ { name: 'scratch', persistentVolumeClaim: { claimName: name } }
67
+ ]
68
+ }
69
+ }
70
+ }
71
+ }
72
+ ];
73
+ }
@@ -0,0 +1,76 @@
1
+ import { isDeepStrictEqual } from 'node:util';
2
+ import { deploymentKube, readKube, verifyKubeNode } from './deploymentKube.js';
3
+ import { renderRelease } from './executeRelease.js';
4
+
5
+ function requireSecretKeys(kube, secrets) {
6
+ for (const { name, keys } of secrets) {
7
+ if (keys) {
8
+ const present = readKube(kube, `secret/${name}`, 'go-template={{range $k,$v := .data}}{{$k}} {{end}}').split(/\s+/u);
9
+ const missing = keys.filter((key) => { return !present.includes(key); });
10
+ if (missing.length) { throw new Error(`Missing Secret ${name} keys: ${missing.join(', ')}`); }
11
+ } else {
12
+ readKube(kube, `secret/${name}`, 'name');
13
+ }
14
+ }
15
+ }
16
+
17
+ function verifyStorageLayout(kube, { name, volume, mountPath, claim, env, environmentValue }) {
18
+ const { spec } = JSON.parse(readKube(kube, `statefulset/${name}`)).spec.template;
19
+ const container = spec.containers[0];
20
+ if (container.env.find((row) => { return row.name === env; })?.value !== environmentValue
21
+ || container.volumeMounts.find((row) => { return row.name === volume; })?.mountPath !== mountPath
22
+ || spec.volumes.find((row) => { return row.name === volume; })?.persistentVolumeClaim?.claimName !== claim) {
23
+ throw new Error(`Storage data layout differs: ${name}; refusing storage adoption`);
24
+ }
25
+ }
26
+
27
+ function preserveStorageTemplates(kube, storage) {
28
+ for (const { name, values } of storage) {
29
+ const { template } = JSON.parse(readKube(kube, `statefulset/${name}`)).spec;
30
+ if (template.spec.containers[0].image !== values.image) {
31
+ throw new Error(`Storage image differs: ${name}; adoption must preserve it`);
32
+ }
33
+ Object.assign(values, { podTemplate: template });
34
+ }
35
+ }
36
+
37
+ function verifyStorageTemplates(kube, execute, { stage, workloads }, action) {
38
+ const manifests = renderRelease(stage, execute);
39
+ const flags = action === 'adopt' ? ['--field-manager=kubectl-client-side-apply'] : ['--server-side', `--field-manager=${stage.fieldManager}`];
40
+ const response = JSON.parse(kube(['apply', ...flags, '--dry-run=server', '-f', '-', '-o', 'json'], manifests, true));
41
+ const objects = response.items ?? [response];
42
+ for (const name of workloads) {
43
+ const desired = objects.find((row) => { return row.kind === 'StatefulSet' && row.metadata.name === name; });
44
+ const live = JSON.parse(readKube(kube, `statefulset/${name}`));
45
+ if (!desired || !isDeepStrictEqual(desired.spec.template, live.spec.template)) {
46
+ throw new Error(`Storage pod template differs: ${name}; adoption must not restart it`);
47
+ }
48
+ }
49
+ }
50
+
51
+ function verifyVolumeIdentity(kube, { name, claimUid, volumeName, volumeUid }) {
52
+ const live = JSON.parse(readKube(kube, `persistentvolumeclaim/${name}`));
53
+ if (!live.metadata.uid || live.status.phase !== 'Bound' || !live.spec.volumeName
54
+ || (claimUid && claimUid !== live.metadata.uid) || (volumeName && volumeName !== live.spec.volumeName)) {
55
+ throw new Error(`PVC identity mismatch: ${name}`);
56
+ }
57
+ const actualUid = readKube(kube, `persistentvolume/${live.spec.volumeName}`, 'jsonpath={.metadata.uid}');
58
+ if (!actualUid || (volumeUid && volumeUid !== actualUid)) { throw new Error(`PV identity mismatch: ${name}`); }
59
+ }
60
+
61
+ /** Inspect a live single-node deployment before constructing its staged cutover. */
62
+ export default function preflightKubeStorage(plan, action, execute) {
63
+ const kube = deploymentKube(plan, execute);
64
+ requireSecretKeys(kube, plan.secrets ?? []);
65
+ plan.beforeStorage?.(kube);
66
+ verifyKubeNode(kube, plan.nodeAddress);
67
+ for (const layout of plan.layouts ?? []) { verifyStorageLayout(kube, layout); }
68
+ preserveStorageTemplates(kube, plan.preserveTemplates ?? []);
69
+ plan.preserveAnnotations?.(kube);
70
+ if (plan.verifyTemplates) { verifyStorageTemplates(kube, execute, plan.verifyTemplates, action); }
71
+ for (const claim of plan.claims ?? []) { verifyVolumeIdentity(kube, claim); }
72
+ for (const resource of plan.resources ?? []) {
73
+ const prefix = resource.namespace ? ['--namespace', resource.namespace] : [];
74
+ kube([...prefix, 'get', resource.name, '-o', 'name'], undefined, !resource.namespace);
75
+ }
76
+ }
@@ -0,0 +1,95 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { isDeepStrictEqual } from 'node:util';
3
+ import { verifyKubeNode } from './deploymentKube.js';
4
+
5
+ function encoded({ data, stringData }) {
6
+ return { ...data, ...Object.fromEntries(Object.entries(stringData ?? {}).map(([key, value]) => {
7
+ return [key, Buffer.from(value).toString('base64')];
8
+ })) };
9
+ }
10
+
11
+ function objectName({ kind, metadata }) {
12
+ return `${kind}/${metadata.name}`;
13
+ }
14
+
15
+ function objectKey({ name, namespace }) {
16
+ return `${namespace}/${name}`;
17
+ }
18
+
19
+ function clientFor(plan, execute) {
20
+ if (typeof plan.context !== 'string' || !plan.context.trim()) { throw new TypeError('Exact Kubernetes context required'); }
21
+ function kube(namespace, args, input) {
22
+ return String(execute('kubectl', ['--context', plan.context, ...(namespace ? ['--namespace', namespace] : []), ...args],
23
+ { input, encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'], timeout: 30000 }));
24
+ }
25
+ const node = verifyKubeNode((args) => { return kube('', args); }, plan.nodeAddress);
26
+ const podCidrs = node.spec?.podCIDRs ?? [node.spec?.podCIDR].filter(Boolean);
27
+ if (plan.requirePodCidrs && !podCidrs.length) { throw new Error('Verified node pod CIDR required'); }
28
+ function optional(namespace, kind, name) {
29
+ return JSON.parse(kube(namespace, ['get', `${kind}/${name}`, '--ignore-not-found', '-o', 'json']) || 'null');
30
+ }
31
+ const namespaces = new Map(plan.namespaces.map((name) => { return [name, Boolean(optional('', 'namespace', name))]; }));
32
+ return {
33
+ podCidrs,
34
+ get(namespace, kind, name) {
35
+ return namespace && !namespaces.get(namespace) ? null : optional(namespace, kind, name);
36
+ },
37
+ create(object) {
38
+ kube(object.metadata.namespace ?? '', ['create', '-f', '-'], JSON.stringify(object));
39
+ }
40
+ };
41
+ }
42
+
43
+ function credential(request, supplied, found, action) {
44
+ const { name, namespace, keys, type: expectedType } = request;
45
+ if (found && supplied && !isDeepStrictEqual(found.data, encoded(supplied))) { throw new Error(`Existing Secret differs: ${name}`); }
46
+ if (supplied && keys.some((key) => { return !encoded(supplied)[key]; })) { throw new Error(`Missing supplied Secret keys: ${name}`); }
47
+ if (found && keys.some((key) => { return !found.data?.[key]; })) { throw new Error(`Missing existing Secret keys: ${name}`); }
48
+ if (action === 'apply' && !found && !supplied) {
49
+ throw new Error(`Missing prerequisites: provide ${name} through a protected Secret file`);
50
+ }
51
+ const source = supplied ?? found ?? {};
52
+ return { apiVersion: 'v1', kind: 'Secret', metadata: { name, namespace }, type: source.type ?? expectedType ?? 'Opaque', data: encoded(source) };
53
+ }
54
+
55
+ function credentialInputs(requests, secrets, client, action) {
56
+ const targets = new Set(requests.map(objectKey));
57
+ if (secrets.some((item) => { return item.kind !== 'Secret' || !item.metadata || !targets.has(objectKey(item.metadata)); })) {
58
+ throw new Error('Unexpected prerequisite Secret target');
59
+ }
60
+ const resolved = new Map();
61
+ return requests.map((request) => {
62
+ const key = objectKey(request);
63
+ const found = client.get(request.namespace, 'secret', request.name);
64
+ const mirrored = !found && request.copyFrom && resolved.get(objectKey(request.copyFrom));
65
+ const supplied = secrets.find(({ metadata }) => { return objectKey(metadata) === key; })
66
+ ?? (mirrored && request.keys.every((name) => { return mirrored.data[name]; }) ? { data: mirrored.data } : null);
67
+ const object = credential(request, supplied, found, action);
68
+ resolved.set(key, object);
69
+ return object;
70
+ });
71
+ }
72
+
73
+ function verifyExisting(object, client, preserved) {
74
+ const found = client.get(object.metadata.namespace ?? '', object.kind.toLowerCase(), object.metadata.name);
75
+ if (found && object.kind === 'Secret' && !isDeepStrictEqual(found.data, object.data)) {
76
+ throw new Error(`Existing Secret differs: ${object.metadata.name}`);
77
+ }
78
+ if (found) { preserved.push(objectName(object)); }
79
+ return !found;
80
+ }
81
+
82
+ /** Create missing prerequisites without replacing any live resource or credential. */
83
+ export default function prepareKubePrerequisites(plan, action = 'check', { execute = execFileSync, secrets = [] } = {}) {
84
+ if (!['render', 'check', 'apply'].includes(action)) { throw new TypeError('prepare action must be render, check or apply'); }
85
+ if (action === 'render') { return plan.objects([]); }
86
+ const target = plan.context;
87
+ if (action === 'apply' && !plan.enabled) { throw new Error(`${target} deployment disabled: target is offline`); }
88
+ const client = clientFor(plan, execute);
89
+ const objects = [...plan.objects(client.podCidrs), ...credentialInputs(plan.credentials ?? [], secrets, client, action)];
90
+ const preserved = [];
91
+ const pending = objects.filter((object) => { return verifyExisting(object, client, preserved); });
92
+ if (action === 'apply') { pending.forEach(client.create); }
93
+ const names = pending.map(objectName);
94
+ return { target, created: action === 'apply' ? names : [], missing: action === 'check' ? names : [], preserved };
95
+ }
@@ -0,0 +1,43 @@
1
+ import { taskSpecHash } from '../../application/runtime/assignment.js';
2
+
3
+ function nodeIdentity(node, namespace, execute) {
4
+ const response = execute('kubectl', ['--context', node, '--namespace', namespace, '--request-timeout=10s', 'get', 'nodes', '-o', 'json'],
5
+ { encoding: 'utf8', timeout: 15000 });
6
+ const nodes = JSON.parse(response).items;
7
+ if (nodes?.length !== 1 || !nodes[0].metadata?.uid) { throw new Error('Single physical node identity required'); }
8
+ return nodes[0];
9
+ }
10
+ function distinct(local, remote) {
11
+ const ips = local.status?.addresses?.filter((row) => { return row.type === 'InternalIP'; }).map((row) => { return row.address; }) ?? [];
12
+ if (local.metadata.uid === remote.metadata.uid || remote.status?.addresses?.some((row) => { return row.type === 'InternalIP' && ips.includes(row.address); })) {
13
+ throw new Error('Surviving reader must run on another physical node');
14
+ }
15
+ }
16
+ function liveReader(proof, task, { namespace, execute, now, freshnessMs, clockSkewMs, container, statusUrl }) {
17
+ const program = `const r=await fetch(${JSON.stringify(statusUrl)},{signal:AbortSignal.timeout(2000)});if(!r.ok)throw new Error('Reader unavailable');process.stdout.write(await r.text());`;
18
+ const response = execute('kubectl', ['--context', proof.nodeId, '--namespace', namespace, '--request-timeout=10s',
19
+ 'exec', proof.workload, '-c', container, '--', 'node', '--input-type=module', '-e', program], { encoding: 'utf8', timeout: 15000 });
20
+ const status = JSON.parse(response);
21
+ const row = status.tasks?.find((item) => { return item.taskId === task.taskId; });
22
+ const at = now();
23
+ if (status.initialized !== true || status.stopping || status.fatal || row?.state !== 'running'
24
+ || ['failed', 'degraded'].includes(row.health) || row.specHash !== taskSpecHash(task.spec)
25
+ || !Number.isFinite(row.lastRead) || row.lastRead > at + clockSkewMs || at - row.lastRead > freshnessMs) {
26
+ throw new Error(`Fresh surviving reader required: ${task.taskId}`);
27
+ }
28
+ }
29
+ /** Probe a matching controlled collector or temporary static bridge immediately before retirement. */
30
+ export default function verifyCollectorCoverage({ cluster, namespace, tasks, evidence, execute, now = Date.now,
31
+ freshnessMs = 15000, clockSkewMs = 5000, workloads, container = 'collector', statusUrl = 'http://127.0.0.1:9091/status' }) {
32
+ if (!tasks.length) { return; }
33
+ const local = nodeIdentity(cluster, namespace, execute);
34
+ for (const task of tasks) {
35
+ const proof = evidence?.coverage?.find((item) => { return item.taskId === task.taskId; });
36
+ if (!proof || proof.nodeId === cluster || !task.eligibleNodes.includes(proof.nodeId)
37
+ || !workloads?.includes(proof.workload)) {
38
+ throw new Error(`Live surviving reader coverage required: ${task.taskId}`);
39
+ }
40
+ distinct(local, nodeIdentity(proof.nodeId, namespace, execute));
41
+ liveReader(proof, task, { namespace, execute, now, freshnessMs, clockSkewMs, container, statusUrl });
42
+ }
43
+ }
@@ -0,0 +1,24 @@
1
+ import { isDeepStrictEqual } from 'node:util';
2
+ import { readKube } from './deploymentKube.js';
3
+
4
+ /** Bind supplied packet probe evidence to the live broker pod and network policy. */
5
+ export default function verifyPeerBrokerBoundary({ context, policy, allowedPeers, selector, proof, maxAgeMs = 900000 }, kube, now = Date.now()) {
6
+ if (!policy) { return; }
7
+ const verifiedAt = Date.parse(proof?.verifiedAt);
8
+ if (!proof || proof.cluster !== context || !proof.networkPolicyEnforced
9
+ || !isDeepStrictEqual(proof.allowedPeers, [...allowedPeers].sort()) || !proof.deniedSources?.length
10
+ || proof.deniedSources.some((source) => { return allowedPeers.includes(source); })
11
+ || !(verifiedAt <= now && verifiedAt > now - maxAgeMs)) {
12
+ throw new Error('Fresh verified peer broker perimeter coverage evidence required');
13
+ }
14
+ const live = JSON.parse(readKube(kube, `networkpolicy/${policy.metadata.name}`));
15
+ if (live.metadata.uid !== proof.policyUID || live.metadata.resourceVersion !== proof.policyResourceVersion
16
+ || !isDeepStrictEqual(live.spec, policy.spec)) {
17
+ throw new Error('Peer broker perimeter policy changed after packet probes');
18
+ }
19
+ const { items: pods } = JSON.parse(kube(['get', 'pods', '-l', selector, '-o', 'json'], undefined, true));
20
+ if (pods.length !== 1 || pods[0].metadata.uid !== proof.brokerPodUID
21
+ || !pods[0].status.containerStatuses?.every((container) => { return container.ready; })) {
22
+ throw new Error('Peer broker identity changed after perimeter packet probes');
23
+ }
24
+ }
@@ -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
+ }