@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.
Files changed (85) hide show
  1. package/README.md +13 -768
  2. package/db/migrations/E0018__stream_worker_checkpoint.sql +9 -0
  3. package/package.json +3 -1
  4. package/src/infrastructure/streams/README.md +12 -5
  5. package/supervisor-engine/src/main/scala/scada/stream/replay/Replay.scala +149 -0
  6. package/supervisor-engine/src/main/scala/scada/stream/worker/Processor.scala +8 -0
  7. package/supervisor-engine/src/main/scala/scada/stream/worker/StreamWorker.scala +119 -0
  8. package/supervisor-engine/src/main/scala/scada/stream/worker/postgres/PgCheckpointStore.scala +83 -0
  9. package/supervisor-engine/src/main/scala/scada/supervisor/core/Condition.scala +33 -0
  10. package/supervisor-engine/src/main/scala/scada/supervisor/core/CyclePhases.scala +65 -0
  11. package/supervisor-engine/src/main/scala/scada/supervisor/core/Decision.scala +67 -0
  12. package/supervisor-engine/src/main/scala/scada/supervisor/core/Emission.scala +19 -0
  13. package/supervisor-engine/src/main/scala/scada/supervisor/core/MachineConfig.scala +21 -0
  14. package/supervisor-engine/src/main/scala/scada/supervisor/core/MachineId.scala +18 -0
  15. package/supervisor-engine/src/main/scala/scada/supervisor/core/MachineMode.scala +4 -0
  16. package/supervisor-engine/src/main/scala/scada/supervisor/core/Params.scala +15 -0
  17. package/supervisor-engine/src/main/scala/scada/supervisor/core/Reading.scala +11 -0
  18. package/supervisor-engine/src/main/scala/scada/supervisor/core/Segment.scala +28 -0
  19. package/supervisor-engine/src/main/scala/scada/supervisor/core/SegmentDef.scala +14 -0
  20. package/supervisor-engine/src/main/scala/scada/supervisor/core/Segmentation.scala +52 -0
  21. package/supervisor-engine/src/main/scala/scada/supervisor/core/Segments.scala +41 -0
  22. package/supervisor-engine/src/main/scala/scada/supervisor/core/SplitFollow.scala +50 -0
  23. package/supervisor-engine/src/main/scala/scada/supervisor/core/SplitPieces.scala +102 -0
  24. package/supervisor-engine/src/main/scala/scada/supervisor/core/Supervisor.scala +66 -0
  25. package/supervisor-engine/src/main/scala/scada/supervisor/core/TagDef.scala +12 -0
  26. package/supervisor-engine/src/main/scala/scada/supervisor/core/TaggedSegment.scala +19 -0
  27. package/supervisor-engine/src/main/scala/scada/supervisor/core/Tagging.scala +42 -0
  28. package/supervisor-engine/src/main/scala/scada/supervisor/core/Timestamp.scala +26 -0
  29. package/supervisor-engine/src/main/scala/scada/supervisor/core/segmentation/Timeline.scala +43 -0
  30. package/supervisor-engine/src/main/scala/scada/supervisor/infra/checkpoint/Checkpoint.scala +61 -0
  31. package/supervisor-engine/src/main/scala/scada/supervisor/infra/checkpoint/ClickhouseReadingsCheckpoint.scala +76 -0
  32. package/supervisor-engine/src/main/scala/scada/supervisor/infra/checkpoint/SupervisorSinkCheckpoint.scala +141 -0
  33. package/supervisor-engine/src/main/scala/scada/supervisor/infra/config/AppConfig.scala +132 -0
  34. package/supervisor-engine/src/main/scala/scada/supervisor/infra/config/ConfigLoad.scala +202 -0
  35. package/supervisor-engine/src/main/scala/scada/supervisor/infra/config/ConfigProfile.scala +13 -0
  36. package/supervisor-engine/src/main/scala/scada/supervisor/infra/mqtt/Mqtt.scala +92 -0
  37. package/supervisor-engine/src/main/scala/scada/supervisor/infra/mqtt/Sessions.scala +18 -0
  38. package/supervisor-engine/src/main/scala/scada/supervisor/infra/state/AtomicStateFile.scala +24 -0
  39. package/supervisor-engine/src/main/scala/scada/supervisor/infra/state/CheckpointSegments.scala +59 -0
  40. package/supervisor-engine/src/main/scala/scada/supervisor/infra/state/SegmentStatePolicy.scala +18 -0
  41. package/supervisor-engine/src/main/scala/scada/supervisor/infra/state/Segments.scala +91 -0
  42. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/ClassifyQueue.scala +37 -0
  43. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/DecisionMessage.scala +49 -0
  44. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/DurableStomp.scala +27 -0
  45. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/SegmentMessage.scala +57 -0
  46. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/SegmentWirePolicy.scala +18 -0
  47. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/SplitFamily.scala +39 -0
  48. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompConnection.scala +106 -0
  49. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompDecisions.scala +43 -0
  50. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompFrame.scala +67 -0
  51. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompMachineDecisions.scala +16 -0
  52. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompQueue.scala +30 -0
  53. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompReadings.scala +29 -0
  54. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompSegments.scala +115 -0
  55. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ClassifierCursors.scala +58 -0
  56. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ClassifyHistory.scala +92 -0
  57. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ClassifyStreams.scala +67 -0
  58. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/Close.scala +23 -0
  59. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/EngineApp.scala +4 -0
  60. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/HealthServer.scala +38 -0
  61. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/HistoryBus.scala +67 -0
  62. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/HistoryClient.scala +23 -0
  63. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/HistoryRun.scala +86 -0
  64. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/LocalHistory.scala +258 -0
  65. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ObservationLead.scala +26 -0
  66. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/Orphans.scala +26 -0
  67. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/PendingIsland.scala +37 -0
  68. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/RuntimeProfile.scala +32 -0
  69. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/Seeding.scala +105 -0
  70. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/SupervisorRuntime.scala +266 -0
  71. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/WriterEpoch.scala +16 -0
  72. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/WriterGate.scala +35 -0
  73. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/WriterLease.scala +218 -0
  74. package/supervisor-engine/vendor/gaps-and-islands/LICENSE +21 -0
  75. package/supervisor-engine/vendor/gaps-and-islands/UPSTREAM +4 -0
  76. package/supervisor-engine/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/Island.scala +40 -0
  77. package/supervisor-engine/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandEvent.scala +55 -0
  78. package/supervisor-engine/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandsFlow.scala +127 -0
  79. package/supervisor-engine/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandsPolicy.scala +105 -0
  80. package/supervisor-engine/vendor/temporal-streams/LICENSE +21 -0
  81. package/supervisor-engine/vendor/temporal-streams/UPSTREAM +3 -0
  82. package/supervisor-engine/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/History.scala +30 -0
  83. package/supervisor-engine/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/LocalStreams.scala +27 -0
  84. package/supervisor-engine/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/Overlay.scala +15 -0
  85. package/supervisor-engine/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/Worker.scala +21 -0
