@yarkivaev/scada 2.5.8 → 2.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +83 -0
- package/db/migrations/E0005__historical_telemetry_grants.sql +5 -0
- package/db/migrations/E0006__historical_telemetry.sql +64 -0
- package/db/migrations/E0007__metric_receipts.sql +7 -0
- package/db/migrations/E0008__metric_receipts_grants.sql +1 -0
- package/db/migrations/E0009__history_continuation.sql +20 -0
- package/db/migrations/E0010__history_admissions.sql +8 -0
- package/db/migrations/E0011__history_classifier_checkpoints.sql +18 -0
- package/db/migrations/E0012__external_history_grants.sql +4 -0
- package/db/migrations/E0013__history_staged_corrections.sql +104 -0
- package/db/migrations/E0014__history_correction_grants.sql +5 -0
- package/db/migrations/E0015__history_retention_frontier.sql +7 -0
- package/db/migrations/E0016__history_retention_grants.sql +1 -0
- package/index.js +7 -0
- package/package.json +5 -3
- package/src/application/control/agent.js +61 -0
- package/src/application/control/catalog.js +22 -0
- package/src/application/control/controlClient.js +75 -0
- package/src/application/control/controlStore.js +55 -0
- package/src/application/control/controller.js +22 -0
- package/src/application/control/executionSnapshot.js +32 -0
- package/src/application/control/index.js +7 -0
- package/src/application/control/localAssignment.js +13 -0
- package/src/application/control/schedule.js +103 -0
- package/src/application/control/snapshotFile.js +24 -0
- package/src/application/foldedMetricsSink.js +1 -0
- package/src/application/mcp/mcpResources.js +1 -1
- package/src/application/mcp/mcpSchema.js +8 -3
- package/src/application/runtime/additionalAdapters.js +13 -9
- package/src/application/runtime/deliveryQueue.js +62 -0
- package/src/application/runtime/deliverySessions.js +28 -0
- package/src/application/runtime/modbusDelivery.js +36 -0
- package/src/application/runtime/pipelineAdapters.js +12 -8
- package/src/application/runtime/queuedDelivery.js +25 -0
- package/src/application/runtime/runCollector.js +34 -3
- package/src/application/runtime/runtime.js +2 -2
- package/src/application/runtime/runtimeHealth.js +1 -1
- package/src/application/runtime/runtimeServices.js +6 -2
- package/src/application/runtime/streamTask.js +13 -4
- package/src/application/runtime/taskContext.js +1 -0
- package/src/application/runtime/taskSlot.js +2 -2
- package/src/application/runtime/telemetrySink.js +18 -0
- package/src/application/siteServer.js +19 -4
- package/src/application/siteTelemetry.js +2 -2
- package/src/application/supervisorSink.js +5 -1
- package/src/application/sync/siteSyncBind.js +2 -2
- package/src/bin/controller.js +8 -0
- package/src/infrastructure/http/edge/edgeApi.js +2 -0
- package/src/infrastructure/http/edge/routes/history/historyRoutes.js +33 -0
- package/src/infrastructure/http/plant/routes/measurementRead.js +3 -0
- package/src/infrastructure/ingest/db/migrationProfile.js +6 -1
- package/src/infrastructure/ingest/db/retainMetricReceipts.js +8 -0
- package/src/infrastructure/ingest/db/runRetention.js +2 -0
- package/src/infrastructure/ingest/mqtt/metricsTransformer.js +11 -2
- package/src/infrastructure/ingest/mqtt/modbusMqtt.js +1 -1
- package/src/infrastructure/ingest/mqtt/modbusPublish.js +2 -0
- package/src/infrastructure/ingest/mqtt/mqttMetrics.js +1 -1
- package/src/infrastructure/ingest/telemetry/amqpMetricsIngest.js +7 -3
- package/src/infrastructure/ingest/telemetry/centralEnvelope.js +46 -0
- package/src/infrastructure/ingest/telemetry/centralMetricsSink.js +64 -0
- package/src/infrastructure/ingest/telemetry/centralPoint.js +14 -0
- package/src/infrastructure/ingest/telemetry/centralPolicy.js +51 -0
- package/src/infrastructure/ingest/telemetry/centralQueueSession.js +29 -0
- package/src/infrastructure/ingest/telemetry/centralTelemetryPreflight.js +31 -0
- package/src/infrastructure/ingest/telemetry/foldingSink.js +3 -0
- package/src/infrastructure/ingest/telemetry/historyTelemetry.js +32 -0
- package/src/infrastructure/persistence/clickhouse/canonicalMetrics.js +26 -0
- package/src/infrastructure/persistence/clickhouse/changes.js +4 -2
- package/src/infrastructure/persistence/clickhouse/connection.js +6 -8
- package/src/infrastructure/persistence/clickhouse/holds.js +10 -7
- package/src/infrastructure/persistence/clickhouse/latest.js +1 -1
- package/src/infrastructure/persistence/clickhouse/metricsQuery.js +70 -0
- package/src/infrastructure/persistence/clickhouse/metricsRelation.js +110 -0
- package/src/infrastructure/persistence/clickhouse/nativeMetricPoints.js +26 -0
- package/src/infrastructure/persistence/clickhouse/nativeMetricsAdmission.js +91 -0
- package/src/infrastructure/persistence/clickhouse/nativeMetricsClock.js +9 -0
- package/src/infrastructure/persistence/clickhouse/nativeMetricsCompaction.js +82 -0
- package/src/infrastructure/persistence/clickhouse/nativeMetricsInsert.js +31 -0
- package/src/infrastructure/persistence/clickhouse/nativeMetricsOwnership.js +8 -0
- package/src/infrastructure/persistence/clickhouse/nativeMetricsSchema.js +44 -0
- package/src/infrastructure/persistence/clickhouse/pollTopicCursors.js +3 -1
- package/src/infrastructure/persistence/clickhouse/rises.js +4 -2
- package/src/infrastructure/persistence/clickhouse/samples.js +10 -0
- package/src/infrastructure/persistence/clickhouse/sensor.js +4 -0
- package/src/infrastructure/persistence/clickhouse/series.js +38 -21
- package/src/infrastructure/persistence/pg/history.js +169 -0
- package/src/infrastructure/persistence/pg/historyAdmission.js +81 -0
- package/src/infrastructure/persistence/pg/historyCheckpoint.js +56 -0
- package/src/infrastructure/persistence/pg/historyConfigure.js +28 -0
- package/src/infrastructure/persistence/pg/historyContext.js +65 -0
- package/src/infrastructure/persistence/pg/historyCorrection.js +34 -0
- package/src/infrastructure/persistence/pg/historyObservations.js +56 -0
- package/src/infrastructure/persistence/pg/historySeed.js +27 -0
- package/src/infrastructure/persistence/pg/metrics.js +5 -4
- package/src/infrastructure/persistence/pg/metricsInsertSql.js +12 -0
- package/src/infrastructure/persistence/runtime/deliverySpool.js +124 -0
- package/src/infrastructure/persistence/stateDataFromPool.js +2 -0
- package/src/infrastructure/streams/amqpSink/session.js +6 -0
- package/src/infrastructure/streams/amqpSource.js +17 -4
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import schedule from './schedule.js';
|
|
2
|
+
export async function reconcile(store, nodeId, options = {}) {
|
|
3
|
+
const token = await store.acquire(nodeId);
|
|
4
|
+
if (!token) { return false; }
|
|
5
|
+
const view = await store.read();
|
|
6
|
+
if (!view.catalog) { return false; }
|
|
7
|
+
const desired = schedule(view.catalog, view.reports, view.assignments, options);
|
|
8
|
+
return store.commit(token, view, desired);
|
|
9
|
+
}
|
|
10
|
+
export default function controlLoop(store, nodeId, { intervalMs = 5000, onError = () => {
|
|
11
|
+
// Optional diagnostic sink.
|
|
12
|
+
}, ...options } = {}) {
|
|
13
|
+
let stopped = false;
|
|
14
|
+
let pending = null;
|
|
15
|
+
function tick() {
|
|
16
|
+
pending ??= reconcile(store, nodeId, options).catch(onError).finally(() => { pending = null; });
|
|
17
|
+
return pending;
|
|
18
|
+
}
|
|
19
|
+
const timer = setInterval(() => { if (!stopped) { void tick(); } }, intervalMs);
|
|
20
|
+
void tick();
|
|
21
|
+
return { tick, async stop() { stopped = true; clearInterval(timer); await pending; } };
|
|
22
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { checkSnapshot } from './snapshotFile.js';
|
|
2
|
+
export function remoteSnapshot(snapshot) {
|
|
3
|
+
const remote = { ...snapshot };
|
|
4
|
+
delete remote.localGeneration;
|
|
5
|
+
delete remote.executionGenerations;
|
|
6
|
+
return remote;
|
|
7
|
+
}
|
|
8
|
+
function epoch(snapshot) { return snapshot?.controlEpoch ?? 'initial'; }
|
|
9
|
+
/** Local runtime generations remain monotonic even when an operator restores etcd. */
|
|
10
|
+
export default function executionSnapshot(snapshot, previous, tasks, restored = false) {
|
|
11
|
+
checkSnapshot(snapshot);
|
|
12
|
+
const remote = remoteSnapshot(snapshot);
|
|
13
|
+
if (previous && epoch(previous) === epoch(remote)) {
|
|
14
|
+
if (remote.generation < previous.generation) { throw new Error('Stale assignment snapshot'); }
|
|
15
|
+
if (remote.generation === previous.generation && JSON.stringify(remote) !== JSON.stringify(remoteSnapshot(previous))) { throw new Error('Conflicting assignment snapshot'); }
|
|
16
|
+
if (remote.generation === previous.generation) { return previous; }
|
|
17
|
+
}
|
|
18
|
+
if (restored && Number.isSafeInteger(snapshot.localGeneration) && snapshot.executionGenerations) { return snapshot; }
|
|
19
|
+
const localGeneration = Math.max(previous?.localGeneration ?? 0, remote.generation, ...tasks.map((row) => { return row.generation ?? 0; })) + 1;
|
|
20
|
+
const executionGenerations = Object.fromEntries(remote.assignments.map((row) => {
|
|
21
|
+
const prior = previous?.assignments.find((item) => { return item.taskId === row.taskId; });
|
|
22
|
+
const unchanged = epoch(previous) === epoch(remote) && prior && prior.generation === row.generation && JSON.stringify(prior.spec) === JSON.stringify(row.spec);
|
|
23
|
+
return [row.taskId, unchanged ? previous.executionGenerations[row.taskId] : localGeneration];
|
|
24
|
+
}));
|
|
25
|
+
return { ...remote, localGeneration, executionGenerations };
|
|
26
|
+
}
|
|
27
|
+
export function remoteStatus(status, snapshot) {
|
|
28
|
+
return { ...status, tasks: status.tasks.map((row) => {
|
|
29
|
+
const assignment = snapshot?.assignments.find((item) => { return item.taskId === row.taskId; });
|
|
30
|
+
return { ...row, executionGeneration: row.generation, generation: assignment && row.generation === snapshot.executionGenerations[row.taskId] ? assignment.generation : null };
|
|
31
|
+
}) };
|
|
32
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export { default as controlClient, clientFromEnv } from './controlClient.js';
|
|
2
|
+
export { default as controlStore } from './controlStore.js';
|
|
3
|
+
export { default as validateCatalog } from './catalog.js';
|
|
4
|
+
export { default as schedule } from './schedule.js';
|
|
5
|
+
export { default as assignmentAgent } from './agent.js';
|
|
6
|
+
export { default as controller, reconcile } from './controller.js';
|
|
7
|
+
export function publishCatalog(store, catalog, expectedRevision) { return store.publish(catalog, expectedRevision); }
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
/** Logical task identity is stable; broker client sessions belong to a replica. */
|
|
3
|
+
export default function localAssignment(input, nodeId) {
|
|
4
|
+
const output = structuredClone(input);
|
|
5
|
+
const suffix = createHash('sha256').update(`${nodeId}:${input.taskId}`).digest('hex').slice(0, 16);
|
|
6
|
+
const specs = [output.spec.config, output.spec.source?.options, ...(output.spec.sinks ?? []).map((sink) => { return sink.options; })];
|
|
7
|
+
let changed = false;
|
|
8
|
+
for (const spec of specs) {
|
|
9
|
+
if (typeof spec?.clientId === 'string') { spec.clientId = `${spec.clientId}-${suffix}`; changed = true; }
|
|
10
|
+
}
|
|
11
|
+
if (changed) { delete output.specHash; }
|
|
12
|
+
return output;
|
|
13
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import validateCatalog from './catalog.js';
|
|
2
|
+
function same(left, right) { return JSON.stringify(left) === JSON.stringify(right); }
|
|
3
|
+
function eligible(task, node) { return (!task.pinnedNode || task.pinnedNode === node.id) && (!task.eligibleNodes || task.eligibleNodes.includes(node.id)); }
|
|
4
|
+
function wanted(task, node) { return !node.retired && eligible(task, node); }
|
|
5
|
+
function inEpoch(report, epoch) { return (report?.controlEpoch ?? 'initial') === epoch; }
|
|
6
|
+
function clockSkew(value) {
|
|
7
|
+
if (!Number.isFinite(value) || value <= 0) { throw new TypeError('Positive finite clock skew bound required'); }
|
|
8
|
+
}
|
|
9
|
+
function copies(task) { return task.pinnedNode ? 1 : task.copies ?? 2; }
|
|
10
|
+
function freshRead(report, input, { now, freshnessMs, controlEpoch, clockSkewMs }) {
|
|
11
|
+
return inEpoch(report, controlEpoch) && report?.tasks?.some((row) => {
|
|
12
|
+
return row.taskId === input.taskId && row.generation === input.generation && row.state === 'running' && !['degraded', 'failed'].includes(row.health)
|
|
13
|
+
&& Number.isFinite(row.lastRead) && row.lastRead <= now + clockSkewMs && now - row.lastRead <= freshnessMs;
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
function failedRead(report, input, controlEpoch) {
|
|
17
|
+
return input && inEpoch(report, controlEpoch) && report?.tasks?.some((row) => {
|
|
18
|
+
return row.taskId === input.taskId && row.generation === input.generation && row.state === 'failed';
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
function updateAllowed(task, node, slots, reports, { now, freshnessMs, controlEpoch, clockSkewMs }) {
|
|
22
|
+
const owners = slots.filter((slot) => { return slot.live && slot.assignments.some((row) => { return row.taskId === task.taskId; }); });
|
|
23
|
+
const modern = owners.filter((slot) => { return slot.assignments.some((row) => { return row.taskId === task.taskId && same(row.spec, task.spec); }); });
|
|
24
|
+
const ready = modern.some((slot) => {
|
|
25
|
+
const input = slot.assignments.find((row) => { return row.taskId === task.taskId; });
|
|
26
|
+
return freshRead(reports.get(slot.id), input, { now, freshnessMs, controlEpoch, clockSkewMs });
|
|
27
|
+
});
|
|
28
|
+
const healthy = owners.filter((slot) => { return freshRead(reports.get(slot.id), slot.assignments.find((row) => { return row.taskId === task.taskId; }), { now, freshnessMs, controlEpoch, clockSkewMs }); });
|
|
29
|
+
function failed(slot) { return failedRead(reports.get(slot.id), slot.assignments.find((row) => { return row.taskId === task.taskId; }), controlEpoch); }
|
|
30
|
+
const outdated = owners.filter((slot) => { return wanted(task, slot) && !modern.includes(slot)
|
|
31
|
+
&& (copies(task) === 1 || failed(slot) || healthy.some((other) => { return other.id !== slot.id; })); });
|
|
32
|
+
return (modern.length === 0 || ready || failed(node)) && outdated[0]?.id === node.id;
|
|
33
|
+
}
|
|
34
|
+
function snapshots(slots, taskMap, { version: catalogVersion, controlEpoch = 'initial' }, reports, timing) {
|
|
35
|
+
return Object.fromEntries(slots.map((node) => {
|
|
36
|
+
const base = node.assignments.map((row) => {
|
|
37
|
+
const task = taskMap.get(row.taskId);
|
|
38
|
+
const update = node.live && task && wanted(task, node) && !same(task.spec, row.spec) && updateAllowed(task, node, slots, reports, { ...timing, controlEpoch });
|
|
39
|
+
return update ? { ...row, spec: task.spec, assignedAt: timing.now } : row;
|
|
40
|
+
});
|
|
41
|
+
const complete = base.every((row) => { return same(row.spec, taskMap.get(row.taskId)?.spec); });
|
|
42
|
+
const appliedCatalog = complete ? catalogVersion : node.previous.catalogVersion;
|
|
43
|
+
const changed = node.live && (!same(base, node.previous.assignments) || node.previous.catalogVersion !== appliedCatalog || (node.previous.controlEpoch ?? 'initial') !== controlEpoch);
|
|
44
|
+
const generation = node.previous.generation + Number(changed);
|
|
45
|
+
const assignments = base.map((row) => {
|
|
46
|
+
const old = node.previous.assignments.find((item) => { return item.taskId === row.taskId; });
|
|
47
|
+
return { ...row, generation: old && same(old.spec, row.spec) ? old.generation : generation };
|
|
48
|
+
});
|
|
49
|
+
return [node.id, changed ? { generation, catalogVersion: appliedCatalog, controlEpoch, assignments } : node.previous];
|
|
50
|
+
}));
|
|
51
|
+
}
|
|
52
|
+
/** Conservative coverage-first placement. Unreachable executors retain their last snapshot. */
|
|
53
|
+
// eslint-disable-next-line max-statements
|
|
54
|
+
export default function schedule(catalog, reports, current, { now = Date.now(), freshnessMs = 15000, replacementDelayMs = 30000, clockSkewMs = 5000 } = {}) {
|
|
55
|
+
validateCatalog(catalog); clockSkew(clockSkewMs);
|
|
56
|
+
const controlEpoch = catalog.controlEpoch ?? 'initial';
|
|
57
|
+
const observed = new Map(reports.map((row) => { return [row.nodeId, row]; }));
|
|
58
|
+
function live(id) { const at = observed.get(id)?.receivedAt; return Number.isFinite(at) && at <= now + clockSkewMs && now - at <= freshnessMs; }
|
|
59
|
+
const taskMap = new Map(catalog.tasks.map((task) => { return [task.taskId, task]; }));
|
|
60
|
+
const declared = new Set(catalog.nodes.map((node) => { return node.id; }));
|
|
61
|
+
const nodes = [...catalog.nodes, ...Object.keys(current).filter((id) => { return !declared.has(id); }).map((id) => { return { id, capacity: 0, retired: true }; })];
|
|
62
|
+
const slots = nodes.map((node) => {
|
|
63
|
+
const previous = current[node.id] ?? { generation: 0, assignments: [] };
|
|
64
|
+
const assignments = previous.assignments.filter((row) => { return !live(node.id) || taskMap.has(row.taskId); });
|
|
65
|
+
return { ...node, previous, assignments: [...assignments], live: live(node.id), load: assignments.reduce((total, row) => { return total + (taskMap.get(row.taskId)?.cost ?? 1); }, 0) };
|
|
66
|
+
});
|
|
67
|
+
const tasks = [...catalog.tasks].sort((a, b) => { return Number(Boolean(b.pinnedNode)) - Number(Boolean(a.pinnedNode)) || a.taskId.localeCompare(b.taskId); });
|
|
68
|
+
function owners(task) {
|
|
69
|
+
return slots.filter((node) => {
|
|
70
|
+
const input = node.assignments.find((row) => { return row.taskId === task.taskId; });
|
|
71
|
+
const status = observed.get(node.id)?.tasks?.find((row) => { return row.taskId === task.taskId; });
|
|
72
|
+
const progressing = input && freshRead(observed.get(node.id), input, { now, freshnessMs, controlEpoch, clockSkewMs });
|
|
73
|
+
const starting = input && now - (input.assignedAt ?? now) <= replacementDelayMs;
|
|
74
|
+
return node.live && input && status?.state !== 'failed' && (progressing || starting);
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
for (let round = 0; round < Math.max(1, ...tasks.map(copies)); round += 1) {
|
|
78
|
+
for (const task of tasks) {
|
|
79
|
+
const active = owners(task).filter((node) => { return wanted(task, node); });
|
|
80
|
+
const missing = slots.filter((node) => { return !node.live && node.assignments.some((row) => { return row.taskId === task.taskId; }); });
|
|
81
|
+
const surviving = active.some((node) => { return freshRead(observed.get(node.id), node.assignments.find((row) => { return row.taskId === task.taskId; }), { now, freshnessMs, controlEpoch, clockSkewMs }); });
|
|
82
|
+
const waiting = surviving && missing.some((node) => { return now - (observed.get(node.id)?.receivedAt ?? 0) < replacementDelayMs; });
|
|
83
|
+
const candidates = slots.filter((node) => { return node.live && wanted(task, node) && !active.includes(node) && !node.assignments.some((row) => { return row.taskId === task.taskId; }) && node.load + (task.cost ?? 1) <= node.capacity; });
|
|
84
|
+
candidates.sort((a, b) => { return a.load / a.capacity - b.load / b.capacity || a.id.localeCompare(b.id); });
|
|
85
|
+
if (active.length <= round && active.length < copies(task) && !waiting && candidates.length) {
|
|
86
|
+
const node = candidates[0];
|
|
87
|
+
node.assignments.push({ taskId: task.taskId, specVersion: 1, generation: 0, assignedAt: now, spec: task.spec });
|
|
88
|
+
node.load += task.cost ?? 1;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
for (const task of tasks) {
|
|
93
|
+
const active = owners(task);
|
|
94
|
+
const confirmed = active.filter((node) => { return wanted(task, node) && node.assignments.some((row) => { return row.taskId === task.taskId && same(row.spec, task.spec); }) && freshRead(observed.get(node.id), node.assignments.find((row) => { return row.taskId === task.taskId; }), { now, freshnessMs, controlEpoch, clockSkewMs }); });
|
|
95
|
+
if (confirmed.length >= copies(task)) {
|
|
96
|
+
const keep = new Set(confirmed.slice(0, copies(task)).map((node) => { return node.id; }));
|
|
97
|
+
slots.filter((node) => { return node.live && !keep.has(node.id); }).forEach((node) => {
|
|
98
|
+
node.assignments = node.assignments.filter((row) => { return row.taskId !== task.taskId; });
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return snapshots(slots, taskMap, catalog, observed, { now, freshnessMs, clockSkewMs });
|
|
103
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { mkdir, open, readFile, rename, unlink } from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
export function checkSnapshot(value) {
|
|
5
|
+
if (!value || !Number.isSafeInteger(value.generation) || value.generation < 0 || !Array.isArray(value.assignments)) { throw new TypeError('Invalid assignment snapshot'); }
|
|
6
|
+
return value;
|
|
7
|
+
}
|
|
8
|
+
export async function loadSnapshot(file) {
|
|
9
|
+
try { return checkSnapshot(JSON.parse(await readFile(file, 'utf8'))); } catch (error) { if (error.code === 'ENOENT') { return null; } throw error; }
|
|
10
|
+
}
|
|
11
|
+
export async function saveSnapshot(file, snapshot) {
|
|
12
|
+
checkSnapshot(snapshot);
|
|
13
|
+
await mkdir(path.dirname(file), { recursive: true });
|
|
14
|
+
const temporary = `${file}.${randomUUID()}.tmp`;
|
|
15
|
+
try {
|
|
16
|
+
const handle = await open(temporary, 'wx', 0o600);
|
|
17
|
+
try { await handle.writeFile(JSON.stringify(snapshot)); await handle.sync(); } finally { await handle.close(); }
|
|
18
|
+
await rename(temporary, file);
|
|
19
|
+
const directory = await open(path.dirname(file), 'r');
|
|
20
|
+
try { await directory.sync(); } finally { await directory.close(); }
|
|
21
|
+
} finally { await unlink(temporary).catch(() => {
|
|
22
|
+
// Rename may already have consumed the temporary file.
|
|
23
|
+
}); }
|
|
24
|
+
}
|
|
@@ -18,5 +18,6 @@ export default function foldedMetricsSink(inner, pool, devices) {
|
|
|
18
18
|
if (!devices || Object.keys(devices).length === 0) {
|
|
19
19
|
return inner;
|
|
20
20
|
}
|
|
21
|
+
if (inner.requireTimestamp) { throw new TypeError('Central telemetry policy cannot be combined with interval folding'); }
|
|
21
22
|
return foldingSink(inner, intervalFold(intervalFoldPg(pool)), opcuaLocate(devices));
|
|
22
23
|
}
|
|
@@ -144,5 +144,5 @@ export default function registerResources(server, tree, catalog) {
|
|
|
144
144
|
return tags(catalog);
|
|
145
145
|
});
|
|
146
146
|
publish(server, 'schema-postgres', 'plant://schema/postgres', 'Postgres tables from scada migrations', postgresSchema);
|
|
147
|
-
publish(server, 'schema-clickhouse', 'plant://schema/clickhouse', 'ClickHouse
|
|
147
|
+
publish(server, 'schema-clickhouse', 'plant://schema/clickhouse', 'ClickHouse adaptive and full canonical metric views', clickhouseSchema);
|
|
148
148
|
}
|
|
@@ -78,7 +78,7 @@ export function postgresSchema() {
|
|
|
78
78
|
}
|
|
79
79
|
|
|
80
80
|
/**
|
|
81
|
-
* ClickHouse metrics
|
|
81
|
+
* ClickHouse canonical metrics view. topic is the only series key.
|
|
82
82
|
*
|
|
83
83
|
* @returns {object} schema body
|
|
84
84
|
*
|
|
@@ -88,11 +88,16 @@ export function postgresSchema() {
|
|
|
88
88
|
export function clickhouseSchema() {
|
|
89
89
|
return {
|
|
90
90
|
tables: [
|
|
91
|
-
table('scada.
|
|
91
|
+
table('scada.metrics_read', [
|
|
92
92
|
{ name: 'topic', type: 'String' },
|
|
93
93
|
{ name: 'ts', type: 'DateTime64(3)' },
|
|
94
94
|
{ name: 'value', type: 'Float64' }
|
|
95
|
-
], ['topic is the only series key'])
|
|
95
|
+
], ['topic is the only series key', 'Legacy history and canonical telemetry; one row per topic and timestamp']),
|
|
96
|
+
table('scada.metrics_raw_read', [
|
|
97
|
+
{ name: 'topic', type: 'String' },
|
|
98
|
+
{ name: 'ts', type: 'DateTime64(3)' },
|
|
99
|
+
{ name: 'value', type: 'Float64' }
|
|
100
|
+
], ['Retained canonical point rows; sealed constant interiors are physically removed. Use bounded clickhouseMetricsRawRange for count/gap analytics; unavailable density is rejected explicitly.'])
|
|
96
101
|
]
|
|
97
102
|
};
|
|
98
103
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import ingestHealth from '../ingestHealth.js';
|
|
2
|
-
import {
|
|
2
|
+
import telemetrySink, { validateTelemetryPolicy } from './telemetrySink.js';
|
|
3
3
|
import mqttMetrics from '../../infrastructure/ingest/mqtt/mqttMetrics.js';
|
|
4
4
|
import amqpMetricsIngest from '../../infrastructure/ingest/telemetry/amqpMetricsIngest.js';
|
|
5
5
|
import operationSyncIngest from '../../infrastructure/sync/operationSyncIngest.js';
|
|
@@ -16,7 +16,7 @@ import resolveSecrets from './resolveSecrets.js';
|
|
|
16
16
|
|
|
17
17
|
function urlOptions(spec) {
|
|
18
18
|
const protocols = { mqtt: ['mqtt:', 'mqtts:', 'ws:', 'wss:'], amqp: ['amqp:', 'amqps:'], stomp: ['stomp:', 'stomps:'],
|
|
19
|
-
postgres: ['postgres:', 'postgresql:'], clickhouse: ['http:', 'https:'] };
|
|
19
|
+
postgres: ['postgres:', 'postgresql:'], clickhouse: ['http:', 'https:'], telemetryAmqp: ['amqp:', 'amqps:'] };
|
|
20
20
|
Object.entries(protocols).forEach(([key, allowed]) => {
|
|
21
21
|
const value = spec[key];
|
|
22
22
|
if (value === undefined || value?.$secret) { return; }
|
|
@@ -33,7 +33,7 @@ function boundedOptions(spec) {
|
|
|
33
33
|
prefetch: Math.min(spec.options?.prefetch ?? 32, maxRecords) };
|
|
34
34
|
}
|
|
35
35
|
function ownedSink(pipeline, sink) {
|
|
36
|
-
return { start() { return pipeline.start(); }, async stop() {
|
|
36
|
+
return { async start() { await sink.start?.(); return pipeline.start(); }, async stop() {
|
|
37
37
|
try { await pipeline.stop(); } finally { await sink.stop?.(); }
|
|
38
38
|
} };
|
|
39
39
|
}
|
|
@@ -52,7 +52,7 @@ function borrowed(pool) {
|
|
|
52
52
|
end() { return Promise.resolve(); } };
|
|
53
53
|
}
|
|
54
54
|
function telemetry(spec, pool) {
|
|
55
|
-
const inner = spec.clickhouse ?
|
|
55
|
+
const inner = spec.clickhouse ? telemetrySink(spec) : metricsSinkFromPool(pool, { firstWins: spec.firstWins === true });
|
|
56
56
|
return foldedMetricsSink(inner, pool, spec.devices);
|
|
57
57
|
}
|
|
58
58
|
function metrics(spec, pool, context) {
|
|
@@ -62,7 +62,8 @@ function metrics(spec, pool, context) {
|
|
|
62
62
|
function mqttPostgres(spec, pool, context) {
|
|
63
63
|
let failed = false;
|
|
64
64
|
context.report?.({ state: 'degraded' });
|
|
65
|
-
|
|
65
|
+
const sink = telemetry(spec, pool);
|
|
66
|
+
return ownedSink(mqttMetrics(spec.mqtt, sink, spec.topic, {
|
|
66
67
|
...boundedOptions(spec), budget: context.budget,
|
|
67
68
|
onReady() { if (!failed) { context.report?.({ state: 'running' }); } },
|
|
68
69
|
onError(error) {
|
|
@@ -71,7 +72,7 @@ function mqttPostgres(spec, pool, context) {
|
|
|
71
72
|
failed ||= ['WRITE_TIMEOUT', 'OPERATION_TIMEOUT'].includes(error.code);
|
|
72
73
|
context.report?.({ state: failed ? 'failed' : 'degraded', fatal: failed });
|
|
73
74
|
}
|
|
74
|
-
});
|
|
75
|
+
}), sink);
|
|
75
76
|
}
|
|
76
77
|
function silent(spec, pool, context) {
|
|
77
78
|
const sink = telemetry(spec, pool);
|
|
@@ -137,6 +138,9 @@ function task(factory, spec, context) {
|
|
|
137
138
|
function required(spec, keys) {
|
|
138
139
|
keys.forEach((key) => { if (!spec[key]) { throw new TypeError(`Missing ingest ${key}`); } });
|
|
139
140
|
}
|
|
141
|
+
function silentConfigStorage(spec) {
|
|
142
|
+
if (!spec.clickhouse && !spec.postgres) { throw new TypeError('Missing metrics storage'); }
|
|
143
|
+
}
|
|
140
144
|
function silentConfig(spec) {
|
|
141
145
|
if (!spec.clickhouse && !spec.postgres) { throw new TypeError('Missing silent metrics storage'); }
|
|
142
146
|
if (spec.devices && Object.keys(spec.devices).length && !spec.postgres) { throw new TypeError('Missing folding postgres'); }
|
|
@@ -148,7 +152,7 @@ function silentConfig(spec) {
|
|
|
148
152
|
})) { throw new TypeError('Invalid silent source'); }
|
|
149
153
|
}
|
|
150
154
|
function descriptor(factory, keys, validate = () => { return undefined; }, resources = () => { return []; }) {
|
|
151
|
-
return { validate(spec) { required(spec, keys); urlOptions(spec); boundedOptions(spec); validate(spec); }, resources,
|
|
155
|
+
return { validate(spec) { required(spec, keys); urlOptions(spec); boundedOptions(spec); validateTelemetryPolicy(spec); validate(spec); }, resources,
|
|
152
156
|
create(spec, context) { return task(factory, spec, context); } };
|
|
153
157
|
}
|
|
154
158
|
/** Portable consumers previously embedded in site HTTP processes; migrations remain external. */
|
|
@@ -157,8 +161,8 @@ export default function additionalAdapters() {
|
|
|
157
161
|
['operation-sync', descriptor((spec, pool, context) => {
|
|
158
162
|
return operationSyncIngest(spec.amqp, spec.queue, operationsFromPg(pool), { ...boundedOptions(spec), budget: context.budget });
|
|
159
163
|
}, ['amqp', 'queue', 'postgres'])],
|
|
160
|
-
['amqp-pg-metrics', descriptor(metrics, ['amqp', 'queue',
|
|
161
|
-
['mqtt-pg-metrics', descriptor(mqttPostgres, ['mqtt', 'topic',
|
|
164
|
+
['amqp-pg-metrics', descriptor(metrics, ['amqp', 'queue'], silentConfigStorage)],
|
|
165
|
+
['mqtt-pg-metrics', descriptor(mqttPostgres, ['mqtt', 'topic'], silentConfigStorage)],
|
|
162
166
|
['silent-streams', descriptor(silent, ['amqp', 'queue', 'sources'], silentConfig, (spec) => {
|
|
163
167
|
return [...new Set(spec.sources.map((source) => { return `modbus-tcp:${source.host}:${source.port}`; }))];
|
|
164
168
|
})],
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import deliverySpool from '../../infrastructure/persistence/runtime/deliverySpool.js';
|
|
2
|
+
import deliverySessions from './deliverySessions.js';
|
|
3
|
+
|
|
4
|
+
function confirmed(event) {
|
|
5
|
+
return { ...event, options: { ...event.options, persistent: true, mandatory: true, messageId: event.eventId } };
|
|
6
|
+
}
|
|
7
|
+
/* eslint max-lines-per-function: ["error", 60] */
|
|
8
|
+
/** Node-owned queue: removing a source does not remove its destination descriptors or receipts. */
|
|
9
|
+
export default function deliveryQueue(directory, options) {
|
|
10
|
+
const spool = deliverySpool(directory, options);
|
|
11
|
+
const sessions = deliverySessions(options.factory, options.writeTimeoutMs);
|
|
12
|
+
let chain = Promise.resolve();
|
|
13
|
+
const state = { pending: 0, draining: false, closed: false };
|
|
14
|
+
function serialized(action) {
|
|
15
|
+
if (state.pending >= (options.maxOperations ?? 32)) { return Promise.reject(new Error('Delivery operation capacity exceeded')); }
|
|
16
|
+
state.pending += 1;
|
|
17
|
+
const result = chain.then(action).finally(() => { state.pending -= 1; });
|
|
18
|
+
chain = result.catch(() => {
|
|
19
|
+
// Individual callers receive rejection; preserve serialization.
|
|
20
|
+
});
|
|
21
|
+
return result;
|
|
22
|
+
}
|
|
23
|
+
async function send(record, id) {
|
|
24
|
+
if (state.closed) { throw new Error('Delivery queue closed'); }
|
|
25
|
+
const descriptor = record.event.destinations.find((item) => { return item.id === id; });
|
|
26
|
+
await sessions.write(descriptor, confirmed(record.event.observation));
|
|
27
|
+
await serialized(() => { return spool.ack(record.event.eventId, id); });
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
return {
|
|
31
|
+
open() { return serialized(() => { return spool.open(); }); },
|
|
32
|
+
accept(event, destinations) {
|
|
33
|
+
if (state.closed) { return Promise.reject(new Error('Delivery queue closed')); }
|
|
34
|
+
if (!destinations?.length || destinations.some((item) => { return item.type !== 'amqp'; })) {
|
|
35
|
+
return Promise.reject(new TypeError('Queued delivery requires confirmed AMQP destinations'));
|
|
36
|
+
}
|
|
37
|
+
// Snapshot before asynchronous I/O; callers may reuse buffers/objects.
|
|
38
|
+
const envelope = JSON.parse(JSON.stringify({ eventId: event.eventId, observation: event, destinations }));
|
|
39
|
+
return serialized(() => { return spool.append(envelope, destinations.map((item) => { return item.id; })); });
|
|
40
|
+
},
|
|
41
|
+
async drain() {
|
|
42
|
+
if (state.draining || state.closed) { return { delivered: 0, failed: 0 }; }
|
|
43
|
+
state.draining = true;
|
|
44
|
+
const result = { delivered: 0, failed: 0 };
|
|
45
|
+
try {
|
|
46
|
+
const rows = await serialized(() => { return spool.pending(options.batchSize ?? 100); });
|
|
47
|
+
for (const row of rows) {
|
|
48
|
+
for (const id of row.remaining) {
|
|
49
|
+
// Recipients fail independently; continue draining other destinations.
|
|
50
|
+
// eslint-disable-next-line no-await-in-loop, max-depth
|
|
51
|
+
try { await send(row, id); result.delivered += 1; } catch (error) {
|
|
52
|
+
result.failed += 1; options.onError?.(error);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return result;
|
|
57
|
+
} finally { Object.assign(state, { draining: false }); }
|
|
58
|
+
},
|
|
59
|
+
close() { state.closed = true; return sessions.close(); },
|
|
60
|
+
status() { return spool.status(); }
|
|
61
|
+
};
|
|
62
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import deadline from './deadline.js';
|
|
2
|
+
|
|
3
|
+
/** Bounded reusable AMQP connections, independent of collector task lifecycles. */
|
|
4
|
+
export default function deliverySessions(factory, timeoutMs = 10000) {
|
|
5
|
+
const sessions = new Map();
|
|
6
|
+
return {
|
|
7
|
+
async write(descriptor, event) {
|
|
8
|
+
const key = JSON.stringify(descriptor);
|
|
9
|
+
let sink = sessions.get(key);
|
|
10
|
+
if (!sink) {
|
|
11
|
+
if (sessions.size >= 64) { throw new Error('Delivery session capacity exceeded'); }
|
|
12
|
+
sink = factory(descriptor); sessions.set(key, sink);
|
|
13
|
+
try { await deadline(() => { return sink.start?.(); }, timeoutMs); } catch (error) {
|
|
14
|
+
sessions.delete(key);
|
|
15
|
+
await deadline(() => { return sink.stop?.(); }, timeoutMs).catch(() => {
|
|
16
|
+
// Original failure propagates.
|
|
17
|
+
});
|
|
18
|
+
throw error;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
await deadline(() => { return sink.write([event]); }, timeoutMs);
|
|
22
|
+
},
|
|
23
|
+
async close() {
|
|
24
|
+
await Promise.allSettled(Array.from(sessions.values(), (sink) => { return deadline(() => { return sink.stop?.(); }, timeoutMs); }));
|
|
25
|
+
sessions.clear();
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import modbusPublish from '../../infrastructure/ingest/mqtt/modbusPublish.js';
|
|
3
|
+
|
|
4
|
+
function runtimeConfig(spec,context) {
|
|
5
|
+
return {...spec.config,onFatal(error) {
|
|
6
|
+
context.report?.({state:'failed',fatal:true,reason:error.code??error.name});
|
|
7
|
+
spec.config.onFatal?.(error);
|
|
8
|
+
}};
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** Preserve the telemetry wire contract while moving durable buffering ahead of the network. */
|
|
12
|
+
export default function modbusDelivery(spec, context, publish = modbusPublish) {
|
|
13
|
+
const config=runtimeConfig(spec,context);
|
|
14
|
+
if (spec.delivery !== 'spooled') { return publish(spec.url, config); }
|
|
15
|
+
if (!context.deliveryQueue || !spec.sinks?.length || spec.sinks.some((sink) => { return sink.type !== 'amqp'; })) {
|
|
16
|
+
throw new TypeError('Spooled Modbus requires node queue and AMQP destinations');
|
|
17
|
+
}
|
|
18
|
+
const output = {
|
|
19
|
+
start() { return Promise.resolve(); },
|
|
20
|
+
stop() { return Promise.resolve(); },
|
|
21
|
+
async write(records) {
|
|
22
|
+
context.signal?.throwIfAborted();
|
|
23
|
+
context.report?.({ state: 'running', read: 1 });
|
|
24
|
+
for (const record of records) {
|
|
25
|
+
const routingKey = record.topic.replaceAll('/', '.');
|
|
26
|
+
const destinations = spec.sinks.filter((sink) => { return !sink.routingKeyPrefix || routingKey.startsWith(sink.routingKeyPrefix); });
|
|
27
|
+
if (!destinations.length) { throw new Error('No matching Modbus telemetry recipient'); }
|
|
28
|
+
// Retain each decoded observation durably before completing source acceptance.
|
|
29
|
+
// eslint-disable-next-line no-await-in-loop
|
|
30
|
+
await context.deliveryQueue.accept({ eventId: record.eventId ?? randomUUID(),
|
|
31
|
+
exchange: 'scada.telemetry', routingKey, body: Buffer.from(record.payload) }, destinations);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
return publish(spec.url, { ...config, size: 1, output });
|
|
36
|
+
}
|
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { mqttSink } from '../../infrastructure/streams/index.js';
|
|
2
|
+
import telemetrySink, { validateTelemetryPolicy } from './telemetrySink.js';
|
|
2
3
|
import activityTracking from '../../infrastructure/ingest/activity/activityTracking.js';
|
|
3
4
|
import amqpMetricsIngest from '../../infrastructure/ingest/telemetry/amqpMetricsIngest.js';
|
|
4
5
|
import amqpMqttRelay from '../../infrastructure/ingest/telemetry/amqpMqttRelay.js';
|
|
5
|
-
import
|
|
6
|
+
import modbusDelivery from './modbusDelivery.js';
|
|
6
7
|
import mqttMetrics from '../../infrastructure/ingest/mqtt/mqttMetrics.js';
|
|
7
8
|
import { parseModbusDeviceSpec } from '../../infrastructure/ingest/mqtt/modbusDeviceSpec.js';
|
|
8
9
|
import compositeLifecycle from './compositeLifecycle.js';
|
|
@@ -11,7 +12,9 @@ import resolveSecrets from './resolveSecrets.js';
|
|
|
11
12
|
function configured(spec, context) {
|
|
12
13
|
const options = { maxRecords: spec.limits?.maxRecords, maxBytes: spec.limits?.maxBytes, budget: context.budget };
|
|
13
14
|
const defined = Object.fromEntries(Object.entries(options).filter(([, value]) => { return value !== undefined; }));
|
|
14
|
-
|
|
15
|
+
const { sinks, ...source } = spec;
|
|
16
|
+
return { ...resolveSecrets(source, context.secrets),
|
|
17
|
+
...(sinks !== undefined && { sinks: structuredClone(sinks) }),
|
|
15
18
|
config: { ...resolveSecrets(spec.config, context.secrets), ...defined },
|
|
16
19
|
options: { ...resolveSecrets(spec.options, context.secrets), ...defined } };
|
|
17
20
|
}
|
|
@@ -19,6 +22,7 @@ function adapter(factory, required, resourceKeys = () => { return []; }) {
|
|
|
19
22
|
return {
|
|
20
23
|
validate(spec) {
|
|
21
24
|
required.forEach((key) => { if (!spec[key]) { throw new TypeError(`Missing pipeline ${key}`); } });
|
|
25
|
+
validateTelemetryPolicy(spec);
|
|
22
26
|
},
|
|
23
27
|
resources(spec) { return resourceKeys(spec); },
|
|
24
28
|
create(spec, context) {
|
|
@@ -46,14 +50,14 @@ function modbusResources(spec) {
|
|
|
46
50
|
return [...new Set(paths)];
|
|
47
51
|
}
|
|
48
52
|
function metrics(spec, factory) {
|
|
49
|
-
const sink =
|
|
50
|
-
return compositeLifecycle({ outputs: [sink
|
|
53
|
+
const sink = telemetrySink(spec);
|
|
54
|
+
return compositeLifecycle({ outputs: [{ start() { return sink.start?.(); }, async stop() {
|
|
55
|
+
await sink.stop();
|
|
56
|
+
} }], inputs: [factory(sink)] });
|
|
51
57
|
}
|
|
52
58
|
export default function pipelineAdapters() {
|
|
53
59
|
return new Map([
|
|
54
|
-
['modbus', adapter((spec, context) => { return
|
|
55
|
-
context.report?.({ state: 'failed', fatal: true, reason: error.code ?? error.name });
|
|
56
|
-
} }); }, ['url', 'config'], modbusResources)],
|
|
60
|
+
['modbus', adapter((spec, context) => { return modbusDelivery(spec, context); }, ['url', 'config'], modbusResources)],
|
|
57
61
|
['activity', adapter((spec) => { return activityTracking(spec.lokiUrl, spec.clickhouseUrl, spec.query, spec.config); }, ['lokiUrl', 'clickhouseUrl', 'query', 'config'])],
|
|
58
62
|
['amqp-relay', adapter((spec) => { return amqpMqttRelay(spec.url, spec.queue, mqttSink(spec.mqttUrl, spec.options), spec.options); }, ['url', 'queue', 'mqttUrl'])],
|
|
59
63
|
['amqp-metrics', adapter((spec) => { return metrics(spec, (sink) => { return amqpMetricsIngest(spec.url, spec.queue, sink, spec.options); }); }, ['url', 'queue', 'clickhouseUrl', 'table'])],
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import deliveryQueue from './deliveryQueue.js';
|
|
2
|
+
import { sinks } from './streamPorts.js';
|
|
3
|
+
|
|
4
|
+
/** Configured once per node; queue draining outlives any individual assignment. */
|
|
5
|
+
export default function queuedDelivery(env, secrets, supplied) {
|
|
6
|
+
let timer;
|
|
7
|
+
let stopped = false;
|
|
8
|
+
const queue = supplied ?? (env.COLLECTOR_SPOOL_DIR ? deliveryQueue(env.COLLECTOR_SPOOL_DIR, {
|
|
9
|
+
maxBytes: Number(env.COLLECTOR_SPOOL_MAX_BYTES), maxRecords: Number(env.COLLECTOR_SPOOL_MAX_RECORDS ?? 100000), factory(spec) { return sinks().get(spec.type)(spec, { secrets }); },
|
|
10
|
+
onError(error) { process.stderr.write(`Collector delivery delayed: ${error.message}\n`); }
|
|
11
|
+
}) : undefined);
|
|
12
|
+
async function tick() {
|
|
13
|
+
if (stopped || !queue) { return; }
|
|
14
|
+
try {
|
|
15
|
+
if (queue.status?.().ready === false) { await queue.open(); }
|
|
16
|
+
await queue.drain();
|
|
17
|
+
} catch (error) { process.stderr.write(`Collector spool: ${error.message}\n`); }
|
|
18
|
+
if (!stopped) { timer = setTimeout(tick, 1000); timer.unref(); }
|
|
19
|
+
}
|
|
20
|
+
return {
|
|
21
|
+
queue,
|
|
22
|
+
async open() { if (queue) { await queue.open(); timer = setTimeout(tick, 0); timer.unref(); } },
|
|
23
|
+
stop() { stopped = true; clearTimeout(timer); return queue?.close?.(); }
|
|
24
|
+
};
|
|
25
|
+
}
|
|
@@ -3,6 +3,10 @@ import collectorSignals from './collectorSignals.js';
|
|
|
3
3
|
import createRuntime from './runtime.js';
|
|
4
4
|
import runtimeServices from './runtimeServices.js';
|
|
5
5
|
import runtimeHealth from './runtimeHealth.js';
|
|
6
|
+
import deadline from './deadline.js';
|
|
7
|
+
import assignmentAgent from '../control/agent.js';
|
|
8
|
+
import controlStore from '../control/controlStore.js';
|
|
9
|
+
import { clientFromEnv } from '../control/controlClient.js';
|
|
6
10
|
|
|
7
11
|
async function apply(runtime, document) {
|
|
8
12
|
for (const removal of document.removals ?? []) {
|
|
@@ -16,11 +20,33 @@ async function apply(runtime, document) {
|
|
|
16
20
|
await runtime.apply(input);
|
|
17
21
|
}
|
|
18
22
|
}
|
|
23
|
+
function healthView(runtime, state) {
|
|
24
|
+
return { status() {
|
|
25
|
+
const status = runtime.status();
|
|
26
|
+
return { ...status, stopping: status.stopping || state.stopped, fatal: status.fatal || state.failed,
|
|
27
|
+
initialized: state.initialized && (!state.agent || state.agent.status().appliedGeneration !== null) };
|
|
28
|
+
} };
|
|
29
|
+
}
|
|
30
|
+
async function initialize(collector, owned, state, { env, registry }) {
|
|
31
|
+
const { runtime } = collector;
|
|
32
|
+
await owned.open?.();
|
|
33
|
+
if (state.stopped) { throw new Error('Collector stopped during recovery'); }
|
|
34
|
+
if (env.COLLECTOR_CONTROL_ENDPOINTS) {
|
|
35
|
+
const store = controlStore(clientFromEnv(env, 'COLLECTOR_CONTROL'), env.COLLECTOR_CONTROL_PREFIX);
|
|
36
|
+
state.agent = assignmentAgent({ nodeId: env.COLLECTOR_NODE_ID, file: env.COLLECTOR_ASSIGNMENT_FILE, store, runtime,
|
|
37
|
+
validate(document) { return validateManifest(document, registry); },
|
|
38
|
+
onError(error) { process.stderr.write(`collector control: ${error.name}\n`); } });
|
|
39
|
+
await state.agent.start({ waitForInitialTick: false });
|
|
40
|
+
} else { await collector.reload(); }
|
|
41
|
+
if (state.stopped) { throw new Error('Collector stopped during recovery'); }
|
|
42
|
+
state.initialized = true;
|
|
43
|
+
}
|
|
19
44
|
/** Local executable host. The external agent can instead use createRuntime directly. */
|
|
45
|
+
// eslint-disable-next-line max-statements
|
|
20
46
|
export default async function runCollector({ registry, env = process.env, argv = process.argv.slice(2), signals = true, manifestReader = readManifest, ...services }) {
|
|
21
47
|
const owned = runtimeServices(env, services);
|
|
22
48
|
const runtime = createRuntime({ registry, ...owned });
|
|
23
|
-
const state = { health: null, reloading: false, stopped: false, detach: null };
|
|
49
|
+
const state = { initialized: false, failed: false, health: null, reloading: false, stopped: false, detach: null, agent: null };
|
|
24
50
|
const collector = {
|
|
25
51
|
runtime,
|
|
26
52
|
async reload() {
|
|
@@ -35,14 +61,19 @@ export default async function runCollector({ registry, env = process.env, argv =
|
|
|
35
61
|
async stop() {
|
|
36
62
|
state.stopped = true;
|
|
37
63
|
state.detach?.();
|
|
64
|
+
await state.agent?.stop();
|
|
38
65
|
try { await runtime.stop(); } finally { await Promise.all([owned.close(), state.health?.stop()]); }
|
|
39
66
|
}
|
|
40
67
|
};
|
|
41
68
|
if (signals) { state.detach = collectorSignals(collector); }
|
|
42
69
|
try {
|
|
43
|
-
|
|
44
|
-
|
|
70
|
+
if (env.COLLECTOR_HEALTH_PORT) { Object.assign(state, { health: await runtimeHealth(healthView(runtime, state), {
|
|
71
|
+
port: Number(env.COLLECTOR_HEALTH_PORT), host: env.COLLECTOR_HEALTH_HOST ?? '127.0.0.1' }) }); }
|
|
72
|
+
const recoveryMs = Number(env.COLLECTOR_RECOVERY_TIMEOUT_MS ?? 900000);
|
|
73
|
+
if (!Number.isSafeInteger(recoveryMs) || recoveryMs < 1) { throw new TypeError('Positive collector recovery timeout required'); }
|
|
74
|
+
await deadline(() => { return initialize(collector, owned, state, { env, registry }); }, recoveryMs);
|
|
45
75
|
} catch (error) {
|
|
76
|
+
Object.assign(state, { failed: true });
|
|
46
77
|
try { await collector.stop(); } catch (cleanup) { throw new AggregateError([error, cleanup], 'Collector startup cleanup failed'); }
|
|
47
78
|
throw error;
|
|
48
79
|
}
|
|
@@ -35,7 +35,7 @@ function duplicate(slot, request) {
|
|
|
35
35
|
}
|
|
36
36
|
if (request.generation !== slot.generation) { return false; }
|
|
37
37
|
if (slot.specHash !== request.specHash) { throw new Error('assignment conflict'); }
|
|
38
|
-
return
|
|
38
|
+
return slot.state !== 'failed';
|
|
39
39
|
}
|
|
40
40
|
async function apply(ctx, input, slot) {
|
|
41
41
|
if (ctx.fatal || ctx.stopping) { throw new Error('Runtime stopping or fatal'); }
|
|
@@ -75,7 +75,7 @@ export default function createRuntime(options) {
|
|
|
75
75
|
maxTasks: positive(options.maxTasks ?? 1000), maxPending: positive(options.maxPending ?? 100),
|
|
76
76
|
stopTimeoutMs: positive(options.stopTimeoutMs ?? 10000), startTimeoutMs: positive(options.startTimeoutMs ?? 10000),
|
|
77
77
|
budget: taskBudget(options.budgets ?? { maxBytes: 16777216, maxRecords: 16384 }),
|
|
78
|
-
services: { stateStore: options.stateStore, secrets: options.secrets, report: options.report } };
|
|
78
|
+
services: { stateStore: options.stateStore, secrets: options.secrets, report: options.report, deliveryQueue: options.deliveryQueue } };
|
|
79
79
|
if (!(ctx.registry instanceof Map)) { throw new TypeError('registry must be a Map'); }
|
|
80
80
|
return {
|
|
81
81
|
apply(input) { return enqueue(ctx, input, (slot) => { return apply(ctx, input, slot); }); },
|