@yarkivaev/scada 2.7.0 → 2.8.0
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 +4 -4
- package/db/migrations/C0008__segment_write_receipts_grants.sql +1 -0
- package/db/migrations/E0019__segment_write_fence.sql +36 -0
- package/db/migrations/E0020__segment_write_fence_grants.sql +4 -0
- package/db/migrations/V0015__segment_write_receipts.sql +7 -0
- package/index.js +2 -0
- package/package.json +6 -3
- package/src/application/supervisorSink.js +15 -5
- package/src/domain/segment/segmentCoalesce.js +2 -1
- package/src/infrastructure/http/edge/edgeApi.js +1 -1
- package/src/infrastructure/http/edge/routes/history/historyRoutes.js +8 -3
- package/src/infrastructure/ingest/codecs/segmentCodec.js +26 -4
- package/src/infrastructure/ingest/db/migrationProfile.js +4 -1
- package/src/infrastructure/ingest/pipelines/segmentPipeline.js +11 -5
- package/src/infrastructure/ingest/sinks/fencedSegments.js +117 -0
- package/src/infrastructure/persistence/pg/history.js +4 -3
- package/src/infrastructure/persistence/pg/segmentWriteFence.js +112 -0
- package/stream-processing/dependencies/stream-worker.jar +0 -0
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/Condition.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/CyclePhases.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/Decision.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/Emission.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/MachineConfig.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/MachineId.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/MachineMode.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/Params.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/Reading.scala +1 -1
- package/stream-processing/src/main/scala/scada/processing/core/ReadingWorker.scala +82 -0
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/Segment.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/SegmentDef.scala +1 -1
- package/stream-processing/src/main/scala/scada/processing/core/Segmentation.scala +47 -0
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/Segments.scala +3 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/SplitFollow.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/SplitPieces.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/TagDef.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/TaggedSegment.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/Tagging.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/Timestamp.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/segmentation/Timeline.scala +2 -2
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/checkpoint/Checkpoint.scala +2 -2
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/checkpoint/ClickhouseReadingsCheckpoint.scala +3 -3
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/checkpoint/SupervisorSinkCheckpoint.scala +3 -3
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/config/AppConfig.scala +2 -2
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/config/ConfigLoad.scala +2 -2
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/config/ConfigProfile.scala +2 -2
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/mqtt/Mqtt.scala +3 -3
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/mqtt/Sessions.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/state/AtomicStateFile.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/state/CheckpointSegments.scala +7 -5
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/state/SegmentStatePolicy.scala +2 -2
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/state/Segments.scala +3 -3
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/ClassifyQueue.scala +4 -4
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/DecisionMessage.scala +2 -2
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/DurableStomp.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/SegmentMessage.scala +2 -2
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/SegmentWirePolicy.scala +2 -2
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/SplitFamily.scala +2 -2
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/StompConnection.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/StompDecisions.scala +3 -3
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/StompFrame.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/StompMachineDecisions.scala +3 -3
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/StompQueue.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/StompReadings.scala +3 -4
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/StompSegments.scala +20 -13
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/ClassifyHistory.scala +3 -3
- package/stream-processing/src/main/scala/scada/processing/runtime/ClassifyStreams.scala +128 -0
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/Close.scala +4 -4
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/HealthServer.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/HistoryBus.scala +40 -8
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/HistoryClient.scala +11 -4
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/HistoryRun.scala +42 -40
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/LocalHistory.scala +122 -36
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/ObservationLead.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/Orphans.scala +4 -4
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/PendingIsland.scala +3 -3
- package/stream-processing/src/main/scala/scada/processing/runtime/ProcessingApp.scala +8 -0
- package/{supervisor-engine/src/main/scala/scada/supervisor/runtime/SupervisorRuntime.scala → stream-processing/src/main/scala/scada/processing/runtime/ProcessingApplication.scala} +108 -106
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/RuntimeProfile.scala +10 -12
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/Seeding.scala +4 -4
- package/stream-processing/src/main/scala/scada/processing/runtime/TimelineWriter.scala +81 -0
- package/stream-processing/src/main/scala/scada/processing/runtime/WorkerDatabase.scala +7 -0
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/WriterEpoch.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/WriterGate.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/WriterLease.scala +11 -9
- package/{supervisor-engine → stream-processing}/src/main/scala/scada/stream/replay/Replay.scala +1 -1
- package/stream-processing/stream-worker.lock +2 -0
- package/supervisor-engine/src/main/scala/scada/stream/worker/Processor.scala +0 -8
- package/supervisor-engine/src/main/scala/scada/stream/worker/StreamWorker.scala +0 -119
- package/supervisor-engine/src/main/scala/scada/stream/worker/postgres/PgCheckpointStore.scala +0 -83
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Segmentation.scala +0 -52
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Supervisor.scala +0 -66
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ClassifierCursors.scala +0 -58
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ClassifyStreams.scala +0 -67
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/EngineApp.scala +0 -4
- /package/{supervisor-engine → stream-processing}/vendor/gaps-and-islands/LICENSE +0 -0
- /package/{supervisor-engine → stream-processing}/vendor/gaps-and-islands/UPSTREAM +0 -0
- /package/{supervisor-engine → stream-processing}/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/Island.scala +0 -0
- /package/{supervisor-engine → stream-processing}/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandEvent.scala +0 -0
- /package/{supervisor-engine → stream-processing}/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandsFlow.scala +0 -0
- /package/{supervisor-engine → stream-processing}/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandsPolicy.scala +0 -0
- /package/{supervisor-engine → stream-processing}/vendor/temporal-streams/LICENSE +0 -0
- /package/{supervisor-engine → stream-processing}/vendor/temporal-streams/UPSTREAM +0 -0
- /package/{supervisor-engine → stream-processing}/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/History.scala +0 -0
- /package/{supervisor-engine → stream-processing}/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/LocalStreams.scala +0 -0
- /package/{supervisor-engine → stream-processing}/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/Overlay.scala +0 -0
- /package/{supervisor-engine → stream-processing}/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/Worker.scala +0 -0
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
package scada.processing.runtime
|
|
2
|
+
|
|
3
|
+
import cats.effect.IO
|
|
4
|
+
import cats.effect.std.Semaphore
|
|
5
|
+
import fs2.Stream
|
|
6
|
+
import io.circe.{Codec, Decoder, Encoder, Json}
|
|
7
|
+
import io.circe.generic.semiauto.deriveCodec
|
|
8
|
+
import io.yarkivaev.temporal.{Conflict, Cursor, History, LocalStreams, Observation, Work}
|
|
9
|
+
import scala.collection.immutable.TreeMap
|
|
10
|
+
import java.time.Instant
|
|
11
|
+
import io.yarkivaev.streamworker.postgres.PgCheckpointStore
|
|
12
|
+
import io.yarkivaev.streamworker.{Checkpoint, CheckpointStore, Delivery, ProcessingError, Processor, ProcessorVersion, StepResult, StreamWorker, TaskIdentity}
|
|
13
|
+
import scada.processing.core.MachineConfig
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Machine AMQP classification with independent event-time cursors.
|
|
17
|
+
* Leased workers checkpoint their active tapes and pending writes in PostgreSQL.
|
|
18
|
+
*
|
|
19
|
+
* {{{
|
|
20
|
+
* ClassifyStreams.start(machine, seed, announce).flatMap(_.accept(point))
|
|
21
|
+
* }}}
|
|
22
|
+
*/
|
|
23
|
+
final class ClassifyStreams private (
|
|
24
|
+
machine: MachineConfig,
|
|
25
|
+
store: CheckpointStore[StreamState, ClassifyStreams.Command],
|
|
26
|
+
task: TaskIdentity,
|
|
27
|
+
ports: ClassifyPorts,
|
|
28
|
+
watermark: Option[Long],
|
|
29
|
+
lock: Semaphore[IO],
|
|
30
|
+
ownership: Long
|
|
31
|
+
):
|
|
32
|
+
import ClassifyStreams.{Command, version}
|
|
33
|
+
|
|
34
|
+
private val processor = new Processor[Unit, StreamState, (Observation, Long), Command]:
|
|
35
|
+
override def step(config: Unit, state: StreamState, input: (Observation, Long))
|
|
36
|
+
: Either[ProcessingError, StepResult[StreamState, Command]] =
|
|
37
|
+
val (point, now) = input
|
|
38
|
+
val (next, routed) = ClassifyStreams.route(state, point, now, machine.window.toLong * 2000)
|
|
39
|
+
Right(StepResult(next, Vector(Command(point, routed))))
|
|
40
|
+
|
|
41
|
+
private val worker = StreamWorker(processor, store, (_, output) =>
|
|
42
|
+
val command = output.value
|
|
43
|
+
store.load(task, ownership).flatMap: checkpoint =>
|
|
44
|
+
IO.whenA(command.routed.changed)(publish(checkpoint.state, command.routed.cursor)) *>
|
|
45
|
+
ports.persist(checkpoint.state.pool))
|
|
46
|
+
|
|
47
|
+
def consume(input: Stream[IO, Observation]): Stream[IO, Unit] = input.evalMap(accept)
|
|
48
|
+
def consumeDurable(input: Stream[IO, (Observation, IO[Unit])]): Stream[IO, Unit] =
|
|
49
|
+
input.evalMap((point, acknowledge) => accept(point) *> acknowledge)
|
|
50
|
+
|
|
51
|
+
def cursors: IO[Vector[Cursor]] = store.load(task, ownership).map(_.state.pool.cursors.streams)
|
|
52
|
+
def accept(point: Observation): IO[Unit] = lock.permit.use: _ =>
|
|
53
|
+
for
|
|
54
|
+
checkpoint <- store.load(task, ownership)
|
|
55
|
+
now <- ports.clock
|
|
56
|
+
retry = checkpoint.pendingOutputs.exists(_.value.point == point)
|
|
57
|
+
position = checkpoint.position.fold(0L)(previous => if retry then previous else previous + 1L)
|
|
58
|
+
// The cursor checkpoint is session-local. Broker ACK waits for publication and cursor persistence.
|
|
59
|
+
_ <- worker.run(task, version, (), ownership)(_ => Stream.emit(Delivery(position, (point, now), IO.unit)))
|
|
60
|
+
yield ()
|
|
61
|
+
private def publish(snapshot: StreamState, cursor: Cursor): IO[Unit] =
|
|
62
|
+
val points = ClassifyHistory.collected(snapshot.tapes.getOrElse(cursor.id, History.empty))
|
|
63
|
+
val until = points.map(_.time).maxOption.getOrElse(0L)
|
|
64
|
+
val from = points.map(_.time).minOption.getOrElse(0L)
|
|
65
|
+
val existing = snapshot.stored.filter(row => ClassifyStreams.overlaps(row, from, until))
|
|
66
|
+
val slack = machine.window.toLong * 2000
|
|
67
|
+
val historical = watermark.exists(end => cursor.position + slack < end)
|
|
68
|
+
val context = Json.obj("segments" -> Json.arr(existing*), "page" -> Json.obj("until" -> Json.fromLong(until)), "rightClosed" -> Json.fromBoolean(historical))
|
|
69
|
+
val classification = if historical then LocalHistory.replay(machine, points, "", s"cursor:${cursor.id}").map(_.segments)
|
|
70
|
+
else IO(LocalHistory.classify(machine, points))
|
|
71
|
+
classification.flatMap: result =>
|
|
72
|
+
val page = ClassifyHistory.published(machine, existing, result, context)
|
|
73
|
+
ports.announce(page, historical)
|
|
74
|
+
|
|
75
|
+
final case class ClassifyPorts(persist: HistoryPool => IO[Unit], announce: (Vector[Json], Boolean) => IO[Unit], clock: IO[Long] = IO.realTime.map(_.toMillis))
|
|
76
|
+
final case class StreamState(pool: HistoryPool, tapes: Map[Long, History], stored: Vector[Json])
|
|
77
|
+
final case class RoutedPoint(cursor: Cursor, changed: Boolean)
|
|
78
|
+
|
|
79
|
+
object ClassifyStreams:
|
|
80
|
+
private final case class Command(point: Observation, routed: RoutedPoint)
|
|
81
|
+
private given Codec.AsObject[Cursor] = deriveCodec
|
|
82
|
+
private given Codec.AsObject[Work] = deriveCodec
|
|
83
|
+
private given Codec.AsObject[LocalStreams] = deriveCodec
|
|
84
|
+
private given Codec.AsObject[Observation] = deriveCodec
|
|
85
|
+
private given Codec.AsObject[HistorySegment] = deriveCodec
|
|
86
|
+
private given Codec.AsObject[HistoryState] = deriveCodec
|
|
87
|
+
private given Codec.AsObject[HistoryPool] = deriveCodec
|
|
88
|
+
private given Encoder.AsObject[History] = Encoder.forProduct2("rows", "seen")(value => (value.rows.toMap, value.seen))
|
|
89
|
+
private given Decoder[History] = Decoder.forProduct2("rows", "seen")(
|
|
90
|
+
(rows: Map[Long, Map[String, Observation]], seen: Set[String]) => History(TreeMap.from(rows), seen))
|
|
91
|
+
private given Codec.AsObject[StreamState] = deriveCodec
|
|
92
|
+
private given Codec.AsObject[RoutedPoint] = deriveCodec
|
|
93
|
+
private given Codec.AsObject[Command] = deriveCodec
|
|
94
|
+
private val version = ProcessorVersion("amqp-classify/1", "session", "history-cursors/1")
|
|
95
|
+
|
|
96
|
+
def start(machine: MachineConfig, seed: Vector[Json], announce: (Vector[Json], Boolean) => IO[Unit]): IO[ClassifyStreams] =
|
|
97
|
+
open(machine, seed, ClassifyPorts(_ => IO.unit, announce))
|
|
98
|
+
def open(machine: MachineConfig, seed: Vector[Json], ports: ClassifyPorts,
|
|
99
|
+
watermark: Option[Long] = None, database: Option[WorkerDatabase] = None): IO[ClassifyStreams] =
|
|
100
|
+
val pool = HistoryPool(LocalStreams.empty(machine.window.toLong * 2000, 10000), Map.empty)
|
|
101
|
+
val owner = database.fold(1L)(_.generation)
|
|
102
|
+
val run = database.fold(IO.randomUUID.map(_.toString))(_ => IO.pure("live"))
|
|
103
|
+
for
|
|
104
|
+
id <- run
|
|
105
|
+
task = TaskIdentity(machine.id.raw, "amqp-classify", id)
|
|
106
|
+
snapshot = Checkpoint[StreamState, Command](task, version, 0L, None, StreamState(pool, Map.empty, seed), Vector.empty)
|
|
107
|
+
store <- database match
|
|
108
|
+
case Some(db) =>
|
|
109
|
+
val durable = PgCheckpointStore[StreamState, Command](db.transactor)
|
|
110
|
+
durable.claim(owner, snapshot).as(durable)
|
|
111
|
+
case None => CheckpointStore.session(snapshot, owner)
|
|
112
|
+
lock <- Semaphore[IO](1)
|
|
113
|
+
yield new ClassifyStreams(machine, store, task, ports, watermark, lock, owner)
|
|
114
|
+
private[runtime] def route(current: StreamState, point: Observation, now: Long, maxGap: Long): (StreamState, RoutedPoint) =
|
|
115
|
+
val gap = if current.pool.cursors.maxGap > 0 then current.pool.cursors.maxGap else maxGap
|
|
116
|
+
val idle = current.pool.cursors.idleTimeout
|
|
117
|
+
val evicted = current.pool.expire(now)
|
|
118
|
+
val routed = evicted.cursors.copy(maxGap = gap, idleTimeout = idle).route(point, now)
|
|
119
|
+
val kept = routed.state.copy(streams = routed.state.streams.takeRight(64))
|
|
120
|
+
val pool = HistoryPool(kept, evicted.states.filter((id, _) => kept.streams.exists(_.id == id)))
|
|
121
|
+
val history = current.tapes.getOrElse(routed.stream.id, History.empty)
|
|
122
|
+
val next = history.accept(point, Conflict.first)
|
|
123
|
+
val tapes = current.tapes.filter((id, _) => kept.streams.exists(_.id == id)).updated(routed.stream.id, next)
|
|
124
|
+
(StreamState(pool, tapes, current.stored), RoutedPoint(routed.stream, next.rows != history.rows))
|
|
125
|
+
private[runtime] def overlaps(row: Json, from: Long, until: Long): Boolean =
|
|
126
|
+
val start = row.hcursor.get[String]("start_time").toOption.map(Instant.parse(_).toEpochMilli).getOrElse(0L)
|
|
127
|
+
val end = row.hcursor.get[String]("end_time").toOption.map(Instant.parse(_).toEpochMilli).getOrElse(0L)
|
|
128
|
+
start <= until && end >= from
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
package scada.
|
|
1
|
+
package scada.processing.runtime
|
|
2
2
|
|
|
3
3
|
import cats.effect.IO
|
|
4
|
-
import scada.
|
|
5
|
-
import scada.
|
|
6
|
-
import scada.
|
|
4
|
+
import scada.processing.core.*
|
|
5
|
+
import scada.processing.core.Segments as CoreSegments
|
|
6
|
+
import scada.processing.infra.checkpoint.PendingSegmentData
|
|
7
7
|
|
|
8
8
|
/**
|
|
9
9
|
* Completes one pending segment row in storage. Upsert carries empty
|
|
@@ -1,12 +1,13 @@
|
|
|
1
|
-
package scada.
|
|
1
|
+
package scada.processing.runtime
|
|
2
2
|
|
|
3
3
|
import cats.effect.IO
|
|
4
4
|
import cats.syntax.all.*
|
|
5
5
|
import io.circe.Json
|
|
6
6
|
import io.circe.parser.parse
|
|
7
7
|
import java.time.Instant
|
|
8
|
-
import scada.
|
|
9
|
-
import scada.
|
|
8
|
+
import scada.processing.core.*
|
|
9
|
+
import scada.processing.infra.config.AppConfig
|
|
10
|
+
import scada.processing.infra.stomp.{SegmentMessage, StompFrame, StompSender}
|
|
10
11
|
|
|
11
12
|
/**
|
|
12
13
|
* Publishes a committed local-history page to the segment exchange.
|
|
@@ -49,11 +50,42 @@ object HistoryBus:
|
|
|
49
50
|
|
|
50
51
|
/** Sends every committed row and stamps the writer epoch when one is supplied. */
|
|
51
52
|
def publish(sender: StompSender, destination: String, machine: MachineId, epoch: Option[Long])(rows: Vector[Json]): IO[Unit] =
|
|
52
|
-
rows.traverse_
|
|
53
|
-
|
|
54
|
-
"",
|
|
55
|
-
|
|
56
|
-
|
|
53
|
+
rows.traverse_ { row =>
|
|
54
|
+
val body = epoch.fold(message(machine, row))(n => stamped(machine, row, n))
|
|
55
|
+
val committed = body.deepMerge(Json.obj("committedOutputId" -> Json.fromString(TimelineWriter.identity(None, body))))
|
|
56
|
+
sender.send(StompFrame.send(destination, "", committed.noSpaces))
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Sends a committed page. A configured lease uses the holder generation and a non-holder sends nothing. */
|
|
60
|
+
private[runtime] def announce(sender: Option[StompSender], config: AppConfig, machine: MachineId, grant: Option[LeaseGrant] = None): Vector[io.circe.Json] => IO[Unit] =
|
|
61
|
+
WriterLease.publication(config.leaseUrl, grant, config.writerEpoch) match
|
|
62
|
+
case None => (_: Vector[io.circe.Json]) => IO.unit
|
|
63
|
+
case Some(epoch) =>
|
|
64
|
+
(sender, config.connectivity.rabbitmq.destinations.segments) match
|
|
65
|
+
case (Some(conn), Some(dest)) => HistoryBus.publish(conn, dest, machine, epoch)
|
|
66
|
+
case _ => (_: Vector[io.circe.Json]) => IO.unit
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Publishes committed history only after a real segment end is covered.
|
|
70
|
+
* A leader may publish when nothing has been replicated. A standby does not.
|
|
71
|
+
* A configured lease stamps its generation and a process that does not hold it does not publish.
|
|
72
|
+
* The same gate covers every configured machine.
|
|
73
|
+
*
|
|
74
|
+
* {{{
|
|
75
|
+
* HistoryBus.lead(sender, config, MachineId("machine-1"), 5L, Some(4L), Some(LeaseGrant(true, 7)))(rows)
|
|
76
|
+
* }}}
|
|
77
|
+
*/
|
|
78
|
+
private[runtime] def lead(
|
|
79
|
+
sender: Option[StompSender],
|
|
80
|
+
config: AppConfig,
|
|
81
|
+
machine: MachineId,
|
|
82
|
+
observationMs: Long,
|
|
83
|
+
segmentEndMs: Option[Long],
|
|
84
|
+
grant: Option[LeaseGrant] = None
|
|
85
|
+
): Vector[io.circe.Json] => IO[Unit] =
|
|
86
|
+
val leader = ObservationLead.leading(config.writerRole, config.leaseUrl)
|
|
87
|
+
if config.leaseHeld && ObservationLead.ready(observationMs, segmentEndMs, leader) then announce(sender, config, machine, grant)
|
|
88
|
+
else (_: Vector[io.circe.Json]) => IO.unit
|
|
57
89
|
|
|
58
90
|
private def required(cursor: io.circe.HCursor, key: String): String =
|
|
59
91
|
cursor.get[String](key).fold(error => throw IllegalArgumentException(s"History segment missing $key: ${error.getMessage}"), identity)
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
package scada.
|
|
1
|
+
package scada.processing.runtime
|
|
2
2
|
|
|
3
3
|
import cats.effect.IO
|
|
4
4
|
import io.circe.Json
|
|
@@ -6,9 +6,12 @@ import io.circe.parser.parse
|
|
|
6
6
|
import java.net.URI
|
|
7
7
|
import java.net.http.{HttpClient,HttpRequest,HttpResponse}
|
|
8
8
|
import java.time.Duration
|
|
9
|
-
import scada.
|
|
9
|
+
import scada.processing.infra.config.CheckpointApiConfig
|
|
10
10
|
import scala.concurrent.duration.*
|
|
11
11
|
|
|
12
|
+
final case class HistoryHttpError(path: String, status: Int, code: Option[String])
|
|
13
|
+
extends RuntimeException(s"history API ${path.takeWhile(_ != '?')} status $status${code.fold("")(value => s" ($value)")}")
|
|
14
|
+
|
|
12
15
|
/** Shared authenticated local history transport; failed requests never retire server work. */
|
|
13
16
|
final class HistoryClient(config: CheckpointApiConfig):
|
|
14
17
|
private val client=HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(config.timeoutSeconds.toLong)).build()
|
|
@@ -18,6 +21,10 @@ final class HistoryClient(config: CheckpointApiConfig):
|
|
|
18
21
|
config.token.foreach(token=>builder.header("Authorization",s"Bearer $token"))
|
|
19
22
|
val request=if method=="GET" then builder.GET().build() else builder.POST(HttpRequest.BodyPublishers.ofString(body.noSpaces)).build()
|
|
20
23
|
IO.blocking(client.send(request,HttpResponse.BodyHandlers.ofString())).flatMap: response =>
|
|
21
|
-
|
|
22
|
-
|
|
24
|
+
val decoded = parse(response.body())
|
|
25
|
+
if response.statusCode()/100!=2 then
|
|
26
|
+
val code = decoded.toOption.flatMap(json =>
|
|
27
|
+
json.hcursor.downField("error").get[String]("code").toOption.orElse(json.hcursor.get[String]("code").toOption))
|
|
28
|
+
IO.raiseError(HistoryHttpError(path, response.statusCode(), code))
|
|
29
|
+
else IO.fromEither(decoded.left.map(error=>RuntimeException(error.message)))
|
|
23
30
|
def retry[A](action: IO[A]): IO[A] = action.handleErrorWith(_=>IO.sleep(2.seconds) *> retry(action))
|
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
package scada.
|
|
1
|
+
package scada.processing.runtime
|
|
2
2
|
|
|
3
|
-
import cats.effect.IO
|
|
3
|
+
import cats.effect.{IO, Resource}
|
|
4
4
|
import cats.syntax.all.*
|
|
5
5
|
import fs2.Stream
|
|
6
6
|
import io.circe.Json
|
|
7
7
|
import org.typelevel.log4cats.Logger
|
|
8
8
|
import org.typelevel.log4cats.slf4j.Slf4jLogger
|
|
9
|
-
import scada.
|
|
10
|
-
import scada.
|
|
9
|
+
import scada.processing.infra.config.{AliasMapping, AppConfig, CheckpointApiConfig}
|
|
10
|
+
import scada.processing.infra.stomp.{ClassifyQueue, StompSender}
|
|
11
11
|
import scala.concurrent.duration.*
|
|
12
12
|
|
|
13
13
|
/**
|
|
@@ -19,66 +19,68 @@ import scala.concurrent.duration.*
|
|
|
19
19
|
* HistoryRun.gated(config, machine, aliases, sender, api)
|
|
20
20
|
* }}}
|
|
21
21
|
*/
|
|
22
|
-
final class HistoryRun(
|
|
22
|
+
final class HistoryRun(profile: RuntimeProfile, writer: Option[TimelineWriter],
|
|
23
|
+
observe: (String, Option[Long]) => Resource[IO, Unit],
|
|
24
|
+
decisions: (AppConfig, scada.processing.core.MachineConfig) => Stream[IO, Unit]):
|
|
23
25
|
private given Logger[IO] = Slf4jLogger.getLogger[IO]
|
|
24
26
|
|
|
25
27
|
/** Retries until this process is the sole classifier. */
|
|
26
|
-
def gated(config: AppConfig, machine: scada.
|
|
28
|
+
def gated(config: AppConfig, machine: scada.processing.core.MachineConfig, aliases: List[AliasMapping], sender: Option[StompSender], api: CheckpointApiConfig, observationMs: Long = 0L, segmentEndMs: Option[Long] = None): Stream[IO, Unit] =
|
|
27
29
|
if !config.leaseHeld then Stream.never[IO]
|
|
28
30
|
else
|
|
29
31
|
val leader = ObservationLead.leading(config.writerRole, config.leaseUrl)
|
|
30
32
|
config.leaseUrl match
|
|
31
33
|
case None if machine.mode.isDefined && !ObservationLead.ready(observationMs, segmentEndMs, leader) =>
|
|
32
34
|
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)
|
|
35
|
+
case None => follow(config, machine, aliases, sender, api, observationMs, segmentEndMs).concurrently(decisions(config, machine))
|
|
34
36
|
case Some(url) => once(url, config, machine, aliases, sender, api) ++ Stream.eval(IO.unit).flatMap(_ => gated(config, machine, aliases, sender, api, observationMs, segmentEndMs))
|
|
35
37
|
|
|
36
|
-
private def once(url: String, config: AppConfig, machine: scada.
|
|
38
|
+
private def once(url: String, config: AppConfig, machine: scada.processing.core.MachineConfig, aliases: List[AliasMapping], sender: Option[StompSender], api: CheckpointApiConfig): Stream[IO, Unit] =
|
|
37
39
|
Stream.resource(WriterLease.open(url, machine.id.raw)).flatMap: hold =>
|
|
38
40
|
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) =>
|
|
41
|
+
else Stream.resource(observe(machine.id.raw, hold.generation)) >> Stream.eval(hold.seed(machine.id.raw)).flatMap: (end, rows) =>
|
|
40
42
|
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
|
|
43
|
-
|
|
43
|
+
if machine.mode.isDefined then follow(config, machine, aliases, sender, api, end.getOrElse(0L), end, grant).concurrently(decisions(config, machine))
|
|
44
|
+
else
|
|
45
|
+
val database = hold.generation.map(token =>
|
|
46
|
+
WorkerDatabase(doobie.Transactor.fromConnection[IO](hold.connection, None), token))
|
|
47
|
+
amqp(config, machine, aliases, rows, end, grant, database)
|
|
44
48
|
|
|
45
|
-
private def follow(config: AppConfig, machine: scada.
|
|
46
|
-
if machine.mode.isEmpty then amqp(config, machine, aliases,
|
|
49
|
+
private def follow(config: AppConfig, machine: scada.processing.core.MachineConfig, aliases: List[AliasMapping], sender: Option[StompSender], api: CheckpointApiConfig, observationMs: Long, segmentEndMs: Option[Long], grant: Option[LeaseGrant] = None): Stream[IO, Unit] =
|
|
50
|
+
if machine.mode.isEmpty then amqp(config, machine, aliases, Vector.empty, segmentEndMs, grant)
|
|
47
51
|
else if !ObservationLead.ready(observationMs, segmentEndMs, ObservationLead.leading(config.writerRole, config.leaseUrl)) then
|
|
48
52
|
Stream.exec(Logger[IO].info(s"classifier waiting for telemetry on ${machine.id.raw}")) ++ Stream.sleep_[IO](5.seconds)
|
|
49
53
|
else custom(config, machine, aliases, sender, api, observationMs, segmentEndMs, grant)
|
|
50
54
|
|
|
51
|
-
private def custom(config: AppConfig, machine: scada.
|
|
52
|
-
val announce =
|
|
53
|
-
profile.history(machine, aliases, api, announce)
|
|
55
|
+
private def custom(config: AppConfig, machine: scada.processing.core.MachineConfig, aliases: List[AliasMapping], sender: Option[StompSender], api: CheckpointApiConfig, observationMs: Long, segmentEndMs: Option[Long], grant: Option[LeaseGrant] = None): Stream[IO, Unit] =
|
|
56
|
+
val announce = HistoryBus.lead(sender, config, machine.id, observationMs, segmentEndMs, grant)
|
|
57
|
+
profile.history(machine, aliases, api, announce, grant.filter(_.held).map(_.generation))
|
|
54
58
|
|
|
55
|
-
private def amqp(config: AppConfig, machine: scada.
|
|
59
|
+
private def amqp(config: AppConfig, machine: scada.processing.core.MachineConfig,
|
|
60
|
+
aliases: List[AliasMapping], seed: Vector[Json], segmentEndMs: Option[Long],
|
|
61
|
+
grant: Option[LeaseGrant], database: Option[WorkerDatabase] = None): Stream[IO, Unit] =
|
|
56
62
|
val leader = ObservationLead.leading(config.writerRole, config.leaseUrl)
|
|
57
|
-
val publish = runtime.historyAnnounce(sender, config, machine.id, grant)
|
|
58
63
|
val queue = s"scada.classify.${machine.id.raw}"
|
|
59
|
-
val input = ClassifyQueue(config.connectivity.rabbitmq, queue, aliases).
|
|
60
|
-
val
|
|
61
|
-
|
|
64
|
+
val input = ClassifyQueue(config.connectivity.rabbitmq, queue, aliases).subscribeDurable
|
|
65
|
+
val write = writer.getOrElse(throw IllegalStateException("Historical classification requires a timeline writer"))
|
|
66
|
+
val owner = grant.filter(_.held).map(_.generation)
|
|
67
|
+
val ports = ClassifyPorts(_ => IO.unit, (rows, historical) =>
|
|
68
|
+
ClassifyBus.publish(segmentEndMs, leader, historical)(rows): approved =>
|
|
69
|
+
approved.traverse_ { row =>
|
|
70
|
+
val message = if row.hcursor.get[String]("type").contains("split-family") then row else HistoryBus.message(machine.id, row)
|
|
71
|
+
write.applyMessage(machine.id.raw, message, TimelineWriter.identity(None, message), owner,
|
|
72
|
+
config.connectivity.rabbitmq.destinations.segments)
|
|
73
|
+
}
|
|
74
|
+
)
|
|
75
|
+
Stream.eval(Logger[IO].info(s"consuming AMQP classify queue $queue")) >> Stream.eval(ClassifyStreams.open(machine, seed, ports, segmentEndMs, database)).flatMap(_.consumeDurable(input))
|
|
62
76
|
|
|
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
77
|
object ClassifyBus:
|
|
71
|
-
def publish(
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
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)
|
|
78
|
+
def publish(segmentEndMs: Option[Long], leader: Boolean, historical: Boolean = false)(rows: Vector[Json])(
|
|
79
|
+
write: Vector[Json] => IO[Unit]
|
|
80
|
+
): IO[Unit] =
|
|
81
|
+
if historical || ObservationLead.ready(horizon(rows), segmentEndMs, leader) then write(rows)
|
|
82
|
+
else IO.unit
|
|
83
|
+
|
|
82
84
|
private def horizon(rows: Vector[Json]): Long =
|
|
83
85
|
val ends = rows.flatMap: row =>
|
|
84
86
|
row.hcursor.get[String]("end_time").toOption.map(java.time.Instant.parse(_).toEpochMilli).toVector ++
|
|
@@ -1,18 +1,23 @@
|
|
|
1
|
-
package scada.
|
|
1
|
+
package scada.processing.runtime
|
|
2
2
|
|
|
3
3
|
import cats.effect.{IO, Ref}
|
|
4
4
|
import cats.syntax.all.*
|
|
5
5
|
import fs2.Stream
|
|
6
|
-
import io.circe.Json
|
|
6
|
+
import io.circe.{Json, Printer}
|
|
7
7
|
import io.circe.parser.parse
|
|
8
|
+
import io.circe.syntax.*
|
|
8
9
|
import io.yarkivaev.temporal.{LocalStreams, Observation, Processing, Work, Worker}
|
|
9
10
|
import java.net.URLEncoder
|
|
10
11
|
import java.nio.charset.StandardCharsets
|
|
12
|
+
import java.security.MessageDigest
|
|
11
13
|
import java.time.Instant
|
|
12
|
-
import
|
|
13
|
-
import scada.
|
|
14
|
-
import
|
|
15
|
-
import scada.
|
|
14
|
+
import java.util.HexFormat
|
|
15
|
+
import scada.stream.replay.{Replay, ReplayFailure, ReplayInput, ReplayManifest, ReplayRange, ReplaySeed}
|
|
16
|
+
import io.yarkivaev.streamworker.{ProcessingError, Processor, StepResult}
|
|
17
|
+
import scada.processing.core.*
|
|
18
|
+
import scada.processing.core.segmentation.Timeline
|
|
19
|
+
import scada.processing.core.segmentation.Timeline.{Boundary, Event, Interval, Output}
|
|
20
|
+
import scada.processing.infra.config.{AliasMapping, CheckpointApiConfig}
|
|
16
21
|
import scala.concurrent.duration.*
|
|
17
22
|
|
|
18
23
|
final case class HistoryRange(from: Long, until: Long)
|
|
@@ -43,28 +48,94 @@ object LocalHistory:
|
|
|
43
48
|
|
|
44
49
|
/** Finite event-time classification: never inject wall-clock silence into past data. */
|
|
45
50
|
def classify(machine: MachineConfig, points: Vector[Observation], seed: Option[HistorySeed] = None, continuity: Vector[HistoryRange] = Vector.empty): Vector[HistorySegment] =
|
|
46
|
-
val
|
|
47
|
-
val
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
51
|
+
val classifier = Classification(machine, continuity)
|
|
52
|
+
val (terminal, closed) = grouped(points).foldLeft((classifier.initial(seed), Vector.empty[HistorySegment])):
|
|
53
|
+
case ((state, completed), sample) =>
|
|
54
|
+
val next = classifier.advance(state, sample)
|
|
55
|
+
(next.state, completed ++ next.outputs)
|
|
56
|
+
closed ++ terminal.segment.map(segment)
|
|
57
|
+
|
|
58
|
+
private final case class Sample(time: Long, values: Map[String, Double])
|
|
59
|
+
private final case class ClassificationState(
|
|
60
|
+
time: Option[Long], parameters: Map[String, (Long, Double)], segment: Option[Interval[Long]]
|
|
61
|
+
)
|
|
62
|
+
private[runtime] final case class Replayed(segments: Vector[HistorySegment], state: Option[HistoryState])
|
|
63
|
+
|
|
64
|
+
private def segment(row: Interval[Long]): HistorySegment = HistorySegment(row.name, row.start, row.end)
|
|
65
|
+
|
|
66
|
+
private def grouped(points: Vector[Observation]): Vector[Sample] =
|
|
67
|
+
points.groupBy(_.time).toVector.sortBy(_._1).map: (time, group) =>
|
|
68
|
+
Sample(time, group.map(p => p.channel -> p.value).toMap)
|
|
69
|
+
|
|
70
|
+
private final class Classification(machine: MachineConfig, continuity: Vector[HistoryRange])
|
|
71
|
+
extends Processor[Unit, ClassificationState, Sample, HistorySegment]:
|
|
72
|
+
private val classify = Timeline.classifier(machine.segments)
|
|
73
|
+
private val gap = machine.window.toLong * 2000
|
|
74
|
+
|
|
75
|
+
def initial(seed: Option[HistorySeed]): ClassificationState =
|
|
76
|
+
val carried = seed.flatMap: value =>
|
|
77
|
+
val stored = value.segment.filter(_.start <= value.time)
|
|
78
|
+
val evaluated = classify(Params(value.values)) match
|
|
79
|
+
case Some(name) => Some(stored.filter(_.name == name).getOrElse(HistorySegment(name, value.time, value.time)))
|
|
80
|
+
case None => stored
|
|
81
|
+
evaluated.map(row => Interval(row.name, row.start, row.end))
|
|
82
|
+
val parameters = seed.fold(Map.empty[String, (Long, Double)])(value => value.values.map((key, reading) => key -> (value.time, reading)))
|
|
83
|
+
ClassificationState(seed.map(_.time), parameters, carried)
|
|
84
|
+
|
|
85
|
+
def advance(state: ClassificationState, sample: Sample): StepResult[ClassificationState, HistorySegment] =
|
|
86
|
+
val continuous = state.time.exists(connected(_, sample.time, gap, continuity))
|
|
87
|
+
val parameters = (if continuous then state.parameters else Map.empty) ++
|
|
88
|
+
sample.values.map((key, value) => key -> (sample.time, value))
|
|
89
|
+
val name = classify(Params(parameters.map((key, value) => key -> value._2)))
|
|
90
|
+
.orElse(if continuous then state.segment.map(_.name) else None)
|
|
91
|
+
val next = ClassificationState(Some(sample.time), parameters, state.segment)
|
|
92
|
+
name.fold(StepResult(next, Vector.empty[HistorySegment])): classified =>
|
|
93
|
+
val result = Timeline.step(Boundary.Observed, state.segment, Event.Sample(sample.time, classified, continuous))
|
|
94
|
+
StepResult(next.copy(segment = result.open), result.outputs.collect { case Output.Closed(row) => segment(row) })
|
|
95
|
+
|
|
96
|
+
override def step(config: Unit, state: ClassificationState, sample: Sample)
|
|
97
|
+
: Either[ProcessingError, StepResult[ClassificationState, HistorySegment]] = Right(advance(state, sample))
|
|
98
|
+
|
|
99
|
+
private[runtime] def replay(
|
|
100
|
+
machine: MachineConfig, points: Vector[Observation], baseRevision: String, runId: String,
|
|
101
|
+
seed: Option[HistorySeed] = None, continuity: Vector[HistoryRange] = Vector.empty
|
|
102
|
+
): IO[Replayed] = IO.defer:
|
|
103
|
+
val classifier = Classification(machine, continuity)
|
|
104
|
+
val initial = classifier.initial(seed)
|
|
105
|
+
val samples = grouped(points)
|
|
106
|
+
def values(readings: Map[String, Double]): Json =
|
|
107
|
+
Json.obj(readings.toVector.map((key, value) => key -> java.lang.Double.doubleToRawLongBits(value).asJson)*)
|
|
108
|
+
val input = ReplayInput(digest(Json.fromValues(samples.map(sample => Json.arr(sample.time.asJson, values(sample.values))))), samples)
|
|
109
|
+
val seedId = digest(Json.fromValues(seed.toVector.map: value =>
|
|
110
|
+
val interval = value.segment.map(row => Json.arr(row.name.asJson, row.start.asJson, row.end.asJson))
|
|
111
|
+
Json.arr(value.time.asJson, values(value.values), interval.asJson)
|
|
112
|
+
))
|
|
113
|
+
val rules = machine.segments.map(rule => Json.arr(rule.name.asJson, rule.condition.toString.asJson))
|
|
114
|
+
val ranges = continuity.map(range => Json.arr(range.from.asJson, range.until.asJson))
|
|
115
|
+
val rulesVersion = digest(Json.arr("observed-v1".asJson, machine.window.asJson, rules.asJson, ranges.asJson))
|
|
116
|
+
val timeline = machine.id.raw
|
|
117
|
+
val start = ReplaySeed(seedId, timeline, rulesVersion, input.id, 0, initial)
|
|
118
|
+
val manifest = ReplayManifest(timeline, ReplayRange(0, samples.size), rulesVersion, input.id, seedId, baseRevision, runId)
|
|
119
|
+
def failure(problem: ReplayFailure) = IllegalStateException(s"History page replay failed: $problem")
|
|
120
|
+
IO.fromEither(Replay.plan(manifest, input, start).leftMap(failure)).flatMap: plan =>
|
|
121
|
+
Replay.run(plan, (), classifier).flatMap(result => IO.fromEither(result.leftMap(failure))).map: result =>
|
|
122
|
+
val terminal = result.terminalState
|
|
123
|
+
val tail = terminal.segment.map(segment)
|
|
124
|
+
val state = samples.lastOption.map(last => HistoryState(last.time, terminal.parameters, tail))
|
|
125
|
+
Replayed(result.outputs.map(_.value) ++ tail, state)
|
|
126
|
+
|
|
127
|
+
private def digest(value: Json): String =
|
|
128
|
+
val text = Printer.noSpaces.copy(sortKeys = true).print(value)
|
|
129
|
+
HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(text.getBytes(StandardCharsets.UTF_8)))
|
|
130
|
+
|
|
131
|
+
private[runtime] def commitFence(machine: MachineId, workId: String, token: String, generation: Option[Long]): Json =
|
|
132
|
+
val outputId = digest(Json.arr(machine.raw.asJson, workId.asJson, token.asJson))
|
|
133
|
+
val fields = ("outputId" -> outputId.asJson) :: generation.toList.map(current => "generation" -> current.asJson)
|
|
134
|
+
Json.obj("fence" -> Json.obj(fields*))
|
|
135
|
+
|
|
136
|
+
private[runtime] def contextRevision(context: Json): IO[String] =
|
|
137
|
+
IO.fromOption(context.hcursor.get[String]("revision").toOption.filter(_.nonEmpty))(
|
|
138
|
+
IllegalStateException("History context revision required"))
|
|
68
139
|
|
|
69
140
|
def sources(context: Json): Vector[Json] =
|
|
70
141
|
val current = context.hcursor.get[Vector[Json]]("segments").getOrElse(Vector.empty)
|
|
@@ -177,7 +248,12 @@ object LocalHistory:
|
|
|
177
248
|
"properties" -> LocalHistory.metadata(inherited,"properties",Json.obj(tagged.properties.toVector.map((k,v) => k -> Json.fromString(v))*))).deepMerge(proof.fold(Json.obj())(owner => Json.obj("preserveSuffix" -> owner)))
|
|
178
249
|
|
|
179
250
|
/** Durable HTTP work queue is local to the receiving edge. Failed requests retry without acknowledging input. */
|
|
180
|
-
final class LocalHistory(
|
|
251
|
+
final class LocalHistory(
|
|
252
|
+
config: CheckpointApiConfig,
|
|
253
|
+
machine: MachineConfig,
|
|
254
|
+
announce: Vector[Json] => IO[Unit] = _ => IO.unit,
|
|
255
|
+
generation: Option[Long] = None
|
|
256
|
+
):
|
|
181
257
|
private val transport=HistoryClient(config)
|
|
182
258
|
import transport.{request,retry}
|
|
183
259
|
private val encoded = URLEncoder.encode(machine.id.raw,StandardCharsets.UTF_8)
|
|
@@ -208,12 +284,12 @@ final class LocalHistory(config: CheckpointApiConfig, machine: MachineConfig, an
|
|
|
208
284
|
// Cursors are a bounded cache; receiver work remains durable when a cursor is evicted.
|
|
209
285
|
val kept = routed.state.copy(streams = routed.state.streams.takeRight(64))
|
|
210
286
|
(HistoryPool(kept,previous.states.filter((id,_) => kept.streams.exists(_.id == id))),routed.work.copy(from = from,until = until))
|
|
211
|
-
committed <- Ref.of[IO,Boolean](false)
|
|
212
287
|
calculated <- Ref.of[IO,Option[HistoryState]](None)
|
|
213
288
|
snapshot <- Ref.of[IO,Json](Json.Null)
|
|
214
289
|
ports = new Processing[IO,HistorySegment]:
|
|
215
290
|
def context(work: Work): IO[Option[Vector[Observation]]] =
|
|
216
|
-
|
|
291
|
+
val claim = s"&workId=${URLEncoder.encode(id,StandardCharsets.UTF_8)}&workToken=${URLEncoder.encode(token,StandardCharsets.UTF_8)}"
|
|
292
|
+
request("GET",s"/v1/history/context?machine=$encoded&from=$from&until=$until&paddingMs=${machine.window.toLong*2000}$claim" + raw.hcursor.get[Long]("cursor").toOption.fold("")(value => s"&cursor=$value") + raw.hcursor.get[Long]("end").toOption.fold("")(value => s"&end=$value")).flatTap(snapshot.set).flatMap: response =>
|
|
217
293
|
if !response.hcursor.get[Boolean]("available").getOrElse(false) then IO.pure(None)
|
|
218
294
|
else IO.fromEither(response.hcursor.get[Vector[Json]]("items").flatMap(_.traverse: item =>
|
|
219
295
|
val p = item.hcursor
|
|
@@ -242,14 +318,24 @@ final class LocalHistory(config: CheckpointApiConfig, machine: MachineConfig, an
|
|
|
242
318
|
from <- row.hcursor.get[Long]("from").toOption
|
|
243
319
|
until <- row.hcursor.get[Long]("until").toOption
|
|
244
320
|
yield HistoryRange(from,until)
|
|
245
|
-
|
|
246
|
-
|
|
321
|
+
LocalHistory.contextRevision(context).flatMap: revision =>
|
|
322
|
+
LocalHistory.replay(machine, points, revision, id, seed, continuity)
|
|
323
|
+
.flatTap(result => calculated.set(result.state)).map(_.segments)
|
|
247
324
|
def commit(work: Work, result: Vector[HistorySegment]): IO[Unit] =
|
|
248
325
|
snapshot.get.flatMap: context =>
|
|
249
326
|
val rows = LocalHistory.commitRows(machine,result,context,raw.hcursor.get[Long]("cursor").toOption.isDefined)
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
327
|
+
val claim = context.hcursor.downField("context").focus.getOrElse(Json.obj()).deepMerge(Json.obj(
|
|
328
|
+
"nativeTailMode" -> Json.fromString(LocalHistory.nativeTailProtocol),
|
|
329
|
+
"revision" -> context.hcursor.downField("revision").focus.getOrElse(Json.Null),
|
|
330
|
+
"workToken" -> Json.fromString(token)
|
|
331
|
+
)).deepMerge(LocalHistory.commitFence(machine.id, id, token, generation))
|
|
332
|
+
val payload = Json.obj("machine" -> Json.fromString(machine.id.raw), "workId" -> Json.fromString(id),
|
|
333
|
+
"segments" -> Json.arr(rows*), "context" -> claim)
|
|
334
|
+
request("POST", "/v1/history/commit", payload).flatMap: response =>
|
|
335
|
+
if response.hcursor.get[Boolean]("applied").contains(true) then announce(rows)
|
|
336
|
+
else calculated.set(None)
|
|
337
|
+
// The receiver owns work retirement. Unavailable context yields no verified proposal.
|
|
338
|
+
def acknowledge(work: Work): IO[Unit] = IO.unit
|
|
253
339
|
_ <- Worker(ports).run(routed).guarantee(pool.update(p => p.copy(cursors = p.cursors.acknowledge(routed.id))))
|
|
254
340
|
result <- calculated.get
|
|
255
341
|
_ <- pool.update: previous =>
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
package scada.
|
|
1
|
+
package scada.processing.runtime
|
|
2
2
|
|
|
3
|
-
import scada.
|
|
4
|
-
import scada.
|
|
5
|
-
import scada.
|
|
3
|
+
import scada.processing.core.MachineId
|
|
4
|
+
import scada.processing.infra.config.AppConfig
|
|
5
|
+
import scada.processing.infra.checkpoint.PendingSegmentData
|
|
6
6
|
|
|
7
7
|
/**
|
|
8
8
|
* Orphan pending segment rows left in the checkpoint by repeated
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
package scada.
|
|
1
|
+
package scada.processing.runtime
|
|
2
2
|
|
|
3
3
|
import cats.effect.IO
|
|
4
4
|
import org.typelevel.log4cats.Logger
|
|
5
5
|
import org.typelevel.log4cats.slf4j.Slf4jLogger
|
|
6
|
-
import scada.
|
|
7
|
-
import scada.
|
|
6
|
+
import scada.processing.core.{MachineConfig, SegmentCursor}
|
|
7
|
+
import scada.processing.infra.checkpoint.Checkpoint
|
|
8
8
|
|
|
9
9
|
/**
|
|
10
10
|
* Resolves the pending open segment cursor for one machine from
|