@@ -0,0 +1,11 @@
1
+ package scada.supervisor.core
2
+
3
+ /**
4
+ * One sensor observation for a machine at one instant. The atomic
5
+ * input of segmentation.
6
+ *
7
+ * {{{
8
+ * Reading(Timestamp(1700000000.0), Params(Map("power" -> 42.0)))
9
+ * }}}
10
+ */
11
+ final case class Reading(timestamp: Timestamp, params: Params)
@@ -0,0 +1,28 @@
1
+ package scada.supervisor.core
2
+
3
+ /**
4
+ * A named, closed time interval produced by segmentation from a
5
+ * contiguous run of readings that matched the same [[SegmentDef]].
6
+ *
7
+ * `duration == 0.0` marks a just-started (pending) segment whose
8
+ * closing boundary a later reading will reveal.
9
+ *
10
+ * {{{
11
+ * Segment("on", Timestamp(100.0), Timestamp(200.0), 100.0)
12
+ * }}}
13
+ */
14
+ final case class Segment(
15
+ name: String,
16
+ start: Timestamp,
17
+ end: Timestamp,
18
+ duration: Double,
19
+ properties: Map[String, String] = Map.empty
20
+ )
21
+
22
+ /**
23
+ * Open-segment resume cursor from Postgres (`segments` row with
24
+ * `duration = 0`). Fed into [[Segmentation]] as the initial
25
+ * gaps-and-islands island; `end` may advance beyond `start` via
26
+ * pending heartbeats.
27
+ */
28
+ final case class SegmentCursor(name: String, start: Timestamp, end: Timestamp)
@@ -0,0 +1,14 @@
1
+ package scada.supervisor.core
2
+
3
+ /**
4
+ * One named segment kind for a machine: a label and the predicate
5
+ * deciding whether a reading belongs to it.
6
+ *
7
+ * Order inside [[MachineConfig.segments]] is significant — the first
8
+ * matching definition wins.
9
+ *
10
+ * {{{
11
+ * SegmentDef("on", Condition.Above("power", 0.1))
12
+ * }}}
13
+ */
14
+ final case class SegmentDef(name: String, condition: Condition)
@@ -0,0 +1,52 @@
1
+ package scada.supervisor.core
2
+
3
+ import cats.effect.Async
4
+ import fs2.{Pipe, Stream}
5
+ import scala.concurrent.duration.*
6
+ import scada.supervisor.core.segmentation.Timeline
7
+ import scada.supervisor.core.segmentation.Timeline.{Boundary, Event, Interval, Output}
8
+
9
+ final case class ReadingOverride(name: String, properties: Map[String, String])
10
+
11
+ /** Merges same-time readings and applies the live interval policy.
12
+ * Class changes close at the next phase's first sample. A gap over twice
13
+ * the machine's window splits equal phases without inventing downtime.
14
+ */
15
+ final class Segmentation[F[_]: Async](overrideReading: Reading => Option[ReadingOverride] = _ => None):
16
+ private val unclassified = "unclassified"
17
+
18
+ def flow(machine: MachineConfig, initial: Option[SegmentCursor] = None): Pipe[F, Reading, Emission[Segment]] =
19
+ val classify = Timeline.classifier(machine.segments)
20
+ val maxGap = machine.window.toDouble * 2.0
21
+ val seed = initial.map: cursor =>
22
+ Interval(cursor.name, Reading(cursor.start, Params(Map.empty)), Reading(cursor.end, Params(Map.empty)))
23
+
24
+ input =>
25
+ gather(input).mapAccumulate(seed): (open, reading) =>
26
+ val name = overrideReading(reading).map(_.name).orElse(classify(reading.params))
27
+ .orElse(open.map(_.name)).getOrElse(unclassified)
28
+ val continuous = open.exists(interval => !(reading.timestamp.minus(interval.end.timestamp) > maxGap))
29
+ val step = Timeline.step(Boundary.Live, open, Event.Sample(reading, name, continuous))
30
+ (step.open, step.outputs.flatMap(toEmission))
31
+ .flatMap((_, emissions) => Stream.emits(emissions))
32
+
33
+ private def gather(in: Stream[F, Reading]): Stream[F, Reading] =
34
+ in.groupWithin(32, 50.millis).flatMap: chunk =>
35
+ Stream.emits:
36
+ chunk.toList.groupBy(_.timestamp.epoch).toList.sortBy(_._1).map: (_, rows) =>
37
+ rows.reduce((left, right) => Reading(right.timestamp, left.params.merge(right.params)))
38
+
39
+ private def toEmission(output: Output[Reading]): Option[Emission[Segment]] =
40
+ def segment(interval: Interval[Reading], closed: Boolean): Segment =
41
+ val start = interval.start.timestamp
42
+ val end = interval.end.timestamp
43
+ val duration = if closed then end.minus(start) else 0.0
44
+ val properties = overrideReading(interval.end).fold(Map.empty[String, String])(_.properties)
45
+ Segment(interval.name, start, end, duration, properties)
46
+
47
+ output match
48
+ case Output.Pending(interval) if interval.name != unclassified =>
49
+ Some(Emission.Started(segment(interval, closed = false)))
50
+ case Output.Closed(interval) if interval.name != unclassified =>
51
+ Some(Emission.Emitted(segment(interval, closed = true)))
52
+ case _ => None
@@ -0,0 +1,41 @@
1
+ package scada.supervisor.core
2
+
3
+ import cats.Monad
4
+ import cats.syntax.all.*
5
+
6
+ /**
7
+ * Persistence boundary for [[TaggedSegment]]s keyed by machine and
8
+ * start timestamp. Abstract over the effect type so decorators
9
+ * (watermark, STOMP publishing) can compose around a concrete
10
+ * in-memory base without pinning the whole core to any runtime.
11
+ *
12
+ * [[resolve]] writes operator `tags` and `properties` on the row
13
+ * keyed by `original.start`. Options:
14
+ * - non-empty `options` → store that list (cascade next choices / leaf);
15
+ * - empty `options` → keep the previous options so HMI can re-edit the
16
+ * same prompt after a resolve that only retags the path.
17
+ *
18
+ * {{{
19
+ * segments.upsert(machineId, taggedSegment)
20
+ * segments.resolve(machine, original, tags, options, properties)
21
+ * }}}
22
+ */
23
+ trait Segments[F[_]]:
24
+ def upsert(machine: MachineId, segment: TaggedSegment): F[Unit]
25
+
26
+ def upsertTransition(machine: MachineId, rows: List[TaggedSegment])(using Monad[F]): F[Unit] =
27
+ rows.traverse_(upsert(machine, _))
28
+
29
+ def find(machine: MachineId, start: Timestamp): F[Option[TaggedSegment]]
30
+
31
+ def list(machine: MachineId): F[List[TaggedSegment]]
32
+
33
+ def replace(machine: MachineId, from: Timestamp, to: Timestamp, segments: List[TaggedSegment]): F[Unit]
34
+
35
+ def resolve(
36
+ machine: MachineId,
37
+ original: Segment,
38
+ tags: List[String],
39
+ options: List[String],
40
+ properties: Map[String, String]
41
+ ): F[Unit]
@@ -0,0 +1,50 @@
1
+ package scada.supervisor.core
2
+
3
+ import scala.collection.immutable.SortedMap
4
+
5
+ /**
6
+ * Keeps a classifier heartbeat on an already split `off` island from
7
+ * rewriting the closed pieces. The heartbeat still names the original
8
+ * start. Only the open tail moves, and a later close finishes that tail.
9
+ *
10
+ * {{{
11
+ * SplitFollow.project(rows, heartbeat)
12
+ * }}}
13
+ */
14
+ object SplitFollow:
15
+ def owned(rows: Iterable[TaggedSegment], incoming: TaggedSegment): Boolean =
16
+ incoming.segment.name == "off" && family(rows, incoming).nonEmpty
17
+
18
+ def project(
19
+ rows: SortedMap[Timestamp, TaggedSegment],
20
+ incoming: TaggedSegment
21
+ ): SortedMap[Timestamp, TaggedSegment] =
22
+ val pieces = family(rows.values, incoming)
23
+ if pieces.isEmpty then rows
24
+ else
25
+ val tail = pieces.maxBy(_.segment.start.epoch)
26
+ moved(tail, incoming) match
27
+ case None => rows
28
+ case Some(next) => rows.updated(tail.segment.start, next)
29
+
30
+ def affected(incoming: TaggedSegment, rows: Iterable[TaggedSegment]): Option[TaggedSegment] =
31
+ val pieces = family(rows, incoming)
32
+ if incoming.segment.name != "off" || pieces.isEmpty then None
33
+ else
34
+ val tail = pieces.maxBy(_.segment.start.epoch)
35
+ moved(tail, incoming).orElse(Some(tail))
36
+
37
+ private def family(rows: Iterable[TaggedSegment], incoming: TaggedSegment): List[TaggedSegment] =
38
+ val key = SplitPieces.originKey(incoming.segment.start)
39
+ rows.filter(_.properties.get("split_of").contains(key)).toList
40
+
41
+ private def moved(tail: TaggedSegment, incoming: TaggedSegment): Option[TaggedSegment] =
42
+ val start = tail.segment.start
43
+ if tail.segment.duration != 0.0 then None
44
+ else if incoming.segment.duration == 0.0 then
45
+ if !incoming.segment.end.isAfter(tail.segment.end) then None
46
+ else Some(tail.copy(segment = tail.segment.copy(end = incoming.segment.end, duration = 0.0)))
47
+ else if !incoming.segment.end.isAfter(start) then None
48
+ else
49
+ val end = incoming.segment.end
50
+ Some(tail.copy(segment = Segment("off", start, end, end.minus(start))))
@@ -0,0 +1,102 @@
1
+ package scada.supervisor.core
2
+
3
+ /**
4
+ * Turns one operator split of an `off` island into flat `off` rows.
5
+ * Each row keeps `name = off`, carries at most one tag, and records
6
+ * `properties.split_of` as the original island start in epoch millis.
7
+ * The first row reuses that start. A last row with `open` stays pending
8
+ * (`duration == 0`). [[span]] widens the parent to the contiguous saved
9
+ * family when the new entries cover that whole island, so deleting one
10
+ * piece merges the rest.
11
+ *
12
+ * {{{
13
+ * SplitPieces.materialize(parent, List(
14
+ * SplitEntry(parent.start, Timestamp(160.0), "maintenance"),
15
+ * SplitEntry(Timestamp(160.0), parent.end, "")
16
+ * ))
17
+ * }}}
18
+ */
19
+ object SplitPieces:
20
+ def originKey(start: Timestamp): String = start.millis.toString
21
+
22
+ def row(origin: Timestamp, entry: SplitEntry): TaggedSegment =
23
+ val duration = if entry.open then 0.0 else entry.end.minus(entry.start)
24
+ val tags = if entry.tag.isEmpty then Nil else List(entry.tag)
25
+ TaggedSegment(
26
+ Segment("off", entry.start, entry.end, duration),
27
+ tags,
28
+ Nil,
29
+ Map("split_of" -> originKey(origin))
30
+ )
31
+
32
+ def span(anchor: TaggedSegment, rows: List[TaggedSegment], entries: List[SplitEntry]): Segment =
33
+ val key = anchor.properties.getOrElse("split_of", originKey(anchor.segment.start))
34
+ val kin = rows.filter(row => row.segment.name == "off" && row.properties.get("split_of").contains(key))
35
+ .sortBy(_.segment.start.millis)
36
+ val run = pieceRun(anchor, kin)
37
+ if run.nonEmpty && covers(run, entries) then bounds(run) else anchor.segment
38
+
39
+ private def pieceRun(anchor: TaggedSegment, kin: List[TaggedSegment]): List[TaggedSegment] =
40
+ val index = kin.indexWhere(_.segment.start.millis == anchor.segment.start.millis)
41
+ if index < 0 then Nil
42
+ else kin.slice(leftOf(kin, index), rightOf(kin, index) + 1)
43
+
44
+ private def leftOf(kin: List[TaggedSegment], index: Int): Int =
45
+ if index == 0 || kin(index - 1).segment.end.millis != kin(index).segment.start.millis then index
46
+ else leftOf(kin, index - 1)
47
+
48
+ private def rightOf(kin: List[TaggedSegment], index: Int): Int =
49
+ if index == kin.length - 1 || kin(index).segment.end.millis != kin(index + 1).segment.start.millis then index
50
+ else rightOf(kin, index + 1)
51
+
52
+ private def covers(run: List[TaggedSegment], entries: List[SplitEntry]): Boolean =
53
+ val ordered = entries.sortBy(_.start.millis)
54
+ val head = run.head.segment
55
+ val tail = run.last.segment
56
+ ordered.nonEmpty && ordered.head.start.millis == head.start.millis &&
57
+ (if tail.duration == 0.0 then ordered.last.open else !ordered.last.open && ordered.last.end.millis == tail.end.millis)
58
+
59
+ private def bounds(run: List[TaggedSegment]): Segment =
60
+ val head = run.head.segment
61
+ val tail = run.last.segment
62
+ val duration = if tail.duration == 0.0 then 0.0 else tail.end.minus(head.start)
63
+ Segment("off", head.start, tail.end, duration)
64
+
65
+ def materialize(parent: Segment, entries: List[SplitEntry]): List[TaggedSegment] =
66
+ if parent.name != "off" then
67
+ throw new IllegalArgumentException(
68
+ s"refusing to split ${parent.name} starting at ${parent.start.millis}"
69
+ )
70
+ if entries.isEmpty then
71
+ throw new IllegalArgumentException(
72
+ s"refusing an empty split of off at ${parent.start.millis}"
73
+ )
74
+ val ordered = entries.sortBy(_.start.epoch)
75
+ if ordered.head.start.millis != parent.start.millis then
76
+ throw new IllegalArgumentException(
77
+ s"split of off at ${parent.start.millis} must keep that start, got ${ordered.head.start.millis}"
78
+ )
79
+ if !ordered.exists(_.tag.nonEmpty) then
80
+ throw new IllegalArgumentException(
81
+ s"split of off at ${parent.start.millis} has no tagged piece"
82
+ )
83
+ ordered.zipWithIndex.foreach: (entry, index) =>
84
+ val last = index == ordered.length - 1
85
+ if entry.open && !last then
86
+ throw new IllegalArgumentException(
87
+ s"open piece at ${entry.start.millis} is not the tail of off at ${parent.start.millis}"
88
+ )
89
+ if index > 0 && ordered(index - 1).end.millis != entry.start.millis then
90
+ throw new IllegalArgumentException(
91
+ s"split of off at ${parent.start.millis} has a gap before ${entry.start.millis}"
92
+ )
93
+ val span = entry.end.minus(entry.start)
94
+ if span < 0 then
95
+ throw new IllegalArgumentException(
96
+ s"piece at ${entry.start.millis} ends before it starts"
97
+ )
98
+ if parent.duration != 0.0 && (ordered.last.open || ordered.last.end.millis != parent.end.millis) then
99
+ throw new IllegalArgumentException(
100
+ s"closed off at ${parent.start.millis} must be covered through ${parent.end.millis}"
101
+ )
102
+ ordered.map(entry => row(parent.start, entry))
@@ -0,0 +1,66 @@
1
+ package scada.supervisor.core
2
+
3
+ import cats.effect.Async
4
+ import cats.syntax.all.*
5
+ import fs2.Stream
6
+ import scala.concurrent.duration.*
7
+
8
+ /**
9
+ * Per-machine processing loop. Takes readings in, emits
10
+ * [[TaggedSegment]]s through a [[Segments]] collection as each
11
+ * segment opens and closes.
12
+ *
13
+ * The outbound stream is supplied by the caller so the supervisor
14
+ * stays transport-agnostic (live MQTT, replay, or test feed all plug
15
+ * in through the same `readings` parameter).
16
+ *
17
+ * A restored pending island is written before live readings. While that
18
+ * island stays open, a one-second pulse advances `end` so a silent
19
+ * machine still heartbeats the tape instead of leaving a hole until now.
20
+ *
21
+ * {{{
22
+ * Supervisor[F](segmentation, tagging, segments).run(machine, readings, None)
23
+ * }}}
24
+ */
25
+ final class Supervisor[F[_]: Async](
26
+ segmentation: Segmentation[F],
27
+ tagging: Tagging,
28
+ segments: Segments[F],
29
+ phases: CyclePhases = CyclePhases.empty,
30
+ customRun: Option[(MachineConfig, Stream[F, Reading], Segments[F]) => F[Unit]] = None
31
+ ):
32
+ def run(machine: MachineConfig, readings: Stream[F, Reading], initial: Option[SegmentCursor] = None): F[Unit] =
33
+ if machine.mode.isDefined then
34
+ customRun.getOrElse(throw IllegalStateException("Machine mode has no configured runner"))(machine,readings,segments)
35
+ else
36
+ val classified = readings
37
+ .through(segmentation.flow(machine, initial))
38
+ .evalMap(emission => write(machine, tagging.resolve(machine.tags, emission.value)))
39
+ val beats = Stream.awakeEvery[F](1.second).evalMap(_ => pulse(machine)).drain
40
+ open(machine, initial) *> classified.mergeHaltL(beats).compile.drain
41
+
42
+ private def open(machine: MachineConfig, initial: Option[SegmentCursor]): F[Unit] =
43
+ initial.fold(Async[F].unit): cursor =>
44
+ write(machine, TaggedSegment(Segment(cursor.name, cursor.start, cursor.end, 0.0), Nil, Nil, Map.empty))
45
+
46
+ private def pulse(machine: MachineConfig): F[Unit] =
47
+ segments.list(machine.id).flatMap: rows =>
48
+ Async[F].realTime.map(_.toMillis).flatMap: millis =>
49
+ val now = Timestamp(millis.toDouble / 1000.0)
50
+ val open = rows.filter(_.segment.duration == 0).sortBy(_.segment.start.epoch).lastOption
51
+ open.fold(cover(machine, rows, now))(tagged => extend(machine, tagged, now))
52
+
53
+ private def extend(machine: MachineConfig, tagged: TaggedSegment, now: Timestamp): F[Unit] =
54
+ if now.isAfter(tagged.segment.end) then write(machine, tagged.copy(segment = tagged.segment.copy(end = now)))
55
+ else Async[F].unit
56
+
57
+ private def cover(machine: MachineConfig, rows: List[TaggedSegment], now: Timestamp): F[Unit] =
58
+ rows.sortBy(_.segment.end.epoch).lastOption.fold(Async[F].unit): last =>
59
+ if !now.isAfter(last.segment.end) then Async[F].unit
60
+ else write(machine, TaggedSegment(Segment(last.segment.name, last.segment.end, now, 0.0), Nil, Nil, Map.empty))
61
+
62
+ private def write(machine: MachineConfig, tagged: TaggedSegment): F[Unit] =
63
+ if phases.isEmpty then segments.upsert(machine.id, tagged)
64
+ else
65
+ segments.list(machine.id).flatMap: all =>
66
+ segments.upsert(machine.id, phases.narrow(tagged, all))
@@ -0,0 +1,12 @@
1
+ package scada.supervisor.core
2
+
3
+ /**
4
+ * One conditional label. When exactly one [[TagDef]] matches a
5
+ * [[Segment]] the label is applied automatically; when several match
6
+ * they land in `options` and trigger a [[Decision]].
7
+ *
8
+ * {{{
9
+ * TagDef("running", Condition.When("on"))
10
+ * }}}
11
+ */
12
+ final case class TagDef(name: String, condition: Condition)
@@ -0,0 +1,19 @@
1
+ package scada.supervisor.core
2
+
3
+ /**
4
+ * A [[Segment]] decorated with tagging output:
5
+ * - `tags` — labels applied automatically or after a decision;
6
+ * - `options` — labels the operator still has to choose between
7
+ * (non-empty means awaiting [[Decision]]);
8
+ * - `properties` — operator-attached metadata.
9
+ *
10
+ * {{{
11
+ * TaggedSegment(segment, List("running"), Nil, Map.empty)
12
+ * }}}
13
+ */
14
+ final case class TaggedSegment(
15
+ segment: Segment,
16
+ tags: List[String],
17
+ options: List[String],
18
+ properties: Map[String, String]
19
+ )
@@ -0,0 +1,42 @@
1
+ package scada.supervisor.core
2
+
3
+ /**
4
+ * Pure tagging of a [[Segment]] against a list of [[TagDef]]s.
5
+ *
6
+ * Matching:
7
+ * - with empty `currentTags`, candidates whose `when` equals the segment name;
8
+ * - with non-empty `currentTags`, candidates whose `when` is in that path.
9
+ *
10
+ * Cascade:
11
+ * - no matches → keep `currentTags`, empty options (leaf / done);
12
+ * - one match → append and continue (auto-deepen);
13
+ * - many → keep path as tags, list matches as options.
14
+ *
15
+ * {{{
16
+ * Tagging().resolve(tagDefs, segment)
17
+ * Tagging().resolve(tagDefs, segment, List("metal_structure"))
18
+ * }}}
19
+ */
20
+ final class Tagging(allow: Segment => Boolean = _ => true):
21
+ def resolve(tagDefs: List[TagDef], segment: Segment): TaggedSegment =
22
+ resolve(tagDefs, segment, Nil)
23
+
24
+ def resolve(tagDefs: List[TagDef], segment: Segment, currentTags: List[String]): TaggedSegment =
25
+ if allow(segment) then deepen(tagDefs, segment, currentTags)
26
+ else TaggedSegment(segment, Nil, Nil, segment.properties)
27
+
28
+ private def deepen(tagDefs: List[TagDef], segment: Segment, currentTags: List[String]): TaggedSegment =
29
+ val matching = candidates(tagDefs, segment, currentTags)
30
+ matching match
31
+ case Nil => TaggedSegment(segment, currentTags, Nil, segment.properties)
32
+ case one :: Nil => deepen(tagDefs, segment, currentTags :+ one)
33
+ case many => TaggedSegment(segment, currentTags, many, segment.properties)
34
+
35
+ private def candidates(tagDefs: List[TagDef], segment: Segment, currentTags: List[String]): List[String] =
36
+ tagDefs.collect:
37
+ case TagDef(name, Condition.When(when)) if matches(when, segment, currentTags) && !currentTags.contains(name) =>
38
+ name
39
+
40
+ private def matches(when: String, segment: Segment, currentTags: List[String]): Boolean =
41
+ if currentTags.isEmpty then when == segment.name
42
+ else currentTags.contains(when)
@@ -0,0 +1,26 @@
1
+ package scada.supervisor.core
2
+
3
+ /**
4
+ * Epoch seconds (double, millisecond precision) as an opaque type so
5
+ * it stays allocation-free in segmentation hot paths yet never mixes
6
+ * with raw numeric values.
7
+ *
8
+ * {{{
9
+ * val t = Timestamp(1700000000.0)
10
+ * t.minus(Timestamp(1699999985.0))
11
+ * }}}
12
+ */
13
+ opaque type Timestamp = Double
14
+
15
+ object Timestamp:
16
+ def apply(epochSeconds: Double): Timestamp = epochSeconds
17
+
18
+ given Ordering[Timestamp] = Ordering.Double.TotalOrdering
19
+
20
+ extension (self: Timestamp)
21
+ def epoch: Double = self
22
+ def millis: Long = (self * 1000).toLong
23
+ def minus(other: Timestamp): Double = self - other
24
+ def plus(seconds: Double): Timestamp = self + seconds
25
+ def isAfter(other: Timestamp): Boolean = self > other
26
+ def isBefore(other: Timestamp): Boolean = self < other
@@ -0,0 +1,43 @@
1
+ package scada.supervisor.core.segmentation
2
+
3
+ import scada.supervisor.core.{Params, SegmentDef}
4
+
5
+ /** Transitions over classified samples in input order. The coordinate type is
6
+ * chosen by the caller and is never rounded or compared here.
7
+ */
8
+ object Timeline:
9
+ enum Boundary:
10
+ case Live, Observed
11
+
12
+ final case class Interval[+A](name: String, start: A, end: A)
13
+
14
+ enum Event[+A]:
15
+ case Sample(at: A, name: String, continuous: Boolean)
16
+ case DeadlineExpired(at: A)
17
+ case EndOfInput
18
+
19
+ enum Output[+A]:
20
+ case Pending(interval: Interval[A])
21
+ case Closed(interval: Interval[A])
22
+
23
+ final case class Result[A](open: Option[Interval[A]], outputs: Vector[Output[A]])
24
+
25
+ def classifier(definitions: List[SegmentDef]): Params => Option[String] =
26
+ val lookup = (name: String) => definitions.find(_.name == name).map(_.condition)
27
+ params => definitions.find(_.condition.matches(params, lookup)).map(_.name)
28
+
29
+ def step[A](boundary: Boundary, open: Option[Interval[A]], event: Event[A]): Result[A] =
30
+ event match
31
+ case Event.Sample(at, name, continuous) =>
32
+ open match
33
+ case Some(previous) if continuous && previous.name == name =>
34
+ val updated = previous.copy(end = at)
35
+ Result(Some(updated), Vector(Output.Pending(updated)))
36
+ case _ =>
37
+ val next = Interval(name, at, at)
38
+ val closed = open.map: previous =>
39
+ val end = if boundary == Boundary.Live && previous.name != name then at else previous.end
40
+ Output.Closed(previous.copy(end = end))
41
+ Result(Some(next), closed.toVector :+ Output.Pending(next))
42
+ // The existing policies keep the last interval open through silence and finite EOF.
43
+ case Event.DeadlineExpired(_) | Event.EndOfInput => Result(open, Vector.empty)
@@ -0,0 +1,61 @@
1
+ package scada.supervisor.infra.checkpoint
2
+
3
+ import cats.effect.IO
4
+ import fs2.Stream
5
+ import scada.supervisor.core.*
6
+
7
+ /**
8
+ * One raw metric row used to seed segmentation on startup.
9
+ *
10
+ * {{{
11
+ * RawReadingData("machine-1/power", Timestamp(1700000000.0), 42.0)
12
+ * }}}
13
+ */
14
+ final case class RawReadingData(topic: String, timestamp: Timestamp, value: Double)
15
+
16
+ /** One pending segment row from `segments` where `duration = 0`. */
17
+ final case class PendingSegmentData(machine: MachineId, name: String, start: Timestamp, end: Timestamp)
18
+
19
+ /**
20
+ * Historical readings boundary. Returns rows strictly newer than the
21
+ * supplied watermark so the supervisor can replay them deterministically
22
+ * before taking the live MQTT stream. Abstract over the backing store
23
+ * so unit tests can substitute an in-memory fake.
24
+ */
25
+ trait Checkpoint:
26
+ /**
27
+ * Replay cursor derived from persisted segments for one machine.
28
+ *
29
+ * Rule:
30
+ * - `closedEnd` = max(end_time) where `duration > 0`
31
+ * - `pendingStart` = max(start_time) where `duration = 0`
32
+ * - cursor = min(closedEnd, pendingStart) when pending exists,
33
+ * else closedEnd, else 0.0
34
+ *
35
+ * This keeps replay anchored to durable segment state while still
36
+ * rewinding to the pending boundary when an open segment exists.
37
+ */
38
+ def fetchReplayCursor(machine: MachineId): IO[Timestamp]
39
+
40
+ def fetchReadings(topics: List[String], from: Timestamp): Stream[IO, RawReadingData]
41
+
42
+ /** Required-history recovery retries a failed fetch instead of treating it as an empty history. */
43
+ def fetchRequiredReadings(topics: List[String], from: Timestamp): Stream[IO, RawReadingData] =
44
+ fetchReadings(topics, from)
45
+
46
+ /** Pending open segments (`duration = 0`), for island resume. */
47
+ def fetchPendingSegments: IO[List[PendingSegmentData]]
48
+
49
+ /** One closed segment row at an exact start timestamp, if present. */
50
+ def fetchSegment(machine: MachineId, start: Timestamp): IO[Option[TaggedSegment]]
51
+
52
+ /** Offs before `before` until a reset tag, chronological. Empty when unused. */
53
+ def fetchCyclePrior(machine: MachineId, before: Timestamp, reset: List[String]): IO[List[TaggedSegment]] =
54
+ IO.pure(Nil)
55
+
56
+ object Checkpoint:
57
+ def empty: Checkpoint = new Checkpoint:
58
+ def fetchReplayCursor(machine: MachineId): IO[Timestamp] = IO.pure(Timestamp(0.0))
59
+ def fetchReadings(topics: List[String], from: Timestamp): Stream[IO, RawReadingData] = Stream.empty
60
+ def fetchPendingSegments: IO[List[PendingSegmentData]] = IO.pure(Nil)
61
+ def fetchSegment(machine: MachineId, start: Timestamp): IO[Option[TaggedSegment]] = IO.pure(None)
@@ -0,0 +1,76 @@
1
+ package scada.supervisor.infra.checkpoint
2
+
3
+ import cats.effect.IO
4
+ import cats.syntax.all.*
5
+ import fs2.Stream
6
+ import io.circe.parser.parse
7
+ import java.net.URI
8
+ import java.net.http.{HttpClient, HttpRequest, HttpResponse}
9
+ import java.time.Duration
10
+ import scada.supervisor.core.*
11
+ import scada.supervisor.infra.config.ClickhouseReadingsConfig
12
+
13
+ /**
14
+ * Decorator that overrides readings fetch with ClickHouse paging.
15
+ */
16
+ final class ClickhouseReadingsCheckpoint(base: Checkpoint, config: ClickhouseReadingsConfig) extends Checkpoint:
17
+
18
+ private val client = HttpClient.newBuilder()
19
+ .connectTimeout(Duration.ofSeconds(config.timeoutSeconds.toLong))
20
+ .build()
21
+
22
+ def fetchReplayCursor(machine: MachineId): IO[Timestamp] =
23
+ base.fetchReplayCursor(machine)
24
+
25
+ def fetchPendingSegments: IO[List[PendingSegmentData]] =
26
+ base.fetchPendingSegments
27
+
28
+ def fetchSegment(machine: MachineId, start: Timestamp): IO[Option[TaggedSegment]] =
29
+ base.fetchSegment(machine, start)
30
+
31
+ def fetchReadings(topics: List[String], from: Timestamp): Stream[IO, RawReadingData] =
32
+ if topics.isEmpty then Stream.empty
33
+ else loop(topics, from, 0)
34
+
35
+ private def loop(topics: List[String], from: Timestamp, offset: Int): Stream[IO, RawReadingData] =
36
+ Stream.eval(page(topics, from, offset)).flatMap: rows =>
37
+ if rows.isEmpty then Stream.empty
38
+ else Stream.emits(rows) ++ loop(topics, from, offset + rows.size)
39
+
40
+ private def page(topics: List[String], from: Timestamp, offset: Int): IO[List[RawReadingData]] =
41
+ val query = buildQuery(topics, from, offset)
42
+ val request = HttpRequest.newBuilder()
43
+ .uri(URI.create(s"${config.baseUrl}/?database=${config.database}"))
44
+ .timeout(Duration.ofSeconds(config.timeoutSeconds.toLong))
45
+ .header("Content-Type", "text/plain")
46
+ .POST(HttpRequest.BodyPublishers.ofString(query))
47
+ .build()
48
+ IO.blocking(client.send(request, HttpResponse.BodyHandlers.ofString())).flatMap: response =>
49
+ if response.statusCode() / 100 != 2 then
50
+ IO.raiseError(RuntimeException(s"clickhouse error ${response.statusCode()}: ${response.body()}"))
51
+ else
52
+ parseRows(response.body())
53
+
54
+ private def buildQuery(topics: List[String], from: Timestamp, offset: Int): String =
55
+ val topicsList = topics.map(quote).mkString(", ")
56
+ s"""SELECT topic, toFloat64(toUnixTimestamp64Milli(ts))/1000.0 as ts, value
57
+ |FROM ${config.table}
58
+ |WHERE topic IN ($topicsList)
59
+ | AND ts > fromUnixTimestamp64Milli(toInt64(${from.epoch} * 1000))
60
+ |ORDER BY ts ASC, topic ASC
61
+ |LIMIT ${config.batchSize} OFFSET $offset
62
+ |FORMAT JSONEachRow""".stripMargin
63
+
64
+ private def parseRows(body: String): IO[List[RawReadingData]] =
65
+ val lines = body.split('\n').toList.filter(_.nonEmpty)
66
+ lines.traverse: line =>
67
+ IO.fromEither(parse(line)).map: json =>
68
+ val cursor = json.hcursor
69
+ RawReadingData(
70
+ cursor.get[String]("topic").getOrElse(""),
71
+ Timestamp(cursor.get[Double]("ts").getOrElse(0.0)),
72
+ cursor.get[Double]("value").getOrElse(0.0)
73
+ )
74
+
75
+ private def quote(value: String): String =
76
+ s"'${value.replace("'", "''")}'"