@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,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
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import kubeServiceAccount from '../management/kubeServiceAccount.js';
|
|
2
|
+
import { tlsMaterialLimit, validateTLSMaterial } from './tlsMaterial.js';
|
|
3
|
+
|
|
4
|
+
function targetPath({namespace,name}) {
|
|
5
|
+
if (![namespace,name].every(value => { return typeof value === 'string' && /^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/u.test(value); })) {
|
|
6
|
+
throw new Error('TLS Secret target is invalid');
|
|
7
|
+
}
|
|
8
|
+
return `/api/v1/namespaces/${namespace}/secrets/${name}`;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function kubernetesTLSAPI(environment) {
|
|
12
|
+
const host = environment.KUBERNETES_SERVICE_HOST;
|
|
13
|
+
const port = environment.KUBERNETES_SERVICE_PORT_HTTPS || '443';
|
|
14
|
+
if (!host) { throw new Error('TLS Secret API address is missing'); }
|
|
15
|
+
const address = `https://${host.includes(':') ? `[${host}]` : host}:${port}`;
|
|
16
|
+
const request = kubeServiceAccount(address, { limit: tlsMaterialLimit, timeoutMs: 10000 });
|
|
17
|
+
async function exchange(path, method, body) {
|
|
18
|
+
try {
|
|
19
|
+
const result = await request(method, path, body);
|
|
20
|
+
if (result.status !== 200) { throw new Error('Refused'); }
|
|
21
|
+
return JSON.parse(result.body);
|
|
22
|
+
} catch { throw new Error('TLS Secret API request failed'); }
|
|
23
|
+
}
|
|
24
|
+
return {get:target => { return exchange(targetPath(target),'GET'); },update:(target,body) => { return exchange(targetPath(target),'PUT',body); }};
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Update an already-existing named Secret only; RBAC grants no create or namespace discovery. */
|
|
28
|
+
export async function mirrorTLSSecret(payload, { target, hosts, api, roots, format }) {
|
|
29
|
+
const data = validateTLSMaterial(payload, { hosts, roots, format });
|
|
30
|
+
targetPath(target);
|
|
31
|
+
const secret = await api.get(target);
|
|
32
|
+
if (secret.metadata?.name !== target.name || secret.metadata?.namespace !== target.namespace
|
|
33
|
+
|| !secret.metadata?.resourceVersion || secret.type !== 'kubernetes.io/tls') { throw new Error('TLS Secret target does not match'); }
|
|
34
|
+
if (secret.data?.['tls.crt'] === data['tls.crt'] && secret.data?.['tls.key'] === data['tls.key']) { return false; }
|
|
35
|
+
await api.update(target,{...secret,data:{...secret.data,...data}});
|
|
36
|
+
return true;
|
|
37
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { createServer, request } from 'node:https';
|
|
3
|
+
|
|
4
|
+
const defaultLimit = 1024 * 1024;
|
|
5
|
+
|
|
6
|
+
export function readMutualTLS({ key, cert, ca }) {
|
|
7
|
+
try {
|
|
8
|
+
return { key: readFileSync(key), cert: readFileSync(cert), ca: readFileSync(ca), minVersion: 'TLSv1.2' };
|
|
9
|
+
} catch { throw new Error('Mutual TLS files are required'); }
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function respond(response, status, body) {
|
|
13
|
+
response.writeHead(status, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }).end(body);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
async function respondJSON(response, { read, maxBytes = defaultLimit, unavailable }) {
|
|
17
|
+
try {
|
|
18
|
+
const result = await read();
|
|
19
|
+
if (result === undefined) {
|
|
20
|
+
respond(response, 404, '{"error":"Not found"}');
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
const body = JSON.stringify(result);
|
|
24
|
+
if (Buffer.byteLength(body) > maxBytes) { throw new Error('JSON body limit exceeded'); }
|
|
25
|
+
respond(response, 200, body);
|
|
26
|
+
} catch { respond(response, 503, JSON.stringify({ error: unavailable || 'Resource unavailable' })); }
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function serveMutualTLS({ tls, routes }) {
|
|
30
|
+
const server = createServer({ ...tls, requestCert: true, rejectUnauthorized: true, minVersion: 'TLSv1.2' }, (incoming, response) => {
|
|
31
|
+
if (!incoming.socket.authorized) { respond(response, 403, '{"error":"Client certificate required"}'); }
|
|
32
|
+
else if (incoming.method !== 'GET') { respond(response, 405, '{"error":"Method not allowed"}'); }
|
|
33
|
+
else if (Object.hasOwn(routes, incoming.url)) { void respondJSON(response, routes[incoming.url]); }
|
|
34
|
+
else { respond(response, 404, '{"error":"Not found"}'); }
|
|
35
|
+
});
|
|
36
|
+
server.requestTimeout = 30000;
|
|
37
|
+
server.headersTimeout = 10000;
|
|
38
|
+
server.maxConnections = 8;
|
|
39
|
+
return server;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function collect(response, resolve, reject, maxBytes, decode) {
|
|
43
|
+
const chunks = [];
|
|
44
|
+
let size = 0;
|
|
45
|
+
response.on('data', (chunk) => {
|
|
46
|
+
size += chunk.length;
|
|
47
|
+
if (size > maxBytes) { response.destroy(new Error('JSON body limit exceeded')); }
|
|
48
|
+
else { chunks.push(chunk); }
|
|
49
|
+
});
|
|
50
|
+
response.on('error', () => { reject(new Error('HTTPS transport failed')); });
|
|
51
|
+
response.on('end', () => {
|
|
52
|
+
try { resolve(decode(JSON.parse(Buffer.concat(chunks).toString('utf8')))); }
|
|
53
|
+
catch { reject(new Error('HTTPS JSON response is invalid')); }
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export async function fetchMutualJSON({ url, tls, maxBytes = defaultLimit, path, decode = (value) => { return value; }, optional }) {
|
|
58
|
+
const address = new URL(url);
|
|
59
|
+
if (address.protocol !== 'https:' || address.username || address.password) {
|
|
60
|
+
throw new Error('JSON transport requires HTTPS without credentials');
|
|
61
|
+
}
|
|
62
|
+
if (address.pathname !== path || address.search || address.hash) {
|
|
63
|
+
throw new Error(`JSON transport requires the ${path} endpoint`);
|
|
64
|
+
}
|
|
65
|
+
return await new Promise((resolve, reject) => {
|
|
66
|
+
const connection = request(address, {
|
|
67
|
+
...tls, method: 'GET', rejectUnauthorized: true, minVersion: 'TLSv1.2', timeout: 20000, agent: false
|
|
68
|
+
}, (response) => {
|
|
69
|
+
if (optional && response.statusCode === 404) { response.resume(); resolve(null); return; }
|
|
70
|
+
if (response.statusCode !== 200 || !response.headers['content-type']?.startsWith('application/json')) {
|
|
71
|
+
response.resume(); reject(new Error('HTTPS endpoint refused the request')); return;
|
|
72
|
+
}
|
|
73
|
+
collect(response, resolve, reject, maxBytes, decode);
|
|
74
|
+
});
|
|
75
|
+
connection.on('timeout', () => { connection.destroy(new Error('HTTPS request timed out')); });
|
|
76
|
+
connection.on('error', () => { reject(new Error('HTTPS transport failed')); });
|
|
77
|
+
connection.end();
|
|
78
|
+
});
|
|
79
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import {createPrivateKey, createPublicKey, X509Certificate} from 'node:crypto';
|
|
2
|
+
import {rootCertificates} from 'node:tls';
|
|
3
|
+
import { readFileSync } from 'node:fs';
|
|
4
|
+
import { jsonDigest } from '../replication/canonicalJSON.js';
|
|
5
|
+
|
|
6
|
+
export const tlsMaterialLimit = 1024 * 1024;
|
|
7
|
+
const defaultFormat = 'tls-material-v1';
|
|
8
|
+
|
|
9
|
+
function invalid() { throw new Error('Public TLS renewal is invalid'); }
|
|
10
|
+
|
|
11
|
+
export function sealTLSMaterial(cert, key, { format = defaultFormat } = {}) {
|
|
12
|
+
const content = {cert:Buffer.from(cert).toString('base64'),key:Buffer.from(key).toString('base64')};
|
|
13
|
+
return {format, ...content, hash: jsonDigest(content)};
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function chain(cert) {
|
|
17
|
+
const blocks = cert.match(/-----BEGIN CERTIFICATE-----[\s\S]+?-----END CERTIFICATE-----/gu);
|
|
18
|
+
if (!blocks?.length || blocks.length > 8) { invalid(); }
|
|
19
|
+
return blocks.map(block => { return new X509Certificate(block); });
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function trusted(certificates, roots, now) {
|
|
23
|
+
if (certificates.some(cert => { return now < Date.parse(cert.validFrom) || now >= Date.parse(cert.validTo); })) { invalid(); }
|
|
24
|
+
const linked = certificates.every((cert,index) => {
|
|
25
|
+
return index === certificates.length - 1 || certificates[index + 1].ca
|
|
26
|
+
&& cert.checkIssued(certificates[index + 1]) && cert.verify(certificates[index + 1].publicKey);
|
|
27
|
+
});
|
|
28
|
+
const last = certificates[certificates.length - 1];
|
|
29
|
+
if (!linked || !roots.some(pem => {
|
|
30
|
+
const root = new X509Certificate(pem);
|
|
31
|
+
return now >= Date.parse(root.validFrom) && now < Date.parse(root.validTo)
|
|
32
|
+
&& (last.raw.equals(root.raw) || last.checkIssued(root) && last.verify(root.publicKey));
|
|
33
|
+
})) { invalid(); }
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function validateTLSMaterial(payload, { hosts, roots = rootCertificates, now = Date.now(), format = defaultFormat }) {
|
|
37
|
+
try {
|
|
38
|
+
if (!payload || payload.format !== format || typeof payload.cert !== 'string'
|
|
39
|
+
|| typeof payload.key !== 'string' || payload.hash !== jsonDigest({cert:payload.cert,key:payload.key})
|
|
40
|
+
|| !Array.isArray(hosts) || !hosts.length || Buffer.byteLength(JSON.stringify(payload)) > tlsMaterialLimit) { invalid(); }
|
|
41
|
+
const certificates = chain(Buffer.from(payload.cert,'base64').toString('utf8'));
|
|
42
|
+
const [leaf] = certificates;
|
|
43
|
+
if (leaf.ca || hosts.some(host => { return !leaf.checkHost(host); })
|
|
44
|
+
|| leaf.keyUsage?.length && !leaf.keyUsage.includes('1.3.6.1.5.5.7.3.1') && !leaf.keyUsage.includes('2.5.29.37.0')) { invalid(); }
|
|
45
|
+
const publicKey = createPublicKey(createPrivateKey(Buffer.from(payload.key,'base64'))).export({type:'spki',format:'der'});
|
|
46
|
+
if (!leaf.publicKey.export({type:'spki',format:'der'}).equals(publicKey)) { invalid(); }
|
|
47
|
+
trusted(certificates,roots,now);
|
|
48
|
+
return {'tls.crt':payload.cert,'tls.key':payload.key};
|
|
49
|
+
} catch { invalid(); }
|
|
50
|
+
return undefined;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Read material per request so a rotating secret is served without restarting the origin. */
|
|
54
|
+
export function readTLSMaterial({ cert, key } = {}, options = {}) {
|
|
55
|
+
if (cert && key) { return sealTLSMaterial(readFileSync(cert), readFileSync(key), options); }
|
|
56
|
+
return undefined;
|
|
57
|
+
}
|
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
package scada.processing.infra.state
|
|
2
2
|
|
|
3
3
|
import cats.effect.IO
|
|
4
|
+
import cats.syntax.all.*
|
|
5
|
+
import io.circe.{Decoder, Encoder}
|
|
6
|
+
import io.circe.parser.decode
|
|
7
|
+
import io.circe.syntax.*
|
|
4
8
|
import java.nio.ByteBuffer
|
|
5
9
|
import java.nio.channels.FileChannel
|
|
6
10
|
import java.nio.file.{Files, Path, StandardCopyOption, StandardOpenOption}
|
|
@@ -10,6 +14,9 @@ import java.nio.charset.StandardCharsets.UTF_8
|
|
|
10
14
|
final class AtomicStateFile(path: Path):
|
|
11
15
|
def read: IO[Option[String]] = IO.blocking:
|
|
12
16
|
if Files.exists(path) then Some(Files.readString(path)) else None
|
|
17
|
+
def readJson[A: Decoder]: IO[Option[A]] = read.flatMap(_.traverse(json => IO.fromEither(decode[A](json))))
|
|
18
|
+
def writeJson[A: Encoder](value: A): IO[Unit] = write(value.asJson.noSpaces)
|
|
19
|
+
|
|
13
20
|
def write(json: String): IO[Unit] = IO.blocking:
|
|
14
21
|
Files.createDirectories(path.getParent)
|
|
15
22
|
val temporary = path.resolveSibling(path.getFileName.toString + ".tmp")
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
package scada.processing.infra.state
|
|
2
|
+
|
|
3
|
+
import cats.effect.{IO, Resource}
|
|
4
|
+
import cats.syntax.all.*
|
|
5
|
+
import io.circe.{Decoder, Encoder}
|
|
6
|
+
import java.nio.channels.FileChannel
|
|
7
|
+
import java.nio.file.{Files, Path, StandardOpenOption}
|
|
8
|
+
|
|
9
|
+
/** Owns a process lock while reading or saving an atomically replaced JSON checkpoint. */
|
|
10
|
+
final class StateJournal[A: Encoder: Decoder] private (file: AtomicStateFile, initial: A):
|
|
11
|
+
def load: IO[A] = file.readJson[A].map(_.getOrElse(initial))
|
|
12
|
+
def save(checkpoint: A): IO[Unit] = file.writeJson(checkpoint)
|
|
13
|
+
|
|
14
|
+
object StateJournal:
|
|
15
|
+
def open[A: Encoder: Decoder](file: String, initial: A): Resource[IO, StateJournal[A]] =
|
|
16
|
+
val path = Path.of(file).toAbsolutePath
|
|
17
|
+
val lockPath = path.resolveSibling(path.getFileName.toString + ".lock")
|
|
18
|
+
Resource.eval(IO.blocking(Files.createDirectories(path.getParent))) *>
|
|
19
|
+
Resource.fromAutoCloseable(IO.blocking(FileChannel.open(lockPath, StandardOpenOption.CREATE, StandardOpenOption.WRITE))).flatMap: channel =>
|
|
20
|
+
Resource.make(IO.blocking(Option(channel.tryLock()).getOrElse(throw IllegalStateException(s"Checkpoint already owned: $file"))))(
|
|
21
|
+
lock => IO.blocking(lock.release())
|
|
22
|
+
).as(new StateJournal(AtomicStateFile(path), initial))
|
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
package scada.processing.runtime
|
|
2
2
|
|
|
3
3
|
import cats.effect.IO
|
|
4
|
-
import io.circe.Json
|
|
4
|
+
import io.circe.{Json, Printer}
|
|
5
5
|
import io.circe.parser.parse
|
|
6
6
|
import java.net.URI
|
|
7
7
|
import java.net.http.{HttpClient,HttpRequest,HttpResponse}
|
|
8
8
|
import java.time.Duration
|
|
9
|
+
import java.nio.charset.StandardCharsets.UTF_8
|
|
10
|
+
import java.security.MessageDigest
|
|
11
|
+
import java.util.HexFormat
|
|
9
12
|
import scada.processing.infra.config.{AppConfig, CheckpointApiConfig}
|
|
10
13
|
import scala.concurrent.duration.*
|
|
11
14
|
|
|
@@ -54,3 +57,9 @@ final class HistoryClient(config: CheckpointApiConfig):
|
|
|
54
57
|
attempt(2)
|
|
55
58
|
|
|
56
59
|
def retry[A](action: IO[A]): IO[A] = action.handleErrorWith(_=>IO.sleep(2.seconds) *> retry(action))
|
|
60
|
+
|
|
61
|
+
object HistoryClient:
|
|
62
|
+
/** Stable fingerprint for classifier configuration and claimed work. */
|
|
63
|
+
def fingerprint(value: Json): String =
|
|
64
|
+
val bytes = Printer.noSpaces.copy(sortKeys = true).print(value).getBytes(UTF_8)
|
|
65
|
+
HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes))
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
package scada.processing.runtime
|
|
2
|
+
|
|
3
|
+
import cats.effect.IO
|
|
4
|
+
import cats.effect.std.Semaphore
|
|
5
|
+
import fs2.Stream
|
|
6
|
+
import fs2.concurrent.SignallingRef
|
|
7
|
+
import io.yarkivaev.streamworker.{Delivery, Output, OutputScope, Processor, ProcessorVersion, StreamWorker}
|
|
8
|
+
import scala.concurrent.duration.*
|
|
9
|
+
|
|
10
|
+
object LiveWorker:
|
|
11
|
+
final case class Replay[S, E](active: S => Boolean, complete: S => IO[E])
|
|
12
|
+
final case class Watchdog[S, E](deadline: S => Option[Long], changed: (S, S) => Boolean, expired: Long => E)
|
|
13
|
+
|
|
14
|
+
/** Serializes input, replay handoff, timeouts, and side effects under one worker's ownership. */
|
|
15
|
+
final class LiveWorker[C, S, E, O](
|
|
16
|
+
processor: Processor[C, S, E, O],
|
|
17
|
+
config: C,
|
|
18
|
+
version: ProcessorVersion,
|
|
19
|
+
binding: WorkerStores.Binding[S, O],
|
|
20
|
+
publish: O => IO[Unit],
|
|
21
|
+
outputs: Option[OutputScope] = None
|
|
22
|
+
):
|
|
23
|
+
import LiveWorker.*
|
|
24
|
+
private val WorkerStores.Binding(store, task, ownership) = binding
|
|
25
|
+
private val current = store.load(task, ownership)
|
|
26
|
+
private val worker = StreamWorker(processor, store, (_: Long, output: Output[O]) =>
|
|
27
|
+
val write = publish(output.value)
|
|
28
|
+
outputs.fold(write)(_.within(output.id)(write)))
|
|
29
|
+
|
|
30
|
+
private def submit(event: E) = worker.run(task, version, config, ownership): cursor =>
|
|
31
|
+
// Allocate the receipt position from the worker checkpoint. Broker receipt IDs may be connection-local.
|
|
32
|
+
Stream.eval(IO(Math.addExact(cursor.getOrElse(0L), 1L))).map(position => Delivery(position, event, IO.unit))
|
|
33
|
+
|
|
34
|
+
def run(
|
|
35
|
+
readings: IO[Unit] => Stream[IO, (E, IO[Unit])],
|
|
36
|
+
sideEffects: Stream[IO, IO[Unit]],
|
|
37
|
+
replay: Replay[S, E],
|
|
38
|
+
watchdog: Watchdog[S, E],
|
|
39
|
+
scheduleOnStart: Boolean
|
|
40
|
+
): IO[Unit] =
|
|
41
|
+
for
|
|
42
|
+
lock <- Semaphore[IO](1)
|
|
43
|
+
deadline <- SignallingRef[IO, Option[Long]](None)
|
|
44
|
+
_ <- worker.run(task, version, config, ownership)(_ => Stream.empty)
|
|
45
|
+
arm = (state: S) => deadline.set(watchdog.deadline(state))
|
|
46
|
+
accept = (event: E, ack: IO[Unit]) =>
|
|
47
|
+
lock.permit.use { _ =>
|
|
48
|
+
for
|
|
49
|
+
before <- current
|
|
50
|
+
next <- submit(event)
|
|
51
|
+
_ <- IO.whenA(!replay.active(next.state) && watchdog.changed(before.state, next.state))(arm(next.state))
|
|
52
|
+
yield replay.active(before.state)
|
|
53
|
+
}.flatMap: replaying =>
|
|
54
|
+
// Archive records have no broker receipt. Live ACKs follow the completed worker step.
|
|
55
|
+
IO.unlessA(replaying)(ack)
|
|
56
|
+
ready = lock.permit.use: _ =>
|
|
57
|
+
current.flatMap: saved =>
|
|
58
|
+
if replay.active(saved.state) then
|
|
59
|
+
replay.complete(saved.state).flatMap(submit).flatMap(next => arm(next.state))
|
|
60
|
+
else IO.unit
|
|
61
|
+
timers = deadline.discrete.changes.switchMap:
|
|
62
|
+
case None => Stream.empty
|
|
63
|
+
case Some(until) =>
|
|
64
|
+
Stream.eval(IO.realTime.flatMap(now => IO.sleep(math.max(0L, until - now.toMillis).millis))).as(until)
|
|
65
|
+
_ <- IO.whenA(scheduleOnStart)(current.flatMap(saved => arm(saved.state)))
|
|
66
|
+
input = readings(ready).evalMap { case (event, ack) => accept(event, ack) }
|
|
67
|
+
live = (input ++ Stream.exec(ready)).concurrently(sideEffects.evalMap(action => lock.permit.use(_ => action)))
|
|
68
|
+
.concurrently(timers.evalMap(at => lock.permit.use(_ => submit(watchdog.expired(at))).void))
|
|
69
|
+
_ <- live.compile.drain
|
|
70
|
+
yield ()
|
|
@@ -4,15 +4,13 @@ import io.yarkivaev.segmentation.{HistoryRange, HistorySeed, HistorySegment, His
|
|
|
4
4
|
import cats.effect.{IO, Ref}
|
|
5
5
|
import cats.syntax.all.*
|
|
6
6
|
import fs2.Stream
|
|
7
|
-
import io.circe.
|
|
7
|
+
import io.circe.Json
|
|
8
8
|
import io.circe.parser.parse
|
|
9
9
|
import io.circe.syntax.*
|
|
10
10
|
import io.yarkivaev.temporal.{LocalStreams, Observation, Processing, Work, Worker}
|
|
11
11
|
import java.net.URLEncoder
|
|
12
12
|
import java.nio.charset.StandardCharsets
|
|
13
|
-
import java.security.MessageDigest
|
|
14
13
|
import java.time.Instant
|
|
15
|
-
import java.util.HexFormat
|
|
16
14
|
import io.yarkivaev.streamworker.{ProcessingError, Processor, StepResult}
|
|
17
15
|
import scada.processing.core.*
|
|
18
16
|
import io.yarkivaev.segmentation.ObservedSegmentation.{Sample, State, segment}
|
|
@@ -58,12 +56,8 @@ object LocalHistory:
|
|
|
58
56
|
val state = samples.lastOption.map(last => HistoryState(last.time, result.state.parameters, tail))
|
|
59
57
|
Calculated(result.outputs ++ tail, state)
|
|
60
58
|
|
|
61
|
-
private def digest(value: Json): String =
|
|
62
|
-
val text = Printer.noSpaces.copy(sortKeys = true).print(value)
|
|
63
|
-
HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(text.getBytes(StandardCharsets.UTF_8)))
|
|
64
|
-
|
|
65
59
|
private[runtime] def commitFence(machine: MachineId, workId: String, token: String, generation: Option[Long]): Json =
|
|
66
|
-
val outputId =
|
|
60
|
+
val outputId = HistoryClient.fingerprint(Json.arr(machine.raw.asJson, workId.asJson, token.asJson))
|
|
67
61
|
val fields = ("outputId" -> outputId.asJson) :: generation.toList.map(current => "generation" -> current.asJson)
|
|
68
62
|
Json.obj("fence" -> Json.obj(fields*))
|
|
69
63
|
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
package scada.processing.runtime
|
|
2
|
+
|
|
3
|
+
import cats.effect.IO
|
|
4
|
+
import cats.syntax.all.*
|
|
5
|
+
import fs2.Stream
|
|
6
|
+
import io.circe.{Decoder, Encoder, Json}
|
|
7
|
+
import io.circe.syntax.*
|
|
8
|
+
import io.yarkivaev.temporal.Observation
|
|
9
|
+
import java.net.URLEncoder
|
|
10
|
+
import java.nio.charset.StandardCharsets.UTF_8
|
|
11
|
+
import java.util.concurrent.atomic.AtomicInteger
|
|
12
|
+
import scada.processing.core.MachineId
|
|
13
|
+
import scada.processing.infra.config.AliasMapping
|
|
14
|
+
import scala.concurrent.duration.*
|
|
15
|
+
|
|
16
|
+
object StatefulHistory:
|
|
17
|
+
final case class Page[S](state: S, rows: Vector[Json], at: Option[Long])
|
|
18
|
+
|
|
19
|
+
private final case class Claim(id: String, token: String, from: Long, until: Long, cursor: Option[Long], end: Option[Long])
|
|
20
|
+
derives Decoder
|
|
21
|
+
|
|
22
|
+
/** Executes bounded, stateful classifier pages with the receiver's work claim and revision. */
|
|
23
|
+
final class StatefulHistory[S: Encoder](
|
|
24
|
+
api: HistoryClient,
|
|
25
|
+
machine: MachineId,
|
|
26
|
+
paddingMs: Long,
|
|
27
|
+
classifierKey: String,
|
|
28
|
+
initial: S,
|
|
29
|
+
decodeState: Json => IO[S],
|
|
30
|
+
replay: (Vector[Observation], S, Int) => IO[StatefulHistory.Page[S]],
|
|
31
|
+
replication: Option[HistoryReplication] = None,
|
|
32
|
+
generation: Option[Long] = None
|
|
33
|
+
):
|
|
34
|
+
import StatefulHistory.*
|
|
35
|
+
private val scale = AtomicInteger(0)
|
|
36
|
+
private val supportedScales = Set(1, 1000)
|
|
37
|
+
private def encode(value: String): String = URLEncoder.encode(value, UTF_8)
|
|
38
|
+
private val encoded = encode(machine.raw)
|
|
39
|
+
|
|
40
|
+
def configure(aliases: List[AliasMapping]): IO[Unit] =
|
|
41
|
+
val topics = aliases.map(alias => Json.obj("topic" -> alias.topic.asJson, "channel" -> alias.metric.asJson))
|
|
42
|
+
val body = Json.obj("machine" -> machine.raw.asJson, "topics" -> Json.arr(topics*), "classifierKey" -> classifierKey.asJson)
|
|
43
|
+
api.retry(api.request("POST", "/v1/history/config", body)).flatMap: response =>
|
|
44
|
+
val protocol = response.hcursor.get[String]("classifierProtocol").toOption
|
|
45
|
+
val unit = response.hcursor.get[Int]("timeScale").toOption
|
|
46
|
+
IO.fromOption(unit.filter(supportedScales).filter(_ => protocol.contains("stateful-correction-v1")))(
|
|
47
|
+
IllegalStateException("Stateful history protocol required")).flatMap(value => IO(scale.set(value)))
|
|
48
|
+
|
|
49
|
+
def process: Stream[IO, Unit] =
|
|
50
|
+
Stream.repeatEval(api.retry(api.request("GET", s"/v1/history/work?machine=$encoded"))).flatMap: response =>
|
|
51
|
+
Stream.eval(IO.fromEither(response.hcursor.get[Vector[Json]]("items"))).flatMap: work =>
|
|
52
|
+
val jobs = work.headOption.fold(Stream.emit(()).covary[IO]): next =>
|
|
53
|
+
val run = IO.fromEither(next.as[Claim]).flatMap(execute)
|
|
54
|
+
Stream.eval(run.attempt.flatTap(_.left.toOption.traverse_(error =>
|
|
55
|
+
IO.println(s"History classifier work deferred: ${Option(error.getMessage).getOrElse(error.toString)}")))).collect { case Right(_) => () }
|
|
56
|
+
jobs ++ Stream.sleep_[IO](1.second)
|
|
57
|
+
|
|
58
|
+
private def observations(context: Json, claim: Claim, unit: Int): IO[Vector[Observation]] =
|
|
59
|
+
val metadata = context.hcursor.downField("context")
|
|
60
|
+
val valid = metadata.get[String]("classifierKey").toOption.contains(classifierKey) &&
|
|
61
|
+
metadata.get[String]("workId").toOption.contains(claim.id) &&
|
|
62
|
+
metadata.get[String]("workToken").toOption.contains(claim.token) &&
|
|
63
|
+
metadata.get[Int]("timeScale").toOption.getOrElse(1) == unit
|
|
64
|
+
IO.raiseUnless(valid)(IllegalStateException("Mismatched classifier history context")) *>
|
|
65
|
+
IO.fromEither(context.hcursor.get[Vector[Json]]("items").flatMap(_.traverse: item =>
|
|
66
|
+
val point = item.hcursor
|
|
67
|
+
for
|
|
68
|
+
event <- point.get[String]("eventId")
|
|
69
|
+
channel <- point.get[String]("channel")
|
|
70
|
+
time <- point.get[Long]("time")
|
|
71
|
+
value <- point.get[Double]("value")
|
|
72
|
+
yield Observation(event, channel, time, value)
|
|
73
|
+
)).flatMap: values =>
|
|
74
|
+
IO.raiseWhen(values.size > 10000)(IllegalStateException("Unbounded classifier history context")).as(values)
|
|
75
|
+
|
|
76
|
+
private def seed(context: Json, continuation: Boolean): IO[S] =
|
|
77
|
+
context.hcursor.downField("classifierSeed").focus.filterNot(_.isNull) match
|
|
78
|
+
case None if continuation => IO.raiseError(IllegalStateException("Durable classifier continuation state required"))
|
|
79
|
+
case None => IO.pure(initial)
|
|
80
|
+
case Some(value) => decodeState(value.hcursor.downField("state").focus.getOrElse(Json.Null))
|
|
81
|
+
|
|
82
|
+
private def path(claim: Claim, unit: Int): String =
|
|
83
|
+
s"/v1/history/context?machine=$encoded&from=${claim.from}&until=${claim.until}&paddingMs=${paddingMs * unit}" +
|
|
84
|
+
s"&classifierKey=${encode(classifierKey)}&workId=${encode(claim.id)}&workToken=${encode(claim.token)}" +
|
|
85
|
+
claim.cursor.fold("")(value => s"&cursor=$value") + claim.end.fold("")(value => s"&end=$value")
|
|
86
|
+
|
|
87
|
+
private def execute(claim: Claim): IO[Unit] =
|
|
88
|
+
val unit = scale.get()
|
|
89
|
+
api.request("GET", path(claim, unit)).flatMap: context =>
|
|
90
|
+
// Only the receiver retires work, as part of the commit. Missing context leaves the claim available.
|
|
91
|
+
IO.whenA(context.hcursor.get[Boolean]("available").contains(true)):
|
|
92
|
+
for
|
|
93
|
+
points <- observations(context, claim, unit)
|
|
94
|
+
revision <- LocalHistory.contextRevision(context)
|
|
95
|
+
start <- seed(context, claim.cursor.isDefined)
|
|
96
|
+
page <- replay(points, start, unit)
|
|
97
|
+
_ <- commit(context, claim, page, revision)
|
|
98
|
+
yield ()
|
|
99
|
+
|
|
100
|
+
private def commit(context: Json, claim: Claim, page: Page[S], revision: String): IO[Unit] =
|
|
101
|
+
val checkpoint = page.at.fold(Json.obj()): at =>
|
|
102
|
+
Json.obj("checkpoint" -> Json.obj("key" -> classifierKey.asJson, "at" -> at.asJson, "state" -> page.state.asJson))
|
|
103
|
+
val metadata = context.hcursor.downField("context").focus.getOrElse(Json.obj()).deepMerge(Json.obj(
|
|
104
|
+
"revision" -> revision.asJson, "workToken" -> claim.token.asJson, "replace" -> Json.True
|
|
105
|
+
)).deepMerge(checkpoint).deepMerge(LocalHistory.commitFence(machine, claim.id, claim.token, generation))
|
|
106
|
+
val payload = Json.obj("machine" -> machine.raw.asJson, "workId" -> claim.id.asJson,
|
|
107
|
+
"segments" -> Json.arr(page.rows*), "context" -> metadata)
|
|
108
|
+
api.commitHistory(payload, replication).void
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
package scada.processing.runtime
|
|
2
|
+
|
|
3
|
+
import cats.effect.IO
|
|
4
|
+
import cats.syntax.all.*
|
|
5
|
+
import io.yarkivaev.segmentation.{TaggedSegment, Timestamp}
|
|
6
|
+
import scada.processing.core.{MachineId, Segments}
|
|
7
|
+
import scada.processing.infra.checkpoint.Checkpoint
|
|
8
|
+
|
|
9
|
+
/** Publishes each completed transition with its pending successor in one revision scope. */
|
|
10
|
+
object TimelinePublication:
|
|
11
|
+
def publish(
|
|
12
|
+
segments: Segments[IO], machine: MachineId, rows: List[TaggedSegment], compactLimit: Option[Int]
|
|
13
|
+
): IO[Unit] =
|
|
14
|
+
segments.atRevision(machine):
|
|
15
|
+
batches(rows, compactLimit).traverse_ { group =>
|
|
16
|
+
group.traverse_(row => segments.find(machine, row.segment.start)) *>
|
|
17
|
+
segments.upsertTransition(machine, group)
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
private def batches(rows: List[TaggedSegment], compactLimit: Option[Int]): List[List[TaggedSegment]] =
|
|
21
|
+
val pending = rows.lastOption.filter(_.segment.duration == 0)
|
|
22
|
+
val closed = (row: TaggedSegment) => row.segment.duration > 0
|
|
23
|
+
val compacted = compactLimit.filter(_ => pending.nonEmpty).fold(List.empty[TaggedSegment])(_ => rows.filter(closed) ++ pending)
|
|
24
|
+
if compacted.nonEmpty && compactLimit.exists(compacted.size <= _) &&
|
|
25
|
+
compacted.zip(compacted.drop(1)).forall((left, right) => left.segment.end == right.segment.start) then
|
|
26
|
+
List(compacted)
|
|
27
|
+
else
|
|
28
|
+
Iterator.unfold(rows): remaining =>
|
|
29
|
+
val (complete, rest) = remaining.span(closed)
|
|
30
|
+
rest match
|
|
31
|
+
case tail :: next => Some((complete :+ tail, next))
|
|
32
|
+
case Nil if complete.nonEmpty => Some((complete, Nil))
|
|
33
|
+
case Nil => None
|
|
34
|
+
.toList
|
|
35
|
+
|
|
36
|
+
/** The authoritative segments take precedence over the older replay cursor. */
|
|
37
|
+
def closedThrough(segments: Segments[IO], machine: MachineId, checkpoint: Option[Checkpoint]): IO[Long] =
|
|
38
|
+
segments.list(machine).flatMap: rows =>
|
|
39
|
+
rows.iterator.filter(_.segment.duration > 0).map(row => millis(row.segment.end)).maxOption match
|
|
40
|
+
case Some(end) => IO.pure(end)
|
|
41
|
+
case None => checkpoint.fold(IO.pure(0L))(_.fetchReplayCursor(machine).map(cursor => math.max(0L, millis(cursor))))
|
|
42
|
+
|
|
43
|
+
private def millis(time: Timestamp): Long = math.round(time.epoch * 1000)
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
package scada.processing.runtime
|
|
2
|
+
|
|
3
|
+
import cats.effect.{IO, Ref}
|
|
4
|
+
import cats.effect.std.Semaphore
|
|
5
|
+
import io.circe.{Decoder, Encoder}
|
|
6
|
+
import io.yarkivaev.streamworker.{Checkpoint, CheckpointStore, StaleOwnership, TaskIdentity}
|
|
7
|
+
import io.yarkivaev.streamworker.postgres.PgCheckpointStore
|
|
8
|
+
|
|
9
|
+
object WorkerStores:
|
|
10
|
+
final case class Binding[S, O](store: CheckpointStore[S, O], task: TaskIdentity, ownership: Long)
|
|
11
|
+
|
|
12
|
+
/** Claim the database checkpoint before draining pending outputs. Reconcile run mode without changing the outbox. */
|
|
13
|
+
def database[S: Encoder: Decoder, O: Encoder: Decoder](
|
|
14
|
+
db: WorkerDatabase,
|
|
15
|
+
initial: Checkpoint[S, O]
|
|
16
|
+
)(reconcile: S => Option[S]): IO[Binding[S, O]] =
|
|
17
|
+
val store = PgCheckpointStore[S, O](db.transactor)
|
|
18
|
+
val owner = db.generation
|
|
19
|
+
for
|
|
20
|
+
_ <- store.claim(owner, initial)
|
|
21
|
+
saved <- store.loadCompatible(initial.task, initial.version, owner)
|
|
22
|
+
_ <- reconcile(saved.state).fold(IO.unit): next =>
|
|
23
|
+
store.commit(owner, saved.revision, saved.copy(revision = saved.revision + 1L, state = next))
|
|
24
|
+
yield Binding(store, initial.task, owner)
|
|
25
|
+
|
|
26
|
+
/** Update the application journal before advancing the in-memory cursor. Caller owns the file lock. */
|
|
27
|
+
def local[S, O](initial: Checkpoint[S, O])(persist: Checkpoint[S, O] => IO[Unit]): IO[Binding[S, O]] =
|
|
28
|
+
val owner = 0L
|
|
29
|
+
for
|
|
30
|
+
state <- Ref.of[IO, Checkpoint[S, O]](initial)
|
|
31
|
+
lock <- Semaphore[IO](1)
|
|
32
|
+
yield
|
|
33
|
+
val store = new CheckpointStore[S, O]:
|
|
34
|
+
def load(task: TaskIdentity, ownership: Long): IO[Checkpoint[S, O]] =
|
|
35
|
+
IO.raiseUnless(task == initial.task && ownership == owner)(StaleOwnership(task, ownership)) *> state.get
|
|
36
|
+
|
|
37
|
+
def commit(ownership: Long, expectedRevision: Long, next: Checkpoint[S, O]): IO[Unit] =
|
|
38
|
+
lock.permit.use: _ =>
|
|
39
|
+
IO.uncancelable: _ =>
|
|
40
|
+
load(next.task, ownership).flatMap: current =>
|
|
41
|
+
IO.raiseUnless(current.revision == expectedRevision)(IllegalStateException("Worker checkpoint revision changed")) *>
|
|
42
|
+
persist(next) *> state.set(next)
|
|
43
|
+
Binding(store, initial.task, owner)
|
|
@@ -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
|
-
]
|