@yarkivaev/scada 2.8.0 → 2.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/package.json +4 -2
  2. package/src/application/management/loadText.js +37 -0
  3. package/src/application/management/management.js +17 -3
  4. package/src/application/management/networkLoad.js +80 -0
  5. package/src/application/management/terminalLabel.js +6 -0
  6. package/src/application/management/topology.js +36 -0
  7. package/src/application/management/topologyStatus.js +44 -0
  8. package/src/application/management/topologyText.js +28 -0
  9. package/src/bin/scada.js +25 -7
  10. package/src/infrastructure/management/controlLoad.js +33 -0
  11. package/src/infrastructure/management/inventory.js +34 -5
  12. package/src/infrastructure/management/kubernetes.js +35 -11
  13. package/src/infrastructure/management/observations.js +80 -0
  14. package/src/infrastructure/management/prometheusLoad.js +69 -0
  15. package/src/infrastructure/management/protocol.js +51 -5
  16. package/src/infrastructure/management/rabbitmqLoad.js +79 -0
  17. package/src/infrastructure/management/responseJson.js +13 -0
  18. package/stream-processing/dependencies/timeline-segmentation.jar +0 -0
  19. package/stream-processing/src/main/scala/scada/processing/core/Decision.scala +1 -11
  20. package/stream-processing/src/main/scala/scada/processing/core/MachineConfig.scala +1 -0
  21. package/stream-processing/src/main/scala/scada/processing/core/ReadingWorker.scala +6 -16
  22. package/stream-processing/src/main/scala/scada/processing/core/Segments.scala +1 -0
  23. package/stream-processing/src/main/scala/scada/processing/infra/checkpoint/Checkpoint.scala +1 -0
  24. package/stream-processing/src/main/scala/scada/processing/infra/checkpoint/ClickhouseReadingsCheckpoint.scala +1 -0
  25. package/stream-processing/src/main/scala/scada/processing/infra/checkpoint/SupervisorSinkCheckpoint.scala +1 -0
  26. package/stream-processing/src/main/scala/scada/processing/infra/config/AppConfig.scala +2 -2
  27. package/stream-processing/src/main/scala/scada/processing/infra/config/ConfigLoad.scala +1 -0
  28. package/stream-processing/src/main/scala/scada/processing/infra/config/ConfigProfile.scala +0 -1
  29. package/stream-processing/src/main/scala/scada/processing/infra/mqtt/Mqtt.scala +1 -1
  30. package/stream-processing/src/main/scala/scada/processing/infra/state/CheckpointSegments.scala +1 -0
  31. package/stream-processing/src/main/scala/scada/processing/infra/state/SegmentStatePolicy.scala +1 -2
  32. package/stream-processing/src/main/scala/scada/processing/infra/state/Segments.scala +1 -0
  33. package/stream-processing/src/main/scala/scada/processing/infra/stomp/DecisionMessage.scala +2 -2
  34. package/stream-processing/src/main/scala/scada/processing/infra/stomp/SegmentMessage.scala +2 -2
  35. package/stream-processing/src/main/scala/scada/processing/infra/stomp/SegmentWirePolicy.scala +1 -2
  36. package/stream-processing/src/main/scala/scada/processing/infra/stomp/SplitFamily.scala +2 -2
  37. package/stream-processing/src/main/scala/scada/processing/infra/stomp/StompMachineDecisions.scala +1 -1
  38. package/stream-processing/src/main/scala/scada/processing/infra/stomp/StompReadings.scala +1 -1
  39. package/stream-processing/src/main/scala/scada/processing/infra/stomp/StompSegments.scala +1 -0
  40. package/stream-processing/src/main/scala/scada/processing/runtime/ClassifyHistory.scala +2 -1
  41. package/stream-processing/src/main/scala/scada/processing/runtime/ClassifyStreams.scala +1 -0
  42. package/stream-processing/src/main/scala/scada/processing/runtime/Close.scala +1 -1
  43. package/stream-processing/src/main/scala/scada/processing/runtime/HistoryBus.scala +1 -0
  44. package/stream-processing/src/main/scala/scada/processing/runtime/LocalHistory.scala +13 -61
  45. package/stream-processing/src/main/scala/scada/processing/runtime/PendingIsland.scala +2 -1
  46. package/stream-processing/src/main/scala/scada/processing/runtime/ProcessingApplication.scala +2 -12
  47. package/stream-processing/src/main/scala/scada/processing/runtime/RuntimeProfile.scala +2 -1
  48. package/stream-processing/src/main/scala/scada/processing/runtime/Seeding.scala +2 -1
  49. package/stream-processing/timeline-segmentation.lock +2 -0
  50. package/stream-processing/src/main/scala/scada/processing/core/Condition.scala +0 -33
  51. package/stream-processing/src/main/scala/scada/processing/core/CyclePhases.scala +0 -65
  52. package/stream-processing/src/main/scala/scada/processing/core/Emission.scala +0 -19
  53. package/stream-processing/src/main/scala/scada/processing/core/Params.scala +0 -15
  54. package/stream-processing/src/main/scala/scada/processing/core/Reading.scala +0 -11
  55. package/stream-processing/src/main/scala/scada/processing/core/Segment.scala +0 -28
  56. package/stream-processing/src/main/scala/scada/processing/core/SegmentDef.scala +0 -14
  57. package/stream-processing/src/main/scala/scada/processing/core/Segmentation.scala +0 -47
  58. package/stream-processing/src/main/scala/scada/processing/core/SplitFollow.scala +0 -50
  59. package/stream-processing/src/main/scala/scada/processing/core/SplitPieces.scala +0 -102
  60. package/stream-processing/src/main/scala/scada/processing/core/TagDef.scala +0 -12
  61. package/stream-processing/src/main/scala/scada/processing/core/TaggedSegment.scala +0 -19
  62. package/stream-processing/src/main/scala/scada/processing/core/Tagging.scala +0 -42
  63. package/stream-processing/src/main/scala/scada/processing/core/Timestamp.scala +0 -26
  64. package/stream-processing/src/main/scala/scada/processing/core/segmentation/Timeline.scala +0 -43
  65. package/stream-processing/vendor/gaps-and-islands/LICENSE +0 -21
  66. package/stream-processing/vendor/gaps-and-islands/UPSTREAM +0 -4
  67. package/stream-processing/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/Island.scala +0 -40
  68. package/stream-processing/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandEvent.scala +0 -55
  69. package/stream-processing/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandsFlow.scala +0 -127
  70. package/stream-processing/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandsPolicy.scala +0 -105
