@yarkivaev/scada 2.6.39 → 2.6.41

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 (82) hide show
  1. package/README.md +13 -768
  2. package/package.json +3 -1
  3. package/src/domain/segment/segmentCoalesce.js +1 -1
  4. package/src/infrastructure/http/plant/routes/timelineRoute.js +1 -1
  5. package/src/infrastructure/ingest/sinks/contiguousPhases.js +13 -3
  6. package/src/infrastructure/streams/README.md +12 -5
  7. package/supervisor-engine/src/main/scala/scada/supervisor/core/Condition.scala +33 -0
  8. package/supervisor-engine/src/main/scala/scada/supervisor/core/CyclePhases.scala +65 -0
  9. package/supervisor-engine/src/main/scala/scada/supervisor/core/Decision.scala +67 -0
  10. package/supervisor-engine/src/main/scala/scada/supervisor/core/Emission.scala +19 -0
  11. package/supervisor-engine/src/main/scala/scada/supervisor/core/MachineConfig.scala +21 -0
  12. package/supervisor-engine/src/main/scala/scada/supervisor/core/MachineId.scala +18 -0
  13. package/supervisor-engine/src/main/scala/scada/supervisor/core/MachineMode.scala +4 -0
  14. package/supervisor-engine/src/main/scala/scada/supervisor/core/Params.scala +15 -0
  15. package/supervisor-engine/src/main/scala/scada/supervisor/core/Reading.scala +11 -0
  16. package/supervisor-engine/src/main/scala/scada/supervisor/core/Segment.scala +28 -0
  17. package/supervisor-engine/src/main/scala/scada/supervisor/core/SegmentDef.scala +14 -0
  18. package/supervisor-engine/src/main/scala/scada/supervisor/core/Segmentation.scala +137 -0
  19. package/supervisor-engine/src/main/scala/scada/supervisor/core/Segments.scala +41 -0
  20. package/supervisor-engine/src/main/scala/scada/supervisor/core/SplitFollow.scala +50 -0
  21. package/supervisor-engine/src/main/scala/scada/supervisor/core/SplitPieces.scala +102 -0
  22. package/supervisor-engine/src/main/scala/scada/supervisor/core/Supervisor.scala +66 -0
  23. package/supervisor-engine/src/main/scala/scada/supervisor/core/TagDef.scala +12 -0
  24. package/supervisor-engine/src/main/scala/scada/supervisor/core/TaggedSegment.scala +19 -0
  25. package/supervisor-engine/src/main/scala/scada/supervisor/core/Tagging.scala +42 -0
  26. package/supervisor-engine/src/main/scala/scada/supervisor/core/Timestamp.scala +26 -0
  27. package/supervisor-engine/src/main/scala/scada/supervisor/infra/checkpoint/Checkpoint.scala +61 -0
  28. package/supervisor-engine/src/main/scala/scada/supervisor/infra/checkpoint/ClickhouseReadingsCheckpoint.scala +76 -0
  29. package/supervisor-engine/src/main/scala/scada/supervisor/infra/checkpoint/SupervisorSinkCheckpoint.scala +141 -0
  30. package/supervisor-engine/src/main/scala/scada/supervisor/infra/config/AppConfig.scala +132 -0
  31. package/supervisor-engine/src/main/scala/scada/supervisor/infra/config/ConfigLoad.scala +202 -0
  32. package/supervisor-engine/src/main/scala/scada/supervisor/infra/config/ConfigProfile.scala +13 -0
  33. package/supervisor-engine/src/main/scala/scada/supervisor/infra/mqtt/Mqtt.scala +92 -0
  34. package/supervisor-engine/src/main/scala/scada/supervisor/infra/mqtt/Sessions.scala +18 -0
  35. package/supervisor-engine/src/main/scala/scada/supervisor/infra/state/AtomicStateFile.scala +24 -0
  36. package/supervisor-engine/src/main/scala/scada/supervisor/infra/state/CheckpointSegments.scala +59 -0
  37. package/supervisor-engine/src/main/scala/scada/supervisor/infra/state/SegmentStatePolicy.scala +18 -0
  38. package/supervisor-engine/src/main/scala/scada/supervisor/infra/state/Segments.scala +91 -0
  39. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/ClassifyQueue.scala +37 -0
  40. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/DecisionMessage.scala +49 -0
  41. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/DurableStomp.scala +27 -0
  42. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/SegmentMessage.scala +57 -0
  43. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/SegmentWirePolicy.scala +18 -0
  44. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/SplitFamily.scala +39 -0
  45. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompConnection.scala +106 -0
  46. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompDecisions.scala +43 -0
  47. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompFrame.scala +67 -0
  48. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompMachineDecisions.scala +16 -0
  49. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompQueue.scala +30 -0
  50. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompReadings.scala +29 -0
  51. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompSegments.scala +115 -0
  52. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ClassifierCursors.scala +58 -0
  53. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ClassifyHistory.scala +92 -0
  54. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ClassifyStreams.scala +67 -0
  55. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/Close.scala +23 -0
  56. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/EngineApp.scala +4 -0
  57. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/HealthServer.scala +38 -0
  58. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/HistoryBus.scala +67 -0
  59. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/HistoryClient.scala +23 -0
  60. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/HistoryRun.scala +86 -0
  61. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/LocalHistory.scala +256 -0
  62. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ObservationLead.scala +26 -0
  63. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/Orphans.scala +26 -0
  64. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/PendingIsland.scala +37 -0
  65. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/RuntimeProfile.scala +32 -0
  66. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/Seeding.scala +105 -0
  67. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/SupervisorRuntime.scala +266 -0
  68. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/WriterEpoch.scala +16 -0
  69. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/WriterGate.scala +35 -0
  70. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/WriterLease.scala +218 -0
  71. package/supervisor-engine/vendor/gaps-and-islands/LICENSE +21 -0
  72. package/supervisor-engine/vendor/gaps-and-islands/UPSTREAM +4 -0
  73. package/supervisor-engine/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/Island.scala +40 -0
  74. package/supervisor-engine/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandEvent.scala +55 -0
  75. package/supervisor-engine/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandsFlow.scala +127 -0
  76. package/supervisor-engine/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandsPolicy.scala +105 -0
  77. package/supervisor-engine/vendor/temporal-streams/LICENSE +21 -0
  78. package/supervisor-engine/vendor/temporal-streams/UPSTREAM +3 -0
  79. package/supervisor-engine/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/History.scala +30 -0
  80. package/supervisor-engine/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/LocalStreams.scala +27 -0
  81. package/supervisor-engine/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/Overlay.scala +15 -0
  82. package/supervisor-engine/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/Worker.scala +21 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yarkivaev/scada",
