@yarkivaev/scada 2.6.41 → 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.
@@ -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.41",
3
+ "version": "2.6.42",
4
4
  "description": "SCADA domain objects, state persistence, and plant monitoring",
5
5
  "repository": {
6
6
  "type": "git",
@@ -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)
@@ -1,54 +1,34 @@
1
1
  package scada.supervisor.core
2
2
 
3
- import cats.Applicative
4
- import cats.effect.{Async, Ref}
3
+ import cats.effect.Async
5
4
  import fs2.{Pipe, Stream}
6
5
  import scala.concurrent.duration.*
7
- import yarkivaev.gapsandislands.api.*
6
+ import scada.supervisor.core.segmentation.Timeline
7
+ import scada.supervisor.core.segmentation.Timeline.{Boundary, Event, Interval, Output}
8
8
 
9
- /**
10
- * Stateless classifier building an `fs2.Pipe` from readings to
11
- * [[Emission]]s of [[Segment]]s. Delegates the event-loop entirely to
12
- * `gaps-and-islands`; no per-machine state leaks outside the returned
13
- * pipe.
14
- *
15
- * Classification picks the first [[SegmentDef]] whose condition
16
- * matches; a missing match extends the currently open segment (or
17
- * emits the `unclassified` sentinel at stream start). Same-timestamp
18
- * MQTT metrics are merged before classification so a voltage heartbeat
19
- * cannot hide a low `power` that arrived in the same instant.
20
- * Island identity follows classification and a gap longer than
21
- * `machine.window * 2` seconds. A kind change holds the closed island
22
- * until the next sample so a 5 s sensor polling period cannot punch a hole in
23
- * the tape. A timestamp jump without an `off` in the stream does not
24
- * open a downtime island: the previous island closes and a new pending
25
- * island of the same kind starts at the later reading. A site can override
26
- * the class and properties of a reading before rules are evaluated.
27
- *
28
- * {{{
29
- * readings.through(Segmentation[F]().flow(machine, None))
30
- * }}}
31
- */
32
9
  final case class ReadingOverride(name: String, properties: Map[String, String])
33
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
+ */
34
15
  final class Segmentation[F[_]: Async](overrideReading: Reading => Option[ReadingOverride] = _ => None):
35
- import Segmentation.{Evidence, Kind, unclassified}
16
+ private val unclassified = "unclassified"
36
17
 
37
18
  def flow(machine: MachineConfig, initial: Option[SegmentCursor] = None): Pipe[F, Reading, Emission[Segment]] =
38
- (in: Stream[F, Reading]) =>
39
- Stream.eval(Ref.of[F, Int](0)).flatMap: gap =>
40
- val maxGap = machine.window.toDouble * 2.0
41
- val evidence: (Option[Island[Reading, Kind]], Reading) => Evidence = (prev, r) => (prev, r)
42
- gather(in).through(
43
- IslandsFlow.pipe(
44
- policy(machine.segments, gap, maxGap),
45
- evidence,
46
- initial.map(Segmentation.toIsland)
47
- )
48
- )
49
- .through(abutKindChange)
50
- .map(toEmission)
51
- .unNone
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))
52
32
 
53
33
  private def gather(in: Stream[F, Reading]): Stream[F, Reading] =
54
34
  in.groupWithin(32, 50.millis).flatMap: chunk =>
