@yarkivaev/scada 2.6.40 → 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 (79) hide show
  1. package/README.md +13 -768
  2. package/package.json +3 -1
  3. package/src/infrastructure/streams/README.md +12 -5
  4. package/supervisor-engine/src/main/scala/scada/supervisor/core/Condition.scala +33 -0
  5. package/supervisor-engine/src/main/scala/scada/supervisor/core/CyclePhases.scala +65 -0
  6. package/supervisor-engine/src/main/scala/scada/supervisor/core/Decision.scala +67 -0
  7. package/supervisor-engine/src/main/scala/scada/supervisor/core/Emission.scala +19 -0
  8. package/supervisor-engine/src/main/scala/scada/supervisor/core/MachineConfig.scala +21 -0
  9. package/supervisor-engine/src/main/scala/scada/supervisor/core/MachineId.scala +18 -0
  10. package/supervisor-engine/src/main/scala/scada/supervisor/core/MachineMode.scala +4 -0
  11. package/supervisor-engine/src/main/scala/scada/supervisor/core/Params.scala +15 -0
  12. package/supervisor-engine/src/main/scala/scada/supervisor/core/Reading.scala +11 -0
  13. package/supervisor-engine/src/main/scala/scada/supervisor/core/Segment.scala +28 -0
  14. package/supervisor-engine/src/main/scala/scada/supervisor/core/SegmentDef.scala +14 -0
  15. package/supervisor-engine/src/main/scala/scada/supervisor/core/Segmentation.scala +137 -0
  16. package/supervisor-engine/src/main/scala/scada/supervisor/core/Segments.scala +41 -0
  17. package/supervisor-engine/src/main/scala/scada/supervisor/core/SplitFollow.scala +50 -0
  18. package/supervisor-engine/src/main/scala/scada/supervisor/core/SplitPieces.scala +102 -0
  19. package/supervisor-engine/src/main/scala/scada/supervisor/core/Supervisor.scala +66 -0
  20. package/supervisor-engine/src/main/scala/scada/supervisor/core/TagDef.scala +12 -0
  21. package/supervisor-engine/src/main/scala/scada/supervisor/core/TaggedSegment.scala +19 -0
  22. package/supervisor-engine/src/main/scala/scada/supervisor/core/Tagging.scala +42 -0
  23. package/supervisor-engine/src/main/scala/scada/supervisor/core/Timestamp.scala +26 -0
  24. package/supervisor-engine/src/main/scala/scada/supervisor/infra/checkpoint/Checkpoint.scala +61 -0
  25. package/supervisor-engine/src/main/scala/scada/supervisor/infra/checkpoint/ClickhouseReadingsCheckpoint.scala +76 -0
  26. package/supervisor-engine/src/main/scala/scada/supervisor/infra/checkpoint/SupervisorSinkCheckpoint.scala +141 -0
  27. package/supervisor-engine/src/main/scala/scada/supervisor/infra/config/AppConfig.scala +132 -0
  28. package/supervisor-engine/src/main/scala/scada/supervisor/infra/config/ConfigLoad.scala +202 -0
  29. package/supervisor-engine/src/main/scala/scada/supervisor/infra/config/ConfigProfile.scala +13 -0
  30. package/supervisor-engine/src/main/scala/scada/supervisor/infra/mqtt/Mqtt.scala +92 -0
  31. package/supervisor-engine/src/main/scala/scada/supervisor/infra/mqtt/Sessions.scala +18 -0
  32. package/supervisor-engine/src/main/scala/scada/supervisor/infra/state/AtomicStateFile.scala +24 -0
  33. package/supervisor-engine/src/main/scala/scada/supervisor/infra/state/CheckpointSegments.scala +59 -0
  34. package/supervisor-engine/src/main/scala/scada/supervisor/infra/state/SegmentStatePolicy.scala +18 -0
  35. package/supervisor-engine/src/main/scala/scada/supervisor/infra/state/Segments.scala +91 -0
  36. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/ClassifyQueue.scala +37 -0
  37. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/DecisionMessage.scala +49 -0
  38. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/DurableStomp.scala +27 -0
  39. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/SegmentMessage.scala +57 -0
  40. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/SegmentWirePolicy.scala +18 -0
  41. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/SplitFamily.scala +39 -0
  42. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompConnection.scala +106 -0
  43. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompDecisions.scala +43 -0
  44. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompFrame.scala +67 -0
  45. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompMachineDecisions.scala +16 -0
  46. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompQueue.scala +30 -0
  47. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompReadings.scala +29 -0
  48. package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompSegments.scala +115 -0
  49. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ClassifierCursors.scala +58 -0
  50. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ClassifyHistory.scala +92 -0
  51. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ClassifyStreams.scala +67 -0
  52. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/Close.scala +23 -0
  53. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/EngineApp.scala +4 -0
  54. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/HealthServer.scala +38 -0
  55. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/HistoryBus.scala +67 -0
  56. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/HistoryClient.scala +23 -0
  57. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/HistoryRun.scala +86 -0
  58. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/LocalHistory.scala +256 -0
  59. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ObservationLead.scala +26 -0
  60. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/Orphans.scala +26 -0
  61. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/PendingIsland.scala +37 -0
  62. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/RuntimeProfile.scala +32 -0
  63. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/Seeding.scala +105 -0
  64. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/SupervisorRuntime.scala +266 -0
  65. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/WriterEpoch.scala +16 -0
  66. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/WriterGate.scala +35 -0
  67. package/supervisor-engine/src/main/scala/scada/supervisor/runtime/WriterLease.scala +218 -0
  68. package/supervisor-engine/vendor/gaps-and-islands/LICENSE +21 -0
  69. package/supervisor-engine/vendor/gaps-and-islands/UPSTREAM +4 -0
  70. package/supervisor-engine/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/Island.scala +40 -0
  71. package/supervisor-engine/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandEvent.scala +55 -0
  72. package/supervisor-engine/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandsFlow.scala +127 -0
  73. package/supervisor-engine/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandsPolicy.scala +105 -0
  74. package/supervisor-engine/vendor/temporal-streams/LICENSE +21 -0
  75. package/supervisor-engine/vendor/temporal-streams/UPSTREAM +3 -0
  76. package/supervisor-engine/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/History.scala +30 -0
  77. package/supervisor-engine/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/LocalStreams.scala +27 -0
  78. package/supervisor-engine/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/Overlay.scala +15 -0
  79. package/supervisor-engine/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/Worker.scala +21 -0
