@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,258 @@
1
+ package scada.supervisor.runtime
2
+
3
+ import cats.effect.{IO, Ref}
4
+ import cats.syntax.all.*
5
+ import fs2.Stream
6
+ import io.circe.Json
7
+ import io.circe.parser.parse
8
+ import io.yarkivaev.temporal.{LocalStreams, Observation, Processing, Work, Worker}
9
+ import java.net.URLEncoder
10
+ import java.nio.charset.StandardCharsets
11
+ import java.time.Instant
12
+ import scada.supervisor.core.*
13
+ import scada.supervisor.core.segmentation.Timeline
14
+ import scada.supervisor.core.segmentation.Timeline.{Boundary, Event, Interval, Output}
15
+ import scada.supervisor.infra.config.{AliasMapping, CheckpointApiConfig}
16
+ import scala.concurrent.duration.*
17
+
18
+ final case class HistoryRange(from: Long, until: Long)
19
+ final case class HistorySeed(time: Long, values: Map[String,Double], segment: Option[HistorySegment] = None)
20
+ final case class HistorySegment(name: String, start: Long, end: Long)
21
+ final case class HistoryState(position: Long, parameters: Map[String,(Long,Double)], segment: Option[HistorySegment])
22
+ final case class HistoryPool(cursors: LocalStreams, states: Map[Long,HistoryState]):
23
+ def expire(now: Long): HistoryPool =
24
+ val alive = cursors.evict(now)
25
+ copy(cursors = alive, states = states.filter((id,_) => alive.streams.exists(_.id == id)))
26
+ def completed(stream: Long, state: HistoryState): HistoryPool =
27
+ val advanced = cursors.copy(streams = cursors.streams.map(c => if c.id == stream then c.copy(position = state.position) else c))
28
+ val known = states.updated(stream,state).filter((id,_) => advanced.streams.exists(_.id == id))
29
+ val equal = known.toVector.filter((id,s) => id != stream && s == state).map(_._1)
30
+ val merged = equal.foldLeft(advanced)((pool,id) => pool.merge(stream,id,true))
31
+ HistoryPool(merged,known.filter((id,_) => merged.streams.exists(_.id == id)))
32
+ object LocalHistory:
33
+ def connected(before: Long, after: Long, gap: Long, continuity: Vector[HistoryRange]): Boolean =
34
+ before <= after && (BigInt(after)-BigInt(before) <= gap || continuity.exists(r => r.from <= before && r.until >= after))
35
+ def state(machine: MachineConfig, points: Vector[Observation], result: Vector[HistorySegment], seed: Option[HistorySeed] = None, continuity: Vector[HistoryRange] = Vector.empty): Option[HistoryState] =
36
+ points.map(_.time).maxOption.map: end =>
37
+ val gap = machine.window.toLong*2000
38
+ val state = points.groupBy(_.time).toVector.sortBy(_._1).foldLeft((seed.map(_.time),seed.fold(Map.empty[String,(Long,Double)])(s => s.values.map((k,v) => k -> (s.time,v))))):
39
+ case ((previous,values),(time,group)) =>
40
+ val prior = if previous.exists(t => connected(t,time,gap,continuity)) then values else Map.empty[String,(Long,Double)]
41
+ (Some(time),prior ++ group.map(p => p.channel -> (p.time,p.value)))
42
+ HistoryState(end,state._2,result.lastOption)
43
+
44
+ /** Finite event-time classification: never inject wall-clock silence into past data. */
45
+ def classify(machine: MachineConfig, points: Vector[Observation], seed: Option[HistorySeed] = None, continuity: Vector[HistoryRange] = Vector.empty): Vector[HistorySegment] =
46
+ val gap = machine.window.toLong * 2000
47
+ val classifyParams = Timeline.classifier(machine.segments)
48
+ val groups = points.groupBy(_.time).toVector.sortBy(_._1)
49
+ val initialSegment = seed.flatMap: initial =>
50
+ val stored = initial.segment.filter(_.start <= initial.time)
51
+ classifyParams(Params(initial.values)) match
52
+ case Some(name) => Some(stored.filter(_.name == name).getOrElse(HistorySegment(name,initial.time,initial.time)))
53
+ case None => stored
54
+ val initialOpen = initialSegment.map(row => Interval(row.name, row.start, row.end))
55
+ val initial = (seed.fold(Map.empty[String,Double])(_.values), seed.map(_.time), initialOpen, Vector.empty[Interval[Long]])
56
+ val (_, _, open, closed) = groups.foldLeft(initial):
57
+ case ((prior, previous, current, completed), (time, group)) =>
58
+ val continuous = previous.exists(t => connected(t,time,gap,continuity))
59
+ val values = (if continuous then prior else Map.empty) ++ group.map(p => p.channel -> p.value)
60
+ val name = classifyParams(Params(values)).orElse(if continuous then current.map(_.name) else None)
61
+ name match
62
+ case Some(n) =>
63
+ val next = Timeline.step(Boundary.Observed, current, Event.Sample(time, n, continuous))
64
+ val finished = next.outputs.collect { case Output.Closed(row) => row }
65
+ (values, Some(time), next.open, completed ++ finished)
66
+ case None => (values, Some(time), current, completed)
67
+ (closed ++ open).map(row => HistorySegment(row.name, row.start, row.end))
68
+
69
+ def sources(context: Json): Vector[Json] =
70
+ val current = context.hcursor.get[Vector[Json]]("segments").getOrElse(Vector.empty)
71
+ def identity(row: Json) = (row.hcursor.get[String]("kind").toOption,row.hcursor.get[String]("name").toOption,row.hcursor.get[String]("start_time").toOption)
72
+ val archived = context.hcursor.get[Vector[Json]]("annotations").getOrElse(Vector.empty).map: row =>
73
+ val metadata = current.find(value => identity(value) == identity(row)).fold(Json.obj()): value =>
74
+ Json.obj(Vector("tags","properties","resolved","consumed").map(key => key -> value.hcursor.downField(key).focus.getOrElse(Json.Null))*)
75
+ row.deepMerge(metadata).deepMerge(Json.obj("_historyArchive" -> Json.True))
76
+ (current ++ archived).distinctBy(row => (identity(row),row.hcursor.get[String]("end_time").toOption))
77
+
78
+ def duration(segment: HistorySegment, tailEnd: Long, rightClosed: Boolean): Double =
79
+ if !rightClosed && segment.end == tailEnd then 0.0 else (segment.end-segment.start)/1000.0
80
+
81
+ def metadata(row: Json, key: String, fallback: Json): Json =
82
+ row.hcursor.downField(key).focus.filterNot(_.isNull).map(v => v.asString.flatMap(t => parse(t).toOption).getOrElse(v)).getOrElse(fallback)
83
+
84
+ /**
85
+ * Attaches operator metadata without slicing one continuous classification.
86
+ * A stored seam is kept when the pieces that meet there differ by name or tags,
87
+ * or when the new class differs from those stored pieces.
88
+ * The same state running past its last stored end stays one segment.
89
+ */
90
+ def overlay(result: Vector[HistorySegment], existing: Vector[Json], continuation: Boolean = false): Vector[(HistorySegment,Json)] =
91
+ def instant(row: Json, key: String): Long = row.hcursor.get[String](key).toOption.map(Instant.parse(_).toEpochMilli).getOrElse(0L)
92
+ def mark(row: Json): (String, String) =
93
+ val name = row.hcursor.get[String]("name").getOrElse("")
94
+ val raw = row.hcursor.downField("tags").focus.getOrElse(Json.Null)
95
+ (name, raw.asString.flatMap(text => parse(text).toOption).getOrElse(raw).noSpaces)
96
+ def kept(segmentName: String, at: Long, from: Long, until: Long): Boolean =
97
+ val ending = existing.filter(row => instant(row, "end_time") == at)
98
+ val starting = existing.filter(row => instant(row, "start_time") == at)
99
+ val later = existing.filter(row => instant(row, "start_time") > at && instant(row, "start_time") < until)
100
+ val earlier = existing.filter(row => instant(row, "end_time") <= at && instant(row, "end_time") > from)
101
+ val foreign = (ending ++ starting).exists(row => !row.hcursor.get[String]("name").toOption.contains(segmentName))
102
+ if ending.nonEmpty && starting.nonEmpty then foreign || ending.exists(left => starting.exists(right => mark(left) != mark(right)))
103
+ else if ending.nonEmpty then ending.exists(row => !row.hcursor.get[String]("name").toOption.contains(segmentName)) || later.exists(row => ending.exists(left => mark(left) != mark(row)))
104
+ else starting.exists(row => !row.hcursor.get[String]("name").toOption.contains(segmentName)) || earlier.exists(row => starting.exists(right => mark(row) != mark(right)))
105
+ val cuts = existing.flatMap: row =>
106
+ val start = instant(row,"start_time")
107
+ val end = instant(row,"end_time")
108
+ if continuation && row.hcursor.get[Double]("duration").toOption.contains(0.0) then Vector(start) else Vector(start,end)
109
+ .distinct.sorted
110
+ result.zipWithIndex.flatMap: (segment,index) =>
111
+ val matches = existing.filter(row => row.hcursor.get[String]("name").toOption.contains(segment.name) && ((instant(row,"start_time") < segment.end && instant(row,"end_time") > segment.start) ||
112
+ (segment.start == segment.end && instant(row,"start_time") <= segment.start && instant(row,"end_time") >= segment.start) ||
113
+ (instant(row,"start_time") == segment.start && instant(row,"end_time") == segment.end)))
114
+ val current = matches.filterNot(_.hcursor.get[Boolean]("_historyArchive").getOrElse(false))
115
+ val owners = if current.nonEmpty then current else matches
116
+ val proposedStart = if index == 0 then owners.map(instant(_,"start_time")).minOption.fold(segment.start)(_.min(segment.start)) else segment.start
117
+ val proposedEnd = if index == result.size-1 then owners.map(instant(_,"end_time")).maxOption.fold(segment.end)(_.max(segment.end)) else segment.end
118
+ val blockers = existing.filter(row => !row.hcursor.get[Boolean]("_historyArchive").getOrElse(false) && !row.hcursor.get[String]("name").toOption.contains(segment.name))
119
+ val start = blockers.filter(row => instant(row,"start_time") < segment.start && instant(row,"end_time") > proposedStart)
120
+ .map(row => instant(row,"end_time").min(segment.start)).foldLeft(proposedStart)(_.max(_))
121
+ val end = blockers.filter(row => instant(row,"end_time") > segment.end && instant(row,"start_time") < proposedEnd)
122
+ .map(row => instant(row,"start_time").max(segment.end)).foldLeft(proposedEnd)(_.min(_))
123
+ val boundaries = Vector(start) ++ cuts.filter(t => t > start && t < end && kept(segment.name, t, start, end)) ++ Vector(end)
124
+ boundaries.sliding(2).collect:
125
+ case Vector(a,b) =>
126
+ val left = owners.map(instant(_,"start_time")).minOption
127
+ val right = owners.map(instant(_,"end_time")).maxOption
128
+ val covered = owners.filter(row => instant(row,"start_time") >= a && instant(row,"end_time") <= b)
129
+ val inherited = owners.find(row => instant(row,"start_time") <= a && instant(row,"end_time") >= b).orElse(owners.find(row => instant(row,"start_time") <= a && instant(row,"end_time") > a)).orElse {
130
+ if left.exists(b <= _) then owners.find(row => left.contains(instant(row,"start_time")))
131
+ else if right.exists(a >= _) then owners.find(row => right.contains(instant(row,"end_time")))
132
+ else None
133
+ }.orElse(if covered.map(mark).distinct.size == 1 then covered.headOption else None).getOrElse(Json.Null)
134
+ (segment.copy(start = a,end = b),inherited)
135
+ .toVector
136
+
137
+ val nativeTailProtocol = "preserve-known-suffix-v1"
138
+ private def instant(row: Json, key: String): Long =
139
+ row.hcursor.get[String](key).toOption.map(Instant.parse(_).toEpochMilli).getOrElse(0L)
140
+
141
+ /** Send observed changes plus only CAS-proved exterior already present in this context. */
142
+ def commitRows(machine: MachineConfig, result: Vector[HistorySegment], context: Json, continuation: Boolean = false): Vector[Json] =
143
+ val current = context.hcursor.get[Vector[Json]]("segments").getOrElse(Vector.empty)
144
+ val pageEnd = context.hcursor.downField("page").get[Long]("until").toOption
145
+ val overlaid = overlay(result,sources(context),continuation)
146
+ val bounded = overlaid.flatMap: (segment,inherited) =>
147
+ val owner = current.find(row => row.hcursor.get[String]("name").toOption.contains(segment.name) &&
148
+ instant(row,"start_time") <= segment.start && instant(row,"end_time") >= segment.end)
149
+ val terminalAnchor = pageEnd.exists(end => segment.start == end) && owner.exists(row =>
150
+ instant(row,"start_time") == segment.start && instant(row,"end_time") > segment.start)
151
+ if terminalAnchor then None
152
+ else
153
+ val exterior = owner.filter(row => pageEnd.exists(end => instant(row,"end_time") > end) && segment.end == instant(row,"end_time"))
154
+ val end = if exterior.nonEmpty then segment.end else pageEnd.fold(segment.end)(_.min(segment.end))
155
+ Some((segment.copy(end = end),inherited,exterior))
156
+ val suffixes = pageEnd.toVector.flatMap: until =>
157
+ current.filter(row => instant(row,"end_time") > until).flatMap: owner =>
158
+ val changed = bounded.exists((segment,_,_) => segment.start == instant(owner,"start_time") &&
159
+ (segment.name != owner.hcursor.get[String]("name").getOrElse("") || segment.end < instant(owner,"end_time")))
160
+ val retained = bounded.exists((_,_,proof) => proof.contains(owner))
161
+ if !changed || retained then None
162
+ else Some((HistorySegment(owner.hcursor.get[String]("name").getOrElse(""),until+1,instant(owner,"end_time")),owner,Some(owner)))
163
+ val rows = bounded ++ suffixes
164
+ rows.filter((segment,_,_) => segment.start <= segment.end).map: (segment,inherited,proof) =>
165
+ val unchanged = proof.exists(owner => instant(owner,"start_time") == segment.start && instant(owner,"end_time") == segment.end)
166
+ val duration = if proof.exists(_.hcursor.get[Double]("duration").toOption.contains(0.0)) then 0.0 else if unchanged then inherited.hcursor.get[Double]("duration").getOrElse(0.0) else LocalHistory.duration(segment,result.lastOption.map(_.end).getOrElse(segment.end),context.hcursor.get[Boolean]("rightClosed").getOrElse(false))
167
+ val base = Segment(segment.name,Timestamp(segment.start/1000.0),Timestamp(segment.end/1000.0),duration)
168
+ val tagged = Tagging().resolve(machine.tags,base)
169
+ Json.obj("kind" -> inherited.hcursor.get[String]("kind").toOption.map(Json.fromString).getOrElse(Json.fromString("phase")),"name" -> Json.fromString(segment.name),
170
+ "start_time" -> Json.fromString(Instant.ofEpochMilli(segment.start).toString),
171
+ "end_time" -> Json.fromString(Instant.ofEpochMilli(segment.end).toString),
172
+ "duration" -> Json.fromDoubleOrNull(base.duration),
173
+ "consumed" -> Json.fromBoolean(inherited.hcursor.get[Boolean]("consumed").getOrElse(true)),
174
+ "resolved" -> Json.fromBoolean(inherited.hcursor.get[Boolean]("resolved").getOrElse(tagged.tags.nonEmpty)),
175
+ "tags" -> LocalHistory.metadata(inherited,"tags",Json.arr(tagged.tags.map(Json.fromString)*)),
176
+ "options" -> LocalHistory.metadata(inherited,"options",Json.arr(tagged.options.map(Json.fromString)*)),
177
+ "properties" -> LocalHistory.metadata(inherited,"properties",Json.obj(tagged.properties.toVector.map((k,v) => k -> Json.fromString(v))*))).deepMerge(proof.fold(Json.obj())(owner => Json.obj("preserveSuffix" -> owner)))
178
+
179
+ /** Durable HTTP work queue is local to the receiving edge. Failed requests retry without acknowledging input. */
180
+ final class LocalHistory(config: CheckpointApiConfig, machine: MachineConfig, announce: Vector[Json] => IO[Unit] = _ => IO.unit):
181
+ private val transport=HistoryClient(config)
182
+ import transport.{request,retry}
183
+ private val encoded = URLEncoder.encode(machine.id.raw,StandardCharsets.UTF_8)
184
+ def configure(aliases: List[AliasMapping]): IO[Unit] =
185
+ val topics = aliases.map(a => Json.obj("topic" -> Json.fromString(a.topic),"channel" -> Json.fromString(a.metric)))
186
+ retry(request("POST","/v1/history/config",Json.obj("machine" -> Json.fromString(machine.id.raw),"topics" -> Json.arr(topics*)))).flatMap: response =>
187
+ IO.raiseUnless(response.hcursor.get[String]("nativeTailProtocol").toOption.contains(LocalHistory.nativeTailProtocol))(new IllegalStateException("History receiver does not preserve known segment suffixes"))
188
+ def accept(reading: Reading): IO[Unit] =
189
+ val observations = reading.params.values.toVector.map: (channel,value) =>
190
+ Json.obj("eventId" -> Json.fromString(s"${machine.id.raw}:$channel:${reading.timestamp.millis}:$value"),
191
+ "channel" -> Json.fromString(channel),"time" -> Json.fromLong(reading.timestamp.millis),"value" -> Json.fromDoubleOrNull(value))
192
+ retry(request("POST","/v1/history/observations",Json.obj("machine" -> Json.fromString(machine.id.raw),"observations" -> Json.arr(observations*)))).void
193
+ def process: Stream[IO,Unit] =
194
+ Stream.eval(Ref.of[IO,HistoryPool](HistoryPool(LocalStreams.empty(machine.window.toLong*2000,10000),Map.empty))).flatMap: pool =>
195
+ Stream.repeatEval(IO.monotonic.flatMap(now => pool.update(_.expire(now.toMillis))) *> retry(request("GET",s"/v1/history/work?machine=$encoded"))).flatMap: body =>
196
+ val work = body.hcursor.get[Vector[Json]]("items").getOrElse(Vector.empty)
197
+ Stream.emits(work).covary[IO].evalMap(raw => run(raw,pool).attempt.flatTap(_.left.toOption.traverse_(error => IO.println(s"Local history work deferred: ${error.getMessage}")))).collect { case Right(_) => () }.append(Stream.sleep_[IO](1.second))
198
+ private def run(raw: Json, pool: Ref[IO,HistoryPool]): IO[Unit] =
199
+ val cursor = raw.hcursor
200
+ for
201
+ id <- IO.fromEither(cursor.get[String]("id"))
202
+ token <- IO.fromEither(cursor.get[String]("token"))
203
+ from <- IO.fromEither(cursor.get[Long]("from"))
204
+ until <- IO.fromEither(cursor.get[Long]("until"))
205
+ now <- IO.monotonic.map(_.toMillis)
206
+ routed <- pool.modify: previous =>
207
+ val routed = previous.cursors.evict(now).route(Observation(id,"work",from,0),now)
208
+ // Cursors are a bounded cache; receiver work remains durable when a cursor is evicted.
209
+ val kept = routed.state.copy(streams = routed.state.streams.takeRight(64))
210
+ (HistoryPool(kept,previous.states.filter((id,_) => kept.streams.exists(_.id == id))),routed.work.copy(from = from,until = until))
211
+ committed <- Ref.of[IO,Boolean](false)
212
+ calculated <- Ref.of[IO,Option[HistoryState]](None)
213
+ snapshot <- Ref.of[IO,Json](Json.Null)
214
+ ports = new Processing[IO,HistorySegment]:
215
+ def context(work: Work): IO[Option[Vector[Observation]]] =
216
+ request("GET",s"/v1/history/context?machine=$encoded&from=$from&until=$until&paddingMs=${machine.window.toLong*2000}" + raw.hcursor.get[Long]("cursor").toOption.fold("")(value => s"&cursor=$value") + raw.hcursor.get[Long]("end").toOption.fold("")(value => s"&end=$value")).flatTap(snapshot.set).flatMap: response =>
217
+ if !response.hcursor.get[Boolean]("available").getOrElse(false) then IO.pure(None)
218
+ else IO.fromEither(response.hcursor.get[Vector[Json]]("items").flatMap(_.traverse: item =>
219
+ val p = item.hcursor
220
+ for
221
+ event <- p.get[String]("eventId")
222
+ channel <- p.get[String]("channel")
223
+ time <- p.get[Long]("time")
224
+ value <- p.get[Double]("value")
225
+ yield Observation(event,channel,time,value)
226
+ )).map(Some(_))
227
+ def classify(work: Work, points: Vector[Observation]): IO[Vector[HistorySegment]] =
228
+ snapshot.get.flatMap: context =>
229
+ val initial = context.hcursor.downField("initial")
230
+ val seed = for
231
+ time <- initial.get[Long]("time").toOption
232
+ values <- initial.get[Map[String,Double]]("values").toOption
233
+ yield
234
+ val prior = initial.downField("segment")
235
+ val segment = for
236
+ name <- prior.get[String]("name").toOption
237
+ start <- prior.get[String]("start_time").toOption.flatMap(t => scala.util.Try(Instant.parse(t).toEpochMilli).toOption)
238
+ yield HistorySegment(name,start,time)
239
+ HistorySeed(time,values,segment)
240
+ val continuity = context.hcursor.get[Vector[Json]]("continuity").getOrElse(Vector.empty).flatMap: row =>
241
+ for
242
+ from <- row.hcursor.get[Long]("from").toOption
243
+ until <- row.hcursor.get[Long]("until").toOption
244
+ yield HistoryRange(from,until)
245
+ val result = LocalHistory.classify(machine,points,seed,continuity)
246
+ calculated.set(LocalHistory.state(machine,points,result,seed,continuity)).as(result)
247
+ def commit(work: Work, result: Vector[HistorySegment]): IO[Unit] =
248
+ snapshot.get.flatMap: context =>
249
+ val rows = LocalHistory.commitRows(machine,result,context,raw.hcursor.get[Long]("cursor").toOption.isDefined)
250
+ request("POST","/v1/history/commit",Json.obj("machine" -> Json.fromString(machine.id.raw),"workId" -> Json.fromString(id),"segments" -> Json.arr(rows*), "context" -> context.hcursor.downField("context").focus.getOrElse(Json.obj()).deepMerge(Json.obj("nativeTailMode" -> Json.fromString(LocalHistory.nativeTailProtocol),"revision" -> context.hcursor.downField("revision").focus.getOrElse(Json.Null),"workToken" -> Json.fromString(token))))).flatTap(_ => announce(rows) *> committed.set(true)).void
251
+ def acknowledge(work: Work): IO[Unit] =
252
+ committed.get.flatMap(done => if done then IO.unit else request("POST","/v1/history/commit",Json.obj("machine" -> Json.fromString(machine.id.raw),"workId" -> Json.fromString(id),"segments" -> Json.arr(),"context" -> Json.obj("workToken" -> Json.fromString(token),"from" -> Json.fromLong(from),"until" -> Json.fromLong(until)))).void)
253
+ _ <- Worker(ports).run(routed).guarantee(pool.update(p => p.copy(cursors = p.cursors.acknowledge(routed.id))))
254
+ result <- calculated.get
255
+ _ <- pool.update: previous =>
256
+ val completed = result.fold(previous)(previous.completed(routed.streamId,_))
257
+ completed.copy(cursors = completed.cursors.acknowledge(routed.id))
258
+ yield ()
@@ -0,0 +1,26 @@
1
+ package scada.supervisor.runtime
2
+
3
+ /**
4
+ * Lets a standby classify only after local observations cover a real replicated segment.
5
+ * A leader may start when nothing has been replicated. Zero is a missing row, not a watermark.
6
+ *
7
+ * {{{
8
+ * ObservationLead.ready(1790000005000L, Some(1790000005000L), false)
9
+ * ObservationLead.ready(0L, None, true)
10
+ * ObservationLead.leading(Some("leader"), Some("postgres://127.0.0.1:1/scada"))
11
+ * }}}
12
+ */
13
+ object ObservationLead:
14
+ /** True for the first writer. A leased process without a role stays a standby. */
15
+ def leading(role: Option[String], lease: Option[String]): Boolean =
16
+ role match
17
+ case Some("leader") => true
18
+ case Some("standby") => false
19
+ case None => lease.forall(_.isEmpty)
20
+ case Some(value) => throw IllegalArgumentException(s"Writer role must be leader or standby, role $value")
21
+
22
+ /** True when this process may classify. A standby needs a positive segment end. */
23
+ def ready(observationMs: Long, segmentEndMs: Option[Long], leader: Boolean = true): Boolean =
24
+ if observationMs < 0 || segmentEndMs.exists(_ < 0) then
25
+ throw IllegalArgumentException(s"Replica watermarks must be non-negative integers, telemetry $observationMs segment ${segmentEndMs.getOrElse("none")}")
26
+ segmentEndMs.filter(_ > 0).fold(leader)(end => observationMs >= end)
@@ -0,0 +1,26 @@
1
+ package scada.supervisor.runtime
2
+
3
+ import scada.supervisor.core.MachineId
4
+ import scada.supervisor.infra.config.AppConfig
5
+ import scada.supervisor.infra.checkpoint.PendingSegmentData
6
+
7
+ /**
8
+ * Orphan pending segment rows left in the checkpoint by repeated
9
+ * crashes. The latest pending row per machine is excluded so
10
+ * [[PendingIsland]] can resume it.
11
+ *
12
+ * {{{
13
+ * Orphans.list(rows)
14
+ * }}}
15
+ */
16
+ object Orphans:
17
+
18
+ def protectedMachines(config: AppConfig): Set[MachineId] =
19
+ if config.localHistory then config.machines.map(_.id).toSet else Set.empty
20
+
21
+ def list(rows: List[PendingSegmentData], historical: Set[MachineId] = Set.empty): List[PendingSegmentData] =
22
+ rows.filterNot(row => historical(row.machine)).groupBy(_.machine).toList.sortBy(_._1.raw).flatMap: (_, xs) =>
23
+ val sorted = xs.sortBy(_.start.epoch)
24
+ sorted.filter(_.name == "on").lastOption match
25
+ case Some(on) => sorted.filterNot(row => row.name == "on" && row.start.epoch == on.start.epoch)
26
+ case None => if sorted.length <= 1 then Nil else sorted.init
@@ -0,0 +1,37 @@
1
+ package scada.supervisor.runtime
2
+
3
+ import cats.effect.IO
4
+ import org.typelevel.log4cats.Logger
5
+ import org.typelevel.log4cats.slf4j.Slf4jLogger
6
+ import scada.supervisor.core.{MachineConfig, SegmentCursor}
7
+ import scada.supervisor.infra.checkpoint.Checkpoint
8
+
9
+ /**
10
+ * Resolves the pending open segment cursor for one machine from
11
+ * checkpoint API rows where `duration = 0`.
12
+ *
13
+ * {{{
14
+ * PendingIsland.resolve(Some(checkpoint), machineConfig)
15
+ * }}}
16
+ */
17
+ object PendingIsland:
18
+
19
+ private given Logger[IO] = Slf4jLogger.getLogger[IO]
20
+
21
+ def resolve(checkpoint: Option[Checkpoint], machine: MachineConfig): IO[Option[SegmentCursor]] =
22
+ checkpoint match
23
+ case None =>
24
+ IO.pure(None)
25
+ case Some(cp) =>
26
+ cp.fetchPendingSegments.flatMap: rows =>
27
+ val xs = rows.filter(_.machine == machine.id).sortBy(_.start.epoch)
28
+ xs match
29
+ case Nil => IO.pure(None)
30
+ case nonEmpty =>
31
+ val last = nonEmpty.last
32
+ (if nonEmpty.length > 1 then
33
+ Logger[IO].warn(
34
+ s"${machine.id.raw}: ${nonEmpty.length} pending segment rows (duration=0); resuming latest at ${last.start.epoch}"
35
+ )
36
+ else IO.unit) *>
37
+ IO.pure(Some(SegmentCursor(last.name, last.start, last.end)))
@@ -0,0 +1,32 @@
1
+ package scada.supervisor.runtime
2
+
3
+ import cats.effect.IO
4
+ import fs2.Stream
5
+ import io.circe.Json
6
+ import scada.supervisor.core.{MachineConfig, Reading, ReadingOverride, Segments, Tagging}
7
+ import scada.supervisor.infra.checkpoint.Checkpoint
8
+ import scada.supervisor.infra.config.{AliasMapping, AppConfig, CheckpointApiConfig, ConfigProfile}
9
+ import scada.supervisor.infra.state.SegmentStatePolicy
10
+ import scada.supervisor.infra.stomp.SegmentWirePolicy
11
+
12
+ /** Site overrides for configured machine modes. The default runs the shared classifier. */
13
+ trait RuntimeProfile:
14
+ def configuration: ConfigProfile = ConfigProfile.default
15
+ def classifyReading(reading: Reading): Option[ReadingOverride] = None
16
+ def tagging: Tagging = Tagging()
17
+ def statePolicy: SegmentStatePolicy = SegmentStatePolicy.default
18
+ def wirePolicy: SegmentWirePolicy = SegmentWirePolicy.default
19
+ def historyProtocols: Vector[String] = Vector("preserve-known-suffix-v1")
20
+ def decorate(config: AppConfig, segments: Segments[IO]): IO[Segments[IO]] = IO.pure(segments)
21
+ def replayAliases(machine: MachineConfig, aliases: List[AliasMapping]): List[AliasMapping] = aliases
22
+ def readings(machine: MachineConfig, live: Stream[IO, Reading]): Stream[IO, Reading] = live
23
+ def input(config: AppConfig, machine: MachineConfig, aliases: List[AliasMapping]): Option[Stream[IO, Reading]] = None
24
+ def live(config: AppConfig, machine: MachineConfig, aliases: List[AliasMapping], segments: Segments[IO],
25
+ checkpoint: Option[Checkpoint], seeding: Option[Seeding]): Option[Stream[IO, Unit]] = None
26
+ def decisions(config: AppConfig, segments: Segments[IO]): Stream[IO, Unit] = Stream.empty
27
+ def history(machine: MachineConfig, aliases: List[AliasMapping], api: CheckpointApiConfig,
28
+ announce: Vector[Json] => IO[Unit]): Stream[IO, Unit] =
29
+ Stream.raiseError[IO](IllegalArgumentException(s"Unsupported history mode for ${machine.id.raw}"))
30
+
31
+ object RuntimeProfile:
32
+ val default: RuntimeProfile = new RuntimeProfile {}
@@ -0,0 +1,105 @@
1
+ package scada.supervisor.runtime
2
+
3
+ import cats.effect.{IO, Outcome}
4
+ import cats.effect.std.Queue
5
+ import fs2.Stream
6
+ import org.typelevel.log4cats.Logger
7
+ import org.typelevel.log4cats.slf4j.Slf4jLogger
8
+ import scala.concurrent.duration.*
9
+ import scada.supervisor.core.{MachineConfig, MachineId, Params, Reading, Timestamp}
10
+ import scada.supervisor.infra.checkpoint.{Checkpoint, RawReadingData}
11
+ import scada.supervisor.infra.config.AliasMapping
12
+
13
+ /**
14
+ * Seamless replay-then-live readings source for one machine.
15
+ *
16
+ * Startup ceremony:
17
+ * 1. Read a replay cursor derived from persisted segments — this is
18
+ * the replay resume point.
19
+ * 2. Open the live MQTT subscription and start offering every
20
+ * reading into a bounded queue (capacity from `seeding.capacity`,
21
+ * default 10_000) the moment this stream is compiled. If
22
+ * history drain falls far behind the live feed the producer
23
+ * back-pressures rather than exhausting the heap.
24
+ * 3. Fetch historical rows strictly after the watermark from
25
+ * the configured checkpoint readings source and emit them in timestamp order.
26
+ * * Dotted aliases also match slash ClickHouse topics.
27
+ * A hung readings fetch empties this step so live MQTT is not parked.
28
+ * 4. Once history drains, take from the queue and keep only
29
+ * readings whose timestamp is strictly after the resume cursor.
30
+ * Later history samples must not raise that bar: a live reading
31
+ * after the cursor still flows even when it is not after the last
32
+ * replayed row.
33
+ *
34
+ * No explicit "switch" is needed — fs2 stream concatenation and the
35
+ * concurrent ingest give a single uninterrupted `Stream[IO, Reading]`.
36
+ *
37
+ * {{{
38
+ * Seeding(checkpoint).seed(machine, aliases, mqtt.subscribe)
39
+ * }}}
40
+ */
41
+ final class Seeding(checkpoint: Checkpoint, capacity: Int, stall: FiniteDuration = 60.seconds):
42
+
43
+ private given Logger[IO] = Slf4jLogger.getLogger[IO]
44
+
45
+ def seed(machine: MachineConfig, aliases: List[AliasMapping], live: Stream[IO, Reading]): Stream[IO, Reading] =
46
+ Stream.eval(prepare(machine)).flatMap: (from, queue) =>
47
+ val history = Stream.exec(logReplay(machine, from)) ++
48
+ Stream.eval(limit(replay(checkpoint.fetchReadings, aliases, from).compile.toList, machine.id, required = false)).flatMap(Stream.emits)
49
+ val queued = Stream.fromQueueUnterminated(queue).filter(_.timestamp.isAfter(from))
50
+ (history ++ Stream.exec(logLive(machine)) ++ queued).concurrently(live.evalMap(queue.tryOffer(_).void))
51
+
52
+ /** The durable RabbitMQ queue retains readings until replay is ready to process them. */
53
+ def seedDurable(machine: MachineConfig, aliases: List[AliasMapping], live: Stream[IO,(Reading,IO[Unit])], onLive: IO[Unit]): Stream[IO,(Reading,IO[Unit])] =
54
+ Stream.eval(resumeFrom(machine)).flatMap: from =>
55
+ val load = limit(replay(checkpoint.fetchRequiredReadings, aliases, from).compile.toList, machine.id, required = true)
56
+ val history = Stream.eval(retryRequired(load, machine.id)).flatMap(Stream.emits).map(_ -> IO.unit)
57
+ val afterCursor = live.evalFilter: (reading, ack) =>
58
+ if reading.timestamp.isAfter(from) then IO.pure(true) else ack.as(false)
59
+ Stream.exec(logReplay(machine, from)) ++ history ++ Stream.exec(onLive *> logLive(machine)) ++ afterCursor
60
+
61
+ private def logReplay(machine: MachineConfig, from: Timestamp): IO[Unit] =
62
+ Logger[IO].info(s"${machine.id.raw}: replay from ts=${from.epoch}")
63
+
64
+ private def logLive(machine: MachineConfig): IO[Unit] =
65
+ Logger[IO].info(s"${machine.id.raw}: history drained, switching to live")
66
+
67
+ private def retryRequired(load: IO[List[Reading]], id: MachineId): IO[List[Reading]] =
68
+ load.handleErrorWith: error =>
69
+ Logger[IO].warn(error)(s"${id.raw}: required history unavailable, retrying replay") *> IO.sleep(1.second) *> retryRequired(load, id)
70
+
71
+ private def prepare(machine: MachineConfig): IO[(Timestamp, Queue[IO, Reading])] =
72
+ for
73
+ from <- resumeFrom(machine)
74
+ queue <- Queue.bounded[IO, Reading](capacity)
75
+ yield (from, queue)
76
+
77
+ private def resumeFrom(machine: MachineConfig): IO[Timestamp] =
78
+ checkpoint.fetchReplayCursor(machine.id)
79
+
80
+ private def limit(rows: IO[List[Reading]], id: MachineId, required: Boolean): IO[List[Reading]] =
81
+ IO.racePair(rows, IO.sleep(stall)).flatMap:
82
+ case Left((done, timer)) =>
83
+ timer.cancel.start *> finish(done)
84
+ case Right((worker, _)) =>
85
+ val expired = if required then IO.raiseError(java.util.concurrent.TimeoutException(s"${id.raw}: required history drain stalled"))
86
+ else Logger[IO].warn(s"${id.raw}: history drain stalled, switching to live").as(Nil)
87
+ worker.cancel.start *> expired
88
+
89
+ private def finish(done: Outcome[IO, Throwable, List[Reading]]): IO[List[Reading]] =
90
+ done match
91
+ case Outcome.Succeeded(got) => got
92
+ case Outcome.Errored(err) => IO.raiseError(err)
93
+ case Outcome.Canceled() => IO.pure(Nil)
94
+ private def replay(fetch: (List[String], Timestamp) => Stream[IO, RawReadingData], aliases: List[AliasMapping], from: Timestamp): Stream[IO, Reading] =
95
+ fetch(topics(aliases), from)
96
+ .flatMap(raw => Stream.fromOption(toReading(aliases, raw)))
97
+
98
+ private def topics(aliases: List[AliasMapping]): List[String] =
99
+ aliases.flatMap(alias => List(alias.topic, alias.topic.replace('.', '/'), alias.topic.replace('/', '.'))).distinct
100
+
101
+ private def toReading(aliases: List[AliasMapping], raw: RawReadingData): Option[Reading] =
102
+ aliases.find(alias => dotted(alias.topic) == dotted(raw.topic)).map: alias =>
103
+ Reading(raw.timestamp, Params(Map(alias.metric -> raw.value)))
104
+
105
+ private def dotted(route: String): String = route.replace('/', '.')