@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.
Files changed (106) hide show
  1. package/README.md +4 -4
  2. package/db/migrations/C0008__segment_write_receipts_grants.sql +1 -0
  3. package/db/migrations/E0019__segment_write_fence.sql +36 -0
  4. package/db/migrations/E0020__segment_write_fence_grants.sql +4 -0
  5. package/db/migrations/V0015__segment_write_receipts.sql +7 -0
  6. package/index.js +2 -0
  7. package/package.json +6 -3
  8. package/src/application/supervisorSink.js +15 -5
  9. package/src/domain/segment/segmentCoalesce.js +2 -1
  10. package/src/infrastructure/http/edge/edgeApi.js +1 -1
  11. package/src/infrastructure/http/edge/routes/history/historyRoutes.js +8 -3
  12. package/src/infrastructure/ingest/codecs/segmentCodec.js +26 -4
  13. package/src/infrastructure/ingest/db/migrationProfile.js +4 -1
  14. package/src/infrastructure/ingest/pipelines/segmentPipeline.js +11 -5
  15. package/src/infrastructure/ingest/sinks/fencedSegments.js +117 -0
  16. package/src/infrastructure/persistence/pg/history.js +4 -3
  17. package/src/infrastructure/persistence/pg/segmentWriteFence.js +112 -0
  18. package/stream-processing/dependencies/stream-worker.jar +0 -0
  19. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/Condition.scala +1 -1
  20. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/CyclePhases.scala +1 -1
  21. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/Decision.scala +1 -1
  22. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/Emission.scala +1 -1
  23. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/MachineConfig.scala +1 -1
  24. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/MachineId.scala +1 -1
  25. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/MachineMode.scala +1 -1
  26. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/Params.scala +1 -1
  27. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/Reading.scala +1 -1
  28. package/stream-processing/src/main/scala/scada/processing/core/ReadingWorker.scala +82 -0
  29. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/Segment.scala +1 -1
  30. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/SegmentDef.scala +1 -1
  31. package/stream-processing/src/main/scala/scada/processing/core/Segmentation.scala +47 -0
  32. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/Segments.scala +3 -1
  33. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/SplitFollow.scala +1 -1
  34. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/SplitPieces.scala +1 -1
  35. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/TagDef.scala +1 -1
  36. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/TaggedSegment.scala +1 -1
  37. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/Tagging.scala +1 -1
  38. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/Timestamp.scala +1 -1
  39. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/segmentation/Timeline.scala +2 -2
  40. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/checkpoint/Checkpoint.scala +2 -2
  41. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/checkpoint/ClickhouseReadingsCheckpoint.scala +3 -3
  42. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/checkpoint/SupervisorSinkCheckpoint.scala +3 -3
  43. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/config/AppConfig.scala +2 -2
  44. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/config/ConfigLoad.scala +2 -2
  45. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/config/ConfigProfile.scala +2 -2
  46. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/mqtt/Mqtt.scala +3 -3
  47. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/mqtt/Sessions.scala +1 -1
  48. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/state/AtomicStateFile.scala +1 -1
  49. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/state/CheckpointSegments.scala +7 -5
  50. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/state/SegmentStatePolicy.scala +2 -2
  51. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/state/Segments.scala +3 -3
  52. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/ClassifyQueue.scala +4 -4
  53. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/DecisionMessage.scala +2 -2
  54. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/DurableStomp.scala +1 -1
  55. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/SegmentMessage.scala +2 -2
  56. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/SegmentWirePolicy.scala +2 -2
  57. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/SplitFamily.scala +2 -2
  58. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/StompConnection.scala +1 -1
  59. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/StompDecisions.scala +3 -3
  60. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/StompFrame.scala +1 -1
  61. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/StompMachineDecisions.scala +3 -3
  62. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/StompQueue.scala +1 -1
  63. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/StompReadings.scala +3 -4
  64. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/StompSegments.scala +20 -13
  65. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/ClassifyHistory.scala +3 -3
  66. package/stream-processing/src/main/scala/scada/processing/runtime/ClassifyStreams.scala +128 -0
  67. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/Close.scala +4 -4
  68. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/HealthServer.scala +1 -1
  69. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/HistoryBus.scala +40 -8
  70. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/HistoryClient.scala +11 -4
  71. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/HistoryRun.scala +42 -40
  72. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/LocalHistory.scala +122 -36
  73. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/ObservationLead.scala +1 -1
  74. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/Orphans.scala +4 -4
  75. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/PendingIsland.scala +3 -3
  76. package/stream-processing/src/main/scala/scada/processing/runtime/ProcessingApp.scala +8 -0
  77. package/{supervisor-engine/src/main/scala/scada/supervisor/runtime/SupervisorRuntime.scala → stream-processing/src/main/scala/scada/processing/runtime/ProcessingApplication.scala} +108 -106
  78. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/RuntimeProfile.scala +10 -12
  79. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/Seeding.scala +4 -4
  80. package/stream-processing/src/main/scala/scada/processing/runtime/TimelineWriter.scala +81 -0
  81. package/stream-processing/src/main/scala/scada/processing/runtime/WorkerDatabase.scala +7 -0
  82. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/WriterEpoch.scala +1 -1
  83. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/WriterGate.scala +1 -1
  84. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/WriterLease.scala +11 -9
  85. package/{supervisor-engine → stream-processing}/src/main/scala/scada/stream/replay/Replay.scala +1 -1
  86. package/stream-processing/stream-worker.lock +2 -0
  87. package/supervisor-engine/src/main/scala/scada/stream/worker/Processor.scala +0 -8
  88. package/supervisor-engine/src/main/scala/scada/stream/worker/StreamWorker.scala +0 -119
  89. package/supervisor-engine/src/main/scala/scada/stream/worker/postgres/PgCheckpointStore.scala +0 -83
  90. package/supervisor-engine/src/main/scala/scada/supervisor/core/Segmentation.scala +0 -52
  91. package/supervisor-engine/src/main/scala/scada/supervisor/core/Supervisor.scala +0 -66
  92. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ClassifierCursors.scala +0 -58
  93. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ClassifyStreams.scala +0 -67
  94. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/EngineApp.scala +0 -4
  95. /package/{supervisor-engine → stream-processing}/vendor/gaps-and-islands/LICENSE +0 -0
  96. /package/{supervisor-engine → stream-processing}/vendor/gaps-and-islands/UPSTREAM +0 -0
  97. /package/{supervisor-engine → stream-processing}/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/Island.scala +0 -0
  98. /package/{supervisor-engine → stream-processing}/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandEvent.scala +0 -0
  99. /package/{supervisor-engine → stream-processing}/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandsFlow.scala +0 -0
  100. /package/{supervisor-engine → stream-processing}/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandsPolicy.scala +0 -0
  101. /package/{supervisor-engine → stream-processing}/vendor/temporal-streams/LICENSE +0 -0
  102. /package/{supervisor-engine → stream-processing}/vendor/temporal-streams/UPSTREAM +0 -0
  103. /package/{supervisor-engine → stream-processing}/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/History.scala +0 -0
  104. /package/{supervisor-engine → stream-processing}/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/LocalStreams.scala +0 -0
  105. /package/{supervisor-engine → stream-processing}/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/Overlay.scala +0 -0
  106. /package/{supervisor-engine → stream-processing}/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/Worker.scala +0 -0
