@yarkivaev/scada 2.6.40 → 2.6.42
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -768
- package/db/migrations/E0018__stream_worker_checkpoint.sql +9 -0
- package/package.json +3 -1
- package/src/infrastructure/streams/README.md +12 -5
- package/supervisor-engine/src/main/scala/scada/stream/replay/Replay.scala +149 -0
- package/supervisor-engine/src/main/scala/scada/stream/worker/Processor.scala +8 -0
- package/supervisor-engine/src/main/scala/scada/stream/worker/StreamWorker.scala +119 -0
- package/supervisor-engine/src/main/scala/scada/stream/worker/postgres/PgCheckpointStore.scala +83 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Condition.scala +33 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/CyclePhases.scala +65 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Decision.scala +67 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Emission.scala +19 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/MachineConfig.scala +21 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/MachineId.scala +18 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/MachineMode.scala +4 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Params.scala +15 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Reading.scala +11 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Segment.scala +28 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/SegmentDef.scala +14 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Segmentation.scala +52 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Segments.scala +41 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/SplitFollow.scala +50 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/SplitPieces.scala +102 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Supervisor.scala +66 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/TagDef.scala +12 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/TaggedSegment.scala +19 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Tagging.scala +42 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Timestamp.scala +26 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/segmentation/Timeline.scala +43 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/checkpoint/Checkpoint.scala +61 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/checkpoint/ClickhouseReadingsCheckpoint.scala +76 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/checkpoint/SupervisorSinkCheckpoint.scala +141 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/config/AppConfig.scala +132 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/config/ConfigLoad.scala +202 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/config/ConfigProfile.scala +13 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/mqtt/Mqtt.scala +92 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/mqtt/Sessions.scala +18 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/state/AtomicStateFile.scala +24 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/state/CheckpointSegments.scala +59 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/state/SegmentStatePolicy.scala +18 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/state/Segments.scala +91 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/ClassifyQueue.scala +37 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/DecisionMessage.scala +49 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/DurableStomp.scala +27 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/SegmentMessage.scala +57 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/SegmentWirePolicy.scala +18 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/SplitFamily.scala +39 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompConnection.scala +106 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompDecisions.scala +43 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompFrame.scala +67 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompMachineDecisions.scala +16 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompQueue.scala +30 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompReadings.scala +29 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompSegments.scala +115 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ClassifierCursors.scala +58 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ClassifyHistory.scala +92 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ClassifyStreams.scala +67 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/Close.scala +23 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/EngineApp.scala +4 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/HealthServer.scala +38 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/HistoryBus.scala +67 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/HistoryClient.scala +23 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/HistoryRun.scala +86 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/LocalHistory.scala +258 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ObservationLead.scala +26 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/Orphans.scala +26 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/PendingIsland.scala +37 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/RuntimeProfile.scala +32 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/Seeding.scala +105 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/SupervisorRuntime.scala +266 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/WriterEpoch.scala +16 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/WriterGate.scala +35 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/WriterLease.scala +218 -0
- package/supervisor-engine/vendor/gaps-and-islands/LICENSE +21 -0
- package/supervisor-engine/vendor/gaps-and-islands/UPSTREAM +4 -0
- package/supervisor-engine/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/Island.scala +40 -0
- package/supervisor-engine/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandEvent.scala +55 -0
- package/supervisor-engine/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandsFlow.scala +127 -0
- package/supervisor-engine/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandsPolicy.scala +105 -0
- package/supervisor-engine/vendor/temporal-streams/LICENSE +21 -0
- package/supervisor-engine/vendor/temporal-streams/UPSTREAM +3 -0
- package/supervisor-engine/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/History.scala +30 -0
- package/supervisor-engine/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/LocalStreams.scala +27 -0
- package/supervisor-engine/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/Overlay.scala +15 -0
- package/supervisor-engine/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/Worker.scala +21 -0
package/supervisor-engine/src/main/scala/scada/supervisor/infra/state/CheckpointSegments.scala
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
package scada.supervisor.infra.state
|
|
2
|
+
|
|
3
|
+
import cats.effect.IO
|
|
4
|
+
import cats.syntax.all.*
|
|
5
|
+
import scada.supervisor.core.*
|
|
6
|
+
import scada.supervisor.core.Segments as CoreSegments
|
|
7
|
+
import scada.supervisor.infra.checkpoint.Checkpoint
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* [[CoreSegments]] decorator that falls back to checkpoint API when
|
|
11
|
+
* the in-memory store misses one segment row. Legacy `list` stays in memory.
|
|
12
|
+
* History-mode decision reads may prefer checkpoint snapshots, refreshing exact
|
|
13
|
+
* cached keys through an injected port. Lists refresh already-known sibling keys;
|
|
14
|
+
* this decorator does not download or discover the complete historical family.
|
|
15
|
+
* A segment write must not download machine history: the site paints
|
|
16
|
+
* shutdown reasons on read.
|
|
17
|
+
*
|
|
18
|
+
* {{{
|
|
19
|
+
* CheckpointSegments(StateSegments(ref), checkpoint)
|
|
20
|
+
* }}}
|
|
21
|
+
*/
|
|
22
|
+
final class CheckpointSegments(
|
|
23
|
+
underlying: CoreSegments[IO],
|
|
24
|
+
checkpoint: Checkpoint,
|
|
25
|
+
preferCheckpoint: Boolean = false,
|
|
26
|
+
refreshCache: Option[(MachineId,Timestamp,Option[TaggedSegment]) => IO[Unit]] = None
|
|
27
|
+
) extends CoreSegments[IO]:
|
|
28
|
+
require(!preferCheckpoint || refreshCache.isDefined,"Checkpoint-first decisions require an exact cache refresh port")
|
|
29
|
+
|
|
30
|
+
def find(machine: MachineId, start: Timestamp): IO[Option[TaggedSegment]] =
|
|
31
|
+
if preferCheckpoint then checkpoint.fetchSegment(machine,start).flatTap(row => refreshCache.get(machine,start,row))
|
|
32
|
+
else underlying.find(machine, start).flatMap:
|
|
33
|
+
case some @ Some(_) => IO.pure(some)
|
|
34
|
+
case None =>
|
|
35
|
+
checkpoint.fetchSegment(machine, start).flatMap:
|
|
36
|
+
case None => IO.pure(None)
|
|
37
|
+
case Some(segment) =>
|
|
38
|
+
underlying.upsert(machine, segment).as(Some(segment))
|
|
39
|
+
|
|
40
|
+
def list(machine: MachineId): IO[List[TaggedSegment]] =
|
|
41
|
+
if preferCheckpoint then underlying.list(machine).flatMap(_.traverse(row => find(machine,row.segment.start)).map(_.flatten))
|
|
42
|
+
else underlying.list(machine)
|
|
43
|
+
|
|
44
|
+
def upsert(machine: MachineId, segment: TaggedSegment): IO[Unit] =
|
|
45
|
+
underlying.upsert(machine, segment)
|
|
46
|
+
|
|
47
|
+
def replace(machine: MachineId, from: Timestamp, to: Timestamp, segments: List[TaggedSegment]): IO[Unit] =
|
|
48
|
+
underlying.replace(machine, from, to, segments)
|
|
49
|
+
|
|
50
|
+
def resolve(
|
|
51
|
+
machine: MachineId,
|
|
52
|
+
original: Segment,
|
|
53
|
+
tags: List[String],
|
|
54
|
+
options: List[String],
|
|
55
|
+
properties: Map[String, String]
|
|
56
|
+
): IO[Unit] =
|
|
57
|
+
find(machine, original.start).flatMap:
|
|
58
|
+
case None => IO.unit
|
|
59
|
+
case Some(fresh) => underlying.resolve(machine, if preferCheckpoint then fresh.segment else original, tags, options, properties)
|
package/supervisor-engine/src/main/scala/scada/supervisor/infra/state/SegmentStatePolicy.scala
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
package scada.supervisor.infra.state
|
|
2
|
+
|
|
3
|
+
import scada.supervisor.core.TaggedSegment
|
|
4
|
+
|
|
5
|
+
/** Preserves or replaces operator annotations when a segment is updated. */
|
|
6
|
+
trait SegmentStatePolicy:
|
|
7
|
+
def merge(existing: TaggedSegment, incoming: TaggedSegment): TaggedSegment =
|
|
8
|
+
if incoming.tags.isEmpty && incoming.properties.isEmpty then
|
|
9
|
+
val options = if existing.tags.nonEmpty then existing.options else incoming.options
|
|
10
|
+
TaggedSegment(incoming.segment, existing.tags, options, existing.properties)
|
|
11
|
+
else incoming
|
|
12
|
+
|
|
13
|
+
def resolve(row: TaggedSegment, tags: List[String], options: List[String], properties: Map[String, String]): Option[TaggedSegment] =
|
|
14
|
+
val kept = if options.isEmpty then row.options else options
|
|
15
|
+
Some(TaggedSegment(row.segment, tags, kept, properties))
|
|
16
|
+
|
|
17
|
+
object SegmentStatePolicy:
|
|
18
|
+
val default: SegmentStatePolicy = new SegmentStatePolicy {}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
package scada.supervisor.infra.state
|
|
2
|
+
|
|
3
|
+
import cats.Functor
|
|
4
|
+
import cats.effect.Ref
|
|
5
|
+
import cats.syntax.all.*
|
|
6
|
+
import scada.supervisor.core.*
|
|
7
|
+
import scada.supervisor.core.Segments as CoreSegments
|
|
8
|
+
import scala.collection.immutable.SortedMap
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* In-memory [[CoreSegments]] backed by a `Ref` of sorted per-machine
|
|
12
|
+
* maps keyed on `segment.start`. Upsert is idempotent on that key, so
|
|
13
|
+
* a `Started` / `Emitted` pair for the same island simply overwrites
|
|
14
|
+
* the prior row with the finalised segment. When the incoming row carries
|
|
15
|
+
* no operator tags or properties, existing markup on that start is kept;
|
|
16
|
+
* if operator tags are already set, existing options are kept too so a
|
|
17
|
+
* heartbeat cannot replace the prompt list after operator markup.
|
|
18
|
+
*
|
|
19
|
+
* [[resolve]] writes operator `tags` and `properties` on the row keyed by
|
|
20
|
+
* `original.start`. Options:
|
|
21
|
+
* - non-empty `options` → store that list (cascade next choices / leaf);
|
|
22
|
+
* - empty `options` → keep the previous options so HMI can re-edit the
|
|
23
|
+
* same prompt after a resolve that only retags the path.
|
|
24
|
+
*
|
|
25
|
+
* Caller acquires the `Ref` so the class itself stays a plain
|
|
26
|
+
* immutable constructor.
|
|
27
|
+
*
|
|
28
|
+
* {{{
|
|
29
|
+
* Ref.of[F, Map[MachineId, SortedMap[Timestamp, TaggedSegment]]](Map.empty)
|
|
30
|
+
* .map(Segments(_))
|
|
31
|
+
* segments.resolve(machine, original, tags, options, properties)
|
|
32
|
+
* }}}
|
|
33
|
+
*/
|
|
34
|
+
final class Segments[F[_]: Functor](
|
|
35
|
+
ref: Ref[F, Map[MachineId, SortedMap[Timestamp, TaggedSegment]]],
|
|
36
|
+
policy: SegmentStatePolicy = SegmentStatePolicy.default
|
|
37
|
+
) extends CoreSegments[F]:
|
|
38
|
+
|
|
39
|
+
def upsert(machine: MachineId, segment: TaggedSegment): F[Unit] =
|
|
40
|
+
ref.update: state =>
|
|
41
|
+
val machineMap = forMachine(state, machine)
|
|
42
|
+
val stored =
|
|
43
|
+
if SplitFollow.owned(machineMap.values, segment) then SplitFollow.project(machineMap, segment)
|
|
44
|
+
else
|
|
45
|
+
val merged = machineMap.get(segment.segment.start) match
|
|
46
|
+
case Some(existing) => policy.merge(existing, segment)
|
|
47
|
+
case _ =>
|
|
48
|
+
segment
|
|
49
|
+
machineMap.updated(segment.segment.start, merged)
|
|
50
|
+
state.updated(machine, stored)
|
|
51
|
+
|
|
52
|
+
/** Exact checkpoint refresh bypasses annotation-preserving upsert and never touches neighbouring keys. */
|
|
53
|
+
def refresh(machine: MachineId, start: Timestamp, row: Option[TaggedSegment]): F[Unit] =
|
|
54
|
+
ref.update: state =>
|
|
55
|
+
val current = forMachine(state,machine)
|
|
56
|
+
val refreshed = row.fold(current - start)(segment => current.updated(start,segment))
|
|
57
|
+
state.updated(machine,refreshed)
|
|
58
|
+
|
|
59
|
+
def find(machine: MachineId, start: Timestamp): F[Option[TaggedSegment]] =
|
|
60
|
+
ref.get.map(state => forMachine(state, machine).get(start))
|
|
61
|
+
|
|
62
|
+
def list(machine: MachineId): F[List[TaggedSegment]] =
|
|
63
|
+
ref.get.map(state => forMachine(state, machine).values.toList)
|
|
64
|
+
|
|
65
|
+
def replace(machine: MachineId, from: Timestamp, to: Timestamp, segments: List[TaggedSegment]): F[Unit] =
|
|
66
|
+
ref.update: state =>
|
|
67
|
+
val cleaned = forMachine(state, machine).filterNot: (_, seg) =>
|
|
68
|
+
seg.segment.start.epoch < to.epoch && seg.segment.end.epoch > from.epoch
|
|
69
|
+
state.updated(machine, segments.foldLeft(cleaned)((m, s) => m.updated(s.segment.start, s)))
|
|
70
|
+
|
|
71
|
+
def resolve(
|
|
72
|
+
machine: MachineId,
|
|
73
|
+
original: Segment,
|
|
74
|
+
tags: List[String],
|
|
75
|
+
options: List[String],
|
|
76
|
+
properties: Map[String, String]
|
|
77
|
+
): F[Unit] =
|
|
78
|
+
ref.update: state =>
|
|
79
|
+
val key = original.start
|
|
80
|
+
val updated = forMachine(state, machine).get(key) match
|
|
81
|
+
case None => forMachine(state, machine)
|
|
82
|
+
case Some(row) =>
|
|
83
|
+
val rows = forMachine(state, machine)
|
|
84
|
+
policy.resolve(row, tags, options, properties).fold(rows)(result => rows.updated(key, result))
|
|
85
|
+
state.updated(machine, updated)
|
|
86
|
+
|
|
87
|
+
private def forMachine(
|
|
88
|
+
state: Map[MachineId, SortedMap[Timestamp, TaggedSegment]],
|
|
89
|
+
machine: MachineId
|
|
90
|
+
): SortedMap[Timestamp, TaggedSegment] =
|
|
91
|
+
state.getOrElse(machine, SortedMap.empty)
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
package scada.supervisor.infra.stomp
|
|
2
|
+
|
|
3
|
+
import cats.effect.{IO, Resource}
|
|
4
|
+
import fs2.Stream
|
|
5
|
+
import io.circe.parser.parse
|
|
6
|
+
import io.yarkivaev.temporal.Observation
|
|
7
|
+
import scada.supervisor.infra.config.{AliasMapping, RabbitMqConfig}
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Durable AMQP classify queue for one machine. MQTT slash aliases match
|
|
11
|
+
* dotted routing keys. First-wins identity is the published eventId.
|
|
12
|
+
*
|
|
13
|
+
* {{{
|
|
14
|
+
* ClassifyQueue(config, "scada.classify.machine-2", aliases).subscribe
|
|
15
|
+
* }}}
|
|
16
|
+
*/
|
|
17
|
+
final class ClassifyQueue(open: Resource[IO, StompLink], queue: String, aliases: List[AliasMapping]):
|
|
18
|
+
def this(config: RabbitMqConfig, queue: String, aliases: List[AliasMapping]) =
|
|
19
|
+
this(StompConnection.open(config.address.host, config.address.port, config.vhost, config.credentials.login, config.credentials.passcode).map(connection => connection: StompLink), queue, aliases)
|
|
20
|
+
def subscribe: Stream[IO, Observation] = StompQueue(open, queue, decode).subscribe
|
|
21
|
+
private[stomp] def decode(frame: StompFrame): Option[Observation] =
|
|
22
|
+
for
|
|
23
|
+
route <- routed(frame.headers)
|
|
24
|
+
alias <- aliases.find(item => dotted(item.topic) == dotted(route))
|
|
25
|
+
json <- parse(frame.body).toOption
|
|
26
|
+
ts <- json.hcursor.get[Double]("ts").toOption.filter(n => n.isFinite && n >= 0)
|
|
27
|
+
value <- json.hcursor.get[Double]("value").toOption.filter(_.isFinite)
|
|
28
|
+
yield
|
|
29
|
+
val time = if ts > 1e10 then ts.toLong else (ts * 1000).toLong
|
|
30
|
+
val event = json.hcursor.get[String]("eventId").toOption.filter(_.nonEmpty).getOrElse(s"${alias.metric}:$time:$value")
|
|
31
|
+
Observation(event, alias.metric, time, value)
|
|
32
|
+
private def routed(headers: Map[String, String]): Option[String] =
|
|
33
|
+
val prefix = "/exchange/"
|
|
34
|
+
val dest = headers.get("destination").getOrElse("")
|
|
35
|
+
val slash = dest.indexOf('/', prefix.length)
|
|
36
|
+
headers.get("scada-route").orElse(headers.get("routing-key")).orElse(headers.get("x-routing-key")).orElse(Option.when(dest.startsWith(prefix) && slash >= 0)(dest.substring(slash + 1)).filter(_.nonEmpty))
|
|
37
|
+
private def dotted(route: String): String = route.replace('/', '.')
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
package scada.supervisor.infra.stomp
|
|
2
|
+
|
|
3
|
+
import io.circe.Json
|
|
4
|
+
import io.circe.parser.parse as parseJson
|
|
5
|
+
import scada.supervisor.core.{Decision, MachineId, SplitEntry, Timestamp}
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Inbound-wire parser for operator [[Decision]]s arriving on the
|
|
9
|
+
* STOMP `user_decisions` destination. Reads a JSON body and picks the
|
|
10
|
+
* decision variant:
|
|
11
|
+
*
|
|
12
|
+
* - presence of `splits` → [[Decision.Split]]
|
|
13
|
+
* - presence of `tags` → [[Decision.Resolve]]
|
|
14
|
+
* - otherwise → [[Decision.Skip]]
|
|
15
|
+
*
|
|
16
|
+
* Missing `machine` / `start` keys produce `None` so the consumer can
|
|
17
|
+
* drop malformed frames.
|
|
18
|
+
*
|
|
19
|
+
* {{{
|
|
20
|
+
* DecisionMessage.parse(bodyJson)
|
|
21
|
+
* }}}
|
|
22
|
+
*/
|
|
23
|
+
object DecisionMessage:
|
|
24
|
+
|
|
25
|
+
def parse(body: String): Option[Decision] =
|
|
26
|
+
parseJson(body).toOption.flatMap: json =>
|
|
27
|
+
val cursor = json.hcursor
|
|
28
|
+
val machine = cursor.downField("machine").as[String].toOption.map(MachineId(_))
|
|
29
|
+
val start = cursor.downField("start").as[Double].toOption.map(Timestamp(_))
|
|
30
|
+
(machine, start) match
|
|
31
|
+
case (Some(m), Some(s)) if cursor.downField("splits").succeeded =>
|
|
32
|
+
Some(Decision.Split(m, s, splits(cursor.downField("splits").as[List[Json]].toOption.getOrElse(Nil))))
|
|
33
|
+
case (Some(m), Some(s)) if cursor.downField("tags").succeeded =>
|
|
34
|
+
val tags = cursor.downField("tags").as[List[String]].toOption.getOrElse(Nil)
|
|
35
|
+
val props = cursor.downField("properties").as[Map[String, String]].toOption.getOrElse(Map.empty)
|
|
36
|
+
Some(Decision.Resolve(m, s, tags, props))
|
|
37
|
+
case (Some(m), Some(s)) =>
|
|
38
|
+
Some(Decision.Skip(s"${m.raw}-${s.millis}"))
|
|
39
|
+
case _ => None
|
|
40
|
+
|
|
41
|
+
private def splits(rows: List[Json]): List[SplitEntry] =
|
|
42
|
+
rows.flatMap: j =>
|
|
43
|
+
val cursor = j.hcursor
|
|
44
|
+
val open = cursor.downField("open").as[Boolean].toOption.getOrElse(false)
|
|
45
|
+
val tag = cursor.downField("tag").as[String].toOption.getOrElse("")
|
|
46
|
+
for
|
|
47
|
+
st <- cursor.downField("start").as[Double].toOption
|
|
48
|
+
en <- cursor.downField("end").as[Double].toOption.orElse(Option.when(open)(st))
|
|
49
|
+
yield SplitEntry(Timestamp(st), Timestamp(en), tag, open)
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
package scada.supervisor.infra.stomp
|
|
2
|
+
|
|
3
|
+
import cats.effect.{IO, Ref}
|
|
4
|
+
import scala.concurrent.duration.*
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* [[StompSender]] that drops a dead socket and opens a new one so
|
|
8
|
+
* segment publish survives a RabbitMQ restart.
|
|
9
|
+
*
|
|
10
|
+
* {{{
|
|
11
|
+
* DurableStomp(StompConnection.connect(...), 3, slot).send(frame)
|
|
12
|
+
* }}}
|
|
13
|
+
*/
|
|
14
|
+
final class DurableStomp(open: IO[StompSender], attempts: Int, slot: Ref[IO, Option[StompSender]]) extends StompSender:
|
|
15
|
+
|
|
16
|
+
def send(frame: StompFrame): IO[Unit] =
|
|
17
|
+
attempt(frame, attempts)
|
|
18
|
+
|
|
19
|
+
private def attempt(frame: StompFrame, left: Int): IO[Unit] =
|
|
20
|
+
ensure.flatMap(_.send(frame)).handleErrorWith: err =>
|
|
21
|
+
if left <= 1 then IO.raiseError(err)
|
|
22
|
+
else slot.set(None) *> IO.sleep(100.millis) *> attempt(frame, left - 1)
|
|
23
|
+
|
|
24
|
+
private def ensure: IO[StompSender] =
|
|
25
|
+
slot.get.flatMap:
|
|
26
|
+
case Some(sender) => IO.pure(sender)
|
|
27
|
+
case None => open.flatTap(sender => slot.set(Some(sender)))
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
package scada.supervisor.infra.stomp
|
|
2
|
+
|
|
3
|
+
import io.circe.Json
|
|
4
|
+
import io.circe.syntax.*
|
|
5
|
+
import scada.supervisor.core.{MachineId, TaggedSegment}
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Wire-format envelope for one event on the supervisor-sink channel.
|
|
9
|
+
* Knows how to render itself as JSON; STOMP publishing just treats the
|
|
10
|
+
* serialised body as an opaque payload.
|
|
11
|
+
*
|
|
12
|
+
* - `kind = "segment"` for live classification;
|
|
13
|
+
* - `kind = "retag"` for operator-resolved tags;
|
|
14
|
+
* - `kind = "split"` for operator-split segments.
|
|
15
|
+
*
|
|
16
|
+
* `status = "pending"` marks a segment still open (duration `0.0`);
|
|
17
|
+
* everything else completes with `"completed"`.
|
|
18
|
+
*
|
|
19
|
+
* {{{
|
|
20
|
+
* SegmentMessage.segment(machineId, taggedSegment).json
|
|
21
|
+
* }}}
|
|
22
|
+
*/
|
|
23
|
+
final case class SegmentMessage(kind: String, machine: MachineId, segment: TaggedSegment, status: String):
|
|
24
|
+
def json: Json = jsonWith(SegmentWirePolicy.default)
|
|
25
|
+
|
|
26
|
+
def jsonWith(policy: SegmentWirePolicy): Json =
|
|
27
|
+
val fields = List(
|
|
28
|
+
"type" -> Json.fromString(kind),
|
|
29
|
+
"status" -> Json.fromString(status),
|
|
30
|
+
"machine" -> Json.fromString(machine.raw),
|
|
31
|
+
"name" -> Json.fromString(segment.segment.name),
|
|
32
|
+
"start" -> Json.fromLong(policy.boundary(segment, segment.segment.start)),
|
|
33
|
+
"end" -> Json.fromLong(policy.boundary(segment, segment.segment.end)),
|
|
34
|
+
"duration" -> Json.fromDoubleOrNull(segment.segment.duration),
|
|
35
|
+
"tags" -> listOrNull(segment.tags),
|
|
36
|
+
"options" -> listOrNull(segment.options),
|
|
37
|
+
"properties" -> mapOrNull(segment.properties)
|
|
38
|
+
)
|
|
39
|
+
Json.obj((if policy.resolved(kind, segment) then fields :+ ("resolved" -> Json.fromBoolean(true)) else fields)*)
|
|
40
|
+
|
|
41
|
+
private def listOrNull(values: List[String]): Json =
|
|
42
|
+
if values.isEmpty then Json.Null else values.asJson
|
|
43
|
+
|
|
44
|
+
private def mapOrNull(values: Map[String, String]): Json =
|
|
45
|
+
if values.isEmpty then Json.Null else values.asJson
|
|
46
|
+
|
|
47
|
+
object SegmentMessage:
|
|
48
|
+
|
|
49
|
+
def segment(machine: MachineId, ts: TaggedSegment): SegmentMessage =
|
|
50
|
+
val status = if ts.segment.duration == 0.0 then "pending" else "completed"
|
|
51
|
+
SegmentMessage("segment", machine, ts, status)
|
|
52
|
+
|
|
53
|
+
def retag(machine: MachineId, ts: TaggedSegment): SegmentMessage =
|
|
54
|
+
SegmentMessage("retag", machine, ts, "completed")
|
|
55
|
+
|
|
56
|
+
def split(machine: MachineId, ts: TaggedSegment): SegmentMessage =
|
|
57
|
+
SegmentMessage("split", machine, ts, "completed")
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
package scada.supervisor.infra.stomp
|
|
2
|
+
|
|
3
|
+
import scada.supervisor.core.{TaggedSegment, Timestamp}
|
|
4
|
+
|
|
5
|
+
/** Controls the wire representation and publishing semantics for segment types. */
|
|
6
|
+
trait SegmentWirePolicy:
|
|
7
|
+
def boundary(row: TaggedSegment, time: Timestamp): Long = time.millis
|
|
8
|
+
|
|
9
|
+
def resolved(kind: String, row: TaggedSegment): Boolean =
|
|
10
|
+
kind == "retag" || kind == "split" || row.tags.nonEmpty
|
|
11
|
+
|
|
12
|
+
def confirmed(row: TaggedSegment): Boolean = false
|
|
13
|
+
def splitBeforeSegment(row: TaggedSegment): Boolean = false
|
|
14
|
+
def bypassHeartbeatThrottle(row: TaggedSegment): Boolean = false
|
|
15
|
+
def atomicTransition: Boolean = false
|
|
16
|
+
|
|
17
|
+
object SegmentWirePolicy:
|
|
18
|
+
val default: SegmentWirePolicy = new SegmentWirePolicy {}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
package scada.supervisor.infra.stomp
|
|
2
|
+
|
|
3
|
+
import io.circe.Json
|
|
4
|
+
import io.circe.syntax.*
|
|
5
|
+
import scada.supervisor.core.{MachineId, TaggedSegment, Timestamp}
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* One STOMP body that replaces a whole split family. The sink applies
|
|
9
|
+
* it in a single transaction so a boundary edit cannot leave the
|
|
10
|
+
* previous intermediate rows on the timeline.
|
|
11
|
+
*
|
|
12
|
+
* {{{
|
|
13
|
+
* SplitFamily.json(machine, origin, pieces)
|
|
14
|
+
* }}}
|
|
15
|
+
*/
|
|
16
|
+
object SplitFamily:
|
|
17
|
+
def json(machine: MachineId, origin: Timestamp, pieces: List[TaggedSegment]): String =
|
|
18
|
+
val rows = pieces.map: piece =>
|
|
19
|
+
Json.obj(
|
|
20
|
+
"name" -> Json.fromString(piece.segment.name),
|
|
21
|
+
"start" -> Json.fromLong(piece.segment.start.millis),
|
|
22
|
+
"end" -> Json.fromLong(piece.segment.end.millis),
|
|
23
|
+
"duration" -> Json.fromDoubleOrNull(piece.segment.duration),
|
|
24
|
+
"tags" -> listOrNull(piece.tags),
|
|
25
|
+
"properties" -> mapOrNull(piece.properties),
|
|
26
|
+
"kind" -> Json.fromString("phase")
|
|
27
|
+
)
|
|
28
|
+
Json.obj(
|
|
29
|
+
"type" -> Json.fromString("split-family"),
|
|
30
|
+
"machine" -> Json.fromString(machine.raw),
|
|
31
|
+
"origin" -> Json.fromLong(origin.millis),
|
|
32
|
+
"pieces" -> Json.fromValues(rows)
|
|
33
|
+
).noSpaces
|
|
34
|
+
|
|
35
|
+
private def listOrNull(values: List[String]): Json =
|
|
36
|
+
if values.isEmpty then Json.Null else values.asJson
|
|
37
|
+
|
|
38
|
+
private def mapOrNull(values: Map[String, String]): Json =
|
|
39
|
+
if values.isEmpty then Json.Null else values.asJson
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
package scada.supervisor.infra.stomp
|
|
2
|
+
|
|
3
|
+
import cats.effect.{IO, Resource}
|
|
4
|
+
import cats.syntax.all.*
|
|
5
|
+
import scala.concurrent.duration.*
|
|
6
|
+
import java.io.{BufferedReader, InputStreamReader, OutputStream}
|
|
7
|
+
import java.net.{Socket, SocketTimeoutException}
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Raw TCP STOMP connection. Sends and receives [[StompFrame]]s over a
|
|
11
|
+
* plain socket. Ownership is scoped by the [[Resource]] returned from
|
|
12
|
+
* [[StompConnection.open]]; the connection is closed with a DISCONNECT
|
|
13
|
+
* frame followed by socket close.
|
|
14
|
+
*
|
|
15
|
+
* The socket uses a short `SO_TIMEOUT` so blocking reads surface
|
|
16
|
+
* periodically and [[receive]] can observe cancellation from the
|
|
17
|
+
* surrounding fiber (plain blocking socket reads ignore
|
|
18
|
+
* `Thread.interrupt`).
|
|
19
|
+
*
|
|
20
|
+
* {{{
|
|
21
|
+
* StompConnection.open(host, port, vhost, login, passcode).use(_.send(frame))
|
|
22
|
+
* }}}
|
|
23
|
+
*/
|
|
24
|
+
/**
|
|
25
|
+
* Minimal send surface used by [[StompSegments]] so unit tests can
|
|
26
|
+
* supply a recording stub without opening a TCP socket.
|
|
27
|
+
*/
|
|
28
|
+
trait StompSender:
|
|
29
|
+
def send(frame: StompFrame): IO[Unit]
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Send plus receive surface used by [[StompDecisions]] so tests can
|
|
33
|
+
* supply an in-memory session without a TCP socket.
|
|
34
|
+
*/
|
|
35
|
+
trait StompLink extends StompSender:
|
|
36
|
+
def receive: IO[Option[StompFrame]]
|
|
37
|
+
|
|
38
|
+
final class StompConnection(socket: Socket, output: OutputStream, reader: BufferedReader) extends StompLink:
|
|
39
|
+
|
|
40
|
+
def send(frame: StompFrame): IO[Unit] =
|
|
41
|
+
write(frame) *> frame.headers.get("receipt").fold(IO.unit)(id => receipt(id).timeout(10.seconds))
|
|
42
|
+
|
|
43
|
+
private def receipt(id: String): IO[Unit] =
|
|
44
|
+
receive.flatMap:
|
|
45
|
+
case Some(frame) if frame.command == "RECEIPT" && frame.headers.get("receipt-id").contains(id) => IO.unit
|
|
46
|
+
case Some(frame) if frame.command == "ERROR" => IO.raiseError(IllegalStateException(frame.body))
|
|
47
|
+
case Some(_) => receipt(id)
|
|
48
|
+
case None => IO.raiseError(IllegalStateException("STOMP closed before receipt"))
|
|
49
|
+
|
|
50
|
+
private def write(frame: StompFrame): IO[Unit] = IO.blocking:
|
|
51
|
+
output.synchronized:
|
|
52
|
+
output.write(frame.encode)
|
|
53
|
+
output.flush()
|
|
54
|
+
|
|
55
|
+
def receive: IO[Option[StompFrame]] =
|
|
56
|
+
def loop(acc: String): IO[Option[StompFrame]] =
|
|
57
|
+
readChunk(acc).flatMap:
|
|
58
|
+
case ReadOutcome.Timeout(partial) => IO.cede *> loop(partial)
|
|
59
|
+
case ReadOutcome.EndOfStream(final0) =>
|
|
60
|
+
IO.pure(if final0.isEmpty then None else StompFrame.decode(final0.dropWhile(c => c == '\n' || c == '\r')))
|
|
61
|
+
case ReadOutcome.FrameEnd(data) =>
|
|
62
|
+
val trimmed = data.dropWhile(c => c == '\n' || c == '\r')
|
|
63
|
+
if trimmed.isEmpty then IO.cede *> loop("") else IO.pure(StompFrame.decode(trimmed))
|
|
64
|
+
loop("")
|
|
65
|
+
|
|
66
|
+
private def readChunk(acc: String): IO[ReadOutcome] = IO.blocking:
|
|
67
|
+
val sb = StringBuilder(acc)
|
|
68
|
+
try
|
|
69
|
+
var ch = reader.read()
|
|
70
|
+
if acc.isEmpty && (ch == '\n' || ch == '\r') then ReadOutcome.FrameEnd("")
|
|
71
|
+
else
|
|
72
|
+
while ch != -1 && ch != 0 do
|
|
73
|
+
sb.append(ch.toChar)
|
|
74
|
+
ch = reader.read()
|
|
75
|
+
if ch == -1 then ReadOutcome.EndOfStream(sb.toString) else ReadOutcome.FrameEnd(sb.toString)
|
|
76
|
+
catch case _: SocketTimeoutException => ReadOutcome.Timeout(sb.toString)
|
|
77
|
+
|
|
78
|
+
def close: IO[Unit] =
|
|
79
|
+
send(StompFrame.disconnect).attempt *> IO.blocking(socket.close())
|
|
80
|
+
|
|
81
|
+
private enum ReadOutcome:
|
|
82
|
+
case Timeout(partial: String)
|
|
83
|
+
case EndOfStream(partial: String)
|
|
84
|
+
case FrameEnd(data: String)
|
|
85
|
+
|
|
86
|
+
object StompConnection:
|
|
87
|
+
private val readTimeoutMillis: Int = 250
|
|
88
|
+
|
|
89
|
+
def open(host: String, port: Int, vhost: String, login: String, passcode: String): Resource[IO, StompConnection] =
|
|
90
|
+
Resource.make(connect(host, port, vhost, login, passcode))(_.close)
|
|
91
|
+
|
|
92
|
+
def connect(host: String, port: Int, vhost: String, login: String, passcode: String): IO[StompConnection] =
|
|
93
|
+
IO.blocking:
|
|
94
|
+
val socket = Socket(host, port)
|
|
95
|
+
socket.setKeepAlive(true)
|
|
96
|
+
val output = socket.getOutputStream
|
|
97
|
+
val reader = BufferedReader(InputStreamReader(socket.getInputStream, "UTF-8"))
|
|
98
|
+
output.write(StompFrame.connect(vhost, login, passcode).encode)
|
|
99
|
+
output.flush()
|
|
100
|
+
val sb = StringBuilder()
|
|
101
|
+
var ch = reader.read()
|
|
102
|
+
while ch != -1 && ch != 0 do
|
|
103
|
+
sb.append(ch.toChar)
|
|
104
|
+
ch = reader.read()
|
|
105
|
+
socket.setSoTimeout(readTimeoutMillis)
|
|
106
|
+
StompConnection(socket, output, reader)
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
package scada.supervisor.infra.stomp
|
|
2
|
+
|
|
3
|
+
import cats.effect.{IO, Resource}
|
|
4
|
+
import fs2.Stream
|
|
5
|
+
import scada.supervisor.core.Decision
|
|
6
|
+
import scada.supervisor.infra.config.RabbitMqConfig
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* STOMP subscription emitting operator [[Decision]]s parsed from the
|
|
10
|
+
* `user_decisions` destination. Each session ends on EOF so the next
|
|
11
|
+
* `open` can subscribe again after RabbitMQ restarts.
|
|
12
|
+
*
|
|
13
|
+
* {{{
|
|
14
|
+
* StompDecisions(config).subscribe.evalMap(_.applyTo(segments)).compile.drain
|
|
15
|
+
* }}}
|
|
16
|
+
*/
|
|
17
|
+
final class StompDecisions(open: Resource[IO, StompLink], dest: String):
|
|
18
|
+
|
|
19
|
+
def this(config: RabbitMqConfig) =
|
|
20
|
+
this(
|
|
21
|
+
StompConnection
|
|
22
|
+
.open(
|
|
23
|
+
config.address.host,
|
|
24
|
+
config.address.port,
|
|
25
|
+
config.vhost,
|
|
26
|
+
config.credentials.login,
|
|
27
|
+
config.credentials.passcode
|
|
28
|
+
)
|
|
29
|
+
.map(conn => conn: StompLink),
|
|
30
|
+
config.destinations.userDecisions
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
def subscribe: Stream[IO, Decision] =
|
|
34
|
+
Stream
|
|
35
|
+
.resource(open)
|
|
36
|
+
.flatMap: conn =>
|
|
37
|
+
Stream.eval(conn.send(StompFrame.subscribe(dest, "decisions-0"))) >>
|
|
38
|
+
Stream.repeatEval(conn.receive).takeThrough(_.isDefined).unNone.flatMap: frame =>
|
|
39
|
+
Stream.fromOption[IO](decode(frame))
|
|
40
|
+
.repeat
|
|
41
|
+
|
|
42
|
+
private def decode(frame: StompFrame): Option[Decision] =
|
|
43
|
+
if frame.command != "MESSAGE" then None else DecisionMessage.parse(frame.body)
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
package scada.supervisor.infra.stomp
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Minimal STOMP 1.2 frame: command, headers, body. Round-trips via
|
|
5
|
+
* [[encode]] / [[StompFrame.decode]].
|
|
6
|
+
*
|
|
7
|
+
* {{{
|
|
8
|
+
* StompFrame("SEND", Map("destination" -> "/exchange/foo"), "body").encode
|
|
9
|
+
* }}}
|
|
10
|
+
*/
|
|
11
|
+
final case class StompFrame(command: String, headers: Map[String, String], body: String):
|
|
12
|
+
def encode: Array[Byte] =
|
|
13
|
+
val sb = StringBuilder()
|
|
14
|
+
sb.append(command).append('\n')
|
|
15
|
+
headers.foreach((k, v) => sb.append(k).append(':').append(v).append('\n'))
|
|
16
|
+
sb.append('\n').append(body).append('\u0000')
|
|
17
|
+
sb.toString.getBytes("UTF-8")
|
|
18
|
+
|
|
19
|
+
object StompFrame:
|
|
20
|
+
def decode(data: String): Option[StompFrame] =
|
|
21
|
+
val nullIdx = data.indexOf('\u0000')
|
|
22
|
+
val clean = if nullIdx >= 0 then data.substring(0, nullIdx) else data
|
|
23
|
+
val parts = clean.split("\n\n", 2)
|
|
24
|
+
if parts.isEmpty then None
|
|
25
|
+
else
|
|
26
|
+
parts(0).split("\n").toList match
|
|
27
|
+
case command :: headerLines =>
|
|
28
|
+
val headers = headerLines.flatMap: line =>
|
|
29
|
+
val idx = line.indexOf(':')
|
|
30
|
+
if idx > 0 then Some(line.substring(0, idx) -> line.substring(idx + 1))
|
|
31
|
+
else None
|
|
32
|
+
Some(StompFrame(command, headers.toMap, if parts.length > 1 then parts(1) else ""))
|
|
33
|
+
case _ => None
|
|
34
|
+
|
|
35
|
+
def connect(host: String, login: String, passcode: String): StompFrame =
|
|
36
|
+
StompFrame(
|
|
37
|
+
"CONNECT",
|
|
38
|
+
Map(
|
|
39
|
+
"accept-version" -> "1.2",
|
|
40
|
+
"host" -> host,
|
|
41
|
+
"login" -> login,
|
|
42
|
+
"passcode" -> passcode,
|
|
43
|
+
"heart-beat" -> "0,0"
|
|
44
|
+
),
|
|
45
|
+
""
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
def send(destination: String, routingKey: String, body: String): StompFrame =
|
|
49
|
+
StompFrame(
|
|
50
|
+
"SEND",
|
|
51
|
+
Map(
|
|
52
|
+
"destination" -> destination,
|
|
53
|
+
"content-type" -> "application/json",
|
|
54
|
+
"routing-key" -> routingKey,
|
|
55
|
+
"persistent" -> "true"
|
|
56
|
+
),
|
|
57
|
+
body
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
def subscribe(destination: String, id: String): StompFrame =
|
|
61
|
+
StompFrame(
|
|
62
|
+
"SUBSCRIBE",
|
|
63
|
+
Map("destination" -> destination, "id" -> id, "ack" -> "auto"),
|
|
64
|
+
""
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
def disconnect: StompFrame = StompFrame("DISCONNECT", Map.empty, "")
|
package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompMachineDecisions.scala
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
package scada.supervisor.infra.stomp
|
|
2
|
+
|
|
3
|
+
import cats.effect.IO
|
|
4
|
+
import fs2.Stream
|
|
5
|
+
import scada.supervisor.core.{Decision,MachineId}
|
|
6
|
+
import scada.supervisor.infra.config.RabbitMqConfig
|
|
7
|
+
|
|
8
|
+
/** A durable per-machine copy; unrelated machine decisions are discarded only from this copy. */
|
|
9
|
+
final class StompMachineDecisions(config: RabbitMqConfig, queue: String, machine: MachineId):
|
|
10
|
+
def subscribe: Stream[IO,Decision] =
|
|
11
|
+
val open = StompConnection.open(config.address.host,config.address.port,config.vhost,config.credentials.login,config.credentials.passcode)
|
|
12
|
+
.map(connection => connection: StompLink)
|
|
13
|
+
StompQueue(open,queue,(frame: StompFrame) => DecisionMessage.parse(frame.body)).subscribe.filter:
|
|
14
|
+
case Decision.Resolve(id,_,_,_) => id == machine
|
|
15
|
+
case Decision.Split(id,_,_) => id == machine
|
|
16
|
+
case _ => false
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
package scada.supervisor.infra.stomp
|
|
2
|
+
|
|
3
|
+
import cats.effect.{IO,Resource}
|
|
4
|
+
import fs2.Stream
|
|
5
|
+
import java.util.concurrent.TimeoutException
|
|
6
|
+
import scala.concurrent.duration.*
|
|
7
|
+
/** Pre-bound durable input; ACK before downstream so prefetch-1 cannot stall the broker. */
|
|
8
|
+
final class StompQueue[A](open: Resource[IO,StompLink], queue: String, decode: StompFrame => Option[A], idle: FiniteDuration = 30.seconds):
|
|
9
|
+
def subscribe: Stream[IO,A] = receive((value, ack) => Stream.exec(ack) ++ Stream.emit(value))
|
|
10
|
+
|
|
11
|
+
def subscribeDurable: Stream[IO,(A,IO[Unit])] = receive((value, ack) => Stream.emit((value, ack)))
|
|
12
|
+
|
|
13
|
+
private def receive[B](message: (A,IO[Unit]) => Stream[IO,B]): Stream[IO,B] =
|
|
14
|
+
Stream.resource(open).flatMap: connection =>
|
|
15
|
+
val subscription = StompFrame("SUBSCRIBE",Map("destination"->s"/amq/queue/$queue","id"->"supervisor-input","ack"->"client-individual","prefetch-count"->"1"),"")
|
|
16
|
+
Stream.eval(connection.send(subscription)) >>
|
|
17
|
+
Stream.repeatEval(connection.receive).unNoneTerminate.flatMap: frame =>
|
|
18
|
+
if frame.command == "ERROR" then Stream.raiseError[IO](IllegalStateException(frame.body))
|
|
19
|
+
else if frame.command != "MESSAGE" then Stream.empty
|
|
20
|
+
else
|
|
21
|
+
val id = frame.headers.getOrElse("ack",throw IllegalArgumentException("Missing STOMP ack id"))
|
|
22
|
+
decode(frame) match
|
|
23
|
+
case Some(value) =>
|
|
24
|
+
message(value, connection.send(StompFrame("ACK",Map("id"->id),"")))
|
|
25
|
+
case None => Stream.exec(connection.send(StompFrame("NACK",Map("id"->id,"requeue"->"false"),"")))
|
|
26
|
+
.timeoutOnPullTo(idle, Stream.raiseError[IO](TimeoutException("stomp idle")))
|
|
27
|
+
.handleErrorWith:
|
|
28
|
+
case _: TimeoutException => Stream.sleep_[IO](10.millis)
|
|
29
|
+
case _ => Stream.sleep_[IO](1.second)
|
|
30
|
+
.repeat
|