@yarkivaev/scada 2.18.0 → 2.19.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 +13 -0
- package/package.json +4 -2
- package/src/application/cycleTimelineFetch.js +56 -0
- package/src/application/deploy/edgeDescriptors.js +31 -0
- package/src/application/deploy/fieldbusSourcePlan.js +79 -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/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/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/highAvailability/configuredBrokerReconciliation.js +21 -0
- package/src/infrastructure/deploy/highAvailability/index.js +1 -0
- package/src/infrastructure/deploy/index.js +19 -0
- 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 +5 -0
- package/src/infrastructure/streams/namedSerialDevices.js +26 -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,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,91 @@
|
|
|
1
|
+
import { appendBrokerReplicas, brokerReplicaPlan } from './brokerReplicaTopology.js';
|
|
2
|
+
import { attachBrokerMesh, brokerEndpoint } from './brokerTopology.js';
|
|
3
|
+
import deploymentTemplate from './deploymentTemplate.js';
|
|
4
|
+
|
|
5
|
+
function pairsFor(machines, rules) {
|
|
6
|
+
return rules.flatMap((rule) => {
|
|
7
|
+
const rows = machines.filter(({ kind }) => { return kind === rule.kind; });
|
|
8
|
+
const homes = rows.map((row) => { return deploymentTemplate(rule.leader, row); });
|
|
9
|
+
return rows.map(({ id: machine }, index) => {
|
|
10
|
+
return { machine, leader: homes[index], standby: rule.standby ?? homes[(index + 1) % homes.length] };
|
|
11
|
+
});
|
|
12
|
+
});
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function streamPolicy(policy, machine, forwardOutbox) {
|
|
16
|
+
const rule = policy.streams.find(({ prefix }) => { return machine.startsWith(prefix); }) ?? policy.defaultStreams;
|
|
17
|
+
return deploymentTemplate(rule.templates, { machine, suffix: machine.slice(rule.prefix?.length ?? 0), forwardOutbox });
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function landingBindings(result, machine, exchange, policy) {
|
|
21
|
+
const rule = policy.restoreBindings;
|
|
22
|
+
if (!rule || !machine.startsWith(rule.prefix)) { return []; }
|
|
23
|
+
const queue = deploymentTemplate(rule.queue, { machine });
|
|
24
|
+
const live = result.bindings.find(({ source, destination, routing_key: key }) => {
|
|
25
|
+
return source === rule.source && destination === queue && key.endsWith(rule.keySuffix);
|
|
26
|
+
});
|
|
27
|
+
return live ? rule.metrics.map((metric) => {
|
|
28
|
+
return { source: exchange, destination: queue, key: live.routing_key.replace('*', metric) };
|
|
29
|
+
}) : [];
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function attachReplicas(policy, pairs, document, node, result) {
|
|
33
|
+
if (document.edgeControlPlane?.historyEnabled !== true) { return result; }
|
|
34
|
+
const { brokerService, writerEpoch: epoch } = document.edgeControlPlane;
|
|
35
|
+
const options = { ...policy.access, fallbackPort: brokerService.nodePort };
|
|
36
|
+
const ids = new Set(pairs.flatMap(({ leader, standby }) => { return [leader, standby]; }));
|
|
37
|
+
const brokers = Object.fromEntries([...ids].map((id) => { return [id, brokerEndpoint(document, id, options)]; }));
|
|
38
|
+
const replicas = pairs.map((pair) => {
|
|
39
|
+
const streams = streamPolicy(policy, pair.machine, true);
|
|
40
|
+
const telemetry = streams.find(({ landing }) => { return landing; });
|
|
41
|
+
const { exchange } = telemetry.restore;
|
|
42
|
+
return { ...pair, epoch, streams, landings: [{ exchange, queue: telemetry.landing, keys: ['#'],
|
|
43
|
+
bindings: landingBindings(result, pair.machine, exchange, policy) }] };
|
|
44
|
+
});
|
|
45
|
+
const blocked = brokers[node] && brokerEndpoint(document, policy.archive, options);
|
|
46
|
+
return appendBrokerReplicas(result, { node, brokers, blocked, replicas });
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function meshRestriction(rules, policy, node) {
|
|
50
|
+
const home = rules.groups.find(({ history, preference }) => { return history && preference[0] === node; });
|
|
51
|
+
const keys = home?.keys.filter((key) => { return policy.restrictPrefixes.some((prefix) => { return key.startsWith(prefix); }); });
|
|
52
|
+
return keys && { queue: policy.restrictQueue, keys: Object.fromEntries(keys.map((key) => {
|
|
53
|
+
return [`${key.split('.')[0]}.#`, key];
|
|
54
|
+
})) };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Compile replica streams and peer mesh from the installation's topology and broker declarations. */
|
|
58
|
+
export default function brokerFleetPolicy(policy, { machines, classifierRules: rules, federation }) {
|
|
59
|
+
const pairs = pairsFor(machines, policy.pairs);
|
|
60
|
+
const meshIds = Object.freeze([...new Set([
|
|
61
|
+
...rules.groups.filter(({ history }) => { return history; }).flatMap(({ preference }) => { return preference; }),
|
|
62
|
+
...rules.mesh.originCopies,
|
|
63
|
+
...rules.groups.flatMap(({ preference }) => { return preference; })
|
|
64
|
+
])]);
|
|
65
|
+
function replicaPlan({ machine, leader, standby, epoch, brokers, central, forwardOutbox = false }) {
|
|
66
|
+
if (leader === standby) { throw new TypeError(deploymentTemplate(policy.sameTargetError, { machine })); }
|
|
67
|
+
if (!brokers[leader] || !brokers[standby]) { throw new TypeError(deploymentTemplate(policy.missingBrokerError, { machine })); }
|
|
68
|
+
return brokerReplicaPlan({ leader, standby, epoch, brokers, blocked: central,
|
|
69
|
+
exchange: policy.exchange, streams: streamPolicy(policy, machine, forwardOutbox) });
|
|
70
|
+
}
|
|
71
|
+
function edgeReplicas(brokers, central, epoch, forwardOutbox = false) {
|
|
72
|
+
return pairs.map((pair) => { return replicaPlan({ ...pair, epoch, brokers, central, forwardOutbox }); });
|
|
73
|
+
}
|
|
74
|
+
function meshEndpoint(document, node) {
|
|
75
|
+
return brokerEndpoint(document, node, { ...policy.access, ...policy.meshAccess,
|
|
76
|
+
fallbackPort: document.edgeControlPlane?.brokerService?.nodePort ?? policy.meshAccess.fallbackPort });
|
|
77
|
+
}
|
|
78
|
+
return {
|
|
79
|
+
replicaPlan, edgeReplicas, meshEndpoint, meshIds,
|
|
80
|
+
edgePairs() { return pairs.map((pair) => { return { ...pair }; }); },
|
|
81
|
+
fleetFor(nodes, central, epoch) {
|
|
82
|
+
const brokers = Object.fromEntries(nodes.map(({ id, brokerEndpoint: endpoint }) => { return [id, endpoint]; }));
|
|
83
|
+
return edgeReplicas(brokers, central, epoch);
|
|
84
|
+
},
|
|
85
|
+
attachReplicas(document, node, result) { return attachReplicas(policy, pairs, document, node, result); },
|
|
86
|
+
attachTelemetryMesh(document, node, result) {
|
|
87
|
+
return attachBrokerMesh(document, node, result, { peers: meshIds, endpoint: meshEndpoint,
|
|
88
|
+
restrict: meshRestriction(rules, policy, node), federation });
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import appReleases from '../../application/deploy/appReleases.js';
|
|
2
|
+
import { liveChartApps, liveChartValues } from '../../application/deploy/liveReleaseOverlay.js';
|
|
3
|
+
import readDeploymentDocument from '../../application/deploy/readDeploymentDocument.js';
|
|
4
|
+
import releases from '../../application/deploy/releases.js';
|
|
5
|
+
import { centralTelemetryChartEnv } from './centralTelemetry.js';
|
|
6
|
+
|
|
7
|
+
/** Render a declared archive contour with its immutable live chart overlays. */
|
|
8
|
+
export default function configuredArchivePlan(file, policy) {
|
|
9
|
+
const declarations = readDeploymentDocument(file).liveReleases;
|
|
10
|
+
function withLive(values, target) {
|
|
11
|
+
return Object.hasOwn(declarations, target) ? liveChartValues(values, declarations[target].chart) : values;
|
|
12
|
+
}
|
|
13
|
+
function withLiveApps(apps, target) {
|
|
14
|
+
return Object.hasOwn(declarations, target) ? liveChartApps(apps, declarations[target].apps) : apps;
|
|
15
|
+
}
|
|
16
|
+
return { withLive, withLiveApps,
|
|
17
|
+
plan(target = policy.target) {
|
|
18
|
+
if (target !== policy.target) { throw new Error(policy.targetError); }
|
|
19
|
+
const document = readDeploymentDocument(file);
|
|
20
|
+
const projected = releases(document, target);
|
|
21
|
+
return { context: policy.context, namespace: policy.namespace, release: target,
|
|
22
|
+
scada: withLive({ ...projected.scada, env: centralTelemetryChartEnv(document, policy.file, projected.scada.env) }, target),
|
|
23
|
+
apps: withLiveApps(appReleases(projected.apps, target), target) };
|
|
24
|
+
} };
|
|
25
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { brokerStreamRoutes } from './brokerTopology.js';
|
|
2
|
+
import deploymentTemplate from './deploymentTemplate.js';
|
|
3
|
+
|
|
4
|
+
function routeBindings(row, policy) {
|
|
5
|
+
const machine = row.name.split('/')[policy.pathIndex];
|
|
6
|
+
const device = machine?.replace(policy.machinePrefix, policy.devicePrefix);
|
|
7
|
+
return { name: row.name, machine, device };
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
function compileRule(rule, bindings, row) {
|
|
11
|
+
const route = deploymentTemplate(rule.route, bindings);
|
|
12
|
+
const metrics = rule.metrics ?? (rule.mappingKeys && Object.keys(row.mapping));
|
|
13
|
+
if (!metrics) { return route; }
|
|
14
|
+
return { ...route, keys: metrics.map((metric) => { return deploymentTemplate(rule.key, { ...bindings, metric }); }) };
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Project broker route keys from declared publisher, protocol and adapter policies. */
|
|
18
|
+
export default function configuredBrokerRoutes(policy, identifyAdapter) {
|
|
19
|
+
return function routes(source) {
|
|
20
|
+
return brokerStreamRoutes(source, { service: policy.service,
|
|
21
|
+
passive(row) {
|
|
22
|
+
const { contract } = row;
|
|
23
|
+
if (!Object.hasOwn(policy.publishers, contract)) {
|
|
24
|
+
throw new Error(deploymentTemplate(policy.contractError, { contract: String(contract) }));
|
|
25
|
+
}
|
|
26
|
+
return compileRule(policy.publishers[contract], routeBindings(row, policy), row);
|
|
27
|
+
},
|
|
28
|
+
local(row) {
|
|
29
|
+
const selected = policy.protocols.find(({ prefix }) => { return row.from.startsWith(prefix); });
|
|
30
|
+
const rule = selected ?? policy.adapters[identifyAdapter(row)];
|
|
31
|
+
return compileRule(rule, routeBindings(row, policy), row);
|
|
32
|
+
} });
|
|
33
|
+
};
|
|
34
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import deploymentTemplate from './deploymentTemplate.js';
|
|
2
|
+
import { holdersFrom } from './highAvailability/classifyShovels.js';
|
|
3
|
+
import projectClassification from './projectClassification.js';
|
|
4
|
+
|
|
5
|
+
function localMachines(ids, rule) {
|
|
6
|
+
const pattern = new RegExp(rule.homePattern, 'u');
|
|
7
|
+
const nodes = ids.filter((id) => { return id.startsWith(rule.homePrefix); });
|
|
8
|
+
if (nodes.length < 2) { throw new TypeError(rule.minimumError); }
|
|
9
|
+
return nodes.map((home) => {
|
|
10
|
+
if (!pattern.test(home)) { throw new TypeError(deploymentTemplate(rule.targetError, { home })); }
|
|
11
|
+
return { machine: rule.machinePrefix + home.at(-1), home, eligibleNodes: [...ids], area: rule.homeArea };
|
|
12
|
+
});
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function remoteMachines(ids, rule) {
|
|
16
|
+
const eligibleNodes = ids.filter((id) => { return rule.remoteEligible.includes(id); });
|
|
17
|
+
return rule.remoteMachines.map((machine) => {
|
|
18
|
+
return { machine, home: rule.remoteHome, eligibleNodes, area: rule.remoteArea };
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Project classification tasks with the installation's declared home and spare groups. */
|
|
23
|
+
export function configuredClassification(policy, calculatePlacement) {
|
|
24
|
+
const { classification: rule } = policy;
|
|
25
|
+
return {
|
|
26
|
+
plan(ids, brokers, central, holders = {}) {
|
|
27
|
+
return projectClassification(localMachines(ids, rule), { ...rule, brokers, central, holders });
|
|
28
|
+
},
|
|
29
|
+
forControl(plant, config) {
|
|
30
|
+
const central = plant.servers.find(({ id }) => { return id === policy.central; })
|
|
31
|
+
?.api.find(({ id }) => { return id === policy.brokerApi; })?.url;
|
|
32
|
+
if (!central) { throw new TypeError(rule.centralError); }
|
|
33
|
+
const ids = config.nodes.map(({ id }) => { return id; });
|
|
34
|
+
const declarations = [...localMachines(ids, rule), ...remoteMachines(ids, rule)].map(({ area, ...item }) => {
|
|
35
|
+
return { ...item, placement: calculatePlacement(config, area, item.home, ids) };
|
|
36
|
+
});
|
|
37
|
+
const brokers = Object.fromEntries(config.nodes.map(({ id, brokerEndpoint }) => { return [id, brokerEndpoint]; }));
|
|
38
|
+
return projectClassification(declarations, { ...rule, brokers, central,
|
|
39
|
+
holders: { ...holdersFrom(config.classifyRecord ?? {}), ...config.classificationHolders } });
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function location(server, service) {
|
|
45
|
+
const endpoint = server.api?.find(({ id }) => { return id === service; });
|
|
46
|
+
if (!endpoint?.url) { return []; }
|
|
47
|
+
const url = new URL(endpoint.url);
|
|
48
|
+
return [[server.id, `${url.protocol}//${url.host}`]];
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Resolve the peer directory behind an enabled classification service. */
|
|
52
|
+
export function classificationEnvironment(policy) {
|
|
53
|
+
return function environment(target, document) {
|
|
54
|
+
if (!document?.[policy.section]?.enabled) { return {}; }
|
|
55
|
+
const peers = Object.fromEntries((document.servers || []).flatMap((server) => { return location(server, policy.service); }));
|
|
56
|
+
return deploymentTemplate(policy.values, { target, peers });
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Project classifier chart values using the declared profile and config renderer. */
|
|
61
|
+
export function configuredSupervisor(policy, render) {
|
|
62
|
+
return function supervisor(config, node, machines = null) {
|
|
63
|
+
const home = node.id.startsWith(policy.homePrefix);
|
|
64
|
+
const targetMachine = policy.machinePrefix + node.id.at(-1);
|
|
65
|
+
const defaults = home ? [targetMachine] : [];
|
|
66
|
+
const selected = machines?.length ? [...new Set(machines)] : defaults;
|
|
67
|
+
const credentials = home ? policy.homeSecret : policy.deliverySecret;
|
|
68
|
+
const env = Object.fromEntries(policy.secretKeys.map((key) => { return [key, { valueFrom: { secretKeyRef: { name: credentials, key } } }]; }));
|
|
69
|
+
return { chart: policy.chart, release: policy.releases[node.id] ?? policy.defaultRelease, values: {
|
|
70
|
+
image: config.supervisorImage ?? null, config: render(node.id, false, selected, policy.checkpoint),
|
|
71
|
+
writerEpoch: config.writerEpoch, machines: selected, env, history: { retentionDays: config.historyRetentionDays }
|
|
72
|
+
} };
|
|
73
|
+
};
|
|
74
|
+
}
|