@@ -0,0 +1,8 @@
1
+ package scada.processing.runtime
2
+
3
+ import cats.effect.{ExitCode, IO, IOApp}
4
+
5
+ /** Standalone entry point for the built-in rules-based worker. */
6
+ object ProcessingApp extends IOApp:
7
+ private val application = ProcessingApplication(RuntimeProfile.default)
8
+ def run(args: List[String]): IO[ExitCode] = application.run(args)
@@ -1,52 +1,34 @@
1
- package scada.supervisor.runtime
1
+ package scada.processing.runtime
2
2
 
3
- import cats.effect.{ExitCode, IO, IOApp, Ref, Resource}
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 io.yarkivaev.streamworker.OutputScope
7
8
  import org.typelevel.log4cats.Logger
8
9
  import org.typelevel.log4cats.slf4j.Slf4jLogger
9
- import scada.supervisor.core.{
10
+ import scada.processing.core.{
10
11
  Decision,
11
12
  MachineConfig,
12
13
  MachineId,
13
14
  Reading,
14
15
  Segmentation,
15
16
  Segments as CoreSegments,
16
- Supervisor,
17
+ ReadingWorker,
17
18
  TagDef,
18
19
  TaggedSegment,
19
20
  Timestamp
20
21
  }
21
- import scada.supervisor.infra.checkpoint.{Checkpoint, ClickhouseReadingsCheckpoint, SupervisorSinkCheckpoint}
22
- import scada.supervisor.infra.config.{AliasMapping, AppConfig, ConfigLoad, RabbitMqConfig}
23
- import scada.supervisor.infra.mqtt.Mqtt
24
- import scada.supervisor.infra.state.{CheckpointSegments, Segments as StateSegments}
25
- import scada.supervisor.infra.stomp.{DurableStomp, StompConnection, StompDecisions, StompSegments, StompSender}
22
+ import scada.processing.infra.checkpoint.{Checkpoint, ClickhouseReadingsCheckpoint, SupervisorSinkCheckpoint}
23
+ import scada.processing.infra.config.{AliasMapping, AppConfig, ConfigLoad, RabbitMqConfig}
24
+ import scada.processing.infra.mqtt.Mqtt
25
+ import scada.processing.infra.state.{CheckpointSegments, Segments as StateSegments}
26
+ import scada.processing.infra.stomp.{DurableStomp, StompConnection, StompDecisions, StompSegments, StompSender}
26
27
  import scala.collection.immutable.SortedMap
27
28
  import scala.concurrent.duration.*
28
29
 
29
- /**
30
- * Live entry point and composition root. Loads HOCON, wires the
31
- * module graph, opens the startup ceremony (checkpoint API replay, live
32
- * MQTT, STOMP decisions) and runs every per-machine supervisor loop
33
- * concurrently with the decision consumer until killed.
34
- *
35
- * `F` is pinned to `IO` here; `core` stays tagless.
36
- *
37
- * Decorator order:
38
- * {{{
39
- * StompSegments(CheckpointSegments(StateSegments(...), checkpoint), connection, dest)
40
- * }}}
41
- * Segment persistence/publish remains the durable boundary. Replay
42
- * cursor is derived from supervisor-sink checkpoint API during startup.
43
- *
44
- * {{{
45
- * sbt "runMain scada.supervisor.runtime.EngineApp config/application.conf"
46
- * }}}
47
- */
48
- open class SupervisorRuntime(profile: RuntimeProfile) extends IOApp:
49
-
30
+ /** Wires broker inputs, task ownership, processing jobs and timeline output adapters. */
31
+ final class ProcessingApplication(profile: RuntimeProfile):
50
32
  private val defaultPath: String = "config/application.conf"
51
33
 
52
34
  private given Logger[IO] = Slf4jLogger.getLogger[IO]
@@ -55,40 +37,53 @@ open class SupervisorRuntime(profile: RuntimeProfile) extends IOApp:
55
37
  args match
56
38
  case "--capabilities" :: Nil => IO.println(io.circe.Json.obj("role" -> io.circe.Json.fromString("supervisor"),
57
39
  "historyProtocols" -> io.circe.Json.arr(profile.historyProtocols.map(io.circe.Json.fromString)*)).noSpaces).as(ExitCode.Success)
58
- case "--check" :: path :: Nil => ConfigLoad(profile = profile.configuration).load(path).as(ExitCode.Success)
40
+ case "--check" :: path :: Nil => load(path).as(ExitCode.Success)
59
41
  case "--check" :: _ => IO.raiseError(IllegalArgumentException("Usage: supervisor --check CONFIG"))
60
- case _ => ConfigLoad(profile = profile.configuration).load(args.headOption.getOrElse(defaultPath)).flatMap(live).as(ExitCode.Success)
42
+ case _ => load(args.headOption.getOrElse(defaultPath)).flatMap(live).as(ExitCode.Success)
43
+
44
+ private def load(path: String): IO[AppConfig] =
45
+ ConfigLoad(profile = profile.configuration).load(path).flatMap: config =>
46
+ val outputEnabled = config.connectivity.rabbitmq.destinations.segments.isDefined
47
+ IO.raiseWhen(outputEnabled && config.connectivity.checkpointApi.isEmpty)(
48
+ IllegalArgumentException("A timeline sink checkpoint API is required when segment output is enabled")
49
+ ).as(config)
61
50
 
62
51
  private def live(config: AppConfig): IO[Unit] =
63
52
  Logger[IO].info(s"supervisor starting: machines=${config.machines.size} stomp=${config.connectivity.rabbitmq.destinations.segments.isDefined} checkpointApi=${config.connectivity.checkpointApi.isDefined}") *>
64
53
  Ref.of[IO, Map[MachineId, SortedMap[Timestamp, TaggedSegment]]](Map.empty).flatMap: segmentsRef =>
65
- resources(config).use: publishConn =>
54
+ (for
55
+ owners <- Resource.eval(Ref.of[IO, Map[String, Long]](Map.empty))
56
+ outputs <- Resource.eval(OutputScope.create)
57
+ publish <- resources(config)
58
+ writer <- Resource.eval(timelineWriter(config, owners, outputs, publish))
59
+ yield (owners, outputs, publish, writer)).use: (owners, outputs, publishConn, writer) =>
66
60
  val checkpoint = checkpointWithDecorators(config)
67
61
  val base = StateSegments[IO](segmentsRef, profile.statePolicy)
68
62
  val withFallback = checkpoint.fold(base)(cp => CheckpointSegments(base, cp))
69
- val decorated = decorate(config, publishConn, withFallback)
70
- profile.decorate(config, decorated).flatMap(runStreams(config, _, checkpoint, base, publishConn))
63
+ val decorated = decorate(config, writer, withFallback)
64
+ profile.decorate(config, decorated).flatMap(runStreams(config, _, checkpoint, base, publishConn, writer, owners, outputs))
71
65
 
72
- private def runStreams(config: AppConfig, segments: CoreSegments[IO], checkpoint: Option[Checkpoint], base: StateSegments[IO], publish: Option[StompSender]): IO[Unit] =
66
+ private def runStreams(config: AppConfig, segments: CoreSegments[IO], checkpoint: Option[Checkpoint], base: StateSegments[IO], publish: Option[StompSender], writer: Option[TimelineWriter],
67
+ owners: Ref[IO, Map[String, Long]], outputs: OutputScope): IO[Unit] =
73
68
 
74
- val supervisor = Supervisor[IO](Segmentation[IO](profile.classifyReading), profile.tagging, segments, config.cyclePhases)
69
+ val worker = ReadingWorker(Segmentation(profile.classifyReading), profile.tagging, segments, config.cyclePhases, outputs = Some(outputs))
75
70
  val decisionSegments = checkpoint.filter(_ => config.localHistory).fold(segments)(cp =>
76
71
  CheckpointSegments(segments,cp,preferCheckpoint=true,refreshCache=Some(base.refresh)))
77
72
  val stall = config.connectivity.checkpointApi.map(api => api.timeoutSeconds.seconds).getOrElse(60.seconds)
78
73
  val seeding = checkpoint.map(Seeding(_, config.seeding.capacity, stall))
79
74
  val protectedMachines = Orphans.protectedMachines(config) ++ config.machines.filter(_.mode.isDefined).map(_.id)
80
- val canCloseOrphans = config.leaseHeld && config.machines.exists(machine => !protectedMachines(machine.id))
75
+ val canCloseOrphans = config.leaseUrl.isEmpty && config.leaseHeld && config.machines.exists(machine => !protectedMachines(machine.id))
81
76
  Logger[IO].info("supervisor ready, closing orphaned pending segments") *>
82
77
  closeWhenHeld(canCloseOrphans, checkpoint, segments, protectedMachines) *>
83
78
  Logger[IO].info("supervisor ready, entering stream loop") *>
84
79
  (if config.machines.isEmpty then IO.never
85
- else streams(config, supervisor, decisionSegments, seeding, checkpoint, publish, segments).compile.drain) *>
80
+ else streams(config, worker, decisionSegments, seeding, checkpoint, publish, segments, writer, owners, outputs).compile.drain) *>
86
81
  Logger[IO].info("supervisor stream loop exited")
