@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.
Files changed (37) hide show
  1. package/db/migrations/C0008__segment_write_receipts_grants.sql +1 -0
  2. package/db/migrations/E0019__segment_write_fence.sql +36 -0
  3. package/db/migrations/E0020__segment_write_fence_grants.sql +4 -0
  4. package/db/migrations/V0015__segment_write_receipts.sql +7 -0
  5. package/index.js +2 -0
  6. package/package.json +1 -1
  7. package/src/application/supervisorSink.js +15 -5
  8. package/src/domain/segment/segmentCoalesce.js +2 -1
  9. package/src/infrastructure/http/edge/edgeApi.js +1 -1
  10. package/src/infrastructure/http/edge/routes/history/historyRoutes.js +8 -3
  11. package/src/infrastructure/ingest/codecs/segmentCodec.js +26 -4
  12. package/src/infrastructure/ingest/db/migrationProfile.js +4 -1
  13. package/src/infrastructure/ingest/pipelines/segmentPipeline.js +11 -5
  14. package/src/infrastructure/ingest/sinks/fencedSegments.js +117 -0
  15. package/src/infrastructure/persistence/pg/history.js +4 -3
  16. package/src/infrastructure/persistence/pg/segmentWriteFence.js +112 -0
  17. package/supervisor-engine/src/main/scala/scada/stream/worker/OutputScope.scala +13 -0
  18. package/supervisor-engine/src/main/scala/scada/stream/worker/StreamWorker.scala +17 -1
  19. package/supervisor-engine/src/main/scala/scada/stream/worker/postgres/WorkerDatabase.scala +7 -0
  20. package/supervisor-engine/src/main/scala/scada/supervisor/core/ReadingWorker.scala +77 -0
  21. package/supervisor-engine/src/main/scala/scada/supervisor/core/Segmentation.scala +24 -13
  22. package/supervisor-engine/src/main/scala/scada/supervisor/core/Segments.scala +2 -0
  23. package/supervisor-engine/src/main/scala/scada/supervisor/infra/state/CheckpointSegments.scala +2 -0
  24. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/ClassifyQueue.scala +2 -2
  25. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompReadings.scala +0 -1
  26. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompSegments.scala +17 -10
  27. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ClassifyStreams.scala +57 -20
  28. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/EngineApp.scala +6 -2
  29. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/HistoryBus.scala +37 -5
  30. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/HistoryClient.scala +9 -2
  31. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/HistoryRun.scala +28 -30
  32. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/LocalHistory.scala +117 -31
  33. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/{SupervisorRuntime.scala → ProcessingApplication.scala} +101 -98
  34. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/RuntimeProfile.scala +5 -6
  35. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/TimelineWriter.scala +81 -0
  36. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/WriterLease.scala +24 -5
  37. package/supervisor-engine/src/main/scala/scada/supervisor/core/Supervisor.scala +0 -66