@@ -0,0 +1,127 @@
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
+ ))
@@ -0,0 +1,105 @@
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))
@@ -0,0 +1,21 @@
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.
@@ -0,0 +1,3 @@
1
+ https://github.com/yarkivaev/temporal-streams
2
+ 00fe5f0f633adf7cd4fa64c031f3ae49a1b82b2d
3
+ Vendored source for review before first release; no unpublished Maven artifact required.
@@ -0,0 +1,30 @@
1
+ package io.yarkivaev.temporal
2
+
3
+ import scala.collection.immutable.TreeMap
4
+
5
+ /** Times use one application-defined integral unit, consistently throughout the engine. */
6
+ final case class Observation(eventId: String, channel: String, time: Long, value: Double)
7
+ trait Conflict:
8
+ def choose(first: Observation, incoming: Observation): Observation
9
+ object Conflict:
10
+ val first: Conflict = new Conflict:
11
+ def choose(first: Observation, incoming: Observation): Observation = first
12
+
13
+ /** Immutable reference history. Applications can implement the same semantics in a database. */
14
+ final case class History(rows: TreeMap[Long, Map[String, Observation]], seen: Set[String]):
15
+ def accept(point: Observation, conflict: Conflict): History =
16
+ if seen(point.eventId) then this
17
+ else
18
+ val group = rows.getOrElse(point.time, Map.empty)
19
+ val chosen = group.get(point.channel).fold(point)(conflict.choose(_,point))
20
+ copy(rows = rows.updated(point.time, group.updated(point.channel, chosen)), seen = seen + point.eventId)
21
+ def at(time: Long): Vector[Observation] = rows.getOrElse(time,Map.empty).toVector.sortBy(_._1).map(_._2)
22
+ /** Inclusive range plus the immediately preceding and following timestamp groups. */
23
+ def context(from: Long, until: Long): Vector[Observation] =
24
+ require(from <= until)
25
+ val times = rows.keysIterator.filter(t => t >= from && t <= until).toVector
26
+ val before = rows.keysIterator.takeWhile(_ < from).toVector.lastOption
27
+ val after = rows.keysIterator.find(_ > until)
28
+ (before.toVector ++ times ++ after.toVector).flatMap(at)
29
+ object History:
30
+ val empty: History = History(TreeMap.empty,Set.empty)
@@ -0,0 +1,27 @@
1
+ package io.yarkivaev.temporal
2
+
3
+ final case class Cursor(id: Long, position: Long, touchedAt: Long)
4
+ final case class Work(id: Long, streamId: Long, from: Long, until: Long)
5
+ final case class Routed(state: LocalStreams, stream: Cursor, work: Work)
6
+ /** Snapshot must be persisted by the owner before acknowledging input. Pending work survives eviction. */
7
+ final case class LocalStreams(maxGap: Long, idleTimeout: Long, nextId: Long, streams: Vector[Cursor], pending: Vector[Work]):
8
+ require(maxGap >= 0 && idleTimeout > 0)
9
+ def route(point: Observation, now: Long): Routed =
10
+ val eligible = streams.filter(c => c.position <= point.time && BigInt(point.time)-BigInt(c.position) <= maxGap)
11
+ val chosen = eligible.sortBy(c => (c.position,c.id)).lastOption
12
+ val cursor = chosen.fold(Cursor(nextId,point.time,now))(_.copy(position = point.time,touchedAt = now))
13
+ val work = Work(nextId + 1,cursor.id,point.time,point.time)
14
+ val next = copy(nextId = nextId + 2, streams = streams.filterNot(_.id == cursor.id) :+ cursor, pending = pending :+ work)
15
+ Routed(next,cursor,work)
16
+ def evict(now: Long): LocalStreams = copy(streams = streams.filter(c => BigInt(now)-BigInt(c.touchedAt) < idleTimeout))
17
+ def acknowledge(workId: Long): LocalStreams = copy(pending = pending.filterNot(_.id == workId))
18
+ /** The application must compare complete classifier states before passing equivalent=true. */
19
+ def merge(keep: Long, remove: Long, equivalent: Boolean): LocalStreams =
20
+ if !equivalent || keep == remove then this
21
+ else
22
+ (streams.find(_.id == keep),streams.find(_.id == remove)) match
23
+ case (Some(a),Some(b)) if a.position == b.position =>
24
+ copy(streams = streams.filterNot(c => c.id == keep || c.id == remove) :+ a.copy(touchedAt = a.touchedAt.max(b.touchedAt)))
25
+ case _ => this
26
+ object LocalStreams:
27
+ def empty(maxGap: Long, idleTimeout: Long): LocalStreams = LocalStreams(maxGap,idleTimeout,1,Vector.empty,Vector.empty)
@@ -0,0 +1,15 @@
1
+ package io.yarkivaev.temporal
2
+
3
+ final case class Segment(id: String, start: Long, end: Long, kind: String, ancestors: Set[String]):
4
+ require(start <= end)
5
+ final case class Annotation(id: String, anchor: String, value: String, applicableKinds: Set[String])
6
+ final case class Decorated(segment: Segment, annotations: Vector[String])
7
+ object Overlay:
8
+ /** Does not merge segments. Ancestry follows extension and splitting, never timestamp proximity. */
9
+ def apply(segments: Vector[Segment], annotations: Vector[Annotation], cuts: Vector[Long]): Vector[Decorated] =
10
+ segments.flatMap: segment =>
11
+ val marks = annotations.filter(a => (a.anchor == segment.id || segment.ancestors(a.anchor)) && a.applicableKinds(segment.kind)).map(_.id)
12
+ val boundaries = Vector(segment.start) ++ cuts.filter(t => t > segment.start && t < segment.end).distinct.sorted ++ Vector(segment.end)
13
+ boundaries.sliding(2).collect:
14
+ case Vector(start,end) => Decorated(segment.copy(id = if start == segment.start then segment.id else s"${segment.id}:cut:$start",start = start,end = end), marks)
15
+ .toVector
@@ -0,0 +1,21 @@
1
+ package io.yarkivaev.temporal
2
+
3
+ import cats.Monad
4
+ import cats.syntax.all.*
5
+ import fs2.Pipe
6
+
7
+ /** Persistent application ports. commit must be idempotent for work.id; acknowledge only retires work. */
8
+ trait Processing[F[_], Result]:
9
+ /** None means required historical context is unavailable; do not classify. */
10
+ def context(work: Work): F[Option[Vector[Observation]]]
11
+ def classify(work: Work, context: Vector[Observation]): F[Vector[Result]]
12
+ def commit(work: Work, result: Vector[Result]): F[Unit]
13
+ def acknowledge(work: Work): F[Unit]
14
+
15
+ final class Worker[F[_]: Monad, Result](ports: Processing[F,Result]):
16
+ def run(work: Work): F[Unit] =
17
+ ports.context(work).flatMap:
18
+ case None => ports.acknowledge(work)
19
+ case Some(points) => ports.classify(work,points).flatMap(ports.commit(work,_)) *> ports.acknowledge(work)
20
+ /** Serial processing is intentional: external partitioning can provide bounded parallelism. */
21
+ def pipe: Pipe[F,Work,Unit] = _.evalMap(run)