87
82
  /**
88
83
  * Closes orphan pending rows only while this process holds the writer lease.
89
84
  *
90
85
  * {{{
91
- * SupervisorRuntime.closeWhenHeld(false, checkpoint, segments, Set.empty)
86
+ * ProcessingApplication.closeWhenHeld(false, checkpoint, segments, Set.empty)
92
87
  * }}}
93
88
  */
94
89
  private[runtime] def closeWhenHeld(held: Boolean, checkpoint: Option[Checkpoint], segments: CoreSegments[IO], historical: Set[MachineId]): IO[Unit] =
@@ -134,68 +129,53 @@ open class SupervisorRuntime(profile: RuntimeProfile) extends IOApp:
134
129
  slot
135
130
  )
136
131
  Some(new StompSender:
137
- def send(frame: scada.supervisor.infra.stomp.StompFrame): IO[Unit] = lock.permit.use(_ => durable.send(frame))
132
+ def send(frame: scada.processing.infra.stomp.StompFrame): IO[Unit] = lock.permit.use(_ => durable.send(frame))
138
133
  )
139
134
 
135
+ private def timelineWriter(config: AppConfig, owners: Ref[IO, Map[String, Long]], outputs: OutputScope,
136
+ publish: Option[StompSender]): IO[Option[TimelineWriter]] =
137
+ config.connectivity.checkpointApi.traverse: api =>
138
+ val owner = (machine: String) => owners.get.flatMap: current =>
139
+ val grant = current.get(machine)
140
+ IO.raiseWhen(config.leaseUrl.isDefined && grant.isEmpty)(
141
+ IllegalStateException(s"No active timeline writer for $machine")).as(grant)
142
+ TimelineWriter.create(HistoryClient(api), owner, outputs, publish)
143
+
144
+ private def track(owners: Ref[IO, Map[String, Long]])(machine: String, generation: Option[Long]): Resource[IO, Unit] =
145
+ generation.fold(Resource.unit[IO])(value => Resource.make(owners.update(_.updated(machine, value)))(_ =>
146
+ owners.update(current => if current.get(machine).contains(value) then current.removed(machine) else current)))
147
+
140
148
  private def decorate(
141
149
  config: AppConfig,
142
- publish: Option[StompSender],
150
+ writer: Option[TimelineWriter],
143
151
  base: CoreSegments[IO]
144
152
  ): CoreSegments[IO] =