@@ -0,0 +1,77 @@
1
+ package scada.supervisor.core
2
+
3
+ import cats.effect.IO
4
+ import cats.syntax.all.*
5
+ import fs2.Stream
6
+ import scada.stream.worker.*
7
+ import scada.supervisor.core.segmentation.Timeline.Interval
8
+ import scala.concurrent.duration.*
9
+
10
+ /** Assembles the MQTT session input and its segment output port. */
11
+ final class ReadingWorker(
12
+ segmentation: Segmentation[IO],
13
+ tagging: Tagging,
14
+ segments: Segments[IO],
15
+ phases: CyclePhases = CyclePhases.empty,
16
+ customRun: Option[(MachineConfig, Stream[IO, Reading], Segments[IO]) => IO[Unit]] = None,
17
+ outputs: Option[OutputScope] = None
18
+ ):
19
+ import ReadingWorker.*
20
+
21
+ private val processor = new Processor[MachineConfig, State, Input, TaggedSegment]:
22
+ def step(machine: MachineConfig, state: State, input: Input): Either[ProcessingError, StepResult[State, TaggedSegment]] =
23
+ input match
24
+ case Input.Sample(reading) =>
25
+ segmentation.step(machine, state, reading).map(result =>
26
+ StepResult(result.state, result.outputs.map(emission => tagging.resolve(machine.tags, emission.value))))
27
+ case Input.Restore(cursor) =>
28
+ Right(StepResult(state, Vector(pending(cursor.name, cursor.start, cursor.end))))
29
+ case Input.Pulse(now, rows) =>
30
+ Right(StepResult(state, pulse(now, rows).toVector))
31
+
32
+ def run(machine: MachineConfig, readings: Stream[IO, Reading], initial: Option[SegmentCursor] = None): IO[Unit] =
33
+ if machine.mode.isDefined then
34
+ customRun.fold(IO.raiseError(IllegalStateException("Machine mode has no configured worker")))(_(machine, readings, segments))
35
+ else
36
+ for
37
+ id <- IO.randomUUID
38
+ task = TaskIdentity(machine.id.raw, "mqtt", id.toString)
39
+ // MQTT reseeds from the timeline checkpoint rather than replaying a stable broker position.
40
+ snapshot = Checkpoint[State, TaggedSegment](task, mqttVersion, 0, None, segmentation.seed(initial), Vector.empty)
41
+ store <- CheckpointStore.session(snapshot, 1)
42
+ worker = StreamWorker(processor, store, (_, row) =>
43
+ outputs.fold(write(machine, row.value))(_.within(row.id)(write(machine, row.value))))
44
+ _ <- worker.run(task, mqttVersion, machine, 1): _ =>
45
+ val samples = segmentation.gather(readings).map(reading => IO.pure(Input.Sample(reading)))
46
+ val beats = Stream.awakeEvery[IO](1.second).as(for
47
+ rows <- segments.list(machine.id)
48
+ now <- IO.realTime.map(value => Timestamp(value.toMillis.toDouble / 1000.0))
49
+ yield Input.Pulse(now, rows))
50
+ val restore = Stream.emits(initial.toList).map(cursor => IO.pure(Input.Restore(cursor)))
51
+ (restore ++ samples.mergeHaltL(beats)).evalMap(identity).zipWithIndex.map: (input, position) =>
52
+ Delivery(position, input, IO.unit)
53
+ yield ()
54
+
55
+ private def write(machine: MachineConfig, tagged: TaggedSegment): IO[Unit] = segments.atRevision(machine.id):
56
+ if phases.isEmpty then segments.upsert(machine.id, tagged)
57
+ else segments.list(machine.id).flatMap(all => segments.upsert(machine.id, phases.narrow(tagged, all)))
58
+
59
+ object ReadingWorker:
60
+ private type State = Option[Interval[Reading]]
61
+ private val mqttVersion = ProcessorVersion("mqtt-segments/1", "session", "timeline/1")
62
+
63
+ private enum Input:
64
+ case Sample(reading: Reading)
65
+ case Restore(cursor: SegmentCursor)
66
+ case Pulse(now: Timestamp, rows: List[TaggedSegment])
67
+
68
+ private def pending(name: String, start: Timestamp, end: Timestamp): TaggedSegment =
69
+ TaggedSegment(Segment(name, start, end, 0.0), Nil, Nil, Map.empty)
70
+
71
+ private def pulse(now: Timestamp, rows: List[TaggedSegment]): Option[TaggedSegment] =
72
+ rows.filter(_.segment.duration == 0).maxByOption(_.segment.start) match
73
+ case Some(open) =>
74
+ Option.when(now.isAfter(open.segment.end))(open.copy(segment = open.segment.copy(end = now)))
75
+ case None =>
76
+ rows.maxByOption(_.segment.end).filter(last => now.isAfter(last.segment.end))
77
+ .map(last => pending(last.segment.name, last.segment.end, now))
@@ -3,6 +3,7 @@ package scada.supervisor.core
3
3
  import cats.effect.Async
4
4
  import fs2.{Pipe, Stream}
5
5
  import scala.concurrent.duration.*
6
+ import scada.stream.worker.{ProcessingError, Processor, StepResult}
6
7
  import scada.supervisor.core.segmentation.Timeline
7
8
  import scada.supervisor.core.segmentation.Timeline.{Boundary, Event, Interval, Output}
8
9
 
@@ -12,25 +13,35 @@ final case class ReadingOverride(name: String, properties: Map[String, String])
12
13
  * Class changes close at the next phase's first sample. A gap over twice
13
14
  * the machine's window splits equal phases without inventing downtime.
14
15
  */
15
- final class Segmentation[F[_]: Async](overrideReading: Reading => Option[ReadingOverride] = _ => None):
16
+ final class Segmentation[F[_]: Async](overrideReading: Reading => Option[ReadingOverride] = _ => None)
17
+ extends Processor[MachineConfig, Option[Interval[Reading]], Reading, Emission[Segment]]:
16
18
  private val unclassified = "unclassified"
