@yarkivaev/scada 2.7.0 → 2.7.1
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/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 +1 -1
- 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/supervisor-engine/src/main/scala/scada/stream/worker/OutputScope.scala +13 -0
- package/supervisor-engine/src/main/scala/scada/stream/worker/StreamWorker.scala +17 -1
- package/supervisor-engine/src/main/scala/scada/stream/worker/postgres/WorkerDatabase.scala +7 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/ReadingWorker.scala +77 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Segmentation.scala +24 -13
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Segments.scala +2 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/state/CheckpointSegments.scala +2 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/ClassifyQueue.scala +2 -2
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompReadings.scala +0 -1
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompSegments.scala +17 -10
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ClassifyStreams.scala +57 -20
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/EngineApp.scala +6 -2
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/HistoryBus.scala +37 -5
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/HistoryClient.scala +9 -2
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/HistoryRun.scala +28 -30
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/LocalHistory.scala +117 -31
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/{SupervisorRuntime.scala → ProcessingApplication.scala} +101 -98
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/RuntimeProfile.scala +5 -6
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/TimelineWriter.scala +81 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/WriterLease.scala +24 -5
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Supervisor.scala +0 -66
|
@@ -3,12 +3,17 @@ package scada.supervisor.runtime
|
|
|
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
|
|
14
|
+
import java.util.HexFormat
|
|
15
|
+
import scada.stream.replay.{Replay, ReplayFailure, ReplayInput, ReplayManifest, ReplayRange, ReplaySeed}
|
|
16
|
+
import scada.stream.worker.{ProcessingError, Processor, StepResult}
|
|
12
17
|
import scada.supervisor.core.*
|
|
13
18
|
import scada.supervisor.core.segmentation.Timeline
|
|
14
19
|
import scada.supervisor.core.segmentation.Timeline.{Boundary, Event, Interval, Output}
|
|
@@ -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,9 +1,11 @@
|
|
|
1
1
|
package scada.supervisor.runtime
|
|
2
2
|
|
|
3
|
-
import cats.effect.{ExitCode, IO,
|
|
3
|
+
import cats.effect.{ExitCode, IO, Ref, Resource}
|
|
4
4
|
import cats.effect.std.Semaphore
|
|
5
5
|
import cats.syntax.all.*
|
|
6
6
|
import fs2.Stream
|
|
7
|
+
import scada.stream.worker.OutputScope
|
|
8
|
+
import scada.stream.worker.postgres.WorkerDatabase
|
|
7
9
|
import org.typelevel.log4cats.Logger
|
|
8
10
|
import org.typelevel.log4cats.slf4j.Slf4jLogger
|
|
9
11
|
import scada.supervisor.core.{
|
|
@@ -13,7 +15,7 @@ import scada.supervisor.core.{
|
|
|
13
15
|
Reading,
|
|
14
16
|
Segmentation,
|
|
15
17
|
Segments as CoreSegments,
|
|
16
|
-
|
|
18
|
+
ReadingWorker,
|
|
17
19
|
TagDef,
|
|
18
20
|
TaggedSegment,
|
|
19
21
|
Timestamp
|
|
@@ -26,27 +28,8 @@ import scada.supervisor.infra.stomp.{DurableStomp, StompConnection, StompDecisio
|
|
|
26
28
|
import scala.collection.immutable.SortedMap
|
|
27
29
|
import scala.concurrent.duration.*
|
|
28
30
|
|
|
29
|
-
/**
|
|
30
|
-
|
|
31
|
-
* module graph, opens the startup ceremony (checkpoint API replay, live
|
|
32
|
-
* MQTT, STOMP decisions) and runs every per-machine supervisor loop
|
|
33
|
-
* concurrently with the decision consumer until killed.
|
|
34
|
-
*
|
|
35
|
-
* `F` is pinned to `IO` here; `core` stays tagless.
|
|
36
|
-
*
|
|
37
|
-
* Decorator order:
|
|
38
|
-
* {{{
|
|
39
|
-
* StompSegments(CheckpointSegments(StateSegments(...), checkpoint), connection, dest)
|
|
40
|
-
* }}}
|
|
41
|
-
* Segment persistence/publish remains the durable boundary. Replay
|
|
42
|
-
* cursor is derived from supervisor-sink checkpoint API during startup.
|
|
43
|
-
*
|
|
44
|
-
* {{{
|
|
45
|
-
* sbt "runMain scada.supervisor.runtime.EngineApp config/application.conf"
|
|
46
|
-
* }}}
|
|
47
|
-
*/
|
|
48
|
-
open class SupervisorRuntime(profile: RuntimeProfile) extends IOApp:
|
|
49
|
-
|
|
31
|
+
/** Wires broker inputs, task ownership, processing jobs and timeline output adapters. */
|
|
32
|
+
final class ProcessingApplication(profile: RuntimeProfile):
|
|
50
33
|
private val defaultPath: String = "config/application.conf"
|
|
51
34
|
|
|
52
35
|
private given Logger[IO] = Slf4jLogger.getLogger[IO]
|
|
@@ -55,40 +38,53 @@ open class SupervisorRuntime(profile: RuntimeProfile) extends IOApp:
|
|
|
55
38
|
args match
|
|
56
39
|
case "--capabilities" :: Nil => IO.println(io.circe.Json.obj("role" -> io.circe.Json.fromString("supervisor"),
|
|
57
40
|
"historyProtocols" -> io.circe.Json.arr(profile.historyProtocols.map(io.circe.Json.fromString)*)).noSpaces).as(ExitCode.Success)
|
|
58
|
-
case "--check" :: path :: Nil =>
|
|
41
|
+
case "--check" :: path :: Nil => load(path).as(ExitCode.Success)
|
|
59
42
|
case "--check" :: _ => IO.raiseError(IllegalArgumentException("Usage: supervisor --check CONFIG"))
|
|
60
|
-
case _ =>
|
|
43
|
+
case _ => load(args.headOption.getOrElse(defaultPath)).flatMap(live).as(ExitCode.Success)
|
|
44
|
+
|
|
45
|
+
private def load(path: String): IO[AppConfig] =
|
|
46
|
+
ConfigLoad(profile = profile.configuration).load(path).flatMap: config =>
|
|
47
|
+
val outputEnabled = config.connectivity.rabbitmq.destinations.segments.isDefined
|
|
48
|
+
IO.raiseWhen(outputEnabled && config.connectivity.checkpointApi.isEmpty)(
|
|
49
|
+
IllegalArgumentException("A timeline sink checkpoint API is required when segment output is enabled")
|
|
50
|
+
).as(config)
|
|
61
51
|
|
|
62
52
|
private def live(config: AppConfig): IO[Unit] =
|
|
63
53
|
Logger[IO].info(s"supervisor starting: machines=${config.machines.size} stomp=${config.connectivity.rabbitmq.destinations.segments.isDefined} checkpointApi=${config.connectivity.checkpointApi.isDefined}") *>
|
|
64
54
|
Ref.of[IO, Map[MachineId, SortedMap[Timestamp, TaggedSegment]]](Map.empty).flatMap: segmentsRef =>
|
|
65
|
-
|
|
55
|
+
(for
|
|
56
|
+
owners <- Resource.eval(Ref.of[IO, Map[String, Long]](Map.empty))
|
|
57
|
+
outputs <- Resource.eval(OutputScope.create)
|
|
58
|
+
publish <- resources(config)
|
|
59
|
+
writer <- Resource.eval(timelineWriter(config, owners, outputs, publish))
|
|
60
|
+
yield (owners, outputs, publish, writer)).use: (owners, outputs, publishConn, writer) =>
|
|
66
61
|
val checkpoint = checkpointWithDecorators(config)
|
|
67
62
|
val base = StateSegments[IO](segmentsRef, profile.statePolicy)
|
|
68
63
|
val withFallback = checkpoint.fold(base)(cp => CheckpointSegments(base, cp))
|
|
69
|
-
val decorated = decorate(config,
|
|
70
|
-
profile.decorate(config, decorated).flatMap(runStreams(config, _, checkpoint, base, publishConn))
|
|
64
|
+
val decorated = decorate(config, writer, withFallback)
|
|
65
|
+
profile.decorate(config, decorated).flatMap(runStreams(config, _, checkpoint, base, publishConn, writer, owners, outputs))
|
|
71
66
|
|
|
72
|
-
private def runStreams(config: AppConfig, segments: CoreSegments[IO], checkpoint: Option[Checkpoint], base: StateSegments[IO], publish: Option[StompSender]
|
|
67
|
+
private def runStreams(config: AppConfig, segments: CoreSegments[IO], checkpoint: Option[Checkpoint], base: StateSegments[IO], publish: Option[StompSender], writer: Option[TimelineWriter],
|
|
68
|
+
owners: Ref[IO, Map[String, Long]], outputs: OutputScope): IO[Unit] =
|
|
73
69
|
|
|
74
|
-
val
|
|
70
|
+
val worker = ReadingWorker(Segmentation[IO](profile.classifyReading), profile.tagging, segments, config.cyclePhases, outputs = Some(outputs))
|
|
75
71
|
val decisionSegments = checkpoint.filter(_ => config.localHistory).fold(segments)(cp =>
|
|
76
72
|
CheckpointSegments(segments,cp,preferCheckpoint=true,refreshCache=Some(base.refresh)))
|
|
77
73
|
val stall = config.connectivity.checkpointApi.map(api => api.timeoutSeconds.seconds).getOrElse(60.seconds)
|
|
78
74
|
val seeding = checkpoint.map(Seeding(_, config.seeding.capacity, stall))
|
|
79
75
|
val protectedMachines = Orphans.protectedMachines(config) ++ config.machines.filter(_.mode.isDefined).map(_.id)
|
|
80
|
-
val canCloseOrphans = config.leaseHeld && config.machines.exists(machine => !protectedMachines(machine.id))
|
|
76
|
+
val canCloseOrphans = config.leaseUrl.isEmpty && config.leaseHeld && config.machines.exists(machine => !protectedMachines(machine.id))
|
|
81
77
|
Logger[IO].info("supervisor ready, closing orphaned pending segments") *>
|
|
82
78
|
closeWhenHeld(canCloseOrphans, checkpoint, segments, protectedMachines) *>
|
|
83
79
|
Logger[IO].info("supervisor ready, entering stream loop") *>
|
|
84
80
|
(if config.machines.isEmpty then IO.never
|
|
85
|
-
else streams(config,
|
|
81
|
+
else streams(config, worker, decisionSegments, seeding, checkpoint, publish, segments, writer, owners, outputs).compile.drain) *>
|
|
86
82
|
Logger[IO].info("supervisor stream loop exited")
|
|
87
83
|
/**
|
|
88
84
|
* Closes orphan pending rows only while this process holds the writer lease.
|
|
89
85
|
*
|
|
90
86
|
* {{{
|
|
91
|
-
*
|
|
87
|
+
* ProcessingApplication.closeWhenHeld(false, checkpoint, segments, Set.empty)
|
|
92
88
|
* }}}
|
|
93
89
|
*/
|
|
94
90
|
private[runtime] def closeWhenHeld(held: Boolean, checkpoint: Option[Checkpoint], segments: CoreSegments[IO], historical: Set[MachineId]): IO[Unit] =
|
|
@@ -137,65 +133,50 @@ open class SupervisorRuntime(profile: RuntimeProfile) extends IOApp:
|
|
|
137
133
|
def send(frame: scada.supervisor.infra.stomp.StompFrame): IO[Unit] = lock.permit.use(_ => durable.send(frame))
|
|
138
134
|
)
|
|
139
135
|
|
|
136
|
+
private def timelineWriter(config: AppConfig, owners: Ref[IO, Map[String, Long]], outputs: OutputScope,
|
|
137
|
+
publish: Option[StompSender]): IO[Option[TimelineWriter]] =
|
|
138
|
+
config.connectivity.checkpointApi.traverse: api =>
|
|
139
|
+
val owner = (machine: String) => owners.get.flatMap: current =>
|
|
140
|
+
val grant = current.get(machine)
|
|
141
|
+
IO.raiseWhen(config.leaseUrl.isDefined && grant.isEmpty)(
|
|
142
|
+
IllegalStateException(s"No active timeline writer for $machine")).as(grant)
|
|
143
|
+
TimelineWriter.create(HistoryClient(api), owner, outputs, publish)
|
|
144
|
+
|
|
145
|
+
private def track(owners: Ref[IO, Map[String, Long]])(machine: String, generation: Option[Long]): Resource[IO, Unit] =
|
|
146
|
+
generation.fold(Resource.unit[IO])(value => Resource.make(owners.update(_.updated(machine, value)))(_ =>
|
|
147
|
+
owners.update(current => if current.get(machine).contains(value) then current.removed(machine) else current)))
|
|
148
|
+
|
|
140
149
|
private def decorate(
|
|
141
150
|
config: AppConfig,
|
|
142
|
-
|
|
151
|
+
writer: Option[TimelineWriter],
|
|
143
152
|
base: CoreSegments[IO]
|
|
144
153
|
): CoreSegments[IO] =
|
|
145
|
-
(
|
|
146
|
-
case (Some(
|
|
154
|
+
(writer, config.connectivity.rabbitmq.destinations.segments) match
|
|
155
|
+
case (Some(sink), Some(dest)) => StompSegments(base, sink, dest, policy = profile.wirePolicy)
|
|
147
156
|
case _ => base
|
|
148
157
|
|
|
149
158
|
private def streams(
|
|
150
159
|
config: AppConfig,
|
|
151
|
-
|
|
160
|
+
worker: ReadingWorker,
|
|
152
161
|
segments: CoreSegments[IO],
|
|
153
162
|
seeding: Option[Seeding],
|
|
154
163
|
checkpoint: Option[Checkpoint],
|
|
155
164
|
publish: Option[StompSender],
|
|
156
|
-
profileSegments: CoreSegments[IO]
|
|
165
|
+
profileSegments: CoreSegments[IO],
|
|
166
|
+
writer: Option[TimelineWriter],
|
|
167
|
+
owners: Ref[IO, Map[String, Long]],
|
|
168
|
+
outputs: OutputScope
|
|
157
169
|
): Stream[IO, Unit] =
|
|
158
|
-
Stream(machineStreams(config,
|
|
159
|
-
|
|
160
|
-
.concurrently(
|
|
161
|
-
|
|
162
|
-
/** Sends a committed page. A configured lease uses the holder generation and a non-holder sends nothing. */
|
|
163
|
-
private[runtime] def historyAnnounce(sender: Option[StompSender], config: AppConfig, machine: MachineId, grant: Option[LeaseGrant] = None): Vector[io.circe.Json] => IO[Unit] =
|
|
164
|
-
WriterLease.publication(config.leaseUrl, grant, config.writerEpoch) match
|
|
165
|
-
case None => (_: Vector[io.circe.Json]) => IO.unit
|
|
166
|
-
case Some(epoch) =>
|
|
167
|
-
(sender, config.connectivity.rabbitmq.destinations.segments) match
|
|
168
|
-
case (Some(conn), Some(dest)) => HistoryBus.publish(conn, dest, machine, epoch)
|
|
169
|
-
case _ => (_: Vector[io.circe.Json]) => IO.unit
|
|
170
|
-
|
|
171
|
-
/**
|
|
172
|
-
* Publishes committed history only after a real segment end is covered.
|
|
173
|
-
* A leader may publish when nothing has been replicated. A standby does not.
|
|
174
|
-
* A configured lease stamps its generation and a process that does not hold it does not publish.
|
|
175
|
-
* The same gate covers every configured machine.
|
|
176
|
-
*
|
|
177
|
-
* {{{
|
|
178
|
-
* SupervisorRuntime.leadAnnounce(sender, config, MachineId("machine-1"), 5L, Some(4L), Some(LeaseGrant(true, 7)))(rows)
|
|
179
|
-
* }}}
|
|
180
|
-
*/
|
|
181
|
-
private[runtime] def leadAnnounce(
|
|
182
|
-
sender: Option[StompSender],
|
|
183
|
-
config: AppConfig,
|
|
184
|
-
machine: MachineId,
|
|
185
|
-
observationMs: Long,
|
|
186
|
-
segmentEndMs: Option[Long],
|
|
187
|
-
grant: Option[LeaseGrant] = None
|
|
188
|
-
): Vector[io.circe.Json] => IO[Unit] =
|
|
189
|
-
val leader = ObservationLead.leading(config.writerRole, config.leaseUrl)
|
|
190
|
-
if config.leaseHeld && ObservationLead.ready(observationMs, segmentEndMs, leader) then historyAnnounce(sender, config, machine, grant)
|
|
191
|
-
else (_: Vector[io.circe.Json]) => IO.unit
|
|
170
|
+
Stream(machineStreams(config, worker, seeding, checkpoint, publish, profileSegments = Some(profileSegments), writer = writer, observe = track(owners), outputs = Some(outputs),
|
|
171
|
+
decisionSegments = Some(segments))*).parJoinUnbounded
|
|
172
|
+
.concurrently(decisionStream(config, segments, owners))
|
|
192
173
|
|
|
193
174
|
/**
|
|
194
175
|
* Sources can replay checkpoint readings
|
|
195
176
|
* after the cursor, then continue with the live subscription.
|
|
196
177
|
*
|
|
197
178
|
* {{{
|
|
198
|
-
*
|
|
179
|
+
* ProcessingApplication.sourced(machine, aliases, live, seeding)
|
|
199
180
|
* }}}
|
|
200
181
|
*/
|
|
201
182
|
private[runtime] def sourced(
|
|
@@ -204,17 +185,20 @@ open class SupervisorRuntime(profile: RuntimeProfile) extends IOApp:
|
|
|
204
185
|
live: Stream[IO, Reading],
|
|
205
186
|
seeding: Option[Seeding]
|
|
206
187
|
): Stream[IO, Reading] =
|
|
207
|
-
|
|
208
|
-
seeding.fold(input)(_.seed(machine, profile.replayAliases(machine, aliases), input))
|
|
188
|
+
seeding.fold(live)(_.seed(machine, aliases, live))
|
|
209
189
|
|
|
210
190
|
/** Holds one classifier per machine. The loser waits and tries the same lock again. */
|
|
211
|
-
private def lease(url: Option[String], machine: String, leader: Boolean,
|
|
191
|
+
private def lease(url: Option[String], machine: String, leader: Boolean,
|
|
192
|
+
observe: (String, Option[Long]) => Resource[IO, Unit], body: Option[WorkerDatabase] => Stream[IO, Unit]): Stream[IO, Unit] =
|
|
212
193
|
url match
|
|
213
|
-
case None => body
|
|
194
|
+
case None => body(None)
|
|
214
195
|
case Some(value) =>
|
|
215
196
|
val attempt = Stream.resource(WriterLease.open(value, machine)).flatMap: hold =>
|
|
216
197
|
Stream.eval(if hold.held && !leader then hold.ready(machine, false).map(_.isDefined) else IO.pure(false)).flatMap: caught =>
|
|
217
|
-
if WriterGate.admit(hold.held, leader, caught) then
|
|
198
|
+
if WriterGate.admit(hold.held, leader, caught) then
|
|
199
|
+
val database = hold.generation.map(token =>
|
|
200
|
+
WorkerDatabase(doobie.Transactor.fromConnection[IO](hold.connection, None), token))
|
|
201
|
+
Stream.resource(observe(machine, hold.generation)) >> body(database)
|
|
218
202
|
else
|
|
219
203
|
val reason = if hold.held then s"classifier waiting for telemetry on $machine" else s"classifier lease denied for $machine"
|
|
220
204
|
Stream.exec(Logger[IO].info(reason)) ++ Stream.sleep_[IO](5.seconds)
|
|
@@ -222,13 +206,17 @@ open class SupervisorRuntime(profile: RuntimeProfile) extends IOApp:
|
|
|
222
206
|
|
|
223
207
|
private[runtime] def machineStreams(
|
|
224
208
|
config: AppConfig,
|
|
225
|
-
|
|
209
|
+
worker: ReadingWorker,
|
|
226
210
|
seeding: Option[Seeding],
|
|
227
211
|
checkpoint: Option[Checkpoint],
|
|
228
212
|
sender: Option[StompSender] = None,
|
|
229
213
|
observationMs: Long = 0L,
|
|
230
214
|
segmentEndMs: Option[Long] = None,
|
|
231
|
-
profileSegments: Option[CoreSegments[IO]] = None
|
|
215
|
+
profileSegments: Option[CoreSegments[IO]] = None,
|
|
216
|
+
writer: Option[TimelineWriter] = None,
|
|
217
|
+
observe: (String, Option[Long]) => Resource[IO, Unit] = (_, _) => Resource.unit[IO],
|
|
218
|
+
outputs: Option[OutputScope] = None,
|
|
219
|
+
decisionSegments: Option[CoreSegments[IO]] = None
|
|
232
220
|
): List[Stream[IO, Unit]] =
|
|
233
221
|
config.machines.map: machine =>
|
|
234
222
|
val aliases = config.routing.aliases.getOrElse(machine.id, Nil)
|
|
@@ -240,27 +228,42 @@ open class SupervisorRuntime(profile: RuntimeProfile) extends IOApp:
|
|
|
240
228
|
case Some(_) if config.localHistory && config.leaseUrl.isEmpty && !ObservationLead.ready(observationMs, segmentEndMs, leader) =>
|
|
241
229
|
Stream.never[IO]
|
|
242
230
|
case Some(api) if config.localHistory =>
|
|
243
|
-
HistoryRun(
|
|
231
|
+
HistoryRun(profile, writer, observe,
|
|
232
|
+
(settings, source) => decisionSegments.fold(Stream.empty.covaryAll[IO, Unit])(
|
|
233
|
+
profile.decisions(settings, source, _))
|
|
234
|
+
).gated(config, machine, aliases, sender, api, observationMs, segmentEndMs)
|
|
244
235
|
case _ =>
|
|
245
|
-
val body =
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
Stream.eval(
|
|
250
|
-
|
|
236
|
+
val body = (database: Option[WorkerDatabase]) =>
|
|
237
|
+
profileSegments.flatMap(profile.live(config, machine, aliases, _, checkpoint, seeding, outputs, database)).getOrElse:
|
|
238
|
+
val live = Mqtt(mqttCfg, aliases).subscribe
|
|
239
|
+
val readings = sourced(machine, aliases, live, seeding)
|
|
240
|
+
Stream.eval(if machine.mode.isDefined then IO.pure(None) else PendingIsland.resolve(checkpoint, machine)).flatMap: initial =>
|
|
241
|
+
Stream.eval(worker.run(machine, readings, initial))
|
|
242
|
+
val prepare = profileSegments.filter(_ => config.leaseUrl.nonEmpty && machine.mode.isEmpty).fold(IO.unit): segments =>
|
|
243
|
+
checkpoint.fold(IO.unit)(_.fetchPendingSegments.flatMap(rows =>
|
|
244
|
+
Orphans.list(rows.filter(_.machine == machine.id)).traverse_(Close.run(segments, _))))
|
|
245
|
+
lease(config.leaseUrl, machine.id.raw, leader, observe, database => Stream.exec(prepare) ++ body(database))
|
|
251
246
|
|
|
252
247
|
private[runtime] def heed(decision: Decision, segments: CoreSegments[IO], tagDefs: List[TagDef]): IO[Unit] =
|
|
253
|
-
decision.applyTo(segments, tagDefs, profile.tagging)
|
|
248
|
+
val write = decision.applyTo(segments, tagDefs, profile.tagging)
|
|
249
|
+
val scoped = decision match
|
|
250
|
+
case Decision.Resolve(machine, _, _, _) => segments.atRevision(machine)(write)
|
|
251
|
+
case Decision.Split(machine, _, _) => segments.atRevision(machine)(write)
|
|
252
|
+
case Decision.Skip(_) => write
|
|
253
|
+
scoped.handleErrorWith:
|
|
254
254
|
case _: IllegalArgumentException => IO.unit
|
|
255
255
|
case error => IO.raiseError(error)
|
|
256
256
|
|
|
257
|
-
private def decisionStream(config: AppConfig, segments: CoreSegments[IO]
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
257
|
+
private def decisionStream(config: AppConfig, segments: CoreSegments[IO], owners: Ref[IO, Map[String, Long]])
|
|
258
|
+
: Stream[IO, Unit] =
|
|
259
|
+
if !config.leaseHeld then Stream.empty
|
|
260
|
+
else
|
|
261
|
+
val byMachine = config.machines.map(m => m.id -> m).toMap
|
|
262
|
+
StompDecisions(config.connectivity.rabbitmq).subscribe.evalMap: decision =>
|
|
263
|
+
val target = decision match
|
|
264
|
+
case Decision.Resolve(id, _, _, _) => byMachine.get(id)
|
|
265
|
+
case Decision.Split(id, _, _) => byMachine.get(id)
|
|
266
|
+
case Decision.Skip(_) => None
|
|
267
|
+
target.filter(_.mode.isEmpty).fold(IO.unit): machine =>
|
|
268
|
+
owners.get.flatMap(current =>
|
|
269
|
+
IO.whenA(config.leaseUrl.isEmpty || current.contains(machine.id.raw))(heed(decision, segments, machine.tags)))
|
|
@@ -3,6 +3,8 @@ package scada.supervisor.runtime
|
|
|
3
3
|
import cats.effect.IO
|
|
4
4
|
import fs2.Stream
|
|
5
5
|
import io.circe.Json
|
|
6
|
+
import scada.stream.worker.OutputScope
|
|
7
|
+
import scada.stream.worker.postgres.WorkerDatabase
|
|
6
8
|
import scada.supervisor.core.{MachineConfig, Reading, ReadingOverride, Segments, Tagging}
|
|
7
9
|
import scada.supervisor.infra.checkpoint.Checkpoint
|
|
8
10
|
import scada.supervisor.infra.config.{AliasMapping, AppConfig, CheckpointApiConfig, ConfigProfile}
|
|
@@ -18,14 +20,11 @@ trait RuntimeProfile:
|
|
|
18
20
|
def wirePolicy: SegmentWirePolicy = SegmentWirePolicy.default
|
|
19
21
|
def historyProtocols: Vector[String] = Vector("preserve-known-suffix-v1")
|
|
20
22
|
def decorate(config: AppConfig, segments: Segments[IO]): IO[Segments[IO]] = IO.pure(segments)
|
|
21
|
-
def replayAliases(machine: MachineConfig, aliases: List[AliasMapping]): List[AliasMapping] = aliases
|
|
22
|
-
def readings(machine: MachineConfig, live: Stream[IO, Reading]): Stream[IO, Reading] = live
|
|
23
|
-
def input(config: AppConfig, machine: MachineConfig, aliases: List[AliasMapping]): Option[Stream[IO, Reading]] = None
|
|
24
23
|
def live(config: AppConfig, machine: MachineConfig, aliases: List[AliasMapping], segments: Segments[IO],
|
|
25
|
-
checkpoint: Option[Checkpoint], seeding: Option[Seeding]): Option[Stream[IO, Unit]] = None
|
|
26
|
-
def decisions(config: AppConfig, segments: Segments[IO]): Stream[IO, Unit] = Stream.empty
|
|
24
|
+
checkpoint: Option[Checkpoint], seeding: Option[Seeding], outputs: Option[OutputScope], database: Option[WorkerDatabase]): Option[Stream[IO, Unit]] = None
|
|
25
|
+
def decisions(config: AppConfig, machine: MachineConfig, segments: Segments[IO]): Stream[IO, Unit] = Stream.empty
|
|
27
26
|
def history(machine: MachineConfig, aliases: List[AliasMapping], api: CheckpointApiConfig,
|
|
28
|
-
announce: Vector[Json] => IO[Unit]): Stream[IO, Unit] =
|
|
27
|
+
announce: Vector[Json] => IO[Unit], generation: Option[Long]): Stream[IO, Unit] =
|
|
29
28
|
Stream.raiseError[IO](IllegalArgumentException(s"Unsupported history mode for ${machine.id.raw}"))
|
|
30
29
|
|
|
31
30
|
object RuntimeProfile:
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
package scada.supervisor.runtime
|
|
2
|
+
|
|
3
|
+
import cats.effect.{IO, IOLocal}
|
|
4
|
+
import io.circe.{Json, Printer}
|
|
5
|
+
import io.circe.parser.parse
|
|
6
|
+
import io.circe.syntax.*
|
|
7
|
+
import java.net.URLEncoder
|
|
8
|
+
import java.nio.charset.StandardCharsets.UTF_8
|
|
9
|
+
import java.security.MessageDigest
|
|
10
|
+
import java.util.HexFormat
|
|
11
|
+
import scada.stream.worker.{OutputId, OutputScope}
|
|
12
|
+
import scada.supervisor.infra.stomp.{StompFrame, StompSender}
|
|
13
|
+
|
|
14
|
+
/** Submits the segment wire format through the authoritative sink transaction. */
|
|
15
|
+
final class TimelineWriter private (
|
|
16
|
+
api: HistoryClient,
|
|
17
|
+
generation: String => IO[Option[Long]],
|
|
18
|
+
scope: OutputScope,
|
|
19
|
+
relay: Option[StompSender],
|
|
20
|
+
revisionScope: IOLocal[Option[(String, String)]]
|
|
21
|
+
) extends StompSender:
|
|
22
|
+
def atRevision[A](machine: String)(prepareAndWrite: IO[A]): IO[A] =
|
|
23
|
+
revisionScope.get.flatMap:
|
|
24
|
+
case Some((active, _)) if active == machine => prepareAndWrite
|
|
25
|
+
case previous =>
|
|
26
|
+
readRevision(machine).bracket(revision =>
|
|
27
|
+
revisionScope.set(Some((machine, revision))) *> prepareAndWrite
|
|
28
|
+
)(_ => revisionScope.set(previous))
|
|
29
|
+
|
|
30
|
+
private def readRevision(machine: String): IO[String] =
|
|
31
|
+
val encoded = URLEncoder.encode(machine, UTF_8)
|
|
32
|
+
api.request("GET", s"/v1/history/live-revision?machine=$encoded")
|
|
33
|
+
.flatMap(value => IO.fromEither(value.hcursor.get[String]("revision")))
|
|
34
|
+
|
|
35
|
+
def send(frame: StompFrame): IO[Unit] =
|
|
36
|
+
for
|
|
37
|
+
payload <- IO.fromEither(parse(frame.body))
|
|
38
|
+
machine <- IO.fromEither(payload.hcursor.get[String]("machine"))
|
|
39
|
+
owner <- generation(machine)
|
|
40
|
+
id <- scope.current.map(TimelineWriter.identity(_, payload))
|
|
41
|
+
_ <- applyMessage(machine, payload, id, owner, frame.headers.get("destination"))
|
|
42
|
+
yield ()
|
|
43
|
+
|
|
44
|
+
def applyMessage(machine: String, payload: Json, outputId: String, owner: Option[Long],
|
|
45
|
+
destination: Option[String]): IO[Unit] =
|
|
46
|
+
atRevision(machine)(commit(machine, payload, outputId, owner, destination))
|
|
47
|
+
|
|
48
|
+
private def commit(machine: String, payload: Json, outputId: String, owner: Option[Long],
|
|
49
|
+
destination: Option[String]): IO[Unit] =
|
|
50
|
+
for
|
|
51
|
+
current <- revisionScope.get
|
|
52
|
+
revision <- IO.fromOption(current.collect { case (matching, value) if matching == machine => value })(
|
|
53
|
+
IllegalStateException(s"Timeline revision is missing for $machine"))
|
|
54
|
+
metadata = List("outputId" -> outputId.asJson, "revision" -> revision.asJson) ++
|
|
55
|
+
owner.toList.map(value => "generation" -> value.asJson)
|
|
56
|
+
answer <- api.request("POST", "/v1/history/live-apply", payload.deepMerge(Json.obj("fence" -> Json.obj(metadata*))))
|
|
57
|
+
_ <- IO.raiseUnless(answer.hcursor.get[Boolean]("applied").contains(true))(
|
|
58
|
+
IllegalStateException(s"Timeline sink did not confirm output $outputId"))
|
|
59
|
+
after <- IO.fromEither(answer.hcursor.get[String]("revision"))
|
|
60
|
+
_ <- revisionScope.set(Some((machine, after)))
|
|
61
|
+
_ <- (relay, destination) match
|
|
62
|
+
case (Some(sender), Some(path)) =>
|
|
63
|
+
val committed = payload.deepMerge(Json.obj("committedOutputId" -> outputId.asJson))
|
|
64
|
+
val frame = StompFrame.send(path, "", committed.noSpaces)
|
|
65
|
+
IO.randomUUID.flatMap(receipt => sender.send(frame.copy(headers = frame.headers.updated("receipt", receipt.toString))))
|
|
66
|
+
case _ => IO.unit
|
|
67
|
+
yield ()
|
|
68
|
+
|
|
69
|
+
object TimelineWriter:
|
|
70
|
+
def create(api: HistoryClient, generation: String => IO[Option[Long]], scope: OutputScope,
|
|
71
|
+
relay: Option[StompSender]): IO[TimelineWriter] =
|
|
72
|
+
IOLocal(Option.empty[(String, String)]).map(new TimelineWriter(api, generation, scope, relay, _))
|
|
73
|
+
|
|
74
|
+
private val canonical = Printer.noSpaces.copy(sortKeys = true)
|
|
75
|
+
|
|
76
|
+
private[runtime] def identity(id: Option[OutputId], payload: Json): String =
|
|
77
|
+
val context = id.fold(Json.Null): output =>
|
|
78
|
+
val task = output.task
|
|
79
|
+
Json.arr(task.taskId.asJson, task.inputId.asJson, task.runId.asJson, output.position.asJson, output.index.asJson)
|
|
80
|
+
val bytes = canonical.print(Json.arr(context, payload)).getBytes(UTF_8)
|
|
81
|
+
HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes))
|