145
- (publish, config.connectivity.rabbitmq.destinations.segments) match
146
- case (Some(conn), Some(dest)) => StompSegments(base, conn, dest, policy = profile.wirePolicy)
153
+ (writer, config.connectivity.rabbitmq.destinations.segments) match
154
+ case (Some(sink), Some(dest)) => StompSegments(base, sink, dest, policy = profile.wirePolicy)
147
155
  case _ => base
148
156
 
149
157
  private def streams(
150
158
  config: AppConfig,
151
- supervisor: Supervisor[IO],
159
+ worker: ReadingWorker,
152
160
  segments: CoreSegments[IO],
153
161
  seeding: Option[Seeding],
154
162
  checkpoint: Option[Checkpoint],
155
163
  publish: Option[StompSender],
156
- profileSegments: CoreSegments[IO]
164
+ profileSegments: CoreSegments[IO],
165
+ writer: Option[TimelineWriter],
166
+ owners: Ref[IO, Map[String, Long]],
167
+ outputs: OutputScope
157
168
  ): Stream[IO, Unit] =
158
- Stream(machineStreams(config, supervisor, seeding, checkpoint, publish, profileSegments = Some(profileSegments))*).parJoinUnbounded
159
- .concurrently(decisionStream(config, segments))
160
- .concurrently(profile.decisions(config, segments))
161
-
162
- /** Sends a committed page. A configured lease uses the holder generation and a non-holder sends nothing. */
163
- private[runtime] def historyAnnounce(sender: Option[StompSender], config: AppConfig, machine: MachineId, grant: Option[LeaseGrant] = None): Vector[io.circe.Json] => IO[Unit] =
164
- WriterLease.publication(config.leaseUrl, grant, config.writerEpoch) match
165
- case None => (_: Vector[io.circe.Json]) => IO.unit
166
- case Some(epoch) =>
167
- (sender, config.connectivity.rabbitmq.destinations.segments) match
168
- case (Some(conn), Some(dest)) => HistoryBus.publish(conn, dest, machine, epoch)
169
- case _ => (_: Vector[io.circe.Json]) => IO.unit
170
-
171
- /**
172
- * Publishes committed history only after a real segment end is covered.
173
- * A leader may publish when nothing has been replicated. A standby does not.
174
- * A configured lease stamps its generation and a process that does not hold it does not publish.
175
- * The same gate covers every configured machine.
176
- *
177
- * {{{
178
- * SupervisorRuntime.leadAnnounce(sender, config, MachineId("machine-1"), 5L, Some(4L), Some(LeaseGrant(true, 7)))(rows)
179
- * }}}
180
- */
181
- private[runtime] def leadAnnounce(
182
- sender: Option[StompSender],
183
- config: AppConfig,
184
- machine: MachineId,
185
- observationMs: Long,
186
- segmentEndMs: Option[Long],
187
- grant: Option[LeaseGrant] = None
188
- ): Vector[io.circe.Json] => IO[Unit] =
189
- val leader = ObservationLead.leading(config.writerRole, config.leaseUrl)
190
- if config.leaseHeld && ObservationLead.ready(observationMs, segmentEndMs, leader) then historyAnnounce(sender, config, machine, grant)
191
- else (_: Vector[io.circe.Json]) => IO.unit
169
+ Stream(machineStreams(config, worker, seeding, checkpoint, publish, profileSegments = Some(profileSegments), writer = writer, observe = track(owners), outputs = Some(outputs),
170
+ decisionSegments = Some(segments))*).parJoinUnbounded
171
+ .concurrently(decisionStream(config, segments, owners))
192
172
 