17
19
 
18
20
  def flow(machine: MachineConfig, initial: Option[SegmentCursor] = None): Pipe[F, Reading, Emission[Segment]] =
19
- val classify = Timeline.classifier(machine.segments)
20
- val maxGap = machine.window.toDouble * 2.0
21
- val seed = initial.map: cursor =>
22
- Interval(cursor.name, Reading(cursor.start, Params(Map.empty)), Reading(cursor.end, Params(Map.empty)))
23
-
24
21
  input =>
25
- gather(input).mapAccumulate(seed): (open, reading) =>
26
- val name = overrideReading(reading).map(_.name).orElse(classify(reading.params))
27
- .orElse(open.map(_.name)).getOrElse(unclassified)
28
- val continuous = open.exists(interval => !(reading.timestamp.minus(interval.end.timestamp) > maxGap))
29
- val step = Timeline.step(Boundary.Live, open, Event.Sample(reading, name, continuous))
30
- (step.open, step.outputs.flatMap(toEmission))
22
+ gather(input).mapAccumulate(seed(initial)): (open, reading) =>
23
+ val result = advance(machine, open, reading)
24
+ (result.state, result.outputs)
31
25
  .flatMap((_, emissions) => Stream.emits(emissions))
32
26
 
33
- private def gather(in: Stream[F, Reading]): Stream[F, Reading] =
27
+ private[core] def seed(initial: Option[SegmentCursor]): Option[Interval[Reading]] =
28
+ initial.map: cursor =>
29
+ Interval(cursor.name, Reading(cursor.start, Params(Map.empty)), Reading(cursor.end, Params(Map.empty)))
30
+
31
+ override def step(machine: MachineConfig, open: Option[Interval[Reading]], reading: Reading)
32
+ : Either[ProcessingError, StepResult[Option[Interval[Reading]], Emission[Segment]]] =
33
+ Right(advance(machine, open, reading))
34
+
35
+ private def advance(machine: MachineConfig, open: Option[Interval[Reading]], reading: Reading)
36
+ : StepResult[Option[Interval[Reading]], Emission[Segment]] =
37
+ val classify = Timeline.classifier(machine.segments)
38
+ val name = overrideReading(reading).map(_.name).orElse(classify(reading.params))
39
+ .orElse(open.map(_.name)).getOrElse(unclassified)
40
+ val continuous = open.exists(interval => !(reading.timestamp.minus(interval.end.timestamp) > machine.window.toDouble * 2.0))
41
+ val result = Timeline.step(Boundary.Live, open, Event.Sample(reading, name, continuous))
42
+ StepResult(result.open, result.outputs.flatMap(toEmission))
43
+
44
+ private[core] def gather(in: Stream[F, Reading]): Stream[F, Reading] =
34
45
  in.groupWithin(32, 50.millis).flatMap: chunk =>
35
46
  Stream.emits:
36
47
  chunk.toList.groupBy(_.timestamp.epoch).toList.sortBy(_._1).map: (_, rows) =>
@@ -21,6 +21,8 @@ import cats.syntax.all.*
21
21
  * }}}
22
22
  */
23
23
  trait Segments[F[_]]:
24
+ def atRevision[A](machine: MachineId)(prepareAndWrite: F[A]): F[A] = prepareAndWrite
25
+
24
26
  def upsert(machine: MachineId, segment: TaggedSegment): F[Unit]
25
27
 
26
28
  def upsertTransition(machine: MachineId, rows: List[TaggedSegment])(using Monad[F]): F[Unit] =
@@ -27,6 +27,8 @@ final class CheckpointSegments(
27
27
  ) extends CoreSegments[IO]:
28
28
  require(!preferCheckpoint || refreshCache.isDefined,"Checkpoint-first decisions require an exact cache refresh port")
29
29
 
30
+ override def atRevision[A](machine: MachineId)(action: IO[A]): IO[A] = underlying.atRevision(machine)(action)
31
+
30
32
  def find(machine: MachineId, start: Timestamp): IO[Option[TaggedSegment]] =
31
33
  if preferCheckpoint then checkpoint.fetchSegment(machine,start).flatTap(row => refreshCache.get(machine,start,row))
32
34
  else underlying.find(machine, start).flatMap:
