@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.
- package/README.md +13 -768
- package/package.json +3 -1
- package/src/domain/segment/segmentCoalesce.js +1 -1
- package/src/infrastructure/http/plant/routes/timelineRoute.js +1 -1
- package/src/infrastructure/ingest/sinks/contiguousPhases.js +13 -3
- package/src/infrastructure/streams/README.md +12 -5
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Condition.scala +33 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/CyclePhases.scala +65 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Decision.scala +67 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Emission.scala +19 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/MachineConfig.scala +21 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/MachineId.scala +18 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/MachineMode.scala +4 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Params.scala +15 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Reading.scala +11 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Segment.scala +28 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/SegmentDef.scala +14 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Segmentation.scala +137 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Segments.scala +41 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/SplitFollow.scala +50 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/SplitPieces.scala +102 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Supervisor.scala +66 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/TagDef.scala +12 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/TaggedSegment.scala +19 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Tagging.scala +42 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Timestamp.scala +26 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/checkpoint/Checkpoint.scala +61 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/checkpoint/ClickhouseReadingsCheckpoint.scala +76 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/checkpoint/SupervisorSinkCheckpoint.scala +141 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/config/AppConfig.scala +132 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/config/ConfigLoad.scala +202 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/config/ConfigProfile.scala +13 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/mqtt/Mqtt.scala +92 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/mqtt/Sessions.scala +18 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/state/AtomicStateFile.scala +24 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/state/CheckpointSegments.scala +59 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/state/SegmentStatePolicy.scala +18 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/state/Segments.scala +91 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/ClassifyQueue.scala +37 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/DecisionMessage.scala +49 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/DurableStomp.scala +27 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/SegmentMessage.scala +57 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/SegmentWirePolicy.scala +18 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/SplitFamily.scala +39 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompConnection.scala +106 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompDecisions.scala +43 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompFrame.scala +67 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompMachineDecisions.scala +16 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompQueue.scala +30 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompReadings.scala +29 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompSegments.scala +115 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ClassifierCursors.scala +58 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ClassifyHistory.scala +92 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ClassifyStreams.scala +67 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/Close.scala +23 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/EngineApp.scala +4 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/HealthServer.scala +38 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/HistoryBus.scala +67 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/HistoryClient.scala +23 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/HistoryRun.scala +86 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/LocalHistory.scala +256 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ObservationLead.scala +26 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/Orphans.scala +26 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/PendingIsland.scala +37 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/RuntimeProfile.scala +32 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/Seeding.scala +105 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/SupervisorRuntime.scala +266 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/WriterEpoch.scala +16 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/WriterGate.scala +35 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/WriterLease.scala +218 -0
- package/supervisor-engine/vendor/gaps-and-islands/LICENSE +21 -0
- package/supervisor-engine/vendor/gaps-and-islands/UPSTREAM +4 -0
- package/supervisor-engine/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/Island.scala +40 -0
- package/supervisor-engine/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandEvent.scala +55 -0
- package/supervisor-engine/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandsFlow.scala +127 -0
- package/supervisor-engine/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandsPolicy.scala +105 -0
- package/supervisor-engine/vendor/temporal-streams/LICENSE +21 -0
- package/supervisor-engine/vendor/temporal-streams/UPSTREAM +3 -0
- package/supervisor-engine/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/History.scala +30 -0
- package/supervisor-engine/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/LocalStreams.scala +27 -0
- package/supervisor-engine/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/Overlay.scala +15 -0
- package/supervisor-engine/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/Worker.scala +21 -0
|
@@ -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,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("'", "''")}'"
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
package scada.supervisor.infra.checkpoint
|
|
2
|
+
|
|
3
|
+
import cats.data.NonEmptyList
|
|
4
|
+
import cats.effect.IO
|
|
5
|
+
import fs2.Stream
|
|
6
|
+
import io.circe.parser.parse
|
|
7
|
+
import java.net.URI
|
|
8
|
+
import java.net.URLEncoder
|
|
9
|
+
import java.net.http.{HttpClient, HttpRequest, HttpResponse}
|
|
10
|
+
import java.nio.charset.StandardCharsets
|
|
11
|
+
import java.time.Duration
|
|
12
|
+
import java.util.concurrent.TimeUnit
|
|
13
|
+
import org.typelevel.log4cats.Logger
|
|
14
|
+
import org.typelevel.log4cats.slf4j.Slf4jLogger
|
|
15
|
+
import scala.concurrent.duration.*
|
|
16
|
+
import scada.supervisor.core.*
|
|
17
|
+
import scada.supervisor.infra.config.CheckpointApiConfig
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* HTTP checkpoint client against supervisor-sink /v1/checkpoint API.
|
|
21
|
+
*
|
|
22
|
+
* Transient connect failures and HTTP 5xx are retried. A closed site-server
|
|
23
|
+
* socket must not exit the supervisor stream.
|
|
24
|
+
*
|
|
25
|
+
* {{{
|
|
26
|
+
* SupervisorSinkCheckpoint(CheckpointApiConfig("http://site:8081", None, 10))
|
|
27
|
+
* }}}
|
|
28
|
+
*/
|
|
29
|
+
final class SupervisorSinkCheckpoint(config: CheckpointApiConfig, pause: FiniteDuration = 2.seconds) extends Checkpoint:
|
|
30
|
+
|
|
31
|
+
private given Logger[IO] = Slf4jLogger.getLogger[IO]
|
|
32
|
+
|
|
33
|
+
private val client = HttpClient.newBuilder()
|
|
34
|
+
.connectTimeout(Duration.ofSeconds(config.timeoutSeconds.toLong))
|
|
35
|
+
.build()
|
|
36
|
+
|
|
37
|
+
def fetchReplayCursor(machine: MachineId): IO[Timestamp] =
|
|
38
|
+
getJson(s"/v1/checkpoint/replay-cursor?machineId=${encode(machine.raw)}")
|
|
39
|
+
.map: body =>
|
|
40
|
+
val cursor = body.hcursor.get[Double]("cursor").getOrElse(0.0)
|
|
41
|
+
Timestamp(cursor)
|
|
42
|
+
|
|
43
|
+
def fetchPendingSegments: IO[List[PendingSegmentData]] =
|
|
44
|
+
getJson("/v1/checkpoint/pending-segments")
|
|
45
|
+
.map: body =>
|
|
46
|
+
val items = body.hcursor.downField("items")
|
|
47
|
+
.as[List[Map[String, io.circe.Json]]]
|
|
48
|
+
.getOrElse(Nil)
|
|
49
|
+
items.map: item =>
|
|
50
|
+
val start = Timestamp(item("start").as[Double].getOrElse(0.0))
|
|
51
|
+
val end = item.get("end").flatMap(_.as[Double].toOption).map(Timestamp.apply).getOrElse(start)
|
|
52
|
+
PendingSegmentData(
|
|
53
|
+
MachineId(item("machine").asString.getOrElse("")),
|
|
54
|
+
item("name").asString.getOrElse(""),
|
|
55
|
+
start,
|
|
56
|
+
end
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
def fetchSegment(machine: MachineId, start: Timestamp): IO[Option[TaggedSegment]] =
|
|
60
|
+
getJson(s"/v1/checkpoint/segment?machineId=${encode(machine.raw)}&start=${start.epoch}")
|
|
61
|
+
.map(body => body.hcursor.downField("item").focus.flatMap(decodeTagged))
|
|
62
|
+
|
|
63
|
+
override def fetchCyclePrior(machine: MachineId, before: Timestamp, reset: List[String]): IO[List[TaggedSegment]] =
|
|
64
|
+
val resetParams = reset.map(id => s"reset=${encode(id)}").mkString("&")
|
|
65
|
+
getJson(s"/v1/checkpoint/cycle-prior?machineId=${encode(machine.raw)}&before=${before.epoch}&$resetParams")
|
|
66
|
+
.map: body =>
|
|
67
|
+
body.hcursor.downField("items").as[List[io.circe.Json]].getOrElse(Nil).flatMap(decodeTagged)
|
|
68
|
+
|
|
69
|
+
def fetchReadings(topics: List[String], from: Timestamp): Stream[IO, RawReadingData] =
|
|
70
|
+
fetchRequiredReadings(topics, from).handleErrorWith: error =>
|
|
71
|
+
Stream.exec(Logger[IO].warn(error)("checkpoint readings failed"))
|
|
72
|
+
|
|
73
|
+
override def fetchRequiredReadings(topics: List[String], from: Timestamp): Stream[IO, RawReadingData] =
|
|
74
|
+
NonEmptyList.fromList(topics).fold(Stream.empty): topicsNel =>
|
|
75
|
+
val topicParams = topicsNel.toList.map(topic => s"topic=${encode(topic)}").mkString("&")
|
|
76
|
+
val path = s"/v1/checkpoint/readings?from=${from.epoch}&$topicParams"
|
|
77
|
+
Stream.eval(load(path)).flatMap(Stream.emits)
|
|
78
|
+
|
|
79
|
+
private def load(path: String): IO[List[RawReadingData]] =
|
|
80
|
+
read(path).flatMap: body =>
|
|
81
|
+
IO.fromEither(body.hcursor.downField("items").as[List[Map[String, io.circe.Json]]]).map: items =>
|
|
82
|
+
items.map: item =>
|
|
83
|
+
RawReadingData(
|
|
84
|
+
item("topic").asString.getOrElse(""),
|
|
85
|
+
Timestamp(item("timestamp").as[Double].getOrElse(0.0)),
|
|
86
|
+
item("value").as[Double].getOrElse(0.0)
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
private def decodeTagged(item: io.circe.Json): Option[TaggedSegment] =
|
|
90
|
+
if item.isNull then None
|
|
91
|
+
else
|
|
92
|
+
val cursor = item.hcursor
|
|
93
|
+
val name = cursor.get[String]("name").getOrElse("")
|
|
94
|
+
val startTs = Timestamp(cursor.get[Double]("start").getOrElse(0.0))
|
|
95
|
+
val endTs = Timestamp(cursor.get[Double]("end").getOrElse(0.0))
|
|
96
|
+
val duration = cursor.get[Double]("duration").getOrElse(0.0)
|
|
97
|
+
val tags = cursor.get[List[String]]("tags").getOrElse(Nil)
|
|
98
|
+
val options = cursor.get[List[String]]("options").getOrElse(Nil)
|
|
99
|
+
val properties = cursor.get[Map[String, String]]("properties").getOrElse(Map.empty)
|
|
100
|
+
Some(TaggedSegment(Segment(name, startTs, endTs, duration), tags, options, properties))
|
|
101
|
+
|
|
102
|
+
private def getJson(path: String): IO[io.circe.Json] =
|
|
103
|
+
read(path).handleErrorWith: err =>
|
|
104
|
+
err match
|
|
105
|
+
case failure: CheckpointStatus if failure.code >= 500 =>
|
|
106
|
+
Logger[IO].warn(failure)(s"checkpoint request failed path=$path") *> IO.sleep(pause) *> getJson(path)
|
|
107
|
+
case _: java.io.IOException =>
|
|
108
|
+
Logger[IO].warn(err)(s"checkpoint request failed path=$path") *> IO.sleep(pause) *> getJson(path)
|
|
109
|
+
case _ =>
|
|
110
|
+
IO.raiseError(err)
|
|
111
|
+
|
|
112
|
+
private def read(path: String): IO[io.circe.Json] =
|
|
113
|
+
val request = baseRequest(path).GET().build()
|
|
114
|
+
IO.fromCompletableFuture(IO.delay(
|
|
115
|
+
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
|
|
116
|
+
.orTimeout(config.timeoutSeconds.toLong, TimeUnit.SECONDS)
|
|
117
|
+
)).flatMap: response =>
|
|
118
|
+
val code = response.statusCode()
|
|
119
|
+
if code >= 500 then
|
|
120
|
+
IO.raiseError(CheckpointStatus(code, path))
|
|
121
|
+
else if code == 404 then
|
|
122
|
+
IO.pure(io.circe.Json.obj())
|
|
123
|
+
else if code / 100 != 2 then
|
|
124
|
+
IO.raiseError(RuntimeException(s"checkpoint api error $code: ${response.body()}"))
|
|
125
|
+
else
|
|
126
|
+
IO.fromEither(parse(response.body()).left.map(err => RuntimeException(err.message)))
|
|
127
|
+
|
|
128
|
+
private def baseRequest(path: String): HttpRequest.Builder =
|
|
129
|
+
val builder = HttpRequest.newBuilder()
|
|
130
|
+
.uri(URI.create(s"${config.baseUrl}$path"))
|
|
131
|
+
.timeout(Duration.ofSeconds(config.timeoutSeconds.toLong))
|
|
132
|
+
.header("Accept", "application/json")
|
|
133
|
+
config.token match
|
|
134
|
+
case Some(token) => builder.header("Authorization", s"Bearer $token")
|
|
135
|
+
case None => builder
|
|
136
|
+
|
|
137
|
+
private def encode(value: String): String =
|
|
138
|
+
URLEncoder.encode(value, StandardCharsets.UTF_8)
|
|
139
|
+
|
|
140
|
+
private final case class CheckpointStatus(code: Int, path: String)
|
|
141
|
+
extends RuntimeException(s"checkpoint http $code path=$path")
|