@yarkivaev/scada 2.6.39 → 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 (82) hide show
  1. package/README.md +13 -768
  2. package/package.json +3 -1
  3. package/src/domain/segment/segmentCoalesce.js +1 -1
  4. package/src/infrastructure/http/plant/routes/timelineRoute.js +1 -1
  5. package/src/infrastructure/ingest/sinks/contiguousPhases.js +13 -3
  6. package/src/infrastructure/streams/README.md +12 -5
  7. package/supervisor-engine/src/main/scala/scada/supervisor/core/Condition.scala +33 -0
  8. package/supervisor-engine/src/main/scala/scada/supervisor/core/CyclePhases.scala +65 -0
  9. package/supervisor-engine/src/main/scala/scada/supervisor/core/Decision.scala +67 -0
  10. package/supervisor-engine/src/main/scala/scada/supervisor/core/Emission.scala +19 -0
  11. package/supervisor-engine/src/main/scala/scada/supervisor/core/MachineConfig.scala +21 -0
  12. package/supervisor-engine/src/main/scala/scada/supervisor/core/MachineId.scala +18 -0
  13. package/supervisor-engine/src/main/scala/scada/supervisor/core/MachineMode.scala +4 -0
  14. package/supervisor-engine/src/main/scala/scada/supervisor/core/Params.scala +15 -0
  15. package/supervisor-engine/src/main/scala/scada/supervisor/core/Reading.scala +11 -0
  16. package/supervisor-engine/src/main/scala/scada/supervisor/core/Segment.scala +28 -0
  17. package/supervisor-engine/src/main/scala/scada/supervisor/core/SegmentDef.scala +14 -0
  18. package/supervisor-engine/src/main/scala/scada/supervisor/core/Segmentation.scala +137 -0
  19. package/supervisor-engine/src/main/scala/scada/supervisor/core/Segments.scala +41 -0
  20. package/supervisor-engine/src/main/scala/scada/supervisor/core/SplitFollow.scala +50 -0
  21. package/supervisor-engine/src/main/scala/scada/supervisor/core/SplitPieces.scala +102 -0
  22. package/supervisor-engine/src/main/scala/scada/supervisor/core/Supervisor.scala +66 -0
  23. package/supervisor-engine/src/main/scala/scada/supervisor/core/TagDef.scala +12 -0
  24. package/supervisor-engine/src/main/scala/scada/supervisor/core/TaggedSegment.scala +19 -0
  25. package/supervisor-engine/src/main/scala/scada/supervisor/core/Tagging.scala +42 -0
  26. package/supervisor-engine/src/main/scala/scada/supervisor/core/Timestamp.scala +26 -0
  27. package/supervisor-engine/src/main/scala/scada/supervisor/infra/checkpoint/Checkpoint.scala +61 -0
  28. package/supervisor-engine/src/main/scala/scada/supervisor/infra/checkpoint/ClickhouseReadingsCheckpoint.scala +76 -0
  29. package/supervisor-engine/src/main/scala/scada/supervisor/infra/checkpoint/SupervisorSinkCheckpoint.scala +141 -0
  30. package/supervisor-engine/src/main/scala/scada/supervisor/infra/config/AppConfig.scala +132 -0
  31. package/supervisor-engine/src/main/scala/scada/supervisor/infra/config/ConfigLoad.scala +202 -0
  32. package/supervisor-engine/src/main/scala/scada/supervisor/infra/config/ConfigProfile.scala +13 -0
  33. package/supervisor-engine/src/main/scala/scada/supervisor/infra/mqtt/Mqtt.scala +92 -0
  34. package/supervisor-engine/src/main/scala/scada/supervisor/infra/mqtt/Sessions.scala +18 -0
  35. package/supervisor-engine/src/main/scala/scada/supervisor/infra/state/AtomicStateFile.scala +24 -0
  36. package/supervisor-engine/src/main/scala/scada/supervisor/infra/state/CheckpointSegments.scala +59 -0
  37. package/supervisor-engine/src/main/scala/scada/supervisor/infra/state/SegmentStatePolicy.scala +18 -0
  38. package/supervisor-engine/src/main/scala/scada/supervisor/infra/state/Segments.scala +91 -0
  39. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/ClassifyQueue.scala +37 -0
  40. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/DecisionMessage.scala +49 -0
  41. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/DurableStomp.scala +27 -0
  42. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/SegmentMessage.scala +57 -0
  43. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/SegmentWirePolicy.scala +18 -0
  44. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/SplitFamily.scala +39 -0
  45. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompConnection.scala +106 -0
  46. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompDecisions.scala +43 -0
  47. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompFrame.scala +67 -0
  48. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompMachineDecisions.scala +16 -0
  49. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompQueue.scala +30 -0
  50. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompReadings.scala +29 -0
  51. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompSegments.scala +115 -0
  52. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ClassifierCursors.scala +58 -0
  53. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ClassifyHistory.scala +92 -0
  54. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ClassifyStreams.scala +67 -0
  55. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/Close.scala +23 -0
  56. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/EngineApp.scala +4 -0
  57. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/HealthServer.scala +38 -0
  58. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/HistoryBus.scala +67 -0
  59. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/HistoryClient.scala +23 -0
  60. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/HistoryRun.scala +86 -0
  61. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/LocalHistory.scala +256 -0
  62. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ObservationLead.scala +26 -0
  63. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/Orphans.scala +26 -0
  64. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/PendingIsland.scala +37 -0
  65. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/RuntimeProfile.scala +32 -0
  66. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/Seeding.scala +105 -0
  67. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/SupervisorRuntime.scala +266 -0
  68. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/WriterEpoch.scala +16 -0
  69. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/WriterGate.scala +35 -0
  70. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/WriterLease.scala +218 -0
  71. package/supervisor-engine/vendor/gaps-and-islands/LICENSE +21 -0
  72. package/supervisor-engine/vendor/gaps-and-islands/UPSTREAM +4 -0
  73. package/supervisor-engine/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/Island.scala +40 -0
  74. package/supervisor-engine/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandEvent.scala +55 -0
  75. package/supervisor-engine/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandsFlow.scala +127 -0
  76. package/supervisor-engine/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandsPolicy.scala +105 -0
  77. package/supervisor-engine/vendor/temporal-streams/LICENSE +21 -0
  78. package/supervisor-engine/vendor/temporal-streams/UPSTREAM +3 -0
  79. package/supervisor-engine/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/History.scala +30 -0
  80. package/supervisor-engine/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/LocalStreams.scala +27 -0
  81. package/supervisor-engine/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/Overlay.scala +15 -0
  82. package/supervisor-engine/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/Worker.scala +21 -0
