@yarkivaev/scada 2.6.40 → 2.6.42
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 +13 -768
- package/db/migrations/E0018__stream_worker_checkpoint.sql +9 -0
- package/package.json +3 -1
- package/src/infrastructure/streams/README.md +12 -5
- package/supervisor-engine/src/main/scala/scada/stream/replay/Replay.scala +149 -0
- package/supervisor-engine/src/main/scala/scada/stream/worker/Processor.scala +8 -0
- package/supervisor-engine/src/main/scala/scada/stream/worker/StreamWorker.scala +119 -0
- package/supervisor-engine/src/main/scala/scada/stream/worker/postgres/PgCheckpointStore.scala +83 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Condition.scala +33 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/CyclePhases.scala +65 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Decision.scala +67 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Emission.scala +19 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/MachineConfig.scala +21 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/MachineId.scala +18 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/MachineMode.scala +4 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Params.scala +15 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Reading.scala +11 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Segment.scala +28 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/SegmentDef.scala +14 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Segmentation.scala +52 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Segments.scala +41 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/SplitFollow.scala +50 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/SplitPieces.scala +102 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Supervisor.scala +66 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/TagDef.scala +12 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/TaggedSegment.scala +19 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Tagging.scala +42 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Timestamp.scala +26 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/segmentation/Timeline.scala +43 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/checkpoint/Checkpoint.scala +61 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/checkpoint/ClickhouseReadingsCheckpoint.scala +76 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/checkpoint/SupervisorSinkCheckpoint.scala +141 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/config/AppConfig.scala +132 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/config/ConfigLoad.scala +202 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/config/ConfigProfile.scala +13 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/mqtt/Mqtt.scala +92 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/mqtt/Sessions.scala +18 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/state/AtomicStateFile.scala +24 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/state/CheckpointSegments.scala +59 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/state/SegmentStatePolicy.scala +18 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/state/Segments.scala +91 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/ClassifyQueue.scala +37 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/DecisionMessage.scala +49 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/DurableStomp.scala +27 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/SegmentMessage.scala +57 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/SegmentWirePolicy.scala +18 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/SplitFamily.scala +39 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompConnection.scala +106 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompDecisions.scala +43 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompFrame.scala +67 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompMachineDecisions.scala +16 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompQueue.scala +30 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompReadings.scala +29 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompSegments.scala +115 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ClassifierCursors.scala +58 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ClassifyHistory.scala +92 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ClassifyStreams.scala +67 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/Close.scala +23 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/EngineApp.scala +4 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/HealthServer.scala +38 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/HistoryBus.scala +67 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/HistoryClient.scala +23 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/HistoryRun.scala +86 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/LocalHistory.scala +258 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ObservationLead.scala +26 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/Orphans.scala +26 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/PendingIsland.scala +37 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/RuntimeProfile.scala +32 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/Seeding.scala +105 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/SupervisorRuntime.scala +266 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/WriterEpoch.scala +16 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/WriterGate.scala +35 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/WriterLease.scala +218 -0
- package/supervisor-engine/vendor/gaps-and-islands/LICENSE +21 -0
- package/supervisor-engine/vendor/gaps-and-islands/UPSTREAM +4 -0
- package/supervisor-engine/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/Island.scala +40 -0
- package/supervisor-engine/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandEvent.scala +55 -0
- package/supervisor-engine/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandsFlow.scala +127 -0
- package/supervisor-engine/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandsPolicy.scala +105 -0
- package/supervisor-engine/vendor/temporal-streams/LICENSE +21 -0
- package/supervisor-engine/vendor/temporal-streams/UPSTREAM +3 -0
- package/supervisor-engine/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/History.scala +30 -0
- package/supervisor-engine/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/LocalStreams.scala +27 -0
- package/supervisor-engine/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/Overlay.scala +15 -0
- package/supervisor-engine/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/Worker.scala +21 -0
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
CREATE TABLE IF NOT EXISTS stream_worker_checkpoint (
|
|
2
|
+
task_id text NOT NULL,
|
|
3
|
+
input_id text NOT NULL,
|
|
4
|
+
run_id text NOT NULL,
|
|
5
|
+
ownership bigint NOT NULL,
|
|
6
|
+
revision bigint NOT NULL CHECK (revision >= 0),
|
|
7
|
+
document jsonb NOT NULL,
|
|
8
|
+
PRIMARY KEY (task_id, input_id, run_id)
|
|
9
|
+
);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@yarkivaev/scada",
|
|
3
|
-
"version": "2.6.
|
|
3
|
+
"version": "2.6.42",
|
|
4
4
|
"description": "SCADA domain objects, state persistence, and plant monitoring",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -64,6 +64,8 @@
|
|
|
64
64
|
"index.js",
|
|
65
65
|
"charts/",
|
|
66
66
|
"db/",
|
|
67
|
+
"supervisor-engine/src/main/scala/",
|
|
68
|
+
"supervisor-engine/vendor/",
|
|
67
69
|
"src/"
|
|
68
70
|
]
|
|
69
71
|
}
|
|
@@ -1,7 +1,10 @@
|
|
|
1
|
-
|
|
1
|
+
[Documentation](../../../docs/README.md) / [Data collection](../../../docs/collect/README.md)
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
3
|
+
# Stream adapters
|
|
4
|
+
|
|
5
|
+
SCADA exports protocol and storage adapters through `@yarkivaev/scada/streams`.
|
|
6
|
+
|
|
7
|
+
Generic batching, circuit breakers and periodic sources come from `@yarkivaev/source-to-sink`.
|
|
5
8
|
|
|
6
9
|
## Components
|
|
7
10
|
|
|
@@ -63,8 +66,7 @@ in-flight acceptance before restart.
|
|
|
63
66
|
For testing or another port implementation, pass `openPort(device)`, returning a
|
|
64
67
|
port or promise for a port. The port supports EventEmitter `data`, `error` and
|
|
65
68
|
`close` events plus `close(callback)`. The default opens `serialport` lazily.
|
|
66
|
-
|
|
67
|
-
limit or pause the device.
|
|
69
|
+
The source pauses the stream during acceptance and bounds the pending chunks and bytes. See [bounded operations and shutdown](#bounded-operations-and-shutdown).
|
|
68
70
|
|
|
69
71
|
### Periodic collection
|
|
70
72
|
|
|
@@ -289,3 +291,8 @@ uncertain resource/outcome, and quarantine it rather than immediately reuse it.
|
|
|
289
291
|
## License
|
|
290
292
|
|
|
291
293
|
MIT
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
---
|
|
297
|
+
|
|
298
|
+
← [Durable delivery](../../../docs/collect/durable-delivery.md) · [Operations](../../../docs/operations/README.md) →
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
package scada.stream.replay
|
|
2
|
+
|
|
3
|
+
import cats.effect.IO
|
|
4
|
+
import cats.syntax.all.*
|
|
5
|
+
import fs2.Stream
|
|
6
|
+
import scada.stream.worker.{ProcessingError, Processor}
|
|
7
|
+
|
|
8
|
+
/** A half-open range of offsets in the input snapshot. */
|
|
9
|
+
final case class ReplayRange(from: Int, until: Int)
|
|
10
|
+
|
|
11
|
+
/** The adapter assigns an identity that uniquely names this immutable, ordered event vector.
|
|
12
|
+
* Event timestamps need not be unique because replay positions are vector offsets.
|
|
13
|
+
*/
|
|
14
|
+
final case class ReplayInput[I](id: String, events: Vector[I])
|
|
15
|
+
|
|
16
|
+
final case class ReplayManifest(
|
|
17
|
+
timeline: String,
|
|
18
|
+
range: ReplayRange,
|
|
19
|
+
rulesVersion: String,
|
|
20
|
+
inputId: String,
|
|
21
|
+
initialSeedId: String,
|
|
22
|
+
baseRevision: String,
|
|
23
|
+
runId: String
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
/** State immediately before the event at position. */
|
|
27
|
+
final case class ReplaySeed[+S](
|
|
28
|
+
id: String,
|
|
29
|
+
timeline: String,
|
|
30
|
+
rulesVersion: String,
|
|
31
|
+
inputId: String,
|
|
32
|
+
position: Int,
|
|
33
|
+
state: S
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
final case class ReplayOutput[O](position: Int, ordinal: Int, value: O)
|
|
37
|
+
|
|
38
|
+
final case class ReplayResult[S, O](
|
|
39
|
+
manifest: ReplayManifest,
|
|
40
|
+
outputs: Vector[ReplayOutput[O]],
|
|
41
|
+
terminalState: S
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
enum ReplayFailure:
|
|
45
|
+
case InvalidManifest(reason: String)
|
|
46
|
+
case InvalidSections
|
|
47
|
+
case BoundaryMismatch(position: Int)
|
|
48
|
+
case ProcessingFailed(position: Int, error: ProcessingError)
|
|
49
|
+
|
|
50
|
+
final class ReplayPlan[I, S] private[replay] (
|
|
51
|
+
val manifest: ReplayManifest,
|
|
52
|
+
private[replay] val input: ReplayInput[I],
|
|
53
|
+
private[replay] val sections: Vector[(ReplayRange, ReplaySeed[S])]
|
|
54
|
+
):
|
|
55
|
+
def ranges: Vector[ReplayRange] = sections.map(_._1)
|
|
56
|
+
|
|
57
|
+
private[replay] final case class SectionResult[I, S, O](
|
|
58
|
+
plan: ReplayPlan[I, S],
|
|
59
|
+
range: ReplayRange,
|
|
60
|
+
outputs: Vector[ReplayOutput[O]],
|
|
61
|
+
terminalState: S
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
object Replay:
|
|
65
|
+
def plan[I, S](
|
|
66
|
+
manifest: ReplayManifest,
|
|
67
|
+
input: ReplayInput[I],
|
|
68
|
+
initial: ReplaySeed[S],
|
|
69
|
+
cuts: Set[Int] = Set.empty,
|
|
70
|
+
boundarySeeds: Vector[ReplaySeed[S]] = Vector.empty
|
|
71
|
+
): Either[ReplayFailure, ReplayPlan[I, S]] =
|
|
72
|
+
val range = manifest.range
|
|
73
|
+
def compatible(seed: ReplaySeed[S]): Boolean =
|
|
74
|
+
seed.timeline == manifest.timeline && seed.rulesVersion == manifest.rulesVersion && seed.inputId == input.id
|
|
75
|
+
|
|
76
|
+
if manifest.inputId != input.id then
|
|
77
|
+
Left(ReplayFailure.InvalidManifest("Input identity does not match the manifest"))
|
|
78
|
+
else if range.from < 0 || range.from > range.until || range.until > input.events.size then
|
|
79
|
+
Left(ReplayFailure.InvalidManifest("Replay range is outside the input snapshot"))
|
|
80
|
+
else if !compatible(initial) || initial.id != manifest.initialSeedId || initial.position != range.from then
|
|
81
|
+
Left(ReplayFailure.InvalidManifest("Initial seed does not match the manifest"))
|
|
82
|
+
else if cuts.exists(position => position < range.from || position > range.until) then
|
|
83
|
+
Left(ReplayFailure.InvalidManifest("Section cut is outside the replay range"))
|
|
84
|
+
else
|
|
85
|
+
val boundaries = boundarySeeds.filter: seed =>
|
|
86
|
+
compatible(seed) && cuts(seed.position) && seed.position > range.from && seed.position < range.until
|
|
87
|
+
// A cut without a unique compatible seed stays in the preceding section.
|
|
88
|
+
val seededCuts = boundaries.groupBy(_.position).values.collect:
|
|
89
|
+
case Vector(seed) => seed
|
|
90
|
+
val starts = initial +: seededCuts.toVector.sortBy(_.position)
|
|
91
|
+
val ends = starts.tail.map(_.position) :+ range.until
|
|
92
|
+
val sections = starts.zip(ends).map: (seed, until) =>
|
|
93
|
+
ReplayRange(seed.position, until) -> seed
|
|
94
|
+
Right(new ReplayPlan(manifest, input, sections))
|
|
95
|
+
|
|
96
|
+
/** Returns a proposal after every section succeeds and all boundaries agree.
|
|
97
|
+
* The processor, versioned configuration, input, and states must be deterministic and
|
|
98
|
+
* immutable. State equality must compare every value that can affect a later step.
|
|
99
|
+
*/
|
|
100
|
+
def run[C, S, I, O](
|
|
101
|
+
plan: ReplayPlan[I, S],
|
|
102
|
+
config: C,
|
|
103
|
+
processor: Processor[C, S, I, O],
|
|
104
|
+
parallelism: Int = 1
|
|
105
|
+
): IO[Either[ReplayFailure, ReplayResult[S, O]]] =
|
|
106
|
+
if parallelism < 1 then IO.pure(Left(ReplayFailure.InvalidManifest("Parallelism must be positive")))
|
|
107
|
+
else
|
|
108
|
+
Stream.emits(plan.ranges).covary[IO]
|
|
109
|
+
.parEvalMap(parallelism)(range => runSection(plan, range, config, processor))
|
|
110
|
+
.compile.toVector
|
|
111
|
+
.map(_.sequence.flatMap(results => gather(plan, results)))
|
|
112
|
+
|
|
113
|
+
private[replay] def runSection[C, S, I, O](
|
|
114
|
+
plan: ReplayPlan[I, S],
|
|
115
|
+
range: ReplayRange,
|
|
116
|
+
config: C,
|
|
117
|
+
processor: Processor[C, S, I, O]
|
|
118
|
+
): IO[Either[ReplayFailure, SectionResult[I, S, O]]] =
|
|
119
|
+
plan.sections.find(_._1 == range) match
|
|
120
|
+
case None => IO.pure(Left(ReplayFailure.InvalidSections))
|
|
121
|
+
case Some((_, seed)) =>
|
|
122
|
+
IO.defer:
|
|
123
|
+
val outputs = Vector.newBuilder[ReplayOutput[O]]
|
|
124
|
+
def advance(position: Int, state: S): IO[Either[ReplayFailure, SectionResult[I, S, O]]] =
|
|
125
|
+
if position == range.until then
|
|
126
|
+
IO.pure(Right(SectionResult(plan, range, outputs.result(), state)))
|
|
127
|
+
else
|
|
128
|
+
IO.defer:
|
|
129
|
+
processor.step(config, state, plan.input.events(position)) match
|
|
130
|
+
case Left(error) => IO.pure(Left(ReplayFailure.ProcessingFailed(position, error)))
|
|
131
|
+
case Right(result) =>
|
|
132
|
+
outputs ++= result.outputs.iterator.zipWithIndex.map: (value, ordinal) =>
|
|
133
|
+
ReplayOutput(position, ordinal, value)
|
|
134
|
+
advance(position + 1, result.state)
|
|
135
|
+
advance(range.from, seed.state)
|
|
136
|
+
|
|
137
|
+
private[replay] def gather[I, S, O](
|
|
138
|
+
plan: ReplayPlan[I, S],
|
|
139
|
+
results: Vector[SectionResult[I, S, O]]
|
|
140
|
+
): Either[ReplayFailure, ReplayResult[S, O]] =
|
|
141
|
+
val ordered = results.sortBy(_.range.from)
|
|
142
|
+
if ordered.map(_.range) != plan.ranges || ordered.exists(result => result.plan ne plan) then
|
|
143
|
+
Left(ReplayFailure.InvalidSections)
|
|
144
|
+
else
|
|
145
|
+
val mismatched = ordered.zip(plan.sections.drop(1)).collectFirst:
|
|
146
|
+
case (result, (range, seed)) if result.terminalState != seed.state => range.from
|
|
147
|
+
mismatched match
|
|
148
|
+
case Some(position) => Left(ReplayFailure.BoundaryMismatch(position))
|
|
149
|
+
case None => Right(ReplayResult(plan.manifest, ordered.flatMap(_.outputs), ordered.last.terminalState))
|
|
@@ -0,0 +1,8 @@
|
|
|
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]]
|
|
@@ -0,0 +1,119 @@
|
|
|
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)
|
|
@@ -0,0 +1,83 @@
|
|
|
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)
|
|
@@ -0,0 +1,33 @@
|
|
|
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))
|
|
@@ -0,0 +1,65 @@
|
|
|
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)
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
package scada.supervisor.core
|
|
2
|
+
|
|
3
|
+
import cats.Monad
|
|
4
|
+
import cats.MonadThrow
|
|
5
|
+
import cats.syntax.all.*
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Operator response to a pending [[TaggedSegment]]. Smart object: the
|
|
9
|
+
* decision knows how to apply itself to a [[Segments]] collection.
|
|
10
|
+
*
|
|
11
|
+
* - `Resolve`: retag via [[Tagging]] cascade (path + next options);
|
|
12
|
+
* - `Split`: replace the open segment with contiguous sub-segments;
|
|
13
|
+
* - `Skip`: dismiss the pending prompt without touching storage.
|
|
14
|
+
*
|
|
15
|
+
* {{{
|
|
16
|
+
* decision.applyTo(segments, tagDefs)
|
|
17
|
+
* }}}
|
|
18
|
+
*/
|
|
19
|
+
enum Decision:
|
|
20
|
+
case Resolve(machine: MachineId, start: Timestamp, tags: List[String], properties: Map[String, String])
|
|
21
|
+
case Split(machine: MachineId, start: Timestamp, entries: List[SplitEntry])
|
|
22
|
+
case Skip(id: String)
|
|
23
|
+
|
|
24
|
+
def applyTo[F[_]: MonadThrow](segments: Segments[F]): F[Unit] =
|
|
25
|
+
applyTo(segments, Nil)
|
|
26
|
+
|
|
27
|
+
def applyTo[F[_]: MonadThrow](segments: Segments[F], tagDefs: List[TagDef], tagging: Tagging = Tagging()): F[Unit] = this match
|
|
28
|
+
case Resolve(machine, start, tags, properties) =>
|
|
29
|
+
segments.find(machine, start).flatMap:
|
|
30
|
+
case None => Monad[F].unit
|
|
31
|
+
case Some(seg) => retag(segments, tagDefs, machine, tags, properties, seg, tagging)
|
|
32
|
+
|
|
33
|
+
case Split(machine, start, entries) =>
|
|
34
|
+
(segments.find(machine, start), segments.list(machine)).tupled.flatMap:
|
|
35
|
+
case (None, _) => Monad[F].unit
|
|
36
|
+
case (Some(seg), rows) =>
|
|
37
|
+
val parent = SplitPieces.span(seg, rows, entries)
|
|
38
|
+
try
|
|
39
|
+
val written = SplitPieces.materialize(parent, entries)
|
|
40
|
+
segments.replace(machine, parent.start, parent.end, written)
|
|
41
|
+
catch
|
|
42
|
+
case err: IllegalArgumentException => MonadThrow[F].raiseError(err)
|
|
43
|
+
|
|
44
|
+
case Skip(_) => Monad[F].unit
|
|
45
|
+
|
|
46
|
+
private def retag[F[_]](
|
|
47
|
+
segments: Segments[F],
|
|
48
|
+
tagDefs: List[TagDef],
|
|
49
|
+
machine: MachineId,
|
|
50
|
+
tags: List[String],
|
|
51
|
+
properties: Map[String, String],
|
|
52
|
+
seg: TaggedSegment,
|
|
53
|
+
tagging: Tagging
|
|
54
|
+
): F[Unit] =
|
|
55
|
+
val cascaded = tagging.resolve(tagDefs, seg.segment, tags)
|
|
56
|
+
segments.resolve(machine, seg.segment, cascaded.tags, cascaded.options, properties)
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* One piece of a [[Decision.Split]]. `tag` may be empty when the
|
|
60
|
+
* operator does not know the reason. `open` marks the live tail.
|
|
61
|
+
*
|
|
62
|
+
* {{{
|
|
63
|
+
* SplitEntry(Timestamp(100.0), Timestamp(160.0), "maintenance")
|
|
64
|
+
* }}}
|
|
65
|
+
*/
|
|
66
|
+
final case class SplitEntry(start: Timestamp, end: Timestamp, tag: String, open: Boolean = false):
|
|
67
|
+
def tagged: TaggedSegment = SplitPieces.row(start, this)
|
|
@@ -0,0 +1,19 @@
|
|
|
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]
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
package scada.supervisor.core
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Per-machine supervision configuration.
|
|
5
|
+
*
|
|
6
|
+
* `window` is the nominal sampling window in seconds. Live classification
|
|
7
|
+
* follows observation timestamps only: a quiet source does not close
|
|
8
|
+
* the open segment. A timestamp jump wider than `window * 2` starts a
|
|
9
|
+
* new same-kind island and does not invent downtime.
|
|
10
|
+
*
|
|
11
|
+
* {{{
|
|
12
|
+
* MachineConfig(MachineId("machine-1"), List(...), List(...), 15)
|
|
13
|
+
* }}}
|
|
14
|
+
*/
|
|
15
|
+
final case class MachineConfig(
|
|
16
|
+
id: MachineId,
|
|
17
|
+
segments: List[SegmentDef],
|
|
18
|
+
tags: List[TagDef],
|
|
19
|
+
window: Int,
|
|
20
|
+
mode: Option[MachineMode] = None
|
|
21
|
+
)
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
package scada.supervisor.core
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Type-safe identifier for a supervised machine. Opaque over
|
|
5
|
+
* [[String]] so machine ids cannot be mixed up with topic strings,
|
|
6
|
+
* metric names, or tag names at the type level.
|
|
7
|
+
*
|
|
8
|
+
* {{{
|
|
9
|
+
* val id = MachineId("machine-1")
|
|
10
|
+
* id.raw
|
|
11
|
+
* }}}
|
|
12
|
+
*/
|
|
13
|
+
opaque type MachineId = String
|
|
14
|
+
|
|
15
|
+
object MachineId:
|
|
16
|
+
def apply(raw: String): MachineId = raw
|
|
17
|
+
|
|
18
|
+
extension (self: MachineId) def raw: String = self
|
|
@@ -0,0 +1,15 @@
|
|
|
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)
|