@yarkivaev/scada 2.7.1 → 2.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/README.md +4 -4
  2. package/package.json +8 -3
  3. package/stream-processing/dependencies/stream-worker.jar +0 -0
  4. package/stream-processing/dependencies/timeline-segmentation.jar +0 -0
  5. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/Decision.scala +2 -12
  6. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/MachineConfig.scala +2 -1
  7. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/MachineId.scala +1 -1
  8. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/MachineMode.scala +1 -1
  9. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/ReadingWorker.scala +17 -22
  10. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/core/Segments.scala +2 -1
  11. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/checkpoint/Checkpoint.scala +3 -2
  12. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/checkpoint/ClickhouseReadingsCheckpoint.scala +4 -3
  13. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/checkpoint/SupervisorSinkCheckpoint.scala +4 -3
  14. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/config/AppConfig.scala +3 -3
  15. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/config/ConfigLoad.scala +3 -2
  16. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/config/ConfigProfile.scala +2 -3
  17. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/mqtt/Mqtt.scala +3 -3
  18. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/mqtt/Sessions.scala +1 -1
  19. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/state/AtomicStateFile.scala +1 -1
  20. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/state/CheckpointSegments.scala +6 -5
  21. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/state/SegmentStatePolicy.scala +2 -3
  22. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/state/Segments.scala +4 -3
  23. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/ClassifyQueue.scala +2 -2
  24. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/DecisionMessage.scala +3 -3
  25. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/DurableStomp.scala +1 -1
  26. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/SegmentMessage.scala +3 -3
  27. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/SegmentWirePolicy.scala +2 -3
  28. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/SplitFamily.scala +3 -3
  29. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/StompConnection.scala +1 -1
  30. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/StompDecisions.scala +3 -3
  31. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/StompFrame.scala +1 -1
  32. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/StompMachineDecisions.scala +3 -3
  33. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/StompQueue.scala +1 -1
  34. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/StompReadings.scala +3 -3
  35. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/infra/stomp/StompSegments.scala +5 -4
  36. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/ClassifyHistory.scala +4 -3
  37. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/ClassifyStreams.scala +43 -18
  38. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/Close.scala +4 -4
  39. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/HealthServer.scala +1 -1
  40. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/HistoryBus.scala +5 -4
  41. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/HistoryClient.scala +2 -2
  42. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/HistoryRun.scala +18 -14
  43. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/LocalHistory.scala +17 -65
  44. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/ObservationLead.scala +1 -1
  45. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/Orphans.scala +4 -4
  46. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/PendingIsland.scala +4 -3
  47. package/{supervisor-engine/src/main/scala/scada/supervisor/runtime/EngineApp.scala → stream-processing/src/main/scala/scada/processing/runtime/ProcessingApp.scala} +2 -2
  48. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/ProcessingApplication.scala +11 -22
  49. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/RuntimeProfile.scala +8 -8
  50. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/Seeding.scala +5 -4
  51. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/TimelineWriter.scala +3 -3
  52. package/{supervisor-engine/src/main/scala/scada/stream/worker/postgres → stream-processing/src/main/scala/scada/processing/runtime}/WorkerDatabase.scala +2 -2
  53. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/WriterEpoch.scala +1 -1
  54. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/WriterGate.scala +1 -1
  55. package/{supervisor-engine/src/main/scala/scada/supervisor → stream-processing/src/main/scala/scada/processing}/runtime/WriterLease.scala +4 -21
  56. package/{supervisor-engine → stream-processing}/src/main/scala/scada/stream/replay/Replay.scala +1 -1
  57. package/stream-processing/stream-worker.lock +2 -0
  58. package/stream-processing/timeline-segmentation.lock +2 -0
  59. package/supervisor-engine/src/main/scala/scada/stream/worker/OutputScope.scala +0 -13
  60. package/supervisor-engine/src/main/scala/scada/stream/worker/Processor.scala +0 -8
  61. package/supervisor-engine/src/main/scala/scada/stream/worker/StreamWorker.scala +0 -135
  62. package/supervisor-engine/src/main/scala/scada/stream/worker/postgres/PgCheckpointStore.scala +0 -83
  63. package/supervisor-engine/src/main/scala/scada/supervisor/core/Condition.scala +0 -33
  64. package/supervisor-engine/src/main/scala/scada/supervisor/core/CyclePhases.scala +0 -65
  65. package/supervisor-engine/src/main/scala/scada/supervisor/core/Emission.scala +0 -19
  66. package/supervisor-engine/src/main/scala/scada/supervisor/core/Params.scala +0 -15
  67. package/supervisor-engine/src/main/scala/scada/supervisor/core/Reading.scala +0 -11
  68. package/supervisor-engine/src/main/scala/scada/supervisor/core/Segment.scala +0 -28
  69. package/supervisor-engine/src/main/scala/scada/supervisor/core/SegmentDef.scala +0 -14
  70. package/supervisor-engine/src/main/scala/scada/supervisor/core/Segmentation.scala +0 -63
  71. package/supervisor-engine/src/main/scala/scada/supervisor/core/SplitFollow.scala +0 -50
  72. package/supervisor-engine/src/main/scala/scada/supervisor/core/SplitPieces.scala +0 -102
  73. package/supervisor-engine/src/main/scala/scada/supervisor/core/TagDef.scala +0 -12
  74. package/supervisor-engine/src/main/scala/scada/supervisor/core/TaggedSegment.scala +0 -19
  75. package/supervisor-engine/src/main/scala/scada/supervisor/core/Tagging.scala +0 -42
  76. package/supervisor-engine/src/main/scala/scada/supervisor/core/Timestamp.scala +0 -26
  77. package/supervisor-engine/src/main/scala/scada/supervisor/core/segmentation/Timeline.scala +0 -43
  78. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ClassifierCursors.scala +0 -58
  79. package/supervisor-engine/vendor/gaps-and-islands/UPSTREAM +0 -4
  80. package/supervisor-engine/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/Island.scala +0 -40
  81. package/supervisor-engine/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandEvent.scala +0 -55
  82. package/supervisor-engine/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandsFlow.scala +0 -127
  83. package/supervisor-engine/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandsPolicy.scala +0 -105
  84. package/supervisor-engine/vendor/temporal-streams/LICENSE +0 -21
  85. /package/{supervisor-engine/vendor/gaps-and-islands → stream-processing/vendor/temporal-streams}/LICENSE +0 -0
  86. /package/{supervisor-engine → stream-processing}/vendor/temporal-streams/UPSTREAM +0 -0
  87. /package/{supervisor-engine → stream-processing}/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/History.scala +0 -0
  88. /package/{supervisor-engine → stream-processing}/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/LocalStreams.scala +0 -0
  89. /package/{supervisor-engine → stream-processing}/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/Overlay.scala +0 -0
  90. /package/{supervisor-engine → stream-processing}/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/Worker.scala +0 -0