@@ -11,13 +11,13 @@ import scada.supervisor.infra.config.{AliasMapping, RabbitMqConfig}
11
11
  * dotted routing keys. First-wins identity is the published eventId.
12
12
  *
13
13
  * {{{
14
- * ClassifyQueue(config, "scada.classify.machine-2", aliases).subscribe
14
+ * ClassifyQueue(config, "scada.classify.machine-2", aliases).subscribeDurable
15
15
  * }}}
16
16
  */
17
17
  final class ClassifyQueue(open: Resource[IO, StompLink], queue: String, aliases: List[AliasMapping]):
18
18
  def this(config: RabbitMqConfig, queue: String, aliases: List[AliasMapping]) =
19
19
  this(StompConnection.open(config.address.host, config.address.port, config.vhost, config.credentials.login, config.credentials.passcode).map(connection => connection: StompLink), queue, aliases)
20
- def subscribe: Stream[IO, Observation] = StompQueue(open, queue, decode).subscribe
20
+ def subscribeDurable: Stream[IO, (Observation, IO[Unit])] = StompQueue(open, queue, decode).subscribeDurable
21
21
  private[stomp] def decode(frame: StompFrame): Option[Observation] =
22
22
  for
23
23
  route <- routed(frame.headers)
@@ -11,7 +11,6 @@ final class StompReadings(open: Resource[IO,StompLink], queue: String, aliases:
11
11
  def this(config: RabbitMqConfig, queue: String, aliases: List[AliasMapping]) =
12
12
  this(StompConnection.open(config.address.host,config.address.port,config.vhost,config.credentials.login,config.credentials.passcode)
13
13
  .map(connection => connection: StompLink),queue,aliases)
14
- def subscribe: Stream[IO,Reading] = StompQueue(open,queue,decode).subscribe
15
14
  def subscribeDurable: Stream[IO,(Reading,IO[Unit])] = StompQueue(open,queue,decode).subscribeDurable
16
15
  private[stomp] def decode(frame: StompFrame): Option[Reading] =
17
16
  for
@@ -9,6 +9,7 @@ import org.typelevel.log4cats.Logger
9
9
  import org.typelevel.log4cats.slf4j.Slf4jLogger
10
10
  import scada.supervisor.core.*
11
11
  import scada.supervisor.core.Segments as CoreSegments
12
+ import scada.supervisor.runtime.{HistoryHttpError, TimelineWriter}
12
13
  import scala.collection.concurrent.TrieMap
13
14
  import scala.concurrent.duration.*
14
15
 
@@ -40,7 +41,12 @@ final class StompSegments(
40
41
 
41
42
  private given Logger[IO] = Slf4jLogger.getLogger[IO]
42
43
 
43
- def upsert(machine: MachineId, segment: TaggedSegment): IO[Unit] =
44
+ override def atRevision[A](machine: MachineId)(action: IO[A]): IO[A] =
45
+ connection match
46
+ case sink: TimelineWriter => sink.atRevision(machine.raw)(action)
47
+ case _ => action
48
+
49
+ def upsert(machine: MachineId, segment: TaggedSegment): IO[Unit] = atRevision(machine):
44
50
  underlying.upsert(machine, segment) *>
45
51
  underlying.list(machine).flatMap: rows =>
46
52
  SplitFollow.affected(segment, rows) match
@@ -50,7 +56,7 @@ final class StompSegments(
50
56
  case None => announce(machine, segment)
51
57
  case Some(seg) => announce(machine, seg)
52
58
 
53
- override def upsertTransition(machine: MachineId, rows: List[TaggedSegment])(using Monad[IO]): IO[Unit] =
59
+ override def upsertTransition(machine: MachineId, rows: List[TaggedSegment])(using Monad[IO]): IO[Unit] = atRevision(machine):
54
60
  if !policy.atomicTransition || rows.size < 2 then super.upsertTransition(machine, rows)
55
61
  else
56
62
  val body = Json.obj("type" -> "phase-transition".asJson, "machine" -> machine.raw.asJson,
@@ -63,7 +69,7 @@ final class StompSegments(
63
69
  def list(machine: MachineId): IO[List[TaggedSegment]] =
64
70
  underlying.list(machine)
65
71
 
66
- def replace(machine: MachineId, from: Timestamp, to: Timestamp, segments: List[TaggedSegment]): IO[Unit] =
72
+ def replace(machine: MachineId, from: Timestamp, to: Timestamp, segments: List[TaggedSegment]): IO[Unit] = atRevision(machine):
67
73
  underlying.replace(machine, from, to, segments) *>
68
74
  (if segments.isEmpty then IO.unit
69
75
  else publishRaw(SplitFamily.json(machine, from, segments)))
@@ -74,7 +80,7 @@ final class StompSegments(
74
80
  tags: List[String],
75
81
  options: List[String],
76
82
  properties: Map[String, String]
77
- ): IO[Unit] =
83
+ ): IO[Unit] = atRevision(machine):
78
84
  underlying.resolve(machine, original, tags, options, properties) *>
79
85
  underlying.find(machine, original.start).flatMap:
80
86
  case None => IO.unit
@@ -106,10 +112,11 @@ final class StompSegments(
106
112
  retrying(connection.send(sent),3,100.millis)
107
113
 
108
114
  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.handleErrorWith:
116
+ case error: HistoryHttpError if error.status >= 400 && error.status < 500 => IO.raiseError(error)
117
+ case error if attempts <= 1 =>
118
+ Logger[IO].error(error)(s"timeline publish failed after all retries on $destination") *>
119
+ IO.raiseError(error)
120
+ case error =>
121
+ Logger[IO].warn(error)(s"timeline publish retry in ${delay.toMillis}ms on $destination") *>
115
122
  IO.sleep(delay) *> retrying(io, attempts - 1, delay * 2)
@@ -1,11 +1,12 @@
1
1
  package scada.supervisor.runtime
2
2
 
3
- import cats.effect.{IO, Ref}
4
- import cats.syntax.all.*
3
+ import cats.effect.IO
4
+ import cats.effect.std.Semaphore
5
5
  import fs2.Stream
6
6
  import io.circe.Json
7
7
  import io.yarkivaev.temporal.{Conflict, Cursor, History, LocalStreams, Observation}
8
8
  import java.time.Instant
9
+ import scada.stream.worker.{Checkpoint, CheckpointStore, Delivery, ProcessingError, Processor, ProcessorVersion, StepResult, StreamWorker, TaskIdentity}
9
10
  import scada.supervisor.core.MachineConfig
10
11
 
11
12
  /**
@@ -16,27 +17,54 @@ import scada.supervisor.core.MachineConfig
16
17
  * ClassifyStreams.start(machine, seed, announce).flatMap(_.accept(point))
17
18
  * }}}
18
19
  */
19
- final class ClassifyStreams(machine: MachineConfig, state: Ref[IO, StreamState], ports: ClassifyPorts, watermark: Option[Long]):
20
+ final class ClassifyStreams private (
21
+ machine: MachineConfig,
22
+ store: CheckpointStore[StreamState, ClassifyStreams.Command],
23
+ task: TaskIdentity,
24
+ ports: ClassifyPorts,
25
+ watermark: Option[Long],
26
+ lock: Semaphore[IO]
27
+ ):
28
+ import ClassifyStreams.{Command, version}
29
+
30
+ private val ownership = 1L
31
+ private val processor = new Processor[Unit, StreamState, (Observation, Long), Command]:
32
+ override def step(config: Unit, state: StreamState, input: (Observation, Long))
33
+ : Either[ProcessingError, StepResult[StreamState, Command]] =
34
+ val (point, now) = input
35
+ val (next, routed) = ClassifyStreams.route(state, point, now, machine.window.toLong * 2000)
36
+ Right(StepResult(next, Vector(Command(point, next, routed))))
37
+
38
+ private val worker = StreamWorker(processor, store, (_, output) =>
39
+ val command = output.value
40
+ IO.whenA(command.routed.changed)(publish(command.snapshot, command.routed.cursor)) *>
41
+ ports.persist(command.snapshot.pool))
42
+
20
43
  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] =
44
+ def consumeDurable(input: Stream[IO, (Observation, IO[Unit])]): Stream[IO, Unit] =
45
+ input.evalMap((point, acknowledge) => accept(point) *> acknowledge)
46
+
47
+ def cursors: IO[Vector[Cursor]] = store.load(task, ownership).map(_.state.pool.cursors.streams)
48
+ def accept(point: Observation): IO[Unit] = lock.permit.use: _ =>
23
49
  for
50
+ checkpoint <- store.load(task, ownership)
24
51
  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)
52
+ retry = checkpoint.pendingOutputs.exists(_.value.point == point)
53
+ position = checkpoint.position.fold(0L)(previous => if retry then previous else previous + 1L)
54
+ // The cursor checkpoint is session-local. Broker ACK waits for publication and cursor persistence.
55
+ _ <- worker.run(task, version, (), ownership)(_ => Stream.emit(Delivery(position, (point, now), IO.unit)))
29
56
  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))
57
+ private def publish(snapshot: StreamState, cursor: Cursor): IO[Unit] =
58
+ val points = ClassifyHistory.collected(snapshot.tapes.getOrElse(cursor.id, History.empty))
59
+ val until = points.map(_.time).maxOption.getOrElse(0L)
60
+ val from = points.map(_.time).minOption.getOrElse(0L)
61
+ val existing = snapshot.stored.filter(row => ClassifyStreams.overlaps(row, from, until))
62
+ val slack = machine.window.toLong * 2000
63
+ val historical = watermark.exists(end => cursor.position + slack < end)
64
+ val context = Json.obj("segments" -> Json.arr(existing*), "page" -> Json.obj("until" -> Json.fromLong(until)), "rightClosed" -> Json.fromBoolean(historical))
65
+ val classification = if historical then LocalHistory.replay(machine, points, "", s"cursor:${cursor.id}").map(_.segments)
66
+ else IO(LocalHistory.classify(machine, points))
67
+ classification.flatMap: result =>
40
68
  val page = ClassifyHistory.published(machine, existing, result, context)
41
69
  ports.announce(page, historical)
42
70
 
@@ -45,11 +73,20 @@ final case class StreamState(pool: HistoryPool, tapes: Map[Long, History], store
45
73
  final case class RoutedPoint(cursor: Cursor, changed: Boolean)
46
74
 
47
75
  object ClassifyStreams:
76
+ private final case class Command(point: Observation, snapshot: StreamState, routed: RoutedPoint)
77
+ private val version = ProcessorVersion("amqp-classify/1", "session", "history-cursors/1")
78
+
48
79
  def start(machine: MachineConfig, seed: Vector[Json], announce: (Vector[Json], Boolean) => IO[Unit]): IO[ClassifyStreams] =
49
80
  open(machine, seed, ClassifyPorts(_ => IO.unit, announce))
50
81
  def open(machine: MachineConfig, seed: Vector[Json], ports: ClassifyPorts, watermark: Option[Long] = None, initial: Option[HistoryPool] = None): IO[ClassifyStreams] =
51
82
  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))