193
173
  /**
194
174
  * Sources can replay checkpoint readings
195
175
  * after the cursor, then continue with the live subscription.
196
176
  *
197
177
  * {{{
198
- * SupervisorRuntime.sourced(machine, aliases, live, seeding)
178
+ * ProcessingApplication.sourced(machine, aliases, live, seeding)
199
179
  * }}}
200
180
  */
201
181
  private[runtime] def sourced(
@@ -204,17 +184,20 @@ open class SupervisorRuntime(profile: RuntimeProfile) extends IOApp:
204
184
  live: Stream[IO, Reading],
205
185
  seeding: Option[Seeding]
206
186
  ): Stream[IO, Reading] =
207
- val input = profile.readings(machine, live)
208
- seeding.fold(input)(_.seed(machine, profile.replayAliases(machine, aliases), input))
187
+ seeding.fold(live)(_.seed(machine, aliases, live))
209
188
 
210
189
  /** Holds one classifier per machine. The loser waits and tries the same lock again. */
211
- private def lease(url: Option[String], machine: String, leader: Boolean, body: Stream[IO, Unit]): Stream[IO, Unit] =
190
+ private def lease(url: Option[String], machine: String, leader: Boolean,
191
+ observe: (String, Option[Long]) => Resource[IO, Unit], body: Option[WorkerDatabase] => Stream[IO, Unit]): Stream[IO, Unit] =
212
192
  url match
213
- case None => body
193
+ case None => body(None)
214
194
  case Some(value) =>
215
195
  val attempt = Stream.resource(WriterLease.open(value, machine)).flatMap: hold =>
216
196
  Stream.eval(if hold.held && !leader then hold.ready(machine, false).map(_.isDefined) else IO.pure(false)).flatMap: caught =>
217
- if WriterGate.admit(hold.held, leader, caught) then body
197
+ if WriterGate.admit(hold.held, leader, caught) then
198
+ val database = hold.generation.map(token =>
199
+ WorkerDatabase(doobie.Transactor.fromConnection[IO](hold.connection, None), token))
200
+ Stream.resource(observe(machine, hold.generation)) >> body(database)
218
201
  else
