@yarkivaev/scada 2.7.1 → 2.9.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 (90) hide show
  1. package/README.md +4 -4
  2. package/package.json +8 -3
  3. package/stream-processing/dependencies/stream-worker.jar +0 -0
  4. package/stream-processing/dependencies/timeline-segmentation.jar +0 -0
  5. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/Decision.scala +2 -12
  6. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/MachineConfig.scala +2 -1
  7. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/MachineId.scala +1 -1
  8. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/MachineMode.scala +1 -1
  9. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/ReadingWorker.scala +17 -22
  10. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/Segments.scala +2 -1
  11. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/checkpoint/Checkpoint.scala +3 -2
  12. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/checkpoint/ClickhouseReadingsCheckpoint.scala +4 -3
  13. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/checkpoint/SupervisorSinkCheckpoint.scala +4 -3
  14. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/config/AppConfig.scala +3 -3
  15. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/config/ConfigLoad.scala +3 -2
  16. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/config/ConfigProfile.scala +2 -3
  17. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/mqtt/Mqtt.scala +3 -3
  18. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/mqtt/Sessions.scala +1 -1
  19. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/state/AtomicStateFile.scala +1 -1
  20. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/state/CheckpointSegments.scala +6 -5
  21. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/state/SegmentStatePolicy.scala +2 -3
  22. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/state/Segments.scala +4 -3
  23. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/ClassifyQueue.scala +2 -2
  24. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/DecisionMessage.scala +3 -3
  25. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/DurableStomp.scala +1 -1
  26. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/SegmentMessage.scala +3 -3
  27. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/SegmentWirePolicy.scala +2 -3
  28. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/SplitFamily.scala +3 -3
  29. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/StompConnection.scala +1 -1
  30. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/StompDecisions.scala +3 -3
  31. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/StompFrame.scala +1 -1
  32. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/StompMachineDecisions.scala +3 -3
  33. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/StompQueue.scala +1 -1
  34. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/StompReadings.scala +3 -3
  35. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/StompSegments.scala +5 -4
  36. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/ClassifyHistory.scala +4 -3
  37. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/ClassifyStreams.scala +43 -18
  38. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/Close.scala +4 -4
  39. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/HealthServer.scala +1 -1
  40. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/HistoryBus.scala +5 -4
  41. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/HistoryClient.scala +2 -2
  42. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/HistoryRun.scala +18 -14
  43. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/LocalHistory.scala +17 -65
  44. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/ObservationLead.scala +1 -1
  45. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/Orphans.scala +4 -4
  46. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/PendingIsland.scala +4 -3
  47. package/{supervisor-engine/src/main/scala/scada/supervisor/runtime/EngineApp.scala → stream-processing/src/main/scala/scada/processing/runtime/ProcessingApp.scala} +2 -2
  48. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/ProcessingApplication.scala +11 -22
  49. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/RuntimeProfile.scala +8 -8
  50. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/Seeding.scala +5 -4
  51. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/TimelineWriter.scala +3 -3
  52. package/{supervisor-engine/src/main/scala/scada/stream/worker/postgres → stream-processing/src/main/scala/scada/processing/runtime}/WorkerDatabase.scala +2 -2
  53. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/WriterEpoch.scala +1 -1
  54. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/WriterGate.scala +1 -1
  55. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/WriterLease.scala +4 -21
  56. package/{supervisor-engine → stream-processing}/src/main/scala/scada/stream/replay/Replay.scala +1 -1
  57. package/stream-processing/stream-worker.lock +2 -0
  58. package/stream-processing/timeline-segmentation.lock +2 -0
  59. package/supervisor-engine/src/main/scala/scada/stream/worker/OutputScope.scala +0 -13
  60. package/supervisor-engine/src/main/scala/scada/stream/worker/Processor.scala +0 -8
  61. package/supervisor-engine/src/main/scala/scada/stream/worker/StreamWorker.scala +0 -135
  62. package/supervisor-engine/src/main/scala/scada/stream/worker/postgres/PgCheckpointStore.scala +0 -83
  63. package/supervisor-engine/src/main/scala/scada/supervisor/core/Condition.scala +0 -33
  64. package/supervisor-engine/src/main/scala/scada/supervisor/core/CyclePhases.scala +0 -65
  65. package/supervisor-engine/src/main/scala/scada/supervisor/core/Emission.scala +0 -19
  66. package/supervisor-engine/src/main/scala/scada/supervisor/core/Params.scala +0 -15
  67. package/supervisor-engine/src/main/scala/scada/supervisor/core/Reading.scala +0 -11
  68. package/supervisor-engine/src/main/scala/scada/supervisor/core/Segment.scala +0 -28
  69. package/supervisor-engine/src/main/scala/scada/supervisor/core/SegmentDef.scala +0 -14
  70. package/supervisor-engine/src/main/scala/scada/supervisor/core/Segmentation.scala +0 -63
  71. package/supervisor-engine/src/main/scala/scada/supervisor/core/SplitFollow.scala +0 -50
  72. package/supervisor-engine/src/main/scala/scada/supervisor/core/SplitPieces.scala +0 -102
  73. package/supervisor-engine/src/main/scala/scada/supervisor/core/TagDef.scala +0 -12
  74. package/supervisor-engine/src/main/scala/scada/supervisor/core/TaggedSegment.scala +0 -19
  75. package/supervisor-engine/src/main/scala/scada/supervisor/core/Tagging.scala +0 -42
  76. package/supervisor-engine/src/main/scala/scada/supervisor/core/Timestamp.scala +0 -26
  77. package/supervisor-engine/src/main/scala/scada/supervisor/core/segmentation/Timeline.scala +0 -43
  78. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ClassifierCursors.scala +0 -58
  79. package/supervisor-engine/vendor/gaps-and-islands/UPSTREAM +0 -4
  80. package/supervisor-engine/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/Island.scala +0 -40
  81. package/supervisor-engine/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandEvent.scala +0 -55
  82. package/supervisor-engine/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandsFlow.scala +0 -127
  83. package/supervisor-engine/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandsPolicy.scala +0 -105
  84. package/supervisor-engine/vendor/temporal-streams/LICENSE +0 -21
  85. /package/{supervisor-engine/vendor/gaps-and-islands → stream-processing/vendor/temporal-streams}/LICENSE +0 -0
  86. /package/{supervisor-engine → stream-processing}/vendor/temporal-streams/UPSTREAM +0 -0
  87. /package/{supervisor-engine → stream-processing}/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/History.scala +0 -0
  88. /package/{supervisor-engine → stream-processing}/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/LocalStreams.scala +0 -0
  89. /package/{supervisor-engine → stream-processing}/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/Overlay.scala +0 -0
  90. /package/{supervisor-engine → stream-processing}/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/Worker.scala +0 -0