83
+ for
84
+ id <- IO.randomUUID
85
+ task = TaskIdentity(machine.id.raw, "amqp-classify", id.toString)
86
+ snapshot = Checkpoint[StreamState, Command](task, version, 0L, None, StreamState(pool, Map.empty, seed), Vector.empty)
87
+ store <- CheckpointStore.session(snapshot, 1L)
88
+ lock <- Semaphore[IO](1)
89
+ yield new ClassifyStreams(machine, store, task, ports, watermark, lock)
53
90
  private[runtime] def route(current: StreamState, point: Observation, now: Long, maxGap: Long): (StreamState, RoutedPoint) =
54
91
  val gap = if current.pool.cursors.maxGap > 0 then current.pool.cursors.maxGap else maxGap
55
92
  val idle = current.pool.cursors.idleTimeout
@@ -1,4 +1,8 @@
1
1
  package scada.supervisor.runtime
2
2
 
3
- /** Standalone entry point for the built-in rules-based classifier. */
4
- object EngineApp extends SupervisorRuntime(RuntimeProfile.default)
3
+ import cats.effect.{ExitCode, IO, IOApp}
4
+
5
+ /** Standalone entry point for the built-in rules-based worker. */
6
+ object EngineApp extends IOApp:
7
+ private val application = ProcessingApplication(RuntimeProfile.default)
8
+ def run(args: List[String]): IO[ExitCode] = application.run(args)
@@ -6,6 +6,7 @@ import io.circe.Json
6
6
  import io.circe.parser.parse