@@ -56,82 +36,17 @@ final class Segmentation[F[_]: Async](overrideReading: Reading => Option[Reading
56
36
  chunk.toList.groupBy(_.timestamp.epoch).toList.sortBy(_._1).map: (_, rows) =>
57
37
  rows.reduce((left, right) => Reading(right.timestamp, left.params.merge(right.params)))
58
38
 
59
- private def policy(defs: List[SegmentDef], gap: Ref[F, Int], maxGap: Double): IslandsPolicy[F, Evidence, Kind] =
60
- for
61
- name <- classification(defs)
62
- session <- gapSession(gap, maxGap)
63
- yield (name, session)
64
-
65
- private def classification(defs: List[SegmentDef]): IslandsPolicy[F, Evidence, String] =
66
- val lookup: String => Option[Condition] = name => defs.find(_.name == name).map(_.condition)
67
- IslandsPolicy: (prev, reading) =>
68
- Applicative[F].pure:
69
- overrideReading(reading).map(_.name)
70
- .orElse(defs.find(_.condition.matches(reading.params, lookup)).map(_.name))
71
- .orElse(prev.map(_.kind._1)).getOrElse(unclassified)
72
-
73
- private def gapSession(gap: Ref[F, Int], maxGap: Double): IslandsPolicy[F, Evidence, Int] =
74
- IslandsPolicy: (prev, reading) =>
75
- prev match
76
- case None => gap.get
77
- case Some(island) =>
78
- val delta = reading.timestamp.minus(island.last.timestamp)
79
- if delta > maxGap then gap.updateAndGet(_ + 1)
80
- else gap.get
81
-
82
- private def abutKindChange(in: Stream[F, IslandEvent[Reading, Kind]]): Stream[F, IslandEvent[Reading, Kind]] =
83
- Stream.eval(Ref.of[F, Option[Island[Reading, Kind]]](None)).flatMap: held =>
84
- val body: Stream[F, IslandEvent[Reading, Kind]] = in.flatMap: event =>
85
- event match
86
- case IslandEvent.IslandClosed(closed) =>
87
- Stream.exec(held.set(Some(closed)))
88
- case started @ IslandEvent.IslandStarted(open) =>
89
- Stream.eval(held.getAndSet(None)).flatMap:
90
- case Some(closed) if closed.kind._1 != open.kind._1 =>
91
- Stream.emit(IslandEvent.IslandClosed(Island(closed.kind, closed.first, open.first)))
92
- ++ Stream.emit(started)
93
- case Some(closed) =>
94
- Stream.emit(IslandEvent.IslandClosed(closed)) ++ Stream.emit(started)
95
- case None =>
96
- Stream.emit(started)
97
- case other =>
98
- Stream.eval(held.getAndSet(None)).flatMap:
99
- case Some(closed) => Stream.emit(IslandEvent.IslandClosed(closed)) ++ Stream.emit(other)
100
- case None => Stream.emit(other)
101
- val rest: Stream[F, IslandEvent[Reading, Kind]] = Stream.eval(held.get).flatMap:
102
- case Some(closed) => Stream.emit(IslandEvent.IslandClosed(closed))
103
- case None => Stream.empty
104
- body ++ rest
105
-
106
- private def toEmission(event: IslandEvent[Reading, Kind]): Option[Emission[Segment]] =
107
- event match
108
- case IslandEvent.IslandStarted(island) if island.kind._1 != unclassified =>
109
- Some(Emission.Started(toPending(island)))
110
- case IslandEvent.IslandExtended(island) if island.kind._1 != unclassified =>
111
- Some(Emission.Started(toPending(island)))
112
- case IslandEvent.IslandClosed(island) if island.kind._1 != unclassified =>
113
- Some(Emission.Emitted(toSegment(island)))
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)))
114
52
  case _ => None
115
-
116
- private def toPending(island: Island[Reading, Kind]): Segment =
117
- val start = island.first.timestamp
118
- val end = island.last.timestamp
119
- Segment(island.kind._1, start, end, 0.0, cover(island.last))
120
-
121
- private def toSegment(island: Island[Reading, Kind]): Segment =
122
- val start = island.first.timestamp
123
- val end = island.last.timestamp
124
- Segment(island.kind._1, start, end, end.minus(start), cover(island.last))
125
-
126
- private def cover(reading: Reading): Map[String, String] =
127
- overrideReading(reading).fold(Map.empty[String, String])(_.properties)
128
-
129
- object Segmentation:
130
- private type Kind = (String, Int)
131
- private type Evidence = (Option[Island[Reading, Kind]], Reading)
132
- private val unclassified: String = "unclassified"
133
-
134
- private def toIsland(cursor: SegmentCursor): Island[Reading, Kind] =
135
- val first = Reading(cursor.start, Params(Map.empty))
136
- val last = Reading(cursor.end, Params(Map.empty))
137
- Island((cursor.name, 0), first, last)
@@ -0,0 +1,43 @@
1
+ package scada.supervisor.core.segmentation
2
+
3
+ import scada.supervisor.core.{Params, SegmentDef}
4
+
5
+ /** Transitions over classified samples in input order. The coordinate type is
6
+ * chosen by the caller and is never rounded or compared here.
7
+ */
8
+ object Timeline:
9
+ enum Boundary:
10
+ case Live, Observed
11
+
12
+ final case class Interval[+A](name: String, start: A, end: A)
13
+
14
+ enum Event[+A]:
15
+ case Sample(at: A, name: String, continuous: Boolean)
16
+ case DeadlineExpired(at: A)
17
+ case EndOfInput
18
+
19
+ enum Output[+A]:
20
+ case Pending(interval: Interval[A])
21
+ case Closed(interval: Interval[A])
22
+
23
+ final case class Result[A](open: Option[Interval[A]], outputs: Vector[Output[A]])
24
+
25
+ def classifier(definitions: List[SegmentDef]): Params => Option[String] =
26
+ val lookup = (name: String) => definitions.find(_.name == name).map(_.condition)
27
+ params => definitions.find(_.condition.matches(params, lookup)).map(_.name)
28
+
29
+ def step[A](boundary: Boundary, open: Option[Interval[A]], event: Event[A]): Result[A] =
30
+ event match
31
+ case Event.Sample(at, name, continuous) =>
32
+ open match
33
+ case Some(previous) if continuous && previous.name == name =>
34
+ val updated = previous.copy(end = at)
35
+ Result(Some(updated), Vector(Output.Pending(updated)))
36
+ case _ =>
37
+ val next = Interval(name, at, at)
38
+ val closed = open.map: previous =>
39
+ val end = if boundary == Boundary.Live && previous.name != name then at else previous.end
40
+ Output.Closed(previous.copy(end = end))
41
+ Result(Some(next), closed.toVector :+ Output.Pending(next))
42
+ // The existing policies keep the last interval open through silence and finite EOF.
43
+ case Event.DeadlineExpired(_) | Event.EndOfInput => Result(open, Vector.empty)
@@ -10,6 +10,8 @@ import java.net.URLEncoder
10
10
  import java.nio.charset.StandardCharsets
