@yarkivaev/scada 2.22.0 → 2.23.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/package.json +3 -1
- package/src/application/runtime/applicationRuntime.js +5 -2
- package/src/application/runtime/index.js +2 -0
- package/src/application/runtime/runCommand.js +10 -0
- package/src/application/runtime/runService.js +14 -0
- package/src/application/siteRuntime/centralConnections.js +13 -0
- package/src/application/siteRuntime/index.js +1 -0
- package/src/infrastructure/deploy/index.js +1 -0
- package/src/infrastructure/deploy/installVerifiedTools.js +44 -0
- package/src/infrastructure/deploy/stagedSitePlan.js +3 -1
- package/src/infrastructure/deploy/useApplicationBundle.sh +22 -0
- package/src/infrastructure/opcua/index.js +2 -0
- package/src/infrastructure/opcua/opcuaRecord.js +44 -0
- package/src/infrastructure/opcua/publishOpcuaRecord.js +23 -0
- package/src/testing/boundedQueue.js +50 -0
- package/stream-processing/src/main/resources/logback.xml +16 -0
- package/stream-processing/src/main/scala/scada/processing/runtime/DurableMachineInput.scala +6 -0
- package/stream-processing/src/main/scala/scada/processing/runtime/WorkerStores.scala +31 -2
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@yarkivaev/scada",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.23.0",
|
|
4
4
|
"description": "SCADA domain objects, state persistence, and plant monitoring",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -19,6 +19,7 @@
|
|
|
19
19
|
"./opcua": "./src/infrastructure/opcua/index.js",
|
|
20
20
|
"./opcua/config": "./src/infrastructure/opcua/config.js",
|
|
21
21
|
"./runtime": "./src/application/runtime/index.js",
|
|
22
|
+
"./testing/bounded-queue": "./src/testing/boundedQueue.js",
|
|
22
23
|
"./streams": "./src/infrastructure/streams/index.js",
|
|
23
24
|
"./control": "./src/application/control/index.js",
|
|
24
25
|
"./mdmesh": "./src/infrastructure/mdmesh/index.js",
|
|
@@ -73,6 +74,7 @@
|
|
|
73
74
|
"charts/",
|
|
74
75
|
"db/",
|
|
75
76
|
"stream-processing/src/main/scala/",
|
|
77
|
+
"stream-processing/src/main/resources/",
|
|
76
78
|
"stream-processing/vendor/",
|
|
77
79
|
"stream-processing/dependencies/stream-worker.jar",
|
|
78
80
|
"stream-processing/stream-worker.lock",
|
|
@@ -7,11 +7,13 @@ const identifier = z.string().regex(/^[a-z0-9][a-z0-9-]*$/u);
|
|
|
7
7
|
const qualified = /^[a-z0-9][a-z0-9-]*\/[a-z0-9][a-z0-9-]*$/u;
|
|
8
8
|
const workload = z.strictObject({
|
|
9
9
|
driver: z.string().regex(qualified),
|
|
10
|
+
profile: identifier.optional(),
|
|
10
11
|
config: z.record(z.string(), z.unknown()).default({}),
|
|
11
12
|
args: z.array(z.string()).default([])
|
|
12
13
|
});
|
|
13
14
|
const runtimeDocument = z.strictObject({
|
|
14
15
|
modules: z.array(z.strictObject({ id: identifier, entry: z.string().min(1) })).default([]),
|
|
16
|
+
configProfiles: z.record(identifier, z.record(z.string(), z.unknown())).default({}),
|
|
15
17
|
services: z.record(identifier, workload).default({}),
|
|
16
18
|
jobs: z.record(identifier, workload).default({})
|
|
17
19
|
});
|
|
@@ -71,13 +73,14 @@ export default async function applicationRuntime(file, { kind, name, args = [] }
|
|
|
71
73
|
core, env = process.env, write = (body) => { process.stdout.write(body); }
|
|
72
74
|
}) {
|
|
73
75
|
if (!['service', 'job'].includes(kind)) { throw new TypeError('expected service or job'); }
|
|
74
|
-
const { modules, services, jobs } = runtimeDocument.parse(readDocumentFile(file));
|
|
76
|
+
const { modules, configProfiles, services, jobs } = runtimeDocument.parse(readDocumentFile(file));
|
|
75
77
|
const declarations = kind === 'service' ? services : jobs;
|
|
76
78
|
if (!Object.hasOwn(declarations, name)) { throw new Error(`unknown ${kind} ${name}`); }
|
|
77
79
|
const selected = declarations[name];
|
|
80
|
+
if (selected.profile && !Object.hasOwn(configProfiles, selected.profile)) { throw new Error(`unknown configuration profile ${selected.profile}`); }
|
|
78
81
|
const load = moduleResolver(file, moduleEntries(modules), core);
|
|
79
82
|
const driver = await resolveExport(selected.driver, `${kind}s`, load);
|
|
80
83
|
if (typeof driver !== 'function') { throw new TypeError(`driver ${selected.driver} must be a function`); }
|
|
81
|
-
const config = await configuration(selected.config, load);
|
|
84
|
+
const config = await configuration({ ...(selected.profile && configProfiles[selected.profile]), ...selected.config }, load);
|
|
82
85
|
return driver({ config, args: [...selected.args, ...args], env, write, file });
|
|
83
86
|
}
|
|
@@ -16,3 +16,5 @@ export { default as embeddedCollectors } from './embeddedCollectors.js';
|
|
|
16
16
|
export { collectorLaunch, launchCollectorCommand } from './collectorLaunch.js';
|
|
17
17
|
export { default as pagedDelivery } from './pagedDelivery.js';
|
|
18
18
|
export { default as runApplication } from './runApplication.js';
|
|
19
|
+
export { default as runCommand } from './runCommand.js';
|
|
20
|
+
export { default as runService } from './runService.js';
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** Write a command result and preserve the exit status of a failed subprocess. */
|
|
2
|
+
export default async function runCommand(command) {
|
|
3
|
+
try {
|
|
4
|
+
const output = await command();
|
|
5
|
+
if (output) { process.stdout.write(output); }
|
|
6
|
+
} catch (error) {
|
|
7
|
+
process.stderr.write(`${error.message}\n`);
|
|
8
|
+
process.exitCode = error.status || 1;
|
|
9
|
+
}
|
|
10
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
function exitOnFailure(message, reason) {
|
|
2
|
+
console.error(message, reason); // eslint-disable-line no-console
|
|
3
|
+
process.exit(1);
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
/** Keep process failures fatal after an asynchronous service has started. */
|
|
7
|
+
export default async function runService(name, start) {
|
|
8
|
+
process.on('unhandledRejection', (reason) => { exitOnFailure('Unhandled rejection:', reason); });
|
|
9
|
+
try {
|
|
10
|
+
await start();
|
|
11
|
+
} catch (error) {
|
|
12
|
+
exitOnFailure(`Failed to start ${name}:`, error);
|
|
13
|
+
}
|
|
14
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import clickhouseConnection from '../../infrastructure/persistence/clickhouse/connection.js';
|
|
2
|
+
import { openPostgresPool } from '../../infrastructure/persistence/postgresPool.js';
|
|
3
|
+
|
|
4
|
+
/** Prepare an application schema and open the shared central-site connections. */
|
|
5
|
+
export default async function centralConnections(env, { prepare, postgresPurpose, openClickHouse = clickhouseConnection,
|
|
6
|
+
openPostgres = openPostgresPool }) {
|
|
7
|
+
const clickhouse = env.CLICKHOUSE_HOST || 'localhost';
|
|
8
|
+
const clickhouseOptions = { username: env.CLICKHOUSE_USER, password: env.CLICKHOUSE_PASSWORD };
|
|
9
|
+
await prepare?.(env, openPostgres);
|
|
10
|
+
const connection = await openClickHouse(clickhouse, clickhouseOptions);
|
|
11
|
+
if (!env.POSTGRES_URL) { throw new Error(`POSTGRES_URL is required for ${postgresPurpose}`); }
|
|
12
|
+
return { clickhouse, clickhouseOptions, connection, pool: openPostgres(env.POSTGRES_URL) };
|
|
13
|
+
}
|
|
@@ -15,3 +15,4 @@ export { default as reconcileOperationSnapshot } from './operationSnapshot.js';
|
|
|
15
15
|
export { default as operatorFieldStore, verifyPostgresRelation } from '../../infrastructure/persistence/pg/operatorFieldStore.js';
|
|
16
16
|
export { operatorFieldRoute } from '../../infrastructure/http/plant/routes/operatorRoute.js';
|
|
17
17
|
export { edgeTelemetryReaders, startEdgeMetrics, startInboundOperations } from './edgeIngress.js';
|
|
18
|
+
export { default as centralConnections } from './centralConnections.js';
|
|
@@ -84,3 +84,4 @@ export { default as configuredCollectorChartDeployment } from './configuredColle
|
|
|
84
84
|
export { default as configuredRuntimeArtifacts } from './configuredRuntimeArtifacts.js';
|
|
85
85
|
export { secretEnvironment } from './configuredSiteAssets.js';
|
|
86
86
|
export { default as configuredBundleCapabilities } from './configuredBundleCapabilities.js';
|
|
87
|
+
export { default as installVerifiedTools } from './installVerifiedTools.js';
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { chmodSync, copyFileSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import { tmpdir } from 'node:os';
|
|
5
|
+
import { basename, join } from 'node:path';
|
|
6
|
+
|
|
7
|
+
async function fetchTool(name, spec, request, fetch) {
|
|
8
|
+
const { url, headers } = request(name, spec);
|
|
9
|
+
const response = await fetch(url, { headers, signal: AbortSignal.timeout(60000) });
|
|
10
|
+
if (!response.ok) { throw new Error(`${name} mirror returned HTTP ${response.status}`); }
|
|
11
|
+
const bytes = Buffer.from(await response.arrayBuffer());
|
|
12
|
+
if (createHash('sha256').update(bytes).digest('hex') !== spec.sha256) {
|
|
13
|
+
throw new Error(`${name} mirror checksum mismatch`);
|
|
14
|
+
}
|
|
15
|
+
return bytes;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function install(name, spec, bytes, { directory, scratch, execute }) {
|
|
19
|
+
const destination = join(directory, basename(name));
|
|
20
|
+
if (spec.archiveEntry) {
|
|
21
|
+
const archive = join(scratch, 'tool.tar.gz');
|
|
22
|
+
writeFileSync(archive, bytes);
|
|
23
|
+
execute('tar', ['-xzf', archive, '-C', scratch, '--', spec.archiveEntry]);
|
|
24
|
+
copyFileSync(join(scratch, spec.archiveEntry), destination);
|
|
25
|
+
} else {
|
|
26
|
+
writeFileSync(destination, bytes);
|
|
27
|
+
}
|
|
28
|
+
chmodSync(destination, 0o755);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Install checksum-pinned CI binaries, accepting release pins and mirror credentials from the application. */
|
|
32
|
+
export default async function installVerifiedTools(tools, { directory, request, fetch = globalThis.fetch, execute = execFileSync }) {
|
|
33
|
+
const scratch = mkdtempSync(join(tmpdir(), 'scada-deploy-tools-'));
|
|
34
|
+
try {
|
|
35
|
+
mkdirSync(directory, { recursive: true });
|
|
36
|
+
for (const [name, spec] of Object.entries(tools)) {
|
|
37
|
+
// eslint-disable-next-line no-await-in-loop -- the tools use one temporary extraction directory
|
|
38
|
+
const bytes = await fetchTool(name, spec, request, fetch);
|
|
39
|
+
install(name, spec, bytes, { directory, scratch, execute });
|
|
40
|
+
}
|
|
41
|
+
} finally {
|
|
42
|
+
rmSync(scratch, { recursive: true, force: true });
|
|
43
|
+
}
|
|
44
|
+
}
|
|
@@ -3,6 +3,7 @@ import { brokerClientEnvironment } from './brokerSecurity.js';
|
|
|
3
3
|
import buildDeploymentStages from './buildDeploymentStages.js';
|
|
4
4
|
import { databaseSecurity } from './databaseSecurity.js';
|
|
5
5
|
import deploymentTemplate from './deploymentTemplate.js';
|
|
6
|
+
import { secretEnvironment as environmentFromSecret } from './configuredSiteAssets.js';
|
|
6
7
|
import { brokerPolicy } from './securityPolicy.js';
|
|
7
8
|
|
|
8
9
|
function nodeAddress(server, service) {
|
|
@@ -84,7 +85,8 @@ function supervisor(state, policy, ports) {
|
|
|
84
85
|
const machine = deploymentTemplate(policy.supervisor.machineId, { number: cluster.at(-1) });
|
|
85
86
|
const config = ports.supervisorConfig(cluster, Boolean(brokerEnvironment), [machine], policy.supervisor.checkpointUrl);
|
|
86
87
|
const environment = { ...(document.edgeControlPlane && { [policy.supervisor.groupVariable]: machine }),
|
|
87
|
-
...deploymentTemplate(policy.supervisorEnvironment, { app }),
|
|
88
|
+
...deploymentTemplate(policy.supervisorEnvironment ?? {}, { app }),
|
|
89
|
+
...environmentFromSecret(app.api.secret, policy.supervisorSecretKeys ?? {}), ...brokerEnvironment };
|
|
88
90
|
return { values: { ...profile.apps.supervisor, ...deploymentTemplate(policy.supervisorValues, { app, image, config, environment }) } };
|
|
89
91
|
}
|
|
90
92
|
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# Source from a protected release job to read its same-pipeline artifact.
|
|
2
|
+
scada_bundle_error() {
|
|
3
|
+
printf 'SCADA application bundle unavailable: %s\n' "$1" >&2
|
|
4
|
+
exit 1
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
if [ -n "${SCADA_APP_BUNDLE_TARGET:-}" ]; then
|
|
8
|
+
test "$CI_COMMIT_REF_PROTECTED" = true || scada_bundle_error "expected a protected release tag"
|
|
9
|
+
test -s scada-app.env || scada_bundle_error "missing release record"
|
|
10
|
+
release=$(sed -n 's/^SCADA_APP_BUNDLE_RELEASE_SHA=//p' scada-app.env)
|
|
11
|
+
digest=$(sed -n 's/^SCADA_APP_BUNDLE_SHA256=//p' scada-app.env)
|
|
12
|
+
url=$(sed -n 's/^SCADA_APP_BUNDLE_URL=//p' scada-app.env)
|
|
13
|
+
test "$release" = "$CI_COMMIT_SHA" || scada_bundle_error "release record does not match this commit"
|
|
14
|
+
case "$digest" in
|
|
15
|
+
*[!a-f0-9]*) scada_bundle_error "invalid digest" ;;
|
|
16
|
+
esac
|
|
17
|
+
test "${#digest}" -eq 64 || scada_bundle_error "invalid digest length"
|
|
18
|
+
origin="${SCADA_APP_BUNDLE_PACKAGE_ORIGIN:-https://${CI_GIT_HOST:-$CI_SERVER_HOST}}"
|
|
19
|
+
expected="${origin%/}/api/v4/projects/$CI_PROJECT_ID/packages/generic/scada-app/$release-$digest/scada-app.tar.gz"
|
|
20
|
+
test "$url" = "$expected" || scada_bundle_error "release URL does not match this project, commit and digest"
|
|
21
|
+
export SCADA_APP_BUNDLE_URL="$url" SCADA_APP_BUNDLE_SHA256="$digest"
|
|
22
|
+
fi
|
|
@@ -9,3 +9,5 @@ export default function opcuaConnections(connections, publish, options = {}) {
|
|
|
9
9
|
|
|
10
10
|
export { default as opcuaSource } from './source.js';
|
|
11
11
|
export { default as opcuaHealth } from './health.js';
|
|
12
|
+
export { default as opcuaRecord, opcuaNumber, opcuaRoutingKey } from './opcuaRecord.js';
|
|
13
|
+
export { default as publishOpcuaRecord, TELEMETRY } from './publishOpcuaRecord.js';
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Coerces OPC UA bool/number to a metrics numeric value.
|
|
3
|
+
*
|
|
4
|
+
* @param {*} value - raw node value
|
|
5
|
+
* @returns {number} 0, 1, or the original number
|
|
6
|
+
*/
|
|
7
|
+
export function opcuaNumber(value) {
|
|
8
|
+
if (value === true) {
|
|
9
|
+
return 1;
|
|
10
|
+
}
|
|
11
|
+
if (value === false) {
|
|
12
|
+
return 0;
|
|
13
|
+
}
|
|
14
|
+
if (typeof value === 'number' && Number.isFinite(value)) {
|
|
15
|
+
return value;
|
|
16
|
+
}
|
|
17
|
+
throw new Error(`opcua value is not numeric: ${String(value)}`);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Wire key emitted for a pinned OPC UA channel on the telemetry exchange. */
|
|
21
|
+
export function opcuaRoutingKey(device, key) {
|
|
22
|
+
return `OPCUA.${device}.GET.${key}.VALUE`;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Maps an OPC UA sample to an AMQP telemetry record.
|
|
27
|
+
*
|
|
28
|
+
* @example
|
|
29
|
+
* const row = opcuaRecord('cell-demo', 'sensor_ready', true);
|
|
30
|
+
* row.routingKey === 'OPCUA.cell-demo.GET.sensor_ready.VALUE';
|
|
31
|
+
*
|
|
32
|
+
* @param {string} device - MQTT/AMQP device id
|
|
33
|
+
* @param {string} key - sensor key
|
|
34
|
+
* @param {*} value - OPC UA value
|
|
35
|
+
* @param {number} [ts] - epoch millis
|
|
36
|
+
* @param {string} [route] - document path, when the chart names one
|
|
37
|
+
* @returns {{ routingKey: string, body: string }}
|
|
38
|
+
*/
|
|
39
|
+
export default function opcuaRecord(device, key, value, ts = Date.now(), route = '') {
|
|
40
|
+
return {
|
|
41
|
+
routingKey: route.length > 0 ? route : opcuaRoutingKey(device, key),
|
|
42
|
+
body: JSON.stringify({ ts, value: opcuaNumber(value) })
|
|
43
|
+
};
|
|
44
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
export const TELEMETRY = 'scada.telemetry';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Publishes one OPC UA metric record to scada.telemetry.
|
|
5
|
+
*
|
|
6
|
+
* @param {object} channel - amqplib channel
|
|
7
|
+
* @param {{ routingKey: string, body: string }} record - telemetry record
|
|
8
|
+
* @returns {boolean} publish accepted
|
|
9
|
+
*/
|
|
10
|
+
export default function publishRecord(channel, record) {
|
|
11
|
+
if (typeof channel.write === 'function') {
|
|
12
|
+
return channel.write([{
|
|
13
|
+
exchange: TELEMETRY, routingKey: record.routingKey, body: Buffer.from(record.body),
|
|
14
|
+
options: { contentType: 'application/json', headers: { 'scada-route': record.routingKey }, persistent: true, mandatory: true }
|
|
15
|
+
}]);
|
|
16
|
+
}
|
|
17
|
+
return channel.publish(TELEMETRY, record.routingKey, Buffer.from(record.body), {
|
|
18
|
+
contentType: 'application/json',
|
|
19
|
+
headers: { 'scada-route': record.routingKey },
|
|
20
|
+
persistent: true,
|
|
21
|
+
mandatory: true
|
|
22
|
+
});
|
|
23
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* In-memory durable-style queue with max-length and drop-head overflow.
|
|
3
|
+
* Models RabbitMQ x-max-length / x-overflow=drop-head for tests and local drains.
|
|
4
|
+
*
|
|
5
|
+
* @param {number} maxLength - maximum ready messages retained
|
|
6
|
+
* @returns {object} queue with publish/take/ack/nack/depth/dropped
|
|
7
|
+
*/
|
|
8
|
+
export default function boundedQueue(maxLength) {
|
|
9
|
+
const ready = [];
|
|
10
|
+
let held = null;
|
|
11
|
+
let dropped = 0;
|
|
12
|
+
return Object.freeze({
|
|
13
|
+
depth() {
|
|
14
|
+
return ready.length + (held === null ? 0 : 1);
|
|
15
|
+
},
|
|
16
|
+
ready() {
|
|
17
|
+
return ready.length;
|
|
18
|
+
},
|
|
19
|
+
dropped() {
|
|
20
|
+
return dropped;
|
|
21
|
+
},
|
|
22
|
+
publish(message) {
|
|
23
|
+
ready.push(message);
|
|
24
|
+
while (ready.length > maxLength) {
|
|
25
|
+
ready.shift();
|
|
26
|
+
dropped += 1;
|
|
27
|
+
}
|
|
28
|
+
},
|
|
29
|
+
take() {
|
|
30
|
+
if (held !== null) {
|
|
31
|
+
throw new Error('boundedQueue already holds an unacked message');
|
|
32
|
+
}
|
|
33
|
+
if (ready.length === 0) {
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
held = ready.shift();
|
|
37
|
+
return held;
|
|
38
|
+
},
|
|
39
|
+
ack() {
|
|
40
|
+
held = null;
|
|
41
|
+
},
|
|
42
|
+
nack() {
|
|
43
|
+
if (held === null) {
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
ready.unshift(held);
|
|
47
|
+
held = null;
|
|
48
|
+
}
|
|
49
|
+
});
|
|
50
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
<configuration>
|
|
2
|
+
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
|
3
|
+
<encoder>
|
|
4
|
+
<pattern>%d{ISO8601} %-5level [%thread] %logger{36} %mdc - %msg%n</pattern>
|
|
5
|
+
</encoder>
|
|
6
|
+
</appender>
|
|
7
|
+
|
|
8
|
+
<logger name="com.zaxxer.hikari" level="INFO"/>
|
|
9
|
+
<logger name="org.eclipse.paho" level="INFO"/>
|
|
10
|
+
<logger name="org.postgresql" level="WARN"/>
|
|
11
|
+
<logger name="org.http4s.ember.server" level="INFO"/>
|
|
12
|
+
|
|
13
|
+
<root level="INFO">
|
|
14
|
+
<appender-ref ref="STDOUT"/>
|
|
15
|
+
</root>
|
|
16
|
+
</configuration>
|
|
@@ -15,3 +15,9 @@ final class DurableMachineInput(config: AppConfig, machine: MachineConfig, queue
|
|
|
15
15
|
def readings(aliases: List[AliasMapping], seeding: Option[Seeding])(ready: IO[Unit]): Stream[IO, (Reading, IO[Unit])] =
|
|
16
16
|
val live = StompReadings(config.connectivity.rabbitmq, queue, aliases).subscribeDurable
|
|
17
17
|
seeding.fold(live)(_.seedDurable(machine, aliases, live, ready))
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def run(aliases: List[AliasMapping], seeding: Option[Seeding])(
|
|
21
|
+
process: (IO[Unit] => Stream[IO, (Reading, IO[Unit])], Stream[IO, Decision], Boolean) => IO[Unit]
|
|
22
|
+
): Stream[IO, Unit] =
|
|
23
|
+
Stream.eval(process(readings(aliases, seeding), decisions, seeding.isDefined))
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
package scada.processing.runtime
|
|
2
2
|
|
|
3
|
-
import cats.effect.{IO, Ref}
|
|
3
|
+
import cats.effect.{IO, Ref, Resource}
|
|
4
4
|
import cats.effect.std.Semaphore
|
|
5
5
|
import io.circe.{Decoder, Encoder}
|
|
6
|
-
import io.yarkivaev.streamworker.{Checkpoint, CheckpointStore, StaleOwnership, TaskIdentity}
|
|
6
|
+
import io.yarkivaev.streamworker.{Checkpoint, CheckpointStore, Output, OutputId, ProcessorVersion, StaleOwnership, TaskIdentity}
|
|
7
7
|
import io.yarkivaev.streamworker.postgres.PgCheckpointStore
|
|
8
|
+
import scada.processing.infra.state.StateJournal
|
|
8
9
|
|
|
9
10
|
object WorkerStores:
|
|
10
11
|
final case class Binding[S, O](store: CheckpointStore[S, O], task: TaskIdentity, ownership: Long)
|
|
@@ -41,3 +42,31 @@ object WorkerStores:
|
|
|
41
42
|
IO.raiseUnless(current.revision == expectedRevision)(IllegalStateException("Worker checkpoint revision changed")) *>
|
|
42
43
|
persist(next) *> state.set(next)
|
|
43
44
|
Binding(store, initial.task, owner)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
/** Stable receipt metadata for application-owned journal formats. */
|
|
48
|
+
final case class JournalCursor(runId: String, position: Option[Long], revision: Long, closedThrough: Long)
|
|
49
|
+
derives Encoder.AsObject, Decoder
|
|
50
|
+
|
|
51
|
+
final case class JournalSnapshot[S, O](state: S, pending: Option[O], cursor: Option[JournalCursor], observedThrough: Long)
|
|
52
|
+
|
|
53
|
+
/** Restore a local outbox without changing its wire format or replay identity. */
|
|
54
|
+
def journal[A, S, O](open: Resource[IO, StateJournal[A]], machine: String, source: String,
|
|
55
|
+
version: ProcessorVersion, publishedThrough: Long)(
|
|
56
|
+
read: A => JournalSnapshot[S, O], restore: (S, Long) => S, attachCursor: (A, JournalCursor) => A,
|
|
57
|
+
write: (Checkpoint[S, O], JournalCursor) => Option[A], closedThrough: S => Long
|
|
58
|
+
): Resource[IO, Binding[S, O]] =
|
|
59
|
+
open.evalMap: journal =>
|
|
60
|
+
for
|
|
61
|
+
record <- journal.load
|
|
62
|
+
saved <- IO(read(record))
|
|
63
|
+
edge = math.max(publishedThrough, math.max(saved.observedThrough, saved.cursor.fold(0L)(_.closedThrough)))
|
|
64
|
+
cursor <- saved.cursor.fold(IO.randomUUID.map(id => JournalCursor(id.toString, None, 0L, edge)))(IO.pure)
|
|
65
|
+
task = TaskIdentity(machine, source, cursor.runId)
|
|
66
|
+
pending = saved.pending.map(value => Output(OutputId(task, cursor.position.getOrElse(0L), 0), value))
|
|
67
|
+
start = Checkpoint(task, version, cursor.revision, cursor.position, restore(saved.state, edge), pending.toVector)
|
|
68
|
+
_ <- IO.whenA(saved.cursor.isEmpty && saved.pending.nonEmpty)(journal.save(attachCursor(record, cursor)))
|
|
69
|
+
binding <- local(start): next =>
|
|
70
|
+
val receipt = JournalCursor(next.task.runId, next.position, next.revision, closedThrough(next.state))
|
|
71
|
+
write(next, receipt).fold(IO.unit)(journal.save)
|
|
72
|
+
yield binding
|