@yarkivaev/scada 2.12.1 → 2.13.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 +1 -1
- package/db/migrations/E0013__history_staged_corrections.sql +1 -1
- package/db/migrations/E0017__history_live_covering.sql +1 -1
- package/db/migrations/E0025__history_processor_properties.sql +76 -0
- package/db/migrations/E0026__history_processor_properties_grants.sql +1 -0
- package/index.js +14 -2
- package/package.json +1 -1
- package/src/application/foldedMetricsSink.js +1 -1
- package/src/application/runtime/collectorStartup.js +23 -0
- package/src/application/runtime/index.js +2 -0
- package/src/application/runtime/queuedDelivery.js +1 -0
- package/src/application/runtime/runCollector.js +46 -9
- package/src/application/runtime/runtimeServices.js +20 -2
- package/src/application/runtime/spoolHistory.js +12 -12
- package/src/application/runtime/spoolSurface.js +2 -2
- package/src/application/runtime/spooledOutput.js +27 -0
- package/src/application/siteServer.js +2 -2
- package/src/application/supervisorSink.js +5 -6
- package/src/application/sync/publishingOperations.js +52 -0
- package/src/application/sync/siteSync.js +1 -1
- package/src/application/sync/siteSyncRows.js +1 -1
- package/src/application/sync/siteSyncSites.js +1 -1
- package/src/application/telemetry/telemetryBackfill.js +127 -0
- package/src/application/timelineOperatorFromEnv.js +1 -1
- package/src/domain/ingest/telemetryTimestamp.js +7 -0
- package/src/domain/segment/dispatch.js +19 -17
- package/src/domain/segment/historyFold.js +2 -1
- package/src/domain/segment/intervalFold.js +1 -1
- package/src/domain/segment/segmentContinue.js +1 -1
- package/src/infrastructure/catalog/tagCatalog.js +7 -11
- package/src/infrastructure/http/plant/json/decisionJson.js +1 -1
- package/src/infrastructure/http/plant/routes/timelineRoute.js +1 -1
- package/src/infrastructure/http/plant/timelineOperator.js +2 -2
- package/src/infrastructure/ingest/db/migrationProfile.js +2 -1
- package/src/infrastructure/ingest/pipelines/segmentPipeline.js +38 -14
- package/src/infrastructure/ingest/sinks/contiguousPhases.js +1 -1
- package/src/infrastructure/ingest/sinks/continuedSegments.js +9 -8
- package/src/infrastructure/ingest/sinks/decisionSegment.js +1 -1
- package/src/infrastructure/ingest/sinks/foldingSegments.js +16 -10
- package/src/infrastructure/ingest/sinks/{foldCastingPhases.js → repairPhaseOverlaps.js} +17 -29
- package/src/infrastructure/ingest/sinks/retagSink.js +1 -1
- package/src/infrastructure/ingest/sinks/userDecisionSink.js +1 -1
- package/src/infrastructure/ingest/telemetry/historyTelemetryMetrics.js +15 -0
- package/src/infrastructure/ingest/telemetry/opcuaLocate.js +2 -2
- package/src/infrastructure/ingest/telemetry/telemetryIngest.js +52 -0
- package/src/infrastructure/ingest/telemetry/telemetryReplay.js +15 -0
- package/src/infrastructure/messaging/stomp/retagBody.js +1 -1
- package/src/infrastructure/messaging/stomp/segmentRetags.js +1 -1
- package/src/infrastructure/persistence/clickhouse/historyObservations.js +149 -0
- package/src/infrastructure/persistence/clickhouse/historyRetention.js +94 -0
- package/src/infrastructure/persistence/clickhouse/historySourceIdentity.js +34 -0
- package/src/infrastructure/persistence/clickhouse/insertMetricRows.js +19 -0
- package/src/infrastructure/persistence/clickhouse/jsonMetrics.js +26 -0
- package/src/infrastructure/persistence/clickhouse/localHistory.js +51 -0
- package/src/infrastructure/persistence/clickhouse/metricsState.js +92 -0
- package/src/infrastructure/persistence/clickhouse/rowBinary.js +38 -0
- package/src/infrastructure/persistence/clickhouse/telemetryTarget.js +41 -0
- package/src/infrastructure/persistence/pg/checkpoints.js +35 -9
- package/src/infrastructure/persistence/pg/history.js +74 -56
- package/src/infrastructure/persistence/pg/historyContext.js +34 -17
- package/src/infrastructure/persistence/pg/historyCorrection.js +5 -2
- package/src/infrastructure/persistence/pg/historyFence.js +1 -1
- package/src/infrastructure/persistence/pg/historyNativeBounds.js +31 -0
- package/src/infrastructure/persistence/pg/historyPurge.js +26 -0
- package/src/infrastructure/persistence/pg/historySeed.js +3 -3
- package/src/infrastructure/persistence/pg/historySession.js +15 -0
- package/src/infrastructure/persistence/pg/intervalFoldPg.js +1 -1
- package/src/infrastructure/persistence/pg/telemetrySource.js +64 -0
- package/src/infrastructure/persistence/postgresPool.js +6 -1
- package/src/infrastructure/persistence/runtime/deliverySpool.js +11 -2
- package/src/infrastructure/persistence/runtime/spoolCheckpoints.js +65 -0
- package/src/infrastructure/persistence/runtime/spoolLimits.js +4 -2
- package/src/infrastructure/persistence/runtime/taskStateSqlite.js +37 -0
- package/src/infrastructure/persistence/stateDataFromPool.js +16 -2
- package/src/infrastructure/streams/modbusSource.js +1 -1
- package/src/infrastructure/streams/stompSend.js +1 -1
- package/src/infrastructure/sync/operationAmqp.js +26 -0
- package/src/infrastructure/sync/operationEvent.js +10 -0
- package/src/infrastructure/catalog/tag-catalog.json +0 -27
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/** Start of the
|
|
1
|
+
/** Start of the active bucket that can still receive observations, in the work time unit. */
|
|
2
2
|
export default async function historyFence(pool, machine, timeScale = 1) {
|
|
3
3
|
if (![1, 1000].includes(timeScale)) { throw new TypeError('External history supports millisecond or microsecond coordinates'); }
|
|
4
4
|
const result = await pool.query(`SELECT floor(extract(epoch FROM clock_timestamp()) * 1000 * $2 / bucket) * bucket AS open_ms
|
|
@@ -30,6 +30,37 @@ function retainExterior(segments, current, owners, until) {
|
|
|
30
30
|
}
|
|
31
31
|
}
|
|
32
32
|
}
|
|
33
|
+
/** Replace pages keep only the observed until; the open tail continues through the checkpoint. */
|
|
34
|
+
export function clipReplacePage(segments, latest, timeScale) {
|
|
35
|
+
if (!latest?.context?.page) { return segments; }
|
|
36
|
+
const until = Math.round(latest.context.page.until / timeScale);
|
|
37
|
+
return segments.flatMap((item) => {
|
|
38
|
+
const start = instant(item.start_time);
|
|
39
|
+
const end = instant(item.end_time);
|
|
40
|
+
if (!Number.isFinite(start) || !Number.isFinite(end) || start >= until) { return []; }
|
|
41
|
+
if (end <= until) { return [item]; }
|
|
42
|
+
return [{ ...item, end_time: new Date(until).toISOString(), duration: (until - start) / 1000 }];
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
/** Coalesces overlapping pieces that carry the same classification. */
|
|
46
|
+
export function joinReplacePage(segments) {
|
|
47
|
+
return [...segments].sort((left, right) => { return instant(left.start_time) - instant(right.start_time); })
|
|
48
|
+
.reduce((rows, item) => {
|
|
49
|
+
const prior = rows.at(-1);
|
|
50
|
+
if (!prior || prior.name !== item.name || (prior.kind ?? 'phase') !== (item.kind ?? 'phase')) {
|
|
51
|
+
return [...rows, item];
|
|
52
|
+
}
|
|
53
|
+
const start = instant(prior.start_time);
|
|
54
|
+
const incoming = instant(item.start_time);
|
|
55
|
+
const priorEnd = instant(prior.end_time);
|
|
56
|
+
const end = Math.max(priorEnd, instant(item.end_time));
|
|
57
|
+
if (!Number.isFinite(start) || !Number.isFinite(incoming) || incoming < start || incoming > priorEnd) {
|
|
58
|
+
return [...rows, item];
|
|
59
|
+
}
|
|
60
|
+
return [...rows.slice(0, -1), { ...item, start_time: prior.start_time,
|
|
61
|
+
end_time: new Date(end).toISOString(), duration: (end - start) / 1000 }];
|
|
62
|
+
}, []);
|
|
63
|
+
}
|
|
33
64
|
/** A bounded native correction may carry existing exterior, never classify new exterior. */
|
|
34
65
|
export default function nativeHistoryBounds(segments, latest, base, timeScale) {
|
|
35
66
|
if (!latest) { return []; }
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import retainMetricReceipts from '../../ingest/db/retainMetricReceipts.js';
|
|
2
|
+
import pgHistorySession from './historySession.js';
|
|
3
|
+
|
|
4
|
+
export default function historyPurge(pool, cutoff, retentionDays, batch) {
|
|
5
|
+
if (!batch) {
|
|
6
|
+
return pool.query(`DELETE FROM history_observations o WHERE time_ms < $1
|
|
7
|
+
AND NOT EXISTS (SELECT 1 FROM history_work w WHERE w.machine=o.machine
|
|
8
|
+
AND (o.time_ms BETWEEN w.from_ms-86400000 AND greatest(w.until_ms,COALESCE(w.end_ms,w.until_ms))+86400000
|
|
9
|
+
OR (o.time_ms<w.from_ms-86400000 AND NOT EXISTS (SELECT 1 FROM history_observations anchor
|
|
10
|
+
WHERE anchor.machine=o.machine AND anchor.channel=o.channel AND anchor.time_ms>o.time_ms AND anchor.time_ms<w.from_ms-86400000))))
|
|
11
|
+
AND EXISTS (SELECT 1 FROM history_observations newer WHERE newer.machine=o.machine
|
|
12
|
+
AND newer.channel=o.channel AND newer.time_ms>o.time_ms AND newer.time_ms<$1)`, [cutoff]).then(async (result) => {
|
|
13
|
+
await retainMetricReceipts(pool, retentionDays);
|
|
14
|
+
return result.rowCount;
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
return pgHistorySession(pool, async (client) => {
|
|
18
|
+
const pending = await client.query('SELECT 1 FROM history_work WHERE from_ms < $1 LIMIT 1', [cutoff]);
|
|
19
|
+
if (pending.rowCount) { return { deferred: 'pending work' }; }
|
|
20
|
+
const result = await client.query(`DELETE FROM history_observations WHERE ctid IN (
|
|
21
|
+
SELECT ctid FROM history_observations WHERE time_ms < $1 ORDER BY machine, time_ms LIMIT $2
|
|
22
|
+
)`, [cutoff, batch]);
|
|
23
|
+
await retainMetricReceipts(client, retentionDays);
|
|
24
|
+
return result.rowCount;
|
|
25
|
+
}, 20000);
|
|
26
|
+
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** Complete carried parameters at the left context boundary within the last continuous run. */
|
|
2
|
-
export default async function historySeed(pool, machine, before, maxGap, {observations,timeScale=1}={}) {
|
|
2
|
+
export default async function historySeed(pool, machine, before, maxGap, {observations,timeScale=1,bounded = false}={}) {
|
|
3
3
|
const external = observations?.seed ? await observations.seed(machine,before,maxGap) : undefined;
|
|
4
4
|
if (external === null) { return null; }
|
|
5
5
|
if (external !== undefined) {
|
|
@@ -9,13 +9,13 @@ export default async function historySeed(pool, machine, before, maxGap, {observ
|
|
|
9
9
|
return {...external,segment:prior.rows[0] ?? null};
|
|
10
10
|
}
|
|
11
11
|
const result = await pool.query(`WITH times AS (
|
|
12
|
-
SELECT DISTINCT time_ms FROM history_observations WHERE machine=$1 AND time_ms<$2
|
|
12
|
+
SELECT DISTINCT time_ms FROM history_observations WHERE machine=$1 AND time_ms<$2${bounded ? ' AND time_ms>=$4' : ''}
|
|
13
13
|
), gaps AS (
|
|
14
14
|
SELECT time_ms,time_ms-lag(time_ms) OVER (ORDER BY time_ms) AS gap FROM times
|
|
15
15
|
), boundary AS MATERIALIZED (
|
|
16
16
|
SELECT COALESCE(max(time_ms) FILTER (WHERE gap>$3),min(time_ms)) AS at FROM gaps
|
|
17
17
|
) SELECT DISTINCT ON (channel) channel,time_ms AS time,value,boundary.at AS since FROM history_observations,boundary
|
|
18
|
-
WHERE machine=$1 AND time_ms>=boundary.at AND time_ms<$2 ORDER BY channel,time_ms DESC`, [machine,before,maxGap]);
|
|
18
|
+
WHERE machine=$1 AND time_ms>=boundary.at AND time_ms<$2 ORDER BY channel,time_ms DESC`, [machine,before,maxGap,...(bounded ? [before-maxGap] : [])]);
|
|
19
19
|
if (!result.rows.length) { return null; }
|
|
20
20
|
const time = Math.max(...result.rows.map((row) => { return Number(row.time); }));
|
|
21
21
|
const since = Number(result.rows[0].since);
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/** Owns a history transaction with an optional statement deadline. */
|
|
2
|
+
export default async function historySession(pool, action, timeoutMs, required = false) {
|
|
3
|
+
if (!required && (!timeoutMs || typeof pool.connect !== 'function')) { return action(pool); }
|
|
4
|
+
const client = await pool.connect();
|
|
5
|
+
try {
|
|
6
|
+
await client.query('BEGIN');
|
|
7
|
+
if (timeoutMs) { await client.query("SELECT set_config('statement_timeout', $1, true)", [String(timeoutMs)]); }
|
|
8
|
+
const result = await action(client);
|
|
9
|
+
await client.query('COMMIT');
|
|
10
|
+
return result;
|
|
11
|
+
} catch (error) {
|
|
12
|
+
await client.query('ROLLBACK');
|
|
13
|
+
throw error;
|
|
14
|
+
} finally { client.release(); }
|
|
15
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
const timestamp = "to_char(ts AT TIME ZONE 'UTC','YYYY-MM-DD HH24:MI:SS.US')";
|
|
2
|
+
|
|
3
|
+
async function finish(state, command) {
|
|
4
|
+
const { client } = state;
|
|
5
|
+
if (!client) { return; }
|
|
6
|
+
state.client = undefined;
|
|
7
|
+
let fault;
|
|
8
|
+
try {
|
|
9
|
+
await client.query(command);
|
|
10
|
+
} catch (error) {
|
|
11
|
+
fault = error;
|
|
12
|
+
throw error;
|
|
13
|
+
} finally {
|
|
14
|
+
client.release(fault);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
async function declare(pool, state, topic, upper, from) {
|
|
19
|
+
const client = await pool.connect();
|
|
20
|
+
Object.assign(state, { client, topic });
|
|
21
|
+
try {
|
|
22
|
+
await client.query('BEGIN READ ONLY');
|
|
23
|
+
await client.query(
|
|
24
|
+
`DECLARE telemetry_rows NO SCROLL CURSOR FOR SELECT topic,${timestamp} AS ts,value
|
|
25
|
+
FROM metrics WHERE topic=$1 AND ts >= $3::timestamptz AND ts <= $2::timestamptz
|
|
26
|
+
ORDER BY metrics.ts,float8send(value)`,
|
|
27
|
+
[topic, `${upper}+00`, from]
|
|
28
|
+
);
|
|
29
|
+
} catch (error) {
|
|
30
|
+
await finish(state, 'ROLLBACK');
|
|
31
|
+
throw error;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Read a bounded snapshot of each topic, retaining physical duplicates and exact timestamps. */
|
|
36
|
+
export default function postgresTelemetrySource(pool, { from = '1970-01-01T00:00:00Z' } = {}) {
|
|
37
|
+
const state = { client: undefined, topic: undefined };
|
|
38
|
+
return {
|
|
39
|
+
async nextTopic(after) {
|
|
40
|
+
const sql = after === null ? 'SELECT topic FROM metrics ORDER BY topic LIMIT 1'
|
|
41
|
+
: 'SELECT topic FROM metrics WHERE topic > $1 ORDER BY topic LIMIT 1';
|
|
42
|
+
const result = await pool.query(sql, after === null ? [] : [after]);
|
|
43
|
+
return result.rows[0]?.topic ?? null;
|
|
44
|
+
},
|
|
45
|
+
async upper(topic) {
|
|
46
|
+
const result = await pool.query(`SELECT ${timestamp} AS ts FROM metrics WHERE topic=$1 ORDER BY metrics.ts DESC LIMIT 1`, [topic]);
|
|
47
|
+
return result.rows[0]?.ts ?? null;
|
|
48
|
+
},
|
|
49
|
+
async page(topic, _after, upper, size) {
|
|
50
|
+
if (!Number.isSafeInteger(size) || size < 1 || size > 100000) { throw new RangeError('Invalid telemetry page size'); }
|
|
51
|
+
if (!state.client) { await declare(pool, state, topic, upper, from); }
|
|
52
|
+
if (state.topic !== topic) { throw new Error('Source cursor belongs to another topic'); }
|
|
53
|
+
try {
|
|
54
|
+
const result = await state.client.query(`FETCH FORWARD ${size} FROM telemetry_rows`);
|
|
55
|
+
if (result.rows.length === 0) { await finish(state, 'COMMIT'); }
|
|
56
|
+
return result.rows;
|
|
57
|
+
} catch (error) {
|
|
58
|
+
await finish(state, 'ROLLBACK');
|
|
59
|
+
throw error;
|
|
60
|
+
}
|
|
61
|
+
},
|
|
62
|
+
close() { return finish(state, 'ROLLBACK'); }
|
|
63
|
+
};
|
|
64
|
+
}
|
|
@@ -19,6 +19,11 @@ export function holdClient(pool) {
|
|
|
19
19
|
return pool;
|
|
20
20
|
}
|
|
21
21
|
|
|
22
|
+
/** Open a pool for an application-owned connection and handle idle socket errors. */
|
|
23
|
+
export function openPostgresPool(connectionString) {
|
|
24
|
+
return holdClient(new pg.Pool({ connectionString }));
|
|
25
|
+
}
|
|
26
|
+
|
|
22
27
|
/**
|
|
23
28
|
* Creates a PostgreSQL pool for supervisor state reads.
|
|
24
29
|
*
|
|
@@ -39,5 +44,5 @@ export default function postgresPool(options = {}) {
|
|
|
39
44
|
if (!url) {
|
|
40
45
|
return undefined;
|
|
41
46
|
}
|
|
42
|
-
return
|
|
47
|
+
return openPostgresPool(url);
|
|
43
48
|
}
|
|
@@ -4,13 +4,16 @@ import { pendingFair } from './spoolReplay.js';
|
|
|
4
4
|
import spoolMutations from './spoolMutations.js';
|
|
5
5
|
import spoolMigration from './spoolMigration.js';
|
|
6
6
|
import spoolLimits from './spoolLimits.js';
|
|
7
|
+
import spoolCheckpoints from './spoolCheckpoints.js';
|
|
7
8
|
|
|
8
9
|
/* eslint max-lines-per-function: ["error", 100], max-statements: ["error", 25] */
|
|
9
10
|
/** Single owner, bounded cache and indexed reads. Caps count logical JSON bytes, not allocated pages. */
|
|
10
11
|
export default function deliverySpool(directory, options) {
|
|
11
|
-
const { maxBytes, maxRecords, legacyMigrationMaxBytes } = spoolLimits(options);
|
|
12
|
+
const { maxBytes, maxRecords, legacyMigrationMaxBytes, walCheckpoint } = spoolLimits(options);
|
|
12
13
|
const state = { db: null, owner: null, ready: false, busy: false, bytes: 0, records: 0 };
|
|
14
|
+
let maintenance;
|
|
13
15
|
function release() {
|
|
16
|
+
maintenance?.cancel(); maintenance = undefined;
|
|
14
17
|
state.ready = false;
|
|
15
18
|
try { state.db?.close(); } finally { state.owner?.close(); state.db = null; state.owner = null; }
|
|
16
19
|
}
|
|
@@ -24,7 +27,12 @@ export default function deliverySpool(directory, options) {
|
|
|
24
27
|
try { return await action(); } finally { Object.assign(state, { busy:false }); }
|
|
25
28
|
}
|
|
26
29
|
function commit(action) {
|
|
27
|
-
try {
|
|
30
|
+
try {
|
|
31
|
+
maintenance?.beforeWrite();
|
|
32
|
+
const result = state.db.transaction(action)();
|
|
33
|
+
refresh(); maintenance?.schedule();
|
|
34
|
+
return result;
|
|
35
|
+
}
|
|
28
36
|
catch (error) { if (error.code?.startsWith('SQLITE_')) { release(); } throw error; }
|
|
29
37
|
}
|
|
30
38
|
function mutateMany(operations) {
|
|
@@ -43,6 +51,7 @@ export default function deliverySpool(directory, options) {
|
|
|
43
51
|
Object.assign(state, await database(directory));
|
|
44
52
|
capacity(state.db, maxBytes, maxRecords);
|
|
45
53
|
await spoolMigration(directory, state.db, { maxBytes, maxRecords, legacyMigrationMaxBytes });
|
|
54
|
+
if (walCheckpoint) { maintenance = spoolCheckpoints(state.db, directory, walCheckpoint); maintenance.schedule(); }
|
|
46
55
|
refresh(); Object.assign(state, { ready:true });
|
|
47
56
|
} catch (error) { release(); throw error; }
|
|
48
57
|
}, false);
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { statSync } from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
|
|
4
|
+
const idleMs = 150;
|
|
5
|
+
const maxDelayMs = 2000;
|
|
6
|
+
|
|
7
|
+
export function spoolCheckpointLimits(options) {
|
|
8
|
+
if (options === undefined) { return undefined; }
|
|
9
|
+
if (!options || typeof options !== 'object' || Array.isArray(options)) { throw new TypeError('Invalid spool WAL checkpoint options'); }
|
|
10
|
+
const { targetBytes = 2 * 1024 * 1024, maxBytes = 8 * 1024 * 1024 } = options;
|
|
11
|
+
if (!Number.isSafeInteger(targetBytes) || targetBytes <= 0 || !Number.isSafeInteger(maxBytes) || maxBytes <= targetBytes) {
|
|
12
|
+
throw new TypeError('Spool WAL limit must be greater than its positive checkpoint target');
|
|
13
|
+
}
|
|
14
|
+
return { targetBytes, maxBytes };
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export default function spoolCheckpoints(db, directory, { targetBytes, maxBytes }) {
|
|
18
|
+
const file = path.join(directory, 'delivery.sqlite-wal');
|
|
19
|
+
db.pragma('wal_autocheckpoint = 0');
|
|
20
|
+
let timer;
|
|
21
|
+
let deadline;
|
|
22
|
+
let failure;
|
|
23
|
+
|
|
24
|
+
function bytes() { return statSync(file, { throwIfNoEntry: false })?.size ?? 0; }
|
|
25
|
+
function cancel() {
|
|
26
|
+
clearTimeout(timer);
|
|
27
|
+
timer = undefined;
|
|
28
|
+
deadline = undefined;
|
|
29
|
+
}
|
|
30
|
+
function checkpoint(mode) { return db.pragma(`wal_checkpoint(${mode})`)[0]; }
|
|
31
|
+
function maintenance() {
|
|
32
|
+
cancel();
|
|
33
|
+
try {
|
|
34
|
+
const size = bytes();
|
|
35
|
+
if (size >= maxBytes) { checkpoint('TRUNCATE'); }
|
|
36
|
+
else if (size >= targetBytes) { checkpoint('PASSIVE'); }
|
|
37
|
+
} catch (error) { failure = error; }
|
|
38
|
+
}
|
|
39
|
+
return {
|
|
40
|
+
beforeWrite() {
|
|
41
|
+
if (failure) {
|
|
42
|
+
const error = failure;
|
|
43
|
+
failure = undefined;
|
|
44
|
+
throw error;
|
|
45
|
+
}
|
|
46
|
+
// A durable group may cross the limit. A later writer cannot extend that WAL.
|
|
47
|
+
if (bytes() < maxBytes) { return; }
|
|
48
|
+
cancel();
|
|
49
|
+
if (checkpoint('TRUNCATE').busy !== 0) { throw new Error('Spool WAL growth limit reached while checkpoint is busy'); }
|
|
50
|
+
},
|
|
51
|
+
schedule() {
|
|
52
|
+
try {
|
|
53
|
+
if (bytes() < targetBytes) { cancel(); return; }
|
|
54
|
+
const now = performance.now();
|
|
55
|
+
deadline ??= now + maxDelayMs;
|
|
56
|
+
// Keep the timer runnable under sustained writes once its maximum deferral expires.
|
|
57
|
+
if (timer && now >= deadline) { return; }
|
|
58
|
+
clearTimeout(timer);
|
|
59
|
+
timer = setTimeout(maintenance, Math.min(idleMs, deadline - now));
|
|
60
|
+
timer.unref();
|
|
61
|
+
} catch (error) { failure = error; }
|
|
62
|
+
},
|
|
63
|
+
cancel
|
|
64
|
+
};
|
|
65
|
+
}
|
|
@@ -1,6 +1,8 @@
|
|
|
1
|
-
|
|
1
|
+
import { spoolCheckpointLimits } from './spoolCheckpoints.js';
|
|
2
|
+
|
|
3
|
+
export default function spoolLimits({ maxBytes, maxRecords = 100000, legacyMigrationMaxBytes = 16 * 1024 * 1024, walCheckpoint } = {}) {
|
|
2
4
|
if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) { throw new TypeError('Explicit positive spool maxBytes required'); }
|
|
3
5
|
if (!Number.isSafeInteger(maxRecords) || maxRecords <= 0) { throw new TypeError('Positive safe spool maxRecords required'); }
|
|
4
6
|
if (!Number.isSafeInteger(legacyMigrationMaxBytes) || legacyMigrationMaxBytes <= 0) { throw new TypeError('Positive safe legacyMigrationMaxBytes required'); }
|
|
5
|
-
return { maxBytes, maxRecords, legacyMigrationMaxBytes };
|
|
7
|
+
return { maxBytes, maxRecords, legacyMigrationMaxBytes, walCheckpoint: spoolCheckpointLimits(walCheckpoint) };
|
|
6
8
|
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import Database from 'better-sqlite3';
|
|
2
|
+
|
|
3
|
+
function documentOf(input) {
|
|
4
|
+
return { taskId: input.taskId, stateVersion: input.stateVersion, compatibilityKey: input.compatibilityKey,
|
|
5
|
+
checkpoint: input.checkpoint, pending: input.pending };
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
function taskState(db, maxBytes) {
|
|
9
|
+
db.exec('CREATE TABLE IF NOT EXISTS collector_task_state (task_id TEXT PRIMARY KEY, version INTEGER NOT NULL, document TEXT NOT NULL)');
|
|
10
|
+
const select = db.prepare('SELECT version, document FROM collector_task_state WHERE task_id = ?');
|
|
11
|
+
const insert = db.prepare('INSERT INTO collector_task_state (task_id, version, document) VALUES (?, 1, ?) ON CONFLICT(task_id) DO NOTHING');
|
|
12
|
+
const update = db.prepare('UPDATE collector_task_state SET version = version + 1, document = ? WHERE task_id = ? AND version = ?');
|
|
13
|
+
return {
|
|
14
|
+
load(taskId) {
|
|
15
|
+
const row = select.get(taskId);
|
|
16
|
+
if (!row) { return Promise.resolve(null); }
|
|
17
|
+
return Promise.resolve({ ...JSON.parse(row.document), version: Number(row.version) });
|
|
18
|
+
},
|
|
19
|
+
commit(input) {
|
|
20
|
+
if (!Number.isSafeInteger(input.expectedVersion) || input.expectedVersion < 0) { throw new TypeError('Invalid expectedVersion'); }
|
|
21
|
+
if (input.ownership !== undefined) { throw new Error('This store has no external ownership integration'); }
|
|
22
|
+
const json = JSON.stringify(documentOf(input));
|
|
23
|
+
if (Buffer.byteLength(json) > maxBytes) { throw new Error('Task state capacity exceeded'); }
|
|
24
|
+
const result = input.expectedVersion === 0 ? insert.run(input.taskId, json) : update.run(json, input.taskId, input.expectedVersion);
|
|
25
|
+
if (!result.changes) { throw new Error('Task state conflict'); }
|
|
26
|
+
return Promise.resolve(input.expectedVersion + 1);
|
|
27
|
+
},
|
|
28
|
+
close() { db.close(); }
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** SQLite CAS store with the same load/commit shape as the PostgreSQL runtime table. */
|
|
33
|
+
export default function taskStateSqlite(file, { maxBytes = 1048576 } = {}) {
|
|
34
|
+
const db = new Database(file);
|
|
35
|
+
try { return taskState(db, maxBytes); }
|
|
36
|
+
catch (error) { db.close(); throw error; }
|
|
37
|
+
}
|
|
@@ -13,8 +13,22 @@ export default function stateDataFromPool(pool, options = {}) {
|
|
|
13
13
|
segments: segmentStatePg(pool),
|
|
14
14
|
alerts: alertsStatePg(pool),
|
|
15
15
|
metrics,
|
|
16
|
-
history: metricsEnabled ? historyPg(pool, { retentionDays: options.historyRetentionDays ?? 30 }) : undefined,
|
|
17
|
-
checkpoints: checkpointStatePg(pool, metricsEnabled),
|
|
16
|
+
history: metricsEnabled ? historyPg(pool, { retentionDays: options.historyRetentionDays ?? 30, ...options.historyPolicy }) : undefined,
|
|
17
|
+
checkpoints: checkpointStatePg(pool, metricsEnabled, options.checkpointPolicy),
|
|
18
18
|
operations: operationStatePg(pool)
|
|
19
19
|
};
|
|
20
20
|
}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
/** Route telemetry and checkpoint readings to the selected backend, preserving business state. */
|
|
24
|
+
export function withTelemetryState(data, metrics, history = data.history) {
|
|
25
|
+
return {
|
|
26
|
+
...data,
|
|
27
|
+
metrics,
|
|
28
|
+
history,
|
|
29
|
+
checkpoints: {
|
|
30
|
+
...data.checkpoints,
|
|
31
|
+
readings(topics, from) { return metrics.readings(topics, from); }
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
}
|
|
@@ -79,7 +79,7 @@ function modbusPollingSource(options) {
|
|
|
79
79
|
* collector via pollingSource.
|
|
80
80
|
*
|
|
81
81
|
* @example
|
|
82
|
-
* const source = modbusSource('192.
|
|
82
|
+
* const source = modbusSource('192.0.2.148', 502, 4000, 14, 5, collector, clock);
|
|
83
83
|
* source.start();
|
|
84
84
|
*
|
|
85
85
|
* @param {string} host - Modbus TCP host address
|
|
@@ -43,7 +43,7 @@ function connectParams(parsed, options) {
|
|
|
43
43
|
*
|
|
44
44
|
* @example
|
|
45
45
|
* await stompSend('stomp://rabbitmq:61613', '/exchange/scada.user_decisions',
|
|
46
|
-
* { machine: '
|
|
46
|
+
* { machine: 'drive2', start: 1700000000, user: 'hmi', tags: ['heating'] },
|
|
47
47
|
* { login: 'guest', passcode: 'guest', host: '/' });
|
|
48
48
|
*
|
|
49
49
|
* @param {string} url - STOMP broker URL
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import amqpSink from '../streams/amqpSink.js';
|
|
2
|
+
import operationEvent from './operationEvent.js';
|
|
3
|
+
|
|
4
|
+
const exchange = 'scada.operations';
|
|
5
|
+
|
|
6
|
+
/** Confirmed operation sync writes. No broker is required for a local-only operations port. */
|
|
7
|
+
export default function operationAmqp(url, options = {}) {
|
|
8
|
+
const sink = url ? amqpSink(url, {
|
|
9
|
+
...options,
|
|
10
|
+
exchanges: [{ name: exchange, type: 'topic', options: { durable: true } }]
|
|
11
|
+
}) : null;
|
|
12
|
+
return {
|
|
13
|
+
active() { return Boolean(sink?.active()); },
|
|
14
|
+
start() { return sink ? sink.start() : Promise.resolve(); },
|
|
15
|
+
stop() { return sink ? sink.stop() : Promise.resolve(); },
|
|
16
|
+
publish(item) {
|
|
17
|
+
if (!sink) { return Promise.resolve(); }
|
|
18
|
+
return sink.write([{
|
|
19
|
+
exchange,
|
|
20
|
+
routingKey: `${item.machine}.${item.key}`,
|
|
21
|
+
body: Buffer.from(JSON.stringify(operationEvent(item))),
|
|
22
|
+
options: { contentType: 'application/json', persistent: true }
|
|
23
|
+
}]);
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** Encode an upsert or deletion for the operation sync protocol. Kinds and payloads are opaque. */
|
|
2
|
+
export default function operationEvent(item) {
|
|
3
|
+
const identity = {
|
|
4
|
+
machine: item.machine,
|
|
5
|
+
occurred_at: item.occurred_at.toISOString(),
|
|
6
|
+
kind: item.kind,
|
|
7
|
+
external_key: item.key
|
|
8
|
+
};
|
|
9
|
+
return item.type === 'deleted' ? { type: 'deleted', ...identity } : { ...identity, payload: item.payload };
|
|
10
|
+
}
|
|
@@ -1,27 +0,0 @@
|
|
|
1
|
-
[
|
|
2
|
-
{
|
|
3
|
-
"id": "on",
|
|
4
|
-
"label": "On",
|
|
5
|
-
"parent": null
|
|
6
|
-
},
|
|
7
|
-
{
|
|
8
|
-
"id": "off",
|
|
9
|
-
"label": "Off",
|
|
10
|
-
"parent": null
|
|
11
|
-
},
|
|
12
|
-
{
|
|
13
|
-
"id": "heating",
|
|
14
|
-
"label": "Heating",
|
|
15
|
-
"parent": "on"
|
|
16
|
-
},
|
|
17
|
-
{
|
|
18
|
-
"id": "idle",
|
|
19
|
-
"label": "Idle",
|
|
20
|
-
"parent": "off"
|
|
21
|
-
},
|
|
22
|
-
{
|
|
23
|
-
"id": "maintenance",
|
|
24
|
-
"label": "Maintenance",
|
|
25
|
-
"parent": "off"
|
|
26
|
-
}
|
|
27
|
-
]
|