@yarkivaev/scada 2.13.0 → 2.15.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/charts/scada/templates/processes.yaml +6 -1
- package/charts/scada/values.schema.json +1 -0
- package/index.js +29 -0
- package/package.json +3 -2
- package/src/application/control/agent.js +8 -14
- package/src/application/control/controlClient.js +1 -1
- package/src/application/control/createOnlyJSON.js +50 -0
- package/src/application/control/executionSnapshot.js +4 -5
- package/src/application/control/index.js +2 -0
- package/src/application/control/jsonAssignments.js +30 -0
- 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/deliveryOperations.js +6 -3
- package/src/application/runtime/deliveryPublications.js +13 -11
- package/src/application/runtime/deliveryQueue.js +5 -4
- package/src/application/runtime/index.js +0 -1
- package/src/application/runtime/queuedDelivery.js +6 -5
- package/src/application/runtime/runCollector.js +8 -6
- package/src/application/runtime/runtime.js +1 -0
- package/src/application/runtime/runtimeServices.js +6 -26
- 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/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/telemetry/edgeTelemetryRuntime.js +83 -0
- package/src/infrastructure/ingest/telemetry/replayStoredTelemetry.js +125 -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/opcua/health.js +91 -0
- package/src/infrastructure/opcua/index.js +1 -0
- package/src/infrastructure/persistence/pg/prepareRuntimeRole.js +67 -0
- package/src/infrastructure/persistence/runtime/memoryDeliveryStore.js +186 -0
- package/src/infrastructure/persistence/runtime/spoolCodec.js +0 -27
- package/src/infrastructure/persistence/runtime/taskStateMemory.js +40 -0
- 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/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/application/control/snapshotFile.js +0 -24
- package/src/infrastructure/persistence/runtime/deliverySpool.js +0 -86
- package/src/infrastructure/persistence/runtime/spoolCheckpoints.js +0 -65
- package/src/infrastructure/persistence/runtime/spoolDatabase.js +0 -69
- package/src/infrastructure/persistence/runtime/spoolFormat.js +0 -63
- package/src/infrastructure/persistence/runtime/spoolLimits.js +0 -8
- package/src/infrastructure/persistence/runtime/spoolMigration.js +0 -66
- package/src/infrastructure/persistence/runtime/spoolMutations.js +0 -19
- package/src/infrastructure/persistence/runtime/spoolProcess.js +0 -89
- package/src/infrastructure/persistence/runtime/spoolProcessChild.js +0 -32
- package/src/infrastructure/persistence/runtime/spoolRecords.js +0 -56
- package/src/infrastructure/persistence/runtime/spoolReplay.js +0 -55
- package/src/infrastructure/persistence/runtime/taskStateSqlite.js +0 -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,24 +0,0 @@
|
|
|
1
|
-
import { mkdir, open, readFile, rename, unlink } from 'node:fs/promises';
|
|
2
|
-
import path from 'node:path';
|
|
3
|
-
import { randomUUID } from 'node:crypto';
|
|
4
|
-
export function checkSnapshot(value) {
|
|
5
|
-
if (!value || !Number.isSafeInteger(value.generation) || value.generation < 0 || !Array.isArray(value.assignments)) { throw new TypeError('Invalid assignment snapshot'); }
|
|
6
|
-
return value;
|
|
7
|
-
}
|
|
8
|
-
export async function loadSnapshot(file) {
|
|
9
|
-
try { return checkSnapshot(JSON.parse(await readFile(file, 'utf8'))); } catch (error) { if (error.code === 'ENOENT') { return null; } throw error; }
|
|
10
|
-
}
|
|
11
|
-
export async function saveSnapshot(file, snapshot) {
|
|
12
|
-
checkSnapshot(snapshot);
|
|
13
|
-
await mkdir(path.dirname(file), { recursive: true });
|
|
14
|
-
const temporary = `${file}.${randomUUID()}.tmp`;
|
|
15
|
-
try {
|
|
16
|
-
const handle = await open(temporary, 'wx', 0o600);
|
|
17
|
-
try { await handle.writeFile(JSON.stringify(snapshot)); await handle.sync(); } finally { await handle.close(); }
|
|
18
|
-
await rename(temporary, file);
|
|
19
|
-
const directory = await open(path.dirname(file), 'r');
|
|
20
|
-
try { await directory.sync(); } finally { await directory.close(); }
|
|
21
|
-
} finally { await unlink(temporary).catch(() => {
|
|
22
|
-
// Rename may already have consumed the temporary file.
|
|
23
|
-
}); }
|
|
24
|
-
}
|
|
@@ -1,86 +0,0 @@
|
|
|
1
|
-
import { capacity, checkpoint, counters, database } from './spoolDatabase.js';
|
|
2
|
-
import { listed, pending } from './spoolRecords.js';
|
|
3
|
-
import { pendingFair } from './spoolReplay.js';
|
|
4
|
-
import spoolMutations from './spoolMutations.js';
|
|
5
|
-
import spoolMigration from './spoolMigration.js';
|
|
6
|
-
import spoolLimits from './spoolLimits.js';
|
|
7
|
-
import spoolCheckpoints from './spoolCheckpoints.js';
|
|
8
|
-
|
|
9
|
-
/* eslint max-lines-per-function: ["error", 100], max-statements: ["error", 25] */
|
|
10
|
-
/** Single owner, bounded cache and indexed reads. Caps count logical JSON bytes, not allocated pages. */
|
|
11
|
-
export default function deliverySpool(directory, options) {
|
|
12
|
-
const { maxBytes, maxRecords, legacyMigrationMaxBytes, walCheckpoint } = spoolLimits(options);
|
|
13
|
-
const state = { db: null, owner: null, ready: false, busy: false, bytes: 0, records: 0 };
|
|
14
|
-
let maintenance;
|
|
15
|
-
function release() {
|
|
16
|
-
maintenance?.cancel(); maintenance = undefined;
|
|
17
|
-
state.ready = false;
|
|
18
|
-
try { state.db?.close(); } finally { state.owner?.close(); state.db = null; state.owner = null; }
|
|
19
|
-
}
|
|
20
|
-
function refresh() {
|
|
21
|
-
const totals = counters(state.db); state.bytes = totals.bytes; state.records = totals.records;
|
|
22
|
-
}
|
|
23
|
-
async function exclusive(action, requireReady = true) {
|
|
24
|
-
if (state.busy) { throw new Error('Spool operation in progress'); }
|
|
25
|
-
if (requireReady && !state.ready) { throw new Error('Spool not opened'); }
|
|
26
|
-
state.busy = true;
|
|
27
|
-
try { return await action(); } finally { Object.assign(state, { busy:false }); }
|
|
28
|
-
}
|
|
29
|
-
function commit(action) {
|
|
30
|
-
try {
|
|
31
|
-
maintenance?.beforeWrite();
|
|
32
|
-
const result = state.db.transaction(action)();
|
|
33
|
-
refresh(); maintenance?.schedule();
|
|
34
|
-
return result;
|
|
35
|
-
}
|
|
36
|
-
catch (error) { if (error.code?.startsWith('SQLITE_')) { release(); } throw error; }
|
|
37
|
-
}
|
|
38
|
-
function mutateMany(operations) {
|
|
39
|
-
return exclusive(() => { return commit(() => { return spoolMutations(state.db, operations, { maxBytes, maxRecords }); }); });
|
|
40
|
-
}
|
|
41
|
-
async function single(operation) {
|
|
42
|
-
const [result] = await mutateMany([operation]);
|
|
43
|
-
if (!result.ok) { throw result.error; }
|
|
44
|
-
}
|
|
45
|
-
return {
|
|
46
|
-
mutateMany,
|
|
47
|
-
open() {
|
|
48
|
-
return exclusive(async () => {
|
|
49
|
-
if (state.ready) { return; }
|
|
50
|
-
try {
|
|
51
|
-
Object.assign(state, await database(directory));
|
|
52
|
-
capacity(state.db, maxBytes, maxRecords);
|
|
53
|
-
await spoolMigration(directory, state.db, { maxBytes, maxRecords, legacyMigrationMaxBytes });
|
|
54
|
-
if (walCheckpoint) { maintenance = spoolCheckpoints(state.db, directory, walCheckpoint); maintenance.schedule(); }
|
|
55
|
-
refresh(); Object.assign(state, { ready:true });
|
|
56
|
-
} catch (error) { release(); throw error; }
|
|
57
|
-
}, false);
|
|
58
|
-
},
|
|
59
|
-
append(event, recipients) { return single({ kind: 'append', event, recipients }); },
|
|
60
|
-
ack(eventId, recipient) { return single({ kind: 'ack', eventId, recipient }); },
|
|
61
|
-
pending(limit = 100) {
|
|
62
|
-
return exclusive(() => {
|
|
63
|
-
if (!Number.isSafeInteger(limit) || limit <= 0) { throw new TypeError('Positive pending limit required'); }
|
|
64
|
-
return commit(() => { return pending(state.db, limit); });
|
|
65
|
-
});
|
|
66
|
-
},
|
|
67
|
-
pendingFair(limit = 100, blocked = []) {
|
|
68
|
-
return exclusive(() => {
|
|
69
|
-
if (!Number.isSafeInteger(limit) || limit <= 0) { throw new TypeError('Positive pending limit required'); }
|
|
70
|
-
return commit(() => { return pendingFair(state.db, limit, blocked); });
|
|
71
|
-
});
|
|
72
|
-
},
|
|
73
|
-
peek(limit = 1000) {
|
|
74
|
-
return exclusive(() => {
|
|
75
|
-
if (!Number.isSafeInteger(limit) || limit <= 0) { throw new TypeError('Positive peek limit required'); }
|
|
76
|
-
return listed(state.db, limit);
|
|
77
|
-
});
|
|
78
|
-
},
|
|
79
|
-
close() {
|
|
80
|
-
return exclusive(() => {
|
|
81
|
-
try { if (state.db) { checkpoint(state.db); } } finally { release(); }
|
|
82
|
-
}, false);
|
|
83
|
-
},
|
|
84
|
-
status() { return { bytes: state.bytes, maxBytes, recordLimit: maxRecords, pending: state.records, ready: state.ready }; }
|
|
85
|
-
};
|
|
86
|
-
}
|