11
11
  import java.time.Instant
12
12
  import scada.supervisor.core.*
13
+ import scada.supervisor.core.segmentation.Timeline
14
+ import scada.supervisor.core.segmentation.Timeline.{Boundary, Event, Interval, Output}
13
15
  import scada.supervisor.infra.config.{AliasMapping, CheckpointApiConfig}
14
16
  import scala.concurrent.duration.*
15
17
 
@@ -42,27 +44,27 @@ object LocalHistory:
42
44
  /** Finite event-time classification: never inject wall-clock silence into past data. */
43
45
  def classify(machine: MachineConfig, points: Vector[Observation], seed: Option[HistorySeed] = None, continuity: Vector[HistoryRange] = Vector.empty): Vector[HistorySegment] =
44
46
  val gap = machine.window.toLong * 2000
45
- val lookup = (name: String) => machine.segments.find(_.name == name).map(_.condition)
47
+ val classifyParams = Timeline.classifier(machine.segments)
46
48
  val groups = points.groupBy(_.time).toVector.sortBy(_._1)
47
49
  val initialSegment = seed.flatMap: initial =>
48
50
  val stored = initial.segment.filter(_.start <= initial.time)
49
- val evaluated = machine.segments.find(_.condition.matches(Params(initial.values),lookup)).map(_.name)
50
- evaluated match
51
+ classifyParams(Params(initial.values)) match
51
52
  case Some(name) => Some(stored.filter(_.name == name).getOrElse(HistorySegment(name,initial.time,initial.time)))
52
53
  case None => stored
53
- groups.foldLeft((seed.fold(Map.empty[String,Double])(_.values),seed.map(_.time),initialSegment.toVector)):
54
- case ((prior,previous,segments),(time,group)) =>
54
+ val initialOpen = initialSegment.map(row => Interval(row.name, row.start, row.end))
55
+ val initial = (seed.fold(Map.empty[String,Double])(_.values), seed.map(_.time), initialOpen, Vector.empty[Interval[Long]])
56
+ val (_, _, open, closed) = groups.foldLeft(initial):
57
+ case ((prior, previous, current, completed), (time, group)) =>
55
58
  val continuous = previous.exists(t => connected(t,time,gap,continuity))
56
59
  val values = (if continuous then prior else Map.empty) ++ group.map(p => p.channel -> p.value)
57
- val name = machine.segments.find(_.condition.matches(Params(values),lookup)).map(_.name)
58
- .orElse(if continuous then segments.lastOption.map(_.name) else None)
59
- val next = name.fold(segments): n =>
60
- segments.lastOption match
61
- case Some(last) if continuous && last.name == n => segments.init :+ last.copy(end = time)
62
- case Some(_) if continuous => segments :+ HistorySegment(n,time,time)
63
- case _ => segments :+ HistorySegment(n,time,time)
64
- (values,Some(time),next)
65
- ._3
60
+ val name = classifyParams(Params(values)).orElse(if continuous then current.map(_.name) else None)
61
+ name match
62
+ case Some(n) =>
63
+ val next = Timeline.step(Boundary.Observed, current, Event.Sample(time, n, continuous))
64
+ val finished = next.outputs.collect { case Output.Closed(row) => row }
65
+ (values, Some(time), next.open, completed ++ finished)
66
+ case None => (values, Some(time), current, completed)
67
+ (closed ++ open).map(row => HistorySegment(row.name, row.start, row.end))
66
68
 
67
69
  def sources(context: Json): Vector[Json] =
68
70
  val current = context.hcursor.get[Vector[Json]]("segments").getOrElse(Vector.empty)