@yarkivaev/scada 2.6.40 → 2.6.42
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/db/migrations/E0018__stream_worker_checkpoint.sql +9 -0
- package/package.json +3 -1
- package/src/infrastructure/streams/README.md +12 -5
- package/supervisor-engine/src/main/scala/scada/stream/replay/Replay.scala +149 -0
- package/supervisor-engine/src/main/scala/scada/stream/worker/Processor.scala +8 -0
- package/supervisor-engine/src/main/scala/scada/stream/worker/StreamWorker.scala +119 -0
- package/supervisor-engine/src/main/scala/scada/stream/worker/postgres/PgCheckpointStore.scala +83 -0
- 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 +52 -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/core/segmentation/Timeline.scala +43 -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 +258 -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,141 @@
|
|
|
1
|
+
package scada.supervisor.infra.checkpoint
|
|
2
|
+
|
|
3
|
+
import cats.data.NonEmptyList
|
|
4
|
+
import cats.effect.IO
|
|
5
|
+
import fs2.Stream
|
|
6
|
+
import io.circe.parser.parse
|
|
7
|
+
import java.net.URI
|
|
8
|
+
import java.net.URLEncoder
|
|
9
|
+
import java.net.http.{HttpClient, HttpRequest, HttpResponse}
|
|
10
|
+
import java.nio.charset.StandardCharsets
|
|
11
|
+
import java.time.Duration
|
|
12
|
+
import java.util.concurrent.TimeUnit
|
|
13
|
+
import org.typelevel.log4cats.Logger
|
|
14
|
+
import org.typelevel.log4cats.slf4j.Slf4jLogger
|
|
15
|
+
import scala.concurrent.duration.*
|
|
16
|
+
import scada.supervisor.core.*
|
|
17
|
+
import scada.supervisor.infra.config.CheckpointApiConfig
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* HTTP checkpoint client against supervisor-sink /v1/checkpoint API.
|
|
21
|
+
*
|
|
22
|
+
* Transient connect failures and HTTP 5xx are retried. A closed site-server
|
|
23
|
+
* socket must not exit the supervisor stream.
|
|
24
|
+
*
|
|
25
|
+
* {{{
|
|
26
|
+
* SupervisorSinkCheckpoint(CheckpointApiConfig("http://site:8081", None, 10))
|
|
27
|
+
* }}}
|
|
28
|
+
*/
|
|
29
|
+
final class SupervisorSinkCheckpoint(config: CheckpointApiConfig, pause: FiniteDuration = 2.seconds) extends Checkpoint:
|
|
30
|
+
|
|
31
|
+
private given Logger[IO] = Slf4jLogger.getLogger[IO]
|
|
32
|
+
|
|
33
|
+
private val client = HttpClient.newBuilder()
|
|
34
|
+
.connectTimeout(Duration.ofSeconds(config.timeoutSeconds.toLong))
|
|
35
|
+
.build()
|
|
36
|
+
|
|
37
|
+
def fetchReplayCursor(machine: MachineId): IO[Timestamp] =
|
|
38
|
+
getJson(s"/v1/checkpoint/replay-cursor?machineId=${encode(machine.raw)}")
|
|
39
|
+
.map: body =>
|
|
40
|
+
val cursor = body.hcursor.get[Double]("cursor").getOrElse(0.0)
|
|
41
|
+
Timestamp(cursor)
|
|
42
|
+
|
|
43
|
+
def fetchPendingSegments: IO[List[PendingSegmentData]] =
|
|
44
|
+
getJson("/v1/checkpoint/pending-segments")
|
|
45
|
+
.map: body =>
|
|
46
|
+
val items = body.hcursor.downField("items")
|
|
47
|
+
.as[List[Map[String, io.circe.Json]]]
|
|
48
|
+
.getOrElse(Nil)
|
|
49
|
+
items.map: item =>
|
|
50
|
+
val start = Timestamp(item("start").as[Double].getOrElse(0.0))
|
|
51
|
+
val end = item.get("end").flatMap(_.as[Double].toOption).map(Timestamp.apply).getOrElse(start)
|
|
52
|
+
PendingSegmentData(
|
|
53
|
+
MachineId(item("machine").asString.getOrElse("")),
|
|
54
|
+
item("name").asString.getOrElse(""),
|
|
55
|
+
start,
|
|
56
|
+
end
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
def fetchSegment(machine: MachineId, start: Timestamp): IO[Option[TaggedSegment]] =
|
|
60
|
+
getJson(s"/v1/checkpoint/segment?machineId=${encode(machine.raw)}&start=${start.epoch}")
|
|
61
|
+
.map(body => body.hcursor.downField("item").focus.flatMap(decodeTagged))
|
|
62
|
+
|
|
63
|
+
override def fetchCyclePrior(machine: MachineId, before: Timestamp, reset: List[String]): IO[List[TaggedSegment]] =
|
|
64
|
+
val resetParams = reset.map(id => s"reset=${encode(id)}").mkString("&")
|
|
65
|
+
getJson(s"/v1/checkpoint/cycle-prior?machineId=${encode(machine.raw)}&before=${before.epoch}&$resetParams")
|
|
66
|
+
.map: body =>
|
|
67
|
+
body.hcursor.downField("items").as[List[io.circe.Json]].getOrElse(Nil).flatMap(decodeTagged)
|
|
68
|
+
|
|
69
|
+
def fetchReadings(topics: List[String], from: Timestamp): Stream[IO, RawReadingData] =
|
|
70
|
+
fetchRequiredReadings(topics, from).handleErrorWith: error =>
|
|
71
|
+
Stream.exec(Logger[IO].warn(error)("checkpoint readings failed"))
|
|
72
|
+
|
|
73
|
+
override def fetchRequiredReadings(topics: List[String], from: Timestamp): Stream[IO, RawReadingData] =
|
|
74
|
+
NonEmptyList.fromList(topics).fold(Stream.empty): topicsNel =>
|
|
75
|
+
val topicParams = topicsNel.toList.map(topic => s"topic=${encode(topic)}").mkString("&")
|
|
76
|
+
val path = s"/v1/checkpoint/readings?from=${from.epoch}&$topicParams"
|
|
77
|
+
Stream.eval(load(path)).flatMap(Stream.emits)
|
|
78
|
+
|
|
79
|
+
private def load(path: String): IO[List[RawReadingData]] =
|
|
80
|
+
read(path).flatMap: body =>
|
|
81
|
+
IO.fromEither(body.hcursor.downField("items").as[List[Map[String, io.circe.Json]]]).map: items =>
|
|
82
|
+
items.map: item =>
|
|
83
|
+
RawReadingData(
|
|
84
|
+
item("topic").asString.getOrElse(""),
|
|
85
|
+
Timestamp(item("timestamp").as[Double].getOrElse(0.0)),
|
|
86
|
+
item("value").as[Double].getOrElse(0.0)
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
private def decodeTagged(item: io.circe.Json): Option[TaggedSegment] =
|
|
90
|
+
if item.isNull then None
|
|
91
|
+
else
|
|
92
|
+
val cursor = item.hcursor
|
|
93
|
+
val name = cursor.get[String]("name").getOrElse("")
|
|
94
|
+
val startTs = Timestamp(cursor.get[Double]("start").getOrElse(0.0))
|
|
95
|
+
val endTs = Timestamp(cursor.get[Double]("end").getOrElse(0.0))
|
|
96
|
+
val duration = cursor.get[Double]("duration").getOrElse(0.0)
|
|
97
|
+
val tags = cursor.get[List[String]]("tags").getOrElse(Nil)
|
|
98
|
+
val options = cursor.get[List[String]]("options").getOrElse(Nil)
|
|
99
|
+
val properties = cursor.get[Map[String, String]]("properties").getOrElse(Map.empty)
|
|
100
|
+
Some(TaggedSegment(Segment(name, startTs, endTs, duration), tags, options, properties))
|
|
101
|
+
|
|
102
|
+
private def getJson(path: String): IO[io.circe.Json] =
|
|
103
|
+
read(path).handleErrorWith: err =>
|
|
104
|
+
err match
|
|
105
|
+
case failure: CheckpointStatus if failure.code >= 500 =>
|
|
106
|
+
Logger[IO].warn(failure)(s"checkpoint request failed path=$path") *> IO.sleep(pause) *> getJson(path)
|
|
107
|
+
case _: java.io.IOException =>
|
|
108
|
+
Logger[IO].warn(err)(s"checkpoint request failed path=$path") *> IO.sleep(pause) *> getJson(path)
|
|
109
|
+
case _ =>
|
|
110
|
+
IO.raiseError(err)
|
|
111
|
+
|
|
112
|
+
private def read(path: String): IO[io.circe.Json] =
|
|
113
|
+
val request = baseRequest(path).GET().build()
|
|
114
|
+
IO.fromCompletableFuture(IO.delay(
|
|
115
|
+
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
|
|
116
|
+
.orTimeout(config.timeoutSeconds.toLong, TimeUnit.SECONDS)
|
|
117
|
+
)).flatMap: response =>
|
|
118
|
+
val code = response.statusCode()
|
|
119
|
+
if code >= 500 then
|
|
120
|
+
IO.raiseError(CheckpointStatus(code, path))
|
|
121
|
+
else if code == 404 then
|
|
122
|
+
IO.pure(io.circe.Json.obj())
|
|
123
|
+
else if code / 100 != 2 then
|
|
124
|
+
IO.raiseError(RuntimeException(s"checkpoint api error $code: ${response.body()}"))
|
|
125
|
+
else
|
|
126
|
+
IO.fromEither(parse(response.body()).left.map(err => RuntimeException(err.message)))
|
|
127
|
+
|
|
128
|
+
private def baseRequest(path: String): HttpRequest.Builder =
|
|
129
|
+
val builder = HttpRequest.newBuilder()
|
|
130
|
+
.uri(URI.create(s"${config.baseUrl}$path"))
|
|
131
|
+
.timeout(Duration.ofSeconds(config.timeoutSeconds.toLong))
|
|
132
|
+
.header("Accept", "application/json")
|
|
133
|
+
config.token match
|
|
134
|
+
case Some(token) => builder.header("Authorization", s"Bearer $token")
|
|
135
|
+
case None => builder
|
|
136
|
+
|
|
137
|
+
private def encode(value: String): String =
|
|
138
|
+
URLEncoder.encode(value, StandardCharsets.UTF_8)
|
|
139
|
+
|
|
140
|
+
private final case class CheckpointStatus(code: Int, path: String)
|
|
141
|
+
extends RuntimeException(s"checkpoint http $code path=$path")
|
|
@@ -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()
|