@yarkivaev/scada 2.18.0 → 2.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.js +17 -0
- package/package.json +4 -2
- package/src/application/cycleTimelineFetch.js +56 -0
- package/src/application/deploy/collectorProcesses.js +1 -0
- package/src/application/deploy/collectorSourcePlan.js +41 -0
- package/src/application/deploy/compileCollectorTasks.js +2 -2
- package/src/application/deploy/edgeDescriptors.js +31 -0
- package/src/application/deploy/fieldbusSourcePlan.js +93 -0
- package/src/application/deploy/plantBindingProfile.js +24 -0
- package/src/application/deploy/topologyGraph.js +81 -0
- package/src/application/edgeOperatorCatalog.js +9 -7
- package/src/application/mcp/analyticsMcpPort.js +20 -0
- package/src/application/mcp/analyticsNamespaceNodes.js +29 -0
- package/src/application/mcp/analyticsTextContent.js +13 -0
- package/src/application/mcp/plantReadPorts.js +168 -0
- package/src/application/mcp/textContentCatalog.js +7 -0
- package/src/application/operationPrefixes.js +67 -0
- package/src/application/operatorCatalogView.js +8 -0
- package/src/application/projectPlantShops.js +17 -0
- package/src/application/runtime/collectorDslManifest.js +44 -0
- package/src/application/runtime/collectorLaunch.js +34 -0
- package/src/application/runtime/collectorOptions.js +21 -0
- package/src/application/runtime/controlDeliveryEnvironment.js +19 -0
- package/src/application/runtime/embeddedCollectors.js +6 -0
- package/src/application/runtime/index.js +7 -1
- package/src/application/runtime/pagedDelivery.js +87 -0
- package/src/application/runtime/resolveSecrets.js +9 -0
- package/src/application/siteOperatorCatalog.js +8 -7
- package/src/application/siteRuntime/checkpointedOperationPoll.js +77 -0
- package/src/application/siteRuntime/cutoverOperations.js +25 -0
- package/src/application/siteRuntime/databaseMigrations.js +27 -0
- package/src/application/siteRuntime/edgeMetricsStore.js +35 -0
- package/src/application/siteRuntime/history.js +29 -0
- package/src/application/siteRuntime/index.js +16 -0
- package/src/application/siteRuntime/measurementTopic.js +9 -0
- package/src/application/siteRuntime/operationFederation.js +15 -0
- package/src/application/siteRuntime/operationSnapshot.js +18 -0
- package/src/application/siteRuntime/operatorField.js +49 -0
- package/src/application/siteRuntime/operatorUpdates.js +37 -0
- package/src/application/siteRuntime/telemetry.js +31 -0
- package/src/application/siteRuntime/telemetryBackfillCommand.js +64 -0
- package/src/application/timelineMetrics.js +36 -0
- package/src/domain/timeline/cyclePhases.js +191 -0
- package/src/domain/timeline/taggedCycleWindows.js +17 -0
- package/src/domain/timeline/taggedSegment.js +47 -0
- package/src/domain/timeline/taggedTimeline.js +98 -0
- package/src/domain/timeline/timelineSegment.js +25 -0
- package/src/infrastructure/deploy/brokerFleetPolicy.js +91 -0
- package/src/infrastructure/deploy/configuredArchivePlan.js +25 -0
- package/src/infrastructure/deploy/configuredBrokerRoutes.js +34 -0
- package/src/infrastructure/deploy/configuredClassification.js +74 -0
- package/src/infrastructure/deploy/configuredCollectorChartDeployment.js +22 -0
- package/src/infrastructure/deploy/configuredControlPlane.js +116 -0
- package/src/infrastructure/deploy/configuredDeploymentCredentials.js +45 -0
- package/src/infrastructure/deploy/configuredEtcdInventory.js +30 -0
- package/src/infrastructure/deploy/configuredRuntimeCapabilities.js +14 -0
- package/src/infrastructure/deploy/configuredSiteAssets.js +50 -0
- package/src/infrastructure/deploy/configuredStagedDeployment.js +48 -0
- package/src/infrastructure/deploy/controlPlaneCli.js +17 -0
- package/src/infrastructure/deploy/highAvailability/configuredBrokerReconciliation.js +21 -0
- package/src/infrastructure/deploy/highAvailability/historyWatermark.js +2 -2
- package/src/infrastructure/deploy/highAvailability/index.js +3 -1
- package/src/infrastructure/deploy/highAvailability/replicaHistoryStore.js +7 -0
- package/src/infrastructure/deploy/index.js +22 -1
- package/src/infrastructure/deploy/mixedStoreHistory.js +27 -0
- package/src/infrastructure/deploy/publicBrokerPlan.js +15 -0
- package/src/infrastructure/deploy/siteBrokerDefinitions.js +97 -0
- package/src/infrastructure/deploy/stagedSitePlan.js +132 -0
- package/src/infrastructure/deploy/supervisedServicePlan.js +82 -0
- package/src/infrastructure/http/edge/attachClassify.js +30 -0
- package/src/infrastructure/http/edge/classifyProxy.js +72 -0
- package/src/infrastructure/http/edge/classifyRecord.js +32 -0
- package/src/infrastructure/http/edge/classifyRouting.js +14 -0
- package/src/infrastructure/http/edge/siteAccess.js +7 -0
- package/src/infrastructure/http/edge/writeGuard.js +84 -0
- package/src/infrastructure/http/plant/routes/machineOperationList.js +18 -0
- package/src/infrastructure/http/plant/routes/operationRoute.js +2 -11
- package/src/infrastructure/http/plant/routes/operatorRoute.js +25 -0
- package/src/infrastructure/http/plant/streams/operationStream.js +25 -37
- package/src/infrastructure/ingest/mqtt/modbusDeviceSpec.js +5 -28
- package/src/infrastructure/ingest/mqtt/registerPoint.js +2 -2
- package/src/infrastructure/mdmesh/adminReconciliation.js +19 -0
- package/src/infrastructure/mdmesh/bootstrapMdmeshCredentials.js +4 -4
- package/src/infrastructure/mdmesh/controllerOperation.js +17 -0
- package/src/infrastructure/mdmesh/index.js +3 -0
- package/src/infrastructure/mdmesh/publishApk.js +30 -0
- package/src/infrastructure/persistence/clickhouse/metricBursts.js +73 -0
- package/src/infrastructure/persistence/pg/cyclePhaseQuery.js +168 -0
- package/src/infrastructure/persistence/pg/cyclePrior.js +96 -0
- package/src/infrastructure/persistence/pg/operatorFieldStore.js +50 -0
- package/src/infrastructure/streams/boundedTextFrames.js +27 -0
- package/src/infrastructure/streams/framedSerialSource.js +25 -0
- package/src/infrastructure/streams/index.js +6 -0
- package/src/infrastructure/streams/namedSerialDevices.js +26 -0
- package/src/infrastructure/streams/pollSnapshot.js +11 -0
- package/src/infrastructure/streams/serialLine.js +26 -0
- package/src/infrastructure/streams/watchCurrentReading.js +31 -0
- package/src/infrastructure/streams/windowPublication.js +73 -0
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
function merged(historic, stored) {
|
|
2
|
+
const byKey = new Map([...historic, ...stored].map((row) => { return [row.key, row]; }));
|
|
3
|
+
return [...byKey.values()].sort((left, right) => { return new Date(left.occurred_at) - new Date(right.occurred_at); });
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
/** Query inclusive intervals split at the first instant owned by the authoritative source. */
|
|
7
|
+
export default function cutoverOperations(historic, authoritative, cutover, { kind, label = kind, caller = 'cutoverOperations' } = {}) {
|
|
8
|
+
if (typeof historic?.list !== 'function') { throw new Error(`ClickHouse ${kind} port with list() is required`); }
|
|
9
|
+
if (typeof authoritative?.listForMachine !== 'function') { throw new Error('Postgres operations port with listForMachine() is required'); }
|
|
10
|
+
if (!(cutover instanceof Date) || Number.isNaN(cutover.getTime())) { throw new Error(`${label} must be a valid Date`); }
|
|
11
|
+
return {
|
|
12
|
+
list(machine, range) {
|
|
13
|
+
if (typeof machine !== 'string' || !machine.length) { throw new Error(`machine must be a non-empty string for ${caller}.list`); }
|
|
14
|
+
if (!(range?.from instanceof Date) || !(range?.to instanceof Date)) {
|
|
15
|
+
throw new Error(`range.from and range.to Date are required for machine ${machine}`);
|
|
16
|
+
}
|
|
17
|
+
const { from, to } = range;
|
|
18
|
+
const before = from < cutover ? historic.list(machine, {
|
|
19
|
+
from, to: to < cutover ? to : new Date(cutover.getTime() - 1)
|
|
20
|
+
}) : [];
|
|
21
|
+
const after = to >= cutover ? authoritative.listForMachine(machine, kind, { from: from > cutover ? from : cutover, to }) : [];
|
|
22
|
+
return Promise.all([before, after]).then(([older, newer]) => { return merged(older, newer); });
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { fileURLToPath } from 'node:url';
|
|
2
|
+
import migrate, { verifyMigrations } from '../../infrastructure/ingest/db/migrate.js';
|
|
3
|
+
|
|
4
|
+
const sharedMigrations = fileURLToPath(new URL('../../../db/migrations', import.meta.url));
|
|
5
|
+
|
|
6
|
+
/** Apply shared schema and optional installation-owned migrations in order. */
|
|
7
|
+
export async function migrateSiteDatabase(pool, profile, { directory, shared = true } = {}) {
|
|
8
|
+
if (shared) { await migrate(pool, sharedMigrations, profile); }
|
|
9
|
+
if (directory) { await migrate(pool, directory, profile); }
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** Choose administrative migration or restricted preflight before starting application routes. */
|
|
13
|
+
export async function prepareSiteDatabase(env, poolFactory, { profile, directory, verify, label }) {
|
|
14
|
+
const mode = env.SUPERVISOR_MIGRATIONS ?? 'apply';
|
|
15
|
+
if (!['apply', 'verify'].includes(mode)) { throw new Error('SUPERVISOR_MIGRATIONS must be apply or verify'); }
|
|
16
|
+
const variable = mode === 'verify' ? 'POSTGRES_URL' : 'POSTGRES_ADMIN_URL';
|
|
17
|
+
if (!env[variable]) { throw new Error(`${variable} is required for ${label} migrations`); }
|
|
18
|
+
const pool = poolFactory(env[variable]);
|
|
19
|
+
try {
|
|
20
|
+
if (mode === 'verify') {
|
|
21
|
+
await verifyMigrations(pool, directory, profile);
|
|
22
|
+
await verify?.(pool);
|
|
23
|
+
} else {
|
|
24
|
+
await migrate(pool, directory, profile);
|
|
25
|
+
}
|
|
26
|
+
} finally { await pool.end(); }
|
|
27
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import foldedMetricsSink from '../foldedMetricsSink.js';
|
|
2
|
+
import { metricsSinkFromPool as pgMetricsSink } from '../../infrastructure/persistence/pg/metrics.js';
|
|
3
|
+
|
|
4
|
+
async function save(connection, devices, records, context, begin) {
|
|
5
|
+
context.signal?.throwIfAborted();
|
|
6
|
+
await connection.query(begin);
|
|
7
|
+
await foldedMetricsSink(pgMetricsSink(connection), connection, devices).write(records, context);
|
|
8
|
+
context.signal?.throwIfAborted();
|
|
9
|
+
await connection.query('COMMIT');
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
async function write(pool, devices, records, { context, begin, timeoutMs }) {
|
|
13
|
+
context.signal?.throwIfAborted();
|
|
14
|
+
const client = await pool.connect();
|
|
15
|
+
const connection = { query(text, values) { return client.query({ text, values, 'query_timeout': timeoutMs }); } };
|
|
16
|
+
let fault;
|
|
17
|
+
try {
|
|
18
|
+
await save(connection, devices, records, context, begin);
|
|
19
|
+
} catch (error) {
|
|
20
|
+
fault = error;
|
|
21
|
+
try { await connection.query('ROLLBACK'); }
|
|
22
|
+
catch (rollback) { throw new AggregateError([error, rollback], 'Edge metrics transaction rollback failed'); }
|
|
23
|
+
throw error;
|
|
24
|
+
} finally { client.release(fault); }
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Commit raw telemetry and derived intervals atomically, serializing writers across replicas. */
|
|
28
|
+
export default function edgeMetricsStore(pool, devices, { lockKey = 'scada:edge-metrics', timeoutMs = 4000 } = {}) {
|
|
29
|
+
if (typeof lockKey !== 'string' || !/^[\w.:-]+$/u.test(lockKey) || !Number.isSafeInteger(timeoutMs) || timeoutMs < 1) {
|
|
30
|
+
throw new TypeError('Invalid metrics transaction lock or deadline');
|
|
31
|
+
}
|
|
32
|
+
const deadline = `'${timeoutMs}ms'`;
|
|
33
|
+
const begin = `BEGIN; SET LOCAL statement_timeout=${deadline}; SET LOCAL lock_timeout=${deadline}; SET LOCAL idle_in_transaction_session_timeout=${deadline}; SELECT pg_advisory_xact_lock(hashtextextended('${lockKey}',0))`;
|
|
34
|
+
return { write(records, context = {}) { return write(pool, devices, records, { context, begin, timeoutMs }); } };
|
|
35
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { historyProtocol } from '../../infrastructure/persistence/pg/history.js';
|
|
2
|
+
import { historyReplicaProtocol } from '../../infrastructure/persistence/pg/historyReplicaOutbox.js';
|
|
3
|
+
|
|
4
|
+
/** Collect history capabilities before reading runtime settings or opening connections. */
|
|
5
|
+
export function historyCapabilities(role, requiredProtocol = historyProtocol) {
|
|
6
|
+
const historyProtocols = historyProtocol === requiredProtocol ? [requiredProtocol] : [];
|
|
7
|
+
if (role === 'site' && historyReplicaProtocol) { historyProtocols.push(historyReplicaProtocol); }
|
|
8
|
+
return { role, historyProtocols };
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function capabilityExit(role, requiredProtocol) {
|
|
12
|
+
if (process.argv.includes('--capabilities')) {
|
|
13
|
+
process.stdout.write(`${JSON.stringify(historyCapabilities(role, requiredProtocol))}\n`);
|
|
14
|
+
process.exit(0);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Validate local history settings and mutually exclusive raw receivers. */
|
|
19
|
+
export function historySettings(env, requiredProtocol = historyProtocol, { defaultDays = 30, maxDays = 365 } = {}) {
|
|
20
|
+
if (env.LOCAL_HISTORY_ENABLED === undefined || env.LOCAL_HISTORY_ENABLED === 'false') { return null; }
|
|
21
|
+
if (env.LOCAL_HISTORY_ENABLED !== 'true') { throw new Error('LOCAL_HISTORY_ENABLED must be true or false'); }
|
|
22
|
+
if (historyProtocol !== requiredProtocol) { throw new Error('Matching Core history protocol required'); }
|
|
23
|
+
const retentionDays = Number(env.HISTORY_RETENTION_DAYS ?? defaultDays);
|
|
24
|
+
if (!Number.isSafeInteger(retentionDays) || retentionDays < 1 || retentionDays > maxDays) {
|
|
25
|
+
throw new Error('Invalid local history retention');
|
|
26
|
+
}
|
|
27
|
+
if (env.HISTORY_AMQP_ENABLED === 'true') { throw new Error('ClickHouse history cannot run a second raw PostgreSQL receiver'); }
|
|
28
|
+
return { retentionDays };
|
|
29
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export { centralTelemetryIngest, orderedMetricsIngest, processTelemetryIngest } from './telemetry.js';
|
|
2
|
+
export { default as edgeMetricsStore } from './edgeMetricsStore.js';
|
|
3
|
+
export { capabilityExit, historyCapabilities, historySettings } from './history.js';
|
|
4
|
+
export { default as measurementTopic } from './measurementTopic.js';
|
|
5
|
+
export { default as operationFederation } from './operationFederation.js';
|
|
6
|
+
export { default as migrate, verifyMigrations } from '../../infrastructure/ingest/db/migrate.js';
|
|
7
|
+
export { centralOperatorsUpdate, edgeOperatorsUpdate } from './operatorUpdates.js';
|
|
8
|
+
export { migrateSiteDatabase, prepareSiteDatabase } from './databaseMigrations.js';
|
|
9
|
+
export { default as cutoverOperations } from './cutoverOperations.js';
|
|
10
|
+
export { default as telemetryBackfillCommand } from './telemetryBackfillCommand.js';
|
|
11
|
+
export { default as clickhouseMetricBursts, metricBurstSql } from '../../infrastructure/persistence/clickhouse/metricBursts.js';
|
|
12
|
+
export { default as checkpointedOperationPoll, operationEventSink } from './checkpointedOperationPoll.js';
|
|
13
|
+
export { default as operatorField } from './operatorField.js';
|
|
14
|
+
export { default as reconcileOperationSnapshot } from './operationSnapshot.js';
|
|
15
|
+
export { default as operatorFieldStore, verifyPostgresRelation } from '../../infrastructure/persistence/pg/operatorFieldStore.js';
|
|
16
|
+
export { operatorFieldRoute } from '../../infrastructure/http/plant/routes/operatorRoute.js';
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import paths from '../deploy/paths.js';
|
|
2
|
+
|
|
3
|
+
/** Find the unique namespace path for a measurement of the requested machine. */
|
|
4
|
+
export default function measurementTopic(machine, key, document, listed) {
|
|
5
|
+
const available = Array.isArray(listed) ? listed : paths(document);
|
|
6
|
+
const matches = available.filter((item) => { return item.endsWith(`/${key}`) && item.split('/').includes(machine); });
|
|
7
|
+
if (matches.length !== 1) { throw new Error(`measurement topic unknown key ${key} on ${machine}`); }
|
|
8
|
+
return matches[0];
|
|
9
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import operationAmqp from '../../infrastructure/sync/operationAmqp.js';
|
|
2
|
+
import publishingOperations from '../sync/publishingOperations.js';
|
|
3
|
+
|
|
4
|
+
/** Start and stop confirmed publication of local operation writes. */
|
|
5
|
+
export default function operationFederation(url, { wrap = (operations) => { return operations; }, report } = {}) {
|
|
6
|
+
const session = operationAmqp(url);
|
|
7
|
+
return {
|
|
8
|
+
publish: session.publish,
|
|
9
|
+
wrap(operations) { return wrap(publishingOperations(operations, session.publish)); },
|
|
10
|
+
start() {
|
|
11
|
+
return report ? session.start().catch(report) : session.start();
|
|
12
|
+
},
|
|
13
|
+
stop() { return session.stop(); }
|
|
14
|
+
};
|
|
15
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import publishingOperations from '../sync/publishingOperations.js';
|
|
2
|
+
|
|
3
|
+
/** Apply an authoritative snapshot in order, then remove records absent from it. */
|
|
4
|
+
export default async function reconcileOperationSnapshot({ operations, publish, machine, kind, range }, { rows, key, accept }) {
|
|
5
|
+
for (const row of rows) {
|
|
6
|
+
// eslint-disable-next-line no-await-in-loop -- Preserve source and publication order.
|
|
7
|
+
await accept(row);
|
|
8
|
+
}
|
|
9
|
+
const keys = new Set(rows.map(key).filter((id) => { return typeof id === 'string' && id.length > 0; }));
|
|
10
|
+
const stored = await operations.listForMachine(machine, kind, range);
|
|
11
|
+
const port = publishingOperations(operations, publish);
|
|
12
|
+
for (const row of stored) {
|
|
13
|
+
if (!keys.has(row.key)) {
|
|
14
|
+
// eslint-disable-next-line no-await-in-loop -- Publish each confirmed deletion in store order.
|
|
15
|
+
await port.remove(machine, row.key);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
function notFound(id) {
|
|
2
|
+
const error = new Error(`operator '${id}' not found`);
|
|
3
|
+
error.routeCode = 'NOT_FOUND';
|
|
4
|
+
error.routeStatus = 404;
|
|
5
|
+
return error;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
async function enrich(rows, store, field) {
|
|
9
|
+
if (!store) {
|
|
10
|
+
return rows.map((row) => { return { ...row, [field]: row[field] ?? '' }; });
|
|
11
|
+
}
|
|
12
|
+
const values = await store.getMap(rows.map(({ id }) => { return id; }));
|
|
13
|
+
return rows.map((row) => {
|
|
14
|
+
const value = values.get(Number(row.id));
|
|
15
|
+
return { ...row, [field]: value === undefined ? '' : value };
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
async function assign(base, store, field, id, value) {
|
|
20
|
+
const found = (await base.list()).find((row) => { return Number(row.id) === Number(id); });
|
|
21
|
+
if (!found) { throw notFound(id); }
|
|
22
|
+
if (value === '') { await store.remove(found.id); }
|
|
23
|
+
else { await store.put(found.id, value); }
|
|
24
|
+
return { ...found, [field]: value };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Enrich operator identities with a separately persisted or remotely owned field. */
|
|
28
|
+
export default function operatorField(base, { field, onCreate, onUpdate, store }) {
|
|
29
|
+
return Object.freeze({
|
|
30
|
+
async list() { return enrich(await base.list(), store, field); },
|
|
31
|
+
async create(fields) {
|
|
32
|
+
const value = onCreate(fields[field]);
|
|
33
|
+
const created = await base.create(fields);
|
|
34
|
+
if (store) { await store.put(created.id, value); }
|
|
35
|
+
return { ...created, [field]: store || created[field] === undefined ? value : created[field] };
|
|
36
|
+
},
|
|
37
|
+
async update(id, fields) {
|
|
38
|
+
const value = onUpdate(fields[field]);
|
|
39
|
+
if (typeof base.update === 'function') {
|
|
40
|
+
const updated = await base.update(id, { [field]: value });
|
|
41
|
+
return { ...updated, [field]: updated[field] === undefined ? value : updated[field] };
|
|
42
|
+
}
|
|
43
|
+
if (!store) { throw notFound(id); }
|
|
44
|
+
return assign(base, store, field, id, value);
|
|
45
|
+
},
|
|
46
|
+
enabled() { return base.enabled(); },
|
|
47
|
+
permit(flag) { return base.permit(flag); }
|
|
48
|
+
});
|
|
49
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import operator from '../../domain/operator/operator.js';
|
|
2
|
+
import centralOperators from '../../infrastructure/operators/centralOperators.js';
|
|
3
|
+
import edgeOperators from '../../infrastructure/operators/edgeOperators.js';
|
|
4
|
+
import operatorExtras, { operatorIdentityKeys } from '../../infrastructure/operators/operatorExtras.js';
|
|
5
|
+
|
|
6
|
+
/** Add PATCH support for catalog-owned operator fields. */
|
|
7
|
+
export function centralOperatorsUpdate(client, basePath) {
|
|
8
|
+
return Object.freeze({
|
|
9
|
+
...centralOperators(client, basePath),
|
|
10
|
+
async update(id, fields) {
|
|
11
|
+
const row = await client.patchJson(`${basePath}/operators/${id}`, fields);
|
|
12
|
+
if (row.id === undefined || row.id === null) { throw new Error('central operators item missing id'); }
|
|
13
|
+
return {
|
|
14
|
+
...operator(row.id, row.cardUid, row.firstName, row.lastName, row.displayName),
|
|
15
|
+
...operatorExtras(row, operatorIdentityKeys())
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Forward operator changes to central and refresh the local materialized catalog. */
|
|
22
|
+
export function edgeOperatorsUpdate(cache, source) {
|
|
23
|
+
return Object.freeze({
|
|
24
|
+
...edgeOperators(cache, source),
|
|
25
|
+
async update(id, fields) {
|
|
26
|
+
if (typeof source?.update !== 'function') {
|
|
27
|
+
const error = new Error('CENTRAL_PLANT_URL is required for edge operator update');
|
|
28
|
+
error.routeCode = 'SERVICE_UNAVAILABLE';
|
|
29
|
+
error.routeStatus = 503;
|
|
30
|
+
throw error;
|
|
31
|
+
}
|
|
32
|
+
const updated = await source.update(id, fields);
|
|
33
|
+
cache.replace(await source.pull());
|
|
34
|
+
return updated;
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { createClient } from '@clickhouse/client';
|
|
2
|
+
import telemetryIngest from '../../infrastructure/ingest/telemetry/telemetryIngest.js';
|
|
3
|
+
import amqpMetricsIngest from '../../infrastructure/ingest/telemetry/amqpMetricsIngest.js';
|
|
4
|
+
import clickhouseJsonMetrics from '../../infrastructure/persistence/clickhouse/jsonMetrics.js';
|
|
5
|
+
|
|
6
|
+
/** Restart an ingest process after an uncertain storage write and report delivery failures. */
|
|
7
|
+
export function processTelemetryIngest(url, queue, metrics, {
|
|
8
|
+
halt = () => { process.exit(1); },
|
|
9
|
+
report = (error) => { process.stderr.write(`Telemetry delivery failed: ${error.message}\n`); },
|
|
10
|
+
...options
|
|
11
|
+
} = {}) {
|
|
12
|
+
return telemetryIngest(url, queue, metrics, { ...options, halt, report });
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Start a dedicated RabbitMQ to ClickHouse ingest using the supplied queue and admission policy. */
|
|
16
|
+
export function centralTelemetryIngest(env, { defaultQueue, admission }, { metrics, ingest = processTelemetryIngest } = {}) {
|
|
17
|
+
if (!env.CLICKHOUSE_URL) { throw new Error('CLICKHOUSE_URL is required'); }
|
|
18
|
+
if (!env.AMQP_URL) { throw new Error('AMQP_URL is required'); }
|
|
19
|
+
const sink = metrics ? metrics(env.CLICKHOUSE_URL) : clickhouseJsonMetrics(
|
|
20
|
+
createClient({ url: env.CLICKHOUSE_URL, 'request_timeout': 60000 }), admission
|
|
21
|
+
);
|
|
22
|
+
const writer = ingest(env.AMQP_URL, env.AMQP_QUEUE || defaultQueue, sink, {
|
|
23
|
+
size: 256, prefetch: 512, maxWaitMs: 1000, writeTimeoutMs: 45000
|
|
24
|
+
});
|
|
25
|
+
return Promise.resolve(writer.start()).then(() => { return writer; });
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Accept deliveries in order with one message in flight to prevent retry overtaking. */
|
|
29
|
+
export function orderedMetricsIngest(url, queue, sink) {
|
|
30
|
+
return amqpMetricsIngest(url, queue, sink, { prefetch: 1, size: 1, maxWaitMs: 250, exclusive: true, writeTimeoutMs: 45000 });
|
|
31
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import pg from 'pg';
|
|
2
|
+
import { createClient } from '@clickhouse/client';
|
|
3
|
+
import telemetryBackfill from '../telemetry/telemetryBackfill.js';
|
|
4
|
+
import postgresTelemetrySource from '../../infrastructure/persistence/pg/telemetrySource.js';
|
|
5
|
+
import clickhouseTelemetryTarget, { assertClickhouseBackfillMode } from '../../infrastructure/persistence/clickhouse/telemetryTarget.js';
|
|
6
|
+
|
|
7
|
+
const readonly = '-c default_transaction_read_only=on -c statement_timeout=120000 -c timezone=UTC';
|
|
8
|
+
|
|
9
|
+
function required(env, name) {
|
|
10
|
+
if (!env[name]) { throw new Error(`${name} is required`); }
|
|
11
|
+
return env[name];
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function publicError(env, error) {
|
|
15
|
+
let { message } = error;
|
|
16
|
+
for (const name of ['SOURCE_POSTGRES_URL', 'CLICKHOUSE_URL', 'CLICKHOUSE_PASSWORD']) {
|
|
17
|
+
if (env[name]) { message = message.split(env[name]).join('[redacted]'); }
|
|
18
|
+
}
|
|
19
|
+
return { error: message, ...(error.report ? { report: error.report } : {}) };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function options(env, value, usage) {
|
|
23
|
+
const source = new URL(required(env, 'SOURCE_POSTGRES_URL'));
|
|
24
|
+
source.searchParams.set('options', readonly);
|
|
25
|
+
const url = required(env, 'CLICKHOUSE_URL');
|
|
26
|
+
const mode = (value || 'copy').toLowerCase();
|
|
27
|
+
if (!['copy', 'verify', 'repair'].includes(mode)) { throw new Error(`Usage: ${usage} copy|verify|repair`); }
|
|
28
|
+
return {
|
|
29
|
+
postgres: { connectionString: source.toString(), max: 1, options: readonly, 'query_timeout': 125000, connectionTimeoutMillis: 15000 },
|
|
30
|
+
clickhouse: { url, username: env.CLICKHOUSE_USER || 'default', password: env.CLICKHOUSE_PASSWORD || '',
|
|
31
|
+
'request_timeout': 125000, 'clickhouse_settings': { 'insert_deduplicate': 0 } },
|
|
32
|
+
mode, from: env.SOURCE_FROM || '1970-01-01T00:00:00Z', pageSize: Number(env.SOURCE_PAGE_SIZE || 20000)
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
async function runBackfill(source, client, config, admission) {
|
|
37
|
+
const target = clickhouseTelemetryTarget(client, admission);
|
|
38
|
+
const report = await telemetryBackfill({ source, target }, {
|
|
39
|
+
mode: config.mode, pageSize: config.pageSize,
|
|
40
|
+
onProgress(progress) { process.stderr.write(`${JSON.stringify({ progress })}\n`); }
|
|
41
|
+
});
|
|
42
|
+
process.stdout.write(`${JSON.stringify(report)}\n`);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Run the resumable PostgreSQL to ClickHouse backfill with read-only source credentials. */
|
|
46
|
+
export default async function telemetryBackfillCommand(env, argument, { admission, usage = 'telemetry-backfill' } = {}) {
|
|
47
|
+
let pool;
|
|
48
|
+
let client;
|
|
49
|
+
let source;
|
|
50
|
+
try {
|
|
51
|
+
const config = options(env, argument, usage);
|
|
52
|
+
pool = new pg.Pool(config.postgres);
|
|
53
|
+
client = createClient(config.clickhouse);
|
|
54
|
+
await assertClickhouseBackfillMode(client, config.mode);
|
|
55
|
+
source = postgresTelemetrySource(pool, { from: config.from });
|
|
56
|
+
await runBackfill(source, client, config, admission);
|
|
57
|
+
} catch (error) {
|
|
58
|
+
process.stderr.write(`${JSON.stringify(publicError(env, error))}\n`);
|
|
59
|
+
process.exitCode = 1;
|
|
60
|
+
} finally {
|
|
61
|
+
try { await source?.close(); }
|
|
62
|
+
finally { await Promise.allSettled([pool?.end(), client?.close()]); }
|
|
63
|
+
}
|
|
64
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/** Convert persistence timestamps into timeline inputs, projecting an open end at the supplied clock. */
|
|
2
|
+
export function timelineSegments(rows, now) {
|
|
3
|
+
return rows.map((row) => {
|
|
4
|
+
return { name: row.name, start: row.start_time.toISOString(),
|
|
5
|
+
end: (row.duration === 0 ? now : row.end_time).toISOString(),
|
|
6
|
+
duration: row.duration, tags: row.tags, options: row.options, properties: row.properties };
|
|
7
|
+
});
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/** Bounds spanning a set of half-open measurement windows. */
|
|
11
|
+
export function measurementBounds(items, windowFor) {
|
|
12
|
+
if (!items.length) { return null; }
|
|
13
|
+
let start = Number.POSITIVE_INFINITY;
|
|
14
|
+
let end = Number.NEGATIVE_INFINITY;
|
|
15
|
+
for (const item of items) {
|
|
16
|
+
const { start: lower, end: upper } = windowFor(item);
|
|
17
|
+
if (lower < start) { start = lower; }
|
|
18
|
+
if (upper > end) { end = upper; }
|
|
19
|
+
}
|
|
20
|
+
return { start: new Date(start), end: new Date(end) };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Add optional scaled peaks from half-open measurement windows. */
|
|
24
|
+
export function measurementPeaks(items, samples, { field, scale = 1, windowFor }) {
|
|
25
|
+
return items.map((item) => {
|
|
26
|
+
const { start, end } = windowFor(item);
|
|
27
|
+
let peak = Number.NEGATIVE_INFINITY;
|
|
28
|
+
for (const sample of samples) {
|
|
29
|
+
const stamp = new Date(sample.timestamp).getTime();
|
|
30
|
+
if (Number.isFinite(sample.value) && stamp >= start && stamp < end) {
|
|
31
|
+
peak = Math.max(peak, sample.value);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
return { ...item, ...(peak !== Number.NEGATIVE_INFINITY && { [field]: peak * scale }) };
|
|
35
|
+
});
|
|
36
|
+
}
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Returns epoch ms for a tagged row used in phase lookup.
|
|
3
|
+
*
|
|
4
|
+
* @param {object} item - row with start, start_time, or startTime
|
|
5
|
+
* @returns {number} epoch milliseconds
|
|
6
|
+
*/
|
|
7
|
+
function startOf(item) {
|
|
8
|
+
const raw = item.start || item.start_time || item.startTime;
|
|
9
|
+
if (raw instanceof Date) {
|
|
10
|
+
return raw.getTime();
|
|
11
|
+
}
|
|
12
|
+
return new Date(raw).getTime();
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Normalizes stored tags to an id list.
|
|
17
|
+
*
|
|
18
|
+
* @param {object} item - row with tags array or JSON string
|
|
19
|
+
* @returns {Array<string>} tag ids
|
|
20
|
+
*/
|
|
21
|
+
function tagList(item) {
|
|
22
|
+
const raw = item.tags;
|
|
23
|
+
if (Array.isArray(raw)) {
|
|
24
|
+
return raw;
|
|
25
|
+
}
|
|
26
|
+
if (typeof raw === 'string' && raw.length > 0) {
|
|
27
|
+
return JSON.parse(raw);
|
|
28
|
+
}
|
|
29
|
+
return [];
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Finds the last index matching pred, or -1.
|
|
34
|
+
*
|
|
35
|
+
* @param {Array<string>} tags - chronological tag ids
|
|
36
|
+
* @param {function} match - predicate
|
|
37
|
+
* @returns {number} last matching index
|
|
38
|
+
*/
|
|
39
|
+
function lastIndex(tags, match) {
|
|
40
|
+
for (let i = tags.length - 1; i >= 0; i -= 1) {
|
|
41
|
+
if (match(tags[i])) {
|
|
42
|
+
return i;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return -1;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Finds the most recent declared phase entry after a cycle start.
|
|
50
|
+
*
|
|
51
|
+
* @param {Array<string>} after - tags after the last start anchor
|
|
52
|
+
* @param {object} idle - idle block
|
|
53
|
+
* @param {Array<object>} blocks - all phase blocks
|
|
54
|
+
* @param {string} start - start anchor id
|
|
55
|
+
* @returns {object} matching phase block
|
|
56
|
+
*/
|
|
57
|
+
function entered(after, idle, blocks, start) {
|
|
58
|
+
const last = [...after].reverse().find((id) => {
|
|
59
|
+
return blocks.some((block) => {
|
|
60
|
+
return block.enter === id;
|
|
61
|
+
});
|
|
62
|
+
});
|
|
63
|
+
if (!last) {
|
|
64
|
+
return blocks.find((block) => {
|
|
65
|
+
return block.enter === start;
|
|
66
|
+
}) || idle;
|
|
67
|
+
}
|
|
68
|
+
return blocks.find((block) => {
|
|
69
|
+
return block.enter === last;
|
|
70
|
+
}) || idle;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Resolves the open cycle phase from earlier tagged segments.
|
|
75
|
+
*
|
|
76
|
+
* @param {Array<object>} others - earlier rows
|
|
77
|
+
* @param {object} anchors - start and stops
|
|
78
|
+
* @param {Array<object>} blocks - phase blocks
|
|
79
|
+
* @returns {object} current phase block
|
|
80
|
+
*/
|
|
81
|
+
function phaseOf(others, anchors, blocks) {
|
|
82
|
+
const idle = blocks.find((block) => {
|
|
83
|
+
return !block.enter;
|
|
84
|
+
}) || { allow: [] };
|
|
85
|
+
const tags = others.slice().sort((left, right) => {
|
|
86
|
+
return startOf(left) - startOf(right);
|
|
87
|
+
}).flatMap(tagList);
|
|
88
|
+
const lastStop = lastIndex(tags, (id) => {
|
|
89
|
+
return anchors.stops.includes(id);
|
|
90
|
+
});
|
|
91
|
+
const lastStart = lastIndex(tags, (id) => {
|
|
92
|
+
return id === anchors.start;
|
|
93
|
+
});
|
|
94
|
+
if (lastStart < 0 || lastStart < lastStop) {
|
|
95
|
+
return idle;
|
|
96
|
+
}
|
|
97
|
+
return entered(tags.slice(lastStart + 1), idle, blocks, anchors.start);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Allow list of one phase block.
|
|
102
|
+
*
|
|
103
|
+
* @param {Array<string>} flat - tag ids in display order
|
|
104
|
+
* @param {object} block - phase block
|
|
105
|
+
* @returns {Array<string>} allowed tag ids
|
|
106
|
+
*/
|
|
107
|
+
function allowOf(flat, block) {
|
|
108
|
+
const allowed = new Set((block || { allow: [] }).allow);
|
|
109
|
+
return flat.filter((id) => {
|
|
110
|
+
return allowed.has(id);
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Allow list for a phase id returned by the database.
|
|
116
|
+
*
|
|
117
|
+
* @param {Array<string>} flat - tag ids in display order
|
|
118
|
+
* @param {Array<object>} blocks - phase blocks
|
|
119
|
+
* @param {string} key - phase id
|
|
120
|
+
* @returns {Array<string>} allowed tag ids
|
|
121
|
+
*/
|
|
122
|
+
function paintOf(flat, blocks, key) {
|
|
123
|
+
const named = blocks.find((item) => {
|
|
124
|
+
return item.enter === key;
|
|
125
|
+
});
|
|
126
|
+
const idle = blocks.find((item) => {
|
|
127
|
+
return !item.enter;
|
|
128
|
+
});
|
|
129
|
+
return allowOf(flat, named || idle);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Phase id at one instant, for tests and fakes.
|
|
134
|
+
*
|
|
135
|
+
* @param {object} anchors - start id and stop ids
|
|
136
|
+
* @param {Array<object>} blocks - phase blocks
|
|
137
|
+
* @param {Array<object>} rows - earlier rows plus the window
|
|
138
|
+
* @param {Date|string|number} at - instant
|
|
139
|
+
* @returns {string} phase id
|
|
140
|
+
*/
|
|
141
|
+
function keyOf(anchors, blocks, rows, at) {
|
|
142
|
+
const moment = at instanceof Date ? at.getTime() : new Date(at).getTime();
|
|
143
|
+
const others = rows.filter((item) => {
|
|
144
|
+
return startOf(item) < moment;
|
|
145
|
+
});
|
|
146
|
+
return phaseOf(others, anchors, blocks).enter || 'idle';
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Resolve cycle phase and allowed tags from declared anchors and phase blocks.
|
|
151
|
+
*
|
|
152
|
+
* @param {object} config - ordered display tags, anchors and phase blocks
|
|
153
|
+
* @returns {object} options, accept, narrow, paint, key
|
|
154
|
+
*
|
|
155
|
+
* @example
|
|
156
|
+
* cyclePhases(config).options([])
|
|
157
|
+
*/
|
|
158
|
+
export default function cyclePhases(config) {
|
|
159
|
+
const { flat, anchors, blocks } = config;
|
|
160
|
+
function options(others) {
|
|
161
|
+
return allowOf(flat, phaseOf(others, anchors, blocks));
|
|
162
|
+
}
|
|
163
|
+
return {
|
|
164
|
+
enters: blocks.flatMap((block) => {
|
|
165
|
+
return block.enter ? [block.enter] : [];
|
|
166
|
+
}),
|
|
167
|
+
options,
|
|
168
|
+
paint(key) {
|
|
169
|
+
return paintOf(flat, blocks, key);
|
|
170
|
+
},
|
|
171
|
+
key(rows, at) {
|
|
172
|
+
return keyOf(anchors, blocks, rows, at);
|
|
173
|
+
},
|
|
174
|
+
accept(others, standing, tags) {
|
|
175
|
+
const ok = new Set([...options(others), ...standing]);
|
|
176
|
+
return tags.every((id) => {
|
|
177
|
+
return ok.has(id);
|
|
178
|
+
});
|
|
179
|
+
},
|
|
180
|
+
narrow(row, all) {
|
|
181
|
+
if (row.name !== 'off') {
|
|
182
|
+
return row;
|
|
183
|
+
}
|
|
184
|
+
const own = startOf(row);
|
|
185
|
+
const others = all.filter((item) => {
|
|
186
|
+
return startOf(item) < own;
|
|
187
|
+
});
|
|
188
|
+
return { ...row, options: options(others) };
|
|
189
|
+
}
|
|
190
|
+
};
|
|
191
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/** Resolve cycles intersecting a half-open window using configured start and stop tags. */
|
|
2
|
+
export default function taggedCycleWindows(timeline, range, { start, stops }) {
|
|
3
|
+
const from = new Date(range.from).getTime();
|
|
4
|
+
const to = new Date(range.to).getTime();
|
|
5
|
+
const now = range.now === undefined ? Date.now() : new Date(range.now).getTime();
|
|
6
|
+
const windowEnd = Math.min(to, now);
|
|
7
|
+
const starts = timeline.anchorStarts(start, -1, Number.MAX_SAFE_INTEGER);
|
|
8
|
+
return starts.flatMap((cycleStart, index) => {
|
|
9
|
+
const nextStart = starts[index + 1];
|
|
10
|
+
const nextStop = Math.min(...stops.map((tag) => {
|
|
11
|
+
return timeline.anchorStarts(tag, cycleStart, Number.MAX_SAFE_INTEGER)[0] ?? Infinity;
|
|
12
|
+
}));
|
|
13
|
+
const closedEnd = Math.min(nextStart > cycleStart ? nextStart : Infinity, nextStop);
|
|
14
|
+
const end = Math.min(closedEnd, windowEnd);
|
|
15
|
+
return end > from && cycleStart < windowEnd ? [{ start: cycleStart, end, open: closedEnd > windowEnd }] : [];
|
|
16
|
+
});
|
|
17
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import timelineSegment from './timelineSegment.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Parses tag names from timeline segment tags JSON string.
|
|
5
|
+
*
|
|
6
|
+
* @param {string|undefined} raw - tags JSON string from persistence
|
|
7
|
+
* @returns {Array<string>} tag names
|
|
8
|
+
*/
|
|
9
|
+
function parseTags(raw) {
|
|
10
|
+
if (!raw) {
|
|
11
|
+
return [];
|
|
12
|
+
}
|
|
13
|
+
if (typeof raw !== 'string') {
|
|
14
|
+
throw new Error('segment tags must be a JSON string from timeline');
|
|
15
|
+
}
|
|
16
|
+
const parsed = JSON.parse(raw);
|
|
17
|
+
if (!Array.isArray(parsed)) {
|
|
18
|
+
throw new Error('segment tags JSON must decode to an array');
|
|
19
|
+
}
|
|
20
|
+
return parsed;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Immutable tagged timeline segment with anchor tag checks.
|
|
25
|
+
*
|
|
26
|
+
* @param {object} row - segment with ISO timestamps and tags JSON string
|
|
27
|
+
* @returns {object} tagged segment with segment, tags, has
|
|
28
|
+
*
|
|
29
|
+
* @example
|
|
30
|
+
* const item = taggedSegment({ start: '2026-01-01T00:00:00.000Z', end: '2026-01-01T01:00:00.000Z', tags: '["ready"]' });
|
|
31
|
+
* item.has('ready');
|
|
32
|
+
*/
|
|
33
|
+
export default function taggedSegment(row) {
|
|
34
|
+
const base = timelineSegment(row);
|
|
35
|
+
const names = parseTags(row.tags);
|
|
36
|
+
return {
|
|
37
|
+
segment() {
|
|
38
|
+
return base;
|
|
39
|
+
},
|
|
40
|
+
tags() {
|
|
41
|
+
return names;
|
|
42
|
+
},
|
|
43
|
+
has(name) {
|
|
44
|
+
return names.includes(name);
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
}
|