@yarkivaev/scada 2.12.2 → 2.14.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 +43 -2
- package/package.json +3 -2
- package/src/application/control/controlClient.js +1 -1
- package/src/application/control/createOnlyJSON.js +50 -0
- package/src/application/control/index.js +2 -0
- package/src/application/control/jsonAssignments.js +30 -0
- package/src/application/foldedMetricsSink.js +1 -1
- package/src/application/mcp/loadMetricSeries.js +69 -0
- package/src/application/mcp/locateMachineMetric.js +25 -0
- package/src/application/mcp/metricQueryPorts.js +78 -0
- package/src/application/mcp/parseBearerTokens.js +43 -0
- package/src/application/runtime/assignment.js +4 -1
- package/src/application/runtime/collectorStartup.js +23 -0
- package/src/application/runtime/index.js +2 -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/deploy/applyWhenChanged.js +15 -0
- package/src/infrastructure/deploy/deploymentKube.js +35 -0
- package/src/infrastructure/deploy/executeKubeSeed.js +24 -0
- package/src/infrastructure/deploy/executeRelease.js +8 -11
- package/src/infrastructure/deploy/operatePostgresMaintenance.js +85 -0
- package/src/infrastructure/deploy/postgresMaintenancePlan.js +54 -0
- package/src/infrastructure/deploy/postgresRestoreObjects.js +73 -0
- package/src/infrastructure/deploy/preflightKubeStorage.js +76 -0
- package/src/infrastructure/deploy/prepareKubePrerequisites.js +95 -0
- package/src/infrastructure/deploy/verifyCollectorCoverage.js +43 -0
- package/src/infrastructure/deploy/verifyPeerBrokerPerimeter.js +24 -0
- 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/mysql40/byteReader.js +51 -0
- package/src/infrastructure/ingest/mysql40/mysql40.js +116 -0
- package/src/infrastructure/ingest/mysql40/packets.js +72 -0
- package/src/infrastructure/ingest/mysql40/resultRows.js +92 -0
- package/src/infrastructure/ingest/mysql40/scramble.js +89 -0
- 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/edgeTelemetryRuntime.js +83 -0
- package/src/infrastructure/ingest/telemetry/historyTelemetryMetrics.js +15 -0
- package/src/infrastructure/ingest/telemetry/opcuaLocate.js +2 -2
- package/src/infrastructure/ingest/telemetry/replayStoredTelemetry.js +125 -0
- package/src/infrastructure/ingest/telemetry/telemetryIngest.js +52 -0
- package/src/infrastructure/ingest/telemetry/telemetryReplay.js +15 -0
- package/src/infrastructure/management/kubeServiceAccount.js +43 -0
- package/src/infrastructure/management/kubectlPortForward.js +27 -0
- package/src/infrastructure/mdmesh/hmiApplication.js +64 -0
- package/src/infrastructure/mdmesh/hmiControl.js +85 -0
- package/src/infrastructure/mdmesh/hmiFile.js +69 -0
- package/src/infrastructure/mdmesh/hmiMonitor.js +53 -0
- package/src/infrastructure/mdmesh/hmiReconcile.js +170 -0
- package/src/infrastructure/mdmesh/hmiRuntime.js +33 -0
- package/src/infrastructure/mdmesh/index.js +7 -0
- package/src/infrastructure/mdmesh/mdmeshClient.js +72 -0
- package/src/infrastructure/messaging/ownership/edgeSitesFromEnv.js +137 -0
- package/src/infrastructure/messaging/rabbitmq/reconcile.js +71 -12
- package/src/infrastructure/messaging/stomp/retagBody.js +1 -1
- package/src/infrastructure/messaging/stomp/segmentRetags.js +1 -1
- package/src/infrastructure/opcua/health.js +91 -0
- package/src/infrastructure/opcua/index.js +1 -0
- 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/prepareRuntimeRole.js +67 -0
- package/src/infrastructure/persistence/pg/telemetrySource.js +64 -0
- package/src/infrastructure/persistence/postgresPool.js +6 -1
- package/src/infrastructure/persistence/runtime/taskStateSqlite.js +37 -0
- package/src/infrastructure/persistence/stateDataFromPool.js +16 -2
- package/src/infrastructure/replication/canonicalJSON.js +15 -0
- package/src/infrastructure/replication/postgresSnapshotReplica.js +129 -0
- package/src/infrastructure/replication/postgresSnapshotRuntime.js +40 -0
- package/src/infrastructure/replication/snapshotSync.js +61 -0
- package/src/infrastructure/replication/tableSnapshotFormat.js +50 -0
- 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/tls/mirrorTLSSecret.js +37 -0
- package/src/infrastructure/tls/mutualJSON.js +79 -0
- package/src/infrastructure/tls/tlsMaterial.js +57 -0
- package/stream-processing/src/main/scala/scada/processing/infra/state/AtomicStateFile.scala +7 -0
- package/stream-processing/src/main/scala/scada/processing/infra/state/StateJournal.scala +22 -0
- package/stream-processing/src/main/scala/scada/processing/runtime/HistoryClient.scala +10 -1
- package/stream-processing/src/main/scala/scada/processing/runtime/LiveWorker.scala +70 -0
- package/stream-processing/src/main/scala/scada/processing/runtime/LocalHistory.scala +2 -8
- package/stream-processing/src/main/scala/scada/processing/runtime/StatefulHistory.scala +108 -0
- package/stream-processing/src/main/scala/scada/processing/runtime/TimelinePublication.scala +43 -0
- package/stream-processing/src/main/scala/scada/processing/runtime/WorkerStores.scala +43 -0
- package/src/infrastructure/catalog/tag-catalog.json +0 -27
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import insertMetricRows from './insertMetricRows.js';
|
|
2
|
+
|
|
3
|
+
function datetime(value) {
|
|
4
|
+
if (value instanceof Date) { return value.toISOString().replace('T', ' ').replace(/Z$/u, ''); }
|
|
5
|
+
if (typeof value === 'number') { return datetime(new Date(value)); }
|
|
6
|
+
return value.replace('T', ' ').replace(/Z$/u, '');
|
|
7
|
+
}
|
|
8
|
+
function instant(value) { return new Date(`${String(value).replace(' ', 'T')}Z`); }
|
|
9
|
+
function samples(rows) {
|
|
10
|
+
return rows.map(row => {
|
|
11
|
+
return { ...row, ts: instant(row.ts), value: Number(row.value), ...(row.until ? { until: instant(row.until) } : {}) };
|
|
12
|
+
});
|
|
13
|
+
}
|
|
14
|
+
function canonical() {
|
|
15
|
+
return 'SELECT topic,ts,max(value) AS value FROM scada.metrics WHERE topic={topic:String} GROUP BY topic,ts';
|
|
16
|
+
}
|
|
17
|
+
function lookup(condition = '') {
|
|
18
|
+
return `SELECT ts,max(value) AS value FROM scada.metrics WHERE topic={topic:String}${condition}
|
|
19
|
+
AND ts=(SELECT ts FROM scada.metrics WHERE topic={topic:String}${condition} ORDER BY ts DESC LIMIT 1) GROUP BY ts`;
|
|
20
|
+
}
|
|
21
|
+
async function query(client, sql, params) {
|
|
22
|
+
const response = await client.query({ query: sql, query_params: params, format: 'JSONEachRow' });
|
|
23
|
+
return response.json();
|
|
24
|
+
}
|
|
25
|
+
function parameters(topic, start, end) { return { topic, start: datetime(start), end: datetime(end) }; }
|
|
26
|
+
function levels() {
|
|
27
|
+
return `WITH canonical AS (${canonical()}), prior AS (
|
|
28
|
+
${lookup(" AND ts < {start:DateTime64(6,'UTC')}")}
|
|
29
|
+
), series AS (
|
|
30
|
+
SELECT ts,value FROM prior UNION ALL
|
|
31
|
+
SELECT ts,value FROM canonical WHERE ts >= {start:DateTime64(6,'UTC')} AND ts <= {end:DateTime64(6,'UTC')}
|
|
32
|
+
), marked AS (
|
|
33
|
+
SELECT ts,value,row_number() OVER(ORDER BY ts) AS n,
|
|
34
|
+
lagInFrame(toNullable(value),1) OVER(ORDER BY ts ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS prev
|
|
35
|
+
FROM series
|
|
36
|
+
)`;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function timeSeries(client) {
|
|
40
|
+
return {
|
|
41
|
+
async rangeForTopic(topic, start, end, step) {
|
|
42
|
+
const rows = await query(client, `SELECT toStartOfInterval(ts,INTERVAL {step:UInt32} SECOND) AS bucket,argMax(value,ts) AS value
|
|
43
|
+
FROM (${canonical()}) WHERE ts >= {start:DateTime64(6,'UTC')} AND ts <= {end:DateTime64(6,'UTC')}
|
|
44
|
+
GROUP BY bucket ORDER BY bucket`, { ...parameters(topic, start, end), step: Math.max(1, Math.floor(step / 1000)) });
|
|
45
|
+
return samples(rows.map(({ bucket, value }) => { return { ts: bucket, value }; }));
|
|
46
|
+
},
|
|
47
|
+
async risesForTopic(topic, start, end) {
|
|
48
|
+
const rows = await query(client, `${levels()}
|
|
49
|
+
SELECT ts,sum(1) OVER(ORDER BY ts) AS prefix FROM marked
|
|
50
|
+
WHERE ts >= {start:DateTime64(6,'UTC')} AND ts < {end:DateTime64(6,'UTC')} AND prev=0 AND value=1 ORDER BY ts`, parameters(topic, start, end));
|
|
51
|
+
return samples(rows.map(({ ts, prefix }) => { return { ts, value: prefix }; }));
|
|
52
|
+
},
|
|
53
|
+
async changesForTopic(topic, start, end) {
|
|
54
|
+
return samples(await query(client, `${levels()}
|
|
55
|
+
SELECT if(ts < {start:DateTime64(6,'UTC')},{start:DateTime64(6,'UTC')},ts) AS ts,value
|
|
56
|
+
FROM marked WHERE n=1 OR value != prev ORDER BY ts`, parameters(topic, start, end)));
|
|
57
|
+
},
|
|
58
|
+
async holdsForTopic(topic, start, end, step) {
|
|
59
|
+
const sql = `WITH canonical AS (${canonical()}), lagged AS (
|
|
60
|
+
SELECT ts,value,lagInFrame(ts,1) OVER(ORDER BY ts) AS previous,
|
|
61
|
+
lagInFrame(toNullable(value),1) OVER(ORDER BY ts) AS prev
|
|
62
|
+
FROM canonical WHERE ts >= {start:DateTime64(6,'UTC')} AND ts < {end:DateTime64(6,'UTC')}
|
|
63
|
+
), grouped AS (
|
|
64
|
+
SELECT ts,value,sum(if(prev IS NULL OR value != prev OR toUnixTimestamp64Micro(ts)-toUnixTimestamp64Micro(previous) > {gap:UInt64},1,0)) OVER(ORDER BY ts) AS grp FROM lagged
|
|
65
|
+
) SELECT min(ts) AS started,max(ts) AS until,min(value) AS value FROM grouped GROUP BY grp ORDER BY started`;
|
|
66
|
+
const rows = await query(client, sql, { ...parameters(topic, start, end), gap: Math.max(1, Number(step) || 1000) * 1000 });
|
|
67
|
+
return samples(rows.map(({ started, until, value }) => { return { ts: started, until, value }; }));
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** ClickHouse state for telemetry graphs and checkpoint readings over canonical samples. */
|
|
73
|
+
export default function clickhouseMetricsState(client, { readingsTable = 'metrics' } = {}) {
|
|
74
|
+
return {
|
|
75
|
+
...timeSeries(client),
|
|
76
|
+
async latestForTopic(topic) {
|
|
77
|
+
return samples(await query(client, lookup(), { topic }))[0] ?? null;
|
|
78
|
+
},
|
|
79
|
+
async pollTopic(topic, after, until) {
|
|
80
|
+
return samples(await query(client, `SELECT ts,value FROM (${canonical()})
|
|
81
|
+
WHERE ts > {start:DateTime64(6,'UTC')} AND ts <= {end:DateTime64(6,'UTC')} ORDER BY ts LIMIT 100`, parameters(topic, after, until)));
|
|
82
|
+
},
|
|
83
|
+
async readings(topics, from) {
|
|
84
|
+
if (topics.length === 0) { return []; }
|
|
85
|
+
const rows = await query(client, `SELECT topic,toUnixTimestamp64Micro(ts) AS instant,max(value) AS value
|
|
86
|
+
FROM scada.{source:Identifier} WHERE topic IN {topics:Array(String)} AND ts > fromUnixTimestamp64Micro({from:Int64})
|
|
87
|
+
GROUP BY topic,ts ORDER BY ts,topic`, { source: readingsTable, topics, from: Math.round(from * 1000000) });
|
|
88
|
+
return rows.map(row => { return { topic: row.topic, timestamp: Number(row.instant) / 1000000, value: Number(row.value) }; });
|
|
89
|
+
},
|
|
90
|
+
insertRows(rows, context) { return insertMetricRows(client, rows, context); }
|
|
91
|
+
};
|
|
92
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
export function micros(value) {
|
|
2
|
+
if (value instanceof Date) { return BigInt(value.getTime()) * 1000n; }
|
|
3
|
+
if (typeof value === 'number') { return micros(new Date(value)); }
|
|
4
|
+
const match = /^(?<date>\d{4}-\d{2}-\d{2})[ T](?<time>\d{2}:\d{2}:\d{2})(?:\.(?<fraction>\d{1,6}))?(?:Z|\+00(?::?00)?)?$/u.exec(value);
|
|
5
|
+
if (!match) { throw new Error('Telemetry timestamp requires exact UTC microseconds'); }
|
|
6
|
+
const { date, time, fraction = '' } = match.groups;
|
|
7
|
+
const decimal = fraction.padEnd(6, '0');
|
|
8
|
+
return BigInt(Date.parse(`${date}T${time}.${decimal.slice(0, 3)}Z`)) * 1000n + BigInt(decimal.slice(3));
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function prefix(length) {
|
|
12
|
+
const bytes = [];
|
|
13
|
+
let remaining = length;
|
|
14
|
+
do {
|
|
15
|
+
const digit = remaining % 128;
|
|
16
|
+
remaining = Math.floor(remaining / 128);
|
|
17
|
+
bytes.push(digit + (remaining ? 128 : 0));
|
|
18
|
+
} while (remaining);
|
|
19
|
+
return Buffer.from(bytes);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function record(row) {
|
|
23
|
+
if (!Number.isFinite(row.value)) { throw new Error(`Finite telemetry value required for topic ${row.topic}`); }
|
|
24
|
+
const topic = Buffer.from(row.topic, 'utf8');
|
|
25
|
+
const length = prefix(topic.length);
|
|
26
|
+
const offset = length.length + topic.length;
|
|
27
|
+
const buffer = Buffer.alloc(offset + 16);
|
|
28
|
+
length.copy(buffer);
|
|
29
|
+
topic.copy(buffer, length.length);
|
|
30
|
+
buffer.writeBigInt64LE(micros(row.ts), offset);
|
|
31
|
+
buffer.writeDoubleLE(row.value, offset + 8);
|
|
32
|
+
return buffer;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Encodes the fixed metrics schema as UTF8 String, UTC DateTime64(6), and exact IEEE754 Float64 bytes. */
|
|
36
|
+
export default function rowBinary(rows) {
|
|
37
|
+
return Buffer.concat(rows.map(record));
|
|
38
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { requireTelemetryTimestamps } from './jsonMetrics.js';
|
|
2
|
+
import insertMetricRows from './insertMetricRows.js';
|
|
3
|
+
|
|
4
|
+
/** Read every Float64 bit pattern at each timestamp for exact backfill verification. */
|
|
5
|
+
export default function clickhouseTelemetryTarget(client, window = {}) {
|
|
6
|
+
return {
|
|
7
|
+
async insertRows(rows) {
|
|
8
|
+
if (!rows.length) { return; }
|
|
9
|
+
requireTelemetryTimestamps(rows, window);
|
|
10
|
+
await insertMetricRows(client, rows);
|
|
11
|
+
},
|
|
12
|
+
async canonical(topic, first, last) {
|
|
13
|
+
const result = await client.query({
|
|
14
|
+
query: `SELECT toString(toUnixTimestamp64Micro(ts)) AS epochMicro,
|
|
15
|
+
groupUniqArray(toString(reinterpretAsUInt64(value))) AS valueBits FROM scada.metrics
|
|
16
|
+
WHERE topic={topic:String} AND ts >= {first:DateTime64(6,'UTC')}
|
|
17
|
+
AND ts <= {last:DateTime64(6,'UTC')} GROUP BY ts ORDER BY ts`,
|
|
18
|
+
query_params: { topic, first, last },
|
|
19
|
+
format: 'JSONEachRow',
|
|
20
|
+
clickhouse_settings: {
|
|
21
|
+
max_execution_time: 120, output_format_json_quote_64bit_integers: 1,
|
|
22
|
+
max_result_rows: 100000, max_result_bytes: 33554432, result_overflow_mode: 'throw'
|
|
23
|
+
}
|
|
24
|
+
});
|
|
25
|
+
return result.json();
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Prevent offline writes from bypassing coordinated history admission. */
|
|
31
|
+
export async function assertClickhouseBackfillMode(client, mode) {
|
|
32
|
+
if (mode === 'verify') { return; }
|
|
33
|
+
const result = await client.query({
|
|
34
|
+
query: "SELECT comment FROM system.tables WHERE database='scada' AND name='metrics'",
|
|
35
|
+
format: 'JSONEachRow'
|
|
36
|
+
});
|
|
37
|
+
const rows = await result.json();
|
|
38
|
+
if (rows.some(({ comment }) => { return comment?.startsWith('scada.local-history:'); })) {
|
|
39
|
+
throw new Error('History-owned ClickHouse target requires coordinated admission; offline copy/repair is disabled');
|
|
40
|
+
}
|
|
41
|
+
}
|
|
@@ -52,9 +52,32 @@ function replayCursor(pool, machineId) {
|
|
|
52
52
|
});
|
|
53
53
|
}
|
|
54
54
|
|
|
55
|
-
|
|
55
|
+
const coveredSegmentsQuery = `WITH open AS (
|
|
56
|
+
SELECT machine, name,
|
|
57
|
+
EXTRACT(EPOCH FROM start_time) AS start,
|
|
58
|
+
EXTRACT(EPOCH FROM end_time) AS "end"
|
|
59
|
+
FROM segments
|
|
60
|
+
WHERE duration = 0
|
|
61
|
+
),
|
|
62
|
+
covered AS (
|
|
63
|
+
SELECT DISTINCT ON (machine) machine, name,
|
|
64
|
+
EXTRACT(EPOCH FROM end_time) AS start,
|
|
65
|
+
EXTRACT(EPOCH FROM end_time) AS "end"
|
|
66
|
+
FROM segments
|
|
67
|
+
WHERE duration > 0
|
|
68
|
+
AND NOT EXISTS (
|
|
69
|
+
SELECT 1 FROM segments AS live
|
|
70
|
+
WHERE live.machine = segments.machine AND live.duration = 0
|
|
71
|
+
)
|
|
72
|
+
ORDER BY machine, start_time DESC
|
|
73
|
+
)
|
|
74
|
+
SELECT machine, name, start, "end" FROM open
|
|
75
|
+
UNION ALL
|
|
76
|
+
SELECT machine, name, start, "end" FROM covered`;
|
|
77
|
+
|
|
78
|
+
function pendingSegments(pool, includeClosedTail) {
|
|
56
79
|
return pool.query(
|
|
57
|
-
`SELECT machine, name,
|
|
80
|
+
includeClosedTail ? coveredSegmentsQuery : `SELECT machine, name,
|
|
58
81
|
EXTRACT(EPOCH FROM start_time) AS start,
|
|
59
82
|
EXTRACT(EPOCH FROM end_time) AS end
|
|
60
83
|
FROM segments
|
|
@@ -71,7 +94,7 @@ function pendingSegments(pool) {
|
|
|
71
94
|
});
|
|
72
95
|
}
|
|
73
96
|
|
|
74
|
-
function readings(pool, topics, from) {
|
|
97
|
+
function readings(pool, topics, from, limit) {
|
|
75
98
|
if (topics.length === 0) {
|
|
76
99
|
return Promise.resolve([]);
|
|
77
100
|
}
|
|
@@ -82,8 +105,8 @@ function readings(pool, topics, from) {
|
|
|
82
105
|
`SELECT topic, EXTRACT(EPOCH FROM ts) AS ts, value
|
|
83
106
|
FROM metrics
|
|
84
107
|
WHERE topic IN (${placeholders}) AND ts > to_timestamp($${topics.length + 1})
|
|
85
|
-
ORDER BY ts ASC`,
|
|
86
|
-
[...topics, from]
|
|
108
|
+
ORDER BY ts ASC${limit === undefined ? '' : ` LIMIT $${topics.length + 2}`}`,
|
|
109
|
+
[...topics, from, ...(limit === undefined ? [] : [limit])]
|
|
87
110
|
).then((result) => {
|
|
88
111
|
return result.rows.map((row) => {
|
|
89
112
|
return {
|
|
@@ -95,19 +118,22 @@ function readings(pool, topics, from) {
|
|
|
95
118
|
});
|
|
96
119
|
}
|
|
97
120
|
|
|
98
|
-
export default function checkpointStatePg(pool, metricsEnabled = true) {
|
|
121
|
+
export default function checkpointStatePg(pool, metricsEnabled = true, { includeClosedTail = false, readingsLimit, cyclePriorAllKinds = false } = {}) {
|
|
122
|
+
if (readingsLimit !== undefined && (!Number.isSafeInteger(readingsLimit) || readingsLimit < 1)) {
|
|
123
|
+
throw new TypeError('Positive checkpoint readingsLimit required');
|
|
124
|
+
}
|
|
99
125
|
return {
|
|
100
126
|
replayCursor(machineId) {
|
|
101
127
|
return replayCursor(pool, machineId);
|
|
102
128
|
},
|
|
103
129
|
pendingSegments() {
|
|
104
|
-
return pendingSegments(pool);
|
|
130
|
+
return pendingSegments(pool, includeClosedTail);
|
|
105
131
|
},
|
|
106
132
|
readings(topics, from) {
|
|
107
133
|
if (!metricsEnabled) {
|
|
108
134
|
return Promise.resolve([]);
|
|
109
135
|
}
|
|
110
|
-
return readings(pool, topics, from);
|
|
136
|
+
return readings(pool, topics, from, readingsLimit);
|
|
111
137
|
},
|
|
112
138
|
segment(machineId, startEpoch) {
|
|
113
139
|
return segmentAt(pool, machineId, startEpoch);
|
|
@@ -116,7 +142,7 @@ export default function checkpointStatePg(pool, metricsEnabled = true) {
|
|
|
116
142
|
return pool.query(
|
|
117
143
|
`SELECT name, start_time, end_time, duration, tags, options, properties
|
|
118
144
|
FROM segments
|
|
119
|
-
WHERE machine = $1 AND kind = 'phase' AND start_time < $2
|
|
145
|
+
WHERE machine = $1${cyclePriorAllKinds ? '' : " AND kind = 'phase'"} AND start_time < $2
|
|
120
146
|
ORDER BY start_time DESC`,
|
|
121
147
|
[machineId, new Date(beforeEpoch * 1000)]
|
|
122
148
|
).then((result) => {
|
|
@@ -1,34 +1,32 @@
|
|
|
1
1
|
import { historyWriteFence } from './segmentWriteFence.js';
|
|
2
|
-
import nativeHistoryBounds, {nativeTailProtocol} from './historyNativeBounds.js';
|
|
2
|
+
import nativeHistoryBounds, { clipReplacePage, joinReplacePage, nativeTailProtocol } from './historyNativeBounds.js';
|
|
3
3
|
import historyAbsorb, {historyDedupe, span} from './historyAbsorb.js';
|
|
4
4
|
import historyFence from './historyFence.js';
|
|
5
|
-
import
|
|
5
|
+
import historyPurge from './historyPurge.js';
|
|
6
6
|
import historyContext from './historyContext.js';
|
|
7
7
|
import historyAdmission, {assertHistoryReady} from './historyAdmission.js';
|
|
8
8
|
import {configureClassifier,saveCheckpoint} from './historyCheckpoint.js';
|
|
9
9
|
import historyCorrection from './historyCorrection.js';
|
|
10
10
|
import historyConfigure from './historyConfigure.js';
|
|
11
|
+
import segmentContinue from '../../../domain/segment/segmentContinue.js';
|
|
12
|
+
import pgHistorySession from './historySession.js';
|
|
11
13
|
|
|
12
14
|
export const historyProtocol = 'stateful-correction-v1';
|
|
13
15
|
|
|
14
16
|
function machineName(machine) {
|
|
15
17
|
if (typeof machine !== 'string' || !machine || machine.length > 200) { throw new TypeError('machine required'); }
|
|
16
18
|
}
|
|
17
|
-
async function ready(connection, machine, hold) {
|
|
19
|
+
async function ready(connection, machine, hold = null) {
|
|
18
20
|
try { await assertHistoryReady(connection, machine); return null; }
|
|
19
21
|
catch (error) { if (error.statusCode===409 && hold) { return hold; } throw error; }
|
|
20
22
|
}
|
|
21
|
-
|
|
23
|
+
function transaction(pool, machine, action, { topology = false, statementTimeoutMs } = {}) {
|
|
22
24
|
machineName(machine);
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
await client.query('BEGIN');
|
|
26
|
-
if (topology) {await client.query("SELECT pg_advisory_xact_lock(hashtextextended('history:configuration',0))");}
|
|
25
|
+
return pgHistorySession(pool, async (client) => {
|
|
26
|
+
if (topology) { await client.query("SELECT pg_advisory_xact_lock(hashtextextended('history:configuration',0))"); }
|
|
27
27
|
await client.query('SELECT pg_advisory_xact_lock(hashtextextended($1, 0))', [`history:${machine}`]);
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
return result;
|
|
31
|
-
} catch (error) { await client.query('ROLLBACK'); throw error; } finally { client.release(); }
|
|
28
|
+
return action(client);
|
|
29
|
+
}, statementTimeoutMs, true);
|
|
32
30
|
}
|
|
33
31
|
function observations(items) {
|
|
34
32
|
if (!Array.isArray(items) || items.length > 500) { throw new TypeError('At most 500 observations required'); }
|
|
@@ -37,8 +35,9 @@ function observations(items) {
|
|
|
37
35
|
|| !Number.isSafeInteger(item.time) || !Number.isFinite(item.value)) { throw new TypeError('Invalid observation'); }
|
|
38
36
|
});
|
|
39
37
|
}
|
|
40
|
-
function accept(pool, machine, items, cutoff) {
|
|
38
|
+
function accept(pool, machine, items, cutoff, { claimScope, statementTimeoutMs }) {
|
|
41
39
|
observations(items);
|
|
40
|
+
const reset = claimScope ? '' : 'token=gen_random_uuid(),cursor_ms=NULL,end_ms=NULL,';
|
|
42
41
|
return transaction(pool, machine, async (client) => {
|
|
43
42
|
const added = [];
|
|
44
43
|
for (const item of items) {
|
|
@@ -54,11 +53,11 @@ function accept(pool, machine, items, cutoff) {
|
|
|
54
53
|
// eslint-disable-next-line no-await-in-loop
|
|
55
54
|
await client.query(`INSERT INTO history_work(id,machine,from_ms,until_ms)
|
|
56
55
|
VALUES(md5($1||':'||$2::text)::uuid,$1,$3,$3)
|
|
57
|
-
ON CONFLICT(id) DO UPDATE SET
|
|
56
|
+
ON CONFLICT(id) DO UPDATE SET ${reset}from_ms=least(history_work.from_ms,excluded.from_ms),until_ms=greatest(history_work.until_ms,excluded.until_ms)`,
|
|
58
57
|
[machine,Math.floor(time/bucket),time]);
|
|
59
58
|
}
|
|
60
59
|
return { inserted: added.length };
|
|
61
|
-
});
|
|
60
|
+
}, { statementTimeoutMs });
|
|
62
61
|
}
|
|
63
62
|
function context(pool,machine,from,until,options) {
|
|
64
63
|
machineName(machine);
|
|
@@ -66,14 +65,14 @@ function context(pool,machine,from,until,options) {
|
|
|
66
65
|
}
|
|
67
66
|
async function snapshot(connection, machine, range, page, observationSource) {
|
|
68
67
|
if (observationSource) {
|
|
69
|
-
const held=await ready(connection,machine,page.classifierKey&&page.workId&&{available:false,items:[],segments:[],annotations:[],context:{from:range.from,until:range.until,paddingMs:page.padding,...page}});
|
|
68
|
+
const held=await ready(connection,machine,page.workPolicy === 'oldest'&&page.classifierKey&&page.workId&&{available:false,items:[],segments:[],annotations:[],context:{from:range.from,until:range.until,paddingMs:page.padding,...page}});
|
|
70
69
|
if (held) { return held; }
|
|
71
70
|
}
|
|
72
71
|
return context(connection,machine,range.from,range.until,{...page,observations:observationSource?.(connection)});
|
|
73
72
|
}
|
|
74
|
-
async function unchanged(client, machine, base, {observationSource,timeScale}) {
|
|
73
|
+
async function unchanged(client, machine, base, {observationSource,timeScale,workPolicy,claimScope,classifierOrigin}) {
|
|
75
74
|
await client.query('LOCK TABLE segments IN SHARE ROW EXCLUSIVE MODE');
|
|
76
|
-
const latest = await context(client, machine, base.from, base.until, { padding: base.paddingMs, cutoff: -Infinity,cursor:base.cursor ?? null,end:base.end ?? null,classifierKey:base.classifierKey,workId:base.workId,workToken:base.workToken,timeScale,observations:observationSource?.(client) });
|
|
75
|
+
const latest = await context(client, machine, base.from, base.until, { padding: base.paddingMs, cutoff: -Infinity,cursor:base.cursor ?? null,end:base.end ?? null,classifierKey:base.classifierKey,workId:base.workId,workToken:base.workToken,timeScale,workPolicy,claimScope,classifierOrigin,observations:observationSource?.(client) });
|
|
77
76
|
if (latest.revision !== base.revision) {
|
|
78
77
|
const error = Object.assign(new Error('History context changed'), {writeCode:'REVISION_CONFLICT'});
|
|
79
78
|
error.statusCode = 409;
|
|
@@ -81,8 +80,8 @@ async function unchanged(client, machine, base, {observationSource,timeScale}) {
|
|
|
81
80
|
}
|
|
82
81
|
return latest;
|
|
83
82
|
}
|
|
84
|
-
function checkClaim(work, base) {
|
|
85
|
-
if (String(work.token) !== base?.workToken || Number(work.from_ms)<base.from || Number(work.until_ms)>base.until || (work.cursor_ms === null ? null : Number(work.cursor_ms)) !== (base.cursor ?? null) || (work.end_ms === null ? null : Number(work.end_ms)) !== (base.end ?? null)) {
|
|
83
|
+
function checkClaim(work, base, claimScope) {
|
|
84
|
+
if (String(work.token) !== base?.workToken || Number(work.from_ms)<base.from || (!claimScope && Number(work.until_ms)>base.until) || (work.cursor_ms === null ? null : Number(work.cursor_ms)) !== (base.cursor ?? null) || (work.end_ms === null ? null : Number(work.end_ms)) !== (base.end ?? null)) {
|
|
86
85
|
const error = new Error('History work claim changed');
|
|
87
86
|
error.statusCode=409;
|
|
88
87
|
throw error;
|
|
@@ -93,17 +92,28 @@ async function advance(client,machine,workId,page) {
|
|
|
93
92
|
await client.query('UPDATE history_work SET cursor_ms=$3,end_ms=$4,token=gen_random_uuid() WHERE id=$1 AND machine=$2',[workId,machine,page.next,page.end]);
|
|
94
93
|
} else { await client.query('DELETE FROM history_work WHERE id=$1 AND machine=$2', [workId, machine]); }
|
|
95
94
|
}
|
|
96
|
-
function
|
|
95
|
+
async function continueStored(client, machine, item, apply) {
|
|
96
|
+
const prior = await client.query(
|
|
97
|
+
'SELECT name, start_time, end_time FROM segments WHERE machine=$1 AND kind=$2 ORDER BY start_time DESC LIMIT 1',
|
|
98
|
+
[machine, item.kind ?? 'phase']
|
|
99
|
+
);
|
|
100
|
+
return apply({ ...item, start_time: new Date(item.start_time).toISOString(), end_time: new Date(item.end_time).toISOString(),
|
|
101
|
+
duration: item.duration ?? 0 }, prior.rows[0]);
|
|
102
|
+
}
|
|
103
|
+
function commit(pool, machine, workId, segments, settings) {
|
|
104
|
+
const {base, observationSource,timeScale,processorProperties,workPolicy,claimScope,continueStoredPhase,statementTimeoutMs} = settings;
|
|
97
105
|
if (!Array.isArray(segments) || segments.length > 1000) { throw new TypeError('Bounded segments required'); }
|
|
98
106
|
// eslint-disable-next-line max-statements -- Claim, correction, checkpoint and advancement share one atomic boundary.
|
|
99
107
|
return transaction(pool, machine, client => {return historyWriteFence(client,machine,{base,workId,segments},async () => {
|
|
100
108
|
const work = await client.query(`SELECT id,token,from_ms,until_ms,cursor_ms,end_ms${base?.replace?',generation':''} FROM history_work WHERE id=$1 AND machine=$2 FOR UPDATE`, [workId, machine]);
|
|
101
109
|
if (!work.rowCount) { return { applied: false }; }
|
|
102
|
-
checkClaim(work.rows[0],base);
|
|
110
|
+
checkClaim(work.rows[0],base,claimScope);
|
|
103
111
|
if (segments.length && !base?.revision) { throw new TypeError('History context revision required'); }
|
|
104
|
-
if (observationSource) { const held=await ready(client,machine,{applied:false}); if (held) { return held; } }
|
|
105
|
-
const latest = base?.revision ? await unchanged(client, machine, base,
|
|
106
|
-
const
|
|
112
|
+
if (observationSource) { const held=await ready(client,machine,workPolicy === 'live' ? null : {applied:false}); if (held) { return held; } }
|
|
113
|
+
const latest = base?.revision ? await unchanged(client, machine, base, settings) : null;
|
|
114
|
+
const rows = base?.replace && workPolicy === 'live'
|
|
115
|
+
? joinReplacePage(clipReplacePage(segments, latest, timeScale)) : segments;
|
|
116
|
+
const exteriors = nativeHistoryBounds(rows, latest, base, timeScale);
|
|
107
117
|
for (const item of exteriors) {
|
|
108
118
|
// An unseen existing cut must never be overwritten by a new exterior piece.
|
|
109
119
|
// eslint-disable-next-line no-await-in-loop
|
|
@@ -111,8 +121,8 @@ function commit(pool, machine, workId, segments, {base, observationSource,timeSc
|
|
|
111
121
|
if (conflict.rowCount) { throw new TypeError('History suffix collides with a cut outside the observed page'); }
|
|
112
122
|
}
|
|
113
123
|
if(base?.replace){
|
|
114
|
-
const next=await historyCorrection(client,machine,work.rows[0],
|
|
115
|
-
if (
|
|
124
|
+
const next=await historyCorrection(client,machine,work.rows[0],rows,{base,context:latest,timeScale,processorProperties});
|
|
125
|
+
if (rows.length) { await historyDedupe(client, machine, span(rows)); }
|
|
116
126
|
await advance(client,machine,workId,next);
|
|
117
127
|
return {applied:true};
|
|
118
128
|
}
|
|
@@ -121,9 +131,11 @@ function commit(pool, machine, workId, segments, {base, observationSource,timeSc
|
|
|
121
131
|
WHERE machine=$1 AND start_time<=$3 AND end_time>=$2
|
|
122
132
|
ON CONFLICT(machine,kind,start_time,name) DO UPDATE SET end_time=greatest(history_annotations.end_time,EXCLUDED.end_time),duration=EXCLUDED.duration,tags=EXCLUDED.tags,properties=EXCLUDED.properties,resolved=EXCLUDED.resolved`, [machine,new Date((latest?.context.page.from ?? base.from)/timeScale),new Date((latest?.context.page.until ?? base.until)/timeScale)]);
|
|
123
133
|
// A CAS-validated native page supplies its own phase boundaries and exterior.
|
|
124
|
-
const nativePage = base?.nativeTailMode === nativeTailProtocol;
|
|
134
|
+
const nativePage = workPolicy !== 'live' && base?.nativeTailMode === nativeTailProtocol;
|
|
125
135
|
const folded = nativePage ? segments : await historyAbsorb(client, machine, segments);
|
|
126
136
|
for (const item of folded) {
|
|
137
|
+
// eslint-disable-next-line no-await-in-loop
|
|
138
|
+
const row = continueStoredPhase ? await continueStored(client, machine, item, continueStoredPhase) : item;
|
|
127
139
|
// Only computed fields change. User cuts/labels must be applied by caller before commit.
|
|
128
140
|
// eslint-disable-next-line no-await-in-loop
|
|
129
141
|
await client.query(`INSERT INTO segments(machine,kind,name,start_time,end_time,duration,options,tags,properties,resolved,consumed)
|
|
@@ -132,7 +144,7 @@ function commit(pool, machine, workId, segments, {base, observationSource,timeSc
|
|
|
132
144
|
tags=CASE WHEN segments.name=EXCLUDED.name THEN segments.tags ELSE EXCLUDED.tags END,
|
|
133
145
|
properties=CASE WHEN segments.name=EXCLUDED.name THEN segments.properties ELSE EXCLUDED.properties END,
|
|
134
146
|
resolved=CASE WHEN segments.name=EXCLUDED.name THEN segments.resolved ELSE EXCLUDED.resolved END`,
|
|
135
|
-
[machine,
|
|
147
|
+
[machine, row.kind ?? 'phase', row.name, row.start_time, row.end_time, row.duration,
|
|
136
148
|
typeof item.options === 'string' ? item.options : JSON.stringify(item.options ?? null),
|
|
137
149
|
typeof item.tags === 'string' ? item.tags : JSON.stringify(item.tags ?? null),
|
|
138
150
|
typeof item.properties === 'string' ? item.properties : JSON.stringify(item.properties ?? null), item.resolved ?? true, item.consumed ?? true]);
|
|
@@ -141,12 +153,35 @@ function commit(pool, machine, workId, segments, {base, observationSource,timeSc
|
|
|
141
153
|
const converged=await saveCheckpoint(client,machine,base?.checkpoint,latest);
|
|
142
154
|
await advance(client,machine,workId,converged ? {next:null} : latest?.context.page);
|
|
143
155
|
return { applied: true };
|
|
144
|
-
})});
|
|
156
|
+
})}, { statementTimeoutMs });
|
|
157
|
+
}
|
|
158
|
+
function ownedProcessorProperties(properties) {
|
|
159
|
+
if (!Array.isArray(properties) || !properties.every((key) => { return typeof key === 'string' && key.length > 0; })) {
|
|
160
|
+
throw new TypeError('Processor properties must be a list of nonempty strings');
|
|
161
|
+
}
|
|
162
|
+
return [...properties];
|
|
163
|
+
}
|
|
164
|
+
async function eligibleWork(pool, machine, { observationSource, timeScale, workPolicy }) {
|
|
165
|
+
const order = workPolicy === 'live' ? 'until_ms DESC,created_at DESC,id DESC LIMIT 1' : 'until_ms ASC,created_at,id LIMIT 8';
|
|
166
|
+
machineName(machine);
|
|
167
|
+
if (observationSource && await ready(pool,machine,workPolicy === 'live' ? null : {items:[]})) { return {items:[]}; }
|
|
168
|
+
const fence = await historyFence(pool, machine, timeScale);
|
|
169
|
+
const result = await pool.query(`SELECT id,token,machine AS "streamId",from_ms AS "from",until_ms AS "until",cursor_ms AS cursor,end_ms AS end
|
|
170
|
+
FROM history_work WHERE machine=$1 AND until_ms < $2 - COALESCE((SELECT bucket_ms FROM history_topics WHERE machine=$1 LIMIT 1), 30000 * $3)
|
|
171
|
+
ORDER BY ${order}`, [machine, fence, timeScale]);
|
|
172
|
+
return { items: result.rows.map((row) => { return { ...row, from: Number(row.from), until: Number(row.until),cursor:row.cursor === null ? null : Number(row.cursor),end:row.end === null ? null : Number(row.end) }; }) };
|
|
145
173
|
}
|
|
146
174
|
/** Local telemetry history and durable classification work; no cross-edge database dependency. */
|
|
147
|
-
export default function historyPg(pool, { retentionDays = 30, now = Date.now, observations: observationSource,timeScale=1,timestamp
|
|
175
|
+
export default function historyPg(pool, { retentionDays = 30, now = Date.now, observations: observationSource,timeScale=1,timestamp,processorProperties = [], workPolicy = 'oldest',
|
|
176
|
+
claimScope = false, classifierOrigin, statementTimeoutMs, purgeBatchSize, continuationSeconds } = {}) {
|
|
148
177
|
if (![1,1000].includes(timeScale) || (timeScale!==1 && !observationSource)) {throw new TypeError('External history supports millisecond or microsecond coordinates');}
|
|
149
178
|
if (!Number.isSafeInteger(retentionDays) || retentionDays <= 0) { throw new TypeError('Positive retentionDays required'); }
|
|
179
|
+
const ownedProperties = ownedProcessorProperties(processorProperties);
|
|
180
|
+
if (!['oldest', 'live'].includes(workPolicy)) { throw new TypeError('Invalid history work policy'); }
|
|
181
|
+
const settings = {
|
|
182
|
+
observationSource, timeScale, workPolicy, claimScope, classifierOrigin, statementTimeoutMs,
|
|
183
|
+
processorProperties: ownedProperties, continueStoredPhase: continuationSeconds ? segmentContinue(continuationSeconds) : null
|
|
184
|
+
};
|
|
150
185
|
function cutoff() { return (now() - retentionDays * 86400000)*timeScale; }
|
|
151
186
|
const admission=observationSource ? historyAdmission(pool,{now:()=>{return now()*timeScale;},timeScale,timestamp}) : null;
|
|
152
187
|
return {
|
|
@@ -159,36 +194,19 @@ export default function historyPg(pool, { retentionDays = 30, now = Date.now, ob
|
|
|
159
194
|
const result=await historyConfigure(client,machine,topics,bucketMs*timeScale,{retentionDays,observations:source});
|
|
160
195
|
await configureClassifier(client,machine,classifierKey,source);
|
|
161
196
|
return {...result,...((timeScale!==1 || classifierKey) && {timeScale}),...(!classifierKey && {nativeTailProtocol}),...(classifierKey && {classifierProtocol:historyProtocol})};
|
|
162
|
-
},true);
|
|
163
|
-
},
|
|
164
|
-
async purge() {
|
|
165
|
-
const result = await pool.query(`DELETE FROM history_observations o WHERE time_ms < $1
|
|
166
|
-
AND NOT EXISTS (SELECT 1 FROM history_work w WHERE w.machine=o.machine
|
|
167
|
-
AND (o.time_ms BETWEEN w.from_ms-86400000 AND greatest(w.until_ms,COALESCE(w.end_ms,w.until_ms))+86400000
|
|
168
|
-
OR (o.time_ms<w.from_ms-86400000 AND NOT EXISTS (SELECT 1 FROM history_observations anchor
|
|
169
|
-
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))))
|
|
170
|
-
AND EXISTS (SELECT 1 FROM history_observations newer WHERE newer.machine=o.machine
|
|
171
|
-
AND newer.channel=o.channel AND newer.time_ms>o.time_ms AND newer.time_ms<$1)`, [cutoff()]);
|
|
172
|
-
await retainMetricReceipts(pool, retentionDays);
|
|
173
|
-
return result.rowCount;
|
|
197
|
+
},{ topology: true, statementTimeoutMs });
|
|
174
198
|
},
|
|
199
|
+
purge() { return historyPurge(pool, cutoff(), retentionDays, purgeBatchSize); },
|
|
175
200
|
accept(machine, items) {
|
|
176
201
|
if (observationSource) { throw new TypeError('External observations require durable telemetry admission'); }
|
|
177
|
-
return accept(pool, machine, items, cutoff()); },
|
|
202
|
+
return accept(pool, machine, items, cutoff(), settings); },
|
|
178
203
|
context(machine, from, until, padding = 60000*timeScale, page = {}) {
|
|
179
|
-
const options={padding,cutoff:cutoff(),...page,timeScale};
|
|
204
|
+
const options={padding,cutoff:cutoff(),...page,timeScale,workPolicy,claimScope,classifierOrigin};
|
|
180
205
|
function read(connection) { return snapshot(connection,machine,{from,until},options,observationSource); }
|
|
181
|
-
return page.classifierKey && page.workId ? transaction(pool,machine,read
|
|
182
|
-
|
|
183
|
-
async work(machine) {
|
|
184
|
-
machineName(machine);
|
|
185
|
-
if (observationSource) { try { await assertHistoryReady(pool,machine); } catch (error) { if (error.statusCode===409) { return {items:[]}; } throw error; } }
|
|
186
|
-
const fence = await historyFence(pool, machine, timeScale);
|
|
187
|
-
const result = await pool.query(`SELECT id,token,machine AS "streamId",from_ms AS "from",until_ms AS "until",cursor_ms AS cursor,end_ms AS end
|
|
188
|
-
FROM history_work WHERE machine=$1 AND until_ms < $2 - COALESCE((SELECT bucket_ms FROM history_topics WHERE machine=$1 LIMIT 1), 30000 * $3)
|
|
189
|
-
ORDER BY until_ms ASC,created_at,id LIMIT 8`, [machine, fence, timeScale]);
|
|
190
|
-
return { items: result.rows.map((row) => { return { ...row, from: Number(row.from), until: Number(row.until),cursor:row.cursor === null ? null : Number(row.cursor),end:row.end === null ? null : Number(row.end) }; }) };
|
|
206
|
+
return page.classifierKey && page.workId ? transaction(pool,machine,read,{ statementTimeoutMs })
|
|
207
|
+
: pgHistorySession(pool, read, statementTimeoutMs);
|
|
191
208
|
},
|
|
192
|
-
|
|
209
|
+
work(machine) { return pgHistorySession(pool, (connection) => { return eligibleWork(connection, machine, settings); }, statementTimeoutMs); },
|
|
210
|
+
commit(machine, workId, segments, base) { return commit(pool, machine, workId, segments, {...settings, base}); }
|
|
193
211
|
};
|
|
194
212
|
}
|
|
@@ -17,43 +17,60 @@ async function segmentBoundary(pool,machine,right,segments,timeScale) {
|
|
|
17
17
|
const tail = await pool.query(`SELECT max(end_time) AS end_time FROM segments WHERE machine=$1 AND kind=$2 AND start_time>=$3`,[machine,last.kind,last.start_time]);
|
|
18
18
|
return Math.max(right,new Date(tail.rows[0].end_time ?? last.end_time).getTime()*timeScale);
|
|
19
19
|
}
|
|
20
|
+
async function islandStart(pool, machine, left, origin, timeScale) {
|
|
21
|
+
if (!Number.isFinite(origin)) { return left; }
|
|
22
|
+
const prior = await pool.query("SELECT start_time FROM segments WHERE machine=$1 AND kind='phase' AND duration>0 AND end_time<=$2 ORDER BY end_time DESC LIMIT 1",
|
|
23
|
+
[machine, new Date(origin/timeScale)]);
|
|
24
|
+
const priorStart = prior.rows[0]?.start_time ? new Date(prior.rows[0].start_time).getTime()*timeScale : origin;
|
|
25
|
+
return Math.min(left, origin, priorStart);
|
|
26
|
+
}
|
|
27
|
+
async function dependencyEnd(pool, machine, {right, previous, held, classifierKey, claimScope, until, timeScale}) {
|
|
28
|
+
if (claimScope) {
|
|
29
|
+
if (classifierKey && held!==null) { return Math.min(until, held); }
|
|
30
|
+
return Math.min(until, await segmentBoundary(pool,machine,right,previous,timeScale));
|
|
31
|
+
}
|
|
32
|
+
const prior = previous.at(-1);
|
|
33
|
+
const edge = classifierKey && prior && Number(prior.duration)===0 ? right : await segmentBoundary(pool,machine,right,previous,timeScale);
|
|
34
|
+
const extended = classifierKey && held!==null ? held : Math.max(held ?? right,edge);
|
|
35
|
+
const fence = !classifierKey && timeScale===1 ? await historyFence(pool, machine) : null;
|
|
36
|
+
return fence!==null && until<fence ? Math.min(extended, fence-1) : extended;
|
|
37
|
+
}
|
|
20
38
|
/** Read a finite dependency envelope in stored history, compacting unchanged heartbeat observations. */
|
|
21
39
|
// eslint-disable-next-line max-statements
|
|
22
|
-
export default async function historyContext(pool,machine,from,until,{padding,cutoff,cursor = null,end: envelope = null,observations: source = historyObservationsPg(pool),classifierKey,timeScale=1,workId,workToken}) {
|
|
40
|
+
export default async function historyContext(pool,machine,from,until,{padding,cutoff,cursor = null,end: envelope = null,observations: source = historyObservationsPg(pool),classifierKey,timeScale=1,workId,workToken,workPolicy,claimScope = false,classifierOrigin}) {
|
|
23
41
|
if (![from,until,padding].every(Number.isSafeInteger) || from>until || padding<0 || padding>86400000*timeScale) { throw new TypeError('Invalid history range'); }
|
|
24
42
|
const range = { from,until,paddingMs:padding,cursor,end:envelope,...(classifierKey && {classifierKey}),...(timeScale!==1 && {timeScale}),...(workId && {workId,workToken}) };
|
|
25
43
|
if ((cursor !== null && !Number.isSafeInteger(cursor)) || (envelope !== null && !Number.isSafeInteger(envelope))) { throw new TypeError('Invalid history cursor'); }
|
|
26
44
|
const claim=await classifierClaim(pool,machine,{workId,workToken,from,until,cursor,end:envelope});
|
|
27
|
-
if(claim){range.from=Number(claim.from_ms);range.until=Number(claim.until_ms);}
|
|
28
|
-
const held
|
|
45
|
+
if(claim && !claimScope){range.from=Number(claim.from_ms);range.until=Number(claim.until_ms);}
|
|
46
|
+
const held=!claimScope && claim && envelope===null && claim.end_ms!==null ? Number(claim.end_ms) : envelope;
|
|
29
47
|
if (held!==null && envelope===null) { range.end=held; }
|
|
30
48
|
if (from<cutoff && !claim) {
|
|
31
49
|
const pending = cursor === null || envelope === null ? {rowCount:0} : await pool.query(`SELECT 1 FROM history_work WHERE machine=$1 AND from_ms=$2 AND until_ms=$3 AND cursor_ms=$4 AND end_ms=$5 LIMIT 1`,[machine,from,until,cursor,envelope]);
|
|
32
50
|
if (!pending.rowCount) { return {available:false,items:[],segments:[],annotations:[],context:range}; }
|
|
33
51
|
}
|
|
34
52
|
const classifier=classifierKey ? await classifierSeed(pool,machine,cursor ?? from,classifierKey,{claim,cursor}) : null;
|
|
35
|
-
let left = cursor ?? from-padding;
|
|
36
|
-
if (classifierKey && cursor===null) { left=classifier ? classifier.at+1 : await source.start(machine); }
|
|
37
|
-
const
|
|
53
|
+
let left = cursor ?? from - padding;
|
|
54
|
+
if (classifierKey && cursor === null) { left = classifier ? classifier.at + 1 : await source.start(machine); }
|
|
55
|
+
const start = workPolicy === 'live' ? Math.max(left, from - padding) : left;
|
|
56
|
+
const boundary = classifierKey && held!==null ? held : Math.max(held ?? until,await source.boundary(machine,from,until,padding));
|
|
57
|
+
const right = claimScope ? Math.min(until, boundary) : boundary;
|
|
38
58
|
const previous = await pool.query(`SELECT kind,name,start_time,end_time,duration FROM segments WHERE machine=$1 AND kind='phase' AND start_time<=$2 ORDER BY start_time DESC LIMIT 1`,[machine,new Date(right/timeScale)]);
|
|
39
|
-
const
|
|
40
|
-
const edge=classifierKey && prior && Number(prior.duration)===0 ? right : await segmentBoundary(pool,machine,right,previous.rows,timeScale);
|
|
41
|
-
const extended = classifierKey && held!==null ? held : Math.max(held ?? right,edge);
|
|
42
|
-
const fence = !classifierKey && timeScale===1 ? await historyFence(pool, machine) : null;
|
|
43
|
-
const end = fence!==null && until<fence ? Math.min(extended, fence-1) : extended;
|
|
59
|
+
const end = await dependencyEnd(pool, machine, {right,previous:previous.rows,held,classifierKey,claimScope,until,timeScale});
|
|
44
60
|
if(classifierKey && claim && held===null){
|
|
45
61
|
await pool.query('UPDATE history_work SET end_ms=$3 WHERE id=$1 AND machine=$2',[workId,machine,end]);
|
|
46
62
|
range.end=end;
|
|
47
63
|
}
|
|
48
64
|
// Fetch timestamp keys only, then read at most 250 complete groups. Never fetch the raw dependency tail.
|
|
49
|
-
const rawPage = await source.page(machine,
|
|
65
|
+
const rawPage = await source.page(machine,start,end);
|
|
50
66
|
const page=classifierKey ? await classifierPage(pool,machine,rawPage,classifierKey) : rawPage;
|
|
51
67
|
const {next,until:pageEnd} = page;
|
|
52
68
|
range.page = page;
|
|
69
|
+
const origin = await islandStart(pool, machine, start, classifierOrigin?.(classifier, timeScale), timeScale);
|
|
53
70
|
const segments = await pool.query(`SELECT kind,name,start_time,end_time,duration,options,tags,properties,resolved,consumed FROM segments
|
|
54
|
-
WHERE machine=$1 AND kind='phase' AND start_time<=$3 AND (end_time>=$2 OR (duration=0 AND start_time>=$2)) ORDER BY start_time LIMIT 10001`,[machine,new Date(
|
|
71
|
+
WHERE machine=$1 AND kind='phase' AND start_time<=$3 AND (end_time>=$2 OR (duration=0 AND start_time>=$2)) ORDER BY start_time LIMIT 10001`,[machine,new Date(origin/timeScale),new Date(pageEnd/timeScale)]);
|
|
55
72
|
bounded(segments.rows);
|
|
56
|
-
const observations = await source.read(machine,
|
|
73
|
+
const observations = await source.read(machine,start,pageEnd,padding);
|
|
57
74
|
const annotations = await pool.query(`SELECT a.kind,a.name,a.start_time,a.end_time,a.duration,
|
|
58
75
|
CASE WHEN s.machine IS NOT NULL THEN s.tags ELSE a.tags END AS tags,
|
|
59
76
|
CASE WHEN s.machine IS NOT NULL THEN s.properties ELSE a.properties END AS properties,
|
|
@@ -61,12 +78,12 @@ export default async function historyContext(pool,machine,from,until,{padding,cu
|
|
|
61
78
|
FROM history_annotations a LEFT JOIN segments s ON s.machine=a.machine AND s.kind=a.kind AND s.start_time=a.start_time AND s.name=a.name
|
|
62
79
|
WHERE a.machine=$1 AND a.kind='phase' AND a.start_time<=$3 AND a.end_time>=$2
|
|
63
80
|
AND (COALESCE(a.tags,'') NOT IN ('','null','[]') OR COALESCE(a.properties,'') NOT IN ('','null','{}')) ORDER BY a.start_time,a.name LIMIT 10001`,
|
|
64
|
-
[machine,new Date(
|
|
81
|
+
[machine,new Date(start/timeScale),new Date(pageEnd/timeScale)]);
|
|
65
82
|
bounded(annotations.rows);
|
|
66
|
-
const initial = classifierKey ? null : await historySeed(pool,machine,
|
|
83
|
+
const initial = classifierKey ? null : await historySeed(pool,machine,start,padding,{observations:source,timeScale,bounded:claimScope});
|
|
67
84
|
if (initial?.segment && !segments.rows.some((row) => { return row.start_time.getTime() === initial.segment.start_time.getTime(); })) { segments.rows.unshift(initial.segment); }
|
|
68
85
|
const last = observations.items.at(-1)?.time;
|
|
69
86
|
const rightClosed = next === null && last !== undefined && segments.rows.some((row) => { return row.duration>0 && new Date(row.end_time).getTime()*timeScale>=last; });
|
|
70
87
|
const snapshot = { page,initial,...(classifierKey && {classifierSeed:classifier}),annotations:annotations.rows,segments:segments.rows,...observations,rightClosed };
|
|
71
|
-
return { ...snapshot,available:true,revision:historyRevision(snapshot, range.until, timeScale),context:range };
|
|
88
|
+
return { ...snapshot,available:true,revision:historyRevision(snapshot, claimScope ? envelope ?? until : range.until, timeScale),context:range };
|
|
72
89
|
}
|
|
@@ -19,7 +19,7 @@ async function writeCorrections(client,machine,work,segments) {
|
|
|
19
19
|
}
|
|
20
20
|
}
|
|
21
21
|
/** Staged results stay invisible until their finite dependency has completed or converged. */
|
|
22
|
-
export default async function historyCorrection(client,machine,work,segments,{base,context,timeScale}) {
|
|
22
|
+
export default async function historyCorrection(client,machine,work,segments,{base,context,timeScale,processorProperties=[]}) {
|
|
23
23
|
if(!context?.context.classifierKey || !base.workId || base.workId!==work.id){throw new TypeError('Claimed classifier context required for staged correction');}
|
|
24
24
|
if(context.items.length && !base.checkpoint){throw new TypeError('Classifier checkpoint required for a nonempty correction page');}
|
|
25
25
|
await writeCorrections(client,machine,work,segments);
|
|
@@ -29,6 +29,9 @@ export default async function historyCorrection(client,machine,work,segments,{ba
|
|
|
29
29
|
const matches=await saveCheckpoint(client,machine,base.checkpoint,context,work);
|
|
30
30
|
const converged=matches && await canConverge(client,machine,work,new Date(Math.round(context.page.until/timeScale)));
|
|
31
31
|
const finished=context.page.next===null || converged;
|
|
32
|
-
if(finished){
|
|
32
|
+
if (finished) {
|
|
33
|
+
await client.query('SELECT history_apply_correction($1,$2,$3,$4,$5::text[])',
|
|
34
|
+
[work.id,machine,timeScale,converged,processorProperties]);
|
|
35
|
+
}
|
|
33
36
|
return finished?{next:null}:context.page;
|
|
34
37
|
}
|