7
7
  import java.time.Instant
8
8
  import scada.supervisor.core.*
9
+ import scada.supervisor.infra.config.AppConfig
9
10
  import scada.supervisor.infra.stomp.{SegmentMessage, StompFrame, StompSender}
10
11
 
11
12
  /**
@@ -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_(row => sender.send(StompFrame.send(
53
- destination,
54
- "",
55
- epoch.fold(message(machine, row))(n => stamped(machine, row, n)).noSpaces
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)
@@ -9,6 +9,9 @@ import java.time.Duration
9
9
  import scada.supervisor.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
- 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)))
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
1
  package scada.supervisor.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
9
  import scada.supervisor.infra.config.{AliasMapping, AppConfig, CheckpointApiConfig}
10
- import scada.supervisor.infra.stomp.{ClassifyQueue, StompFrame, StompSender}
10
+ import scada.supervisor.infra.stomp.{ClassifyQueue, StompSender}
11
11
  import scala.concurrent.duration.*
12
12
 
13
13
  /**
@@ -19,7 +19,9 @@ import scala.concurrent.duration.*
19
19
  * HistoryRun.gated(config, machine, aliases, sender, api)
20
20
  * }}}
21
21
  */
22
- final class HistoryRun(runtime: SupervisorRuntime, profile: RuntimeProfile):
22
+ final class HistoryRun(profile: RuntimeProfile, writer: Option[TimelineWriter],
23
+ observe: (String, Option[Long]) => Resource[IO, Unit],
24
+ decisions: (AppConfig, scada.supervisor.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. */
@@ -30,15 +32,15 @@ final class HistoryRun(runtime: SupervisorRuntime, profile: RuntimeProfile):
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
38
  private def once(url: String, config: AppConfig, machine: scada.supervisor.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)
43
+ if machine.mode.isDefined then follow(config, machine, aliases, sender, api, end.getOrElse(0L), end, grant).concurrently(decisions(config, machine))
42
44
  else Stream.eval(IO.blocking(ClassifierCursors.load(hold.connection, machine.id.raw, machine.window.toLong * 2000, 10000))).flatMap: pool =>
43
45
  amqp(config, machine, aliases, sender, rows, end, grant, p => IO.blocking(ClassifierCursors.save(hold.connection, machine.id.raw, p)), Some(pool))
44
46
 
@@ -49,36 +51,32 @@ final class HistoryRun(runtime: SupervisorRuntime, profile: RuntimeProfile):
49
51
  else custom(config, machine, aliases, sender, api, observationMs, segmentEndMs, grant)
50
52
 
51
53
  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
+ val announce = HistoryBus.lead(sender, config, machine.id, observationMs, segmentEndMs, grant)
55
+ profile.history(machine, aliases, api, announce, grant.filter(_.held).map(_.generation))
54
56
 
55
57
  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
58
  val leader = ObservationLead.leading(config.writerRole, config.leaseUrl)
57
- val publish = runtime.historyAnnounce(sender, config, machine.id, grant)
58
59
  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))