@@ -1,5 +1,6 @@
1
1
  package scada.processing.runtime
2
2
 
3
+ import io.yarkivaev.segmentation.{HistoryRange, HistorySeed, HistorySegment, HistoryState, ObservedSegmentation, Reading, Segment, Tagging, Timestamp}
3
4
  import cats.effect.{IO, Ref}
4
5
  import cats.syntax.all.*
5
6
  import fs2.Stream
@@ -15,15 +16,10 @@ import java.util.HexFormat
15
16
  import scada.stream.replay.{Replay, ReplayFailure, ReplayInput, ReplayManifest, ReplayRange, ReplaySeed}
16
17
  import io.yarkivaev.streamworker.{ProcessingError, Processor, StepResult}
17
18
  import scada.processing.core.*
18
- import scada.processing.core.segmentation.Timeline
19
- import scada.processing.core.segmentation.Timeline.{Boundary, Event, Interval, Output}
19
+ import io.yarkivaev.segmentation.ObservedSegmentation.{Sample, State, segment}
20
20
  import scada.processing.infra.config.{AliasMapping, CheckpointApiConfig}
21
21
  import scala.concurrent.duration.*
22
22
 
23
- final case class HistoryRange(from: Long, until: Long)
24
- final case class HistorySeed(time: Long, values: Map[String,Double], segment: Option[HistorySegment] = None)
25
- final case class HistorySegment(name: String, start: Long, end: Long)
26
- final case class HistoryState(position: Long, parameters: Map[String,(Long,Double)], segment: Option[HistorySegment])
27
23
  final case class HistoryPool(cursors: LocalStreams, states: Map[Long,HistoryState]):
28
24
  def expire(now: Long): HistoryPool =
29
25
  val alive = cursors.evict(now)