@@ -1,102 +0,0 @@
1
- package scada.supervisor.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.supervisor.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.supervisor.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
- )
@@ -1,42 +0,0 @@
1
- package scada.supervisor.core
2
-
3
- /**
4
- * Pure tagging of a [[Segment]] against a list of [[TagDef]]s.
5
- *
6
- * Matching:
7
- * - with empty `currentTags`, candidates whose `when` equals the segment name;
8
- * - with non-empty `currentTags`, candidates whose `when` is in that path.
9
- *
10
- * Cascade:
11
- * - no matches → keep `currentTags`, empty options (leaf / done);
12
- * - one match → append and continue (auto-deepen);
13
- * - many → keep path as tags, list matches as options.
14
- *
15
- * {{{
16
- * Tagging().resolve(tagDefs, segment)
17
- * Tagging().resolve(tagDefs, segment, List("metal_structure"))
18
- * }}}
19
- */
20
- final class Tagging(allow: Segment => Boolean = _ => true):
21
- def resolve(tagDefs: List[TagDef], segment: Segment): TaggedSegment =
22
- resolve(tagDefs, segment, Nil)
23
-
24
- def resolve(tagDefs: List[TagDef], segment: Segment, currentTags: List[String]): TaggedSegment =
25
- if allow(segment) then deepen(tagDefs, segment, currentTags)
26
- else TaggedSegment(segment, Nil, Nil, segment.properties)
27
-
28
- private def deepen(tagDefs: List[TagDef], segment: Segment, currentTags: List[String]): TaggedSegment =
29
- val matching = candidates(tagDefs, segment, currentTags)
30
- matching match
31
- case Nil => TaggedSegment(segment, currentTags, Nil, segment.properties)
32
- case one :: Nil => deepen(tagDefs, segment, currentTags :+ one)
33
- case many => TaggedSegment(segment, currentTags, many, segment.properties)
34
-
35
- private def candidates(tagDefs: List[TagDef], segment: Segment, currentTags: List[String]): List[String] =
36
- tagDefs.collect:
37
- case TagDef(name, Condition.When(when)) if matches(when, segment, currentTags) && !currentTags.contains(name) =>
38
- name
39
-
40
- private def matches(when: String, segment: Segment, currentTags: List[String]): Boolean =
41
- if currentTags.isEmpty then when == segment.name
42
- else currentTags.contains(when)
@@ -1,26 +0,0 @@
1
- package scada.supervisor.core
2
-
3
- /**
4
- * Epoch seconds (double, millisecond precision) as an opaque type so
5
- * it stays allocation-free in segmentation hot paths yet never mixes
6
- * with raw numeric values.
7
- *
8
- * {{{
9
- * val t = Timestamp(1700000000.0)
10
- * t.minus(Timestamp(1699999985.0))
11
- * }}}
12
- */
13
- opaque type Timestamp = Double
14
-
15
- object Timestamp:
16
- def apply(epochSeconds: Double): Timestamp = epochSeconds
17
-
18
- given Ordering[Timestamp] = Ordering.Double.TotalOrdering
19
-
20
- extension (self: Timestamp)
21
- def epoch: Double = self
22
- def millis: Long = (self * 1000).toLong
23
- def minus(other: Timestamp): Double = self - other
24
- def plus(seconds: Double): Timestamp = self + seconds
25
- def isAfter(other: Timestamp): Boolean = self > other
26
- def isBefore(other: Timestamp): Boolean = self < other
@@ -1,43 +0,0 @@
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)
@@ -1,58 +0,0 @@
1
- package scada.supervisor.runtime
2
-
3
- import io.circe.Json
4
- import io.circe.parser.parse
5
- import io.yarkivaev.temporal.{Cursor, LocalStreams}
6
- import java.sql.Connection
7
-
8
- /**
9
- * Persists LocalStreams cursor metadata for one machine. Telemetry
10
- * points stay out of Postgres; only id, position and touchedAt remain.
11
- *
12
- * {{{
13
- * ClassifierCursors.save(connection, "machine-2", pool)
14
- * ClassifierCursors.load(connection, "machine-2", 30000, 10000)
15
- * }}}
16
- */
17
- object ClassifierCursors:
18
- val ddl: String = "CREATE TABLE IF NOT EXISTS classifier_cursors (machine text PRIMARY KEY, snapshot text NOT NULL)"
19
- val writeSql: String = "INSERT INTO classifier_cursors (machine, snapshot) VALUES (?, ?) ON CONFLICT (machine) DO UPDATE SET snapshot = EXCLUDED.snapshot"
20
- val readSql: String = "SELECT snapshot FROM classifier_cursors WHERE machine = ?"
21
- def save(connection: Connection, machine: String, pool: HistoryPool): Unit =
22
- val created = connection.prepareStatement(ddl)
23
- try created.execute()
24
- finally created.close()
25
- val statement = connection.prepareStatement(writeSql)
26
- try
27
- statement.setString(1, machine)
28
- statement.setString(2, snapshot(pool).noSpaces)
29
- val _ = statement.executeUpdate()
30
- finally statement.close()
31
- def load(connection: Connection, machine: String, maxGap: Long, idleTimeout: Long): HistoryPool =
32
- val created = connection.prepareStatement(ddl)
33
- try created.execute()
34
- finally created.close()
35
- val statement = connection.prepareStatement(readSql)
36
- try
37
- statement.setString(1, machine)
38
- val rows = statement.executeQuery()
39
- val pool = if rows.next() then restore(rows.getString(1), maxGap, idleTimeout) else HistoryPool(LocalStreams.empty(maxGap, idleTimeout), Map.empty)
40
- rows.close()
41
- pool
42
- finally statement.close()
43
- private def snapshot(pool: HistoryPool): Json =
44
- Json.obj(
45
- "nextId" -> Json.fromLong(pool.cursors.nextId),
46
- "streams" -> Json.arr(pool.cursors.streams.map: cursor =>
47
- Json.obj("id" -> Json.fromLong(cursor.id), "position" -> Json.fromLong(cursor.position), "touchedAt" -> Json.fromLong(cursor.touchedAt))
48
- *)
49
- )
50
- private def restore(body: String, maxGap: Long, idleTimeout: Long): HistoryPool =
51
- val json = parse(body).getOrElse(Json.obj())
52
- val nextId = json.hcursor.get[Long]("nextId").getOrElse(1L)
53
- val streams = json.hcursor.get[Vector[Json]]("streams").getOrElse(Vector.empty).flatMap: row =>
54
- for
55
- id <- row.hcursor.get[Long]("id").toOption
56
- position <- row.hcursor.get[Long]("position").toOption
57
- yield Cursor(id, position, System.currentTimeMillis())
58
- HistoryPool(LocalStreams(maxGap, idleTimeout, nextId, streams, Vector.empty), Map.empty)
@@ -1,4 +0,0 @@
1
- https://github.com/yarkivaev/gaps-and-islands
2
- Commit: 1a59628544dfc2f788b535f78dae14506cf861cf
3
- Version: 0.1.1
4
- The Scala sources are unmodified. See LICENSE.
@@ -1,40 +0,0 @@
1
- package yarkivaev.gapsandislands.api
2
-
3
- /**
4
- * A run of consecutive observations that share the same classification
5
- * kind.
6
- *
7
- * An `Island` is the fundamental unit of output from an [[IslandsFlow]].
8
- * It represents a contiguous stretch of the input stream in which every
9
- * observation was classified as the same `kind` by an [[IslandsPolicy]].
10
- *
11
- * The library is deliberately agnostic about what an observation is and
12
- * how time is represented. The island therefore carries the actual
13
- * `first` and `last` observations of the run rather than any derived
14
- * metadata: anything domain-specific (duration, midpoint, summary,
15
- * sampling count) is computed by the caller from the payloads.
16
- *
17
- * An `Island` is always non-empty: it is born when an observation is
18
- * first classified as `kind` and grows as subsequent observations of the
19
- * same kind arrive. A single-observation run yields an island with
20
- * `first == last`.
21
- *
22
- * ==Example==
23
- * {{{
24
- * final case class Tick(timestamp: Long, value: Double)
25
- *
26
- * val island = Island(kind = "on", first = Tick(100L, 5.0), last = Tick(180L, 5.2))
27
- * val durationMs = island.last.timestamp - island.first.timestamp
28
- * }}}
29
- *
30
- * @tparam A the observation payload type chosen by the caller
31
- * @tparam K the classification kind type chosen by the caller
32
- * @param kind the classification shared by every observation in the run
33
- * @param first the observation that opened this island
34
- * @param last the most recent observation that extended this island
35
- */
36
- final case class Island[A, K](
37
- kind: K,
38
- first: A,
39
- last: A
40
- )
@@ -1,55 +0,0 @@
1
- package yarkivaev.gapsandislands.api
2
-
3
- /**
4
- * Event emitted by [[IslandsFlow.pipe]] for every observation.
5
- *
6
- * Every input observation produces exactly one or two events:
7
- * - [[IslandEvent.IslandStarted]] — the observation opened a new island;
8
- * - [[IslandEvent.IslandExtended]] — the observation extended the open
9
- * island (same kind as before);
10
- * - [[IslandEvent.IslandClosed]] followed by [[IslandEvent.IslandStarted]]
11
- * — the observation's kind differed, so the previous island ended
12
- * and a new one began.
13
- *
14
- * Because every event carries the [[Island]] it describes (with the
15
- * latest `first`/`last` observations), the stream of events is a
16
- * lossless record of state: the open island after step N is exactly
17
- * the island of the most recent event that is not an
18
- * [[IslandEvent.IslandClosed]].
19
- *
20
- * @tparam A the observation payload type
21
- * @tparam K the classification kind type
22
- */
23
- sealed trait IslandEvent[A, K]:
24
- /** The island described by this event. */
25
- def island: Island[A, K]
26
-
27
- object IslandEvent:
28
- /**
29
- * A new island has just opened.
30
- *
31
- * Emitted on the first observation of a flow or when an
32
- * observation's classified kind differs from the kind of the
33
- * currently open island. The island's `first` and `last` both
34
- * reference the observation that triggered the start.
35
- */
36
- final case class IslandStarted[A, K](island: Island[A, K]) extends IslandEvent[A, K]
37
-
38
- /**
39
- * The current island has absorbed one more observation.
40
- *
41
- * Emitted whenever an observation is classified with the same kind
42
- * as the currently open island. The island's `first` is unchanged;
43
- * `last` now references the new observation.
44
- */
45
- final case class IslandExtended[A, K](island: Island[A, K]) extends IslandEvent[A, K]
46
-
47
- /**
48
- * A previously open island has just closed.
49
- *
50
- * Emitted when a new observation has a different kind than the
51
- * currently open island; an [[IslandStarted]] follows immediately.
52
- * The closed island's `last` references the most recent observation
53
- * that belonged to that run.
54
- */
55
- final case class IslandClosed[A, K](island: Island[A, K]) extends IslandEvent[A, K]
@@ -1,127 +0,0 @@
1
- package yarkivaev.gapsandislands.api
2
-
3
- import fs2.{Chunk, Pipe, Pull, Stream}
4
-
5
- /**
6
- * Pure stream transformation that turns a stream of observations into
7
- * a stream of [[IslandEvent]]s.
8
- *
9
- * The library offers no stateful "flow object". State is threaded
10
- * internally through the pipe's fold over the input; the caller never
11
- * sees the intermediate cursor. Every input observation produces one
12
- * or two events, so the emitted stream is a lossless record of the
13
- * open island over time — any snapshot or derived view is a plain
14
- * stream operation over that output.
15
- *
16
- * The pipe leaves the trailing island open when the input terminates.
17
- * Callers that need a final [[IslandEvent.IslandClosed]] (finite
18
- * batches, explicit end-of-run markers) compose their own terminator;
19
- * doing so is intentionally the caller's concern because the semantics
20
- * of "the input ended" vary by domain.
21
- *
22
- * ==Effect polymorphism==
23
- * The pipe is parametric in the effect `F[_]`. It imposes no typeclass
24
- * constraint: the only effectful step is evaluating the supplied
25
- * [[IslandsPolicy]], which is lifted into the stream via `Pull.eval`.
26
- * `F` is typically `cats.effect.IO`, but anything that the policy
27
- * speaks (`SyncIO`, a custom tagless-final algebra, etc.) works.
28
- *
29
- * ==Usage==
30
- * {{{
31
- * // `F` is inferred from the policy; with an `IslandsPolicy[IO, _, _]`
32
- * // the pipe is `Pipe[IO, A, IslandEvent[A, K]]`.
33
- * val events: Stream[F, IslandEvent[Tick, String]] =
34
- * observations.through(IslandsFlow.pipe(policy, evidence))
35
- *
36
- * // lifecycle-only view
37
- * events.collect {
38
- * case e: IslandEvent.IslandStarted[Tick, String] => e
39
- * case e: IslandEvent.IslandClosed[Tick, String] => e
40
- * }
41
- *
42
- * // open-island checkpoint at each step
43
- * events.map(_.island)
44
- * }}}
45
- */
46
- object IslandsFlow:
47
-
48
- /**
49
- * Build a gaps-and-islands transformation.
50
- *
51
- * The returned pipe consumes observations of type `A`, asks the
52
- * supplied [[IslandsPolicy]] to classify each into a kind of type
53
- * `K`, and emits [[IslandEvent]]s describing how the island
54
- * structure evolves.
55
- *
56
- * ==Recovery==
57
- * Pass `initial = Some(island)` to resume from a previously
58
- * snapshotted open island. No [[IslandEvent.IslandStarted]] is
59
- * emitted for the resumed island; the next observation will either
60
- * extend it (emitting [[IslandEvent.IslandExtended]]) or close it
61
- * (emitting [[IslandEvent.IslandClosed]] followed by
62
- * [[IslandEvent.IslandStarted]]).
63
- *
64
- * ==Snapshot==
65
- * The open island at any point is the `island` of the latest
66
- * non-`IslandClosed` event. Derive it with a plain `scan`:
67
- * {{{
68
- * events.scan(Option.empty[Island[A, K]]) {
69
- * case (_, IslandEvent.IslandClosed(_)) => None
70
- * case (_, other) => Some(other.island)
71
- * }
72
- * }}}
73
- *
74
- * ==Terminal close==
75
- * The pipe emits no event when the input terminates. Callers that
76
- * treat the input as a finite batch and want a final
77
- * [[IslandEvent.IslandClosed]] add one themselves, for example via
78
- * a post-processing pipe that tracks the open island and emits a
79
- * close on end-of-stream.
80
- *
81
- * @tparam F the effect used to evaluate the policy
82
- * @tparam A the observation payload type
83
- * @tparam K the classification kind type
84
- * @tparam E the evidence type consumed by the policy
85
- * @param policy decision rule used to classify each observation
86
- * @param evidence builds the policy's input from the currently open
87
- * island (if any) and the incoming observation
88
- * @param initial optional open island to resume from
89
- */
90
- def pipe[F[_], A, K, E](
91
- policy: IslandsPolicy[F, E, K],
92
- evidence: (Option[Island[A, K]], A) => E,
93
- initial: Option[Island[A, K]] = None
94
- ): Pipe[F, A, IslandEvent[A, K]] =
95
- input => advance(initial, input, policy, evidence).stream
96
-
97
- private def advance[F[_], A, K, E](
98
- state: Option[Island[A, K]],
99
- input: Stream[F, A],
100
- policy: IslandsPolicy[F, E, K],
101
- evidence: (Option[Island[A, K]], A) => E
102
- ): Pull[F, IslandEvent[A, K], Unit] =
103
- input.pull.uncons1.flatMap:
104
- case None => Pull.done
105
- case Some((item, rest)) =>
106
- Pull.eval(policy.decide(evidence(state, item))).flatMap: kind =>
107
- val (next, events) = step(state, item, kind)
108
- Pull.output(Chunk.from(events)) >> advance(next, rest, policy, evidence)
109
-
110
- private def step[A, K](
111
- state: Option[Island[A, K]],
112
- item: A,
113
- kind: K
114
- ): (Option[Island[A, K]], List[IslandEvent[A, K]]) =
115
- state match
116
- case None =>
117
- val fresh = Island(kind, item, item)
118
- (Some(fresh), List(IslandEvent.IslandStarted(fresh)))
119
- case Some(open) if open.kind == kind =>
120
- val extended = Island(kind, open.first, item)
121
- (Some(extended), List(IslandEvent.IslandExtended(extended)))
122
- case Some(open) =>
123
- val fresh = Island(kind, item, item)
124
- (Some(fresh), List(
125
- IslandEvent.IslandClosed(open),
126
- IslandEvent.IslandStarted(fresh)
127
- ))
@@ -1,105 +0,0 @@
1
- package yarkivaev.gapsandislands.api
2
-
3
- import cats.Monad
4
- import cats.data.Kleisli
5
-
6
- /**
7
- * Decision rule that classifies an observation into a kind.
8
- *
9
- * An `IslandsPolicy` is the only place where the caller expresses domain
10
- * meaning. Given whatever evidence it needs — the observation itself, a
11
- * rolling window, a lookup against a database, the previously open
12
- * island — it returns the kind `K` to which the current observation
13
- * belongs. The [[IslandsFlow]] then uses that kind to decide whether to
14
- * extend the current island or close it and open a new one.
15
- *
16
- * There is no privileged "boundary" or "gap" outcome: every observation
17
- * belongs to some island. If the caller wants to distinguish missing
18
- * data, idle periods, or rejected samples from useful runs, they encode
19
- * that distinction as a dedicated value of `K` (for example a
20
- * `"gap"` string or a `Gap` variant of a sealed trait).
21
- *
22
- * ==Composition==
23
- * Policies form a monad over `K` in their shared `F` and `Evidence`.
24
- * `flatMap` runs every stage on every observation, which lets callers
25
- * build refined decisions pipeline-style, for example "first tag as
26
- * live-or-stale, then classify live samples as on-or-off":
27
- *
28
- * {{{
29
- * val tagFreshness: IslandsPolicy[IO, Tick, String] =
30
- * IslandsPolicy(t => IO.pure(if t.ageMs > 30000 then "stale" else "live"))
31
- *
32
- * val refine: String => IslandsPolicy[IO, Tick, String] =
33
- * case "live" => IslandsPolicy(t => IO.pure(if t.power >= 5.0 then "on" else "off"))
34
- * case other => IslandsPolicy(_ => IO.pure(other))
35
- *
36
- * val policy = tagFreshness.flatMap(refine)
37
- * }}}
38
- *
39
- * @tparam F the effect type used to evaluate the decision
40
- * @tparam Evidence the contextual input the policy needs to decide;
41
- * contravariant so narrower evidence types can be
42
- * supplied than declared
43
- * @tparam K the classification kind returned by this policy
44
- */
45
- trait IslandsPolicy[F[_], -Evidence, K]:
46
- /**
47
- * Classify the observation described by `evidence`.
48
- *
49
- * Implementations should be referentially transparent with respect to
50
- * the supplied evidence; any mutable state they need must live inside
51
- * `F`.
52
- *
53
- * @param evidence everything the caller has decided the policy needs
54
- * @return the kind of island the current observation belongs to
55
- */
56
- def decide(evidence: Evidence): F[K]
57
-
58
- object IslandsPolicy:
59
- /**
60
- * Build a policy from a plain decision function.
61
- *
62
- * @param fn function mapping evidence to an effectful kind
63
- */
64
- def apply[F[_], E, K](fn: E => F[K]): IslandsPolicy[F, E, K] =
65
- new IslandsPolicy[F, E, K]:
66
- def decide(evidence: E): F[K] =
67
- fn(evidence)
68
-
69
- /**
70
- * Lift a `cats.data.Kleisli` into an `IslandsPolicy`.
71
- *
72
- * Useful when callers already express their decision logic as a
73
- * `Kleisli[F, E, K]` and want to reuse its combinators before handing
74
- * the rule to a flow.
75
- */
76
- def liftKleisli[F[_], E, K](rule: Kleisli[F, E, K]): IslandsPolicy[F, E, K] =
77
- apply(rule.run)
78
-
79
- extension [F[_], E, K](policy: IslandsPolicy[F, E, K])
80
- /**
81
- * Post-process the kind produced by this policy.
82
- *
83
- * `map` is a pure relabelling: it never changes whether an
84
- * observation is classified, only how the resulting kind is named.
85
- *
86
- * @param fn transformation applied to the classified kind
87
- * @param monad monad instance for the policy's effect
88
- */
89
- def map[L](fn: K => L)(using monad: Monad[F]): IslandsPolicy[F, E, L] =
90
- IslandsPolicy(evidence => monad.map(policy.decide(evidence))(fn))
91
-
92
- /**
93
- * Chain a second decision stage onto this policy.
94
- *
95
- * Both stages are evaluated on every observation; the kind produced
96
- * by the first stage is fed into the function that chooses the next
97
- * policy. This models refinement pipelines where later stages
98
- * specialise the classification of earlier stages.
99
- *
100
- * @param next function producing the next policy from the previous kind
101
- * @param monad monad instance for the policy's effect
102
- */
103
- def flatMap[L](next: K => IslandsPolicy[F, E, L])(using monad: Monad[F]): IslandsPolicy[F, E, L] =
104
- IslandsPolicy: evidence =>
105
- monad.flatMap(policy.decide(evidence))(kind => next(kind).decide(evidence))
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 Yaroslav Kivaev
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.