219
202
  val reason = if hold.held then s"classifier waiting for telemetry on $machine" else s"classifier lease denied for $machine"
220
203
  Stream.exec(Logger[IO].info(reason)) ++ Stream.sleep_[IO](5.seconds)
@@ -222,13 +205,17 @@ open class SupervisorRuntime(profile: RuntimeProfile) extends IOApp:
222
205
 
223
206
  private[runtime] def machineStreams(
224
207
  config: AppConfig,
225
- supervisor: Supervisor[IO],
208
+ worker: ReadingWorker,
226
209
  seeding: Option[Seeding],
227
210
  checkpoint: Option[Checkpoint],
228
211
  sender: Option[StompSender] = None,
229
212
  observationMs: Long = 0L,
230
213
  segmentEndMs: Option[Long] = None,
231
- profileSegments: Option[CoreSegments[IO]] = None
214
+ profileSegments: Option[CoreSegments[IO]] = None,
215
+ writer: Option[TimelineWriter] = None,
216
+ observe: (String, Option[Long]) => Resource[IO, Unit] = (_, _) => Resource.unit[IO],
217
+ outputs: Option[OutputScope] = None,
218
+ decisionSegments: Option[CoreSegments[IO]] = None
232
219
  ): List[Stream[IO, Unit]] =
233
220
  config.machines.map: machine =>
234
221
  val aliases = config.routing.aliases.getOrElse(machine.id, Nil)
@@ -240,27 +227,42 @@ open class SupervisorRuntime(profile: RuntimeProfile) extends IOApp:
240
227
  case Some(_) if config.localHistory && config.leaseUrl.isEmpty && !ObservationLead.ready(observationMs, segmentEndMs, leader) =>
241
228
  Stream.never[IO]
242
229
  case Some(api) if config.localHistory =>
243
- HistoryRun(this, profile).gated(config, machine, aliases, sender, api, observationMs, segmentEndMs)
230
+ HistoryRun(profile, writer, observe,
231
+ (settings, source) => decisionSegments.fold(Stream.empty.covaryAll[IO, Unit])(
232
+ profile.decisions(settings, source, _))
233
+ ).gated(config, machine, aliases, sender, api, observationMs, segmentEndMs)
244
234
  case _ =>
245
- val body = profileSegments.flatMap(profile.live(config, machine, aliases, _, checkpoint, seeding)).getOrElse:
246
- val live = profile.input(config, machine, aliases).getOrElse(Mqtt(mqttCfg, aliases).subscribe)
247
- val readings = sourced(machine, aliases, live, seeding)
248
- Stream.eval(if machine.mode.isDefined then IO.pure(None) else PendingIsland.resolve(checkpoint, machine)).flatMap: initial =>
249
- Stream.eval(supervisor.run(machine, readings, initial))
250
- lease(config.leaseUrl, machine.id.raw, leader, body)
235
+ val body = (database: Option[WorkerDatabase]) =>
236
+ profileSegments.flatMap(profile.live(config, machine, aliases, _, checkpoint, seeding, outputs, database)).getOrElse:
237
+ val live = Mqtt(mqttCfg, aliases).subscribe
238
+ val readings = sourced(machine, aliases, live, seeding)
239
+ Stream.eval(if machine.mode.isDefined then IO.pure(None) else PendingIsland.resolve(checkpoint, machine)).flatMap: initial =>
240
+ Stream.eval(worker.run(machine, readings, initial))
241
+ val prepare = profileSegments.filter(_ => config.leaseUrl.nonEmpty && machine.mode.isEmpty).fold(IO.unit): segments =>
242
+ checkpoint.fold(IO.unit)(_.fetchPendingSegments.flatMap(rows =>
243
+ Orphans.list(rows.filter(_.machine == machine.id)).traverse_(Close.run(segments, _))))
244
+ lease(config.leaseUrl, machine.id.raw, leader, observe, database => Stream.exec(prepare) ++ body(database))
251
245
 
252
246
  private[runtime] def heed(decision: Decision, segments: CoreSegments[IO], tagDefs: List[TagDef]): IO[Unit] =
253
- decision.applyTo(segments, tagDefs, profile.tagging).handleErrorWith:
247
+ val write = decision.applyTo(segments, tagDefs, profile.tagging)
248
+ val scoped = decision match
249
+ case Decision.Resolve(machine, _, _, _) => segments.atRevision(machine)(write)
250
+ case Decision.Split(machine, _, _) => segments.atRevision(machine)(write)
251
+ case Decision.Skip(_) => write
252
+ scoped.handleErrorWith:
254
253
  case _: IllegalArgumentException => IO.unit
255
254
  case error => IO.raiseError(error)
256
255
 