@@ -0,0 +1,256 @@
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.infra.config.{AliasMapping, CheckpointApiConfig}
14
+ import scala.concurrent.duration.*
15
+
16
+ final case class HistoryRange(from: Long, until: Long)
17
+ final case class HistorySeed(time: Long, values: Map[String,Double], segment: Option[HistorySegment] = None)
18
+ final case class HistorySegment(name: String, start: Long, end: Long)
19
+ final case class HistoryState(position: Long, parameters: Map[String,(Long,Double)], segment: Option[HistorySegment])
20
+ final case class HistoryPool(cursors: LocalStreams, states: Map[Long,HistoryState]):
21
+ def expire(now: Long): HistoryPool =
22
+ val alive = cursors.evict(now)
23
+ copy(cursors = alive, states = states.filter((id,_) => alive.streams.exists(_.id == id)))
24
+ def completed(stream: Long, state: HistoryState): HistoryPool =
25
+ val advanced = cursors.copy(streams = cursors.streams.map(c => if c.id == stream then c.copy(position = state.position) else c))
26
+ val known = states.updated(stream,state).filter((id,_) => advanced.streams.exists(_.id == id))
27
+ val equal = known.toVector.filter((id,s) => id != stream && s == state).map(_._1)
28
+ val merged = equal.foldLeft(advanced)((pool,id) => pool.merge(stream,id,true))
29
+ HistoryPool(merged,known.filter((id,_) => merged.streams.exists(_.id == id)))
30
+ object LocalHistory:
31
+ def connected(before: Long, after: Long, gap: Long, continuity: Vector[HistoryRange]): Boolean =
32
+ before <= after && (BigInt(after)-BigInt(before) <= gap || continuity.exists(r => r.from <= before && r.until >= after))
33
+ def state(machine: MachineConfig, points: Vector[Observation], result: Vector[HistorySegment], seed: Option[HistorySeed] = None, continuity: Vector[HistoryRange] = Vector.empty): Option[HistoryState] =
34
+ points.map(_.time).maxOption.map: end =>
35
+ val gap = machine.window.toLong*2000
36
+ 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))))):
37
+ case ((previous,values),(time,group)) =>
38
+ val prior = if previous.exists(t => connected(t,time,gap,continuity)) then values else Map.empty[String,(Long,Double)]
39
+ (Some(time),prior ++ group.map(p => p.channel -> (p.time,p.value)))
40
+ HistoryState(end,state._2,result.lastOption)
41
+
42
+ /** Finite event-time classification: never inject wall-clock silence into past data. */
43
+ def classify(machine: MachineConfig, points: Vector[Observation], seed: Option[HistorySeed] = None, continuity: Vector[HistoryRange] = Vector.empty): Vector[HistorySegment] =
44
+ val gap = machine.window.toLong * 2000
45
+ val lookup = (name: String) => machine.segments.find(_.name == name).map(_.condition)
46
+ val groups = points.groupBy(_.time).toVector.sortBy(_._1)
47
+ val initialSegment = seed.flatMap: initial =>
48
+ val stored = initial.segment.filter(_.start <= initial.time)
49
+ val evaluated = machine.segments.find(_.condition.matches(Params(initial.values),lookup)).map(_.name)
50
+ evaluated match
51
+ case Some(name) => Some(stored.filter(_.name == name).getOrElse(HistorySegment(name,initial.time,initial.time)))
52
+ case None => stored
53
+ groups.foldLeft((seed.fold(Map.empty[String,Double])(_.values),seed.map(_.time),initialSegment.toVector)):
54
+ case ((prior,previous,segments),(time,group)) =>
55
+ val continuous = previous.exists(t => connected(t,time,gap,continuity))
56
+ val values = (if continuous then prior else Map.empty) ++ group.map(p => p.channel -> p.value)
57
+ val name = machine.segments.find(_.condition.matches(Params(values),lookup)).map(_.name)
58
+ .orElse(if continuous then segments.lastOption.map(_.name) else None)
59
+ val next = name.fold(segments): n =>
60
+ segments.lastOption match
61
+ case Some(last) if continuous && last.name == n => segments.init :+ last.copy(end = time)
62
+ case Some(_) if continuous => segments :+ HistorySegment(n,time,time)
63
+ case _ => segments :+ HistorySegment(n,time,time)
64
+ (values,Some(time),next)
65
+ ._3
66
+
67
+ def sources(context: Json): Vector[Json] =
68
+ val current = context.hcursor.get[Vector[Json]]("segments").getOrElse(Vector.empty)
69
+ def identity(row: Json) = (row.hcursor.get[String]("kind").toOption,row.hcursor.get[String]("name").toOption,row.hcursor.get[String]("start_time").toOption)
70
+ val archived = context.hcursor.get[Vector[Json]]("annotations").getOrElse(Vector.empty).map: row =>
71
+ val metadata = current.find(value => identity(value) == identity(row)).fold(Json.obj()): value =>
72
+ Json.obj(Vector("tags","properties","resolved","consumed").map(key => key -> value.hcursor.downField(key).focus.getOrElse(Json.Null))*)
73
+ row.deepMerge(metadata).deepMerge(Json.obj("_historyArchive" -> Json.True))
74
+ (current ++ archived).distinctBy(row => (identity(row),row.hcursor.get[String]("end_time").toOption))
75
+
76
+ def duration(segment: HistorySegment, tailEnd: Long, rightClosed: Boolean): Double =
77
+ if !rightClosed && segment.end == tailEnd then 0.0 else (segment.end-segment.start)/1000.0
78
+
79
+ def metadata(row: Json, key: String, fallback: Json): Json =
80
+ row.hcursor.downField(key).focus.filterNot(_.isNull).map(v => v.asString.flatMap(t => parse(t).toOption).getOrElse(v)).getOrElse(fallback)
81
+
82
+ /**
83
+ * Attaches operator metadata without slicing one continuous classification.
84
+ * A stored seam is kept when the pieces that meet there differ by name or tags,
85
+ * or when the new class differs from those stored pieces.
86
+ * The same state running past its last stored end stays one segment.
87
+ */
88
+ def overlay(result: Vector[HistorySegment], existing: Vector[Json], continuation: Boolean = false): Vector[(HistorySegment,Json)] =
89
+ def instant(row: Json, key: String): Long = row.hcursor.get[String](key).toOption.map(Instant.parse(_).toEpochMilli).getOrElse(0L)
90
+ def mark(row: Json): (String, String) =
91
+ val name = row.hcursor.get[String]("name").getOrElse("")
92
+ val raw = row.hcursor.downField("tags").focus.getOrElse(Json.Null)
93
+ (name, raw.asString.flatMap(text => parse(text).toOption).getOrElse(raw).noSpaces)
94
+ def kept(segmentName: String, at: Long, from: Long, until: Long): Boolean =
95
+ val ending = existing.filter(row => instant(row, "end_time") == at)
96
+ val starting = existing.filter(row => instant(row, "start_time") == at)
97
+ val later = existing.filter(row => instant(row, "start_time") > at && instant(row, "start_time") < until)
98
+ val earlier = existing.filter(row => instant(row, "end_time") <= at && instant(row, "end_time") > from)
99
+ val foreign = (ending ++ starting).exists(row => !row.hcursor.get[String]("name").toOption.contains(segmentName))
100
+ if ending.nonEmpty && starting.nonEmpty then foreign || ending.exists(left => starting.exists(right => mark(left) != mark(right)))
101
+ 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)))
102
+ else starting.exists(row => !row.hcursor.get[String]("name").toOption.contains(segmentName)) || earlier.exists(row => starting.exists(right => mark(row) != mark(right)))
103
+ val cuts = existing.flatMap: row =>
104
+ val start = instant(row,"start_time")
105
+ val end = instant(row,"end_time")
106
+ if continuation && row.hcursor.get[Double]("duration").toOption.contains(0.0) then Vector(start) else Vector(start,end)
107
+ .distinct.sorted
108
+ result.zipWithIndex.flatMap: (segment,index) =>
109
+ 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) ||
110
+ (segment.start == segment.end && instant(row,"start_time") <= segment.start && instant(row,"end_time") >= segment.start) ||
111
+ (instant(row,"start_time") == segment.start && instant(row,"end_time") == segment.end)))
112
+ val current = matches.filterNot(_.hcursor.get[Boolean]("_historyArchive").getOrElse(false))
113
+ val owners = if current.nonEmpty then current else matches
114
+ val proposedStart = if index == 0 then owners.map(instant(_,"start_time")).minOption.fold(segment.start)(_.min(segment.start)) else segment.start
115
+ val proposedEnd = if index == result.size-1 then owners.map(instant(_,"end_time")).maxOption.fold(segment.end)(_.max(segment.end)) else segment.end
116
+ val blockers = existing.filter(row => !row.hcursor.get[Boolean]("_historyArchive").getOrElse(false) && !row.hcursor.get[String]("name").toOption.contains(segment.name))
117
+ val start = blockers.filter(row => instant(row,"start_time") < segment.start && instant(row,"end_time") > proposedStart)
118
+ .map(row => instant(row,"end_time").min(segment.start)).foldLeft(proposedStart)(_.max(_))
119
+ val end = blockers.filter(row => instant(row,"end_time") > segment.end && instant(row,"start_time") < proposedEnd)
120
+ .map(row => instant(row,"start_time").max(segment.end)).foldLeft(proposedEnd)(_.min(_))
121
+ val boundaries = Vector(start) ++ cuts.filter(t => t > start && t < end && kept(segment.name, t, start, end)) ++ Vector(end)
122
+ boundaries.sliding(2).collect:
123
+ case Vector(a,b) =>
124
+ val left = owners.map(instant(_,"start_time")).minOption
125
+ val right = owners.map(instant(_,"end_time")).maxOption
126
+ val covered = owners.filter(row => instant(row,"start_time") >= a && instant(row,"end_time") <= b)
127
+ 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 {
128
+ if left.exists(b <= _) then owners.find(row => left.contains(instant(row,"start_time")))
129
+ else if right.exists(a >= _) then owners.find(row => right.contains(instant(row,"end_time")))
130
+ else None
131
+ }.orElse(if covered.map(mark).distinct.size == 1 then covered.headOption else None).getOrElse(Json.Null)
132
+ (segment.copy(start = a,end = b),inherited)
133
+ .toVector
134
+
135
+ val nativeTailProtocol = "preserve-known-suffix-v1"
136
+ private def instant(row: Json, key: String): Long =
137
+ row.hcursor.get[String](key).toOption.map(Instant.parse(_).toEpochMilli).getOrElse(0L)
138
+
139
+ /** Send observed changes plus only CAS-proved exterior already present in this context. */
140
+ def commitRows(machine: MachineConfig, result: Vector[HistorySegment], context: Json, continuation: Boolean = false): Vector[Json] =
141
+ val current = context.hcursor.get[Vector[Json]]("segments").getOrElse(Vector.empty)
142
+ val pageEnd = context.hcursor.downField("page").get[Long]("until").toOption
143
+ val overlaid = overlay(result,sources(context),continuation)
144
+ val bounded = overlaid.flatMap: (segment,inherited) =>
145
+ val owner = current.find(row => row.hcursor.get[String]("name").toOption.contains(segment.name) &&
146
+ instant(row,"start_time") <= segment.start && instant(row,"end_time") >= segment.end)
147
+ val terminalAnchor = pageEnd.exists(end => segment.start == end) && owner.exists(row =>
148
+ instant(row,"start_time") == segment.start && instant(row,"end_time") > segment.start)
149
+ if terminalAnchor then None
150
+ else
151
+ val exterior = owner.filter(row => pageEnd.exists(end => instant(row,"end_time") > end) && segment.end == instant(row,"end_time"))
152
+ val end = if exterior.nonEmpty then segment.end else pageEnd.fold(segment.end)(_.min(segment.end))
153
+ Some((segment.copy(end = end),inherited,exterior))
154
+ val suffixes = pageEnd.toVector.flatMap: until =>
155
+ current.filter(row => instant(row,"end_time") > until).flatMap: owner =>
156
+ val changed = bounded.exists((segment,_,_) => segment.start == instant(owner,"start_time") &&
157
+ (segment.name != owner.hcursor.get[String]("name").getOrElse("") || segment.end < instant(owner,"end_time")))
158
+ val retained = bounded.exists((_,_,proof) => proof.contains(owner))
159
+ if !changed || retained then None
160
+ else Some((HistorySegment(owner.hcursor.get[String]("name").getOrElse(""),until+1,instant(owner,"end_time")),owner,Some(owner)))
161
+ val rows = bounded ++ suffixes
162
+ rows.filter((segment,_,_) => segment.start <= segment.end).map: (segment,inherited,proof) =>
163
+ val unchanged = proof.exists(owner => instant(owner,"start_time") == segment.start && instant(owner,"end_time") == segment.end)
164
+ 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))
165
+ val base = Segment(segment.name,Timestamp(segment.start/1000.0),Timestamp(segment.end/1000.0),duration)
166
+ val tagged = Tagging().resolve(machine.tags,base)
167
+ Json.obj("kind" -> inherited.hcursor.get[String]("kind").toOption.map(Json.fromString).getOrElse(Json.fromString("phase")),"name" -> Json.fromString(segment.name),
168
+ "start_time" -> Json.fromString(Instant.ofEpochMilli(segment.start).toString),
169
+ "end_time" -> Json.fromString(Instant.ofEpochMilli(segment.end).toString),
170
+ "duration" -> Json.fromDoubleOrNull(base.duration),
171
+ "consumed" -> Json.fromBoolean(inherited.hcursor.get[Boolean]("consumed").getOrElse(true)),
172
+ "resolved" -> Json.fromBoolean(inherited.hcursor.get[Boolean]("resolved").getOrElse(tagged.tags.nonEmpty)),
173
+ "tags" -> LocalHistory.metadata(inherited,"tags",Json.arr(tagged.tags.map(Json.fromString)*)),
174
+ "options" -> LocalHistory.metadata(inherited,"options",Json.arr(tagged.options.map(Json.fromString)*)),
175
+ "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)))
176
+
177
+ /** Durable HTTP work queue is local to the receiving edge. Failed requests retry without acknowledging input. */
178
+ final class LocalHistory(config: CheckpointApiConfig, machine: MachineConfig, announce: Vector[Json] => IO[Unit] = _ => IO.unit):
179
+ private val transport=HistoryClient(config)
180
+ import transport.{request,retry}
181
+ private val encoded = URLEncoder.encode(machine.id.raw,StandardCharsets.UTF_8)
182
+ def configure(aliases: List[AliasMapping]): IO[Unit] =
183
+ val topics = aliases.map(a => Json.obj("topic" -> Json.fromString(a.topic),"channel" -> Json.fromString(a.metric)))
184
+ retry(request("POST","/v1/history/config",Json.obj("machine" -> Json.fromString(machine.id.raw),"topics" -> Json.arr(topics*)))).flatMap: response =>
185
+ IO.raiseUnless(response.hcursor.get[String]("nativeTailProtocol").toOption.contains(LocalHistory.nativeTailProtocol))(new IllegalStateException("History receiver does not preserve known segment suffixes"))
186
+ def accept(reading: Reading): IO[Unit] =
187
+ val observations = reading.params.values.toVector.map: (channel,value) =>
188
+ Json.obj("eventId" -> Json.fromString(s"${machine.id.raw}:$channel:${reading.timestamp.millis}:$value"),
189
+ "channel" -> Json.fromString(channel),"time" -> Json.fromLong(reading.timestamp.millis),"value" -> Json.fromDoubleOrNull(value))
190
+ retry(request("POST","/v1/history/observations",Json.obj("machine" -> Json.fromString(machine.id.raw),"observations" -> Json.arr(observations*)))).void
191
+ def process: Stream[IO,Unit] =
192
+ Stream.eval(Ref.of[IO,HistoryPool](HistoryPool(LocalStreams.empty(machine.window.toLong*2000,10000),Map.empty))).flatMap: pool =>
193
+ Stream.repeatEval(IO.monotonic.flatMap(now => pool.update(_.expire(now.toMillis))) *> retry(request("GET",s"/v1/history/work?machine=$encoded"))).flatMap: body =>
194
+ val work = body.hcursor.get[Vector[Json]]("items").getOrElse(Vector.empty)
195
+ 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))
196
+ private def run(raw: Json, pool: Ref[IO,HistoryPool]): IO[Unit] =
197
+ val cursor = raw.hcursor
198
+ for
199
+ id <- IO.fromEither(cursor.get[String]("id"))
200
+ token <- IO.fromEither(cursor.get[String]("token"))
201
+ from <- IO.fromEither(cursor.get[Long]("from"))
202
+ until <- IO.fromEither(cursor.get[Long]("until"))
203
+ now <- IO.monotonic.map(_.toMillis)
204
+ routed <- pool.modify: previous =>
205
+ val routed = previous.cursors.evict(now).route(Observation(id,"work",from,0),now)
206
+ // Cursors are a bounded cache; receiver work remains durable when a cursor is evicted.
207
+ val kept = routed.state.copy(streams = routed.state.streams.takeRight(64))
208
+ (HistoryPool(kept,previous.states.filter((id,_) => kept.streams.exists(_.id == id))),routed.work.copy(from = from,until = until))
209
+ committed <- Ref.of[IO,Boolean](false)
210
+ calculated <- Ref.of[IO,Option[HistoryState]](None)
211
+ snapshot <- Ref.of[IO,Json](Json.Null)
212
+ ports = new Processing[IO,HistorySegment]:
213
+ def context(work: Work): IO[Option[Vector[Observation]]] =
214
+ 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 =>
215
+ if !response.hcursor.get[Boolean]("available").getOrElse(false) then IO.pure(None)
216
+ else IO.fromEither(response.hcursor.get[Vector[Json]]("items").flatMap(_.traverse: item =>
217
+ val p = item.hcursor
218
+ for
219
+ event <- p.get[String]("eventId")
220
+ channel <- p.get[String]("channel")
221
+ time <- p.get[Long]("time")
222
+ value <- p.get[Double]("value")
223
+ yield Observation(event,channel,time,value)
224
+ )).map(Some(_))
225
+ def classify(work: Work, points: Vector[Observation]): IO[Vector[HistorySegment]] =
226
+ snapshot.get.flatMap: context =>
227
+ val initial = context.hcursor.downField("initial")
228
+ val seed = for
229
+ time <- initial.get[Long]("time").toOption
230
+ values <- initial.get[Map[String,Double]]("values").toOption
231
+ yield
232
+ val prior = initial.downField("segment")
233
+ val segment = for
234
+ name <- prior.get[String]("name").toOption
235
+ start <- prior.get[String]("start_time").toOption.flatMap(t => scala.util.Try(Instant.parse(t).toEpochMilli).toOption)
236
+ yield HistorySegment(name,start,time)
237
+ HistorySeed(time,values,segment)
238
+ val continuity = context.hcursor.get[Vector[Json]]("continuity").getOrElse(Vector.empty).flatMap: row =>
239
+ for
240
+ from <- row.hcursor.get[Long]("from").toOption
241
+ until <- row.hcursor.get[Long]("until").toOption
242
+ yield HistoryRange(from,until)
243
+ val result = LocalHistory.classify(machine,points,seed,continuity)
244
+ calculated.set(LocalHistory.state(machine,points,result,seed,continuity)).as(result)
245
+ def commit(work: Work, result: Vector[HistorySegment]): IO[Unit] =
246
+ snapshot.get.flatMap: context =>
247
+ val rows = LocalHistory.commitRows(machine,result,context,raw.hcursor.get[Long]("cursor").toOption.isDefined)
248
+ 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
249
+ def acknowledge(work: Work): IO[Unit] =
250
+ 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)
251
+ _ <- Worker(ports).run(routed).guarantee(pool.update(p => p.copy(cursors = p.cursors.acknowledge(routed.id))))
252
+ result <- calculated.get
253
+ _ <- pool.update: previous =>
254
+ val completed = result.fold(previous)(previous.completed(routed.streamId,_))
255
+ completed.copy(cursors = completed.cursors.acknowledge(routed.id))
256
+ 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('/', '.')