@yarkivaev/scada 2.7.0 → 2.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -4
- package/db/migrations/C0008__segment_write_receipts_grants.sql +1 -0
- package/db/migrations/E0019__segment_write_fence.sql +36 -0
- package/db/migrations/E0020__segment_write_fence_grants.sql +4 -0
- package/db/migrations/V0015__segment_write_receipts.sql +7 -0
- package/index.js +2 -0
- package/package.json +6 -3
- package/src/application/supervisorSink.js +15 -5
- package/src/domain/segment/segmentCoalesce.js +2 -1
- package/src/infrastructure/http/edge/edgeApi.js +1 -1
- package/src/infrastructure/http/edge/routes/history/historyRoutes.js +8 -3
- package/src/infrastructure/ingest/codecs/segmentCodec.js +26 -4
- package/src/infrastructure/ingest/db/migrationProfile.js +4 -1
- package/src/infrastructure/ingest/pipelines/segmentPipeline.js +11 -5
- package/src/infrastructure/ingest/sinks/fencedSegments.js +117 -0
- package/src/infrastructure/persistence/pg/history.js +4 -3
- package/src/infrastructure/persistence/pg/segmentWriteFence.js +112 -0
- package/stream-processing/dependencies/stream-worker.jar +0 -0
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/Condition.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/CyclePhases.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/Decision.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/Emission.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/MachineConfig.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/MachineId.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/MachineMode.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/Params.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/Reading.scala +1 -1
- package/stream-processing/src/main/scala/scada/processing/core/ReadingWorker.scala +82 -0
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/Segment.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/SegmentDef.scala +1 -1
- package/stream-processing/src/main/scala/scada/processing/core/Segmentation.scala +47 -0
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/Segments.scala +3 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/SplitFollow.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/SplitPieces.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/TagDef.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/TaggedSegment.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/Tagging.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/Timestamp.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/segmentation/Timeline.scala +2 -2
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/checkpoint/Checkpoint.scala +2 -2
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/checkpoint/ClickhouseReadingsCheckpoint.scala +3 -3
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/checkpoint/SupervisorSinkCheckpoint.scala +3 -3
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/config/AppConfig.scala +2 -2
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/config/ConfigLoad.scala +2 -2
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/config/ConfigProfile.scala +2 -2
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/mqtt/Mqtt.scala +3 -3
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/mqtt/Sessions.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/state/AtomicStateFile.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/state/CheckpointSegments.scala +7 -5
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/state/SegmentStatePolicy.scala +2 -2
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/state/Segments.scala +3 -3
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/ClassifyQueue.scala +4 -4
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/DecisionMessage.scala +2 -2
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/DurableStomp.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/SegmentMessage.scala +2 -2
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/SegmentWirePolicy.scala +2 -2
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/SplitFamily.scala +2 -2
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/StompConnection.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/StompDecisions.scala +3 -3
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/StompFrame.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/StompMachineDecisions.scala +3 -3
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/StompQueue.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/StompReadings.scala +3 -4
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/StompSegments.scala +20 -13
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/ClassifyHistory.scala +3 -3
- package/stream-processing/src/main/scala/scada/processing/runtime/ClassifyStreams.scala +128 -0
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/Close.scala +4 -4
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/HealthServer.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/HistoryBus.scala +40 -8
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/HistoryClient.scala +11 -4
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/HistoryRun.scala +42 -40
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/LocalHistory.scala +122 -36
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/ObservationLead.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/Orphans.scala +4 -4
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/PendingIsland.scala +3 -3
- package/stream-processing/src/main/scala/scada/processing/runtime/ProcessingApp.scala +8 -0
- package/{supervisor-engine/src/main/scala/scada/supervisor/runtime/SupervisorRuntime.scala → stream-processing/src/main/scala/scada/processing/runtime/ProcessingApplication.scala} +108 -106
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/RuntimeProfile.scala +10 -12
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/Seeding.scala +4 -4
- package/stream-processing/src/main/scala/scada/processing/runtime/TimelineWriter.scala +81 -0
- package/stream-processing/src/main/scala/scada/processing/runtime/WorkerDatabase.scala +7 -0
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/WriterEpoch.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/WriterGate.scala +1 -1
- package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/WriterLease.scala +11 -9
- package/{supervisor-engine → stream-processing}/src/main/scala/scada/stream/replay/Replay.scala +1 -1
- package/stream-processing/stream-worker.lock +2 -0
- package/supervisor-engine/src/main/scala/scada/stream/worker/Processor.scala +0 -8
- package/supervisor-engine/src/main/scala/scada/stream/worker/StreamWorker.scala +0 -119
- package/supervisor-engine/src/main/scala/scada/stream/worker/postgres/PgCheckpointStore.scala +0 -83
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Segmentation.scala +0 -52
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Supervisor.scala +0 -66
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ClassifierCursors.scala +0 -58
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ClassifyStreams.scala +0 -67
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/EngineApp.scala +0 -4
- /package/{supervisor-engine → stream-processing}/vendor/gaps-and-islands/LICENSE +0 -0
- /package/{supervisor-engine → stream-processing}/vendor/gaps-and-islands/UPSTREAM +0 -0
- /package/{supervisor-engine → stream-processing}/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/Island.scala +0 -0
- /package/{supervisor-engine → stream-processing}/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandEvent.scala +0 -0
- /package/{supervisor-engine → stream-processing}/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandsFlow.scala +0 -0
- /package/{supervisor-engine → stream-processing}/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandsPolicy.scala +0 -0
- /package/{supervisor-engine → stream-processing}/vendor/temporal-streams/LICENSE +0 -0
- /package/{supervisor-engine → stream-processing}/vendor/temporal-streams/UPSTREAM +0 -0
- /package/{supervisor-engine → stream-processing}/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/History.scala +0 -0
- /package/{supervisor-engine → stream-processing}/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/LocalStreams.scala +0 -0
- /package/{supervisor-engine → stream-processing}/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/Overlay.scala +0 -0
- /package/{supervisor-engine → stream-processing}/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/Worker.scala +0 -0
|
@@ -1,119 +0,0 @@
|
|
|
1
|
-
package scada.stream.worker
|
|
2
|
-
|
|
3
|
-
import cats.effect.IO
|
|
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
|
-
/** Runtime for a deterministic processor. The sink checks ownership and deduplicates by OutputId. */
|
|
60
|
-
final class StreamWorker[C, S, I, O](
|
|
61
|
-
processor: Processor[C, S, I, O],
|
|
62
|
-
store: CheckpointStore[S, O],
|
|
63
|
-
publish: (Long, Output[O]) => IO[Unit]
|
|
64
|
-
):
|
|
65
|
-
def run(task: TaskIdentity, version: ProcessorVersion, config: C, ownership: Long)(
|
|
66
|
-
input: Option[Long] => Stream[IO, Delivery[I]]
|
|
67
|
-
): IO[Checkpoint[S, O]] =
|
|
68
|
-
for
|
|
69
|
-
checkpoint <- store.loadCompatible(task, version, ownership)
|
|
70
|
-
start <- deliver(ownership, checkpoint)
|
|
71
|
-
end <- input(start.position)
|
|
72
|
-
.evalMapAccumulate(start): (current, event) =>
|
|
73
|
-
process(config, ownership, current, event).map(next => (next, next))
|
|
74
|
-
.map(_._2)
|
|
75
|
-
.compile
|
|
76
|
-
.last
|
|
77
|
-
yield end.getOrElse(start)
|
|
78
|
-
|
|
79
|
-
/** Change rules while input consumption is stopped, after confirming the previous version's outputs.
|
|
80
|
-
* The current codec must be able to read the previous state.
|
|
81
|
-
*/
|
|
82
|
-
def reconfigure(task: TaskIdentity, previous: ProcessorVersion, next: ProcessorVersion, ownership: Long)(
|
|
83
|
-
migrate: S => Either[ProcessingError, S]
|
|
84
|
-
): IO[Checkpoint[S, O]] =
|
|
85
|
-
for
|
|
86
|
-
current <- store.loadCompatible(task, previous, ownership)
|
|
87
|
-
_ <- IO.raiseWhen(current.pendingOutputs.nonEmpty)(UnconfirmedOutputs(task))
|
|
88
|
-
migrated <- IO.defer(IO.fromEither(migrate(current.state).left.map(StepFailed.apply)))
|
|
89
|
-
updated = current.copy(version = next, revision = current.revision + 1, state = migrated)
|
|
90
|
-
_ <- store.commit(ownership, current.revision, updated)
|
|
91
|
-
yield updated
|
|
92
|
-
|
|
93
|
-
private def process(config: C, ownership: Long, current: Checkpoint[S, O], event: Delivery[I])
|
|
94
|
-
: IO[Checkpoint[S, O]] =
|
|
95
|
-
if current.position.exists(_ >= event.position) then event.acknowledge.as(current)
|
|
96
|
-
else
|
|
97
|
-
for
|
|
98
|
-
result <- IO.defer(IO.fromEither(
|
|
99
|
-
processor.step(config, current.state, event.value).left.map(StepFailed.apply)
|
|
100
|
-
))
|
|
101
|
-
outputs = result.outputs.zipWithIndex.map: (value, index) =>
|
|
102
|
-
Output(OutputId(current.task, event.position, index), value)
|
|
103
|
-
updated = current.copy(
|
|
104
|
-
revision = current.revision + 1,
|
|
105
|
-
position = Some(event.position),
|
|
106
|
-
state = result.state,
|
|
107
|
-
pendingOutputs = outputs
|
|
108
|
-
)
|
|
109
|
-
_ <- store.commit(ownership, current.revision, updated)
|
|
110
|
-
_ <- event.acknowledge
|
|
111
|
-
delivered <- deliver(ownership, updated)
|
|
112
|
-
yield delivered
|
|
113
|
-
|
|
114
|
-
private def deliver(ownership: Long, current: Checkpoint[S, O]): IO[Checkpoint[S, O]] =
|
|
115
|
-
if current.pendingOutputs.isEmpty then IO.pure(current)
|
|
116
|
-
else
|
|
117
|
-
val updated = current.copy(revision = current.revision + 1, pendingOutputs = Vector.empty[Output[O]])
|
|
118
|
-
Stream.emits(current.pendingOutputs).evalMap(row => publish(ownership, row)).compile.drain *>
|
|
119
|
-
store.commit(ownership, current.revision, updated).as(updated)
|
package/supervisor-engine/src/main/scala/scada/stream/worker/postgres/PgCheckpointStore.scala
DELETED
|
@@ -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,52 +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.supervisor.core.segmentation.Timeline
|
|
7
|
-
import scada.supervisor.core.segmentation.Timeline.{Boundary, Event, Interval, Output}
|
|
8
|
-
|
|
9
|
-
final case class ReadingOverride(name: String, properties: Map[String, String])
|
|
10
|
-
|
|
11
|
-
/** Merges same-time readings and applies the live interval policy.
|
|
12
|
-
* Class changes close at the next phase's first sample. A gap over twice
|
|
13
|
-
* the machine's window splits equal phases without inventing downtime.
|
|
14
|
-
*/
|
|
15
|
-
final class Segmentation[F[_]: Async](overrideReading: Reading => Option[ReadingOverride] = _ => None):
|
|
16
|
-
private val unclassified = "unclassified"
|
|
17
|
-
|
|
18
|
-
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
|
-
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))
|
|
31
|
-
.flatMap((_, emissions) => Stream.emits(emissions))
|
|
32
|
-
|
|
33
|
-
private def gather(in: Stream[F, Reading]): Stream[F, Reading] =
|
|
34
|
-
in.groupWithin(32, 50.millis).flatMap: chunk =>
|
|
35
|
-
Stream.emits:
|
|
36
|
-
chunk.toList.groupBy(_.timestamp.epoch).toList.sortBy(_._1).map: (_, rows) =>
|
|
37
|
-
rows.reduce((left, right) => Reading(right.timestamp, left.params.merge(right.params)))
|
|
38
|
-
|
|
39
|
-
private def toEmission(output: Output[Reading]): Option[Emission[Segment]] =
|
|
40
|
-
def segment(interval: Interval[Reading], closed: Boolean): Segment =
|
|
41
|
-
val start = interval.start.timestamp
|
|
42
|
-
val end = interval.end.timestamp
|
|
43
|
-
val duration = if closed then end.minus(start) else 0.0
|
|
44
|
-
val properties = overrideReading(interval.end).fold(Map.empty[String, String])(_.properties)
|
|
45
|
-
Segment(interval.name, start, end, duration, properties)
|
|
46
|
-
|
|
47
|
-
output match
|
|
48
|
-
case Output.Pending(interval) if interval.name != unclassified =>
|
|
49
|
-
Some(Emission.Started(segment(interval, closed = false)))
|
|
50
|
-
case Output.Closed(interval) if interval.name != unclassified =>
|
|
51
|
-
Some(Emission.Emitted(segment(interval, closed = true)))
|
|
52
|
-
case _ => None
|
|
@@ -1,66 +0,0 @@
|
|
|
1
|
-
package scada.supervisor.core
|
|
2
|
-
|
|
3
|
-
import cats.effect.Async
|
|
4
|
-
import cats.syntax.all.*
|
|
5
|
-
import fs2.Stream
|
|
6
|
-
import scala.concurrent.duration.*
|
|
7
|
-
|
|
8
|
-
/**
|
|
9
|
-
* Per-machine processing loop. Takes readings in, emits
|
|
10
|
-
* [[TaggedSegment]]s through a [[Segments]] collection as each
|
|
11
|
-
* segment opens and closes.
|
|
12
|
-
*
|
|
13
|
-
* The outbound stream is supplied by the caller so the supervisor
|
|
14
|
-
* stays transport-agnostic (live MQTT, replay, or test feed all plug
|
|
15
|
-
* in through the same `readings` parameter).
|
|
16
|
-
*
|
|
17
|
-
* A restored pending island is written before live readings. While that
|
|
18
|
-
* island stays open, a one-second pulse advances `end` so a silent
|
|
19
|
-
* machine still heartbeats the tape instead of leaving a hole until now.
|
|
20
|
-
*
|
|
21
|
-
* {{{
|
|
22
|
-
* Supervisor[F](segmentation, tagging, segments).run(machine, readings, None)
|
|
23
|
-
* }}}
|
|
24
|
-
*/
|
|
25
|
-
final class Supervisor[F[_]: Async](
|
|
26
|
-
segmentation: Segmentation[F],
|
|
27
|
-
tagging: Tagging,
|
|
28
|
-
segments: Segments[F],
|
|
29
|
-
phases: CyclePhases = CyclePhases.empty,
|
|
30
|
-
customRun: Option[(MachineConfig, Stream[F, Reading], Segments[F]) => F[Unit]] = None
|
|
31
|
-
):
|
|
32
|
-
def run(machine: MachineConfig, readings: Stream[F, Reading], initial: Option[SegmentCursor] = None): F[Unit] =
|
|
33
|
-
if machine.mode.isDefined then
|
|
34
|
-
customRun.getOrElse(throw IllegalStateException("Machine mode has no configured runner"))(machine,readings,segments)
|
|
35
|
-
else
|
|
36
|
-
val classified = readings
|
|
37
|
-
.through(segmentation.flow(machine, initial))
|
|
38
|
-
.evalMap(emission => write(machine, tagging.resolve(machine.tags, emission.value)))
|
|
39
|
-
val beats = Stream.awakeEvery[F](1.second).evalMap(_ => pulse(machine)).drain
|
|
40
|
-
open(machine, initial) *> classified.mergeHaltL(beats).compile.drain
|
|
41
|
-
|
|
42
|
-
private def open(machine: MachineConfig, initial: Option[SegmentCursor]): F[Unit] =
|
|
43
|
-
initial.fold(Async[F].unit): cursor =>
|
|
44
|
-
write(machine, TaggedSegment(Segment(cursor.name, cursor.start, cursor.end, 0.0), Nil, Nil, Map.empty))
|
|
45
|
-
|
|
46
|
-
private def pulse(machine: MachineConfig): F[Unit] =
|
|
47
|
-
segments.list(machine.id).flatMap: rows =>
|
|
48
|
-
Async[F].realTime.map(_.toMillis).flatMap: millis =>
|
|
49
|
-
val now = Timestamp(millis.toDouble / 1000.0)
|
|
50
|
-
val open = rows.filter(_.segment.duration == 0).sortBy(_.segment.start.epoch).lastOption
|
|
51
|
-
open.fold(cover(machine, rows, now))(tagged => extend(machine, tagged, now))
|
|
52
|
-
|
|
53
|
-
private def extend(machine: MachineConfig, tagged: TaggedSegment, now: Timestamp): F[Unit] =
|
|
54
|
-
if now.isAfter(tagged.segment.end) then write(machine, tagged.copy(segment = tagged.segment.copy(end = now)))
|
|
55
|
-
else Async[F].unit
|
|
56
|
-
|
|
57
|
-
private def cover(machine: MachineConfig, rows: List[TaggedSegment], now: Timestamp): F[Unit] =
|
|
58
|
-
rows.sortBy(_.segment.end.epoch).lastOption.fold(Async[F].unit): last =>
|
|
59
|
-
if !now.isAfter(last.segment.end) then Async[F].unit
|
|
60
|
-
else write(machine, TaggedSegment(Segment(last.segment.name, last.segment.end, now, 0.0), Nil, Nil, Map.empty))
|
|
61
|
-
|
|
62
|
-
private def write(machine: MachineConfig, tagged: TaggedSegment): F[Unit] =
|
|
63
|
-
if phases.isEmpty then segments.upsert(machine.id, tagged)
|
|
64
|
-
else
|
|
65
|
-
segments.list(machine.id).flatMap: all =>
|
|
66
|
-
segments.upsert(machine.id, phases.narrow(tagged, all))
|
|
@@ -1,58 +0,0 @@
|
|
|
1
|
-
package scada.supervisor.runtime
|
|
2
|
-
|
|
3
|
-
import io.circe.Json
|
|
4
|
-
import io.circe.parser.parse
|
|
5
|
-
import io.yarkivaev.temporal.{Cursor, LocalStreams}
|
|
6
|
-
import java.sql.Connection
|
|
7
|
-
|
|
8
|
-
/**
|
|
9
|
-
* Persists LocalStreams cursor metadata for one machine. Telemetry
|
|
10
|
-
* points stay out of Postgres; only id, position and touchedAt remain.
|
|
11
|
-
*
|
|
12
|
-
* {{{
|
|
13
|
-
* ClassifierCursors.save(connection, "machine-2", pool)
|
|
14
|
-
* ClassifierCursors.load(connection, "machine-2", 30000, 10000)
|
|
15
|
-
* }}}
|
|
16
|
-
*/
|
|
17
|
-
object ClassifierCursors:
|
|
18
|
-
val ddl: String = "CREATE TABLE IF NOT EXISTS classifier_cursors (machine text PRIMARY KEY, snapshot text NOT NULL)"
|
|
19
|
-
val writeSql: String = "INSERT INTO classifier_cursors (machine, snapshot) VALUES (?, ?) ON CONFLICT (machine) DO UPDATE SET snapshot = EXCLUDED.snapshot"
|
|
20
|
-
val readSql: String = "SELECT snapshot FROM classifier_cursors WHERE machine = ?"
|
|
21
|
-
def save(connection: Connection, machine: String, pool: HistoryPool): Unit =
|
|
22
|
-
val created = connection.prepareStatement(ddl)
|
|
23
|
-
try created.execute()
|
|
24
|
-
finally created.close()
|
|
25
|
-
val statement = connection.prepareStatement(writeSql)
|
|
26
|
-
try
|
|
27
|
-
statement.setString(1, machine)
|
|
28
|
-
statement.setString(2, snapshot(pool).noSpaces)
|
|
29
|
-
val _ = statement.executeUpdate()
|
|
30
|
-
finally statement.close()
|
|
31
|
-
def load(connection: Connection, machine: String, maxGap: Long, idleTimeout: Long): HistoryPool =
|
|
32
|
-
val created = connection.prepareStatement(ddl)
|
|
33
|
-
try created.execute()
|
|
34
|
-
finally created.close()
|
|
35
|
-
val statement = connection.prepareStatement(readSql)
|
|
36
|
-
try
|
|
37
|
-
statement.setString(1, machine)
|
|
38
|
-
val rows = statement.executeQuery()
|
|
39
|
-
val pool = if rows.next() then restore(rows.getString(1), maxGap, idleTimeout) else HistoryPool(LocalStreams.empty(maxGap, idleTimeout), Map.empty)
|
|
40
|
-
rows.close()
|
|
41
|
-
pool
|
|
42
|
-
finally statement.close()
|
|
43
|
-
private def snapshot(pool: HistoryPool): Json =
|
|
44
|
-
Json.obj(
|
|
45
|
-
"nextId" -> Json.fromLong(pool.cursors.nextId),
|
|
46
|
-
"streams" -> Json.arr(pool.cursors.streams.map: cursor =>
|
|
47
|
-
Json.obj("id" -> Json.fromLong(cursor.id), "position" -> Json.fromLong(cursor.position), "touchedAt" -> Json.fromLong(cursor.touchedAt))
|
|
48
|
-
*)
|
|
49
|
-
)
|
|
50
|
-
private def restore(body: String, maxGap: Long, idleTimeout: Long): HistoryPool =
|
|
51
|
-
val json = parse(body).getOrElse(Json.obj())
|
|
52
|
-
val nextId = json.hcursor.get[Long]("nextId").getOrElse(1L)
|
|
53
|
-
val streams = json.hcursor.get[Vector[Json]]("streams").getOrElse(Vector.empty).flatMap: row =>
|
|
54
|
-
for
|
|
55
|
-
id <- row.hcursor.get[Long]("id").toOption
|
|
56
|
-
position <- row.hcursor.get[Long]("position").toOption
|
|
57
|
-
yield Cursor(id, position, System.currentTimeMillis())
|
|
58
|
-
HistoryPool(LocalStreams(maxGap, idleTimeout, nextId, streams, Vector.empty), Map.empty)
|
|
@@ -1,67 +0,0 @@
|
|
|
1
|
-
package scada.supervisor.runtime
|
|
2
|
-
|
|
3
|
-
import cats.effect.{IO, Ref}
|
|
4
|
-
import cats.syntax.all.*
|
|
5
|
-
import fs2.Stream
|
|
6
|
-
import io.circe.Json
|
|
7
|
-
import io.yarkivaev.temporal.{Conflict, Cursor, History, LocalStreams, Observation}
|
|
8
|
-
import java.time.Instant
|
|
9
|
-
import scada.supervisor.core.MachineConfig
|
|
10
|
-
|
|
11
|
-
/**
|
|
12
|
-
* Machine AMQP classification with independent event-time cursors.
|
|
13
|
-
* Telemetry stays in memory; Postgres only stores cursor metadata.
|
|
14
|
-
*
|
|
15
|
-
* {{{
|
|
16
|
-
* ClassifyStreams.start(machine, seed, announce).flatMap(_.accept(point))
|
|
17
|
-
* }}}
|
|
18
|
-
*/
|
|
19
|
-
final class ClassifyStreams(machine: MachineConfig, state: Ref[IO, StreamState], ports: ClassifyPorts, watermark: Option[Long]):
|
|
20
|
-
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] =
|
|
23
|
-
for
|
|
24
|
-
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)
|
|
29
|
-
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))
|
|
40
|
-
val page = ClassifyHistory.published(machine, existing, result, context)
|
|
41
|
-
ports.announce(page, historical)
|
|
42
|
-
|
|
43
|
-
final case class ClassifyPorts(persist: HistoryPool => IO[Unit], announce: (Vector[Json], Boolean) => IO[Unit], clock: IO[Long] = IO.realTime.map(_.toMillis))
|
|
44
|
-
final case class StreamState(pool: HistoryPool, tapes: Map[Long, History], stored: Vector[Json])
|
|
45
|
-
final case class RoutedPoint(cursor: Cursor, changed: Boolean)
|
|
46
|
-
|
|
47
|
-
object ClassifyStreams:
|
|
48
|
-
def start(machine: MachineConfig, seed: Vector[Json], announce: (Vector[Json], Boolean) => IO[Unit]): IO[ClassifyStreams] =
|
|
49
|
-
open(machine, seed, ClassifyPorts(_ => IO.unit, announce))
|
|
50
|
-
def open(machine: MachineConfig, seed: Vector[Json], ports: ClassifyPorts, watermark: Option[Long] = None, initial: Option[HistoryPool] = None): IO[ClassifyStreams] =
|
|
51
|
-
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))
|
|
53
|
-
private[runtime] def route(current: StreamState, point: Observation, now: Long, maxGap: Long): (StreamState, RoutedPoint) =
|
|
54
|
-
val gap = if current.pool.cursors.maxGap > 0 then current.pool.cursors.maxGap else maxGap
|
|
55
|
-
val idle = current.pool.cursors.idleTimeout
|
|
56
|
-
val evicted = current.pool.expire(now)
|
|
57
|
-
val routed = evicted.cursors.copy(maxGap = gap, idleTimeout = idle).route(point, now)
|
|
58
|
-
val kept = routed.state.copy(streams = routed.state.streams.takeRight(64))
|
|
59
|
-
val pool = HistoryPool(kept, evicted.states.filter((id, _) => kept.streams.exists(_.id == id)))
|
|
60
|
-
val history = current.tapes.getOrElse(routed.stream.id, History.empty)
|
|
61
|
-
val next = history.accept(point, Conflict.first)
|
|
62
|
-
val tapes = current.tapes.filter((id, _) => kept.streams.exists(_.id == id)).updated(routed.stream.id, next)
|
|
63
|
-
(StreamState(pool, tapes, current.stored), RoutedPoint(routed.stream, next.rows != history.rows))
|
|
64
|
-
private[runtime] def overlaps(row: Json, from: Long, until: Long): Boolean =
|
|
65
|
-
val start = row.hcursor.get[String]("start_time").toOption.map(Instant.parse(_).toEpochMilli).getOrElse(0L)
|
|
66
|
-
val end = row.hcursor.get[String]("end_time").toOption.map(Instant.parse(_).toEpochMilli).getOrElse(0L)
|
|
67
|
-
start <= until && end >= from
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|