3
- "version": "2.6.39",
3
+ "version": "2.6.41",
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
  }
@@ -30,7 +30,7 @@ function heartbeatKey(parsed) {
30
30
  * @returns {boolean}
31
31
  */
32
32
  function isHeartbeat(parsed) {
33
- return parsed.type === 'segment' && parsed.duration === 0;
33
+ return parsed.type === 'segment' && parsed.duration === 0 && parsed.properties?.phase_revision === undefined;
34
34
  }
35
35
 
36
36
  /**
@@ -96,7 +96,7 @@ export default function timelineRoute(basePath, plant, operatorOptions, decorate
96
96
  return kind.length > 0;
97
97
  });
98
98
  }
99
- const rows = await decorate(params.machineId, await result.machine.timeline.list(options));
99
+ const rows = await decorate(params.machineId, await result.machine.timeline.list(options), options);
100
100
  jsonResponse({ items: segmentItems(currentPhase ? currentPhase(params.machineId, rows) : rows) }).send(res);
101
101
  }),
102
102
  route('PATCH', `${basePath}/machines/:machineId/segments`, async (req, res, params) => {
@@ -15,14 +15,24 @@ export function phaseAnchors(raw) {
15
15
  }));
16
16
  }
17
17
 
18
+ function revision(properties) {
19
+ // Older property strings need not be valid JSON. The wire revision is a decimal string.
20
+ return `COALESCE(substring((${properties}) from '"phase_revision"[[:space:]]*:[[:space:]]*"([0-9]{1,16})"')::bigint,0)`;
21
+ }
22
+
23
+ function advancesPending(incoming, stored, nondecreasingEnd) {
24
+ return `(${revision(incoming)} > ${revision(stored)}
25
+ OR (${revision(incoming)} = ${revision(stored)} AND ${nondecreasingEnd}))`;
26
+ }
27
+
18
28
  const stage = `
19
29
  INSERT INTO contiguous_phase_inbox (machine, start_time, phase)
20
30
  VALUES ($1,$2,$3)
21
31
  ON CONFLICT (machine, start_time) DO UPDATE SET phase=EXCLUDED.phase
22
32
  WHERE (contiguous_phase_inbox.phase->>'duration')::numeric = 0
23
33
  AND ((EXCLUDED.phase->>'duration')::numeric > 0
24
- OR (EXCLUDED.phase->>'end_time')::timestamptz >=
25
- (contiguous_phase_inbox.phase->>'end_time')::timestamptz)`;
34
+ OR ${advancesPending("EXCLUDED.phase->>'properties'", "contiguous_phase_inbox.phase->>'properties'",
35
+ "(EXCLUDED.phase->>'end_time')::timestamptz >= (contiguous_phase_inbox.phase->>'end_time')::timestamptz")})`;
26
36
 
27
37
  const visible = `
28
38
  INSERT INTO segments (machine,kind,name,start_time,end_time,duration,options,tags,properties,resolved,updated_at)
@@ -33,7 +43,7 @@ const visible = `
33
43
  WHERE segments.duration=0
34
44
  AND (EXCLUDED.duration>0 OR
35
45
  ((segments.name=EXCLUDED.name OR segments.start_time=segments.end_time)
36
- AND segments.end_time<=EXCLUDED.end_time))`;
46
+ AND ${advancesPending('EXCLUDED.properties', 'segments.properties', 'segments.end_time<=EXCLUDED.end_time')}))`;
37
47
 
38
48
  function invalid(message) {
39
49
  return Object.assign(new RangeError(message), { permanent: true });
@@ -1,7 +1,10 @@
1
- # SCADA stream adapters
1
+ [Documentation](../../../docs/README.md) / [Data collection](../../../docs/collect/README.md)
2
2
 
3
- Protocol and storage adapters are exported by `@yarkivaev/scada/streams`.
4
- Generic batching, circuit and periodic sources are imported from `@yarkivaev/source-to-sink`.
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
- Serial input is a push stream; the source does not impose a collector backlog
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,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,4 @@
1
+ package scada.supervisor.core
2
+
3
+ /** Marker for machine configuration interpreted by a site profile. */
4
+ trait MachineMode
@@ -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)
@@ -0,0 +1,11 @@
1
+ package scada.supervisor.core
2
+
3
+ /**
4
+ * One sensor observation for a machine at one instant. The atomic
5
+ * input of segmentation.
6
+ *
7
+ * {{{
8
+ * Reading(Timestamp(1700000000.0), Params(Map("power" -> 42.0)))
9
+ * }}}
10
+ */
11
+ final case class Reading(timestamp: Timestamp, params: Params)
@@ -0,0 +1,28 @@
1
+ package scada.supervisor.core
2
+
3
+ /**
4
+ * A named, closed time interval produced by segmentation from a
5
+ * contiguous run of readings that matched the same [[SegmentDef]].
6
+ *
7
+ * `duration == 0.0` marks a just-started (pending) segment whose
8
+ * closing boundary a later reading will reveal.
9
+ *
10
+ * {{{
11
+ * Segment("on", Timestamp(100.0), Timestamp(200.0), 100.0)
12
+ * }}}
13
+ */
14
+ final case class Segment(
15
+ name: String,
16
+ start: Timestamp,
17
+ end: Timestamp,
18
+ duration: Double,
19
+ properties: Map[String, String] = Map.empty
20
+ )
21
+
22
+ /**
23
+ * Open-segment resume cursor from Postgres (`segments` row with
24
+ * `duration = 0`). Fed into [[Segmentation]] as the initial
25
+ * gaps-and-islands island; `end` may advance beyond `start` via
26
+ * pending heartbeats.
27
+ */
28
+ final case class SegmentCursor(name: String, start: Timestamp, end: Timestamp)
@@ -0,0 +1,14 @@
1
+ package scada.supervisor.core
2
+
3
+ /**
4
+ * One named segment kind for a machine: a label and the predicate
5
+ * deciding whether a reading belongs to it.
6
+ *
7
+ * Order inside [[MachineConfig.segments]] is significant — the first
8
+ * matching definition wins.
9
+ *
10
+ * {{{
11
+ * SegmentDef("on", Condition.Above("power", 0.1))
12
+ * }}}
13
+ */
14
+ final case class SegmentDef(name: String, condition: Condition)
@@ -0,0 +1,137 @@
1
+ package scada.supervisor.core
2
+
3
+ import cats.Applicative
4
+ import cats.effect.{Async, Ref}
5
+ import fs2.{Pipe, Stream}
6
+ import scala.concurrent.duration.*
7
+ import yarkivaev.gapsandislands.api.*
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
+ final case class ReadingOverride(name: String, properties: Map[String, String])
33
+
34
+ final class Segmentation[F[_]: Async](overrideReading: Reading => Option[ReadingOverride] = _ => None):
35
+ import Segmentation.{Evidence, Kind, unclassified}
36
+
37
+ 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
52
+
53
+ private def gather(in: Stream[F, Reading]): Stream[F, Reading] =
54
+ in.groupWithin(32, 50.millis).flatMap: chunk =>
55
+ Stream.emits:
56
+ chunk.toList.groupBy(_.timestamp.epoch).toList.sortBy(_._1).map: (_, rows) =>
57
+ rows.reduce((left, right) => Reading(right.timestamp, left.params.merge(right.params)))
58
+
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)))
114
+ 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,41 @@
1
+ package scada.supervisor.core
2
+
3
+ import cats.Monad
4
+ import cats.syntax.all.*
5
+
6
+ /**
7
+ * Persistence boundary for [[TaggedSegment]]s keyed by machine and
8
+ * start timestamp. Abstract over the effect type so decorators
9
+ * (watermark, STOMP publishing) can compose around a concrete
10
+ * in-memory base without pinning the whole core to any runtime.
11
+ *
12
+ * [[resolve]] writes operator `tags` and `properties` on the row
13
+ * keyed by `original.start`. Options:
14
+ * - non-empty `options` → store that list (cascade next choices / leaf);
15
+ * - empty `options` → keep the previous options so HMI can re-edit the
16
+ * same prompt after a resolve that only retags the path.
17
+ *
18
+ * {{{
19
+ * segments.upsert(machineId, taggedSegment)
20
+ * segments.resolve(machine, original, tags, options, properties)
21
+ * }}}
22
+ */
23
+ trait Segments[F[_]]:
24
+ def upsert(machine: MachineId, segment: TaggedSegment): F[Unit]
25
+
26
+ def upsertTransition(machine: MachineId, rows: List[TaggedSegment])(using Monad[F]): F[Unit] =
27
+ rows.traverse_(upsert(machine, _))
28
+
29
+ def find(machine: MachineId, start: Timestamp): F[Option[TaggedSegment]]
30
+
31
+ def list(machine: MachineId): F[List[TaggedSegment]]
32
+
33
+ def replace(machine: MachineId, from: Timestamp, to: Timestamp, segments: List[TaggedSegment]): F[Unit]
34
+
35
+ def resolve(
36
+ machine: MachineId,
37
+ original: Segment,
38
+ tags: List[String],
39
+ options: List[String],
40
+ properties: Map[String, String]
41
+ ): F[Unit]
@@ -0,0 +1,50 @@
1
+ package scada.supervisor.core
2
+
3
+ import scala.collection.immutable.SortedMap
4
+
5
+ /**
6
+ * Keeps a classifier heartbeat on an already split `off` island from
7
+ * rewriting the closed pieces. The heartbeat still names the original
8
+ * start. Only the open tail moves, and a later close finishes that tail.
9
+ *
10
+ * {{{
11
+ * SplitFollow.project(rows, heartbeat)
12
+ * }}}
13
+ */
14
+ object SplitFollow:
15
+ def owned(rows: Iterable[TaggedSegment], incoming: TaggedSegment): Boolean =
16
+ incoming.segment.name == "off" && family(rows, incoming).nonEmpty
17
+
18
+ def project(
19
+ rows: SortedMap[Timestamp, TaggedSegment],
20
+ incoming: TaggedSegment
21
+ ): SortedMap[Timestamp, TaggedSegment] =
22
+ val pieces = family(rows.values, incoming)
23
+ if pieces.isEmpty then rows
24
+ else
25
+ val tail = pieces.maxBy(_.segment.start.epoch)
26
+ moved(tail, incoming) match
27
+ case None => rows
28
+ case Some(next) => rows.updated(tail.segment.start, next)
29
+
30
+ def affected(incoming: TaggedSegment, rows: Iterable[TaggedSegment]): Option[TaggedSegment] =
31
+ val pieces = family(rows, incoming)
32
+ if incoming.segment.name != "off" || pieces.isEmpty then None
33
+ else
34
+ val tail = pieces.maxBy(_.segment.start.epoch)
35
+ moved(tail, incoming).orElse(Some(tail))
36
+
37
+ private def family(rows: Iterable[TaggedSegment], incoming: TaggedSegment): List[TaggedSegment] =
38
+ val key = SplitPieces.originKey(incoming.segment.start)
39
+ rows.filter(_.properties.get("split_of").contains(key)).toList
40
+
41
+ private def moved(tail: TaggedSegment, incoming: TaggedSegment): Option[TaggedSegment] =
42
+ val start = tail.segment.start
43
+ if tail.segment.duration != 0.0 then None
44
+ else if incoming.segment.duration == 0.0 then
45
+ if !incoming.segment.end.isAfter(tail.segment.end) then None
46
+ else Some(tail.copy(segment = tail.segment.copy(end = incoming.segment.end, duration = 0.0)))
47
+ else if !incoming.segment.end.isAfter(start) then None
48
+ else
49
+ val end = incoming.segment.end
50
+ Some(tail.copy(segment = Segment("off", start, end, end.minus(start))))