60
+ val input = ClassifyQueue(config.connectivity.rabbitmq, queue, aliases).subscribeDurable
61
+ val write = writer.getOrElse(throw IllegalStateException("Historical classification requires a timeline writer"))
62
+ val owner = grant.filter(_.held).map(_.generation)
63
+ val ports = ClassifyPorts(persist, (rows, historical) =>
64
+ ClassifyBus.publish(segmentEndMs, leader, historical)(rows): approved =>
65
+ approved.traverse_ { row =>
66
+ val message = if row.hcursor.get[String]("type").contains("split-family") then row else HistoryBus.message(machine.id, row)
67
+ write.applyMessage(machine.id.raw, message, TimelineWriter.identity(None, message), owner,
68
+ config.connectivity.rabbitmq.destinations.segments)
69
+ }
70
+ )
71
+ Stream.eval(Logger[IO].info(s"consuming AMQP classify queue $queue")) >> Stream.eval(ClassifyStreams.open(machine, seed, ports, segmentEndMs, initial)).flatMap(_.consumeDurable(input))
62
72
 
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
73
  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)
74
+ def publish(segmentEndMs: Option[Long], leader: Boolean, historical: Boolean = false)(rows: Vector[Json])(
75
+ write: Vector[Json] => IO[Unit]
76
+ ): IO[Unit] =
77
+ if historical || ObservationLead.ready(horizon(rows), segmentEndMs, leader) then write(rows)
78
+ else IO.unit
79
+
82
80
  private def horizon(rows: Vector[Json]): Long =
83
81
  val ends = rows.flatMap: row =>
84
82
  row.hcursor.get[String]("end_time").toOption.map(java.time.Instant.parse(_).toEpochMilli).toVector ++