@yarkivaev/scada 2.6.40 → 2.6.41

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.
Files changed (79) hide show
  1. package/README.md +13 -768
  2. package/package.json +3 -1
  3. package/src/infrastructure/streams/README.md +12 -5
  4. package/supervisor-engine/src/main/scala/scada/supervisor/core/Condition.scala +33 -0
  5. package/supervisor-engine/src/main/scala/scada/supervisor/core/CyclePhases.scala +65 -0
  6. package/supervisor-engine/src/main/scala/scada/supervisor/core/Decision.scala +67 -0
  7. package/supervisor-engine/src/main/scala/scada/supervisor/core/Emission.scala +19 -0
  8. package/supervisor-engine/src/main/scala/scada/supervisor/core/MachineConfig.scala +21 -0
  9. package/supervisor-engine/src/main/scala/scada/supervisor/core/MachineId.scala +18 -0
  10. package/supervisor-engine/src/main/scala/scada/supervisor/core/MachineMode.scala +4 -0
  11. package/supervisor-engine/src/main/scala/scada/supervisor/core/Params.scala +15 -0
  12. package/supervisor-engine/src/main/scala/scada/supervisor/core/Reading.scala +11 -0
  13. package/supervisor-engine/src/main/scala/scada/supervisor/core/Segment.scala +28 -0
  14. package/supervisor-engine/src/main/scala/scada/supervisor/core/SegmentDef.scala +14 -0
  15. package/supervisor-engine/src/main/scala/scada/supervisor/core/Segmentation.scala +137 -0
  16. package/supervisor-engine/src/main/scala/scada/supervisor/core/Segments.scala +41 -0
  17. package/supervisor-engine/src/main/scala/scada/supervisor/core/SplitFollow.scala +50 -0
  18. package/supervisor-engine/src/main/scala/scada/supervisor/core/SplitPieces.scala +102 -0
  19. package/supervisor-engine/src/main/scala/scada/supervisor/core/Supervisor.scala +66 -0
  20. package/supervisor-engine/src/main/scala/scada/supervisor/core/TagDef.scala +12 -0
  21. package/supervisor-engine/src/main/scala/scada/supervisor/core/TaggedSegment.scala +19 -0
  22. package/supervisor-engine/src/main/scala/scada/supervisor/core/Tagging.scala +42 -0
  23. package/supervisor-engine/src/main/scala/scada/supervisor/core/Timestamp.scala +26 -0
  24. package/supervisor-engine/src/main/scala/scada/supervisor/infra/checkpoint/Checkpoint.scala +61 -0
  25. package/supervisor-engine/src/main/scala/scada/supervisor/infra/checkpoint/ClickhouseReadingsCheckpoint.scala +76 -0
  26. package/supervisor-engine/src/main/scala/scada/supervisor/infra/checkpoint/SupervisorSinkCheckpoint.scala +141 -0
  27. package/supervisor-engine/src/main/scala/scada/supervisor/infra/config/AppConfig.scala +132 -0
  28. package/supervisor-engine/src/main/scala/scada/supervisor/infra/config/ConfigLoad.scala +202 -0
  29. package/supervisor-engine/src/main/scala/scada/supervisor/infra/config/ConfigProfile.scala +13 -0
  30. package/supervisor-engine/src/main/scala/scada/supervisor/infra/mqtt/Mqtt.scala +92 -0
  31. package/supervisor-engine/src/main/scala/scada/supervisor/infra/mqtt/Sessions.scala +18 -0
  32. package/supervisor-engine/src/main/scala/scada/supervisor/infra/state/AtomicStateFile.scala +24 -0
  33. package/supervisor-engine/src/main/scala/scada/supervisor/infra/state/CheckpointSegments.scala +59 -0
  34. package/supervisor-engine/src/main/scala/scada/supervisor/infra/state/SegmentStatePolicy.scala +18 -0
  35. package/supervisor-engine/src/main/scala/scada/supervisor/infra/state/Segments.scala +91 -0
  36. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/ClassifyQueue.scala +37 -0
  37. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/DecisionMessage.scala +49 -0
  38. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/DurableStomp.scala +27 -0
  39. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/SegmentMessage.scala +57 -0
  40. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/SegmentWirePolicy.scala +18 -0
  41. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/SplitFamily.scala +39 -0
  42. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompConnection.scala +106 -0
  43. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompDecisions.scala +43 -0
  44. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompFrame.scala +67 -0
  45. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompMachineDecisions.scala +16 -0
  46. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompQueue.scala +30 -0
  47. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompReadings.scala +29 -0
  48. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompSegments.scala +115 -0
  49. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ClassifierCursors.scala +58 -0
  50. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ClassifyHistory.scala +92 -0
  51. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ClassifyStreams.scala +67 -0
  52. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/Close.scala +23 -0
  53. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/EngineApp.scala +4 -0
  54. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/HealthServer.scala +38 -0
  55. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/HistoryBus.scala +67 -0
  56. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/HistoryClient.scala +23 -0
  57. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/HistoryRun.scala +86 -0
  58. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/LocalHistory.scala +256 -0
  59. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ObservationLead.scala +26 -0
  60. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/Orphans.scala +26 -0
  61. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/PendingIsland.scala +37 -0
  62. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/RuntimeProfile.scala +32 -0
  63. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/Seeding.scala +105 -0
  64. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/SupervisorRuntime.scala +266 -0
  65. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/WriterEpoch.scala +16 -0
  66. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/WriterGate.scala +35 -0
  67. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/WriterLease.scala +218 -0
  68. package/supervisor-engine/vendor/gaps-and-islands/LICENSE +21 -0
  69. package/supervisor-engine/vendor/gaps-and-islands/UPSTREAM +4 -0
  70. package/supervisor-engine/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/Island.scala +40 -0
  71. package/supervisor-engine/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandEvent.scala +55 -0
  72. package/supervisor-engine/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandsFlow.scala +127 -0
  73. package/supervisor-engine/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandsPolicy.scala +105 -0
  74. package/supervisor-engine/vendor/temporal-streams/LICENSE +21 -0
  75. package/supervisor-engine/vendor/temporal-streams/UPSTREAM +3 -0
  76. package/supervisor-engine/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/History.scala +30 -0
  77. package/supervisor-engine/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/LocalStreams.scala +27 -0
  78. package/supervisor-engine/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/Overlay.scala +15 -0
  79. package/supervisor-engine/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/Worker.scala +21 -0
