@yarkivaev/scada 2.9.2 → 2.10.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 +1 -1
- package/src/infrastructure/persistence/runtime/spoolDatabase.js +3 -5
- package/src/infrastructure/persistence/runtime/spoolFormat.js +35 -9
- package/src/infrastructure/persistence/runtime/spoolReplay.js +10 -37
- package/stream-processing/src/main/scala/scada/processing/infra/stomp/StompConnection.scala +24 -14
- package/stream-processing/src/main/scala/scada/processing/runtime/ClassifyStreams.scala +60 -21
- package/stream-processing/src/main/scala/scada/processing/runtime/HistoryClient.scala +9 -0
- package/stream-processing/src/main/scala/scada/processing/runtime/HistoryInput.scala +76 -0
- package/stream-processing/src/main/scala/scada/processing/runtime/HistoryRun.scala +27 -11
- package/stream-processing/src/main/scala/scada/processing/runtime/LocalHistory.scala +17 -34
- package/stream-processing/src/main/scala/scada/processing/runtime/RuntimeProfile.scala +1 -1
- package/stream-processing/src/main/scala/scada/processing/runtime/TimelineWriter.scala +9 -6
- package/stream-processing/src/main/scala/scada/processing/runtime/WriterLease.scala +12 -3
- package/stream-processing/src/main/scala/scada/stream/replay/Replay.scala +0 -149
package/package.json
CHANGED
|
@@ -3,14 +3,13 @@ import path from 'node:path';
|
|
|
3
3
|
import { lstat, mkdir, open } from 'node:fs/promises';
|
|
4
4
|
import { constants } from 'node:fs';
|
|
5
5
|
import { format, initialize } from './spoolFormat.js';
|
|
6
|
-
import { replayFiles, replayIndex } from './spoolReplay.js';
|
|
7
6
|
|
|
8
7
|
// POSIX closes release this process's advisory locks for an inode, even from unrelated descriptors.
|
|
9
8
|
// Reserve directory identity before opening ANY owner descriptor, including rejected contenders.
|
|
10
9
|
const registry = Symbol.for('@yarkivaev/scada/delivery-spool-owners');
|
|
11
10
|
globalThis[registry] ??= new Set();
|
|
12
11
|
const owners = globalThis[registry];
|
|
13
|
-
const files = [
|
|
12
|
+
const files = ['owner.sqlite', 'delivery.sqlite'].flatMap((name) => { return [name, `${name}-journal`, `${name}-wal`, `${name}-shm`]; });
|
|
14
13
|
export async function regular(file) {
|
|
15
14
|
try {
|
|
16
15
|
const info = await lstat(file);
|
|
@@ -56,12 +55,11 @@ export async function database(directory) {
|
|
|
56
55
|
owner.exec('BEGIN EXCLUSIVE; CREATE TABLE IF NOT EXISTS owner (id INTEGER)');
|
|
57
56
|
await privateFile(path.join(directory, 'delivery.sqlite'));
|
|
58
57
|
db = new Database(path.join(directory, 'delivery.sqlite'), { timeout: 0 });
|
|
59
|
-
const
|
|
58
|
+
const version = format(db);
|
|
60
59
|
db.pragma('journal_mode = WAL'); db.pragma('synchronous = FULL');
|
|
61
60
|
db.pragma('cache_size = -2048'); db.pragma('wal_autocheckpoint = 256');
|
|
62
61
|
db.pragma('journal_size_limit = 1048576'); db.pragma('secure_delete = FAST');
|
|
63
|
-
if (
|
|
64
|
-
await replayIndex(db, directory);
|
|
62
|
+
if (version < 2) { initialize(db, version); }
|
|
65
63
|
return { db, owner: { close() { try { owner.close(); } finally { owners.delete(key); } } } };
|
|
66
64
|
} catch (error) {
|
|
67
65
|
try { db?.close(); } finally { try { owner?.close(); } finally { owners.delete(key); } }
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const
|
|
1
|
+
const canonical = [
|
|
2
2
|
'CREATE TABLE counters (id INTEGER PRIMARY KEY CHECK(id=1), bytes INTEGER NOT NULL, records INTEGER NOT NULL, sequence INTEGER NOT NULL)',
|
|
3
3
|
'CREATE TABLE destinations (id TEXT PRIMARY KEY, json TEXT NOT NULL, refs INTEGER NOT NULL)',
|
|
4
4
|
`CREATE TABLE events (id TEXT PRIMARY KEY, fingerprint TEXT NOT NULL, payload BLOB NOT NULL,
|
|
@@ -6,8 +6,17 @@ const statements = [
|
|
|
6
6
|
'CREATE INDEX event_sequence ON events(sequence)',
|
|
7
7
|
'CREATE TABLE imports (name TEXT PRIMARY KEY, digest TEXT NOT NULL, event_id TEXT NOT NULL)'
|
|
8
8
|
];
|
|
9
|
+
const replayPending = `CREATE TABLE replay_pending (target TEXT NOT NULL, event_id TEXT NOT NULL, recipient TEXT NOT NULL, sequence INTEGER NOT NULL,
|
|
10
|
+
PRIMARY KEY(target,sequence,event_id,recipient)) WITHOUT ROWID`;
|
|
11
|
+
const replayIndexes = [
|
|
12
|
+
'CREATE UNIQUE INDEX replay_event_recipient ON replay_pending(event_id,recipient)',
|
|
13
|
+
'CREATE TABLE replay_targets (id TEXT PRIMARY KEY, sequence INTEGER NOT NULL)',
|
|
14
|
+
'CREATE INDEX replay_target_sequence ON replay_targets(sequence)'
|
|
15
|
+
];
|
|
16
|
+
const current = [...canonical, replayPending, ...replayIndexes];
|
|
17
|
+
|
|
9
18
|
function metadata(db) {
|
|
10
|
-
return db.prepare("SELECT
|
|
19
|
+
return db.prepare("SELECT sql FROM sqlite_schema WHERE name NOT GLOB 'sqlite_*' LIMIT ?").all(current.length + 1);
|
|
11
20
|
}
|
|
12
21
|
function validCounters(db) {
|
|
13
22
|
const rows = db.prepare('SELECT id,bytes,records,sequence FROM counters LIMIT 2').all();
|
|
@@ -22,16 +31,33 @@ function validCounters(db) {
|
|
|
22
31
|
export function format(db) {
|
|
23
32
|
const version = db.pragma('user_version', { simple: true });
|
|
24
33
|
const schema = metadata(db);
|
|
25
|
-
if (version === 0 && schema.length === 0) { return
|
|
26
|
-
if (version !== 1) { throw new Error('Unsupported spool format version or nonempty database'); }
|
|
27
|
-
const expected =
|
|
34
|
+
if (version === 0 && schema.length === 0) { return 0; }
|
|
35
|
+
if (version !== 1 && version !== 2) { throw new Error('Unsupported spool format version or nonempty database'); }
|
|
36
|
+
const expected = (version === 1 ? canonical : current).map((sql) => { return sql.replaceAll(/\s+/gu, ' '); }).sort();
|
|
28
37
|
const actual = schema.map((row) => { return row.sql.replaceAll(/\s+/gu, ' '); }).sort();
|
|
29
38
|
if (JSON.stringify(actual) !== JSON.stringify(expected) || !validCounters(db)) { throw new Error('Corrupt spool format or counters'); }
|
|
30
|
-
return
|
|
39
|
+
return version;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function populateReplay(db) {
|
|
43
|
+
db.exec(`INSERT INTO replay_pending
|
|
44
|
+
SELECT COALESCE(json_extract(e.destinations,'$['||r.key||']'),'legacy:'||r.value) AS target, e.id, r.value, e.sequence
|
|
45
|
+
FROM events e, json_each(e.recipients) r
|
|
46
|
+
WHERE r.value IN (SELECT value FROM json_each(e.remaining))
|
|
47
|
+
ORDER BY target, e.sequence, e.id, r.value`);
|
|
31
48
|
}
|
|
32
|
-
|
|
49
|
+
|
|
50
|
+
export function initialize(db, version) {
|
|
51
|
+
// The schema version and derived rows commit together under the spool owner's lock.
|
|
33
52
|
db.transaction(() => {
|
|
34
|
-
|
|
35
|
-
|
|
53
|
+
if (version === 0) {
|
|
54
|
+
db.exec(canonical.join(';'));
|
|
55
|
+
db.prepare('INSERT INTO counters VALUES (1,0,0,0)').run();
|
|
56
|
+
}
|
|
57
|
+
db.exec(replayPending);
|
|
58
|
+
if (version === 1) { populateReplay(db); }
|
|
59
|
+
db.exec(replayIndexes.join(';'));
|
|
60
|
+
db.exec('INSERT INTO replay_targets SELECT target,MIN(sequence) FROM replay_pending GROUP BY target');
|
|
61
|
+
db.pragma('user_version=2');
|
|
36
62
|
})();
|
|
37
63
|
}
|
|
@@ -1,46 +1,19 @@
|
|
|
1
|
-
import path from 'node:path';
|
|
2
|
-
import { open, unlink } from 'node:fs/promises';
|
|
3
|
-
import { constants } from 'node:fs';
|
|
4
1
|
import { decoded } from './spoolCodec.js';
|
|
5
2
|
|
|
6
|
-
export const replayFiles = ['replay-index.sqlite', 'replay-index.sqlite-journal', 'replay-index.sqlite-wal', 'replay-index.sqlite-shm'];
|
|
7
|
-
/** Disposable routing index. Every open rebuilds from canonical FULL-committed event metadata. */
|
|
8
|
-
export async function replayIndex(db, directory) {
|
|
9
|
-
for (const name of replayFiles) {
|
|
10
|
-
// Caller holds the directory owner and has rejected aliases before any mutation.
|
|
11
|
-
// eslint-disable-next-line no-await-in-loop
|
|
12
|
-
await unlink(path.join(directory, name)).catch(error => { if (error.code !== 'ENOENT') { throw error; } });
|
|
13
|
-
}
|
|
14
|
-
const file = path.join(directory, replayFiles[0]);
|
|
15
|
-
const handle = await open(file, constants.O_RDWR + constants.O_CREAT + constants.O_EXCL + constants.O_NOFOLLOW, 0o600);
|
|
16
|
-
await handle.close();
|
|
17
|
-
db.prepare('ATTACH DATABASE ? AS replay').run(file);
|
|
18
|
-
db.exec(`PRAGMA replay.journal_mode=MEMORY; PRAGMA replay.synchronous=OFF; PRAGMA replay.cache_size=-2048;
|
|
19
|
-
CREATE TABLE replay.targets (id TEXT PRIMARY KEY, sequence INTEGER NOT NULL);
|
|
20
|
-
CREATE INDEX replay.target_sequence ON targets(sequence);
|
|
21
|
-
CREATE TABLE replay.pending (target TEXT NOT NULL, event_id TEXT NOT NULL, recipient TEXT NOT NULL, sequence INTEGER NOT NULL,
|
|
22
|
-
PRIMARY KEY(target,sequence,event_id,recipient)) WITHOUT ROWID;
|
|
23
|
-
CREATE UNIQUE INDEX replay.event_recipient ON pending(event_id,recipient);
|
|
24
|
-
INSERT INTO replay.pending
|
|
25
|
-
SELECT COALESCE(json_extract(e.destinations,'$['||r.key||']'),'legacy:'||r.value), e.id, r.value, e.sequence
|
|
26
|
-
FROM main.events e, json_each(e.recipients) r
|
|
27
|
-
WHERE r.value IN (SELECT value FROM json_each(e.remaining));
|
|
28
|
-
INSERT INTO replay.targets SELECT target,MIN(sequence) FROM replay.pending GROUP BY target;`);
|
|
29
|
-
}
|
|
30
3
|
export function indexInsert(db, value, sequence) {
|
|
31
4
|
const recipients = JSON.parse(value.recipients);
|
|
32
5
|
for (const recipient of JSON.parse(value.remaining)) {
|
|
33
6
|
const target = value.destinations?.[recipients.indexOf(recipient)]?.id ?? `legacy:${recipient}`;
|
|
34
|
-
db.prepare('INSERT INTO
|
|
35
|
-
db.prepare('INSERT OR IGNORE INTO
|
|
7
|
+
db.prepare('INSERT INTO replay_pending VALUES (?,?,?,?)').run(target, value.id, recipient, sequence);
|
|
8
|
+
db.prepare('INSERT OR IGNORE INTO replay_targets VALUES (?,?)').run(target, sequence);
|
|
36
9
|
}
|
|
37
10
|
}
|
|
38
11
|
export function indexAck(db, id, recipient) {
|
|
39
|
-
const row = db.prepare('SELECT target FROM
|
|
12
|
+
const row = db.prepare('SELECT target FROM replay_pending WHERE event_id=? AND recipient=?').get(id, recipient);
|
|
40
13
|
if (!row) { return; }
|
|
41
|
-
db.prepare('DELETE FROM
|
|
42
|
-
if (!db.prepare('SELECT 1 FROM
|
|
43
|
-
db.prepare('DELETE FROM
|
|
14
|
+
db.prepare('DELETE FROM replay_pending WHERE event_id=? AND recipient=?').run(id, recipient);
|
|
15
|
+
if (!db.prepare('SELECT 1 FROM replay_pending WHERE target=? LIMIT 1').get(row.target)) {
|
|
16
|
+
db.prepare('DELETE FROM replay_targets WHERE id=?').run(row.target);
|
|
44
17
|
}
|
|
45
18
|
}
|
|
46
19
|
/* eslint max-depth: ["error", 4] */
|
|
@@ -62,20 +35,20 @@ function interleaved(pages, limit) {
|
|
|
62
35
|
export function pendingFair(db, limit, blocked) {
|
|
63
36
|
const excluded = [...blocked];
|
|
64
37
|
const where = excluded.length ? `WHERE id NOT IN (${excluded.map(() => { return '?'; }).join(',')})` : '';
|
|
65
|
-
const targets = db.prepare(`SELECT id FROM
|
|
66
|
-
const pages = targets.map(({id}) => { return db.prepare('SELECT event_id,recipient,target FROM
|
|
38
|
+
const targets = db.prepare(`SELECT id FROM replay_targets ${where} ORDER BY sequence LIMIT ?`).all(...excluded, Math.min(limit, 64));
|
|
39
|
+
const pages = targets.map(({id}) => { return db.prepare('SELECT event_id,recipient,target FROM replay_pending WHERE target=? ORDER BY sequence LIMIT ?').all(id, limit); });
|
|
67
40
|
const selected = interleaved(pages, limit);
|
|
68
41
|
let {sequence} = db.prepare('SELECT sequence FROM counters WHERE id=1').get();
|
|
69
42
|
const rows = [...selected].map(([id, pairs]) => {
|
|
70
43
|
for (const pair of pairs) {
|
|
71
44
|
sequence += 1;
|
|
72
|
-
db.prepare('UPDATE
|
|
45
|
+
db.prepare('UPDATE replay_pending SET sequence=? WHERE event_id=? AND recipient=?').run(sequence, id, pair.recipient);
|
|
73
46
|
}
|
|
74
47
|
const row = decoded(db.prepare('SELECT * FROM events WHERE id=?').get(id), db);
|
|
75
48
|
return {...row, remaining:pairs.map(pair => { return pair.recipient; }), targets:Object.fromEntries(pairs.map(pair => { return [pair.recipient,pair.target]; }))};
|
|
76
49
|
});
|
|
77
50
|
for (const {id} of targets) {
|
|
78
|
-
sequence += 1; db.prepare('UPDATE
|
|
51
|
+
sequence += 1; db.prepare('UPDATE replay_targets SET sequence=? WHERE id=?').run(sequence, id);
|
|
79
52
|
}
|
|
80
53
|
db.prepare('UPDATE counters SET sequence=? WHERE id=1').run(sequence);
|
|
81
54
|
return rows;
|
|
@@ -4,7 +4,7 @@ import cats.effect.{IO, Resource}
|
|
|
4
4
|
import cats.syntax.all.*
|
|
5
5
|
import scala.concurrent.duration.*
|
|
6
6
|
import java.io.{BufferedReader, InputStreamReader, OutputStream}
|
|
7
|
-
import java.net.{Socket, SocketTimeoutException}
|
|
7
|
+
import java.net.{InetSocketAddress, Socket, SocketTimeoutException}
|
|
8
8
|
|
|
9
9
|
/**
|
|
10
10
|
* Raw TCP STOMP connection. Sends and receives [[StompFrame]]s over a
|
|
@@ -91,16 +91,26 @@ object StompConnection:
|
|
|
91
91
|
|
|
92
92
|
def connect(host: String, port: Int, vhost: String, login: String, passcode: String): IO[StompConnection] =
|
|
93
93
|
IO.blocking:
|
|
94
|
-
val socket = Socket(
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
sb
|
|
104
|
-
ch = reader.read()
|
|
105
|
-
|
|
106
|
-
|
|
94
|
+
val socket = Socket()
|
|
95
|
+
try
|
|
96
|
+
socket.connect(InetSocketAddress(host, port), 10000)
|
|
97
|
+
socket.setSoTimeout(10000)
|
|
98
|
+
socket.setKeepAlive(true)
|
|
99
|
+
val output = socket.getOutputStream
|
|
100
|
+
val reader = BufferedReader(InputStreamReader(socket.getInputStream, "UTF-8"))
|
|
101
|
+
output.write(StompFrame.connect(vhost, login, passcode).encode)
|
|
102
|
+
output.flush()
|
|
103
|
+
val sb = StringBuilder()
|
|
104
|
+
var ch = reader.read()
|
|
105
|
+
while ch != -1 && ch != 0 do
|
|
106
|
+
sb.append(ch.toChar)
|
|
107
|
+
ch = reader.read()
|
|
108
|
+
if !StompFrame.decode(sb.toString).exists(_.command == "CONNECTED") then
|
|
109
|
+
throw IllegalStateException("RabbitMQ did not accept the STOMP connection")
|
|
110
|
+
socket.setSoTimeout(readTimeoutMillis)
|
|
111
|
+
StompConnection(socket, output, reader)
|
|
112
|
+
catch
|
|
113
|
+
case scala.util.control.NonFatal(error) =>
|
|
114
|
+
try socket.close()
|
|
115
|
+
catch case scala.util.control.NonFatal(closeError) => error.addSuppressed(closeError)
|
|
116
|
+
throw error
|
|
@@ -3,6 +3,7 @@ package scada.processing.runtime
|
|
|
3
3
|
import io.yarkivaev.segmentation.{HistorySegment, HistoryState}
|
|
4
4
|
import cats.effect.IO
|
|
5
5
|
import cats.effect.std.Semaphore
|
|
6
|
+
import cats.syntax.all.*
|
|
6
7
|
import fs2.Stream
|
|
7
8
|
import io.circe.{Codec, Decoder, Encoder, Json}
|
|
8
9
|
import io.circe.generic.semiauto.deriveCodec
|
|
@@ -30,20 +31,21 @@ final class ClassifyStreams private (
|
|
|
30
31
|
lock: Semaphore[IO],
|
|
31
32
|
ownership: Long
|
|
32
33
|
):
|
|
33
|
-
import ClassifyStreams.{Command, version}
|
|
34
|
+
import ClassifyStreams.{Command, Publication, version}
|
|
34
35
|
|
|
35
|
-
private val processor = new Processor[Unit, StreamState, (Observation, Long), Command]:
|
|
36
|
-
override def step(config: Unit, state: StreamState, input: (Observation, Long))
|
|
36
|
+
private val processor = new Processor[Unit, StreamState, (Observation, Long, Option[TimelineSnapshot]), Command]:
|
|
37
|
+
override def step(config: Unit, state: StreamState, input: (Observation, Long, Option[TimelineSnapshot]))
|
|
37
38
|
: Either[ProcessingError, StepResult[StreamState, Command]] =
|
|
38
|
-
val (point, now) = input
|
|
39
|
+
val (point, now, timeline) = input
|
|
39
40
|
val (next, routed) = ClassifyStreams.route(state, point, now, machine.window.toLong * 2000)
|
|
40
|
-
|
|
41
|
+
val publication = Option.when(routed.changed)(prepare(next, routed.cursor, timeline))
|
|
42
|
+
Right(StepResult(next, Vector(Command(point, routed, publication))))
|
|
41
43
|
|
|
42
44
|
private val worker = StreamWorker(processor, store, (_, output) =>
|
|
43
|
-
val
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
45
|
+
val attempt = output.value.publication.filter(_.admitted).traverse_ { publication =>
|
|
46
|
+
ports.atRevision(publication.revision, ports.announce(publication.rows, publication.historical))
|
|
47
|
+
}
|
|
48
|
+
attempt *> store.load(task, ownership).flatMap(checkpoint => ports.persist(checkpoint.state.pool)))
|
|
47
49
|
|
|
48
50
|
def consume(input: Stream[IO, Observation]): Stream[IO, Unit] = input.evalMap(accept)
|
|
49
51
|
def consumeDurable(input: Stream[IO, (Observation, IO[Unit])]): Stream[IO, Unit] =
|
|
@@ -56,29 +58,65 @@ final class ClassifyStreams private (
|
|
|
56
58
|
now <- ports.clock
|
|
57
59
|
retry = checkpoint.pendingOutputs.exists(_.value.point == point)
|
|
58
60
|
position = checkpoint.position.fold(0L)(previous => if retry then previous else previous + 1L)
|
|
59
|
-
|
|
60
|
-
|
|
61
|
+
pending = checkpoint.pendingOutputs.find(output => output.value.routed.changed && output.value.publication.isEmpty)
|
|
62
|
+
saved <- pending.traverse: output =>
|
|
63
|
+
val routed = output.value.routed
|
|
64
|
+
capture(checkpoint.state, routed).map(timeline => prepare(checkpoint.state, routed.cursor, timeline))
|
|
65
|
+
_ <- replacePendingPlan(checkpoint, saved, when = _.publication.isEmpty)
|
|
66
|
+
next <- if retry then IO.pure(None)
|
|
67
|
+
else
|
|
68
|
+
val (state, routed) = ClassifyStreams.route(checkpoint.state, point, now, machine.window.toLong * 2000)
|
|
69
|
+
capture(state, routed)
|
|
70
|
+
_ <- worker.run(task, version, (), ownership)(_ => Stream.emit(Delivery(position, (point, now, next), IO.unit)))
|
|
71
|
+
.handleErrorWith:
|
|
72
|
+
case conflict: HistoryHttpError if conflict.code.contains("REVISION_CONFLICT") =>
|
|
73
|
+
store.load(task, ownership).flatMap(replacePendingPlan(_, None, when = _.publication.nonEmpty)) *> IO.raiseError(conflict)
|
|
74
|
+
case failure => IO.raiseError(failure)
|
|
61
75
|
yield ()
|
|
62
|
-
|
|
76
|
+
|
|
77
|
+
private def replacePendingPlan(
|
|
78
|
+
checkpoint: Checkpoint[StreamState, Command], publication: Option[Publication], when: Command => Boolean
|
|
79
|
+
): IO[Unit] =
|
|
80
|
+
val pending = checkpoint.pendingOutputs.map: output =>
|
|
81
|
+
if when(output.value) then output.copy(value = output.value.copy(publication = publication)) else output
|
|
82
|
+
IO.whenA(pending != checkpoint.pendingOutputs)(
|
|
83
|
+
store.commit(ownership, checkpoint.revision, checkpoint.copy(revision = checkpoint.revision + 1L, pendingOutputs = pending)))
|
|
84
|
+
private def capture(state: StreamState, routed: RoutedPoint): IO[Option[TimelineSnapshot]] =
|
|
85
|
+
if !routed.changed then IO.pure(None)
|
|
86
|
+
else
|
|
87
|
+
val rows = state.tapes.getOrElse(routed.cursor.id, History.empty).rows
|
|
88
|
+
(rows.headOption, rows.lastOption) match
|
|
89
|
+
case (Some((from, _)), Some((until, _))) => ports.timeline(from, until)
|
|
90
|
+
case _ => IO.pure(None)
|
|
91
|
+
|
|
92
|
+
private def prepare(snapshot: StreamState, cursor: Cursor, timeline: Option[TimelineSnapshot]): Publication =
|
|
63
93
|
val points = ClassifyHistory.collected(snapshot.tapes.getOrElse(cursor.id, History.empty))
|
|
64
94
|
val until = points.map(_.time).maxOption.getOrElse(0L)
|
|
65
95
|
val from = points.map(_.time).minOption.getOrElse(0L)
|
|
66
|
-
val existing = snapshot.stored.filter(row => ClassifyStreams.overlaps(row, from, until))
|
|
67
96
|
val slack = machine.window.toLong * 2000
|
|
68
97
|
val historical = watermark.exists(end => cursor.position + slack < end)
|
|
69
|
-
val
|
|
70
|
-
val
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
98
|
+
val existing = timeline.fold(snapshot.stored)(_.rows).filter(row => ClassifyStreams.overlaps(row, from, until))
|
|
99
|
+
val result = LocalHistory.classify(machine, points)
|
|
100
|
+
val context = Json.obj("segments" -> Json.arr(existing*), "page" -> Json.obj("until" -> Json.fromLong(until)),
|
|
101
|
+
"rightClosed" -> Json.fromBoolean(historical))
|
|
102
|
+
val rows = ClassifyHistory.published(machine, existing, result, context)
|
|
103
|
+
Publication(timeline.map(_.revision), rows, historical, ports.admit(rows, historical))
|
|
104
|
+
|
|
105
|
+
final case class TimelineSnapshot(revision: String, rows: Vector[Json])
|
|
75
106
|
|
|
76
|
-
final case class ClassifyPorts(
|
|
107
|
+
final case class ClassifyPorts(
|
|
108
|
+
persist: HistoryPool => IO[Unit], announce: (Vector[Json], Boolean) => IO[Unit],
|
|
109
|
+
clock: IO[Long] = IO.realTime.map(_.toMillis),
|
|
110
|
+
timeline: (Long, Long) => IO[Option[TimelineSnapshot]] = (_, _) => IO.pure(None),
|
|
111
|
+
atRevision: (Option[String], IO[Unit]) => IO[Unit] = (_, action) => action,
|
|
112
|
+
admit: (Vector[Json], Boolean) => Boolean = (_, _) => true
|
|
113
|
+
)
|
|
77
114
|
final case class StreamState(pool: HistoryPool, tapes: Map[Long, History], stored: Vector[Json])
|
|
78
115
|
final case class RoutedPoint(cursor: Cursor, changed: Boolean)
|
|
79
116
|
|
|
80
117
|
object ClassifyStreams:
|
|
81
|
-
private final case class
|
|
118
|
+
private final case class Publication(revision: Option[String], rows: Vector[Json], historical: Boolean, admitted: Boolean)
|
|
119
|
+
private final case class Command(point: Observation, routed: RoutedPoint, publication: Option[Publication])
|
|
82
120
|
private given Codec.AsObject[Cursor] = deriveCodec
|
|
83
121
|
private given Codec.AsObject[Work] = deriveCodec
|
|
84
122
|
private given Codec.AsObject[LocalStreams] = deriveCodec
|
|
@@ -91,6 +129,7 @@ object ClassifyStreams:
|
|
|
91
129
|
(rows: Map[Long, Map[String, Observation]], seen: Set[String]) => History(TreeMap.from(rows), seen))
|
|
92
130
|
private given Codec.AsObject[StreamState] = deriveCodec
|
|
93
131
|
private given Codec.AsObject[RoutedPoint] = deriveCodec
|
|
132
|
+
private given Codec.AsObject[Publication] = deriveCodec
|
|
94
133
|
private given Codec.AsObject[Command] = deriveCodec
|
|
95
134
|
private val version = ProcessorVersion("amqp-classify/1", "session", "history-cursors/1")
|
|
96
135
|
|
|
@@ -27,4 +27,13 @@ final class HistoryClient(config: CheckpointApiConfig):
|
|
|
27
27
|
json.hcursor.downField("error").get[String]("code").toOption.orElse(json.hcursor.get[String]("code").toOption))
|
|
28
28
|
IO.raiseError(HistoryHttpError(path, response.statusCode(), code))
|
|
29
29
|
else IO.fromEither(decoded.left.map(error=>RuntimeException(error.message)))
|
|
30
|
+
/** Retry a lost commit response with the same fenced body and receipt identity. */
|
|
31
|
+
def commitHistory(body: Json): IO[Json] =
|
|
32
|
+
def attempt(retries: Int): IO[Json] =
|
|
33
|
+
request("POST", "/v1/history/commit", body).handleErrorWith:
|
|
34
|
+
case error: HistoryHttpError if error.status < 500 => IO.raiseError(error)
|
|
35
|
+
case error if retries == 0 => IO.raiseError(error)
|
|
36
|
+
case _ => IO.sleep(200.millis) *> attempt(retries - 1)
|
|
37
|
+
attempt(2)
|
|
38
|
+
|
|
30
39
|
def retry[A](action: IO[A]): IO[A] = action.handleErrorWith(_=>IO.sleep(2.seconds) *> retry(action))
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
package scada.processing.runtime
|
|
2
|
+
|
|
3
|
+
import cats.effect.{IO, Ref}
|
|
4
|
+
import cats.syntax.all.*
|
|
5
|
+
import fs2.Stream
|
|
6
|
+
import io.circe.{Decoder, Encoder, Json}
|
|
7
|
+
import io.circe.parser.parse
|
|
8
|
+
import io.yarkivaev.streamworker.{Checkpoint, CheckpointStore, Delivery, Processor, ProcessorVersion, StreamWorker, TaskIdentity}
|
|
9
|
+
import scada.processing.infra.config.RabbitMqConfig
|
|
10
|
+
import scada.processing.infra.stomp.{StompConnection, StompFrame, StompLink}
|
|
11
|
+
import scala.concurrent.duration.*
|
|
12
|
+
|
|
13
|
+
/** Supplies one bounded history page as an ordered input to the normal worker. */
|
|
14
|
+
trait HistoryInput:
|
|
15
|
+
def run[C, S, I: Encoder: Decoder, O](processor: Processor[C, S, I, O], config: C, initial: S, events: Vector[I])
|
|
16
|
+
: IO[HistoryInput.Result[S, O]]
|
|
17
|
+
|
|
18
|
+
object HistoryInput:
|
|
19
|
+
final case class Result[S, O](state: S, outputs: Vector[O])
|
|
20
|
+
|
|
21
|
+
def rabbit(config: RabbitMqConfig): HistoryInput = new HistoryInput:
|
|
22
|
+
def run[C, S, I: Encoder: Decoder, O](processor: Processor[C, S, I, O], rules: C, initial: S, events: Vector[I])
|
|
23
|
+
: IO[Result[S, O]] =
|
|
24
|
+
StompConnection.open(config.address.host, config.address.port, config.vhost,
|
|
25
|
+
config.credentials.login, config.credentials.passcode).use { link =>
|
|
26
|
+
for
|
|
27
|
+
id <- IO.randomUUID.map(_.toString)
|
|
28
|
+
queue = s"scada.history.input.$id"
|
|
29
|
+
task = TaskIdentity("history", queue, id)
|
|
30
|
+
version = ProcessorVersion("history-input/1", "page", "session/1")
|
|
31
|
+
store <- CheckpointStore.session(Checkpoint[S, O](task, version, 0L, None, initial, Vector.empty), 1L)
|
|
32
|
+
outputs <- Ref.of[IO, Vector[O]](Vector.empty)
|
|
33
|
+
worker = StreamWorker(processor, store, (_, output) => outputs.update(_ :+ output.value))
|
|
34
|
+
result <- worker.run(task, version, rules, 1L)(_ => page(link, queue, events))
|
|
35
|
+
rows <- outputs.get
|
|
36
|
+
yield Result(result.state, rows)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// The upstream work claim or unacknowledged outer observation owns durability.
|
|
40
|
+
// If this connection fails, its queue is deleted and the caller retries the whole bounded page.
|
|
41
|
+
private def page[I: Encoder: Decoder](link: StompLink, queue: String, events: Vector[I]): Stream[IO, Delivery[I]] =
|
|
42
|
+
val subscribe = StompFrame("SUBSCRIBE", Map(
|
|
43
|
+
"destination" -> s"/queue/$queue", "id" -> "history", "ack" -> "client-individual",
|
|
44
|
+
"prefetch-count" -> "1", "exclusive" -> "true", "auto-delete" -> "true", "durable" -> "false",
|
|
45
|
+
"receipt" -> "history-subscribe"), "")
|
|
46
|
+
val batches = events.grouped(128).toVector
|
|
47
|
+
val input = Stream.emits(batches.zipWithIndex).covary[IO].flatMap: (batch, index) =>
|
|
48
|
+
val position = index.toLong * 128L
|
|
49
|
+
val command = Json.obj("position" -> Json.fromLong(position),
|
|
50
|
+
"events" -> Json.arr(batch.map(Encoder[I].apply)*))
|
|
51
|
+
Stream.eval(send(link, queue, command) *> message(link)).flatMap: (body, ack) =>
|
|
52
|
+
val decoded = body.hcursor.get[Long]("position").flatMap: actual =>
|
|
53
|
+
if actual == position then body.hcursor.get[Vector[I]]("events")
|
|
54
|
+
else Left(io.circe.DecodingFailure(s"Expected history input position $position", Nil))
|
|
55
|
+
Stream.eval(IO.fromEither(decoded)).flatMap: values =>
|
|
56
|
+
if values.size != batch.size then Stream.raiseError[IO](IllegalStateException("Incomplete history input batch"))
|
|
57
|
+
else Stream.emits(values.zipWithIndex).map: (event, offset) =>
|
|
58
|
+
Delivery(position + offset, event, if offset == values.size - 1 then ack else IO.unit)
|
|
59
|
+
val end = (send(link, queue, Json.obj("end" -> Json.fromInt(events.size))) *> message(link)).flatMap: (body, ack) =>
|
|
60
|
+
IO.raiseUnless(body.hcursor.get[Int]("end").contains(events.size))(
|
|
61
|
+
IllegalStateException("History input ended without its page marker")) *> ack
|
|
62
|
+
Stream.exec(link.send(subscribe)) ++ input ++ Stream.exec(end)
|
|
63
|
+
|
|
64
|
+
private def send(link: StompLink, queue: String, body: Json): IO[Unit] =
|
|
65
|
+
val frame = StompFrame.send(s"/amq/queue/$queue", "", body.noSpaces)
|
|
66
|
+
link.send(frame.copy(headers = frame.headers.updated("persistent", "false")))
|
|
67
|
+
|
|
68
|
+
private def message(link: StompLink): IO[(Json, IO[Unit])] =
|
|
69
|
+
link.receive.timeout(10.seconds).flatMap:
|
|
70
|
+
case Some(frame) if frame.command == "MESSAGE" =>
|
|
71
|
+
(IO.fromEither(parse(frame.body)), IO.fromOption(frame.headers.get("ack"))(
|
|
72
|
+
IllegalStateException("Missing history delivery acknowledgement"))).mapN { (body, id) =>
|
|
73
|
+
(body, link.send(StompFrame("ACK", Map("id" -> id), "")))
|
|
74
|
+
}
|
|
75
|
+
case Some(frame) => IO.raiseError(IllegalStateException(s"Unexpected history input frame ${frame.command}"))
|
|
76
|
+
case None => IO.raiseError(IllegalStateException("RabbitMQ closed the history input before the end marker"))
|
|
@@ -32,8 +32,17 @@ final class HistoryRun(profile: RuntimeProfile, writer: Option[TimelineWriter],
|
|
|
32
32
|
config.leaseUrl match
|
|
33
33
|
case None if machine.mode.isDefined && !ObservationLead.ready(observationMs, segmentEndMs, leader) =>
|
|
34
34
|
Stream.exec(Logger[IO].info(s"classifier waiting for telemetry on ${machine.id.raw}")) ++ Stream.sleep_[IO](5.seconds) ++ gated(config, machine, aliases, sender, api, observationMs, segmentEndMs)
|
|
35
|
-
case None =>
|
|
36
|
-
|
|
35
|
+
case None =>
|
|
36
|
+
follow(config, machine, aliases, sender, api, observationMs, segmentEndMs)
|
|
37
|
+
.concurrently(decisions(config, machine)).handleErrorWith(error =>
|
|
38
|
+
retry(error) ++ gated(config, machine, aliases, sender, api, observationMs, segmentEndMs))
|
|
39
|
+
case Some(url) =>
|
|
40
|
+
once(url, config, machine, aliases, sender, api).handleErrorWith(retry) ++
|
|
41
|
+
Stream.eval(IO.unit).flatMap(_ => gated(config, machine, aliases, sender, api, observationMs, segmentEndMs))
|
|
42
|
+
|
|
43
|
+
private def retry(error: Throwable): Stream[IO, Unit] =
|
|
44
|
+
Stream.exec(Logger[IO].warn(error)("Classification interrupted; waiting for unconfirmed input")) ++
|
|
45
|
+
Stream.sleep_[IO](1.second)
|
|
37
46
|
|
|
38
47
|
private def once(url: String, config: AppConfig, machine: scada.processing.core.MachineConfig, aliases: List[AliasMapping], sender: Option[StompSender], api: CheckpointApiConfig): Stream[IO, Unit] =
|
|
39
48
|
Stream.resource(WriterLease.open(url, machine.id.raw)).flatMap: hold =>
|
|
@@ -44,7 +53,7 @@ final class HistoryRun(profile: RuntimeProfile, writer: Option[TimelineWriter],
|
|
|
44
53
|
else
|
|
45
54
|
val database = hold.generation.map(token =>
|
|
46
55
|
WorkerDatabase(doobie.Transactor.fromConnection[IO](hold.connection, None), token))
|
|
47
|
-
amqp(config, machine, aliases, rows, end, grant, database)
|
|
56
|
+
amqp(config, machine, aliases, rows, end, grant, database, Some((from, until) => hold.phasesBetween(machine.id.raw, from, until)))
|
|
48
57
|
|
|
49
58
|
private def follow(config: AppConfig, machine: scada.processing.core.MachineConfig, aliases: List[AliasMapping], sender: Option[StompSender], api: CheckpointApiConfig, observationMs: Long, segmentEndMs: Option[Long], grant: Option[LeaseGrant] = None): Stream[IO, Unit] =
|
|
50
59
|
if machine.mode.isEmpty then amqp(config, machine, aliases, Vector.empty, segmentEndMs, grant)
|
|
@@ -54,23 +63,28 @@ final class HistoryRun(profile: RuntimeProfile, writer: Option[TimelineWriter],
|
|
|
54
63
|
|
|
55
64
|
private def custom(config: AppConfig, machine: scada.processing.core.MachineConfig, aliases: List[AliasMapping], sender: Option[StompSender], api: CheckpointApiConfig, observationMs: Long, segmentEndMs: Option[Long], grant: Option[LeaseGrant] = None): Stream[IO, Unit] =
|
|
56
65
|
val announce = HistoryBus.lead(sender, config, machine.id, observationMs, segmentEndMs, grant)
|
|
57
|
-
profile.history(machine, aliases, api, announce, grant.filter(_.held).map(_.generation)
|
|
66
|
+
profile.history(machine, aliases, api, announce, grant.filter(_.held).map(_.generation),
|
|
67
|
+
HistoryInput.rabbit(config.connectivity.rabbitmq))
|
|
58
68
|
|
|
59
69
|
private def amqp(config: AppConfig, machine: scada.processing.core.MachineConfig,
|
|
60
70
|
aliases: List[AliasMapping], seed: Vector[Json], segmentEndMs: Option[Long],
|
|
61
|
-
grant: Option[LeaseGrant], database: Option[WorkerDatabase] = None): Stream[IO, Unit] =
|
|
71
|
+
grant: Option[LeaseGrant], database: Option[WorkerDatabase] = None, readStored: Option[(Long, Long) => IO[Vector[Json]]] = None): Stream[IO, Unit] =
|
|
62
72
|
val leader = ObservationLead.leading(config.writerRole, config.leaseUrl)
|
|
63
73
|
val queue = s"scada.classify.${machine.id.raw}"
|
|
64
74
|
val input = ClassifyQueue(config.connectivity.rabbitmq, queue, aliases).subscribeDurable
|
|
65
75
|
val write = writer.getOrElse(throw IllegalStateException("Historical classification requires a timeline writer"))
|
|
66
76
|
val owner = grant.filter(_.held).map(_.generation)
|
|
67
|
-
val ports = ClassifyPorts(_ => IO.unit, (rows,
|
|
68
|
-
|
|
69
|
-
approved.traverse_ { row =>
|
|
77
|
+
val ports = ClassifyPorts(_ => IO.unit, (rows, _) =>
|
|
78
|
+
rows.traverse_ { row =>
|
|
70
79
|
val message = if row.hcursor.get[String]("type").contains("split-family") then row else HistoryBus.message(machine.id, row)
|
|
71
80
|
write.applyMessage(machine.id.raw, message, TimelineWriter.identity(None, message), owner,
|
|
72
81
|
config.connectivity.rabbitmq.destinations.segments)
|
|
73
|
-
}
|
|
82
|
+
},
|
|
83
|
+
timeline = (from, until) => write.readRevision(machine.id.raw).flatMap: revision =>
|
|
84
|
+
readStored.fold(IO.pure(seed))(_(from, until)).map(rows => Some(TimelineSnapshot(revision, rows))),
|
|
85
|
+
atRevision = (revision, action) => revision.fold(write.atRevision(machine.id.raw)(action))(
|
|
86
|
+
expected => write.atExpectedRevision(machine.id.raw, expected)(action)),
|
|
87
|
+
admit = (rows, historical) => ClassifyBus.allowed(segmentEndMs, leader, historical)(rows)
|
|
74
88
|
)
|
|
75
89
|
Stream.eval(Logger[IO].info(s"consuming AMQP classify queue $queue")) >> Stream.eval(ClassifyStreams.open(machine, seed, ports, segmentEndMs, database)).flatMap(_.consumeDurable(input))
|
|
76
90
|
|
|
@@ -78,8 +92,10 @@ object ClassifyBus:
|
|
|
78
92
|
def publish(segmentEndMs: Option[Long], leader: Boolean, historical: Boolean = false)(rows: Vector[Json])(
|
|
79
93
|
write: Vector[Json] => IO[Unit]
|
|
80
94
|
): IO[Unit] =
|
|
81
|
-
|
|
82
|
-
|
|
95
|
+
IO.whenA(allowed(segmentEndMs, leader, historical)(rows))(write(rows))
|
|
96
|
+
|
|
97
|
+
def allowed(segmentEndMs: Option[Long], leader: Boolean, historical: Boolean)(rows: Vector[Json]): Boolean =
|
|
98
|
+
historical || ObservationLead.ready(horizon(rows), segmentEndMs, leader)
|
|
83
99
|
|
|
84
100
|
private def horizon(rows: Vector[Json]): Long =
|
|
85
101
|
val ends = rows.flatMap: row =>
|
|
@@ -13,7 +13,6 @@ import java.nio.charset.StandardCharsets
|
|
|
13
13
|
import java.security.MessageDigest
|
|
14
14
|
import java.time.Instant
|
|
15
15
|
import java.util.HexFormat
|
|
16
|
-
import scada.stream.replay.{Replay, ReplayFailure, ReplayInput, ReplayManifest, ReplayRange, ReplaySeed}
|
|
17
16
|
import io.yarkivaev.streamworker.{ProcessingError, Processor, StepResult}
|
|
18
17
|
import scada.processing.core.*
|
|
19
18
|
import io.yarkivaev.segmentation.ObservedSegmentation.{Sample, State, segment}
|
|
@@ -35,46 +34,29 @@ object LocalHistory:
|
|
|
35
34
|
continuity: Vector[HistoryRange] = Vector.empty): Vector[HistorySegment] =
|
|
36
35
|
ObservedSegmentation(machine.segments, machine.window, continuity).run(grouped(points), seed)
|
|
37
36
|
|
|
38
|
-
private[runtime] final case class
|
|
37
|
+
private[runtime] final case class Calculated(segments: Vector[HistorySegment], state: Option[HistoryState])
|
|
38
|
+
|
|
39
|
+
private given io.circe.Codec.AsObject[Sample] = io.circe.generic.semiauto.deriveCodec
|
|
39
40
|
|
|
40
41
|
private def grouped(points: Vector[Observation]): Vector[Sample] =
|
|
41
42
|
points.groupBy(_.time).toVector.sortBy(_._1).map: (time, group) =>
|
|
42
43
|
Sample(time, group.map(p => p.channel -> p.value).toMap)
|
|
43
44
|
|
|
44
|
-
private def
|
|
45
|
-
|
|
45
|
+
private[runtime] def classifyQueued(
|
|
46
|
+
input: HistoryInput, machine: MachineConfig, points: Vector[Observation],
|
|
47
|
+
seed: Option[HistorySeed] = None, continuity: Vector[HistoryRange] = Vector.empty
|
|
48
|
+
): IO[Calculated] =
|
|
49
|
+
val classifier = ObservedSegmentation(machine.segments, machine.window, continuity)
|
|
50
|
+
val processor = new Processor[Unit, State, Sample, HistorySegment]:
|
|
46
51
|
def step(config: Unit, state: State, sample: Sample)
|
|
47
52
|
: Either[ProcessingError, StepResult[State, HistorySegment]] =
|
|
48
53
|
val result = classifier.step(state, sample)
|
|
49
54
|
Right(StepResult(result.state, result.outputs))
|
|
50
|
-
|
|
51
|
-
private[runtime] def replay(
|
|
52
|
-
machine: MachineConfig, points: Vector[Observation], baseRevision: String, runId: String,
|
|
53
|
-
seed: Option[HistorySeed] = None, continuity: Vector[HistoryRange] = Vector.empty
|
|
54
|
-
): IO[Replayed] = IO.defer:
|
|
55
|
-
val classifier = ObservedSegmentation(machine.segments, machine.window, continuity)
|
|
56
|
-
val initial = classifier.initial(seed)
|
|
57
55
|
val samples = grouped(points)
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
val interval = value.segment.map(row => Json.arr(row.name.asJson, row.start.asJson, row.end.asJson))
|
|
63
|
-
Json.arr(value.time.asJson, values(value.values), interval.asJson)
|
|
64
|
-
))
|
|
65
|
-
val rules = machine.segments.map(rule => Json.arr(rule.name.asJson, rule.condition.toString.asJson))
|
|
66
|
-
val ranges = continuity.map(range => Json.arr(range.from.asJson, range.until.asJson))
|
|
67
|
-
val rulesVersion = digest(Json.arr("observed-v1".asJson, machine.window.asJson, rules.asJson, ranges.asJson))
|
|
68
|
-
val timeline = machine.id.raw
|
|
69
|
-
val start = ReplaySeed(seedId, timeline, rulesVersion, input.id, 0, initial)
|
|
70
|
-
val manifest = ReplayManifest(timeline, ReplayRange(0, samples.size), rulesVersion, input.id, seedId, baseRevision, runId)
|
|
71
|
-
def failure(problem: ReplayFailure) = IllegalStateException(s"History page replay failed: $problem")
|
|
72
|
-
IO.fromEither(Replay.plan(manifest, input, start).leftMap(failure)).flatMap: plan =>
|
|
73
|
-
Replay.run(plan, (), processor(classifier)).flatMap(result => IO.fromEither(result.leftMap(failure))).map: result =>
|
|
74
|
-
val terminal = result.terminalState
|
|
75
|
-
val tail = terminal.segment.map(segment)
|
|
76
|
-
val state = samples.lastOption.map(last => HistoryState(last.time, terminal.parameters, tail))
|
|
77
|
-
Replayed(result.outputs.map(_.value) ++ tail, state)
|
|
56
|
+
input.run(processor, (), classifier.initial(seed), samples).map: result =>
|
|
57
|
+
val tail = result.state.segment.map(segment)
|
|
58
|
+
val state = samples.lastOption.map(last => HistoryState(last.time, result.state.parameters, tail))
|
|
59
|
+
Calculated(result.outputs ++ tail, state)
|
|
78
60
|
|
|
79
61
|
private def digest(value: Json): String =
|
|
80
62
|
val text = Printer.noSpaces.copy(sortKeys = true).print(value)
|
|
@@ -203,6 +185,7 @@ object LocalHistory:
|
|
|
203
185
|
final class LocalHistory(
|
|
204
186
|
config: CheckpointApiConfig,
|
|
205
187
|
machine: MachineConfig,
|
|
188
|
+
input: HistoryInput,
|
|
206
189
|
announce: Vector[Json] => IO[Unit] = _ => IO.unit,
|
|
207
190
|
generation: Option[Long] = None
|
|
208
191
|
):
|
|
@@ -270,8 +253,8 @@ final class LocalHistory(
|
|
|
270
253
|
from <- row.hcursor.get[Long]("from").toOption
|
|
271
254
|
until <- row.hcursor.get[Long]("until").toOption
|
|
272
255
|
yield HistoryRange(from,until)
|
|
273
|
-
LocalHistory.contextRevision(context)
|
|
274
|
-
LocalHistory.
|
|
256
|
+
LocalHistory.contextRevision(context) *>
|
|
257
|
+
LocalHistory.classifyQueued(input, machine, points, seed, continuity)
|
|
275
258
|
.flatTap(result => calculated.set(result.state)).map(_.segments)
|
|
276
259
|
def commit(work: Work, result: Vector[HistorySegment]): IO[Unit] =
|
|
277
260
|
snapshot.get.flatMap: context =>
|
|
@@ -283,7 +266,7 @@ final class LocalHistory(
|
|
|
283
266
|
)).deepMerge(LocalHistory.commitFence(machine.id, id, token, generation))
|
|
284
267
|
val payload = Json.obj("machine" -> Json.fromString(machine.id.raw), "workId" -> Json.fromString(id),
|
|
285
268
|
"segments" -> Json.arr(rows*), "context" -> claim)
|
|
286
|
-
|
|
269
|
+
transport.commitHistory(payload).flatMap: response =>
|
|
287
270
|
if response.hcursor.get[Boolean]("applied").contains(true) then announce(rows)
|
|
288
271
|
else calculated.set(None)
|
|
289
272
|
// The receiver owns work retirement. Unavailable context yields no verified proposal.
|
|
@@ -24,7 +24,7 @@ trait RuntimeProfile:
|
|
|
24
24
|
checkpoint: Option[Checkpoint], seeding: Option[Seeding], outputs: Option[OutputScope], database: Option[WorkerDatabase]): Option[Stream[IO, Unit]] = None
|
|
25
25
|
def decisions(config: AppConfig, machine: MachineConfig, segments: Segments[IO]): Stream[IO, Unit] = Stream.empty
|
|
26
26
|
def history(machine: MachineConfig, aliases: List[AliasMapping], api: CheckpointApiConfig,
|
|
27
|
-
announce: Vector[Json] => IO[Unit], generation: Option[Long]): Stream[IO, Unit] =
|
|
27
|
+
announce: Vector[Json] => IO[Unit], generation: Option[Long], input: HistoryInput): Stream[IO, Unit] =
|
|
28
28
|
Stream.raiseError[IO](IllegalArgumentException(s"Unsupported history mode for ${machine.id.raw}"))
|
|
29
29
|
|
|
30
30
|
object RuntimeProfile:
|
|
@@ -22,12 +22,13 @@ final class TimelineWriter private (
|
|
|
22
22
|
def atRevision[A](machine: String)(prepareAndWrite: IO[A]): IO[A] =
|
|
23
23
|
revisionScope.get.flatMap:
|
|
24
24
|
case Some((active, _)) if active == machine => prepareAndWrite
|
|
25
|
-
case
|
|
26
|
-
readRevision(machine).
|
|
27
|
-
revisionScope.set(Some((machine, revision))) *> prepareAndWrite
|
|
28
|
-
)(_ => revisionScope.set(previous))
|
|
25
|
+
case _ =>
|
|
26
|
+
readRevision(machine).flatMap(revision => atExpectedRevision(machine, revision)(prepareAndWrite))
|
|
29
27
|
|
|
30
|
-
private def
|
|
28
|
+
private[runtime] def atExpectedRevision[A](machine: String, revision: String)(action: IO[A]): IO[A] =
|
|
29
|
+
revisionScope.get.bracket(_ => revisionScope.set(Some((machine, revision))) *> action)(revisionScope.set)
|
|
30
|
+
|
|
31
|
+
private[runtime] def readRevision(machine: String): IO[String] =
|
|
31
32
|
val encoded = URLEncoder.encode(machine, UTF_8)
|
|
32
33
|
api.request("GET", s"/v1/history/live-revision?machine=$encoded")
|
|
33
34
|
.flatMap(value => IO.fromEither(value.hcursor.get[String]("revision")))
|
|
@@ -57,7 +58,9 @@ final class TimelineWriter private (
|
|
|
57
58
|
_ <- IO.raiseUnless(answer.hcursor.get[Boolean]("applied").contains(true))(
|
|
58
59
|
IllegalStateException(s"Timeline sink did not confirm output $outputId"))
|
|
59
60
|
after <- IO.fromEither(answer.hcursor.get[String]("revision"))
|
|
60
|
-
|
|
61
|
+
// An idempotent retry may return the original receipt, whose revision predates this scope.
|
|
62
|
+
next <- IO(BigInt(revision).max(BigInt(after)).toString)
|
|
63
|
+
_ <- revisionScope.set(Some((machine, next)))
|
|
61
64
|
_ <- (relay, destination) match
|
|
62
65
|
case (Some(sender), Some(path)) =>
|
|
63
66
|
val committed = payload.deepMerge(Json.obj("committedOutputId" -> outputId.asJson))
|
|
@@ -13,7 +13,9 @@ import java.sql.{Connection, DriverManager}
|
|
|
13
13
|
*/
|
|
14
14
|
object WriterLease:
|
|
15
15
|
val tailSql: String = "SELECT COALESCE((EXTRACT(EPOCH FROM max(end_time)) * 1000)::bigint, 0) FROM segments WHERE machine = ? AND kind = 'phase'"
|
|
16
|
-
val
|
|
16
|
+
private val phasesSql = "SELECT kind,name,start_time,end_time,duration,options,tags,properties,resolved,consumed FROM segments WHERE machine = ? AND kind = 'phase'"
|
|
17
|
+
val listSql: String = phasesSql + " ORDER BY start_time"
|
|
18
|
+
private[runtime] val rangeSql = phasesSql + " AND start_time <= ? AND end_time >= ? ORDER BY start_time"
|
|
17
19
|
private[runtime] def row(result: java.sql.ResultSet): io.circe.Json =
|
|
18
20
|
import io.circe.Json
|
|
19
21
|
def field(name: String): Json =
|
|
@@ -209,10 +211,17 @@ final case class LeaseHold(held: Boolean, connection: Connection, generation: Op
|
|
|
209
211
|
if rows.next() then rows.getLong(1) else 0L
|
|
210
212
|
finally statement.close()
|
|
211
213
|
|
|
212
|
-
private def
|
|
213
|
-
|
|
214
|
+
private[runtime] def phasesBetween(machine: String, from: Long, until: Long): IO[Vector[io.circe.Json]] =
|
|
215
|
+
IO.blocking(phases(machine, Some((from, until))))
|
|
216
|
+
|
|
217
|
+
private def phases(machine: String, range: Option[(Long, Long)] = None): Vector[io.circe.Json] =
|
|
218
|
+
val statement = connection.prepareStatement(range.fold(WriterLease.listSql)(_ => WriterLease.rangeSql))
|
|
214
219
|
try
|
|
215
220
|
statement.setString(1, machine)
|
|
221
|
+
range.foreach { (from, until) =>
|
|
222
|
+
statement.setTimestamp(2, java.sql.Timestamp.from(java.time.Instant.ofEpochMilli(until)))
|
|
223
|
+
statement.setTimestamp(3, java.sql.Timestamp.from(java.time.Instant.ofEpochMilli(from)))
|
|
224
|
+
}
|
|
216
225
|
val result = statement.executeQuery()
|
|
217
226
|
val buffer = Vector.newBuilder[io.circe.Json]
|
|
218
227
|
while result.next() do buffer += WriterLease.row(result)
|
|
@@ -1,149 +0,0 @@
|
|
|
1
|
-
package scada.stream.replay
|
|
2
|
-
|
|
3
|
-
import cats.effect.IO
|
|
4
|
-
import cats.syntax.all.*
|
|
5
|
-
import fs2.Stream
|
|
6
|
-
import io.yarkivaev.streamworker.{ProcessingError, Processor}
|
|
7
|
-
|
|
8
|
-
/** A half-open range of offsets in the input snapshot. */
|
|
9
|
-
final case class ReplayRange(from: Int, until: Int)
|
|
10
|
-
|
|
11
|
-
/** The adapter assigns an identity that uniquely names this immutable, ordered event vector.
|
|
12
|
-
* Event timestamps need not be unique because replay positions are vector offsets.
|
|
13
|
-
*/
|
|
14
|
-
final case class ReplayInput[I](id: String, events: Vector[I])
|
|
15
|
-
|
|
16
|
-
final case class ReplayManifest(
|
|
17
|
-
timeline: String,
|
|
18
|
-
range: ReplayRange,
|
|
19
|
-
rulesVersion: String,
|
|
20
|
-
inputId: String,
|
|
21
|
-
initialSeedId: String,
|
|
22
|
-
baseRevision: String,
|
|
23
|
-
runId: String
|
|
24
|
-
)
|
|
25
|
-
|
|
26
|
-
/** State immediately before the event at position. */
|
|
27
|
-
final case class ReplaySeed[+S](
|
|
28
|
-
id: String,
|
|
29
|
-
timeline: String,
|
|
30
|
-
rulesVersion: String,
|
|
31
|
-
inputId: String,
|
|
32
|
-
position: Int,
|
|
33
|
-
state: S
|
|
34
|
-
)
|
|
35
|
-
|
|
36
|
-
final case class ReplayOutput[O](position: Int, ordinal: Int, value: O)
|
|
37
|
-
|
|
38
|
-
final case class ReplayResult[S, O](
|
|
39
|
-
manifest: ReplayManifest,
|
|
40
|
-
outputs: Vector[ReplayOutput[O]],
|
|
41
|
-
terminalState: S
|
|
42
|
-
)
|
|
43
|
-
|
|
44
|
-
enum ReplayFailure:
|
|
45
|
-
case InvalidManifest(reason: String)
|
|
46
|
-
case InvalidSections
|
|
47
|
-
case BoundaryMismatch(position: Int)
|
|
48
|
-
case ProcessingFailed(position: Int, error: ProcessingError)
|
|
49
|
-
|
|
50
|
-
final class ReplayPlan[I, S] private[replay] (
|
|
51
|
-
val manifest: ReplayManifest,
|
|
52
|
-
private[replay] val input: ReplayInput[I],
|
|
53
|
-
private[replay] val sections: Vector[(ReplayRange, ReplaySeed[S])]
|
|
54
|
-
):
|
|
55
|
-
def ranges: Vector[ReplayRange] = sections.map(_._1)
|
|
56
|
-
|
|
57
|
-
private[replay] final case class SectionResult[I, S, O](
|
|
58
|
-
plan: ReplayPlan[I, S],
|
|
59
|
-
range: ReplayRange,
|
|
60
|
-
outputs: Vector[ReplayOutput[O]],
|
|
61
|
-
terminalState: S
|
|
62
|
-
)
|
|
63
|
-
|
|
64
|
-
object Replay:
|
|
65
|
-
def plan[I, S](
|
|
66
|
-
manifest: ReplayManifest,
|
|
67
|
-
input: ReplayInput[I],
|
|
68
|
-
initial: ReplaySeed[S],
|
|
69
|
-
cuts: Set[Int] = Set.empty,
|
|
70
|
-
boundarySeeds: Vector[ReplaySeed[S]] = Vector.empty
|
|
71
|
-
): Either[ReplayFailure, ReplayPlan[I, S]] =
|
|
72
|
-
val range = manifest.range
|
|
73
|
-
def compatible(seed: ReplaySeed[S]): Boolean =
|
|
74
|
-
seed.timeline == manifest.timeline && seed.rulesVersion == manifest.rulesVersion && seed.inputId == input.id
|
|
75
|
-
|
|
76
|
-
if manifest.inputId != input.id then
|
|
77
|
-
Left(ReplayFailure.InvalidManifest("Input identity does not match the manifest"))
|
|
78
|
-
else if range.from < 0 || range.from > range.until || range.until > input.events.size then
|
|
79
|
-
Left(ReplayFailure.InvalidManifest("Replay range is outside the input snapshot"))
|
|
80
|
-
else if !compatible(initial) || initial.id != manifest.initialSeedId || initial.position != range.from then
|
|
81
|
-
Left(ReplayFailure.InvalidManifest("Initial seed does not match the manifest"))
|
|
82
|
-
else if cuts.exists(position => position < range.from || position > range.until) then
|
|
83
|
-
Left(ReplayFailure.InvalidManifest("Section cut is outside the replay range"))
|
|
84
|
-
else
|
|
85
|
-
val boundaries = boundarySeeds.filter: seed =>
|
|
86
|
-
compatible(seed) && cuts(seed.position) && seed.position > range.from && seed.position < range.until
|
|
87
|
-
// A cut without a unique compatible seed stays in the preceding section.
|
|
88
|
-
val seededCuts = boundaries.groupBy(_.position).values.collect:
|
|
89
|
-
case Vector(seed) => seed
|
|
90
|
-
val starts = initial +: seededCuts.toVector.sortBy(_.position)
|
|
91
|
-
val ends = starts.tail.map(_.position) :+ range.until
|
|
92
|
-
val sections = starts.zip(ends).map: (seed, until) =>
|
|
93
|
-
ReplayRange(seed.position, until) -> seed
|
|
94
|
-
Right(new ReplayPlan(manifest, input, sections))
|
|
95
|
-
|
|
96
|
-
/** Returns a proposal after every section succeeds and all boundaries agree.
|
|
97
|
-
* The processor, versioned configuration, input, and states must be deterministic and
|
|
98
|
-
* immutable. State equality must compare every value that can affect a later step.
|
|
99
|
-
*/
|
|
100
|
-
def run[C, S, I, O](
|
|
101
|
-
plan: ReplayPlan[I, S],
|
|
102
|
-
config: C,
|
|
103
|
-
processor: Processor[C, S, I, O],
|
|
104
|
-
parallelism: Int = 1
|
|
105
|
-
): IO[Either[ReplayFailure, ReplayResult[S, O]]] =
|
|
106
|
-
if parallelism < 1 then IO.pure(Left(ReplayFailure.InvalidManifest("Parallelism must be positive")))
|
|
107
|
-
else
|
|
108
|
-
Stream.emits(plan.ranges).covary[IO]
|
|
109
|
-
.parEvalMap(parallelism)(range => runSection(plan, range, config, processor))
|
|
110
|
-
.compile.toVector
|
|
111
|
-
.map(_.sequence.flatMap(results => gather(plan, results)))
|
|
112
|
-
|
|
113
|
-
private[replay] def runSection[C, S, I, O](
|
|
114
|
-
plan: ReplayPlan[I, S],
|
|
115
|
-
range: ReplayRange,
|
|
116
|
-
config: C,
|
|
117
|
-
processor: Processor[C, S, I, O]
|
|
118
|
-
): IO[Either[ReplayFailure, SectionResult[I, S, O]]] =
|
|
119
|
-
plan.sections.find(_._1 == range) match
|
|
120
|
-
case None => IO.pure(Left(ReplayFailure.InvalidSections))
|
|
121
|
-
case Some((_, seed)) =>
|
|
122
|
-
IO.defer:
|
|
123
|
-
val outputs = Vector.newBuilder[ReplayOutput[O]]
|
|
124
|
-
def advance(position: Int, state: S): IO[Either[ReplayFailure, SectionResult[I, S, O]]] =
|
|
125
|
-
if position == range.until then
|
|
126
|
-
IO.pure(Right(SectionResult(plan, range, outputs.result(), state)))
|
|
127
|
-
else
|
|
128
|
-
IO.defer:
|
|
129
|
-
processor.step(config, state, plan.input.events(position)) match
|
|
130
|
-
case Left(error) => IO.pure(Left(ReplayFailure.ProcessingFailed(position, error)))
|
|
131
|
-
case Right(result) =>
|
|
132
|
-
outputs ++= result.outputs.iterator.zipWithIndex.map: (value, ordinal) =>
|
|
133
|
-
ReplayOutput(position, ordinal, value)
|
|
134
|
-
advance(position + 1, result.state)
|
|
135
|
-
advance(range.from, seed.state)
|
|
136
|
-
|
|
137
|
-
private[replay] def gather[I, S, O](
|
|
138
|
-
plan: ReplayPlan[I, S],
|
|
139
|
-
results: Vector[SectionResult[I, S, O]]
|
|
140
|
-
): Either[ReplayFailure, ReplayResult[S, O]] =
|
|
141
|
-
val ordered = results.sortBy(_.range.from)
|
|
142
|
-
if ordered.map(_.range) != plan.ranges || ordered.exists(result => result.plan ne plan) then
|
|
143
|
-
Left(ReplayFailure.InvalidSections)
|
|
144
|
-
else
|
|
145
|
-
val mismatched = ordered.zip(plan.sections.drop(1)).collectFirst:
|
|
146
|
-
case (result, (range, seed)) if result.terminalState != seed.state => range.from
|
|
147
|
-
mismatched match
|
|
148
|
-
case Some(position) => Left(ReplayFailure.BoundaryMismatch(position))
|
|
149
|
-
case None => Right(ReplayResult(plan.manifest, ordered.flatMap(_.outputs), ordered.last.terminalState))
|