257
- private def decisionStream(config: AppConfig, segments: CoreSegments[IO]): Stream[IO, Unit] =
258
- val byMachine = config.machines.map(m => m.id -> m).toMap
259
- StompDecisions(config.connectivity.rabbitmq).subscribe.evalMap: decision =>
260
- val machine = decision match
261
- case Decision.Resolve(id, _, _, _) => byMachine.get(id)
262
- case Decision.Split(id, _, _) => byMachine.get(id)
263
- case _ => None
264
- machine.flatMap(_.mode) match
265
- case Some(_) => IO.unit
266
- case None => heed(decision, segments, machine.fold(List.empty[TagDef])(_.tags))
256
+ private def decisionStream(config: AppConfig, segments: CoreSegments[IO], owners: Ref[IO, Map[String, Long]])
257
+ : Stream[IO, Unit] =
258
+ if !config.leaseHeld then Stream.empty
259
+ else
260
+ val byMachine = config.machines.map(m => m.id -> m).toMap
261
+ StompDecisions(config.connectivity.rabbitmq).subscribe.evalMap: decision =>
262
+ val target = decision match
263
+ case Decision.Resolve(id, _, _, _) => byMachine.get(id)
264
+ case Decision.Split(id, _, _) => byMachine.get(id)
265
+ case Decision.Skip(_) => None
266
+ target.filter(_.mode.isEmpty).fold(IO.unit): machine =>
267
+ owners.get.flatMap(current =>
268
+ IO.whenA(config.leaseUrl.isEmpty || current.contains(machine.id.raw))(heed(decision, segments, machine.tags)))
@@ -1,13 +1,14 @@
1
- package scada.supervisor.runtime
1
+ package scada.processing.runtime
2
2
 
3
3
  import cats.effect.IO
4
4
  import fs2.Stream
5
5
  import io.circe.Json
6
- import scada.supervisor.core.{MachineConfig, Reading, ReadingOverride, Segments, Tagging}
7
- import scada.supervisor.infra.checkpoint.Checkpoint
8
- import scada.supervisor.infra.config.{AliasMapping, AppConfig, CheckpointApiConfig, ConfigProfile}
9
- import scada.supervisor.infra.state.SegmentStatePolicy
10
- import scada.supervisor.infra.stomp.SegmentWirePolicy
6
+ import io.yarkivaev.streamworker.OutputScope
7
+ import scada.processing.core.{MachineConfig, Reading, ReadingOverride, Segments, Tagging}
8
+ import scada.processing.infra.checkpoint.Checkpoint
9
+ import scada.processing.infra.config.{AliasMapping, AppConfig, CheckpointApiConfig, ConfigProfile}
10
+ import scada.processing.infra.state.SegmentStatePolicy
11
+ import scada.processing.infra.stomp.SegmentWirePolicy
11
12
 
12
13
  /** Site overrides for configured machine modes. The default runs the shared classifier. */
13
14
  trait RuntimeProfile:
@@ -18,14 +19,11 @@ trait RuntimeProfile:
18
19
  def wirePolicy: SegmentWirePolicy = SegmentWirePolicy.default
19
20
  def historyProtocols: Vector[String] = Vector("preserve-known-suffix-v1")
20
21
  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
22
  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
23
+ checkpoint: Option[Checkpoint], seeding: Option[Seeding], outputs: Option[OutputScope], database: Option[WorkerDatabase]): Option[Stream[IO, Unit]] = None
24
+ def decisions(config: AppConfig, machine: MachineConfig, segments: Segments[IO]): Stream[IO, Unit] = Stream.empty
27
25
  def history(machine: MachineConfig, aliases: List[AliasMapping], api: CheckpointApiConfig,
28
- announce: Vector[Json] => IO[Unit]): Stream[IO, Unit] =
26
+ announce: Vector[Json] => IO[Unit], generation: Option[Long]): Stream[IO, Unit] =
29
27
  Stream.raiseError[IO](IllegalArgumentException(s"Unsupported history mode for ${machine.id.raw}"))
30
28
 
31
29
  object RuntimeProfile:
@@ -1,4 +1,4 @@
1
- package scada.supervisor.runtime
1
+ package scada.processing.runtime
2
2
 
3
3
  import cats.effect.{IO, Outcome}
4
4
  import cats.effect.std.Queue
@@ -6,9 +6,9 @@ import fs2.Stream
6
6
  import org.typelevel.log4cats.Logger
7
7
  import org.typelevel.log4cats.slf4j.Slf4jLogger
8
8
  import scala.concurrent.duration.*
9
- import scada.supervisor.core.{MachineConfig, MachineId, Params, Reading, Timestamp}
10
- import scada.supervisor.infra.checkpoint.{Checkpoint, RawReadingData}
11
- import scada.supervisor.infra.config.AliasMapping
9
+ import scada.processing.core.{MachineConfig, MachineId, Params, Reading, Timestamp}
10
+ import scada.processing.infra.checkpoint.{Checkpoint, RawReadingData}
11
+ import scada.processing.infra.config.AliasMapping
12
12
 