@@ -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
@@ -0,0 +1,2 @@
1
+ 0.1.0
2
+ 495505f53a60028903b212b765bf09b37a67f578191dfce29a662b00f20c09dc
@@ -1,13 +0,0 @@
1
- package scada.stream.worker
2
-
3
- import cats.effect.{IO, IOLocal}
4
-
5
- /** Carries the durable worker output ID through decorators that emit multiple wire messages. */
6
- final class OutputScope private (local: IOLocal[Option[OutputId]]):
7
- def current: IO[Option[OutputId]] = local.get
8
-
9
- def within[A](id: OutputId)(write: IO[A]): IO[A] =
10
- local.get.bracket(previous => local.set(Some(id)) *> write)(local.set)
11
-
12
- object OutputScope:
13
- def create: IO[OutputScope] = IOLocal(Option.empty[OutputId]).map(new OutputScope(_))
@@ -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]]
@@ -1,135 +0,0 @@
1
- package scada.stream.worker
2
-
3
- import cats.effect.{IO, Ref}
4
- import fs2.Stream
5
-
6
- final case class TaskIdentity(taskId: String, inputId: String, runId: String)
7
- final case class ProcessorVersion(implementation: String, rules: String, stateSchema: String)
8
-
9
- final case class OutputId(task: TaskIdentity, position: Long, index: Int)
10
- final case class Output[O](id: OutputId, value: O)
11
-
12
- /** Positions identify immutable records in one ordered input. An adapter must not skip unseen records. */
13
- final case class Delivery[I](position: Long, value: I, acknowledge: IO[Unit])
14
-
15
- final case class Checkpoint[S, O](
16
- task: TaskIdentity,
17
- version: ProcessorVersion,
18
- revision: Long,
19
- position: Option[Long],
20
- state: S,
21
- pendingOutputs: Vector[Output[O]]
22
- )
23
-
24
- final case class StaleOwnership(task: TaskIdentity, ownership: Long)
25
- extends RuntimeException(s"Ownership $ownership is stale for $task")
26
-
27
- final case class IncompatibleCheckpoint(
28
- expectedTask: TaskIdentity,
29
- expectedVersion: ProcessorVersion,
30
- actualTask: TaskIdentity,
31
- actualVersion: ProcessorVersion
32
- ) extends RuntimeException(
33
- s"Expected checkpoint for $expectedTask at $expectedVersion, found $actualTask at $actualVersion"
34
- )
35
-
36
- final case class StepFailed(error: ProcessingError) extends RuntimeException(error.message)
37
- final case class UnconfirmedOutputs(task: TaskIdentity)
38
- extends RuntimeException(s"Checkpoint for $task still has unconfirmed outputs")
39
-
40
- private[worker] object CheckpointCompatibility:
41
- def check(task: TaskIdentity, version: ProcessorVersion, actualTask: TaskIdentity, actualVersion: ProcessorVersion)
42
- : IO[Unit] =
43
- IO.raiseUnless(actualTask == task && actualVersion == version)(
44
- IncompatibleCheckpoint(task, version, actualTask, actualVersion)
45
- )
46
-
47
- trait CheckpointStore[S, O]:
48
- /** Load the checkpoint while validating current ownership. */
49
- def load(task: TaskIdentity, ownership: Long): IO[Checkpoint[S, O]]
50
-
51
- /** Validate the checkpoint version before consumption. Serialized stores can check the header first. */
52
- def loadCompatible(task: TaskIdentity, version: ProcessorVersion, ownership: Long): IO[Checkpoint[S, O]] =
53
- load(task, ownership).flatMap: checkpoint =>
54
- CheckpointCompatibility.check(task, version, checkpoint.task, checkpoint.version).as(checkpoint)
55
-
56
- /** Atomically validate ownership and revision, then replace the checkpoint. */
57
- def commit(ownership: Long, expectedRevision: Long, next: Checkpoint[S, O]): IO[Unit]
58
-
59
- object CheckpointStore:
60
- /** A session store for sources that recover by reseeding and cannot resume by delivery position. */
61
- def session[S, O](initial: Checkpoint[S, O], token: Long): IO[CheckpointStore[S, O]] =
62
- Ref.of[IO, Checkpoint[S, O]](initial).map: ref =>
63
- new CheckpointStore[S, O]:
64
- def load(task: TaskIdentity, ownership: Long): IO[Checkpoint[S, O]] =
65
- IO.raiseUnless(task == initial.task && ownership == token)(StaleOwnership(task, ownership)) *> ref.get
66
-
67
- def commit(ownership: Long, expectedRevision: Long, next: Checkpoint[S, O]): IO[Unit] =
68
- IO.raiseUnless(next.task == initial.task && ownership == token)(StaleOwnership(next.task, ownership)) *>
69
- ref.modify: current =>
70
- if current.revision == expectedRevision && next.revision == expectedRevision + 1 then
71
- (next, IO.unit)
72
- else (current, IO.raiseError(IllegalStateException("Session checkpoint revision changed")))
73
- .flatten
74
-
75
- /** Runtime for a deterministic processor. The sink checks ownership and deduplicates by OutputId. */
76
- final class StreamWorker[C, S, I, O](
77
- processor: Processor[C, S, I, O],
78
- store: CheckpointStore[S, O],
79
- publish: (Long, Output[O]) => IO[Unit]
80
- ):
81
- def run(task: TaskIdentity, version: ProcessorVersion, config: C, ownership: Long)(
82
- input: Option[Long] => Stream[IO, Delivery[I]]
83
- ): IO[Checkpoint[S, O]] =
84
- for
85
- checkpoint <- store.loadCompatible(task, version, ownership)
86
- start <- deliver(ownership, checkpoint)
87
- end <- input(start.position)
88
- .evalMapAccumulate(start): (current, event) =>
89
- process(config, ownership, current, event).map(next => (next, next))
90
- .map(_._2)
91
- .compile
92
- .last
93
- yield end.getOrElse(start)
94
-
95
- /** Change rules while input consumption is stopped, after confirming the previous version's outputs.
96
- * The current codec must be able to read the previous state.
97
- */
98
- def reconfigure(task: TaskIdentity, previous: ProcessorVersion, next: ProcessorVersion, ownership: Long)(
99
- migrate: S => Either[ProcessingError, S]
100
- ): IO[Checkpoint[S, O]] =
101
- for
102
- current <- store.loadCompatible(task, previous, ownership)
103
- _ <- IO.raiseWhen(current.pendingOutputs.nonEmpty)(UnconfirmedOutputs(task))
104
- migrated <- IO.defer(IO.fromEither(migrate(current.state).left.map(StepFailed.apply)))
105
- updated = current.copy(version = next, revision = current.revision + 1, state = migrated)
106
- _ <- store.commit(ownership, current.revision, updated)
107
- yield updated
108
-
109
- private def process(config: C, ownership: Long, current: Checkpoint[S, O], event: Delivery[I])
110
- : IO[Checkpoint[S, O]] =
111
- if current.position.exists(_ >= event.position) then event.acknowledge.as(current)
112
- else
113
- for
114
- result <- IO.defer(IO.fromEither(
115
- processor.step(config, current.state, event.value).left.map(StepFailed.apply)
116
- ))
117
- outputs = result.outputs.zipWithIndex.map: (value, index) =>
118
- Output(OutputId(current.task, event.position, index), value)
119
- updated = current.copy(
120
- revision = current.revision + 1,
121
- position = Some(event.position),
122
- state = result.state,
123
- pendingOutputs = outputs
124
- )
125
- _ <- store.commit(ownership, current.revision, updated)
126
- _ <- event.acknowledge
127
- delivered <- deliver(ownership, updated)
128
- yield delivered
129
-
130
- private def deliver(ownership: Long, current: Checkpoint[S, O]): IO[Checkpoint[S, O]] =
131
- if current.pendingOutputs.isEmpty then IO.pure(current)
132
- else
133
- val updated = current.copy(revision = current.revision + 1, pendingOutputs = Vector.empty[Output[O]])
134
- Stream.emits(current.pendingOutputs).evalMap(row => publish(ownership, row)).compile.drain *>
135
- store.commit(ownership, current.revision, updated).as(updated)
@@ -1,83 +0,0 @@
1
- package scada.stream.worker.postgres
2
-
3
- import cats.effect.IO
4
- import cats.syntax.all.*
5
- import doobie.*
6
- import doobie.implicits.*
7
- import io.circe.{Decoder, Encoder, Json}
8
- import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder}
9
- import io.circe.parser.parse
10
- import io.circe.syntax.*
11
- import scada.stream.worker.*
12
-
13
- final case class CheckpointConflict(task: TaskIdentity, expectedRevision: Long)
14
- extends RuntimeException(s"Checkpoint for $task is no longer at revision $expectedRevision")
15
-
16
- /** Shared storage for workers. The coordinator supplies strictly increasing ownership tokens. */
17
- final class PgCheckpointStore[S: Encoder: Decoder, O: Encoder: Decoder](xa: Transactor[IO])
18
- extends CheckpointStore[S, O]:
19
- private given CodecForTask: Encoder[TaskIdentity] = deriveEncoder
20
- private given DecodeTask: Decoder[TaskIdentity] = deriveDecoder
21
- private given EncodeVersion: Encoder[ProcessorVersion] = deriveEncoder
22
- private given DecodeVersion: Decoder[ProcessorVersion] = deriveDecoder
23
- private given EncodeId: Encoder[OutputId] = deriveEncoder
24
- private given DecodeId: Decoder[OutputId] = deriveDecoder
25
- private given EncodeOutput: Encoder[Output[O]] = deriveEncoder
26
- private given DecodeOutput: Decoder[Output[O]] = deriveDecoder
27
- private given EncodeCheckpoint: Encoder[Checkpoint[S, O]] = deriveEncoder
28
- private given DecodeCheckpoint: Decoder[Checkpoint[S, O]] = deriveDecoder
29
-
30
- /** Activate the coordinator's grant. A takeover keeps the previous checkpoint and pending output. */
31
- def claim(ownership: Long, initial: Checkpoint[S, O]): IO[Unit] =
32
- val task = initial.task
33
- val document = initial.asJson.noSpaces
34
- sql"""
35
- INSERT INTO stream_worker_checkpoint (task_id, input_id, run_id, ownership, revision, document)
36
- VALUES (${task.taskId}, ${task.inputId}, ${task.runId}, $ownership, ${initial.revision}, $document::jsonb)
37
- ON CONFLICT (task_id, input_id, run_id) DO UPDATE SET ownership = EXCLUDED.ownership
38
- WHERE stream_worker_checkpoint.ownership <= EXCLUDED.ownership
39
- """.update.run.transact(xa).flatMap(rows => IO.raiseWhen(rows != 1)(StaleOwnership(task, ownership)))
40
-
41
- def load(task: TaskIdentity, ownership: Long): IO[Checkpoint[S, O]] =
42
- document(task, ownership).flatMap(value => IO.fromEither(value.as[Checkpoint[S, O]]))
43
-
44
- override def loadCompatible(task: TaskIdentity, version: ProcessorVersion, ownership: Long)
45
- : IO[Checkpoint[S, O]] =
46
- for
47
- value <- document(task, ownership)
48
- actualTask <- IO.fromEither(value.hcursor.get[TaskIdentity]("task"))
49
- actualVersion <- IO.fromEither(value.hcursor.get[ProcessorVersion]("version"))
50
- _ <- CheckpointCompatibility.check(task, version, actualTask, actualVersion)
51
- checkpoint <- IO.fromEither(value.as[Checkpoint[S, O]])
52
- yield checkpoint
53
-
54
- private def document(task: TaskIdentity, ownership: Long): IO[Json] =
55
- sql"""
56
- SELECT document::text FROM stream_worker_checkpoint
57
- WHERE task_id = ${task.taskId} AND input_id = ${task.inputId} AND run_id = ${task.runId}
58
- AND ownership = $ownership
59
- """.query[String].option.transact(xa).flatMap:
60
- case Some(document) => IO.fromEither(parse(document))
61
- case None => IO.raiseError(StaleOwnership(task, ownership))
62
-
63
- def commit(ownership: Long, expectedRevision: Long, next: Checkpoint[S, O]): IO[Unit] =
64
- val task = next.task
65
- val document = next.asJson.noSpaces
66
- val update = sql"""
67
- UPDATE stream_worker_checkpoint SET revision = ${next.revision}, document = $document::jsonb
68
- WHERE task_id = ${task.taskId} AND input_id = ${task.inputId} AND run_id = ${task.runId}
69
- AND ownership = $ownership AND revision = $expectedRevision
70
- """.update.run
71
- if next.revision != expectedRevision + 1 then IO.raiseError(CheckpointConflict(task, expectedRevision))
72
- else
73
- val checked = update.flatMap:
74
- case 1 => ().pure[ConnectionIO]
75
- case _ =>
76
- sql"""
77
- SELECT ownership FROM stream_worker_checkpoint
78
- WHERE task_id = ${task.taskId} AND input_id = ${task.inputId} AND run_id = ${task.runId}
79
- """.query[Long].option.flatMap:
80
- case Some(active) if active == ownership =>
81
- CheckpointConflict(task, expectedRevision).raiseError[ConnectionIO, Unit]
82
- case _ => StaleOwnership(task, ownership).raiseError[ConnectionIO, Unit]
83
- checked.transact(xa)
@@ -1,33 +0,0 @@
1
- package scada.supervisor.core
2
-
3
- /**
4
- * Declarative predicate over a single [[Reading]]. Smart object:
5
- * every case answers [[matches]] for itself.
6
- *
7
- * `When(name)` delegates to the condition of the same-named
8
- * [[SegmentDef]]; callers pass a `lookup` function that resolves the
9
- * reference. In tagging context `When` is matched by name only, not
10
- * by evaluating this predicate.
11
- *
12
- * {{{
13
- * Condition.Above("power", 5.0).matches(Params(Map("power" -> 42.0)))
14
- * }}}
15
- */
16
- enum Condition:
17
- case Above(param: String, threshold: Double)
18
- case Below(param: String, threshold: Double)
19
- case Equal(param: String, value: Double)
20
- case And(left: Condition, right: Condition)
21
- case Or(left: Condition, right: Condition)
22
- case When(segmentName: String)
23
-
24
- def matches(params: Params): Boolean =
25
- matches(params, _ => None)
26
-
27
- def matches(params: Params, lookup: String => Option[Condition]): Boolean = this match
28
- case Above(param, threshold) => params.value(param).exists(_ >= threshold)
29
- case Below(param, threshold) => params.value(param).exists(_ < threshold)
30
- case Equal(param, value) => params.value(param).contains(value)
31
- case And(left, right) => left.matches(params, lookup) && right.matches(params, lookup)
32
- case Or(left, right) => left.matches(params, lookup) || right.matches(params, lookup)
33
- case When(name) => lookup(name).exists(_.matches(params, lookup))
@@ -1,65 +0,0 @@
1
- package scada.supervisor.core
2
-
3
- /**
4
- * One cycle phase loaded from HOCON: optional `enter` anchor and the
5
- * flat tag ids allowed while that phase is open.
6
- *
7
- * {{{
8
- * CyclePhase(List("cycle_start", "transfer", "repair"), None)
9
- * CyclePhase(List("transfer", "repair"), Some("ready"))
10
- * }}}
11
- */
12
- final case class CyclePhase(allow: List[String], enter: Option[String])
13
-
14
- /**
15
- * Anchor tag ids that close or advance a production cycle.
16
- *
17
- * {{{
18
- * CycleAnchors("cycle_start", List("planned_stop"))
19
- * }}}
20
- */
21
- final case class CycleAnchors(start: String, stop: List[String])
22
-
23
- /**
24
- * Cycle allowlists loaded from generated HOCON. Phase lookup uses
25
- * anchors of other segments; `flat` keeps HMI button order.
26
- *
27
- * {{{
28
- * phases.options(others)
29
- * phases.accept(others, standing, tags)
30
- * }}}
31
- */
32
- final case class CyclePhases(flat: List[String], anchors: CycleAnchors, phases: List[CyclePhase]):
33
- def isEmpty: Boolean = phases.isEmpty
34
-
35
- def options(others: List[TaggedSegment]): List[String] =
36
- val allowed = phaseOf(others).allow.toSet
37
- flat.filter(allowed.contains)
38
-
39
- def accept(others: List[TaggedSegment], standing: List[String], tags: List[String]): Boolean =
40
- if isEmpty then true
41
- else
42
- val ok = options(others).toSet ++ standing.toSet
43
- tags.forall(ok.contains)
44
-
45
- def narrow(segment: TaggedSegment, all: List[TaggedSegment]): TaggedSegment =
46
- if isEmpty || segment.segment.name != "off" then segment
47
- else
48
- val past = all.filter(_.segment.start.epoch < segment.segment.start.epoch)
49
- TaggedSegment(segment.segment, segment.tags, options(past :+ segment), segment.properties)
50
-
51
- private def phaseOf(others: List[TaggedSegment]): CyclePhase =
52
- val idle = phases.find(_.enter.isEmpty).getOrElse(CyclePhase(Nil, None))
53
- val tags = others.sortBy(_.segment.start).flatMap(_.tags)
54
- val lastStop = tags.lastIndexWhere(id => anchors.stop.contains(id))
55
- val lastStart = tags.lastIndexWhere(_ == anchors.start)
56
- if lastStart < 0 || lastStart < lastStop then idle
57
- else entered(tags.drop(lastStart + 1), idle)
58
-
59
- private def entered(after: List[String], idle: CyclePhase): CyclePhase =
60
- val last = after.reverse.find(id => phases.exists(_.enter.contains(id)))
61
- last.flatMap(id => phases.find(_.enter.contains(id))).getOrElse:
62
- phases.find(_.enter.contains(anchors.start)).getOrElse(idle)
63
-
64
- object CyclePhases:
65
- val empty: CyclePhases = CyclePhases(Nil, CycleAnchors("", Nil), Nil)
@@ -1,19 +0,0 @@
1
- package scada.supervisor.core
2
-
3
- /**
4
- * Lifecycle marker for a value flowing through the pipeline.
5
- *
6
- * `Started` carries a pending value whose boundaries may still grow;
7
- * `Emitted` carries the finalised value.
8
- *
9
- * {{{
10
- * Emission.Started(segment): Emission[Segment]
11
- * Emission.Emitted(segment): Emission[Segment]
12
- * }}}
13
- */
14
- sealed trait Emission[+A]:
15
- def value: A
16
-
17
- object Emission:
18
- final case class Started[A](value: A) extends Emission[A]
19
- final case class Emitted[A](value: A) extends Emission[A]
@@ -1,15 +0,0 @@
1
- package scada.supervisor.core
2
-
3
- /**
4
- * Immutable snapshot of the named metric values attached to one
5
- * [[Reading]]. Keys are metric names (as configured by routing);
6
- * values are raw sensor doubles.
7
- *
8
- * {{{
9
- * Params(Map("power" -> 0.95)).value("power")
10
- * }}}
11
- */
12
- final case class Params(values: Map[String, Double]):
13
- def value(key: String): Option[Double] = values.get(key)
14
-
15
- def merge(other: Params): Params = Params(values ++ other.values)
@@ -1,11 +0,0 @@
1
- package scada.supervisor.core
2
-
3
- /**
4
- * One sensor observation for a machine at one instant. The atomic
5
- * input of segmentation.
6
- *
7
- * {{{
8
- * Reading(Timestamp(1700000000.0), Params(Map("power" -> 42.0)))
9
- * }}}
10
- */
11
- final case class Reading(timestamp: Timestamp, params: Params)
@@ -1,28 +0,0 @@
1
- package scada.supervisor.core
2
-
3
- /**
4
- * A named, closed time interval produced by segmentation from a
5
- * contiguous run of readings that matched the same [[SegmentDef]].
6
- *
7
- * `duration == 0.0` marks a just-started (pending) segment whose
8
- * closing boundary a later reading will reveal.
9
- *
10
- * {{{
11
- * Segment("on", Timestamp(100.0), Timestamp(200.0), 100.0)
12
- * }}}
13
- */
14
- final case class Segment(
15
- name: String,
16
- start: Timestamp,
17
- end: Timestamp,
18
- duration: Double,
19
- properties: Map[String, String] = Map.empty
20
- )
21
-
22
- /**
23
- * Open-segment resume cursor from Postgres (`segments` row with
24
- * `duration = 0`). Fed into [[Segmentation]] as the initial
25
- * gaps-and-islands island; `end` may advance beyond `start` via
26
- * pending heartbeats.
27
- */
28
- final case class SegmentCursor(name: String, start: Timestamp, end: Timestamp)
@@ -1,14 +0,0 @@
1
- package scada.supervisor.core
2
-
3
- /**
4
- * One named segment kind for a machine: a label and the predicate
5
- * deciding whether a reading belongs to it.
6
- *
7
- * Order inside [[MachineConfig.segments]] is significant — the first
8
- * matching definition wins.
9
- *
10
- * {{{
11
- * SegmentDef("on", Condition.Above("power", 0.1))
12
- * }}}
13
- */
14
- final case class SegmentDef(name: String, condition: Condition)
@@ -1,63 +0,0 @@
1
- package scada.supervisor.core
2
-
3
- import cats.effect.Async
4
- import fs2.{Pipe, Stream}
5
- import scala.concurrent.duration.*
6
- import scada.stream.worker.{ProcessingError, Processor, StepResult}
7
- import scada.supervisor.core.segmentation.Timeline
8
- import scada.supervisor.core.segmentation.Timeline.{Boundary, Event, Interval, Output}
9
-
10
- final case class ReadingOverride(name: String, properties: Map[String, String])
11
-
12
- /** Merges same-time readings and applies the live interval policy.
13
- * Class changes close at the next phase's first sample. A gap over twice
14
- * the machine's window splits equal phases without inventing downtime.
15
- */
16
- final class Segmentation[F[_]: Async](overrideReading: Reading => Option[ReadingOverride] = _ => None)
17
- extends Processor[MachineConfig, Option[Interval[Reading]], Reading, Emission[Segment]]:
18
- private val unclassified = "unclassified"
19
-
20
- def flow(machine: MachineConfig, initial: Option[SegmentCursor] = None): Pipe[F, Reading, Emission[Segment]] =
21
- input =>
22
- gather(input).mapAccumulate(seed(initial)): (open, reading) =>
23
- val result = advance(machine, open, reading)
24
- (result.state, result.outputs)
25
- .flatMap((_, emissions) => Stream.emits(emissions))
26
-
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] =
45
- in.groupWithin(32, 50.millis).flatMap: chunk =>
46
- Stream.emits:
47
- chunk.toList.groupBy(_.timestamp.epoch).toList.sortBy(_._1).map: (_, rows) =>
48
- rows.reduce((left, right) => Reading(right.timestamp, left.params.merge(right.params)))
49
-
50
- private def toEmission(output: Output[Reading]): Option[Emission[Segment]] =
51
- def segment(interval: Interval[Reading], closed: Boolean): Segment =
52
- val start = interval.start.timestamp
53
- val end = interval.end.timestamp
54
- val duration = if closed then end.minus(start) else 0.0
55
- val properties = overrideReading(interval.end).fold(Map.empty[String, String])(_.properties)
56
- Segment(interval.name, start, end, duration, properties)
57
-
58
- output match
59
- case Output.Pending(interval) if interval.name != unclassified =>
60
- Some(Emission.Started(segment(interval, closed = false)))
61
- case Output.Closed(interval) if interval.name != unclassified =>
62
- Some(Emission.Emitted(segment(interval, closed = true)))
63
- case _ => None
@@ -1,50 +0,0 @@
1
- package scada.supervisor.core
2
-
3
- import scala.collection.immutable.SortedMap
4
-
5
- /**
6
- * Keeps a classifier heartbeat on an already split `off` island from
7
- * rewriting the closed pieces. The heartbeat still names the original
8
- * start. Only the open tail moves, and a later close finishes that tail.
9
- *
10
- * {{{
11
- * SplitFollow.project(rows, heartbeat)
12
- * }}}
13
- */
14
- object SplitFollow:
15
- def owned(rows: Iterable[TaggedSegment], incoming: TaggedSegment): Boolean =
16
- incoming.segment.name == "off" && family(rows, incoming).nonEmpty
17
-
18
- def project(
19
- rows: SortedMap[Timestamp, TaggedSegment],
20
- incoming: TaggedSegment
21
- ): SortedMap[Timestamp, TaggedSegment] =
22
- val pieces = family(rows.values, incoming)
23
- if pieces.isEmpty then rows
24
- else
25
- val tail = pieces.maxBy(_.segment.start.epoch)
26
- moved(tail, incoming) match
27
- case None => rows
28
- case Some(next) => rows.updated(tail.segment.start, next)
29
-
30
- def affected(incoming: TaggedSegment, rows: Iterable[TaggedSegment]): Option[TaggedSegment] =
31
- val pieces = family(rows, incoming)
32
- if incoming.segment.name != "off" || pieces.isEmpty then None
33
- else
34
- val tail = pieces.maxBy(_.segment.start.epoch)
35
- moved(tail, incoming).orElse(Some(tail))
36
-
37
- private def family(rows: Iterable[TaggedSegment], incoming: TaggedSegment): List[TaggedSegment] =
38
- val key = SplitPieces.originKey(incoming.segment.start)
39
- rows.filter(_.properties.get("split_of").contains(key)).toList
40
-
41
- private def moved(tail: TaggedSegment, incoming: TaggedSegment): Option[TaggedSegment] =
42
- val start = tail.segment.start
43
- if tail.segment.duration != 0.0 then None
44
- else if incoming.segment.duration == 0.0 then
45
- if !incoming.segment.end.isAfter(tail.segment.end) then None
46
- else Some(tail.copy(segment = tail.segment.copy(end = incoming.segment.end, duration = 0.0)))
47
- else if !incoming.segment.end.isAfter(start) then None
48
- else
49
- val end = incoming.segment.end
50
- Some(tail.copy(segment = Segment("off", start, end, end.minus(start))))