@@ -35,72 +31,28 @@ final case class HistoryPool(cursors: LocalStreams, states: Map[Long,HistoryStat
35
31
  val merged = equal.foldLeft(advanced)((pool,id) => pool.merge(stream,id,true))
36
32
  HistoryPool(merged,known.filter((id,_) => merged.streams.exists(_.id == id)))
37
33
  object LocalHistory:
38
- def connected(before: Long, after: Long, gap: Long, continuity: Vector[HistoryRange]): Boolean =
39
- before <= after && (BigInt(after)-BigInt(before) <= gap || continuity.exists(r => r.from <= before && r.until >= after))
40
- def state(machine: MachineConfig, points: Vector[Observation], result: Vector[HistorySegment], seed: Option[HistorySeed] = None, continuity: Vector[HistoryRange] = Vector.empty): Option[HistoryState] =
41
- points.map(_.time).maxOption.map: end =>
42
- val gap = machine.window.toLong*2000
43
- val state = points.groupBy(_.time).toVector.sortBy(_._1).foldLeft((seed.map(_.time),seed.fold(Map.empty[String,(Long,Double)])(s => s.values.map((k,v) => k -> (s.time,v))))):
44
- case ((previous,values),(time,group)) =>
45
- val prior = if previous.exists(t => connected(t,time,gap,continuity)) then values else Map.empty[String,(Long,Double)]
46
- (Some(time),prior ++ group.map(p => p.channel -> (p.time,p.value)))
47
- HistoryState(end,state._2,result.lastOption)
34
+ def classify(machine: MachineConfig, points: Vector[Observation], seed: Option[HistorySeed] = None,
35
+ continuity: Vector[HistoryRange] = Vector.empty): Vector[HistorySegment] =
36
+ ObservedSegmentation(machine.segments, machine.window, continuity).run(grouped(points), seed)
48
37
 
49
- /** Finite event-time classification: never inject wall-clock silence into past data. */
50
- def classify(machine: MachineConfig, points: Vector[Observation], seed: Option[HistorySeed] = None, continuity: Vector[HistoryRange] = Vector.empty): Vector[HistorySegment] =
51
- val classifier = Classification(machine, continuity)
52
- val (terminal, closed) = grouped(points).foldLeft((classifier.initial(seed), Vector.empty[HistorySegment])):
53
- case ((state, completed), sample) =>
54
- val next = classifier.advance(state, sample)
55
- (next.state, completed ++ next.outputs)
56
- closed ++ terminal.segment.map(segment)
57
-
58
- private final case class Sample(time: Long, values: Map[String, Double])
59
- private final case class ClassificationState(
60
- time: Option[Long], parameters: Map[String, (Long, Double)], segment: Option[Interval[Long]]
61
- )
62
38
  private[runtime] final case class Replayed(segments: Vector[HistorySegment], state: Option[HistoryState])
63
39
 
64
- private def segment(row: Interval[Long]): HistorySegment = HistorySegment(row.name, row.start, row.end)
65
-
66
40
  private def grouped(points: Vector[Observation]): Vector[Sample] =
67
41
  points.groupBy(_.time).toVector.sortBy(_._1).map: (time, group) =>
68
42
  Sample(time, group.map(p => p.channel -> p.value).toMap)
69
43
 
70
- private final class Classification(machine: MachineConfig, continuity: Vector[HistoryRange])
71
- extends Processor[Unit, ClassificationState, Sample, HistorySegment]:
72
- private val classify = Timeline.classifier(machine.segments)
73
- private val gap = machine.window.toLong * 2000
74
-
75
- def initial(seed: Option[HistorySeed]): ClassificationState =
76
- val carried = seed.flatMap: value =>
77
- val stored = value.segment.filter(_.start <= value.time)
78
- val evaluated = classify(Params(value.values)) match
79
- case Some(name) => Some(stored.filter(_.name == name).getOrElse(HistorySegment(name, value.time, value.time)))
80
- case None => stored
81
- evaluated.map(row => Interval(row.name, row.start, row.end))
82
- val parameters = seed.fold(Map.empty[String, (Long, Double)])(value => value.values.map((key, reading) => key -> (value.time, reading)))
83
- ClassificationState(seed.map(_.time), parameters, carried)
84
-
85
- def advance(state: ClassificationState, sample: Sample): StepResult[ClassificationState, HistorySegment] =
86
- val continuous = state.time.exists(connected(_, sample.time, gap, continuity))
87
- val parameters = (if continuous then state.parameters else Map.empty) ++
88
- sample.values.map((key, value) => key -> (sample.time, value))
89
- val name = classify(Params(parameters.map((key, value) => key -> value._2)))
90
- .orElse(if continuous then state.segment.map(_.name) else None)
91
- val next = ClassificationState(Some(sample.time), parameters, state.segment)
92
- name.fold(StepResult(next, Vector.empty[HistorySegment])): classified =>
93
- val result = Timeline.step(Boundary.Observed, state.segment, Event.Sample(sample.time, classified, continuous))
94
- StepResult(next.copy(segment = result.open), result.outputs.collect { case Output.Closed(row) => segment(row) })
95
-
96
- override def step(config: Unit, state: ClassificationState, sample: Sample)
97
- : Either[ProcessingError, StepResult[ClassificationState, HistorySegment]] = Right(advance(state, sample))
44
+ private def processor(classifier: ObservedSegmentation): Processor[Unit, State, Sample, HistorySegment] =
45
+ new Processor[Unit, State, Sample, HistorySegment]:
46
+ def step(config: Unit, state: State, sample: Sample)
47
+ : Either[ProcessingError, StepResult[State, HistorySegment]] =
48
+ val result = classifier.step(state, sample)
49
+ Right(StepResult(result.state, result.outputs))
98
50
 
99
51
  private[runtime] def replay(
100
52
  machine: MachineConfig, points: Vector[Observation], baseRevision: String, runId: String,
101
53
  seed: Option[HistorySeed] = None, continuity: Vector[HistoryRange] = Vector.empty
102
54
  ): IO[Replayed] = IO.defer:
103
- val classifier = Classification(machine, continuity)
55
+ val classifier = ObservedSegmentation(machine.segments, machine.window, continuity)
104
56
  val initial = classifier.initial(seed)
105
57
  val samples = grouped(points)
106
58
  def values(readings: Map[String, Double]): Json =
@@ -118,7 +70,7 @@ object LocalHistory:
118
70
  val manifest = ReplayManifest(timeline, ReplayRange(0, samples.size), rulesVersion, input.id, seedId, baseRevision, runId)
119
71
  def failure(problem: ReplayFailure) = IllegalStateException(s"History page replay failed: $problem")
120
72
  IO.fromEither(Replay.plan(manifest, input, start).leftMap(failure)).flatMap: plan =>
121
- Replay.run(plan, (), classifier).flatMap(result => IO.fromEither(result.leftMap(failure))).map: result =>
73
+ Replay.run(plan, (), processor(classifier)).flatMap(result => IO.fromEither(result.leftMap(failure))).map: result =>
122
74
  val terminal = result.terminalState
123
75
  val tail = terminal.segment.map(segment)
124
76
  val state = samples.lastOption.map(last => HistoryState(last.time, terminal.parameters, tail))
@@ -1,9 +1,10 @@
1
1
  package scada.processing.runtime
2
2
 
3
+ import io.yarkivaev.segmentation.SegmentCursor
3
4
  import cats.effect.IO
4
5
  import org.typelevel.log4cats.Logger
5
6
  import org.typelevel.log4cats.slf4j.Slf4jLogger
6
- import scada.processing.core.{MachineConfig, SegmentCursor}
7
+ import scada.processing.core.MachineConfig
7
8
  import scada.processing.infra.checkpoint.Checkpoint
8
9
 
9
10
  /**
@@ -1,5 +1,6 @@
1
1
  package scada.processing.runtime
2
2
 
3
+ import io.yarkivaev.segmentation.{Reading, Segmentation, TagDef, TaggedSegment, Timestamp}
3
4
  import cats.effect.{ExitCode, IO, Ref, Resource}
4
5
  import cats.effect.std.Semaphore
5
6
  import cats.syntax.all.*
@@ -7,18 +8,7 @@ import fs2.Stream
7
8
  import io.yarkivaev.streamworker.OutputScope
8
9
  import org.typelevel.log4cats.Logger
9
10
  import org.typelevel.log4cats.slf4j.Slf4jLogger
10
- import scada.processing.core.{
11
- Decision,
12
- MachineConfig,
13
- MachineId,
14
- Reading,
15
- Segmentation,
16
- Segments as CoreSegments,
17
- ReadingWorker,
18
- TagDef,
19
- TaggedSegment,
20
- Timestamp
21
- }
11
+ import scada.processing.core.{Decision, MachineConfig, MachineId, Segments as CoreSegments, ReadingWorker}
22
12
  import scada.processing.infra.checkpoint.{Checkpoint, ClickhouseReadingsCheckpoint, SupervisorSinkCheckpoint}
23
13
  import scada.processing.infra.config.{AliasMapping, AppConfig, ConfigLoad, RabbitMqConfig}
24
14
  import scada.processing.infra.mqtt.Mqtt
@@ -1,10 +1,11 @@
1
1
  package scada.processing.runtime
2
2
 
3
+ import io.yarkivaev.segmentation.{Reading, ReadingOverride, Tagging}
3
4
  import cats.effect.IO
4
5
  import fs2.Stream
5
6
  import io.circe.Json
6
7
  import io.yarkivaev.streamworker.OutputScope
7
- import scada.processing.core.{MachineConfig, Reading, ReadingOverride, Segments, Tagging}
8
+ import scada.processing.core.{MachineConfig, Segments}
8
9
  import scada.processing.infra.checkpoint.Checkpoint
9
10
  import scada.processing.infra.config.{AliasMapping, AppConfig, CheckpointApiConfig, ConfigProfile}
10
11
  import scada.processing.infra.state.SegmentStatePolicy
@@ -1,12 +1,13 @@
1
1
  package scada.processing.runtime
2
2
 
3
+ import io.yarkivaev.segmentation.{Params, Reading, Timestamp}
3
4
  import cats.effect.{IO, Outcome}
4
5
  import cats.effect.std.Queue
5
6
  import fs2.Stream
6
7
  import org.typelevel.log4cats.Logger
7
8
  import org.typelevel.log4cats.slf4j.Slf4jLogger
8
9
  import scala.concurrent.duration.*
9
- import scada.processing.core.{MachineConfig, MachineId, Params, Reading, Timestamp}
10
+ import scada.processing.core.{MachineConfig, MachineId}
10
11
  import scada.processing.infra.checkpoint.{Checkpoint, RawReadingData}
11
12
  import scada.processing.infra.config.AliasMapping
12
13
 
@@ -0,0 +1,2 @@
1
+ 0.1.0
2
+ 495505f53a60028903b212b765bf09b37a67f578191dfce29a662b00f20c09dc
@@ -1,33 +0,0 @@
1
- package scada.processing.core
2
-
3
- /**
4
- * Declarative predicate over a single [[Reading]]. Smart object:
5
- * every case answers [[matches]] for itself.
6
- *
7
- * `When(name)` delegates to the condition of the same-named
8
- * [[SegmentDef]]; callers pass a `lookup` function that resolves the
9
- * reference. In tagging context `When` is matched by name only, not
10
- * by evaluating this predicate.
11
- *
12
- * {{{
13
- * Condition.Above("power", 5.0).matches(Params(Map("power" -> 42.0)))
14
- * }}}
15
- */
16
- enum Condition:
17
- case Above(param: String, threshold: Double)
18
- case Below(param: String, threshold: Double)
19
- case Equal(param: String, value: Double)
20
- case And(left: Condition, right: Condition)
21
- case Or(left: Condition, right: Condition)
22
- case When(segmentName: String)
23
-
24
- def matches(params: Params): Boolean =
25
- matches(params, _ => None)
26
-
27
- def matches(params: Params, lookup: String => Option[Condition]): Boolean = this match
28
- case Above(param, threshold) => params.value(param).exists(_ >= threshold)
29
- case Below(param, threshold) => params.value(param).exists(_ < threshold)
30
- case Equal(param, value) => params.value(param).contains(value)
31
- case And(left, right) => left.matches(params, lookup) && right.matches(params, lookup)
32
- case Or(left, right) => left.matches(params, lookup) || right.matches(params, lookup)
33
- case When(name) => lookup(name).exists(_.matches(params, lookup))
@@ -1,65 +0,0 @@
1
- package scada.processing.core
2
-
3
- /**
4
- * One cycle phase loaded from HOCON: optional `enter` anchor and the
5
- * flat tag ids allowed while that phase is open.
6
- *
7
- * {{{
8
- * CyclePhase(List("cycle_start", "transfer", "repair"), None)
9
- * CyclePhase(List("transfer", "repair"), Some("ready"))
10
- * }}}
11
- */
12
- final case class CyclePhase(allow: List[String], enter: Option[String])
13
-
14
- /**
15
- * Anchor tag ids that close or advance a production cycle.
16
- *
17
- * {{{
18
- * CycleAnchors("cycle_start", List("planned_stop"))
19
- * }}}
20
- */
21
- final case class CycleAnchors(start: String, stop: List[String])
22
-
23
- /**
24
- * Cycle allowlists loaded from generated HOCON. Phase lookup uses
25
- * anchors of other segments; `flat` keeps HMI button order.
26
- *
27
- * {{{
28
- * phases.options(others)
29
- * phases.accept(others, standing, tags)
30
- * }}}
31
- */
32
- final case class CyclePhases(flat: List[String], anchors: CycleAnchors, phases: List[CyclePhase]):
33
- def isEmpty: Boolean = phases.isEmpty
34
-
35
- def options(others: List[TaggedSegment]): List[String] =
36
- val allowed = phaseOf(others).allow.toSet
37
- flat.filter(allowed.contains)
38
-
39
- def accept(others: List[TaggedSegment], standing: List[String], tags: List[String]): Boolean =
40
- if isEmpty then true
41
- else
42
- val ok = options(others).toSet ++ standing.toSet
43
- tags.forall(ok.contains)
44
-
45
- def narrow(segment: TaggedSegment, all: List[TaggedSegment]): TaggedSegment =
46
- if isEmpty || segment.segment.name != "off" then segment
47
- else
48
- val past = all.filter(_.segment.start.epoch < segment.segment.start.epoch)
49
- TaggedSegment(segment.segment, segment.tags, options(past :+ segment), segment.properties)
50
-
51
- private def phaseOf(others: List[TaggedSegment]): CyclePhase =
52
- val idle = phases.find(_.enter.isEmpty).getOrElse(CyclePhase(Nil, None))
53
- val tags = others.sortBy(_.segment.start).flatMap(_.tags)
54
- val lastStop = tags.lastIndexWhere(id => anchors.stop.contains(id))
55
- val lastStart = tags.lastIndexWhere(_ == anchors.start)
56
- if lastStart < 0 || lastStart < lastStop then idle
57
- else entered(tags.drop(lastStart + 1), idle)
58
-
59
- private def entered(after: List[String], idle: CyclePhase): CyclePhase =
60
- val last = after.reverse.find(id => phases.exists(_.enter.contains(id)))
61
- last.flatMap(id => phases.find(_.enter.contains(id))).getOrElse:
62
- phases.find(_.enter.contains(anchors.start)).getOrElse(idle)
63
-
64
- object CyclePhases:
65
- val empty: CyclePhases = CyclePhases(Nil, CycleAnchors("", Nil), Nil)
@@ -1,19 +0,0 @@
1
- package scada.processing.core
2
-
3
- /**
4
- * Lifecycle marker for a value flowing through the pipeline.
5
- *
6
- * `Started` carries a pending value whose boundaries may still grow;
7
- * `Emitted` carries the finalised value.
8
- *
9
- * {{{
10
- * Emission.Started(segment): Emission[Segment]
11
- * Emission.Emitted(segment): Emission[Segment]
12
- * }}}
13
- */
14
- sealed trait Emission[+A]:
15
- def value: A
16
-
17
- object Emission:
18
- final case class Started[A](value: A) extends Emission[A]
19
- final case class Emitted[A](value: A) extends Emission[A]
@@ -1,15 +0,0 @@
1
- package scada.processing.core
2
-
3
- /**
4
- * Immutable snapshot of the named metric values attached to one
5
- * [[Reading]]. Keys are metric names (as configured by routing);
6
- * values are raw sensor doubles.
7
- *
8
- * {{{
9
- * Params(Map("power" -> 0.95)).value("power")
10
- * }}}
11
- */
12
- final case class Params(values: Map[String, Double]):
13
- def value(key: String): Option[Double] = values.get(key)
14
-
15
- def merge(other: Params): Params = Params(values ++ other.values)
@@ -1,11 +0,0 @@
1
- package scada.processing.core
2
-
3
- /**
4
- * One sensor observation for a machine at one instant. The atomic
5
- * input of segmentation.
6
- *
7
- * {{{
8
- * Reading(Timestamp(1700000000.0), Params(Map("power" -> 42.0)))
9
- * }}}
10
- */
11
- final case class Reading(timestamp: Timestamp, params: Params)
@@ -1,28 +0,0 @@
1
- package scada.processing.core
2
-
3
- /**
4
- * A named, closed time interval produced by segmentation from a
5
- * contiguous run of readings that matched the same [[SegmentDef]].
6
- *
7
- * `duration == 0.0` marks a just-started (pending) segment whose
8
- * closing boundary a later reading will reveal.
9
- *
10
- * {{{
11
- * Segment("on", Timestamp(100.0), Timestamp(200.0), 100.0)
12
- * }}}
13
- */
14
- final case class Segment(
15
- name: String,
16
- start: Timestamp,
17
- end: Timestamp,
18
- duration: Double,
19
- properties: Map[String, String] = Map.empty
20
- )
21
-
22
- /**
23
- * Open-segment resume cursor from Postgres (`segments` row with
24
- * `duration = 0`). Fed into [[Segmentation]] as the initial
25
- * gaps-and-islands island; `end` may advance beyond `start` via
26
- * pending heartbeats.
27
- */
28
- final case class SegmentCursor(name: String, start: Timestamp, end: Timestamp)
@@ -1,14 +0,0 @@
1
- package scada.processing.core
2
-
3
- /**
4
- * One named segment kind for a machine: a label and the predicate
5
- * deciding whether a reading belongs to it.
6
- *
7
- * Order inside [[MachineConfig.segments]] is significant — the first
8
- * matching definition wins.
9
- *
10
- * {{{
11
- * SegmentDef("on", Condition.Above("power", 0.1))
12
- * }}}
13
- */
14
- final case class SegmentDef(name: String, condition: Condition)
@@ -1,47 +0,0 @@
1
- package scada.processing.core
2
-
3
- import io.yarkivaev.streamworker.{ProcessingError, Processor, StepResult}
4
- import scada.processing.core.segmentation.Timeline
5
- import scada.processing.core.segmentation.Timeline.{Boundary, Event, Interval, Output}
6
-
7
- final case class ReadingOverride(name: String, properties: Map[String, String])
8
-
9
- /** Merges same-time readings and applies the live interval policy.
10
- * Class changes close at the next phase's first sample. A gap over twice
11
- * the machine's window splits equal phases without inventing downtime.
12
- */
13
- final class Segmentation(overrideReading: Reading => Option[ReadingOverride] = _ => None)
14
- extends Processor[MachineConfig, Option[Interval[Reading]], Reading, Emission[Segment]]:
15
- private val unclassified = "unclassified"
16
-
17
- private[processing] def seed(initial: Option[SegmentCursor]): Option[Interval[Reading]] =
18
- initial.map: cursor =>
19
- Interval(cursor.name, Reading(cursor.start, Params(Map.empty)), Reading(cursor.end, Params(Map.empty)))
20
-
21
- override def step(machine: MachineConfig, open: Option[Interval[Reading]], reading: Reading)
22
- : Either[ProcessingError, StepResult[Option[Interval[Reading]], Emission[Segment]]] =
23
- Right(advance(machine, open, reading))
24
-
25
- private def advance(machine: MachineConfig, open: Option[Interval[Reading]], reading: Reading)
26
- : StepResult[Option[Interval[Reading]], Emission[Segment]] =
27
- val classify = Timeline.classifier(machine.segments)
28
- val name = overrideReading(reading).map(_.name).orElse(classify(reading.params))
29
- .orElse(open.map(_.name)).getOrElse(unclassified)
30
- val continuous = open.exists(interval => !(reading.timestamp.minus(interval.end.timestamp) > machine.window.toDouble * 2.0))
31
- val result = Timeline.step(Boundary.Live, open, Event.Sample(reading, name, continuous))
32
- StepResult(result.open, result.outputs.flatMap(toEmission))
33
-
34
- private def toEmission(output: Output[Reading]): Option[Emission[Segment]] =
35
- def segment(interval: Interval[Reading], closed: Boolean): Segment =
36
- val start = interval.start.timestamp
37
- val end = interval.end.timestamp
38
- val duration = if closed then end.minus(start) else 0.0
39
- val properties = overrideReading(interval.end).fold(Map.empty[String, String])(_.properties)
40
- Segment(interval.name, start, end, duration, properties)
41
-
42
- output match
43
- case Output.Pending(interval) if interval.name != unclassified =>
44
- Some(Emission.Started(segment(interval, closed = false)))
45
- case Output.Closed(interval) if interval.name != unclassified =>
46
- Some(Emission.Emitted(segment(interval, closed = true)))
47
- case _ => None
@@ -1,50 +0,0 @@
1
- package scada.processing.core
2
-
3
- import scala.collection.immutable.SortedMap
4
-
5
- /**
6
- * Keeps a classifier heartbeat on an already split `off` island from
7
- * rewriting the closed pieces. The heartbeat still names the original
8
- * start. Only the open tail moves, and a later close finishes that tail.
9
- *
10
- * {{{
11
- * SplitFollow.project(rows, heartbeat)
12
- * }}}
13
- */
14
- object SplitFollow:
15
- def owned(rows: Iterable[TaggedSegment], incoming: TaggedSegment): Boolean =
16
- incoming.segment.name == "off" && family(rows, incoming).nonEmpty
17
-
18
- def project(
19
- rows: SortedMap[Timestamp, TaggedSegment],
20
- incoming: TaggedSegment
21
- ): SortedMap[Timestamp, TaggedSegment] =
22
- val pieces = family(rows.values, incoming)
23
- if pieces.isEmpty then rows
24
- else
25
- val tail = pieces.maxBy(_.segment.start.epoch)
26
- moved(tail, incoming) match
27
- case None => rows
28
- case Some(next) => rows.updated(tail.segment.start, next)
29
-
30
- def affected(incoming: TaggedSegment, rows: Iterable[TaggedSegment]): Option[TaggedSegment] =
31
- val pieces = family(rows, incoming)
32
- if incoming.segment.name != "off" || pieces.isEmpty then None
33
- else
34
- val tail = pieces.maxBy(_.segment.start.epoch)
35
- moved(tail, incoming).orElse(Some(tail))
36
-
37
- private def family(rows: Iterable[TaggedSegment], incoming: TaggedSegment): List[TaggedSegment] =
38
- val key = SplitPieces.originKey(incoming.segment.start)
39
- rows.filter(_.properties.get("split_of").contains(key)).toList
40
-
41
- private def moved(tail: TaggedSegment, incoming: TaggedSegment): Option[TaggedSegment] =
42
- val start = tail.segment.start
43
- if tail.segment.duration != 0.0 then None
44
- else if incoming.segment.duration == 0.0 then
45
- if !incoming.segment.end.isAfter(tail.segment.end) then None
46
- else Some(tail.copy(segment = tail.segment.copy(end = incoming.segment.end, duration = 0.0)))
47
- else if !incoming.segment.end.isAfter(start) then None
48
- else
49
- val end = incoming.segment.end
50
- Some(tail.copy(segment = Segment("off", start, end, end.minus(start))))
@@ -1,102 +0,0 @@
1
- package scada.processing.core
2
-
3
- /**
4
- * Turns one operator split of an `off` island into flat `off` rows.
5
- * Each row keeps `name = off`, carries at most one tag, and records
6
- * `properties.split_of` as the original island start in epoch millis.
7
- * The first row reuses that start. A last row with `open` stays pending
8
- * (`duration == 0`). [[span]] widens the parent to the contiguous saved
9
- * family when the new entries cover that whole island, so deleting one
10
- * piece merges the rest.
11
- *
12
- * {{{
13
- * SplitPieces.materialize(parent, List(
14
- * SplitEntry(parent.start, Timestamp(160.0), "maintenance"),
15
- * SplitEntry(Timestamp(160.0), parent.end, "")
16
- * ))
17
- * }}}
18
- */
19
- object SplitPieces:
20
- def originKey(start: Timestamp): String = start.millis.toString
21
-
22
- def row(origin: Timestamp, entry: SplitEntry): TaggedSegment =
23
- val duration = if entry.open then 0.0 else entry.end.minus(entry.start)
24
- val tags = if entry.tag.isEmpty then Nil else List(entry.tag)
25
- TaggedSegment(
26
- Segment("off", entry.start, entry.end, duration),
27
- tags,
28
- Nil,
29
- Map("split_of" -> originKey(origin))
30
- )
31
-
32
- def span(anchor: TaggedSegment, rows: List[TaggedSegment], entries: List[SplitEntry]): Segment =
33
- val key = anchor.properties.getOrElse("split_of", originKey(anchor.segment.start))
34
- val kin = rows.filter(row => row.segment.name == "off" && row.properties.get("split_of").contains(key))
35
- .sortBy(_.segment.start.millis)
36
- val run = pieceRun(anchor, kin)
37
- if run.nonEmpty && covers(run, entries) then bounds(run) else anchor.segment
38
-
39
- private def pieceRun(anchor: TaggedSegment, kin: List[TaggedSegment]): List[TaggedSegment] =
40
- val index = kin.indexWhere(_.segment.start.millis == anchor.segment.start.millis)
41
- if index < 0 then Nil
42
- else kin.slice(leftOf(kin, index), rightOf(kin, index) + 1)
43
-
44
- private def leftOf(kin: List[TaggedSegment], index: Int): Int =
45
- if index == 0 || kin(index - 1).segment.end.millis != kin(index).segment.start.millis then index
46
- else leftOf(kin, index - 1)
47
-
48
- private def rightOf(kin: List[TaggedSegment], index: Int): Int =
49
- if index == kin.length - 1 || kin(index).segment.end.millis != kin(index + 1).segment.start.millis then index
50
- else rightOf(kin, index + 1)
51
-
52
- private def covers(run: List[TaggedSegment], entries: List[SplitEntry]): Boolean =
53
- val ordered = entries.sortBy(_.start.millis)
54
- val head = run.head.segment
55
- val tail = run.last.segment
56
- ordered.nonEmpty && ordered.head.start.millis == head.start.millis &&
57
- (if tail.duration == 0.0 then ordered.last.open else !ordered.last.open && ordered.last.end.millis == tail.end.millis)
58
-
59
- private def bounds(run: List[TaggedSegment]): Segment =
60
- val head = run.head.segment
61
- val tail = run.last.segment
62
- val duration = if tail.duration == 0.0 then 0.0 else tail.end.minus(head.start)
63
- Segment("off", head.start, tail.end, duration)
64
-
65
- def materialize(parent: Segment, entries: List[SplitEntry]): List[TaggedSegment] =
66
- if parent.name != "off" then
67
- throw new IllegalArgumentException(
68
- s"refusing to split ${parent.name} starting at ${parent.start.millis}"
69
- )
70
- if entries.isEmpty then
71
- throw new IllegalArgumentException(
72
- s"refusing an empty split of off at ${parent.start.millis}"
73
- )
74
- val ordered = entries.sortBy(_.start.epoch)
75
- if ordered.head.start.millis != parent.start.millis then
76
- throw new IllegalArgumentException(
77
- s"split of off at ${parent.start.millis} must keep that start, got ${ordered.head.start.millis}"
78
- )
79
- if !ordered.exists(_.tag.nonEmpty) then
80
- throw new IllegalArgumentException(
81
- s"split of off at ${parent.start.millis} has no tagged piece"
82
- )
83
- ordered.zipWithIndex.foreach: (entry, index) =>
84
- val last = index == ordered.length - 1
85
- if entry.open && !last then
86
- throw new IllegalArgumentException(
87
- s"open piece at ${entry.start.millis} is not the tail of off at ${parent.start.millis}"
88
- )
89
- if index > 0 && ordered(index - 1).end.millis != entry.start.millis then
90
- throw new IllegalArgumentException(
91
- s"split of off at ${parent.start.millis} has a gap before ${entry.start.millis}"
92
- )
93
- val span = entry.end.minus(entry.start)
94
- if span < 0 then
95
- throw new IllegalArgumentException(
96
- s"piece at ${entry.start.millis} ends before it starts"
97
- )
98
- if parent.duration != 0.0 && (ordered.last.open || ordered.last.end.millis != parent.end.millis) then
99
- throw new IllegalArgumentException(
100
- s"closed off at ${parent.start.millis} must be covered through ${parent.end.millis}"
101
- )
102
- ordered.map(entry => row(parent.start, entry))
@@ -1,12 +0,0 @@
1
- package scada.processing.core
2
-
3
- /**
4
- * One conditional label. When exactly one [[TagDef]] matches a
5
- * [[Segment]] the label is applied automatically; when several match
6
- * they land in `options` and trigger a [[Decision]].
7
- *
8
- * {{{
9
- * TagDef("running", Condition.When("on"))
10
- * }}}
11
- */
12
- final case class TagDef(name: String, condition: Condition)
@@ -1,19 +0,0 @@
1
- package scada.processing.core
2
-
3
- /**
4
- * A [[Segment]] decorated with tagging output:
5
- * - `tags` — labels applied automatically or after a decision;
6
- * - `options` — labels the operator still has to choose between
7
- * (non-empty means awaiting [[Decision]]);
8
- * - `properties` — operator-attached metadata.
9
- *
10
- * {{{
11
- * TaggedSegment(segment, List("running"), Nil, Map.empty)
12
- * }}}
13
- */
14
- final case class TaggedSegment(
15
- segment: Segment,
16
- tags: List[String],
17
- options: List[String],
18
- properties: Map[String, String]
19
- )