13
13
  /**
14
14
  * Seamless replay-then-live readings source for one machine.
@@ -0,0 +1,81 @@
1
+ package scada.processing.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 io.yarkivaev.streamworker.{OutputId, OutputScope}
12
+ import scada.processing.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))
@@ -0,0 +1,7 @@
1
+ package scada.processing.runtime
2
+
3
+ import cats.effect.IO
4
+ import doobie.Transactor
5
+
6
+ /** Checkpoint access supplied by the SCADA classifier lease. */
7
+ final case class WorkerDatabase(transactor: Transactor[IO], generation: Long)
@@ -1,4 +1,4 @@
1
- package scada.supervisor.runtime
1
+ package scada.processing.runtime
2
2
 
3
3
  /**
4
4
  * Accepts a segment only from the current etcd writer epoch.
@@ -1,4 +1,4 @@
1
- package scada.supervisor.runtime
1
+ package scada.processing.runtime
2
2
 
3
3
  /**
4
4
  * Decides whether one process may classify a machine.
@@ -1,4 +1,4 @@
1
- package scada.supervisor.runtime
1
+ package scada.processing.runtime
2
2
 
3
3
  import cats.effect.{IO, Resource}
4
4
  import java.sql.{Connection, DriverManager}
@@ -71,7 +71,7 @@ object WriterLease:
71
71
 
72
72
  /**
73
73
  * Epoch to publish. None means this process must not publish.
74
- * Some(None) is the legacy publisher with no epoch field.
74
+ * Some(None) allows an unleased sender to omit the epoch.
75
75
  *
76
76
  * {{{
77
77
  * WriterLease.publication(Some("postgres://127.0.0.1:1/scada"), Some(LeaseGrant(true, 7)), Some(1L))
@@ -129,16 +129,12 @@ object WriterLease:
129
129
 
130
130
  /** Reads the stored counter on this session and returns the generation the holder may stamp. */
131
131
  private def advance(connection: Connection, machine: String, held: Boolean): Option[Long] =
132
- val grant = claim(held, if held then counter(connection, machine) else 0L)
132
+ val grant = claim(held, if held then currentGeneration(connection, machine) else 0L)
133
133
  grant.foreach(item => remember(connection, machine, item.generation))
134
134
  grant.flatMap(_.epoch)
135
135
 
136
136
  /** Last generation issued for this machine, or zero when the lock has never been held. */
137
- private def counter(connection: Connection, machine: String): Long =
138
- val created = connection.prepareStatement("CREATE TABLE IF NOT EXISTS classifier_generation (machine text PRIMARY KEY, generation bigint NOT NULL)")
139
- try
140
- val _ = created.execute()
141
- finally created.close()
137
+ private def currentGeneration(connection: Connection, machine: String): Long =
142
138
  val query = connection.prepareStatement("SELECT generation FROM classifier_generation WHERE machine = ?")
143
139
  try
144
140
  query.setString(1, machine)
@@ -150,7 +146,13 @@ object WriterLease:
150
146
 
151
147
  /** Stores the generation this session just issued so the next hold is greater. */
152
148
  private def remember(connection: Connection, machine: String, generation: Long): Unit =
153
- val query = connection.prepareStatement("INSERT INTO classifier_generation (machine, generation) VALUES (?, ?) ON CONFLICT (machine) DO UPDATE SET generation = EXCLUDED.generation")
149
+ val stamped =
150
+ "INSERT INTO classifier_generation (machine, generation, holder_pid) VALUES (?, ?, pg_backend_pid()) " +
151
+ "ON CONFLICT (machine) DO UPDATE SET generation = EXCLUDED.generation, holder_pid = EXCLUDED.holder_pid"
152
+ writeGeneration(connection, machine, generation, stamped)
153
+
154
+ private def writeGeneration(connection: Connection, machine: String, generation: Long, sql: String): Unit =
155
+ val query = connection.prepareStatement(sql)
154
156
  try
155
157
  query.setString(1, machine)
156
158
  query.setLong(2, generation)
@@ -3,7 +3,7 @@ package scada.stream.replay
3
3
  import cats.effect.IO
4
4
  import cats.syntax.all.*
5
5
  import fs2.Stream
6
- import scada.stream.worker.{ProcessingError, Processor}
6
+ import io.yarkivaev.streamworker.{ProcessingError, Processor}
7
7
 
8
8
  /** A half-open range of offsets in the input snapshot. */
9
9
  final case class ReplayRange(from: Int, until: Int)
@@ -0,0 +1,2 @@
1
+ 0.1.0
2
+ 6672fd500fcc38776cf195df3a1dee76d45832b3b25b0bcd93131c9f5527da3b
@@ -1,8 +0,0 @@
1
- package scada.stream.worker
2
-
3
- final case class ProcessingError(message: String)
4
- final case class StepResult[S, O](state: S, outputs: Vector[O])
5
-
6
- /** A deterministic step over inputs already ordered by the source adapter. */
7
- trait Processor[C, S, I, O]:
8
- def step(config: C, state: S, event: I): Either[ProcessingError, StepResult[S, O]]