@@ -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, "")
@@ -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
@@ -0,0 +1,29 @@
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 scada.supervisor.core.*
7
+ import scada.supervisor.infra.config.{AliasMapping,RabbitMqConfig}
8
+
9
+ /** One pre-bound durable AMQP queue preserves parameter/rise order. Slash aliases match dotted routing keys. */
10
+ final class StompReadings(open: Resource[IO,StompLink], queue: String, aliases: List[AliasMapping]):
11
+ def this(config: RabbitMqConfig, queue: String, aliases: List[AliasMapping]) =
12
+ this(StompConnection.open(config.address.host,config.address.port,config.vhost,config.credentials.login,config.credentials.passcode)
13
+ .map(connection => connection: StompLink),queue,aliases)
14
+ def subscribe: Stream[IO,Reading] = StompQueue(open,queue,decode).subscribe
15
+ def subscribeDurable: Stream[IO,(Reading,IO[Unit])] = StompQueue(open,queue,decode).subscribeDurable
16
+ private[stomp] def decode(frame: StompFrame): Option[Reading] =
17
+ for
18
+ route <- routed(frame.headers)
19
+ alias <- aliases.find(item => dotted(item.topic) == dotted(route))
20
+ json <- parse(frame.body).toOption
21
+ ts <- json.hcursor.get[Double]("ts").toOption.filter(n => n.isFinite && n >= 0)
22
+ value <- json.hcursor.get[Double]("value").toOption.filter(_.isFinite)
23
+ yield Reading(Timestamp(if ts > 1e10 then ts/1000 else ts),Params(Map(alias.metric->value)))
24
+ private def routed(headers: Map[String, String]): Option[String] =
25
+ val prefix = "/exchange/"
26
+ val dest = headers.get("destination").getOrElse("")
27
+ val slash = dest.indexOf('/', prefix.length)
28
+ 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))
29
+ private def dotted(route: String): String = route.replace('/', '.')
@@ -0,0 +1,115 @@
1
+ package scada.supervisor.infra.stomp
2
+
3
+ import cats.Monad
4
+ import cats.effect.IO
5
+ import cats.syntax.all.*
6
+ import io.circe.Json
7
+ import io.circe.syntax.*
8
+ import org.typelevel.log4cats.Logger
9
+ import org.typelevel.log4cats.slf4j.Slf4jLogger
10
+ import scada.supervisor.core.*
11
+ import scada.supervisor.core.Segments as CoreSegments
12
+ import scala.collection.concurrent.TrieMap
13
+ import scala.concurrent.duration.*
14
+
15
+ /**
16
+ * STOMP-publishing decorator over a [[CoreSegments]]. Every write
17
+ * (upsert, replace, resolve) is forwarded to `underlying` and then
18
+ * announced on `destination` using the [[SegmentMessage]] JSON
19
+ * contract.
20
+ *
21
+ * Pending heartbeats (`duration == 0`) are published at most once per
22
+ * `heartbeat` interval per `(machine, start)` key so shovel traffic
23
+ * does not overwhelm central ingest. Open, close, retag, and split
24
+ * announcements are never delayed.
25
+ *
26
+ * {{{
27
+ * StompSegments(base, connection, "/exchange/segments")
28
+ * StompSegments(base, connection, "/exchange/segments", 1.second)
29
+ * }}}
30
+ */
31
+ final class StompSegments(
32
+ underlying: CoreSegments[IO],
33
+ connection: StompSender,
34
+ destination: String,
35
+ heartbeat: FiniteDuration = 1.second,
36
+ nowMillis: IO[Long] = IO.realTime.map(_.toMillis),
37
+ private val stamps: TrieMap[(String, Long), Long] = TrieMap.empty,
38
+ policy: SegmentWirePolicy = SegmentWirePolicy.default
39
+ ) extends CoreSegments[IO]:
40
+
41
+ private given Logger[IO] = Slf4jLogger.getLogger[IO]
42
+
43
+ def upsert(machine: MachineId, segment: TaggedSegment): IO[Unit] =
44
+ underlying.upsert(machine, segment) *>
45
+ underlying.list(machine).flatMap: rows =>
46
+ SplitFollow.affected(segment, rows) match
47
+ case Some(tail) => announce(machine, tail)
48
+ case None =>
49
+ underlying.find(machine, segment.segment.start).flatMap:
50
+ case None => announce(machine, segment)
51
+ case Some(seg) => announce(machine, seg)
52
+
53
+ override def upsertTransition(machine: MachineId, rows: List[TaggedSegment])(using Monad[IO]): IO[Unit] =
54
+ if !policy.atomicTransition || rows.size < 2 then super.upsertTransition(machine, rows)
55
+ else
56
+ val body = Json.obj("type" -> "phase-transition".asJson, "machine" -> machine.raw.asJson,
57
+ "pieces" -> rows.map(row => SegmentMessage.segment(machine,row).jsonWith(policy)).asJson)
58
+ rows.traverse_(underlying.upsert(machine, _)) *> publishRaw(body.noSpaces, true)
59
+
60
+ def find(machine: MachineId, start: Timestamp): IO[Option[TaggedSegment]] =
61
+ underlying.find(machine, start)
62
+
63
+ def list(machine: MachineId): IO[List[TaggedSegment]] =
64
+ underlying.list(machine)
65
+
66
+ def replace(machine: MachineId, from: Timestamp, to: Timestamp, segments: List[TaggedSegment]): IO[Unit] =
67
+ underlying.replace(machine, from, to, segments) *>
68
+ (if segments.isEmpty then IO.unit
69
+ else publishRaw(SplitFamily.json(machine, from, segments)))
70
+
71
+ def resolve(
72
+ machine: MachineId,
73
+ original: Segment,
74
+ tags: List[String],
75
+ options: List[String],
76
+ properties: Map[String, String]
77
+ ): IO[Unit] =
78
+ underlying.resolve(machine, original, tags, options, properties) *>
79
+ underlying.find(machine, original.start).flatMap:
80
+ case None => IO.unit
81
+ case Some(seg) => publish(SegmentMessage.retag(machine, seg))
82
+
83
+ private def announce(machine: MachineId, segment: TaggedSegment): IO[Unit] =
84
+ val message = publish(SegmentMessage.segment(machine, segment))
85
+ val output = if policy.splitBeforeSegment(segment) then publish(SegmentMessage.split(machine, segment)) *> message else message
86
+ if segment.segment.duration != 0.0 then
87
+ stamps.remove((machine.raw, segment.segment.start.millis))
88
+ output
89
+ else if policy.bypassHeartbeatThrottle(segment) then output
90
+ else throttle(machine, segment.segment.start, output)
91
+
92
+ private def throttle(machine: MachineId, start: Timestamp, publishIo: IO[Unit]): IO[Unit] =
93
+ val key = (machine.raw, start.millis)
94
+ nowMillis.flatMap: now =>
95
+ stamps.get(key) match
96
+ case Some(last) if now - last < heartbeat.toMillis => IO.unit
97
+ case _ =>
98
+ IO.delay { stamps.update(key, now) } *> publishIo
99
+
100
+ private def publish(message: SegmentMessage): IO[Unit] =
101
+ publishRaw(message.jsonWith(policy).noSpaces, policy.confirmed(message.segment))
102
+
103
+ private def publishRaw(body: String, confirmed: Boolean = false): IO[Unit] =
104
+ val frame = StompFrame.send(destination,"",body)
105
+ val sent = if confirmed then frame.copy(headers=frame.headers.updated("receipt",java.util.UUID.randomUUID().toString)) else frame
106
+ retrying(connection.send(sent),3,100.millis)
107
+
108
+ private def retrying[A](io: IO[A], attempts: Int, delay: FiniteDuration): IO[A] =
109
+ io.handleErrorWith: err =>
110
+ if attempts <= 1 then
111
+ Logger[IO].error(err)(s"STOMP publish failed after all retries on $destination; crashing") *>
112
+ IO.raiseError(err)
113
+ else
114
+ Logger[IO].warn(err)(s"STOMP publish retry in ${delay.toMillis}ms on $destination") *>
115
+ IO.sleep(delay) *> retrying(io, attempts - 1, delay * 2)