@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.
- package/README.md +13 -768
- package/db/migrations/E0018__stream_worker_checkpoint.sql +9 -0
- package/package.json +3 -1
- package/src/infrastructure/streams/README.md +12 -5
- package/supervisor-engine/src/main/scala/scada/stream/replay/Replay.scala +149 -0
- package/supervisor-engine/src/main/scala/scada/stream/worker/Processor.scala +8 -0
- package/supervisor-engine/src/main/scala/scada/stream/worker/StreamWorker.scala +119 -0
- package/supervisor-engine/src/main/scala/scada/stream/worker/postgres/PgCheckpointStore.scala +83 -0
- 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 +52 -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/core/segmentation/Timeline.scala +43 -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 +258 -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,266 @@
|
|
|
1
|
+
package scada.supervisor.runtime
|
|
2
|
+
|
|
3
|
+
import cats.effect.{ExitCode, IO, IOApp, Ref, Resource}
|
|
4
|
+
import cats.effect.std.Semaphore
|
|
5
|
+
import cats.syntax.all.*
|
|
6
|
+
import fs2.Stream
|
|
7
|
+
import org.typelevel.log4cats.Logger
|
|
8
|
+
import org.typelevel.log4cats.slf4j.Slf4jLogger
|
|
9
|
+
import scada.supervisor.core.{
|
|
10
|
+
Decision,
|
|
11
|
+
MachineConfig,
|
|
12
|
+
MachineId,
|
|
13
|
+
Reading,
|
|
14
|
+
Segmentation,
|
|
15
|
+
Segments as CoreSegments,
|
|
16
|
+
Supervisor,
|
|
17
|
+
TagDef,
|
|
18
|
+
TaggedSegment,
|
|
19
|
+
Timestamp
|
|
20
|
+
}
|
|
21
|
+
import scada.supervisor.infra.checkpoint.{Checkpoint, ClickhouseReadingsCheckpoint, SupervisorSinkCheckpoint}
|
|
22
|
+
import scada.supervisor.infra.config.{AliasMapping, AppConfig, ConfigLoad, RabbitMqConfig}
|
|
23
|
+
import scada.supervisor.infra.mqtt.Mqtt
|
|
24
|
+
import scada.supervisor.infra.state.{CheckpointSegments, Segments as StateSegments}
|
|
25
|
+
import scada.supervisor.infra.stomp.{DurableStomp, StompConnection, StompDecisions, StompSegments, StompSender}
|
|
26
|
+
import scala.collection.immutable.SortedMap
|
|
27
|
+
import scala.concurrent.duration.*
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Live entry point and composition root. Loads HOCON, wires the
|
|
31
|
+
* module graph, opens the startup ceremony (checkpoint API replay, live
|
|
32
|
+
* MQTT, STOMP decisions) and runs every per-machine supervisor loop
|
|
33
|
+
* concurrently with the decision consumer until killed.
|
|
34
|
+
*
|
|
35
|
+
* `F` is pinned to `IO` here; `core` stays tagless.
|
|
36
|
+
*
|
|
37
|
+
* Decorator order:
|
|
38
|
+
* {{{
|
|
39
|
+
* StompSegments(CheckpointSegments(StateSegments(...), checkpoint), connection, dest)
|
|
40
|
+
* }}}
|
|
41
|
+
* Segment persistence/publish remains the durable boundary. Replay
|
|
42
|
+
* cursor is derived from supervisor-sink checkpoint API during startup.
|
|
43
|
+
*
|
|
44
|
+
* {{{
|
|
45
|
+
* sbt "runMain scada.supervisor.runtime.EngineApp config/application.conf"
|
|
46
|
+
* }}}
|
|
47
|
+
*/
|
|
48
|
+
open class SupervisorRuntime(profile: RuntimeProfile) extends IOApp:
|
|
49
|
+
|
|
50
|
+
private val defaultPath: String = "config/application.conf"
|
|
51
|
+
|
|
52
|
+
private given Logger[IO] = Slf4jLogger.getLogger[IO]
|
|
53
|
+
|
|
54
|
+
def run(args: List[String]): IO[ExitCode] =
|
|
55
|
+
args match
|
|
56
|
+
case "--capabilities" :: Nil => IO.println(io.circe.Json.obj("role" -> io.circe.Json.fromString("supervisor"),
|
|
57
|
+
"historyProtocols" -> io.circe.Json.arr(profile.historyProtocols.map(io.circe.Json.fromString)*)).noSpaces).as(ExitCode.Success)
|
|
58
|
+
case "--check" :: path :: Nil => ConfigLoad(profile = profile.configuration).load(path).as(ExitCode.Success)
|
|
59
|
+
case "--check" :: _ => IO.raiseError(IllegalArgumentException("Usage: supervisor --check CONFIG"))
|
|
60
|
+
case _ => ConfigLoad(profile = profile.configuration).load(args.headOption.getOrElse(defaultPath)).flatMap(live).as(ExitCode.Success)
|
|
61
|
+
|
|
62
|
+
private def live(config: AppConfig): IO[Unit] =
|
|
63
|
+
Logger[IO].info(s"supervisor starting: machines=${config.machines.size} stomp=${config.connectivity.rabbitmq.destinations.segments.isDefined} checkpointApi=${config.connectivity.checkpointApi.isDefined}") *>
|
|
64
|
+
Ref.of[IO, Map[MachineId, SortedMap[Timestamp, TaggedSegment]]](Map.empty).flatMap: segmentsRef =>
|
|
65
|
+
resources(config).use: publishConn =>
|
|
66
|
+
val checkpoint = checkpointWithDecorators(config)
|
|
67
|
+
val base = StateSegments[IO](segmentsRef, profile.statePolicy)
|
|
68
|
+
val withFallback = checkpoint.fold(base)(cp => CheckpointSegments(base, cp))
|
|
69
|
+
val decorated = decorate(config, publishConn, withFallback)
|
|
70
|
+
profile.decorate(config, decorated).flatMap(runStreams(config, _, checkpoint, base, publishConn))
|
|
71
|
+
|
|
72
|
+
private def runStreams(config: AppConfig, segments: CoreSegments[IO], checkpoint: Option[Checkpoint], base: StateSegments[IO], publish: Option[StompSender]): IO[Unit] =
|
|
73
|
+
|
|
74
|
+
val supervisor = Supervisor[IO](Segmentation[IO](profile.classifyReading), profile.tagging, segments, config.cyclePhases)
|
|
75
|
+
val decisionSegments = checkpoint.filter(_ => config.localHistory).fold(segments)(cp =>
|
|
76
|
+
CheckpointSegments(segments,cp,preferCheckpoint=true,refreshCache=Some(base.refresh)))
|
|
77
|
+
val stall = config.connectivity.checkpointApi.map(api => api.timeoutSeconds.seconds).getOrElse(60.seconds)
|
|
78
|
+
val seeding = checkpoint.map(Seeding(_, config.seeding.capacity, stall))
|
|
79
|
+
val protectedMachines = Orphans.protectedMachines(config) ++ config.machines.filter(_.mode.isDefined).map(_.id)
|
|
80
|
+
val canCloseOrphans = config.leaseHeld && config.machines.exists(machine => !protectedMachines(machine.id))
|
|
81
|
+
Logger[IO].info("supervisor ready, closing orphaned pending segments") *>
|
|
82
|
+
closeWhenHeld(canCloseOrphans, checkpoint, segments, protectedMachines) *>
|
|
83
|
+
Logger[IO].info("supervisor ready, entering stream loop") *>
|
|
84
|
+
(if config.machines.isEmpty then IO.never
|
|
85
|
+
else streams(config, supervisor, decisionSegments, seeding, checkpoint, publish, segments).compile.drain) *>
|
|
86
|
+
Logger[IO].info("supervisor stream loop exited")
|
|
87
|
+
/**
|
|
88
|
+
* Closes orphan pending rows only while this process holds the writer lease.
|
|
89
|
+
*
|
|
90
|
+
* {{{
|
|
91
|
+
* SupervisorRuntime.closeWhenHeld(false, checkpoint, segments, Set.empty)
|
|
92
|
+
* }}}
|
|
93
|
+
*/
|
|
94
|
+
private[runtime] def closeWhenHeld(held: Boolean, checkpoint: Option[Checkpoint], segments: CoreSegments[IO], historical: Set[MachineId]): IO[Unit] =
|
|
95
|
+
if held then closeOrphanPending(checkpoint, segments, historical) else IO.unit
|
|
96
|
+
|
|
97
|
+
private def closeOrphanPending(checkpoint: Option[Checkpoint], segments: CoreSegments[IO], historical: Set[MachineId]): IO[Unit] =
|
|
98
|
+
checkpoint match
|
|
99
|
+
case None => IO.unit
|
|
100
|
+
case Some(cp) =>
|
|
101
|
+
cp.fetchPendingSegments.flatMap: rows =>
|
|
102
|
+
val xs = Orphans.list(rows,historical)
|
|
103
|
+
(if xs.nonEmpty then
|
|
104
|
+
Logger[IO].info(s"closing ${xs.length} orphaned pending segment rows at startup")
|
|
105
|
+
else IO.unit) *>
|
|
106
|
+
xs.traverse_(row => Close.run(segments, row))
|
|
107
|
+
|
|
108
|
+
private def checkpointWithDecorators(config: AppConfig): Option[Checkpoint] =
|
|
109
|
+
val base = config.connectivity.checkpointApi.map(SupervisorSinkCheckpoint(_))
|
|
110
|
+
(config.seeding.useClickhouseReadings, base, config.connectivity.clickhouseReadings) match
|
|
111
|
+
case (true, Some(cp), Some(ch)) => Some(ClickhouseReadingsCheckpoint(cp, ch))
|
|
112
|
+
case _ => base
|
|
113
|
+
|
|
114
|
+
private def resources(
|
|
115
|
+
config: AppConfig
|
|
116
|
+
): Resource[IO, Option[StompSender]] =
|
|
117
|
+
for
|
|
118
|
+
publish <- stompConnection(config.connectivity.rabbitmq)
|
|
119
|
+
_ <- HealthServer().serve(config.health.port)
|
|
120
|
+
yield publish
|
|
121
|
+
|
|
122
|
+
private def stompConnection(rabbit: RabbitMqConfig): Resource[IO, Option[StompSender]] =
|
|
123
|
+
rabbit.destinations.segments.fold(Resource.pure[IO, Option[StompSender]](None)): _ =>
|
|
124
|
+
Resource.eval((Ref.of[IO, Option[StompSender]](None),Semaphore[IO](1)).tupled).map: (slot,lock) =>
|
|
125
|
+
val durable = DurableStomp(
|
|
126
|
+
StompConnection.connect(
|
|
127
|
+
rabbit.address.host,
|
|
128
|
+
rabbit.address.port,
|
|
129
|
+
rabbit.vhost,
|
|
130
|
+
rabbit.credentials.login,
|
|
131
|
+
rabbit.credentials.passcode
|
|
132
|
+
),
|
|
133
|
+
3,
|
|
134
|
+
slot
|
|
135
|
+
)
|
|
136
|
+
Some(new StompSender:
|
|
137
|
+
def send(frame: scada.supervisor.infra.stomp.StompFrame): IO[Unit] = lock.permit.use(_ => durable.send(frame))
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
private def decorate(
|
|
141
|
+
config: AppConfig,
|
|
142
|
+
publish: Option[StompSender],
|
|
143
|
+
base: CoreSegments[IO]
|
|
144
|
+
): CoreSegments[IO] =
|
|
145
|
+
(publish, config.connectivity.rabbitmq.destinations.segments) match
|
|
146
|
+
case (Some(conn), Some(dest)) => StompSegments(base, conn, dest, policy = profile.wirePolicy)
|
|
147
|
+
case _ => base
|
|
148
|
+
|
|
149
|
+
private def streams(
|
|
150
|
+
config: AppConfig,
|
|
151
|
+
supervisor: Supervisor[IO],
|
|
152
|
+
segments: CoreSegments[IO],
|
|
153
|
+
seeding: Option[Seeding],
|
|
154
|
+
checkpoint: Option[Checkpoint],
|
|
155
|
+
publish: Option[StompSender],
|
|
156
|
+
profileSegments: CoreSegments[IO]
|
|
157
|
+
): Stream[IO, Unit] =
|
|
158
|
+
Stream(machineStreams(config, supervisor, seeding, checkpoint, publish, profileSegments = Some(profileSegments))*).parJoinUnbounded
|
|
159
|
+
.concurrently(decisionStream(config, segments))
|
|
160
|
+
.concurrently(profile.decisions(config, segments))
|
|
161
|
+
|
|
162
|
+
/** Sends a committed page. A configured lease uses the holder generation and a non-holder sends nothing. */
|
|
163
|
+
private[runtime] def historyAnnounce(sender: Option[StompSender], config: AppConfig, machine: MachineId, grant: Option[LeaseGrant] = None): Vector[io.circe.Json] => IO[Unit] =
|
|
164
|
+
WriterLease.publication(config.leaseUrl, grant, config.writerEpoch) match
|
|
165
|
+
case None => (_: Vector[io.circe.Json]) => IO.unit
|
|
166
|
+
case Some(epoch) =>
|
|
167
|
+
(sender, config.connectivity.rabbitmq.destinations.segments) match
|
|
168
|
+
case (Some(conn), Some(dest)) => HistoryBus.publish(conn, dest, machine, epoch)
|
|
169
|
+
case _ => (_: Vector[io.circe.Json]) => IO.unit
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Publishes committed history only after a real segment end is covered.
|
|
173
|
+
* A leader may publish when nothing has been replicated. A standby does not.
|
|
174
|
+
* A configured lease stamps its generation and a process that does not hold it does not publish.
|
|
175
|
+
* The same gate covers every configured machine.
|
|
176
|
+
*
|
|
177
|
+
* {{{
|
|
178
|
+
* SupervisorRuntime.leadAnnounce(sender, config, MachineId("machine-1"), 5L, Some(4L), Some(LeaseGrant(true, 7)))(rows)
|
|
179
|
+
* }}}
|
|
180
|
+
*/
|
|
181
|
+
private[runtime] def leadAnnounce(
|
|
182
|
+
sender: Option[StompSender],
|
|
183
|
+
config: AppConfig,
|
|
184
|
+
machine: MachineId,
|
|
185
|
+
observationMs: Long,
|
|
186
|
+
segmentEndMs: Option[Long],
|
|
187
|
+
grant: Option[LeaseGrant] = None
|
|
188
|
+
): Vector[io.circe.Json] => IO[Unit] =
|
|
189
|
+
val leader = ObservationLead.leading(config.writerRole, config.leaseUrl)
|
|
190
|
+
if config.leaseHeld && ObservationLead.ready(observationMs, segmentEndMs, leader) then historyAnnounce(sender, config, machine, grant)
|
|
191
|
+
else (_: Vector[io.circe.Json]) => IO.unit
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Sources can replay checkpoint readings
|
|
195
|
+
* after the cursor, then continue with the live subscription.
|
|
196
|
+
*
|
|
197
|
+
* {{{
|
|
198
|
+
* SupervisorRuntime.sourced(machine, aliases, live, seeding)
|
|
199
|
+
* }}}
|
|
200
|
+
*/
|
|
201
|
+
private[runtime] def sourced(
|
|
202
|
+
machine: MachineConfig,
|
|
203
|
+
aliases: List[AliasMapping],
|
|
204
|
+
live: Stream[IO, Reading],
|
|
205
|
+
seeding: Option[Seeding]
|
|
206
|
+
): Stream[IO, Reading] =
|
|
207
|
+
val input = profile.readings(machine, live)
|
|
208
|
+
seeding.fold(input)(_.seed(machine, profile.replayAliases(machine, aliases), input))
|
|
209
|
+
|
|
210
|
+
/** Holds one classifier per machine. The loser waits and tries the same lock again. */
|
|
211
|
+
private def lease(url: Option[String], machine: String, leader: Boolean, body: Stream[IO, Unit]): Stream[IO, Unit] =
|
|
212
|
+
url match
|
|
213
|
+
case None => body
|
|
214
|
+
case Some(value) =>
|
|
215
|
+
val attempt = Stream.resource(WriterLease.open(value, machine)).flatMap: hold =>
|
|
216
|
+
Stream.eval(if hold.held && !leader then hold.ready(machine, false).map(_.isDefined) else IO.pure(false)).flatMap: caught =>
|
|
217
|
+
if WriterGate.admit(hold.held, leader, caught) then body
|
|
218
|
+
else
|
|
219
|
+
val reason = if hold.held then s"classifier waiting for telemetry on $machine" else s"classifier lease denied for $machine"
|
|
220
|
+
Stream.exec(Logger[IO].info(reason)) ++ Stream.sleep_[IO](5.seconds)
|
|
221
|
+
attempt.repeat
|
|
222
|
+
|
|
223
|
+
private[runtime] def machineStreams(
|
|
224
|
+
config: AppConfig,
|
|
225
|
+
supervisor: Supervisor[IO],
|
|
226
|
+
seeding: Option[Seeding],
|
|
227
|
+
checkpoint: Option[Checkpoint],
|
|
228
|
+
sender: Option[StompSender] = None,
|
|
229
|
+
observationMs: Long = 0L,
|
|
230
|
+
segmentEndMs: Option[Long] = None,
|
|
231
|
+
profileSegments: Option[CoreSegments[IO]] = None
|
|
232
|
+
): List[Stream[IO, Unit]] =
|
|
233
|
+
config.machines.map: machine =>
|
|
234
|
+
val aliases = config.routing.aliases.getOrElse(machine.id, Nil)
|
|
235
|
+
val mqttCfg = config.connectivity.mqtt.copy(clientId = s"${config.connectivity.mqtt.clientId}-${machine.id.raw}")
|
|
236
|
+
val leader = ObservationLead.leading(config.writerRole, config.leaseUrl)
|
|
237
|
+
config.connectivity.checkpointApi match
|
|
238
|
+
case _ if !config.leaseHeld =>
|
|
239
|
+
Stream.exec(Logger[IO].info(s"classifier lease unheld for ${machine.id.raw}")) ++ Stream.never[IO]
|
|
240
|
+
case Some(_) if config.localHistory && config.leaseUrl.isEmpty && !ObservationLead.ready(observationMs, segmentEndMs, leader) =>
|
|
241
|
+
Stream.never[IO]
|
|
242
|
+
case Some(api) if config.localHistory =>
|
|
243
|
+
HistoryRun(this, profile).gated(config, machine, aliases, sender, api, observationMs, segmentEndMs)
|
|
244
|
+
case _ =>
|
|
245
|
+
val body = profileSegments.flatMap(profile.live(config, machine, aliases, _, checkpoint, seeding)).getOrElse:
|
|
246
|
+
val live = profile.input(config, machine, aliases).getOrElse(Mqtt(mqttCfg, aliases).subscribe)
|
|
247
|
+
val readings = sourced(machine, aliases, live, seeding)
|
|
248
|
+
Stream.eval(if machine.mode.isDefined then IO.pure(None) else PendingIsland.resolve(checkpoint, machine)).flatMap: initial =>
|
|
249
|
+
Stream.eval(supervisor.run(machine, readings, initial))
|
|
250
|
+
lease(config.leaseUrl, machine.id.raw, leader, body)
|
|
251
|
+
|
|
252
|
+
private[runtime] def heed(decision: Decision, segments: CoreSegments[IO], tagDefs: List[TagDef]): IO[Unit] =
|
|
253
|
+
decision.applyTo(segments, tagDefs, profile.tagging).handleErrorWith:
|
|
254
|
+
case _: IllegalArgumentException => IO.unit
|
|
255
|
+
case error => IO.raiseError(error)
|
|
256
|
+
|
|
257
|
+
private def decisionStream(config: AppConfig, segments: CoreSegments[IO]): Stream[IO, Unit] =
|
|
258
|
+
val byMachine = config.machines.map(m => m.id -> m).toMap
|
|
259
|
+
StompDecisions(config.connectivity.rabbitmq).subscribe.evalMap: decision =>
|
|
260
|
+
val machine = decision match
|
|
261
|
+
case Decision.Resolve(id, _, _, _) => byMachine.get(id)
|
|
262
|
+
case Decision.Split(id, _, _) => byMachine.get(id)
|
|
263
|
+
case _ => None
|
|
264
|
+
machine.flatMap(_.mode) match
|
|
265
|
+
case Some(_) => IO.unit
|
|
266
|
+
case None => heed(decision, segments, machine.fold(List.empty[TagDef])(_.tags))
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
package scada.supervisor.runtime
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Accepts a segment only from the current etcd writer epoch.
|
|
5
|
+
* A fenced leader may still publish; receivers apply one epoch.
|
|
6
|
+
*
|
|
7
|
+
* {{{
|
|
8
|
+
* WriterEpoch.accept(4, 4)
|
|
9
|
+
* }}}
|
|
10
|
+
*/
|
|
11
|
+
object WriterEpoch:
|
|
12
|
+
/** True when the message epoch is the epoch the quorum still grants. */
|
|
13
|
+
def accept(messageEpoch: Long, currentEpoch: Long): Boolean =
|
|
14
|
+
if messageEpoch < 1 || currentEpoch < 1 then
|
|
15
|
+
throw IllegalArgumentException(s"Writer epoch must be positive, message $messageEpoch current $currentEpoch")
|
|
16
|
+
messageEpoch == currentEpoch
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
package scada.supervisor.runtime
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Decides whether one process may classify a machine.
|
|
5
|
+
* A second holder is fenced. Classification waits until telemetry
|
|
6
|
+
* covers the replicated segment end.
|
|
7
|
+
*
|
|
8
|
+
* {{{
|
|
9
|
+
* WriterGate.claim(Some("edge-machine-1"), "edge-machine-2")
|
|
10
|
+
* WriterGate.ready(1790000005000L, 1790000005000L)
|
|
11
|
+
* }}}
|
|
12
|
+
*/
|
|
13
|
+
object WriterGate:
|
|
14
|
+
/** The current holder keeps the lease. A different holder is fenced. */
|
|
15
|
+
def claim(held: Option[String], holder: String): Option[String] =
|
|
16
|
+
if holder.isEmpty then
|
|
17
|
+
throw IllegalArgumentException(s"Lease holder required, holder $holder")
|
|
18
|
+
held match
|
|
19
|
+
case Some(owner) if owner != holder => None
|
|
20
|
+
case _ => Some(holder)
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Live classification follows the lock.
|
|
24
|
+
* A leader does not wait for stored history. A standby still does.
|
|
25
|
+
*
|
|
26
|
+
* {{{
|
|
27
|
+
* WriterGate.admit(true, true, false)
|
|
28
|
+
* }}}
|
|
29
|
+
*/
|
|
30
|
+
def admit(held: Boolean, leader: Boolean, caughtUp: Boolean): Boolean =
|
|
31
|
+
held && (leader || caughtUp)
|
|
32
|
+
|
|
33
|
+
/** True when stored telemetry has reached a real replicated segment. Zero waits. */
|
|
34
|
+
def ready(observationMs: Long, segmentEndMs: Long, leader: Boolean = false): Boolean =
|
|
35
|
+
ObservationLead.ready(observationMs, Some(segmentEndMs), leader)
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
package scada.supervisor.runtime
|
|
2
|
+
|
|
3
|
+
import cats.effect.{IO, Resource}
|
|
4
|
+
import java.sql.{Connection, DriverManager}
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* One Postgres session owns classification of one machine.
|
|
8
|
+
* The advisory lock dies with the session, so a dead leader is fenced out.
|
|
9
|
+
*
|
|
10
|
+
* {{{
|
|
11
|
+
* WriterLease.open("jdbc:postgresql://127.0.0.1:1/scada", "machine-1")
|
|
12
|
+
* }}}
|
|
13
|
+
*/
|
|
14
|
+
object WriterLease:
|
|
15
|
+
val tailSql: String = "SELECT COALESCE((EXTRACT(EPOCH FROM max(end_time)) * 1000)::bigint, 0) FROM segments WHERE machine = ? AND kind = 'phase'"
|
|
16
|
+
val listSql: String = "SELECT kind,name,start_time,end_time,duration,options,tags,properties,resolved,consumed FROM segments WHERE machine = ? AND kind = 'phase' ORDER BY start_time"
|
|
17
|
+
private[runtime] def row(result: java.sql.ResultSet): io.circe.Json =
|
|
18
|
+
import io.circe.Json
|
|
19
|
+
def field(name: String): Json =
|
|
20
|
+
Option(result.getString(name)).map(text => io.circe.parser.parse(text).getOrElse(Json.fromString(text))).getOrElse(Json.Null)
|
|
21
|
+
val start = result.getTimestamp("start_time").toInstant
|
|
22
|
+
val end = result.getTimestamp("end_time").toInstant
|
|
23
|
+
Json.obj(
|
|
24
|
+
"kind" -> Json.fromString(Option(result.getString("kind")).getOrElse("phase")),
|
|
25
|
+
"name" -> Json.fromString(Option(result.getString("name")).getOrElse("")),
|
|
26
|
+
"start_time" -> Json.fromString(start.toString),
|
|
27
|
+
"end_time" -> Json.fromString(end.toString),
|
|
28
|
+
"duration" -> Json.fromDoubleOrNull(result.getDouble("duration")),
|
|
29
|
+
"options" -> field("options"),
|
|
30
|
+
"tags" -> field("tags"),
|
|
31
|
+
"properties" -> field("properties"),
|
|
32
|
+
"resolved" -> Json.fromBoolean(result.getBoolean("resolved")),
|
|
33
|
+
"consumed" -> Json.fromBoolean(result.getBoolean("consumed"))
|
|
34
|
+
)
|
|
35
|
+
/** Holds the session when this process is the only classifier. */
|
|
36
|
+
def open(url: String, machine: String): Resource[IO, LeaseHold] =
|
|
37
|
+
if machine.isEmpty then Resource.raiseError[IO, LeaseHold, Throwable](IllegalArgumentException("Lease holder required"))
|
|
38
|
+
else Resource.make(IO.blocking(claim(url, machine)))(hold => IO.blocking(hold.close()))
|
|
39
|
+
|
|
40
|
+
/** Accepts the JDBC form and the postgres URL the history secret already stores. User info stays out of the JDBC string. */
|
|
41
|
+
def jdbc(url: String): String =
|
|
42
|
+
val normalized =
|
|
43
|
+
if url.startsWith("jdbc:postgresql:") then url
|
|
44
|
+
else if url.startsWith("postgresql://") then s"jdbc:$url"
|
|
45
|
+
else if url.startsWith("postgres://") then s"jdbc:postgresql://${url.drop("postgres://".length)}"
|
|
46
|
+
else throw IllegalArgumentException("Lease url must be a postgres jdbc url")
|
|
47
|
+
val marker = "://"
|
|
48
|
+
val start = normalized.indexOf(marker)
|
|
49
|
+
val rest = normalized.drop(start + marker.length)
|
|
50
|
+
val at = rest.lastIndexOf('@')
|
|
51
|
+
if at < 0 then normalized else normalized.take(start + marker.length) + rest.drop(at + 1)
|
|
52
|
+
|
|
53
|
+
/** User and password for a URL that stores them before the host. */
|
|
54
|
+
private[runtime] def credentials(url: String): java.util.Properties =
|
|
55
|
+
val props = new java.util.Properties()
|
|
56
|
+
val marker = "://"
|
|
57
|
+
val start = url.indexOf(marker)
|
|
58
|
+
if start < 0 then props
|
|
59
|
+
else
|
|
60
|
+
val rest = url.drop(start + marker.length)
|
|
61
|
+
val at = rest.lastIndexOf('@')
|
|
62
|
+
if at < 0 then props
|
|
63
|
+
else
|
|
64
|
+
val info = rest.take(at)
|
|
65
|
+
val colon = info.indexOf(':')
|
|
66
|
+
val user = if colon < 0 then info else info.take(colon)
|
|
67
|
+
val password = if colon < 0 then "" else info.drop(colon + 1)
|
|
68
|
+
props.setProperty("user", java.net.URLDecoder.decode(user, "UTF-8"))
|
|
69
|
+
props.setProperty("password", java.net.URLDecoder.decode(password, "UTF-8"))
|
|
70
|
+
props
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Epoch to publish. None means this process must not publish.
|
|
74
|
+
* Some(None) is the legacy publisher with no epoch field.
|
|
75
|
+
*
|
|
76
|
+
* {{{
|
|
77
|
+
* WriterLease.publication(Some("postgres://127.0.0.1:1/scada"), Some(LeaseGrant(true, 7)), Some(1L))
|
|
78
|
+
* }}}
|
|
79
|
+
*/
|
|
80
|
+
def publication(lease: Option[String], grant: Option[LeaseGrant], configured: Option[Long]): Option[Option[Long]] =
|
|
81
|
+
if lease.exists(_.nonEmpty) then grant.flatMap(_.epoch).map(Some(_)) else Some(configured)
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Generation for the session that took the lock.
|
|
85
|
+
* The stored counter is the last generation issued for this machine, or zero when none exists.
|
|
86
|
+
* The same counter keeps the same generation. A missed lock returns nothing to publish.
|
|
87
|
+
* The advisory-lock session reads that counter and calls this step.
|
|
88
|
+
*
|
|
89
|
+
* {{{
|
|
90
|
+
* WriterLease.claim(true, 4L)
|
|
91
|
+
* }}}
|
|
92
|
+
*/
|
|
93
|
+
private[runtime] def claim(held: Boolean, stored: Long): Option[LeaseGrant] =
|
|
94
|
+
if !held then None
|
|
95
|
+
else
|
|
96
|
+
val grant = LeaseGrant(true, stored + 1)
|
|
97
|
+
val _ = grant.epoch
|
|
98
|
+
Some(grant)
|
|
99
|
+
|
|
100
|
+
private def claim(url: String, machine: String): LeaseHold =
|
|
101
|
+
try session(url, machine)
|
|
102
|
+
catch case error: Exception => throw IllegalStateException(s"Classifier lease failed for $machine: ${error.getClass.getSimpleName}")
|
|
103
|
+
|
|
104
|
+
/** Opens the driver and drops the session when the hold cannot be built. */
|
|
105
|
+
private def session(url: String, machine: String): LeaseHold =
|
|
106
|
+
val _ = Class.forName("org.postgresql.Driver")
|
|
107
|
+
val connection = DriverManager.getConnection(jdbc(url), credentials(url))
|
|
108
|
+
try hold(connection, machine)
|
|
109
|
+
catch
|
|
110
|
+
case error: Exception =>
|
|
111
|
+
connection.close()
|
|
112
|
+
throw error
|
|
113
|
+
|
|
114
|
+
/** Takes the advisory lock and stamps the stored generation when this session holds it. */
|
|
115
|
+
private def hold(connection: Connection, machine: String): LeaseHold =
|
|
116
|
+
val held = locked(connection, machine)
|
|
117
|
+
LeaseHold(held, connection, advance(connection, machine, held))
|
|
118
|
+
|
|
119
|
+
/** True when this session took the classifier lock. The lock stays with the connection. */
|
|
120
|
+
private def locked(connection: Connection, machine: String): Boolean =
|
|
121
|
+
val statement = connection.prepareStatement("SELECT pg_try_advisory_lock(hashtext('scada-classify'), hashtext(?))")
|
|
122
|
+
try
|
|
123
|
+
statement.setString(1, machine)
|
|
124
|
+
val rows = statement.executeQuery()
|
|
125
|
+
val held = rows.next() && rows.getBoolean(1)
|
|
126
|
+
rows.close()
|
|
127
|
+
held
|
|
128
|
+
finally statement.close()
|
|
129
|
+
|
|
130
|
+
/** Reads the stored counter on this session and returns the generation the holder may stamp. */
|
|
131
|
+
private def advance(connection: Connection, machine: String, held: Boolean): Option[Long] =
|
|
132
|
+
val grant = claim(held, if held then counter(connection, machine) else 0L)
|
|
133
|
+
grant.foreach(item => remember(connection, machine, item.generation))
|
|
134
|
+
grant.flatMap(_.epoch)
|
|
135
|
+
|
|
136
|
+
/** Last generation issued for this machine, or zero when the lock has never been held. */
|
|
137
|
+
private def counter(connection: Connection, machine: String): Long =
|
|
138
|
+
val created = connection.prepareStatement("CREATE TABLE IF NOT EXISTS classifier_generation (machine text PRIMARY KEY, generation bigint NOT NULL)")
|
|
139
|
+
try
|
|
140
|
+
val _ = created.execute()
|
|
141
|
+
finally created.close()
|
|
142
|
+
val query = connection.prepareStatement("SELECT generation FROM classifier_generation WHERE machine = ?")
|
|
143
|
+
try
|
|
144
|
+
query.setString(1, machine)
|
|
145
|
+
val rows = query.executeQuery()
|
|
146
|
+
val generation = if rows.next() then rows.getLong(1) else 0L
|
|
147
|
+
rows.close()
|
|
148
|
+
generation
|
|
149
|
+
finally query.close()
|
|
150
|
+
|
|
151
|
+
/** Stores the generation this session just issued so the next hold is greater. */
|
|
152
|
+
private def remember(connection: Connection, machine: String, generation: Long): Unit =
|
|
153
|
+
val query = connection.prepareStatement("INSERT INTO classifier_generation (machine, generation) VALUES (?, ?) ON CONFLICT (machine) DO UPDATE SET generation = EXCLUDED.generation")
|
|
154
|
+
try
|
|
155
|
+
query.setString(1, machine)
|
|
156
|
+
query.setLong(2, generation)
|
|
157
|
+
val _ = query.executeUpdate()
|
|
158
|
+
finally query.close()
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Generation a process may stamp while it holds the classifier lease.
|
|
162
|
+
* A process that does not hold the lease has nothing to publish.
|
|
163
|
+
*
|
|
164
|
+
* {{{
|
|
165
|
+
* LeaseGrant(true, 7).epoch
|
|
166
|
+
* }}}
|
|
167
|
+
*/
|
|
168
|
+
final case class LeaseGrant(held: Boolean, generation: Long):
|
|
169
|
+
/** Epoch field for a holder. Empty when the lease is not held. */
|
|
170
|
+
def epoch: Option[Long] =
|
|
171
|
+
if !held then None
|
|
172
|
+
else
|
|
173
|
+
require(WriterEpoch.accept(generation, generation), s"Writer epoch must be positive, message $generation")
|
|
174
|
+
Some(generation)
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* The open session. Ready reads watermarks on that same session.
|
|
178
|
+
* A missing phase comes back as millisecond 0 and does not count as caught up.
|
|
179
|
+
* The session that takes the lock stores the next generation here.
|
|
180
|
+
* A missed lock leaves the generation empty.
|
|
181
|
+
*
|
|
182
|
+
* {{{
|
|
183
|
+
* hold.ready("machine-1", false)
|
|
184
|
+
* }}}
|
|
185
|
+
*/
|
|
186
|
+
final case class LeaseHold(held: Boolean, connection: Connection, generation: Option[Long] = None):
|
|
187
|
+
/** Live AMQP watermark plus stored segment end when this process may classify. None waits. */
|
|
188
|
+
def ready(machine: String, leader: Boolean, observationMs: Long = 0L): IO[Option[(Long, Option[Long])]] =
|
|
189
|
+
IO.blocking:
|
|
190
|
+
val segment = scalar(WriterLease.tailSql, machine)
|
|
191
|
+
if WriterGate.ready(observationMs, segment, leader) then Some((observationMs, Option.when(segment > 0)(segment))) else None
|
|
192
|
+
|
|
193
|
+
/** Stored phase rows and their latest end. Supervisor postgres is segments only. */
|
|
194
|
+
def seed(machine: String): IO[(Option[Long], Vector[io.circe.Json])] =
|
|
195
|
+
IO.blocking:
|
|
196
|
+
val segment = scalar(WriterLease.tailSql, machine)
|
|
197
|
+
(Option.when(segment > 0)(segment), phases(machine))
|
|
198
|
+
|
|
199
|
+
/** Closes the session and drops the advisory lock. */
|
|
200
|
+
def close(): Unit = connection.close()
|
|
201
|
+
|
|
202
|
+
private def scalar(sql: String, machine: String): Long =
|
|
203
|
+
val statement = connection.prepareStatement(sql)
|
|
204
|
+
try
|
|
205
|
+
statement.setString(1, machine)
|
|
206
|
+
val rows = statement.executeQuery()
|
|
207
|
+
if rows.next() then rows.getLong(1) else 0L
|
|
208
|
+
finally statement.close()
|
|
209
|
+
|
|
210
|
+
private def phases(machine: String): Vector[io.circe.Json] =
|
|
211
|
+
val statement = connection.prepareStatement(WriterLease.listSql)
|
|
212
|
+
try
|
|
213
|
+
statement.setString(1, machine)
|
|
214
|
+
val result = statement.executeQuery()
|
|
215
|
+
val buffer = Vector.newBuilder[io.circe.Json]
|
|
216
|
+
while result.next() do buffer += WriterLease.row(result)
|
|
217
|
+
buffer.result()
|
|
218
|
+
finally statement.close()
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Yaroslav Kivaev
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
package yarkivaev.gapsandislands.api
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* A run of consecutive observations that share the same classification
|
|
5
|
+
* kind.
|
|
6
|
+
*
|
|
7
|
+
* An `Island` is the fundamental unit of output from an [[IslandsFlow]].
|
|
8
|
+
* It represents a contiguous stretch of the input stream in which every
|
|
9
|
+
* observation was classified as the same `kind` by an [[IslandsPolicy]].
|
|
10
|
+
*
|
|
11
|
+
* The library is deliberately agnostic about what an observation is and
|
|
12
|
+
* how time is represented. The island therefore carries the actual
|
|
13
|
+
* `first` and `last` observations of the run rather than any derived
|
|
14
|
+
* metadata: anything domain-specific (duration, midpoint, summary,
|
|
15
|
+
* sampling count) is computed by the caller from the payloads.
|
|
16
|
+
*
|
|
17
|
+
* An `Island` is always non-empty: it is born when an observation is
|
|
18
|
+
* first classified as `kind` and grows as subsequent observations of the
|
|
19
|
+
* same kind arrive. A single-observation run yields an island with
|
|
20
|
+
* `first == last`.
|
|
21
|
+
*
|
|
22
|
+
* ==Example==
|
|
23
|
+
* {{{
|
|
24
|
+
* final case class Tick(timestamp: Long, value: Double)
|
|
25
|
+
*
|
|
26
|
+
* val island = Island(kind = "on", first = Tick(100L, 5.0), last = Tick(180L, 5.2))
|
|
27
|
+
* val durationMs = island.last.timestamp - island.first.timestamp
|
|
28
|
+
* }}}
|
|
29
|
+
*
|
|
30
|
+
* @tparam A the observation payload type chosen by the caller
|
|
31
|
+
* @tparam K the classification kind type chosen by the caller
|
|
32
|
+
* @param kind the classification shared by every observation in the run
|
|
33
|
+
* @param first the observation that opened this island
|
|
34
|
+
* @param last the most recent observation that extended this island
|
|
35
|
+
*/
|
|
36
|
+
final case class Island[A, K](
|
|
37
|
+
kind: K,
|
|
38
|
+
first: A,
|
|
39
|
+
last: A
|
|
40
|
+
)
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
package yarkivaev.gapsandislands.api
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Event emitted by [[IslandsFlow.pipe]] for every observation.
|
|
5
|
+
*
|
|
6
|
+
* Every input observation produces exactly one or two events:
|
|
7
|
+
* - [[IslandEvent.IslandStarted]] — the observation opened a new island;
|
|
8
|
+
* - [[IslandEvent.IslandExtended]] — the observation extended the open
|
|
9
|
+
* island (same kind as before);
|
|
10
|
+
* - [[IslandEvent.IslandClosed]] followed by [[IslandEvent.IslandStarted]]
|
|
11
|
+
* — the observation's kind differed, so the previous island ended
|
|
12
|
+
* and a new one began.
|
|
13
|
+
*
|
|
14
|
+
* Because every event carries the [[Island]] it describes (with the
|
|
15
|
+
* latest `first`/`last` observations), the stream of events is a
|
|
16
|
+
* lossless record of state: the open island after step N is exactly
|
|
17
|
+
* the island of the most recent event that is not an
|
|
18
|
+
* [[IslandEvent.IslandClosed]].
|
|
19
|
+
*
|
|
20
|
+
* @tparam A the observation payload type
|
|
21
|
+
* @tparam K the classification kind type
|
|
22
|
+
*/
|
|
23
|
+
sealed trait IslandEvent[A, K]:
|
|
24
|
+
/** The island described by this event. */
|
|
25
|
+
def island: Island[A, K]
|
|
26
|
+
|
|
27
|
+
object IslandEvent:
|
|
28
|
+
/**
|
|
29
|
+
* A new island has just opened.
|
|
30
|
+
*
|
|
31
|
+
* Emitted on the first observation of a flow or when an
|
|
32
|
+
* observation's classified kind differs from the kind of the
|
|
33
|
+
* currently open island. The island's `first` and `last` both
|
|
34
|
+
* reference the observation that triggered the start.
|
|
35
|
+
*/
|
|
36
|
+
final case class IslandStarted[A, K](island: Island[A, K]) extends IslandEvent[A, K]
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* The current island has absorbed one more observation.
|
|
40
|
+
*
|
|
41
|
+
* Emitted whenever an observation is classified with the same kind
|
|
42
|
+
* as the currently open island. The island's `first` is unchanged;
|
|
43
|
+
* `last` now references the new observation.
|
|
44
|
+
*/
|
|
45
|
+
final case class IslandExtended[A, K](island: Island[A, K]) extends IslandEvent[A, K]
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* A previously open island has just closed.
|
|
49
|
+
*
|
|
50
|
+
* Emitted when a new observation has a different kind than the
|
|
51
|
+
* currently open island; an [[IslandStarted]] follows immediately.
|
|
52
|
+
* The closed island's `last` references the most recent observation
|
|
53
|
+
* that belonged to that run.
|
|
54
|
+
*/
|
|
55
|
+
final case class IslandClosed[A, K](island: Island[A, K]) extends IslandEvent[A, K]
|