@yarkivaev/scada 2.13.0 → 2.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.js +29 -0
- package/package.json +3 -2
- package/src/application/control/controlClient.js +1 -1
- package/src/application/control/createOnlyJSON.js +50 -0
- package/src/application/control/index.js +2 -0
- package/src/application/control/jsonAssignments.js +30 -0
- package/src/application/mcp/loadMetricSeries.js +69 -0
- package/src/application/mcp/locateMachineMetric.js +25 -0
- package/src/application/mcp/metricQueryPorts.js +78 -0
- package/src/application/mcp/parseBearerTokens.js +43 -0
- package/src/application/runtime/assignment.js +4 -1
- package/src/infrastructure/deploy/applyWhenChanged.js +15 -0
- package/src/infrastructure/deploy/deploymentKube.js +35 -0
- package/src/infrastructure/deploy/executeKubeSeed.js +24 -0
- package/src/infrastructure/deploy/executeRelease.js +8 -11
- package/src/infrastructure/deploy/operatePostgresMaintenance.js +85 -0
- package/src/infrastructure/deploy/postgresMaintenancePlan.js +54 -0
- package/src/infrastructure/deploy/postgresRestoreObjects.js +73 -0
- package/src/infrastructure/deploy/preflightKubeStorage.js +76 -0
- package/src/infrastructure/deploy/prepareKubePrerequisites.js +95 -0
- package/src/infrastructure/deploy/verifyCollectorCoverage.js +43 -0
- package/src/infrastructure/deploy/verifyPeerBrokerPerimeter.js +24 -0
- package/src/infrastructure/ingest/mysql40/byteReader.js +51 -0
- package/src/infrastructure/ingest/mysql40/mysql40.js +116 -0
- package/src/infrastructure/ingest/mysql40/packets.js +72 -0
- package/src/infrastructure/ingest/mysql40/resultRows.js +92 -0
- package/src/infrastructure/ingest/mysql40/scramble.js +89 -0
- package/src/infrastructure/ingest/telemetry/edgeTelemetryRuntime.js +83 -0
- package/src/infrastructure/ingest/telemetry/replayStoredTelemetry.js +125 -0
- package/src/infrastructure/management/kubeServiceAccount.js +43 -0
- package/src/infrastructure/management/kubectlPortForward.js +27 -0
- package/src/infrastructure/mdmesh/hmiApplication.js +64 -0
- package/src/infrastructure/mdmesh/hmiControl.js +85 -0
- package/src/infrastructure/mdmesh/hmiFile.js +69 -0
- package/src/infrastructure/mdmesh/hmiMonitor.js +53 -0
- package/src/infrastructure/mdmesh/hmiReconcile.js +170 -0
- package/src/infrastructure/mdmesh/hmiRuntime.js +33 -0
- package/src/infrastructure/mdmesh/index.js +7 -0
- package/src/infrastructure/mdmesh/mdmeshClient.js +72 -0
- package/src/infrastructure/messaging/ownership/edgeSitesFromEnv.js +137 -0
- package/src/infrastructure/messaging/rabbitmq/reconcile.js +71 -12
- package/src/infrastructure/opcua/health.js +91 -0
- package/src/infrastructure/opcua/index.js +1 -0
- package/src/infrastructure/persistence/pg/prepareRuntimeRole.js +67 -0
- package/src/infrastructure/replication/canonicalJSON.js +15 -0
- package/src/infrastructure/replication/postgresSnapshotReplica.js +129 -0
- package/src/infrastructure/replication/postgresSnapshotRuntime.js +40 -0
- package/src/infrastructure/replication/snapshotSync.js +61 -0
- package/src/infrastructure/replication/tableSnapshotFormat.js +50 -0
- package/src/infrastructure/tls/mirrorTLSSecret.js +37 -0
- package/src/infrastructure/tls/mutualJSON.js +79 -0
- package/src/infrastructure/tls/tlsMaterial.js +57 -0
- package/stream-processing/src/main/scala/scada/processing/infra/state/AtomicStateFile.scala +7 -0
- package/stream-processing/src/main/scala/scada/processing/infra/state/StateJournal.scala +22 -0
- package/stream-processing/src/main/scala/scada/processing/runtime/HistoryClient.scala +10 -1
- package/stream-processing/src/main/scala/scada/processing/runtime/LiveWorker.scala +70 -0
- package/stream-processing/src/main/scala/scada/processing/runtime/LocalHistory.scala +2 -8
- package/stream-processing/src/main/scala/scada/processing/runtime/StatefulHistory.scala +108 -0
- package/stream-processing/src/main/scala/scada/processing/runtime/TimelinePublication.scala +43 -0
- package/stream-processing/src/main/scala/scada/processing/runtime/WorkerStores.scala +43 -0
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
package scada.processing.runtime
|
|
2
|
+
|
|
3
|
+
import cats.effect.IO
|
|
4
|
+
import cats.effect.std.Semaphore
|
|
5
|
+
import fs2.Stream
|
|
6
|
+
import fs2.concurrent.SignallingRef
|
|
7
|
+
import io.yarkivaev.streamworker.{Delivery, Output, OutputScope, Processor, ProcessorVersion, StreamWorker}
|
|
8
|
+
import scala.concurrent.duration.*
|
|
9
|
+
|
|
10
|
+
object LiveWorker:
|
|
11
|
+
final case class Replay[S, E](active: S => Boolean, complete: S => IO[E])
|
|
12
|
+
final case class Watchdog[S, E](deadline: S => Option[Long], changed: (S, S) => Boolean, expired: Long => E)
|
|
13
|
+
|
|
14
|
+
/** Serializes input, replay handoff, timeouts, and side effects under one worker's ownership. */
|
|
15
|
+
final class LiveWorker[C, S, E, O](
|
|
16
|
+
processor: Processor[C, S, E, O],
|
|
17
|
+
config: C,
|
|
18
|
+
version: ProcessorVersion,
|
|
19
|
+
binding: WorkerStores.Binding[S, O],
|
|
20
|
+
publish: O => IO[Unit],
|
|
21
|
+
outputs: Option[OutputScope] = None
|
|
22
|
+
):
|
|
23
|
+
import LiveWorker.*
|
|
24
|
+
private val WorkerStores.Binding(store, task, ownership) = binding
|
|
25
|
+
private val current = store.load(task, ownership)
|
|
26
|
+
private val worker = StreamWorker(processor, store, (_: Long, output: Output[O]) =>
|
|
27
|
+
val write = publish(output.value)
|
|
28
|
+
outputs.fold(write)(_.within(output.id)(write)))
|
|
29
|
+
|
|
30
|
+
private def submit(event: E) = worker.run(task, version, config, ownership): cursor =>
|
|
31
|
+
// Allocate the receipt position from the worker checkpoint. Broker receipt IDs may be connection-local.
|
|
32
|
+
Stream.eval(IO(Math.addExact(cursor.getOrElse(0L), 1L))).map(position => Delivery(position, event, IO.unit))
|
|
33
|
+
|
|
34
|
+
def run(
|
|
35
|
+
readings: IO[Unit] => Stream[IO, (E, IO[Unit])],
|
|
36
|
+
sideEffects: Stream[IO, IO[Unit]],
|
|
37
|
+
replay: Replay[S, E],
|
|
38
|
+
watchdog: Watchdog[S, E],
|
|
39
|
+
scheduleOnStart: Boolean
|
|
40
|
+
): IO[Unit] =
|
|
41
|
+
for
|
|
42
|
+
lock <- Semaphore[IO](1)
|
|
43
|
+
deadline <- SignallingRef[IO, Option[Long]](None)
|
|
44
|
+
_ <- worker.run(task, version, config, ownership)(_ => Stream.empty)
|
|
45
|
+
arm = (state: S) => deadline.set(watchdog.deadline(state))
|
|
46
|
+
accept = (event: E, ack: IO[Unit]) =>
|
|
47
|
+
lock.permit.use { _ =>
|
|
48
|
+
for
|
|
49
|
+
before <- current
|
|
50
|
+
next <- submit(event)
|
|
51
|
+
_ <- IO.whenA(!replay.active(next.state) && watchdog.changed(before.state, next.state))(arm(next.state))
|
|
52
|
+
yield replay.active(before.state)
|
|
53
|
+
}.flatMap: replaying =>
|
|
54
|
+
// Archive records have no broker receipt. Live ACKs follow the completed worker step.
|
|
55
|
+
IO.unlessA(replaying)(ack)
|
|
56
|
+
ready = lock.permit.use: _ =>
|
|
57
|
+
current.flatMap: saved =>
|
|
58
|
+
if replay.active(saved.state) then
|
|
59
|
+
replay.complete(saved.state).flatMap(submit).flatMap(next => arm(next.state))
|
|
60
|
+
else IO.unit
|
|
61
|
+
timers = deadline.discrete.changes.switchMap:
|
|
62
|
+
case None => Stream.empty
|
|
63
|
+
case Some(until) =>
|
|
64
|
+
Stream.eval(IO.realTime.flatMap(now => IO.sleep(math.max(0L, until - now.toMillis).millis))).as(until)
|
|
65
|
+
_ <- IO.whenA(scheduleOnStart)(current.flatMap(saved => arm(saved.state)))
|
|
66
|
+
input = readings(ready).evalMap { case (event, ack) => accept(event, ack) }
|
|
67
|
+
live = (input ++ Stream.exec(ready)).concurrently(sideEffects.evalMap(action => lock.permit.use(_ => action)))
|
|
68
|
+
.concurrently(timers.evalMap(at => lock.permit.use(_ => submit(watchdog.expired(at))).void))
|
|
69
|
+
_ <- live.compile.drain
|
|
70
|
+
yield ()
|
|
@@ -4,15 +4,13 @@ import io.yarkivaev.segmentation.{HistoryRange, HistorySeed, HistorySegment, His
|
|
|
4
4
|
import cats.effect.{IO, Ref}
|
|
5
5
|
import cats.syntax.all.*
|
|
6
6
|
import fs2.Stream
|
|
7
|
-
import io.circe.
|
|
7
|
+
import io.circe.Json
|
|
8
8
|
import io.circe.parser.parse
|
|
9
9
|
import io.circe.syntax.*
|
|
10
10
|
import io.yarkivaev.temporal.{LocalStreams, Observation, Processing, Work, Worker}
|
|
11
11
|
import java.net.URLEncoder
|
|
12
12
|
import java.nio.charset.StandardCharsets
|
|
13
|
-
import java.security.MessageDigest
|
|
14
13
|
import java.time.Instant
|
|
15
|
-
import java.util.HexFormat
|
|
16
14
|
import io.yarkivaev.streamworker.{ProcessingError, Processor, StepResult}
|
|
17
15
|
import scada.processing.core.*
|
|
18
16
|
import io.yarkivaev.segmentation.ObservedSegmentation.{Sample, State, segment}
|
|
@@ -58,12 +56,8 @@ object LocalHistory:
|
|
|
58
56
|
val state = samples.lastOption.map(last => HistoryState(last.time, result.state.parameters, tail))
|
|
59
57
|
Calculated(result.outputs ++ tail, state)
|
|
60
58
|
|
|
61
|
-
private def digest(value: Json): String =
|
|
62
|
-
val text = Printer.noSpaces.copy(sortKeys = true).print(value)
|
|
63
|
-
HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(text.getBytes(StandardCharsets.UTF_8)))
|
|
64
|
-
|
|
65
59
|
private[runtime] def commitFence(machine: MachineId, workId: String, token: String, generation: Option[Long]): Json =
|
|
66
|
-
val outputId =
|
|
60
|
+
val outputId = HistoryClient.fingerprint(Json.arr(machine.raw.asJson, workId.asJson, token.asJson))
|
|
67
61
|
val fields = ("outputId" -> outputId.asJson) :: generation.toList.map(current => "generation" -> current.asJson)
|
|
68
62
|
Json.obj("fence" -> Json.obj(fields*))
|
|
69
63
|
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
package scada.processing.runtime
|
|
2
|
+
|
|
3
|
+
import cats.effect.IO
|
|
4
|
+
import cats.syntax.all.*
|
|
5
|
+
import fs2.Stream
|
|
6
|
+
import io.circe.{Decoder, Encoder, Json}
|
|
7
|
+
import io.circe.syntax.*
|
|
8
|
+
import io.yarkivaev.temporal.Observation
|
|
9
|
+
import java.net.URLEncoder
|
|
10
|
+
import java.nio.charset.StandardCharsets.UTF_8
|
|
11
|
+
import java.util.concurrent.atomic.AtomicInteger
|
|
12
|
+
import scada.processing.core.MachineId
|
|
13
|
+
import scada.processing.infra.config.AliasMapping
|
|
14
|
+
import scala.concurrent.duration.*
|
|
15
|
+
|
|
16
|
+
object StatefulHistory:
|
|
17
|
+
final case class Page[S](state: S, rows: Vector[Json], at: Option[Long])
|
|
18
|
+
|
|
19
|
+
private final case class Claim(id: String, token: String, from: Long, until: Long, cursor: Option[Long], end: Option[Long])
|
|
20
|
+
derives Decoder
|
|
21
|
+
|
|
22
|
+
/** Executes bounded, stateful classifier pages with the receiver's work claim and revision. */
|
|
23
|
+
final class StatefulHistory[S: Encoder](
|
|
24
|
+
api: HistoryClient,
|
|
25
|
+
machine: MachineId,
|
|
26
|
+
paddingMs: Long,
|
|
27
|
+
classifierKey: String,
|
|
28
|
+
initial: S,
|
|
29
|
+
decodeState: Json => IO[S],
|
|
30
|
+
replay: (Vector[Observation], S, Int) => IO[StatefulHistory.Page[S]],
|
|
31
|
+
replication: Option[HistoryReplication] = None,
|
|
32
|
+
generation: Option[Long] = None
|
|
33
|
+
):
|
|
34
|
+
import StatefulHistory.*
|
|
35
|
+
private val scale = AtomicInteger(0)
|
|
36
|
+
private val supportedScales = Set(1, 1000)
|
|
37
|
+
private def encode(value: String): String = URLEncoder.encode(value, UTF_8)
|
|
38
|
+
private val encoded = encode(machine.raw)
|
|
39
|
+
|
|
40
|
+
def configure(aliases: List[AliasMapping]): IO[Unit] =
|
|
41
|
+
val topics = aliases.map(alias => Json.obj("topic" -> alias.topic.asJson, "channel" -> alias.metric.asJson))
|
|
42
|
+
val body = Json.obj("machine" -> machine.raw.asJson, "topics" -> Json.arr(topics*), "classifierKey" -> classifierKey.asJson)
|
|
43
|
+
api.retry(api.request("POST", "/v1/history/config", body)).flatMap: response =>
|
|
44
|
+
val protocol = response.hcursor.get[String]("classifierProtocol").toOption
|
|
45
|
+
val unit = response.hcursor.get[Int]("timeScale").toOption
|
|
46
|
+
IO.fromOption(unit.filter(supportedScales).filter(_ => protocol.contains("stateful-correction-v1")))(
|
|
47
|
+
IllegalStateException("Stateful history protocol required")).flatMap(value => IO(scale.set(value)))
|
|
48
|
+
|
|
49
|
+
def process: Stream[IO, Unit] =
|
|
50
|
+
Stream.repeatEval(api.retry(api.request("GET", s"/v1/history/work?machine=$encoded"))).flatMap: response =>
|
|
51
|
+
Stream.eval(IO.fromEither(response.hcursor.get[Vector[Json]]("items"))).flatMap: work =>
|
|
52
|
+
val jobs = work.headOption.fold(Stream.emit(()).covary[IO]): next =>
|
|
53
|
+
val run = IO.fromEither(next.as[Claim]).flatMap(execute)
|
|
54
|
+
Stream.eval(run.attempt.flatTap(_.left.toOption.traverse_(error =>
|
|
55
|
+
IO.println(s"History classifier work deferred: ${Option(error.getMessage).getOrElse(error.toString)}")))).collect { case Right(_) => () }
|
|
56
|
+
jobs ++ Stream.sleep_[IO](1.second)
|
|
57
|
+
|
|
58
|
+
private def observations(context: Json, claim: Claim, unit: Int): IO[Vector[Observation]] =
|
|
59
|
+
val metadata = context.hcursor.downField("context")
|
|
60
|
+
val valid = metadata.get[String]("classifierKey").toOption.contains(classifierKey) &&
|
|
61
|
+
metadata.get[String]("workId").toOption.contains(claim.id) &&
|
|
62
|
+
metadata.get[String]("workToken").toOption.contains(claim.token) &&
|
|
63
|
+
metadata.get[Int]("timeScale").toOption.getOrElse(1) == unit
|
|
64
|
+
IO.raiseUnless(valid)(IllegalStateException("Mismatched classifier history context")) *>
|
|
65
|
+
IO.fromEither(context.hcursor.get[Vector[Json]]("items").flatMap(_.traverse: item =>
|
|
66
|
+
val point = item.hcursor
|
|
67
|
+
for
|
|
68
|
+
event <- point.get[String]("eventId")
|
|
69
|
+
channel <- point.get[String]("channel")
|
|
70
|
+
time <- point.get[Long]("time")
|
|
71
|
+
value <- point.get[Double]("value")
|
|
72
|
+
yield Observation(event, channel, time, value)
|
|
73
|
+
)).flatMap: values =>
|
|
74
|
+
IO.raiseWhen(values.size > 10000)(IllegalStateException("Unbounded classifier history context")).as(values)
|
|
75
|
+
|
|
76
|
+
private def seed(context: Json, continuation: Boolean): IO[S] =
|
|
77
|
+
context.hcursor.downField("classifierSeed").focus.filterNot(_.isNull) match
|
|
78
|
+
case None if continuation => IO.raiseError(IllegalStateException("Durable classifier continuation state required"))
|
|
79
|
+
case None => IO.pure(initial)
|
|
80
|
+
case Some(value) => decodeState(value.hcursor.downField("state").focus.getOrElse(Json.Null))
|
|
81
|
+
|
|
82
|
+
private def path(claim: Claim, unit: Int): String =
|
|
83
|
+
s"/v1/history/context?machine=$encoded&from=${claim.from}&until=${claim.until}&paddingMs=${paddingMs * unit}" +
|
|
84
|
+
s"&classifierKey=${encode(classifierKey)}&workId=${encode(claim.id)}&workToken=${encode(claim.token)}" +
|
|
85
|
+
claim.cursor.fold("")(value => s"&cursor=$value") + claim.end.fold("")(value => s"&end=$value")
|
|
86
|
+
|
|
87
|
+
private def execute(claim: Claim): IO[Unit] =
|
|
88
|
+
val unit = scale.get()
|
|
89
|
+
api.request("GET", path(claim, unit)).flatMap: context =>
|
|
90
|
+
// Only the receiver retires work, as part of the commit. Missing context leaves the claim available.
|
|
91
|
+
IO.whenA(context.hcursor.get[Boolean]("available").contains(true)):
|
|
92
|
+
for
|
|
93
|
+
points <- observations(context, claim, unit)
|
|
94
|
+
revision <- LocalHistory.contextRevision(context)
|
|
95
|
+
start <- seed(context, claim.cursor.isDefined)
|
|
96
|
+
page <- replay(points, start, unit)
|
|
97
|
+
_ <- commit(context, claim, page, revision)
|
|
98
|
+
yield ()
|
|
99
|
+
|
|
100
|
+
private def commit(context: Json, claim: Claim, page: Page[S], revision: String): IO[Unit] =
|
|
101
|
+
val checkpoint = page.at.fold(Json.obj()): at =>
|
|
102
|
+
Json.obj("checkpoint" -> Json.obj("key" -> classifierKey.asJson, "at" -> at.asJson, "state" -> page.state.asJson))
|
|
103
|
+
val metadata = context.hcursor.downField("context").focus.getOrElse(Json.obj()).deepMerge(Json.obj(
|
|
104
|
+
"revision" -> revision.asJson, "workToken" -> claim.token.asJson, "replace" -> Json.True
|
|
105
|
+
)).deepMerge(checkpoint).deepMerge(LocalHistory.commitFence(machine, claim.id, claim.token, generation))
|
|
106
|
+
val payload = Json.obj("machine" -> machine.raw.asJson, "workId" -> claim.id.asJson,
|
|
107
|
+
"segments" -> Json.arr(page.rows*), "context" -> metadata)
|
|
108
|
+
api.commitHistory(payload, replication).void
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
package scada.processing.runtime
|
|
2
|
+
|
|
3
|
+
import cats.effect.IO
|
|
4
|
+
import cats.syntax.all.*
|
|
5
|
+
import io.yarkivaev.segmentation.{TaggedSegment, Timestamp}
|
|
6
|
+
import scada.processing.core.{MachineId, Segments}
|
|
7
|
+
import scada.processing.infra.checkpoint.Checkpoint
|
|
8
|
+
|
|
9
|
+
/** Publishes each completed transition with its pending successor in one revision scope. */
|
|
10
|
+
object TimelinePublication:
|
|
11
|
+
def publish(
|
|
12
|
+
segments: Segments[IO], machine: MachineId, rows: List[TaggedSegment], compactLimit: Option[Int]
|
|
13
|
+
): IO[Unit] =
|
|
14
|
+
segments.atRevision(machine):
|
|
15
|
+
batches(rows, compactLimit).traverse_ { group =>
|
|
16
|
+
group.traverse_(row => segments.find(machine, row.segment.start)) *>
|
|
17
|
+
segments.upsertTransition(machine, group)
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
private def batches(rows: List[TaggedSegment], compactLimit: Option[Int]): List[List[TaggedSegment]] =
|
|
21
|
+
val pending = rows.lastOption.filter(_.segment.duration == 0)
|
|
22
|
+
val closed = (row: TaggedSegment) => row.segment.duration > 0
|
|
23
|
+
val compacted = compactLimit.filter(_ => pending.nonEmpty).fold(List.empty[TaggedSegment])(_ => rows.filter(closed) ++ pending)
|
|
24
|
+
if compacted.nonEmpty && compactLimit.exists(compacted.size <= _) &&
|
|
25
|
+
compacted.zip(compacted.drop(1)).forall((left, right) => left.segment.end == right.segment.start) then
|
|
26
|
+
List(compacted)
|
|
27
|
+
else
|
|
28
|
+
Iterator.unfold(rows): remaining =>
|
|
29
|
+
val (complete, rest) = remaining.span(closed)
|
|
30
|
+
rest match
|
|
31
|
+
case tail :: next => Some((complete :+ tail, next))
|
|
32
|
+
case Nil if complete.nonEmpty => Some((complete, Nil))
|
|
33
|
+
case Nil => None
|
|
34
|
+
.toList
|
|
35
|
+
|
|
36
|
+
/** The authoritative segments take precedence over the older replay cursor. */
|
|
37
|
+
def closedThrough(segments: Segments[IO], machine: MachineId, checkpoint: Option[Checkpoint]): IO[Long] =
|
|
38
|
+
segments.list(machine).flatMap: rows =>
|
|
39
|
+
rows.iterator.filter(_.segment.duration > 0).map(row => millis(row.segment.end)).maxOption match
|
|
40
|
+
case Some(end) => IO.pure(end)
|
|
41
|
+
case None => checkpoint.fold(IO.pure(0L))(_.fetchReplayCursor(machine).map(cursor => math.max(0L, millis(cursor))))
|
|
42
|
+
|
|
43
|
+
private def millis(time: Timestamp): Long = math.round(time.epoch * 1000)
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
package scada.processing.runtime
|
|
2
|
+
|
|
3
|
+
import cats.effect.{IO, Ref}
|
|
4
|
+
import cats.effect.std.Semaphore
|
|
5
|
+
import io.circe.{Decoder, Encoder}
|
|
6
|
+
import io.yarkivaev.streamworker.{Checkpoint, CheckpointStore, StaleOwnership, TaskIdentity}
|
|
7
|
+
import io.yarkivaev.streamworker.postgres.PgCheckpointStore
|
|
8
|
+
|
|
9
|
+
object WorkerStores:
|
|
10
|
+
final case class Binding[S, O](store: CheckpointStore[S, O], task: TaskIdentity, ownership: Long)
|
|
11
|
+
|
|
12
|
+
/** Claim the database checkpoint before draining pending outputs. Reconcile run mode without changing the outbox. */
|
|
13
|
+
def database[S: Encoder: Decoder, O: Encoder: Decoder](
|
|
14
|
+
db: WorkerDatabase,
|
|
15
|
+
initial: Checkpoint[S, O]
|
|
16
|
+
)(reconcile: S => Option[S]): IO[Binding[S, O]] =
|
|
17
|
+
val store = PgCheckpointStore[S, O](db.transactor)
|
|
18
|
+
val owner = db.generation
|
|
19
|
+
for
|
|
20
|
+
_ <- store.claim(owner, initial)
|
|
21
|
+
saved <- store.loadCompatible(initial.task, initial.version, owner)
|
|
22
|
+
_ <- reconcile(saved.state).fold(IO.unit): next =>
|
|
23
|
+
store.commit(owner, saved.revision, saved.copy(revision = saved.revision + 1L, state = next))
|
|
24
|
+
yield Binding(store, initial.task, owner)
|
|
25
|
+
|
|
26
|
+
/** Update the application journal before advancing the in-memory cursor. Caller owns the file lock. */
|
|
27
|
+
def local[S, O](initial: Checkpoint[S, O])(persist: Checkpoint[S, O] => IO[Unit]): IO[Binding[S, O]] =
|
|
28
|
+
val owner = 0L
|
|
29
|
+
for
|
|
30
|
+
state <- Ref.of[IO, Checkpoint[S, O]](initial)
|
|
31
|
+
lock <- Semaphore[IO](1)
|
|
32
|
+
yield
|
|
33
|
+
val store = new CheckpointStore[S, O]:
|
|
34
|
+
def load(task: TaskIdentity, ownership: Long): IO[Checkpoint[S, O]] =
|
|
35
|
+
IO.raiseUnless(task == initial.task && ownership == owner)(StaleOwnership(task, ownership)) *> state.get
|
|
36
|
+
|
|
37
|
+
def commit(ownership: Long, expectedRevision: Long, next: Checkpoint[S, O]): IO[Unit] =
|
|
38
|
+
lock.permit.use: _ =>
|
|
39
|
+
IO.uncancelable: _ =>
|
|
40
|
+
load(next.task, ownership).flatMap: current =>
|
|
41
|
+
IO.raiseUnless(current.revision == expectedRevision)(IllegalStateException("Worker checkpoint revision changed")) *>
|
|
42
|
+
persist(next) *> state.set(next)
|
|
43
|
+
Binding(store, initial.task, owner)
|