@yarkivaev/scada 2.6.13 → 2.6.17
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/package.json +1 -1
- package/src/application/control/controlStore.js +10 -0
- package/src/application/runtime/deliveryQueue.js +4 -0
- package/src/application/runtime/runCollector.js +9 -6
- package/src/application/runtime/runtime.js +1 -1
- package/src/application/runtime/runtimeHealth.js +4 -3
- package/src/application/runtime/spoolHistory.js +76 -0
- package/src/application/runtime/spoolSurface.js +24 -0
- package/src/infrastructure/persistence/runtime/deliverySpool.js +7 -1
- package/src/infrastructure/persistence/runtime/spoolRecords.js +3 -0
package/package.json
CHANGED
|
@@ -4,6 +4,15 @@ function encoded(value) { return Buffer.from(value).toString('base64'); }
|
|
|
4
4
|
function decoded(value) { return Buffer.from(value, 'base64').toString(); }
|
|
5
5
|
function put(key, value, lease) { return { request_put: { key: encoded(key), value: encoded(JSON.stringify(value)), ...(lease && { lease }) } }; }
|
|
6
6
|
function revision(key, value) { return { key: encoded(key), target: 'MOD', result: 'EQUAL', mod_revision: String(value) }; }
|
|
7
|
+
function cursor(call, root, range) {
|
|
8
|
+
return {
|
|
9
|
+
async load(taskId) {
|
|
10
|
+
const row = await range(`${root}/cursors/${taskId}`);
|
|
11
|
+
return row ? JSON.parse(decoded(row.value)) : null;
|
|
12
|
+
},
|
|
13
|
+
save(taskId, value) { return call('/v3/kv/put', put(`${root}/cursors/${taskId}`, value).request_put); }
|
|
14
|
+
};
|
|
15
|
+
}
|
|
7
16
|
export default function controlStore(call, prefix = '/scada/control') {
|
|
8
17
|
const root = prefix.replace(/\/$/u, '');
|
|
9
18
|
const lock = `${root}/leader`;
|
|
@@ -41,6 +50,7 @@ export default function controlStore(call, prefix = '/scada/control') {
|
|
|
41
50
|
return Boolean(result.succeeded);
|
|
42
51
|
},
|
|
43
52
|
async assignment(id) { const row = await range(`${root}/assignments/${id}`); return row ? JSON.parse(decoded(row.value)) : null; },
|
|
53
|
+
cursor: cursor(call, root, range),
|
|
44
54
|
report(id, value) { return call('/v3/kv/put', put(`${root}/reports/${id}`, value).request_put); },
|
|
45
55
|
async publish(catalog, expectedRevision) {
|
|
46
56
|
validateCatalog(catalog);
|
|
@@ -91,6 +91,10 @@ export default function deliveryQueue(directory, options) {
|
|
|
91
91
|
})().catch((error) => { state.closing = null; throw error; });
|
|
92
92
|
return state.closing;
|
|
93
93
|
},
|
|
94
|
+
peek(limit = 1000) {
|
|
95
|
+
if (state.closed) { return Promise.reject(new Error('Delivery queue closed')); }
|
|
96
|
+
return commands.barrier(() => { return spool.peek(limit); });
|
|
97
|
+
},
|
|
94
98
|
status() {
|
|
95
99
|
const usage = commands.status();
|
|
96
100
|
return { ...spool.status(), queuedOperations: usage.operations, queuedBytes: usage.bytes, drainFull: state.full };
|
|
@@ -3,6 +3,7 @@ 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 spoolSurface from './spoolSurface.js';
|
|
6
7
|
import deadline from './deadline.js';
|
|
7
8
|
import assignmentAgent from '../control/agent.js';
|
|
8
9
|
import controlStore from '../control/controlStore.js';
|
|
@@ -27,12 +28,11 @@ function healthView(runtime, state) {
|
|
|
27
28
|
initialized: state.initialized && (!state.agent || state.agent.status().appliedGeneration !== null) };
|
|
28
29
|
} };
|
|
29
30
|
}
|
|
30
|
-
async function initialize(collector, owned, state, { env, registry }) {
|
|
31
|
+
async function initialize(collector, owned, state, { env, registry, store }) {
|
|
31
32
|
const { runtime } = collector;
|
|
32
33
|
await owned.open?.();
|
|
33
34
|
if (state.stopped) { throw new Error('Collector stopped during recovery'); }
|
|
34
|
-
if (
|
|
35
|
-
const store = controlStore(clientFromEnv(env, 'COLLECTOR_CONTROL'), env.COLLECTOR_CONTROL_PREFIX);
|
|
35
|
+
if (store) {
|
|
36
36
|
state.agent = assignmentAgent({ nodeId: env.COLLECTOR_NODE_ID, file: env.COLLECTOR_ASSIGNMENT_FILE, store, runtime,
|
|
37
37
|
validate(document) { return validateManifest(document, registry); },
|
|
38
38
|
onError(error) { process.stderr.write(`collector control: ${error.name}\n`); } });
|
|
@@ -44,7 +44,9 @@ async function initialize(collector, owned, state, { env, registry }) {
|
|
|
44
44
|
/** Local executable host. The external agent can instead use createRuntime directly. */
|
|
45
45
|
// eslint-disable-next-line max-statements
|
|
46
46
|
export default async function runCollector({ registry, env = process.env, argv = process.argv.slice(2), signals = true, manifestReader = readManifest, ...services }) {
|
|
47
|
-
const
|
|
47
|
+
const store = env.COLLECTOR_CONTROL_ENDPOINTS
|
|
48
|
+
? controlStore(clientFromEnv(env, 'COLLECTOR_CONTROL'), env.COLLECTOR_CONTROL_PREFIX) : null;
|
|
49
|
+
const owned = runtimeServices(env, { ...services, cursor: services.cursor ?? store?.cursor });
|
|
48
50
|
const runtime = createRuntime({ registry, ...owned });
|
|
49
51
|
const state = { initialized: false, failed: false, health: null, reloading: false, stopped: false, detach: null, agent: null };
|
|
50
52
|
const collector = {
|
|
@@ -68,10 +70,11 @@ export default async function runCollector({ registry, env = process.env, argv =
|
|
|
68
70
|
if (signals) { state.detach = collectorSignals(collector); }
|
|
69
71
|
try {
|
|
70
72
|
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'
|
|
73
|
+
port: Number(env.COLLECTOR_HEALTH_PORT), host: env.COLLECTOR_HEALTH_HOST ?? '127.0.0.1',
|
|
74
|
+
handle: spoolSurface(owned.deliveryQueue, env.STATE_HTTP_TOKEN) }) }); }
|
|
72
75
|
const recoveryMs = Number(env.COLLECTOR_RECOVERY_TIMEOUT_MS ?? 900000);
|
|
73
76
|
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);
|
|
77
|
+
await deadline(() => { return initialize(collector, owned, state, { env, registry, store }); }, recoveryMs);
|
|
75
78
|
} catch (error) {
|
|
76
79
|
Object.assign(state, { failed: true });
|
|
77
80
|
try { await collector.stop(); } catch (cleanup) { throw new AggregateError([error, cleanup], 'Collector startup cleanup failed'); }
|
|
@@ -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, deliveryQueue: options.deliveryQueue } };
|
|
78
|
+
services: { stateStore: options.stateStore, secrets: options.secrets, report: options.report, deliveryQueue: options.deliveryQueue, cursor: options.cursor } };
|
|
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); }); },
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { createServer } from 'node:http';
|
|
2
2
|
import { monitorEventLoopDelay } from 'node:perf_hooks';
|
|
3
3
|
|
|
4
|
-
function response(runtime, histogram, request, result) {
|
|
4
|
+
function response(runtime, histogram, request, result, handle) {
|
|
5
|
+
if (handle?.(request, result)) { return; }
|
|
5
6
|
if (!['/live', '/ready', '/status'].includes(request.url)) { result.writeHead(404).end(); return; }
|
|
6
7
|
const state = runtime.status();
|
|
7
8
|
const ready = state.initialized !== false && !state.fatal && !state.stopping && !state.tasks.some((task) => {
|
|
@@ -12,10 +13,10 @@ function response(runtime, histogram, request, result) {
|
|
|
12
13
|
result.end(JSON.stringify(body));
|
|
13
14
|
}
|
|
14
15
|
/** Read-only health surface. A blocked event loop cannot answer an external probe. */
|
|
15
|
-
export default async function runtimeHealth(runtime, { port, host = '127.0.0.1' }) {
|
|
16
|
+
export default async function runtimeHealth(runtime, { port, host = '127.0.0.1', handle = null }) {
|
|
16
17
|
if (!Number.isInteger(port) || port < 0 || port > 65535) { throw new TypeError('Invalid health port'); }
|
|
17
18
|
const histogram = monitorEventLoopDelay({ resolution: 20 });
|
|
18
|
-
const server = createServer((request, result) => { response(runtime, histogram, request, result); });
|
|
19
|
+
const server = createServer((request, result) => { response(runtime, histogram, request, result, handle); });
|
|
19
20
|
server.requestTimeout = 2000;
|
|
20
21
|
server.headersTimeout = 2000;
|
|
21
22
|
await new Promise((resolve, reject) => { server.once('error', reject); server.listen(port, host, resolve); });
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HistoryRun and SupervisorSinkCheckpoint view of undelivered collector samples.
|
|
3
|
+
*
|
|
4
|
+
* {{{
|
|
5
|
+
* spoolHistory({ peek() { return []; } }).work('icht2')
|
|
6
|
+
* }}}
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { nativeTailProtocol } from '../../infrastructure/persistence/pg/historyNativeBounds.js';
|
|
10
|
+
import { randomUUID } from 'node:crypto';
|
|
11
|
+
|
|
12
|
+
function machineOf(key) {
|
|
13
|
+
const match = /icht-?(?<n>\d)/iu.exec(String(key).replaceAll('/', '.'));
|
|
14
|
+
return match ? `icht${match.groups.n}` : null;
|
|
15
|
+
}
|
|
16
|
+
function channelOf(key) {
|
|
17
|
+
const parts = String(key).replaceAll('/', '.').split('.');
|
|
18
|
+
return parts.at(-2) ?? key;
|
|
19
|
+
}
|
|
20
|
+
function sample(record) {
|
|
21
|
+
const key = record.routingKey ?? record.topic;
|
|
22
|
+
const raw = record.body ? JSON.parse(Buffer.isBuffer(record.body) ? record.body.toString() : record.body) : record;
|
|
23
|
+
const time = Number(raw.ts ?? raw.time ?? raw.timestamp);
|
|
24
|
+
const value = Number(raw.value);
|
|
25
|
+
if (!key || !Number.isFinite(time) || !Number.isFinite(value)) { return []; }
|
|
26
|
+
return [{ eventId: record.eventId ?? `${key}:${time}`, channel: channelOf(key), topic: key.replaceAll('.', '/'),
|
|
27
|
+
time, timestamp: time / 1000, value, machine: machineOf(key) }];
|
|
28
|
+
}
|
|
29
|
+
function unpack(event) {
|
|
30
|
+
const payload = event.observation ?? event;
|
|
31
|
+
if (Array.isArray(payload.records)) { return payload.records.flatMap(sample); }
|
|
32
|
+
return sample({ ...payload, eventId: payload.eventId ?? event.eventId });
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Collector spool as a checkpoint and history receiver. */
|
|
36
|
+
export default function spoolHistory(queue) {
|
|
37
|
+
async function rows() {
|
|
38
|
+
if (!queue?.peek) { return []; }
|
|
39
|
+
const listed = await queue.peek(1000);
|
|
40
|
+
return listed.flatMap((item) => { return unpack(item.event ?? item); });
|
|
41
|
+
}
|
|
42
|
+
async function owned(machine) {
|
|
43
|
+
return (await rows()).filter((row) => { return row.machine === machine; });
|
|
44
|
+
}
|
|
45
|
+
return {
|
|
46
|
+
async replayCursor(machine) {
|
|
47
|
+
const times = (await owned(machine)).map((row) => { return row.timestamp; });
|
|
48
|
+
return times.length ? Math.min(...times) : 0;
|
|
49
|
+
},
|
|
50
|
+
pendingSegments() { return Promise.resolve([]); },
|
|
51
|
+
segment() { return Promise.resolve(null); },
|
|
52
|
+
cyclePrior() { return Promise.resolve([]); },
|
|
53
|
+
async readings(topics, from) {
|
|
54
|
+
const wanted = new Set(topics);
|
|
55
|
+
return (await rows()).filter((row) => { return row.timestamp >= from && (!wanted.size || wanted.has(row.topic)); })
|
|
56
|
+
.map((row) => { return { topic: row.topic, timestamp: row.timestamp, value: row.value }; });
|
|
57
|
+
},
|
|
58
|
+
configure() { return Promise.resolve({ nativeTailProtocol }); },
|
|
59
|
+
purge() { return Promise.resolve({}); },
|
|
60
|
+
accept() { return Promise.resolve({ inserted: 0 }); },
|
|
61
|
+
async work(machine) {
|
|
62
|
+
const items = await owned(machine);
|
|
63
|
+
if (!items.length) { return { items: [] }; }
|
|
64
|
+
const times = items.map((row) => { return row.time; });
|
|
65
|
+
return { items: [{ id: randomUUID(), token: randomUUID(), from: Math.min(...times), until: Math.max(...times) }] };
|
|
66
|
+
},
|
|
67
|
+
async context(machine, from, until) {
|
|
68
|
+
const items = (await owned(machine)).filter((row) => { return row.time >= from && row.time <= until; })
|
|
69
|
+
.map((row) => { return { eventId: row.eventId, channel: row.channel, time: row.time, value: row.value }; });
|
|
70
|
+
return { available: true, revision: 'spool', nativeTailMode: nativeTailProtocol,
|
|
71
|
+
context: { from, until }, items, segments: [], annotations: [],
|
|
72
|
+
continuity: items.length ? [{ from: items[0].time, until: items.at(-1).time }] : [] };
|
|
73
|
+
},
|
|
74
|
+
commit() { return Promise.resolve({}); }
|
|
75
|
+
};
|
|
76
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Mounts SupervisorSinkCheckpoint and HistoryRun routes on the collector health port.
|
|
3
|
+
*
|
|
4
|
+
* {{{
|
|
5
|
+
* spoolSurface(queue, token)
|
|
6
|
+
* }}}
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { routes } from '@yarkivaev/simple-server';
|
|
10
|
+
import checkpointRoutes from '../../infrastructure/http/edge/routes/checkpoint/checkpointRoutes.js';
|
|
11
|
+
import historyRoutes from '../../infrastructure/http/edge/routes/history/historyRoutes.js';
|
|
12
|
+
import spoolHistory from './spoolHistory.js';
|
|
13
|
+
|
|
14
|
+
/** True when the request was a spool history or checkpoint path. */
|
|
15
|
+
export default function spoolSurface(queue, token) {
|
|
16
|
+
if (!queue) { return null; }
|
|
17
|
+
const history = spoolHistory(queue);
|
|
18
|
+
const api = routes([...checkpointRoutes(token ?? null, history), ...historyRoutes(token ?? null, history)]);
|
|
19
|
+
return (request, result) => {
|
|
20
|
+
if (!request.url?.startsWith('/v1/')) { return false; }
|
|
21
|
+
void api.handle(request, result);
|
|
22
|
+
return true;
|
|
23
|
+
};
|
|
24
|
+
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { capacity, checkpoint, counters, database } from './spoolDatabase.js';
|
|
2
|
-
import { pending } from './spoolRecords.js';
|
|
2
|
+
import { listed, pending } from './spoolRecords.js';
|
|
3
3
|
import { pendingFair } from './spoolReplay.js';
|
|
4
4
|
import spoolMutations from './spoolMutations.js';
|
|
5
5
|
import spoolMigration from './spoolMigration.js';
|
|
@@ -62,6 +62,12 @@ export default function deliverySpool(directory, { maxBytes, maxRecords = 100000
|
|
|
62
62
|
return commit(() => { return pendingFair(state.db, limit, blocked); });
|
|
63
63
|
});
|
|
64
64
|
},
|
|
65
|
+
peek(limit = 1000) {
|
|
66
|
+
return exclusive(() => {
|
|
67
|
+
if (!Number.isSafeInteger(limit) || limit <= 0) { throw new TypeError('Positive peek limit required'); }
|
|
68
|
+
return listed(state.db, limit);
|
|
69
|
+
});
|
|
70
|
+
},
|
|
65
71
|
close() {
|
|
66
72
|
return exclusive(() => {
|
|
67
73
|
try { if (state.db) { checkpoint(state.db); } } finally { release(); }
|
|
@@ -50,4 +50,7 @@ export function pending(db, limit) {
|
|
|
50
50
|
db.prepare('UPDATE counters SET sequence=? WHERE id=1').run(sequence);
|
|
51
51
|
return rows.map((row) => { return decoded(row, db); });
|
|
52
52
|
}
|
|
53
|
+
export function listed(db, limit) {
|
|
54
|
+
return db.prepare('SELECT * FROM events ORDER BY sequence LIMIT ?').all(limit).map((row) => { return decoded(row, db); });
|
|
55
|
+
}
|
|
53
56
|
export function admission(db, maxBytes, maxRecords) { return capacity(db, maxBytes, maxRecords); }
|