@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,29 @@
|
|
|
1
|
+
package scada.supervisor.infra.stomp
|
|
2
|
+
|
|
3
|
+
import cats.effect.{IO, Resource}
|
|
4
|
+
import fs2.Stream
|
|
5
|
+
import io.circe.parser.parse
|
|
6
|
+
import scada.supervisor.core.*
|
|
7
|
+
import scada.supervisor.infra.config.{AliasMapping,RabbitMqConfig}
|
|
8
|
+
|
|
9
|
+
/** One pre-bound durable AMQP queue preserves parameter/rise order. Slash aliases match dotted routing keys. */
|
|
10
|
+
final class StompReadings(open: Resource[IO,StompLink], queue: String, aliases: List[AliasMapping]):
|
|
11
|
+
def this(config: RabbitMqConfig, queue: String, aliases: List[AliasMapping]) =
|
|
12
|
+
this(StompConnection.open(config.address.host,config.address.port,config.vhost,config.credentials.login,config.credentials.passcode)
|
|
13
|
+
.map(connection => connection: StompLink),queue,aliases)
|
|
14
|
+
def subscribe: Stream[IO,Reading] = StompQueue(open,queue,decode).subscribe
|
|
15
|
+
def subscribeDurable: Stream[IO,(Reading,IO[Unit])] = StompQueue(open,queue,decode).subscribeDurable
|
|
16
|
+
private[stomp] def decode(frame: StompFrame): Option[Reading] =
|
|
17
|
+
for
|
|
18
|
+
route <- routed(frame.headers)
|
|
19
|
+
alias <- aliases.find(item => dotted(item.topic) == dotted(route))
|
|
20
|
+
json <- parse(frame.body).toOption
|
|
21
|
+
ts <- json.hcursor.get[Double]("ts").toOption.filter(n => n.isFinite && n >= 0)
|
|
22
|
+
value <- json.hcursor.get[Double]("value").toOption.filter(_.isFinite)
|
|
23
|
+
yield Reading(Timestamp(if ts > 1e10 then ts/1000 else ts),Params(Map(alias.metric->value)))
|
|
24
|
+
private def routed(headers: Map[String, String]): Option[String] =
|
|
25
|
+
val prefix = "/exchange/"
|
|
26
|
+
val dest = headers.get("destination").getOrElse("")
|
|
27
|
+
val slash = dest.indexOf('/', prefix.length)
|
|
28
|
+
headers.get("scada-route").orElse(headers.get("routing-key")).orElse(headers.get("x-routing-key")).orElse(Option.when(dest.startsWith(prefix) && slash >= 0)(dest.substring(slash + 1)).filter(_.nonEmpty))
|
|
29
|
+
private def dotted(route: String): String = route.replace('/', '.')
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
package scada.supervisor.infra.stomp
|
|
2
|
+
|
|
3
|
+
import cats.Monad
|
|
4
|
+
import cats.effect.IO
|
|
5
|
+
import cats.syntax.all.*
|
|
6
|
+
import io.circe.Json
|
|
7
|
+
import io.circe.syntax.*
|
|
8
|
+
import org.typelevel.log4cats.Logger
|
|
9
|
+
import org.typelevel.log4cats.slf4j.Slf4jLogger
|
|
10
|
+
import scada.supervisor.core.*
|
|
11
|
+
import scada.supervisor.core.Segments as CoreSegments
|
|
12
|
+
import scala.collection.concurrent.TrieMap
|
|
13
|
+
import scala.concurrent.duration.*
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* STOMP-publishing decorator over a [[CoreSegments]]. Every write
|
|
17
|
+
* (upsert, replace, resolve) is forwarded to `underlying` and then
|
|
18
|
+
* announced on `destination` using the [[SegmentMessage]] JSON
|
|
19
|
+
* contract.
|
|
20
|
+
*
|
|
21
|
+
* Pending heartbeats (`duration == 0`) are published at most once per
|
|
22
|
+
* `heartbeat` interval per `(machine, start)` key so shovel traffic
|
|
23
|
+
* does not overwhelm central ingest. Open, close, retag, and split
|
|
24
|
+
* announcements are never delayed.
|
|
25
|
+
*
|
|
26
|
+
* {{{
|
|
27
|
+
* StompSegments(base, connection, "/exchange/segments")
|
|
28
|
+
* StompSegments(base, connection, "/exchange/segments", 1.second)
|
|
29
|
+
* }}}
|
|
30
|
+
*/
|
|
31
|
+
final class StompSegments(
|
|
32
|
+
underlying: CoreSegments[IO],
|
|
33
|
+
connection: StompSender,
|
|
34
|
+
destination: String,
|
|
35
|
+
heartbeat: FiniteDuration = 1.second,
|
|
36
|
+
nowMillis: IO[Long] = IO.realTime.map(_.toMillis),
|
|
37
|
+
private val stamps: TrieMap[(String, Long), Long] = TrieMap.empty,
|
|
38
|
+
policy: SegmentWirePolicy = SegmentWirePolicy.default
|
|
39
|
+
) extends CoreSegments[IO]:
|
|
40
|
+
|
|
41
|
+
private given Logger[IO] = Slf4jLogger.getLogger[IO]
|
|
42
|
+
|
|
43
|
+
def upsert(machine: MachineId, segment: TaggedSegment): IO[Unit] =
|
|
44
|
+
underlying.upsert(machine, segment) *>
|
|
45
|
+
underlying.list(machine).flatMap: rows =>
|
|
46
|
+
SplitFollow.affected(segment, rows) match
|
|
47
|
+
case Some(tail) => announce(machine, tail)
|
|
48
|
+
case None =>
|
|
49
|
+
underlying.find(machine, segment.segment.start).flatMap:
|
|
50
|
+
case None => announce(machine, segment)
|
|
51
|
+
case Some(seg) => announce(machine, seg)
|
|
52
|
+
|
|
53
|
+
override def upsertTransition(machine: MachineId, rows: List[TaggedSegment])(using Monad[IO]): IO[Unit] =
|
|
54
|
+
if !policy.atomicTransition || rows.size < 2 then super.upsertTransition(machine, rows)
|
|
55
|
+
else
|
|
56
|
+
val body = Json.obj("type" -> "phase-transition".asJson, "machine" -> machine.raw.asJson,
|
|
57
|
+
"pieces" -> rows.map(row => SegmentMessage.segment(machine,row).jsonWith(policy)).asJson)
|
|
58
|
+
rows.traverse_(underlying.upsert(machine, _)) *> publishRaw(body.noSpaces, true)
|
|
59
|
+
|
|
60
|
+
def find(machine: MachineId, start: Timestamp): IO[Option[TaggedSegment]] =
|
|
61
|
+
underlying.find(machine, start)
|
|
62
|
+
|
|
63
|
+
def list(machine: MachineId): IO[List[TaggedSegment]] =
|
|
64
|
+
underlying.list(machine)
|
|
65
|
+
|
|
66
|
+
def replace(machine: MachineId, from: Timestamp, to: Timestamp, segments: List[TaggedSegment]): IO[Unit] =
|
|
67
|
+
underlying.replace(machine, from, to, segments) *>
|
|
68
|
+
(if segments.isEmpty then IO.unit
|
|
69
|
+
else publishRaw(SplitFamily.json(machine, from, segments)))
|
|
70
|
+
|
|
71
|
+
def resolve(
|
|
72
|
+
machine: MachineId,
|
|
73
|
+
original: Segment,
|
|
74
|
+
tags: List[String],
|
|
75
|
+
options: List[String],
|
|
76
|
+
properties: Map[String, String]
|
|
77
|
+
): IO[Unit] =
|
|
78
|
+
underlying.resolve(machine, original, tags, options, properties) *>
|
|
79
|
+
underlying.find(machine, original.start).flatMap:
|
|
80
|
+
case None => IO.unit
|
|
81
|
+
case Some(seg) => publish(SegmentMessage.retag(machine, seg))
|
|
82
|
+
|
|
83
|
+
private def announce(machine: MachineId, segment: TaggedSegment): IO[Unit] =
|
|
84
|
+
val message = publish(SegmentMessage.segment(machine, segment))
|
|
85
|
+
val output = if policy.splitBeforeSegment(segment) then publish(SegmentMessage.split(machine, segment)) *> message else message
|
|
86
|
+
if segment.segment.duration != 0.0 then
|
|
87
|
+
stamps.remove((machine.raw, segment.segment.start.millis))
|
|
88
|
+
output
|
|
89
|
+
else if policy.bypassHeartbeatThrottle(segment) then output
|
|
90
|
+
else throttle(machine, segment.segment.start, output)
|
|
91
|
+
|
|
92
|
+
private def throttle(machine: MachineId, start: Timestamp, publishIo: IO[Unit]): IO[Unit] =
|
|
93
|
+
val key = (machine.raw, start.millis)
|
|
94
|
+
nowMillis.flatMap: now =>
|
|
95
|
+
stamps.get(key) match
|
|
96
|
+
case Some(last) if now - last < heartbeat.toMillis => IO.unit
|
|
97
|
+
case _ =>
|
|
98
|
+
IO.delay { stamps.update(key, now) } *> publishIo
|
|
99
|
+
|
|
100
|
+
private def publish(message: SegmentMessage): IO[Unit] =
|
|
101
|
+
publishRaw(message.jsonWith(policy).noSpaces, policy.confirmed(message.segment))
|
|
102
|
+
|
|
103
|
+
private def publishRaw(body: String, confirmed: Boolean = false): IO[Unit] =
|
|
104
|
+
val frame = StompFrame.send(destination,"",body)
|
|
105
|
+
val sent = if confirmed then frame.copy(headers=frame.headers.updated("receipt",java.util.UUID.randomUUID().toString)) else frame
|
|
106
|
+
retrying(connection.send(sent),3,100.millis)
|
|
107
|
+
|
|
108
|
+
private def retrying[A](io: IO[A], attempts: Int, delay: FiniteDuration): IO[A] =
|
|
109
|
+
io.handleErrorWith: err =>
|
|
110
|
+
if attempts <= 1 then
|
|
111
|
+
Logger[IO].error(err)(s"STOMP publish failed after all retries on $destination; crashing") *>
|
|
112
|
+
IO.raiseError(err)
|
|
113
|
+
else
|
|
114
|
+
Logger[IO].warn(err)(s"STOMP publish retry in ${delay.toMillis}ms on $destination") *>
|
|
115
|
+
IO.sleep(delay) *> retrying(io, attempts - 1, delay * 2)
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
package scada.supervisor.runtime
|
|
2
|
+
|
|
3
|
+
import io.circe.Json
|
|
4
|
+
import io.circe.parser.parse
|
|
5
|
+
import io.yarkivaev.temporal.{Cursor, LocalStreams}
|
|
6
|
+
import java.sql.Connection
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Persists LocalStreams cursor metadata for one machine. Telemetry
|
|
10
|
+
* points stay out of Postgres; only id, position and touchedAt remain.
|
|
11
|
+
*
|
|
12
|
+
* {{{
|
|
13
|
+
* ClassifierCursors.save(connection, "machine-2", pool)
|
|
14
|
+
* ClassifierCursors.load(connection, "machine-2", 30000, 10000)
|
|
15
|
+
* }}}
|
|
16
|
+
*/
|
|
17
|
+
object ClassifierCursors:
|
|
18
|
+
val ddl: String = "CREATE TABLE IF NOT EXISTS classifier_cursors (machine text PRIMARY KEY, snapshot text NOT NULL)"
|
|
19
|
+
val writeSql: String = "INSERT INTO classifier_cursors (machine, snapshot) VALUES (?, ?) ON CONFLICT (machine) DO UPDATE SET snapshot = EXCLUDED.snapshot"
|
|
20
|
+
val readSql: String = "SELECT snapshot FROM classifier_cursors WHERE machine = ?"
|
|
21
|
+
def save(connection: Connection, machine: String, pool: HistoryPool): Unit =
|
|
22
|
+
val created = connection.prepareStatement(ddl)
|
|
23
|
+
try created.execute()
|
|
24
|
+
finally created.close()
|
|
25
|
+
val statement = connection.prepareStatement(writeSql)
|
|
26
|
+
try
|
|
27
|
+
statement.setString(1, machine)
|
|
28
|
+
statement.setString(2, snapshot(pool).noSpaces)
|
|
29
|
+
val _ = statement.executeUpdate()
|
|
30
|
+
finally statement.close()
|
|
31
|
+
def load(connection: Connection, machine: String, maxGap: Long, idleTimeout: Long): HistoryPool =
|
|
32
|
+
val created = connection.prepareStatement(ddl)
|
|
33
|
+
try created.execute()
|
|
34
|
+
finally created.close()
|
|
35
|
+
val statement = connection.prepareStatement(readSql)
|
|
36
|
+
try
|
|
37
|
+
statement.setString(1, machine)
|
|
38
|
+
val rows = statement.executeQuery()
|
|
39
|
+
val pool = if rows.next() then restore(rows.getString(1), maxGap, idleTimeout) else HistoryPool(LocalStreams.empty(maxGap, idleTimeout), Map.empty)
|
|
40
|
+
rows.close()
|
|
41
|
+
pool
|
|
42
|
+
finally statement.close()
|
|
43
|
+
private def snapshot(pool: HistoryPool): Json =
|
|
44
|
+
Json.obj(
|
|
45
|
+
"nextId" -> Json.fromLong(pool.cursors.nextId),
|
|
46
|
+
"streams" -> Json.arr(pool.cursors.streams.map: cursor =>
|
|
47
|
+
Json.obj("id" -> Json.fromLong(cursor.id), "position" -> Json.fromLong(cursor.position), "touchedAt" -> Json.fromLong(cursor.touchedAt))
|
|
48
|
+
*)
|
|
49
|
+
)
|
|
50
|
+
private def restore(body: String, maxGap: Long, idleTimeout: Long): HistoryPool =
|
|
51
|
+
val json = parse(body).getOrElse(Json.obj())
|
|
52
|
+
val nextId = json.hcursor.get[Long]("nextId").getOrElse(1L)
|
|
53
|
+
val streams = json.hcursor.get[Vector[Json]]("streams").getOrElse(Vector.empty).flatMap: row =>
|
|
54
|
+
for
|
|
55
|
+
id <- row.hcursor.get[Long]("id").toOption
|
|
56
|
+
position <- row.hcursor.get[Long]("position").toOption
|
|
57
|
+
yield Cursor(id, position, System.currentTimeMillis())
|
|
58
|
+
HistoryPool(LocalStreams(maxGap, idleTimeout, nextId, streams, Vector.empty), Map.empty)
|
|
@@ -0,0 +1,92 @@
|
|
|
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.yarkivaev.temporal.{Conflict, History, Observation}
|
|
8
|
+
import java.time.Instant
|
|
9
|
+
import scada.supervisor.core.{MachineConfig, MachineId, Segment, TaggedSegment, Timestamp}
|
|
10
|
+
import scada.supervisor.infra.stomp.SplitFamily
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Event-time machine classification from an AMQP classify stream.
|
|
14
|
+
* First-wins on eventId and on (channel, time). Late points overlay
|
|
15
|
+
* already committed segments and keep operator tags and cuts.
|
|
16
|
+
*
|
|
17
|
+
* {{{
|
|
18
|
+
* ClassifyHistory.start(machine, seed, announce).flatMap(_.accept(point))
|
|
19
|
+
* }}}
|
|
20
|
+
*/
|
|
21
|
+
final class ClassifyHistory(
|
|
22
|
+
machine: MachineConfig,
|
|
23
|
+
tape: Ref[IO, History],
|
|
24
|
+
stored: Ref[IO, Vector[Json]],
|
|
25
|
+
announce: Vector[Json] => IO[Unit]
|
|
26
|
+
):
|
|
27
|
+
def consume(input: Stream[IO, Observation]): Stream[IO, Unit] = input.evalMap(accept)
|
|
28
|
+
def accept(point: Observation): IO[Unit] =
|
|
29
|
+
tape.modify: history =>
|
|
30
|
+
val next = history.accept(point, Conflict.first)
|
|
31
|
+
(next, next.rows != history.rows)
|
|
32
|
+
.flatMap(changed => if changed then publish else IO.unit)
|
|
33
|
+
def classified: IO[Vector[HistorySegment]] =
|
|
34
|
+
tape.get.map(history => LocalHistory.classify(machine, ClassifyHistory.collected(history)))
|
|
35
|
+
def marked: IO[Vector[Json]] =
|
|
36
|
+
(tape.get, stored.get).mapN: (history, existing) =>
|
|
37
|
+
val result = LocalHistory.classify(machine, ClassifyHistory.collected(history))
|
|
38
|
+
LocalHistory.overlay(result, existing).map(ClassifyHistory.frame)
|
|
39
|
+
private def publish: IO[Unit] =
|
|
40
|
+
(tape.get, stored.get).flatMapN: (history, existing) =>
|
|
41
|
+
val points = ClassifyHistory.collected(history)
|
|
42
|
+
val result = LocalHistory.classify(machine, points)
|
|
43
|
+
val until = points.map(_.time).maxOption.getOrElse(0L)
|
|
44
|
+
val context = Json.obj("segments" -> Json.arr(existing*), "page" -> Json.obj("until" -> Json.fromLong(until)), "rightClosed" -> Json.False)
|
|
45
|
+
announce(ClassifyHistory.published(machine, existing, result, context))
|
|
46
|
+
|
|
47
|
+
object ClassifyHistory:
|
|
48
|
+
def start(machine: MachineConfig, seed: Vector[Json], announce: Vector[Json] => IO[Unit]): IO[ClassifyHistory] =
|
|
49
|
+
(Ref.of[IO, History](History.empty), Ref.of[IO, Vector[Json]](seed)).mapN(ClassifyHistory(machine, _, _, announce))
|
|
50
|
+
def collected(history: History): Vector[Observation] =
|
|
51
|
+
history.rows.iterator.flatMap((_, group) => group.valuesIterator).toVector
|
|
52
|
+
def frame(segment: HistorySegment, inherited: Json): Json =
|
|
53
|
+
Json.obj(
|
|
54
|
+
"kind" -> Json.fromString("phase"),
|
|
55
|
+
"name" -> Json.fromString(segment.name),
|
|
56
|
+
"start_time" -> Json.fromString(Instant.ofEpochMilli(segment.start).toString),
|
|
57
|
+
"end_time" -> Json.fromString(Instant.ofEpochMilli(segment.end).toString),
|
|
58
|
+
"duration" -> Json.fromDoubleOrNull(LocalHistory.duration(segment, segment.end, false)),
|
|
59
|
+
"consumed" -> Json.fromBoolean(inherited.hcursor.get[Boolean]("consumed").getOrElse(true)),
|
|
60
|
+
"resolved" -> Json.fromBoolean(inherited.hcursor.get[Boolean]("resolved").getOrElse(true)),
|
|
61
|
+
"tags" -> LocalHistory.metadata(inherited, "tags", Json.arr()),
|
|
62
|
+
"properties" -> LocalHistory.metadata(inherited, "properties", Json.obj())
|
|
63
|
+
)
|
|
64
|
+
def published(machine: MachineConfig, existing: Vector[Json], result: Vector[HistorySegment], context: Json): Vector[Json] =
|
|
65
|
+
val overlaid = LocalHistory.overlay(result, LocalHistory.sources(context))
|
|
66
|
+
val rows = LocalHistory.commitRows(machine, result, context).filterNot(row => nested(row, existing))
|
|
67
|
+
rows ++ families(machine.id.raw, existing, overlaid)
|
|
68
|
+
def families(machine: String, existing: Vector[Json], overlaid: Vector[(HistorySegment, Json)]): Vector[Json] =
|
|
69
|
+
existing.flatMap: row =>
|
|
70
|
+
val start = instant(row, "start_time")
|
|
71
|
+
val end = instant(row, "end_time")
|
|
72
|
+
val kids = overlaid.flatMap:
|
|
73
|
+
case (segment, inherited) if ClassifyHistory.covers(segment, start, end) =>
|
|
74
|
+
Vector((segment.copy(start = segment.start.max(start), end = segment.end.min(end)), inherited))
|
|
75
|
+
case _ => Vector.empty
|
|
76
|
+
if kids.size < 2 then Vector.empty
|
|
77
|
+
else
|
|
78
|
+
val pieces = kids.map { case (child, inherited) => tagged(child, inherited) }.toList
|
|
79
|
+
io.circe.parser.parse(SplitFamily.json(MachineId(machine), Timestamp(start / 1000.0), pieces)).toOption.toVector
|
|
80
|
+
private[runtime] def covers(segment: HistorySegment, start: Long, end: Long): Boolean =
|
|
81
|
+
if segment.start == segment.end then segment.start >= start && segment.start <= end
|
|
82
|
+
else segment.start < end && segment.end > start
|
|
83
|
+
private def nested(row: Json, existing: Vector[Json]): Boolean =
|
|
84
|
+
val start = instant(row, "start_time")
|
|
85
|
+
val end = instant(row, "end_time")
|
|
86
|
+
existing.exists(owner => instant(owner, "start_time") < start && instant(owner, "end_time") >= end)
|
|
87
|
+
private def tagged(segment: HistorySegment, inherited: Json): TaggedSegment =
|
|
88
|
+
val tags = LocalHistory.metadata(inherited, "tags", Json.arr()).asArray.getOrElse(Vector.empty).flatMap(_.asString).toList
|
|
89
|
+
val properties = LocalHistory.metadata(inherited, "properties", Json.obj()).asObject.map(_.toMap.flatMap((key, value) => value.asString.map(key -> _))).getOrElse(Map.empty)
|
|
90
|
+
TaggedSegment(Segment(segment.name, Timestamp(segment.start / 1000.0), Timestamp(segment.end / 1000.0), LocalHistory.duration(segment, segment.end, true)), tags, Nil, properties)
|
|
91
|
+
private def instant(row: Json, key: String): Long =
|
|
92
|
+
row.hcursor.get[String](key).toOption.map(Instant.parse(_).toEpochMilli).getOrElse(0L)
|
|
@@ -0,0 +1,67 @@
|
|
|
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.yarkivaev.temporal.{Conflict, Cursor, History, LocalStreams, Observation}
|
|
8
|
+
import java.time.Instant
|
|
9
|
+
import scada.supervisor.core.MachineConfig
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Machine AMQP classification with independent event-time cursors.
|
|
13
|
+
* Telemetry stays in memory; Postgres only stores cursor metadata.
|
|
14
|
+
*
|
|
15
|
+
* {{{
|
|
16
|
+
* ClassifyStreams.start(machine, seed, announce).flatMap(_.accept(point))
|
|
17
|
+
* }}}
|
|
18
|
+
*/
|
|
19
|
+
final class ClassifyStreams(machine: MachineConfig, state: Ref[IO, StreamState], ports: ClassifyPorts, watermark: Option[Long]):
|
|
20
|
+
def consume(input: Stream[IO, Observation]): Stream[IO, Unit] = input.evalMap(accept)
|
|
21
|
+
def cursors: IO[Vector[Cursor]] = state.get.map(_.pool.cursors.streams)
|
|
22
|
+
def accept(point: Observation): IO[Unit] =
|
|
23
|
+
for
|
|
24
|
+
now <- ports.clock
|
|
25
|
+
routed <- state.modify(current => ClassifyStreams.route(current, point, now, machine.window.toLong * 2000))
|
|
26
|
+
_ <- IO.whenA(routed.changed)(publish(routed.cursor))
|
|
27
|
+
snapshot <- state.get
|
|
28
|
+
_ <- ports.persist(snapshot.pool)
|
|
29
|
+
yield ()
|
|
30
|
+
private def publish(cursor: Cursor): IO[Unit] =
|
|
31
|
+
state.get.flatMap: current =>
|
|
32
|
+
val points = ClassifyHistory.collected(current.tapes.getOrElse(cursor.id, History.empty))
|
|
33
|
+
val result = LocalHistory.classify(machine, points)
|
|
34
|
+
val until = points.map(_.time).maxOption.getOrElse(0L)
|
|
35
|
+
val from = points.map(_.time).minOption.getOrElse(0L)
|
|
36
|
+
val existing = current.stored.filter(row => ClassifyStreams.overlaps(row, from, until))
|
|
37
|
+
val slack = machine.window.toLong * 2000
|
|
38
|
+
val historical = watermark.exists(end => cursor.position + slack < end)
|
|
39
|
+
val context = Json.obj("segments" -> Json.arr(existing*), "page" -> Json.obj("until" -> Json.fromLong(until)), "rightClosed" -> Json.fromBoolean(historical))
|
|
40
|
+
val page = ClassifyHistory.published(machine, existing, result, context)
|
|
41
|
+
ports.announce(page, historical)
|
|
42
|
+
|
|
43
|
+
final case class ClassifyPorts(persist: HistoryPool => IO[Unit], announce: (Vector[Json], Boolean) => IO[Unit], clock: IO[Long] = IO.realTime.map(_.toMillis))
|
|
44
|
+
final case class StreamState(pool: HistoryPool, tapes: Map[Long, History], stored: Vector[Json])
|
|
45
|
+
final case class RoutedPoint(cursor: Cursor, changed: Boolean)
|
|
46
|
+
|
|
47
|
+
object ClassifyStreams:
|
|
48
|
+
def start(machine: MachineConfig, seed: Vector[Json], announce: (Vector[Json], Boolean) => IO[Unit]): IO[ClassifyStreams] =
|
|
49
|
+
open(machine, seed, ClassifyPorts(_ => IO.unit, announce))
|
|
50
|
+
def open(machine: MachineConfig, seed: Vector[Json], ports: ClassifyPorts, watermark: Option[Long] = None, initial: Option[HistoryPool] = None): IO[ClassifyStreams] =
|
|
51
|
+
val pool = initial.getOrElse(HistoryPool(LocalStreams.empty(machine.window.toLong * 2000, 10000), Map.empty))
|
|
52
|
+
Ref.of[IO, StreamState](StreamState(pool, Map.empty, seed)).map(ClassifyStreams(machine, _, ports, watermark))
|
|
53
|
+
private[runtime] def route(current: StreamState, point: Observation, now: Long, maxGap: Long): (StreamState, RoutedPoint) =
|
|
54
|
+
val gap = if current.pool.cursors.maxGap > 0 then current.pool.cursors.maxGap else maxGap
|
|
55
|
+
val idle = current.pool.cursors.idleTimeout
|
|
56
|
+
val evicted = current.pool.expire(now)
|
|
57
|
+
val routed = evicted.cursors.copy(maxGap = gap, idleTimeout = idle).route(point, now)
|
|
58
|
+
val kept = routed.state.copy(streams = routed.state.streams.takeRight(64))
|
|
59
|
+
val pool = HistoryPool(kept, evicted.states.filter((id, _) => kept.streams.exists(_.id == id)))
|
|
60
|
+
val history = current.tapes.getOrElse(routed.stream.id, History.empty)
|
|
61
|
+
val next = history.accept(point, Conflict.first)
|
|
62
|
+
val tapes = current.tapes.filter((id, _) => kept.streams.exists(_.id == id)).updated(routed.stream.id, next)
|
|
63
|
+
(StreamState(pool, tapes, current.stored), RoutedPoint(routed.stream, next.rows != history.rows))
|
|
64
|
+
private[runtime] def overlaps(row: Json, from: Long, until: Long): Boolean =
|
|
65
|
+
val start = row.hcursor.get[String]("start_time").toOption.map(Instant.parse(_).toEpochMilli).getOrElse(0L)
|
|
66
|
+
val end = row.hcursor.get[String]("end_time").toOption.map(Instant.parse(_).toEpochMilli).getOrElse(0L)
|
|
67
|
+
start <= until && end >= from
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
package scada.supervisor.runtime
|
|
2
|
+
|
|
3
|
+
import cats.effect.IO
|
|
4
|
+
import scada.supervisor.core.*
|
|
5
|
+
import scada.supervisor.core.Segments as CoreSegments
|
|
6
|
+
import scada.supervisor.infra.checkpoint.PendingSegmentData
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Completes one pending segment row in storage. Upsert carries empty
|
|
10
|
+
* tags and properties so supervisor-sink preserves operator markup.
|
|
11
|
+
*
|
|
12
|
+
* {{{
|
|
13
|
+
* Close.run(segments, row)
|
|
14
|
+
* }}}
|
|
15
|
+
*/
|
|
16
|
+
object Close:
|
|
17
|
+
|
|
18
|
+
private val closeSeconds = 1.0
|
|
19
|
+
|
|
20
|
+
def run(segments: CoreSegments[IO], row: PendingSegmentData): IO[Unit] =
|
|
21
|
+
val end = Timestamp(row.start.epoch + closeSeconds)
|
|
22
|
+
val seg = TaggedSegment(Segment(row.name, row.start, end, closeSeconds), Nil, Nil, Map.empty)
|
|
23
|
+
segments.upsert(row.machine, seg)
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
package scada.supervisor.runtime
|
|
2
|
+
|
|
3
|
+
import cats.effect.{IO, Resource}
|
|
4
|
+
import cats.syntax.all.*
|
|
5
|
+
import com.comcast.ip4s.*
|
|
6
|
+
import org.http4s.*
|
|
7
|
+
import org.http4s.dsl.io.*
|
|
8
|
+
import org.http4s.ember.server.EmberServerBuilder
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Kubernetes-friendly liveness/readiness endpoint pair.
|
|
12
|
+
*
|
|
13
|
+
* - `GET /health` — 200 OK as soon as the HTTP server is bound.
|
|
14
|
+
* - `GET /ready` — 200 OK while this process is listening.
|
|
15
|
+
* A silent source does not make the process unhealthy.
|
|
16
|
+
*
|
|
17
|
+
* {{{
|
|
18
|
+
* HealthServer().serve(8080)
|
|
19
|
+
* }}}
|
|
20
|
+
*/
|
|
21
|
+
final class HealthServer:
|
|
22
|
+
|
|
23
|
+
def serve(port: Int): Resource[IO, Unit] =
|
|
24
|
+
Port
|
|
25
|
+
.fromInt(port)
|
|
26
|
+
.fold(Resource.raiseError[IO, Unit, Throwable](IllegalArgumentException(s"invalid health port: $port"))): p =>
|
|
27
|
+
EmberServerBuilder
|
|
28
|
+
.default[IO]
|
|
29
|
+
.withHost(host"0.0.0.0")
|
|
30
|
+
.withPort(p)
|
|
31
|
+
.withHttpApp(routes.orNotFound)
|
|
32
|
+
.build
|
|
33
|
+
.void
|
|
34
|
+
|
|
35
|
+
private[runtime] def routes: HttpRoutes[IO] =
|
|
36
|
+
HttpRoutes.of[IO]:
|
|
37
|
+
case GET -> Root / "health" => Ok("ok")
|
|
38
|
+
case GET -> Root / "ready" => Ok("ready")
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
package scada.supervisor.runtime
|
|
2
|
+
|
|
3
|
+
import cats.effect.IO
|
|
4
|
+
import cats.syntax.all.*
|
|
5
|
+
import io.circe.Json
|
|
6
|
+
import io.circe.parser.parse
|
|
7
|
+
import java.time.Instant
|
|
8
|
+
import scada.supervisor.core.*
|
|
9
|
+
import scada.supervisor.infra.stomp.{SegmentMessage, StompFrame, StompSender}
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Publishes a committed local-history page to the segment exchange.
|
|
13
|
+
* Local ingest is unbound, so the already stored row is not written again.
|
|
14
|
+
*
|
|
15
|
+
* {{{
|
|
16
|
+
* HistoryBus.message(MachineId("machine-1"), row)
|
|
17
|
+
* HistoryBus.publish(sender, "/exchange/scada.segments", MachineId("machine-1"))(rows)
|
|
18
|
+
* HistoryBus.publish(sender, "/exchange/scada.segments", MachineId("machine-1"), Some(7L))(rows)
|
|
19
|
+
* }}}
|
|
20
|
+
*/
|
|
21
|
+
object HistoryBus:
|
|
22
|
+
/** Bus envelope for one committed row, with start and end kept as exact epoch millis. */
|
|
23
|
+
def message(machine: MachineId, row: Json): Json =
|
|
24
|
+
val cursor = row.hcursor
|
|
25
|
+
val name = required(cursor, "name")
|
|
26
|
+
val start = Instant.parse(required(cursor, "start_time")).toEpochMilli
|
|
27
|
+
val end = Instant.parse(required(cursor, "end_time")).toEpochMilli
|
|
28
|
+
val duration = cursor.get[Double]("duration").getOrElse(0.0)
|
|
29
|
+
val tagged = TaggedSegment(
|
|
30
|
+
Segment(name, Timestamp(start / 1000.0), Timestamp(end / 1000.0), duration),
|
|
31
|
+
strings(cursor.downField("tags").focus.getOrElse(Json.Null)),
|
|
32
|
+
strings(cursor.downField("options").focus.getOrElse(Json.Null)),
|
|
33
|
+
props(cursor.downField("properties").focus.getOrElse(Json.Null))
|
|
34
|
+
)
|
|
35
|
+
SegmentMessage.segment(machine, tagged).json.deepMerge(Json.obj(
|
|
36
|
+
"start" -> Json.fromLong(start),
|
|
37
|
+
"end" -> Json.fromLong(end),
|
|
38
|
+
"kind" -> Json.fromString(cursor.get[String]("kind").getOrElse("phase"))
|
|
39
|
+
))
|
|
40
|
+
|
|
41
|
+
/** Same envelope plus the etcd writer epoch receivers use to keep one writer. */
|
|
42
|
+
def stamped(machine: MachineId, row: Json, epoch: Long): Json =
|
|
43
|
+
require(WriterEpoch.accept(epoch, epoch), s"Writer epoch must be positive, message $epoch")
|
|
44
|
+
message(machine, row).deepMerge(Json.obj("epoch" -> Json.fromLong(epoch)))
|
|
45
|
+
|
|
46
|
+
/** Sends every committed row. An empty page sends nothing. */
|
|
47
|
+
def publish(sender: StompSender, destination: String, machine: MachineId)(rows: Vector[Json]): IO[Unit] =
|
|
48
|
+
publish(sender, destination, machine, None)(rows)
|
|
49
|
+
|
|
50
|
+
/** Sends every committed row and stamps the writer epoch when one is supplied. */
|
|
51
|
+
def publish(sender: StompSender, destination: String, machine: MachineId, epoch: Option[Long])(rows: Vector[Json]): IO[Unit] =
|
|
52
|
+
rows.traverse_(row => sender.send(StompFrame.send(
|
|
53
|
+
destination,
|
|
54
|
+
"",
|
|
55
|
+
epoch.fold(message(machine, row))(n => stamped(machine, row, n)).noSpaces
|
|
56
|
+
)))
|
|
57
|
+
|
|
58
|
+
private def required(cursor: io.circe.HCursor, key: String): String =
|
|
59
|
+
cursor.get[String](key).fold(error => throw IllegalArgumentException(s"History segment missing $key: ${error.getMessage}"), identity)
|
|
60
|
+
|
|
61
|
+
private def strings(value: Json): List[String] =
|
|
62
|
+
val parsed = value.asString.flatMap(text => parse(text).toOption).getOrElse(value)
|
|
63
|
+
parsed.asArray.fold(List.empty[String])(_.flatMap(_.asString).toList)
|
|
64
|
+
|
|
65
|
+
private def props(value: Json): Map[String, String] =
|
|
66
|
+
val parsed = value.asString.flatMap(text => parse(text).toOption).getOrElse(value)
|
|
67
|
+
parsed.asObject.fold(Map.empty[String, String])(_.toIterable.flatMap((key, item) => item.asString.map(key -> _)).toMap)
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
package scada.supervisor.runtime
|
|
2
|
+
|
|
3
|
+
import cats.effect.IO
|
|
4
|
+
import io.circe.Json
|
|
5
|
+
import io.circe.parser.parse
|
|
6
|
+
import java.net.URI
|
|
7
|
+
import java.net.http.{HttpClient,HttpRequest,HttpResponse}
|
|
8
|
+
import java.time.Duration
|
|
9
|
+
import scada.supervisor.infra.config.CheckpointApiConfig
|
|
10
|
+
import scala.concurrent.duration.*
|
|
11
|
+
|
|
12
|
+
/** Shared authenticated local history transport; failed requests never retire server work. */
|
|
13
|
+
final class HistoryClient(config: CheckpointApiConfig):
|
|
14
|
+
private val client=HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(config.timeoutSeconds.toLong)).build()
|
|
15
|
+
def request(method: String,path: String,body: Json=Json.Null): IO[Json] =
|
|
16
|
+
val builder=HttpRequest.newBuilder(URI.create(config.baseUrl.stripSuffix("/")+path))
|
|
17
|
+
.timeout(Duration.ofSeconds(config.timeoutSeconds.toLong)).header("Content-Type","application/json")
|
|
18
|
+
config.token.foreach(token=>builder.header("Authorization",s"Bearer $token"))
|
|
19
|
+
val request=if method=="GET" then builder.GET().build() else builder.POST(HttpRequest.BodyPublishers.ofString(body.noSpaces)).build()
|
|
20
|
+
IO.blocking(client.send(request,HttpResponse.BodyHandlers.ofString())).flatMap: response =>
|
|
21
|
+
if response.statusCode()/100!=2 then IO.raiseError(RuntimeException(s"history API $path status ${response.statusCode()}"))
|
|
22
|
+
else IO.fromEither(parse(response.body()).left.map(error=>RuntimeException(error.message)))
|
|
23
|
+
def retry[A](action: IO[A]): IO[A] = action.handleErrorWith(_=>IO.sleep(2.seconds) *> retry(action))
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
package scada.supervisor.runtime
|
|
2
|
+
|
|
3
|
+
import cats.effect.IO
|
|
4
|
+
import cats.syntax.all.*
|
|
5
|
+
import fs2.Stream
|
|
6
|
+
import io.circe.Json
|
|
7
|
+
import org.typelevel.log4cats.Logger
|
|
8
|
+
import org.typelevel.log4cats.slf4j.Slf4jLogger
|
|
9
|
+
import scada.supervisor.infra.config.{AliasMapping, AppConfig, CheckpointApiConfig}
|
|
10
|
+
import scada.supervisor.infra.stomp.{ClassifyQueue, StompFrame, StompSender}
|
|
11
|
+
import scala.concurrent.duration.*
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Starts classification from AMQP `scada.classify.{machine}`.
|
|
15
|
+
* Site modes can use a durable HTTP work queue. A holder stamps the
|
|
16
|
+
* lease generation. A missing generation does not publish.
|
|
17
|
+
*
|
|
18
|
+
* {{{
|
|
19
|
+
* HistoryRun.gated(config, machine, aliases, sender, api)
|
|
20
|
+
* }}}
|
|
21
|
+
*/
|
|
22
|
+
final class HistoryRun(runtime: SupervisorRuntime, profile: RuntimeProfile):
|
|
23
|
+
private given Logger[IO] = Slf4jLogger.getLogger[IO]
|
|
24
|
+
|
|
25
|
+
/** Retries until this process is the sole classifier. */
|
|
26
|
+
def gated(config: AppConfig, machine: scada.supervisor.core.MachineConfig, aliases: List[AliasMapping], sender: Option[StompSender], api: CheckpointApiConfig, observationMs: Long = 0L, segmentEndMs: Option[Long] = None): Stream[IO, Unit] =
|
|
27
|
+
if !config.leaseHeld then Stream.never[IO]
|
|
28
|
+
else
|
|
29
|
+
val leader = ObservationLead.leading(config.writerRole, config.leaseUrl)
|
|
30
|
+
config.leaseUrl match
|
|
31
|
+
case None if machine.mode.isDefined && !ObservationLead.ready(observationMs, segmentEndMs, leader) =>
|
|
32
|
+
Stream.exec(Logger[IO].info(s"classifier waiting for telemetry on ${machine.id.raw}")) ++ Stream.sleep_[IO](5.seconds) ++ gated(config, machine, aliases, sender, api, observationMs, segmentEndMs)
|
|
33
|
+
case None => follow(config, machine, aliases, sender, api, observationMs, segmentEndMs)
|
|
34
|
+
case Some(url) => once(url, config, machine, aliases, sender, api) ++ Stream.eval(IO.unit).flatMap(_ => gated(config, machine, aliases, sender, api, observationMs, segmentEndMs))
|
|
35
|
+
|
|
36
|
+
private def once(url: String, config: AppConfig, machine: scada.supervisor.core.MachineConfig, aliases: List[AliasMapping], sender: Option[StompSender], api: CheckpointApiConfig): Stream[IO, Unit] =
|
|
37
|
+
Stream.resource(WriterLease.open(url, machine.id.raw)).flatMap: hold =>
|
|
38
|
+
if !hold.held then Stream.exec(Logger[IO].info(s"classifier lease denied for ${machine.id.raw}")) ++ Stream.sleep_[IO](5.seconds)
|
|
39
|
+
else Stream.eval(hold.seed(machine.id.raw)).flatMap: (end, rows) =>
|
|
40
|
+
val grant = hold.generation.map(value => LeaseGrant(true, value))
|
|
41
|
+
if machine.mode.isDefined then follow(config, machine, aliases, sender, api, end.getOrElse(0L), end, grant)
|
|
42
|
+
else Stream.eval(IO.blocking(ClassifierCursors.load(hold.connection, machine.id.raw, machine.window.toLong * 2000, 10000))).flatMap: pool =>
|
|
43
|
+
amqp(config, machine, aliases, sender, rows, end, grant, p => IO.blocking(ClassifierCursors.save(hold.connection, machine.id.raw, p)), Some(pool))
|
|
44
|
+
|
|
45
|
+
private def follow(config: AppConfig, machine: scada.supervisor.core.MachineConfig, aliases: List[AliasMapping], sender: Option[StompSender], api: CheckpointApiConfig, observationMs: Long, segmentEndMs: Option[Long], grant: Option[LeaseGrant] = None): Stream[IO, Unit] =
|
|
46
|
+
if machine.mode.isEmpty then amqp(config, machine, aliases, sender, Vector.empty, segmentEndMs, grant)
|
|
47
|
+
else if !ObservationLead.ready(observationMs, segmentEndMs, ObservationLead.leading(config.writerRole, config.leaseUrl)) then
|
|
48
|
+
Stream.exec(Logger[IO].info(s"classifier waiting for telemetry on ${machine.id.raw}")) ++ Stream.sleep_[IO](5.seconds)
|
|
49
|
+
else custom(config, machine, aliases, sender, api, observationMs, segmentEndMs, grant)
|
|
50
|
+
|
|
51
|
+
private def custom(config: AppConfig, machine: scada.supervisor.core.MachineConfig, aliases: List[AliasMapping], sender: Option[StompSender], api: CheckpointApiConfig, observationMs: Long, segmentEndMs: Option[Long], grant: Option[LeaseGrant] = None): Stream[IO, Unit] =
|
|
52
|
+
val announce = runtime.leadAnnounce(sender, config, machine.id, observationMs, segmentEndMs, grant)
|
|
53
|
+
profile.history(machine, aliases, api, announce)
|
|
54
|
+
|
|
55
|
+
private def amqp(config: AppConfig, machine: scada.supervisor.core.MachineConfig, aliases: List[AliasMapping], sender: Option[StompSender], seed: Vector[Json], segmentEndMs: Option[Long], grant: Option[LeaseGrant], persist: HistoryPool => IO[Unit] = _ => IO.unit, initial: Option[HistoryPool] = None): Stream[IO, Unit] =
|
|
56
|
+
val leader = ObservationLead.leading(config.writerRole, config.leaseUrl)
|
|
57
|
+
val publish = runtime.historyAnnounce(sender, config, machine.id, grant)
|
|
58
|
+
val queue = s"scada.classify.${machine.id.raw}"
|
|
59
|
+
val input = ClassifyQueue(config.connectivity.rabbitmq, queue, aliases).subscribe
|
|
60
|
+
val ports = ClassifyPorts(persist, (rows, historical) => ClassifyBus.publish(sender, config, segmentEndMs, leader, publish, historical)(rows))
|
|
61
|
+
Stream.eval(Logger[IO].info(s"consuming AMQP classify queue $queue")) >> Stream.eval(ClassifyStreams.open(machine, seed, ports, segmentEndMs, initial)).flatMap(_.consume(input))
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Sends committed classify rows. Split-family bodies stay raw JSON.
|
|
65
|
+
*
|
|
66
|
+
* {{{
|
|
67
|
+
* ClassifyBus.publish(sender, config, None, true, announce)(rows)
|
|
68
|
+
* }}}
|
|
69
|
+
*/
|
|
70
|
+
object ClassifyBus:
|
|
71
|
+
def publish(sender: Option[StompSender], config: AppConfig, segmentEndMs: Option[Long], leader: Boolean, announce: Vector[Json] => IO[Unit], historical: Boolean = false)(rows: Vector[Json]): IO[Unit] =
|
|
72
|
+
val dest = config.connectivity.rabbitmq.destinations.segments
|
|
73
|
+
val families = rows.filter(_.hcursor.get[String]("type").toOption.contains("split-family"))
|
|
74
|
+
val segments = rows.filterNot(_.hcursor.get[String]("type").toOption.contains("split-family"))
|
|
75
|
+
val obs = ClassifyBus.horizon(rows)
|
|
76
|
+
if !historical && !ObservationLead.ready(obs, segmentEndMs, leader) then IO.unit
|
|
77
|
+
else
|
|
78
|
+
val outbound = if sender.isEmpty then rows else segments
|
|
79
|
+
announce(outbound) *> ((sender, dest) match
|
|
80
|
+
case (Some(conn), Some(path)) => families.traverse_(row => conn.send(StompFrame.send(path, "", row.noSpaces)))
|
|
81
|
+
case _ => IO.unit)
|
|
82
|
+
private def horizon(rows: Vector[Json]): Long =
|
|
83
|
+
val ends = rows.flatMap: row =>
|
|
84
|
+
row.hcursor.get[String]("end_time").toOption.map(java.time.Instant.parse(_).toEpochMilli).toVector ++
|
|
85
|
+
row.hcursor.downField("pieces").as[Vector[Json]].toOption.getOrElse(Vector.empty).flatMap(_.hcursor.get[Long]("end").toOption)
|
|
86
|
+
ends.maxOption.getOrElse(0L)
|