@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.
- package/README.md +13 -768
- package/package.json +3 -1
- package/src/infrastructure/streams/README.md +12 -5
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Condition.scala +33 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/CyclePhases.scala +65 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Decision.scala +67 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Emission.scala +19 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/MachineConfig.scala +21 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/MachineId.scala +18 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/MachineMode.scala +4 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Params.scala +15 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Reading.scala +11 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Segment.scala +28 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/SegmentDef.scala +14 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Segmentation.scala +137 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Segments.scala +41 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/SplitFollow.scala +50 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/SplitPieces.scala +102 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Supervisor.scala +66 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/TagDef.scala +12 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/TaggedSegment.scala +19 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Tagging.scala +42 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/core/Timestamp.scala +26 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/checkpoint/Checkpoint.scala +61 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/checkpoint/ClickhouseReadingsCheckpoint.scala +76 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/checkpoint/SupervisorSinkCheckpoint.scala +141 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/config/AppConfig.scala +132 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/config/ConfigLoad.scala +202 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/config/ConfigProfile.scala +13 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/mqtt/Mqtt.scala +92 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/mqtt/Sessions.scala +18 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/state/AtomicStateFile.scala +24 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/state/CheckpointSegments.scala +59 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/state/SegmentStatePolicy.scala +18 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/state/Segments.scala +91 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/ClassifyQueue.scala +37 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/DecisionMessage.scala +49 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/DurableStomp.scala +27 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/SegmentMessage.scala +57 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/SegmentWirePolicy.scala +18 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/SplitFamily.scala +39 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompConnection.scala +106 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompDecisions.scala +43 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompFrame.scala +67 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompMachineDecisions.scala +16 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompQueue.scala +30 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompReadings.scala +29 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/infra/stomp/StompSegments.scala +115 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ClassifierCursors.scala +58 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ClassifyHistory.scala +92 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ClassifyStreams.scala +67 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/Close.scala +23 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/EngineApp.scala +4 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/HealthServer.scala +38 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/HistoryBus.scala +67 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/HistoryClient.scala +23 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/HistoryRun.scala +86 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/LocalHistory.scala +256 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/ObservationLead.scala +26 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/Orphans.scala +26 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/PendingIsland.scala +37 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/RuntimeProfile.scala +32 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/Seeding.scala +105 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/SupervisorRuntime.scala +266 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/WriterEpoch.scala +16 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/WriterGate.scala +35 -0
- package/supervisor-engine/src/main/scala/scada/supervisor/runtime/WriterLease.scala +218 -0
- package/supervisor-engine/vendor/gaps-and-islands/LICENSE +21 -0
- package/supervisor-engine/vendor/gaps-and-islands/UPSTREAM +4 -0
- package/supervisor-engine/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/Island.scala +40 -0
- package/supervisor-engine/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandEvent.scala +55 -0
- package/supervisor-engine/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandsFlow.scala +127 -0
- package/supervisor-engine/vendor/gaps-and-islands/src/main/scala/yarkivaev/gapsandislands/api/IslandsPolicy.scala +105 -0
- package/supervisor-engine/vendor/temporal-streams/LICENSE +21 -0
- package/supervisor-engine/vendor/temporal-streams/UPSTREAM +3 -0
- package/supervisor-engine/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/History.scala +30 -0
- package/supervisor-engine/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/LocalStreams.scala +27 -0
- package/supervisor-engine/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/Overlay.scala +15 -0
- package/supervisor-engine/vendor/temporal-streams/src/main/scala/io/yarkivaev/temporal/Worker.scala +21 -0
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
package scada.supervisor.infra.config
|
|
2
|
+
|
|
3
|
+
import scada.supervisor.core.{CyclePhases, MachineConfig, MachineId}
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Alias routing entry: which MQTT topic carries which metric.
|
|
7
|
+
*
|
|
8
|
+
* {{{
|
|
9
|
+
* AliasMapping("machine-1/power", "power")
|
|
10
|
+
* }}}
|
|
11
|
+
*/
|
|
12
|
+
final case class AliasMapping(topic: String, metric: String)
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Alias routing table (machine → its topic/metric list).
|
|
16
|
+
*
|
|
17
|
+
* {{{
|
|
18
|
+
* RoutingConfig(Map(MachineId("machine-1") -> List(AliasMapping(...))))
|
|
19
|
+
* }}}
|
|
20
|
+
*/
|
|
21
|
+
final case class RoutingConfig(aliases: Map[MachineId, List[AliasMapping]])
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* MQTT broker connection settings.
|
|
25
|
+
*
|
|
26
|
+
* {{{
|
|
27
|
+
* MqttConfig("localhost", 1883, "sup")
|
|
28
|
+
* }}}
|
|
29
|
+
*/
|
|
30
|
+
final case class MqttConfig(host: String, port: Int, clientId: String, username: Option[String] = None, password: Option[String] = None):
|
|
31
|
+
require(username.isDefined == password.isDefined, "MQTT username and password must be supplied together")
|
|
32
|
+
require(username.forall(_.nonEmpty) && password.forall(_.nonEmpty), "MQTT credentials must be nonempty")
|
|
33
|
+
|
|
34
|
+
/** STOMP broker endpoint. */
|
|
35
|
+
final case class StompAddress(host: String, port: Int)
|
|
36
|
+
|
|
37
|
+
/** STOMP login credentials. */
|
|
38
|
+
final case class StompCredentials(login: String, passcode: String)
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* RabbitMQ STOMP destinations. `segments` is optional — when absent
|
|
42
|
+
* outbound segment publishing is disabled.
|
|
43
|
+
*
|
|
44
|
+
* {{{
|
|
45
|
+
* StompDestinations("user_decisions", Some("segments"))
|
|
46
|
+
* }}}
|
|
47
|
+
*/
|
|
48
|
+
final case class StompDestinations(userDecisions: String, segments: Option[String])
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* RabbitMQ STOMP connection and routing settings.
|
|
52
|
+
*
|
|
53
|
+
* {{{
|
|
54
|
+
* RabbitMqConfig(StompAddress("rmq", 61613), "/", StompCredentials(...), StompDestinations(...))
|
|
55
|
+
* }}}
|
|
56
|
+
*/
|
|
57
|
+
final case class RabbitMqConfig(
|
|
58
|
+
address: StompAddress,
|
|
59
|
+
vhost: String,
|
|
60
|
+
credentials: StompCredentials,
|
|
61
|
+
destinations: StompDestinations
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
/** Internal checkpoint API exposed by supervisor-sink. */
|
|
65
|
+
final case class CheckpointApiConfig(baseUrl: String, token: Option[String], timeoutSeconds: Int)
|
|
66
|
+
|
|
67
|
+
object CheckpointApiConfig:
|
|
68
|
+
val defaultTimeoutSeconds: Int = 10
|
|
69
|
+
|
|
70
|
+
final case class ClickhouseReadingsConfig(
|
|
71
|
+
baseUrl: String,
|
|
72
|
+
database: String,
|
|
73
|
+
table: String,
|
|
74
|
+
batchSize: Int,
|
|
75
|
+
timeoutSeconds: Int
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
object ClickhouseReadingsConfig:
|
|
79
|
+
val defaultTable: String = "metrics"
|
|
80
|
+
val defaultBatchSize: Int = 5000
|
|
81
|
+
val defaultTimeoutSeconds: Int = 30
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* IO boundaries of the supervisor. `checkpointApi` is optional; without it
|
|
85
|
+
* startup replay and pending-island restore are disabled.
|
|
86
|
+
*/
|
|
87
|
+
final case class ConnectivityConfig(
|
|
88
|
+
mqtt: MqttConfig,
|
|
89
|
+
rabbitmq: RabbitMqConfig,
|
|
90
|
+
checkpointApi: Option[CheckpointApiConfig],
|
|
91
|
+
clickhouseReadings: Option[ClickhouseReadingsConfig]
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Bounded-queue capacity for the startup replay-to-live seam.
|
|
96
|
+
* Larger values absorb more live readings while history drains at
|
|
97
|
+
* the cost of heap; smaller values back-pressure Paho sooner.
|
|
98
|
+
*/
|
|
99
|
+
final case class SeedingConfig(capacity: Int, useClickhouseReadings: Boolean)
|
|
100
|
+
|
|
101
|
+
object SeedingConfig:
|
|
102
|
+
val default: SeedingConfig = SeedingConfig(10000, false)
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* HTTP health/readiness endpoint binding. `/health` and `/ready` are
|
|
106
|
+
* process liveness. Source silence is a tape cover, not a 503.
|
|
107
|
+
*/
|
|
108
|
+
final case class HealthConfig(port: Int, readyWindowSeconds: Int)
|
|
109
|
+
|
|
110
|
+
object HealthConfig:
|
|
111
|
+
val default: HealthConfig = HealthConfig(8080, 60)
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Top-level application configuration loaded from HOCON.
|
|
115
|
+
*
|
|
116
|
+
* {{{
|
|
117
|
+
* AppConfig(connectivity, machines, routing, seeding, health, cyclePhases)
|
|
118
|
+
* }}}
|
|
119
|
+
*/
|
|
120
|
+
final case class AppConfig(
|
|
121
|
+
connectivity: ConnectivityConfig,
|
|
122
|
+
machines: List[MachineConfig],
|
|
123
|
+
routing: RoutingConfig,
|
|
124
|
+
seeding: SeedingConfig,
|
|
125
|
+
health: HealthConfig,
|
|
126
|
+
cyclePhases: CyclePhases,
|
|
127
|
+
localHistory: Boolean = false,
|
|
128
|
+
writerEpoch: Option[Long] = None,
|
|
129
|
+
leaseUrl: Option[String] = None,
|
|
130
|
+
writerRole: Option[String] = None,
|
|
131
|
+
leaseHeld: Boolean = true
|
|
132
|
+
)
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
package scada.supervisor.infra.config
|
|
2
|
+
|
|
3
|
+
import cats.effect.IO
|
|
4
|
+
import com.typesafe.config.{Config, ConfigFactory, ConfigValueType}
|
|
5
|
+
import scada.supervisor.core.*
|
|
6
|
+
import scala.jdk.CollectionConverters.*
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Loads and validates [[AppConfig]] from HOCON files. Fails fast on
|
|
10
|
+
* missing required paths and unknown condition shapes.
|
|
11
|
+
*
|
|
12
|
+
* {{{
|
|
13
|
+
* ConfigLoad().load("config/application.conf")
|
|
14
|
+
* }}}
|
|
15
|
+
*/
|
|
16
|
+
final class ConfigLoad(
|
|
17
|
+
runtimeToken: Option[String] = sys.env.get("STATE_HTTP_TOKEN"),
|
|
18
|
+
env: collection.Map[String, String] = sys.env,
|
|
19
|
+
profile: ConfigProfile = ConfigProfile.default
|
|
20
|
+
):
|
|
21
|
+
def load(path: String): IO[AppConfig] = IO:
|
|
22
|
+
parse(ConfigFactory.parseFile(java.io.File(path)).resolve())
|
|
23
|
+
|
|
24
|
+
private def parse(raw: Config): AppConfig =
|
|
25
|
+
val historyOn = (raw.hasPath("history.enabled") && raw.getBoolean("history.enabled")) || env.get("SUPERVISOR_LOCAL_HISTORY").contains("true")
|
|
26
|
+
val epoch = writerEpoch(raw)
|
|
27
|
+
val lease = leaseUrl(raw)
|
|
28
|
+
val role = writerRole(raw)
|
|
29
|
+
val held = env.contains("SUPERVISOR_LEASE_URL") || !env.contains("SUPERVISOR_LEASE_URL_HELD")
|
|
30
|
+
require(!historyOn || epoch.exists(_ >= 1L), "Local history requires a positive writer epoch")
|
|
31
|
+
require(!historyOn || lease.exists(_.nonEmpty), "Local history requires a lease url")
|
|
32
|
+
val loaded = AppConfig(
|
|
33
|
+
connectivity(raw),
|
|
34
|
+
classifyGroup(machines(raw)),
|
|
35
|
+
routing(raw.getConfig("routing")),
|
|
36
|
+
seeding(raw),
|
|
37
|
+
health(raw),
|
|
38
|
+
cyclePhases(raw),
|
|
39
|
+
historyOn,
|
|
40
|
+
epoch,
|
|
41
|
+
lease,
|
|
42
|
+
role,
|
|
43
|
+
held
|
|
44
|
+
)
|
|
45
|
+
profile.validate(raw, loaded)
|
|
46
|
+
loaded
|
|
47
|
+
|
|
48
|
+
private def writerEpoch(raw: Config): Option[Long] =
|
|
49
|
+
val configured = if raw.hasPath("history.writer-epoch") then Some(raw.getLong("history.writer-epoch")) else None
|
|
50
|
+
val epoch = configured.orElse(env.get("SUPERVISOR_WRITER_EPOCH").map(_.toLong))
|
|
51
|
+
epoch.foreach(value => require(value >= 1L, s"Writer epoch must be positive, message $value"))
|
|
52
|
+
epoch
|
|
53
|
+
|
|
54
|
+
private def writerRole(raw: Config): Option[String] =
|
|
55
|
+
val configured = if raw.hasPath("history.role") then Some(raw.getString("history.role")) else None
|
|
56
|
+
val role = configured.orElse(env.get("SUPERVISOR_WRITER_ROLE"))
|
|
57
|
+
role.foreach(value => require(value == "leader" || value == "standby", s"Writer role must be leader or standby, role $value"))
|
|
58
|
+
role
|
|
59
|
+
|
|
60
|
+
private def leaseUrl(raw: Config): Option[String] =
|
|
61
|
+
val configured = if raw.hasPath("history.lease-url") then Some(raw.getString("history.lease-url")) else None
|
|
62
|
+
val url = configured.orElse(env.get("SUPERVISOR_LEASE_URL")).orElse(env.get("SUPERVISOR_LEASE_URL_HELD"))
|
|
63
|
+
url.foreach(value => require(value.startsWith("jdbc:postgresql:") || value.startsWith("postgresql://") || value.startsWith("postgres://"), "Lease url must be a postgres jdbc url"))
|
|
64
|
+
url
|
|
65
|
+
|
|
66
|
+
private def connectivity(raw: Config): ConnectivityConfig =
|
|
67
|
+
ConnectivityConfig(mqtt(raw), rabbitmq(raw), checkpointApi(raw), clickhouseReadings(raw))
|
|
68
|
+
|
|
69
|
+
private def mqtt(raw: Config): MqttConfig =
|
|
70
|
+
MqttConfig(raw.getString("mqtt.host"), raw.getInt("mqtt.port"), raw.getString("mqtt.client-id"),
|
|
71
|
+
Option.when(raw.hasPath("mqtt.username"))(raw.getString("mqtt.username")),
|
|
72
|
+
Option.when(raw.hasPath("mqtt.password"))(raw.getString("mqtt.password")))
|
|
73
|
+
|
|
74
|
+
private def rabbitmq(raw: Config): RabbitMqConfig =
|
|
75
|
+
val segmentsDest =
|
|
76
|
+
if raw.hasPath("rabbitmq.destinations.segments") then Some(raw.getString("rabbitmq.destinations.segments"))
|
|
77
|
+
else None
|
|
78
|
+
RabbitMqConfig(
|
|
79
|
+
StompAddress(raw.getString("rabbitmq.address.host"), raw.getInt("rabbitmq.address.port")),
|
|
80
|
+
raw.getString("rabbitmq.vhost"),
|
|
81
|
+
StompCredentials(raw.getString("rabbitmq.credentials.login"), raw.getString("rabbitmq.credentials.passcode")),
|
|
82
|
+
StompDestinations(raw.getString("rabbitmq.destinations.user-decisions"), segmentsDest)
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
private def checkpointApi(raw: Config): Option[CheckpointApiConfig] =
|
|
86
|
+
if raw.hasPath("checkpoint-api.base-url") then
|
|
87
|
+
val token =
|
|
88
|
+
if raw.hasPath("checkpoint-api.token") then Some(raw.getString("checkpoint-api.token"))
|
|
89
|
+
else runtimeToken
|
|
90
|
+
val timeoutSeconds =
|
|
91
|
+
if raw.hasPath("checkpoint-api.timeout-seconds") then raw.getInt("checkpoint-api.timeout-seconds")
|
|
92
|
+
else CheckpointApiConfig.defaultTimeoutSeconds
|
|
93
|
+
Some(CheckpointApiConfig(raw.getString("checkpoint-api.base-url"), token, timeoutSeconds))
|
|
94
|
+
else None
|
|
95
|
+
|
|
96
|
+
private def seeding(raw: Config): SeedingConfig =
|
|
97
|
+
val capacity =
|
|
98
|
+
if raw.hasPath("seeding.capacity") then raw.getInt("seeding.capacity")
|
|
99
|
+
else SeedingConfig.default.capacity
|
|
100
|
+
val useClickhouseReadings =
|
|
101
|
+
if raw.hasPath("seeding.use-clickhouse-readings") then raw.getBoolean("seeding.use-clickhouse-readings")
|
|
102
|
+
else SeedingConfig.default.useClickhouseReadings
|
|
103
|
+
SeedingConfig(capacity, useClickhouseReadings)
|
|
104
|
+
|
|
105
|
+
private def clickhouseReadings(raw: Config): Option[ClickhouseReadingsConfig] =
|
|
106
|
+
if raw.hasPath("clickhouse-readings.base-url") then
|
|
107
|
+
val table =
|
|
108
|
+
if raw.hasPath("clickhouse-readings.table") then raw.getString("clickhouse-readings.table")
|
|
109
|
+
else ClickhouseReadingsConfig.defaultTable
|
|
110
|
+
val batchSize =
|
|
111
|
+
if raw.hasPath("clickhouse-readings.batch-size") then raw.getInt("clickhouse-readings.batch-size")
|
|
112
|
+
else ClickhouseReadingsConfig.defaultBatchSize
|
|
113
|
+
val timeoutSeconds =
|
|
114
|
+
if raw.hasPath("clickhouse-readings.timeout-seconds") then raw.getInt("clickhouse-readings.timeout-seconds")
|
|
115
|
+
else ClickhouseReadingsConfig.defaultTimeoutSeconds
|
|
116
|
+
Some(ClickhouseReadingsConfig(
|
|
117
|
+
raw.getString("clickhouse-readings.base-url"),
|
|
118
|
+
raw.getString("clickhouse-readings.database"),
|
|
119
|
+
table,
|
|
120
|
+
batchSize,
|
|
121
|
+
timeoutSeconds
|
|
122
|
+
))
|
|
123
|
+
else None
|
|
124
|
+
|
|
125
|
+
private def health(raw: Config): HealthConfig =
|
|
126
|
+
val port =
|
|
127
|
+
if raw.hasPath("health.port") then raw.getInt("health.port") else HealthConfig.default.port
|
|
128
|
+
val window =
|
|
129
|
+
if raw.hasPath("health.ready-window-seconds") then raw.getInt("health.ready-window-seconds")
|
|
130
|
+
else HealthConfig.default.readyWindowSeconds
|
|
131
|
+
HealthConfig(port, window)
|
|
132
|
+
|
|
133
|
+
private def classifyGroup(loaded: List[MachineConfig]): List[MachineConfig] =
|
|
134
|
+
val want = env.get("CLASSIFY_GROUP").toList.flatMap(_.split(',')).map(_.trim).filter(_.nonEmpty).toSet
|
|
135
|
+
loaded.filter(machine => want(machine.id.raw) || profile.inGroup(machine, want))
|
|
136
|
+
|
|
137
|
+
private def machines(raw: Config): List[MachineConfig] =
|
|
138
|
+
raw.getConfigList("machines").asScala.toList.map(machine)
|
|
139
|
+
|
|
140
|
+
private def machine(raw: Config): MachineConfig =
|
|
141
|
+
MachineConfig(
|
|
142
|
+
MachineId(raw.getString("id")),
|
|
143
|
+
raw.getConfigList("segments").asScala.toList.map(segmentDef),
|
|
144
|
+
if raw.hasPath("tags") then raw.getConfigList("tags").asScala.toList.map(tagDef) else Nil,
|
|
145
|
+
raw.getInt("window"),
|
|
146
|
+
profile.mode(raw)
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
private def segmentDef(raw: Config): SegmentDef =
|
|
150
|
+
SegmentDef(raw.getString("name"), condition(raw.getConfig("condition")))
|
|
151
|
+
|
|
152
|
+
private def tagDef(raw: Config): TagDef =
|
|
153
|
+
TagDef(raw.getString("name"), condition(raw.getConfig("condition")))
|
|
154
|
+
|
|
155
|
+
private def condition(raw: Config): Condition =
|
|
156
|
+
if raw.hasPath("above") then
|
|
157
|
+
Condition.Above(raw.getConfig("above").getString("param"), raw.getConfig("above").getDouble("threshold"))
|
|
158
|
+
else if raw.hasPath("below") then
|
|
159
|
+
Condition.Below(raw.getConfig("below").getString("param"), raw.getConfig("below").getDouble("threshold"))
|
|
160
|
+
else if raw.hasPath("equal") then
|
|
161
|
+
Condition.Equal(raw.getConfig("equal").getString("param"), raw.getConfig("equal").getDouble("value"))
|
|
162
|
+
else if raw.hasPath("when") then Condition.When(raw.getString("when"))
|
|
163
|
+
else if raw.hasPath("and") then
|
|
164
|
+
raw.getConfigList("and").asScala.toList.map(condition).reduceLeft(Condition.And(_, _))
|
|
165
|
+
else if raw.hasPath("or") then
|
|
166
|
+
raw.getConfigList("or").asScala.toList.map(condition).reduceLeft(Condition.Or(_, _))
|
|
167
|
+
else throw RuntimeException(s"unknown condition shape: ${raw.root().keySet()}")
|
|
168
|
+
|
|
169
|
+
private def routing(raw: Config): RoutingConfig =
|
|
170
|
+
val aliasesRaw = raw.getConfig("aliases")
|
|
171
|
+
RoutingConfig(aliasesRaw.root().keySet().asScala.toList.map: id =>
|
|
172
|
+
MachineId(id) -> aliasesRaw.getConfigList(id).asScala.toList.map: a =>
|
|
173
|
+
AliasMapping(a.getString("topic"), a.getString("metric"))
|
|
174
|
+
.toMap)
|
|
175
|
+
|
|
176
|
+
private def cyclePhases(raw: Config): CyclePhases =
|
|
177
|
+
if !raw.hasPath("cycle-phases") then CyclePhases.empty
|
|
178
|
+
else
|
|
179
|
+
val cfg = raw.getConfig("cycle-phases")
|
|
180
|
+
val names = cfg.root().keySet().asScala.toList.filterNot(key => key == "flat" || key == "anchors")
|
|
181
|
+
val loaded = names.map: name =>
|
|
182
|
+
val block = cfg.getConfig(name)
|
|
183
|
+
val allow = block.getStringList("allow").asScala.toList
|
|
184
|
+
val enter = if block.hasPath("enter") then Some(block.getString("enter")) else None
|
|
185
|
+
CyclePhase(allow, enter)
|
|
186
|
+
if !loaded.exists(_.enter.isEmpty) then
|
|
187
|
+
throw RuntimeException("cycle-phases has no idle phase without enter")
|
|
188
|
+
CyclePhases(
|
|
189
|
+
cfg.getStringList("flat").asScala.toList,
|
|
190
|
+
CycleAnchors(
|
|
191
|
+
cfg.getString("anchors.start"),
|
|
192
|
+
stopIds(cfg.getConfig("anchors"))
|
|
193
|
+
),
|
|
194
|
+
loaded
|
|
195
|
+
)
|
|
196
|
+
|
|
197
|
+
private def stopIds(anchors: Config): List[String] =
|
|
198
|
+
if anchors.hasPath("stops") && anchors.getValue("stops").valueType == ConfigValueType.LIST then
|
|
199
|
+
anchors.getStringList("stops").asScala.toList
|
|
200
|
+
else if anchors.hasPath("stop") && anchors.getValue("stop").valueType == ConfigValueType.LIST then
|
|
201
|
+
anchors.getStringList("stop").asScala.toList
|
|
202
|
+
else List(anchors.getString("stop"))
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
package scada.supervisor.infra.config
|
|
2
|
+
|
|
3
|
+
import com.typesafe.config.Config
|
|
4
|
+
import scada.supervisor.core.{MachineConfig, MachineMode}
|
|
5
|
+
|
|
6
|
+
/** Extension points for site-specific HOCON rules and groups. */
|
|
7
|
+
trait ConfigProfile:
|
|
8
|
+
def mode(machine: Config): Option[MachineMode] = None
|
|
9
|
+
def inGroup(machine: MachineConfig, groups: Set[String]): Boolean = false
|
|
10
|
+
def validate(raw: Config, config: AppConfig): Unit = ()
|
|
11
|
+
|
|
12
|
+
object ConfigProfile:
|
|
13
|
+
val default: ConfigProfile = new ConfigProfile {}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
package scada.supervisor.infra.mqtt
|
|
2
|
+
|
|
3
|
+
import cats.effect.{IO, Resource}
|
|
4
|
+
import fs2.Stream
|
|
5
|
+
import io.circe.parser.parse as parseJson
|
|
6
|
+
import java.util.concurrent.LinkedBlockingQueue
|
|
7
|
+
import org.eclipse.paho.client.mqttv3.{
|
|
8
|
+
IMqttDeliveryToken,
|
|
9
|
+
MqttCallbackExtended,
|
|
10
|
+
MqttClient,
|
|
11
|
+
MqttConnectOptions,
|
|
12
|
+
MqttMessage as PahoMqttMessage
|
|
13
|
+
}
|
|
14
|
+
import org.slf4j.LoggerFactory
|
|
15
|
+
import org.typelevel.log4cats.Logger
|
|
16
|
+
import org.typelevel.log4cats.slf4j.Slf4jLogger
|
|
17
|
+
import scada.supervisor.core.*
|
|
18
|
+
import scada.supervisor.infra.config.{AliasMapping, MqttConfig}
|
|
19
|
+
import scala.concurrent.duration.*
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* MQTT reading stream for one machine. Subscribes to the topics
|
|
23
|
+
* listed in `aliases`, parses `{ts, value}` JSON payloads, and emits
|
|
24
|
+
* one single-metric [[Reading]] per message.
|
|
25
|
+
*
|
|
26
|
+
* A dropped broker connection ends the inner session; [[Sessions]]
|
|
27
|
+
* opens a new client and resubscribes.
|
|
28
|
+
*
|
|
29
|
+
* {{{
|
|
30
|
+
* Mqtt(mqttConfig, aliases).subscribe
|
|
31
|
+
* }}}
|
|
32
|
+
*/
|
|
33
|
+
final class Mqtt(config: MqttConfig, aliases: List[AliasMapping]):
|
|
34
|
+
|
|
35
|
+
private given Logger[IO] = Slf4jLogger.getLogger[IO]
|
|
36
|
+
private val callbackLog = LoggerFactory.getLogger(getClass)
|
|
37
|
+
|
|
38
|
+
def subscribe: Stream[IO, Reading] =
|
|
39
|
+
Sessions(1.second).repeat(IO(session))
|
|
40
|
+
|
|
41
|
+
private def session: Stream[IO, Reading] =
|
|
42
|
+
val queue = LinkedBlockingQueue[Option[Reading]]()
|
|
43
|
+
val topics = aliases.map(_.topic)
|
|
44
|
+
val client = Resource.make(
|
|
45
|
+
Logger[IO].info(s"MQTT connecting to ${config.host}:${config.port} topics=${topics.size}") *>
|
|
46
|
+
connect(topics, queue)
|
|
47
|
+
)(c =>
|
|
48
|
+
Logger[IO].info("MQTT disconnecting") *>
|
|
49
|
+
IO.blocking(c.disconnect()).attempt.void *> IO.blocking(c.close()).attempt.void
|
|
50
|
+
)
|
|
51
|
+
Stream.resource(client) >> Stream.repeatEval(IO.interruptible(queue.take())).unNoneTerminate
|
|
52
|
+
|
|
53
|
+
private def connect(topics: List[String], queue: LinkedBlockingQueue[Option[Reading]]): IO[MqttClient] = IO.blocking:
|
|
54
|
+
val client = MqttClient(s"tcp://${config.host}:${config.port}", config.clientId)
|
|
55
|
+
val opts = Mqtt.options(config)
|
|
56
|
+
client.setCallback(new MqttCallbackExtended:
|
|
57
|
+
def connectComplete(reconnect: Boolean, serverURI: String): Unit =
|
|
58
|
+
if reconnect && topics.nonEmpty then client.subscribe(topics.toArray, topics.map(_ => 1).toArray)
|
|
59
|
+
def connectionLost(cause: Throwable): Unit =
|
|
60
|
+
val reason = Option(cause).flatMap(e => Option(e.getMessage)).getOrElse("unknown")
|
|
61
|
+
callbackLog.warn("MQTT connection lost for {}: {}", config.clientId, reason)
|
|
62
|
+
queue.put(None)
|
|
63
|
+
def messageArrived(topic: String, message: PahoMqttMessage): Unit =
|
|
64
|
+
val payload = String(message.getPayload)
|
|
65
|
+
reading(topic, payload) match
|
|
66
|
+
case Some(r) => queue.put(Some(r))
|
|
67
|
+
case None => callbackLog.warn("dropping MQTT message on {}: payload did not match {{ts, value}}: {}", topic, payload)
|
|
68
|
+
def deliveryComplete(token: IMqttDeliveryToken): Unit = ()
|
|
69
|
+
)
|
|
70
|
+
client.connect(opts)
|
|
71
|
+
if topics.nonEmpty then client.subscribe(topics.toArray, topics.map(_ => 1).toArray)
|
|
72
|
+
client
|
|
73
|
+
|
|
74
|
+
private def reading(topic: String, payload: String): Option[Reading] =
|
|
75
|
+
for
|
|
76
|
+
metric <- aliases.find(_.topic == topic).map(_.metric)
|
|
77
|
+
json <- parseJson(payload).toOption
|
|
78
|
+
rawTs <- json.hcursor.downField("ts").as[Double].toOption
|
|
79
|
+
value <- json.hcursor.downField("value").as[Double].toOption
|
|
80
|
+
yield
|
|
81
|
+
val epochSeconds = if rawTs > 1e10 then rawTs / 1000.0 else rawTs
|
|
82
|
+
Reading(Timestamp(epochSeconds), Params(Map(metric -> value)))
|
|
83
|
+
|
|
84
|
+
object Mqtt:
|
|
85
|
+
private[mqtt] def options(config: MqttConfig): MqttConnectOptions =
|
|
86
|
+
val options = MqttConnectOptions()
|
|
87
|
+
options.setAutomaticReconnect(false)
|
|
88
|
+
options.setCleanSession(true)
|
|
89
|
+
options.setKeepAliveInterval(60)
|
|
90
|
+
config.username.foreach(options.setUserName)
|
|
91
|
+
config.password.foreach(value => options.setPassword(value.toCharArray))
|
|
92
|
+
options
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
package scada.supervisor.infra.mqtt
|
|
2
|
+
|
|
3
|
+
import cats.effect.IO
|
|
4
|
+
import fs2.Stream
|
|
5
|
+
import scala.concurrent.duration.FiniteDuration
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Repeats an inner readings stream after it ends so a dropped MQTT
|
|
9
|
+
* session is followed by a fresh `open`.
|
|
10
|
+
*
|
|
11
|
+
* {{{
|
|
12
|
+
* Sessions(1.second).repeat(IO(session))
|
|
13
|
+
* }}}
|
|
14
|
+
*/
|
|
15
|
+
final class Sessions(pause: FiniteDuration):
|
|
16
|
+
|
|
17
|
+
def repeat[A](open: IO[Stream[IO, A]]): Stream[IO, A] =
|
|
18
|
+
Stream.force(open) ++ Stream.sleep_[IO](pause) ++ repeat(open)
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
package scada.supervisor.infra.state
|
|
2
|
+
|
|
3
|
+
import cats.effect.IO
|
|
4
|
+
import java.nio.ByteBuffer
|
|
5
|
+
import java.nio.channels.FileChannel
|
|
6
|
+
import java.nio.file.{Files, Path, StandardCopyOption, StandardOpenOption}
|
|
7
|
+
import java.nio.charset.StandardCharsets.UTF_8
|
|
8
|
+
|
|
9
|
+
/** Atomic UTF-8 state file; AtomicStateFile(path).write(json) fsyncs contents and directory. */
|
|
10
|
+
final class AtomicStateFile(path: Path):
|
|
11
|
+
def read: IO[Option[String]] = IO.blocking:
|
|
12
|
+
if Files.exists(path) then Some(Files.readString(path)) else None
|
|
13
|
+
def write(json: String): IO[Unit] = IO.blocking:
|
|
14
|
+
Files.createDirectories(path.getParent)
|
|
15
|
+
val temporary = path.resolveSibling(path.getFileName.toString + ".tmp")
|
|
16
|
+
val channel = FileChannel.open(temporary, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)
|
|
17
|
+
try
|
|
18
|
+
val bytes = ByteBuffer.wrap(json.getBytes(UTF_8))
|
|
19
|
+
while bytes.hasRemaining do channel.write(bytes)
|
|
20
|
+
channel.force(true)
|
|
21
|
+
finally channel.close()
|
|
22
|
+
Files.move(temporary, path, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING)
|
|
23
|
+
val directory = FileChannel.open(path.getParent, StandardOpenOption.READ)
|
|
24
|
+
try directory.force(true) finally directory.close()
|
package/supervisor-engine/src/main/scala/scada/supervisor/infra/state/CheckpointSegments.scala
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
package scada.supervisor.infra.state
|
|
2
|
+
|
|
3
|
+
import cats.effect.IO
|
|
4
|
+
import cats.syntax.all.*
|
|
5
|
+
import scada.supervisor.core.*
|
|
6
|
+
import scada.supervisor.core.Segments as CoreSegments
|
|
7
|
+
import scada.supervisor.infra.checkpoint.Checkpoint
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* [[CoreSegments]] decorator that falls back to checkpoint API when
|
|
11
|
+
* the in-memory store misses one segment row. Legacy `list` stays in memory.
|
|
12
|
+
* History-mode decision reads may prefer checkpoint snapshots, refreshing exact
|
|
13
|
+
* cached keys through an injected port. Lists refresh already-known sibling keys;
|
|
14
|
+
* this decorator does not download or discover the complete historical family.
|
|
15
|
+
* A segment write must not download machine history: the site paints
|
|
16
|
+
* shutdown reasons on read.
|
|
17
|
+
*
|
|
18
|
+
* {{{
|
|
19
|
+
* CheckpointSegments(StateSegments(ref), checkpoint)
|
|
20
|
+
* }}}
|
|
21
|
+
*/
|
|
22
|
+
final class CheckpointSegments(
|
|
23
|
+
underlying: CoreSegments[IO],
|
|
24
|
+
checkpoint: Checkpoint,
|
|
25
|
+
preferCheckpoint: Boolean = false,
|
|
26
|
+
refreshCache: Option[(MachineId,Timestamp,Option[TaggedSegment]) => IO[Unit]] = None
|
|
27
|
+
) extends CoreSegments[IO]:
|
|
28
|
+
require(!preferCheckpoint || refreshCache.isDefined,"Checkpoint-first decisions require an exact cache refresh port")
|
|
29
|
+
|
|
30
|
+
def find(machine: MachineId, start: Timestamp): IO[Option[TaggedSegment]] =
|
|
31
|
+
if preferCheckpoint then checkpoint.fetchSegment(machine,start).flatTap(row => refreshCache.get(machine,start,row))
|
|
32
|
+
else underlying.find(machine, start).flatMap:
|
|
33
|
+
case some @ Some(_) => IO.pure(some)
|
|
34
|
+
case None =>
|
|
35
|
+
checkpoint.fetchSegment(machine, start).flatMap:
|
|
36
|
+
case None => IO.pure(None)
|
|
37
|
+
case Some(segment) =>
|
|
38
|
+
underlying.upsert(machine, segment).as(Some(segment))
|
|
39
|
+
|
|
40
|
+
def list(machine: MachineId): IO[List[TaggedSegment]] =
|
|
41
|
+
if preferCheckpoint then underlying.list(machine).flatMap(_.traverse(row => find(machine,row.segment.start)).map(_.flatten))
|
|
42
|
+
else underlying.list(machine)
|
|
43
|
+
|
|
44
|
+
def upsert(machine: MachineId, segment: TaggedSegment): IO[Unit] =
|
|
45
|
+
underlying.upsert(machine, segment)
|
|
46
|
+
|
|
47
|
+
def replace(machine: MachineId, from: Timestamp, to: Timestamp, segments: List[TaggedSegment]): IO[Unit] =
|
|
48
|
+
underlying.replace(machine, from, to, segments)
|
|
49
|
+
|
|
50
|
+
def resolve(
|
|
51
|
+
machine: MachineId,
|
|
52
|
+
original: Segment,
|
|
53
|
+
tags: List[String],
|
|
54
|
+
options: List[String],
|
|
55
|
+
properties: Map[String, String]
|
|
56
|
+
): IO[Unit] =
|
|
57
|
+
find(machine, original.start).flatMap:
|
|
58
|
+
case None => IO.unit
|
|
59
|
+
case Some(fresh) => underlying.resolve(machine, if preferCheckpoint then fresh.segment else original, tags, options, properties)
|
package/supervisor-engine/src/main/scala/scada/supervisor/infra/state/SegmentStatePolicy.scala
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
package scada.supervisor.infra.state
|
|
2
|
+
|
|
3
|
+
import scada.supervisor.core.TaggedSegment
|
|
4
|
+
|
|
5
|
+
/** Preserves or replaces operator annotations when a segment is updated. */
|
|
6
|
+
trait SegmentStatePolicy:
|
|
7
|
+
def merge(existing: TaggedSegment, incoming: TaggedSegment): TaggedSegment =
|
|
8
|
+
if incoming.tags.isEmpty && incoming.properties.isEmpty then
|
|
9
|
+
val options = if existing.tags.nonEmpty then existing.options else incoming.options
|
|
10
|
+
TaggedSegment(incoming.segment, existing.tags, options, existing.properties)
|
|
11
|
+
else incoming
|
|
12
|
+
|
|
13
|
+
def resolve(row: TaggedSegment, tags: List[String], options: List[String], properties: Map[String, String]): Option[TaggedSegment] =
|
|
14
|
+
val kept = if options.isEmpty then row.options else options
|
|
15
|
+
Some(TaggedSegment(row.segment, tags, kept, properties))
|
|
16
|
+
|
|
17
|
+
object SegmentStatePolicy:
|
|
18
|
+
val default: SegmentStatePolicy = new SegmentStatePolicy {}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
package scada.supervisor.infra.state
|
|
2
|
+
|
|
3
|
+
import cats.Functor
|
|
4
|
+
import cats.effect.Ref
|
|
5
|
+
import cats.syntax.all.*
|
|
6
|
+
import scada.supervisor.core.*
|
|
7
|
+
import scada.supervisor.core.Segments as CoreSegments
|
|
8
|
+
import scala.collection.immutable.SortedMap
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* In-memory [[CoreSegments]] backed by a `Ref` of sorted per-machine
|
|
12
|
+
* maps keyed on `segment.start`. Upsert is idempotent on that key, so
|
|
13
|
+
* a `Started` / `Emitted` pair for the same island simply overwrites
|
|
14
|
+
* the prior row with the finalised segment. When the incoming row carries
|
|
15
|
+
* no operator tags or properties, existing markup on that start is kept;
|
|
16
|
+
* if operator tags are already set, existing options are kept too so a
|
|
17
|
+
* heartbeat cannot replace the prompt list after operator markup.
|
|
18
|
+
*
|
|
19
|
+
* [[resolve]] writes operator `tags` and `properties` on the row keyed by
|
|
20
|
+
* `original.start`. Options:
|
|
21
|
+
* - non-empty `options` → store that list (cascade next choices / leaf);
|
|
22
|
+
* - empty `options` → keep the previous options so HMI can re-edit the
|
|
23
|
+
* same prompt after a resolve that only retags the path.
|
|
24
|
+
*
|
|
25
|
+
* Caller acquires the `Ref` so the class itself stays a plain
|
|
26
|
+
* immutable constructor.
|
|
27
|
+
*
|
|
28
|
+
* {{{
|
|
29
|
+
* Ref.of[F, Map[MachineId, SortedMap[Timestamp, TaggedSegment]]](Map.empty)
|
|
30
|
+
* .map(Segments(_))
|
|
31
|
+
* segments.resolve(machine, original, tags, options, properties)
|
|
32
|
+
* }}}
|
|
33
|
+
*/
|
|
34
|
+
final class Segments[F[_]: Functor](
|
|
35
|
+
ref: Ref[F, Map[MachineId, SortedMap[Timestamp, TaggedSegment]]],
|
|
36
|
+
policy: SegmentStatePolicy = SegmentStatePolicy.default
|
|
37
|
+
) extends CoreSegments[F]:
|
|
38
|
+
|
|
39
|
+
def upsert(machine: MachineId, segment: TaggedSegment): F[Unit] =
|
|
40
|
+
ref.update: state =>
|
|
41
|
+
val machineMap = forMachine(state, machine)
|
|
42
|
+
val stored =
|
|
43
|
+
if SplitFollow.owned(machineMap.values, segment) then SplitFollow.project(machineMap, segment)
|
|
44
|
+
else
|
|
45
|
+
val merged = machineMap.get(segment.segment.start) match
|
|
46
|
+
case Some(existing) => policy.merge(existing, segment)
|
|
47
|
+
case _ =>
|
|
48
|
+
segment
|
|
49
|
+
machineMap.updated(segment.segment.start, merged)
|
|
50
|
+
state.updated(machine, stored)
|
|
51
|
+
|
|
52
|
+
/** Exact checkpoint refresh bypasses annotation-preserving upsert and never touches neighbouring keys. */
|
|
53
|
+
def refresh(machine: MachineId, start: Timestamp, row: Option[TaggedSegment]): F[Unit] =
|
|
54
|
+
ref.update: state =>
|
|
55
|
+
val current = forMachine(state,machine)
|
|
56
|
+
val refreshed = row.fold(current - start)(segment => current.updated(start,segment))
|
|
57
|
+
state.updated(machine,refreshed)
|
|
58
|
+
|
|
59
|
+
def find(machine: MachineId, start: Timestamp): F[Option[TaggedSegment]] =
|
|
60
|
+
ref.get.map(state => forMachine(state, machine).get(start))
|
|
61
|
+
|
|
62
|
+
def list(machine: MachineId): F[List[TaggedSegment]] =
|
|
63
|
+
ref.get.map(state => forMachine(state, machine).values.toList)
|
|
64
|
+
|
|
65
|
+
def replace(machine: MachineId, from: Timestamp, to: Timestamp, segments: List[TaggedSegment]): F[Unit] =
|
|
66
|
+
ref.update: state =>
|
|
67
|
+
val cleaned = forMachine(state, machine).filterNot: (_, seg) =>
|
|
68
|
+
seg.segment.start.epoch < to.epoch && seg.segment.end.epoch > from.epoch
|
|
69
|
+
state.updated(machine, segments.foldLeft(cleaned)((m, s) => m.updated(s.segment.start, s)))
|
|
70
|
+
|
|
71
|
+
def resolve(
|
|
72
|
+
machine: MachineId,
|
|
73
|
+
original: Segment,
|
|
74
|
+
tags: List[String],
|
|
75
|
+
options: List[String],
|
|
76
|
+
properties: Map[String, String]
|
|
77
|
+
): F[Unit] =
|
|
78
|
+
ref.update: state =>
|
|
79
|
+
val key = original.start
|
|
80
|
+
val updated = forMachine(state, machine).get(key) match
|
|
81
|
+
case None => forMachine(state, machine)
|
|
82
|
+
case Some(row) =>
|
|
83
|
+
val rows = forMachine(state, machine)
|
|
84
|
+
policy.resolve(row, tags, options, properties).fold(rows)(result => rows.updated(key, result))
|
|
85
|
+
state.updated(machine, updated)
|
|
86
|
+
|
|
87
|
+
private def forMachine(
|
|
88
|
+
state: Map[MachineId, SortedMap[Timestamp, TaggedSegment]],
|
|
89
|
+
machine: MachineId
|
|
90
|
+
): SortedMap[Timestamp, TaggedSegment] =
|
|
91
|
+
state.getOrElse(machine, SortedMap.empty)
|