forked from apache/pekko-persistence-jdbc
/
JdbcDurableStateStore.scala
239 lines (205 loc) · 8.64 KB
/
JdbcDurableStateStore.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* license agreements; and to You under the Apache License, version 2.0:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* This file is part of the Apache Pekko project, which was derived from Akka.
*/
/*
* Copyright (C) 2014 - 2019 Dennis Vriend <https://github.com/dnvriend>
* Copyright (C) 2019 - 2021 Lightbend Inc. <https://www.lightbend.com>
*/
package org.apache.pekko.persistence.jdbc.state.scaladsl
import scala.concurrent.{ ExecutionContext, Future }
import scala.concurrent.duration._
import scala.util.Try
import slick.jdbc.{ JdbcBackend, JdbcProfile }
import org.apache.pekko
import pekko.{ Done, NotUsed }
import pekko.actor.ExtendedActorSystem
import pekko.pattern.ask
import pekko.persistence.state.scaladsl.{ DurableStateUpdateStore, GetObjectResult }
import pekko.persistence.jdbc.PekkoSerialization
import pekko.persistence.jdbc.state.DurableStateQueries
import pekko.persistence.jdbc.config.DurableStateTableConfiguration
import pekko.persistence.jdbc.state.{ DurableStateTables, OffsetSyntax }
import pekko.persistence.query.{ DurableStateChange, Offset }
import pekko.persistence.query.scaladsl.DurableStateStoreQuery
import pekko.persistence.jdbc.journal.dao.FlowControl
import pekko.serialization.Serialization
import pekko.stream.scaladsl.{ Sink, Source }
import pekko.stream.{ Materializer, SystemMaterializer }
import pekko.util.Timeout
import DurableStateSequenceActor._
import OffsetSyntax._
import pekko.annotation.ApiMayChange
import pekko.persistence.query.UpdatedDurableState
object JdbcDurableStateStore {
val Identifier = "jdbc-durable-state-store"
}
/**
* API may change
*/
@ApiMayChange
class JdbcDurableStateStore[A](
db: JdbcBackend#Database,
val profile: JdbcProfile,
durableStateConfig: DurableStateTableConfiguration,
serialization: Serialization)(implicit val system: ExtendedActorSystem)
extends DurableStateUpdateStore[A]
with DurableStateStoreQuery[A] {
import FlowControl._
import profile.api._
implicit val ec: ExecutionContext = system.dispatcher
implicit val mat: Materializer = SystemMaterializer(system).materializer
lazy val queries = new DurableStateQueries(profile, durableStateConfig)
// Started lazily to prevent the actor for querying the db if no changesByTag queries are used
private[jdbc] lazy val stateSequenceActor = system.systemActorOf(
DurableStateSequenceActor.props(this, durableStateConfig.stateSequenceConfig),
s"pekko-persistence-jdbc-durable-state-sequence-actor")
def getObject(persistenceId: String): Future[GetObjectResult[A]] = {
db.run(queries.selectFromDbByPersistenceId(persistenceId).result).map { rows =>
rows.headOption match {
case Some(row) =>
GetObjectResult(
PekkoSerialization.fromDurableStateRow(serialization)(row).toOption.asInstanceOf[Option[A]],
row.revision)
case None =>
GetObjectResult(None, 0)
}
}
}
def upsertObject(persistenceId: String, revision: Long, value: A, tag: String): Future[Done] = {
require(revision > 0)
val row =
PekkoSerialization.serialize(serialization, value).map { serialized =>
DurableStateTables.DurableStateRow(
0, // insert 0 for autoinc columns
persistenceId,
revision,
serialized.payload,
Option(tag).filter(_.trim.nonEmpty),
serialized.serId,
Option(serialized.serManifest).filter(_.trim.nonEmpty),
System.currentTimeMillis)
}
Future
.fromTry(row)
.flatMap { r =>
val action = if (revision == 1) insertDurableState(r) else updateDurableState(r)
db.run(action)
}
.map { rowsAffected =>
if (rowsAffected == 0)
throw new IllegalStateException(
s"Incorrect revision number [$revision] provided: It has to be 1 more than the value existing in the database for persistenceId [$persistenceId]")
else Done
}
}
def deleteObject(persistenceId: String): Future[Done] =
db.run(queries.deleteFromDb(persistenceId).map(_ => Done))
def deleteObject(persistenceId: String, revision: Long): Future[Done] =
db.run(queries.deleteFromDb(persistenceId).map(_ => Done))
def currentChanges(tag: String, offset: Offset): Source[DurableStateChange[A], NotUsed] = {
Source
.futureSource(maxStateStoreOffset().map { maxOrderingInDb =>
changesByTag(tag, offset.value, terminateAfterOffset = Some(maxOrderingInDb))
})
.mapMaterializedValue(_ => NotUsed)
}
def changes(tag: String, offset: Offset): Source[DurableStateChange[A], NotUsed] =
changesByTag(tag, offset.value, terminateAfterOffset = None)
private def currentChangesByTag(
tag: String,
from: Long,
batchSize: Long,
queryUntil: MaxGlobalOffset): Source[DurableStateChange[A], NotUsed] = {
if (queryUntil.maxOffset < from) Source.empty
else changesByTagFromDb(tag, from, queryUntil.maxOffset, batchSize).mapAsync(1)(Future.fromTry)
}
private def changesByTagFromDb(
tag: String,
offset: Long,
maxOffset: Long,
batchSize: Long): Source[Try[DurableStateChange[A]], NotUsed] = {
Source
.fromPublisher(db.stream(queries.changesByTag((tag, offset, maxOffset, batchSize)).result))
.map(toDurableStateChange)
}
private[jdbc] def changesByTag(
tag: String,
offset: Long,
terminateAfterOffset: Option[Long]): Source[DurableStateChange[A], NotUsed] = {
val batchSize = durableStateConfig.batchSize
val startingOffsets = List.empty[Long]
implicit val askTimeout: Timeout = Timeout(durableStateConfig.stateSequenceConfig.askTimeout)
Source
.unfoldAsync[(Long, FlowControl, List[Long]), Seq[DurableStateChange[A]]]((offset, Continue, startingOffsets)) {
case (from, control, s) =>
def retrieveNextBatch() = {
for {
queryUntil <- stateSequenceActor.ask(GetMaxGlobalOffset).mapTo[MaxGlobalOffset]
xs <- currentChangesByTag(tag, from, batchSize, queryUntil).runWith(Sink.seq)
} yield {
val hasMoreEvents = xs.size == batchSize
val nextControl: FlowControl =
terminateAfterOffset match {
// we may stop if target is behind queryUntil and we don't have more events to fetch
case Some(target) if !hasMoreEvents && target <= queryUntil.maxOffset => Stop
// We may also stop if we have found an event with an offset >= target
case Some(target) if xs.exists(_.offset.value >= target) => Stop
// otherwise, disregarding if Some or None, we must decide how to continue
case _ =>
if (hasMoreEvents) Continue
else ContinueDelayed
}
val nextStartingOffset = if (xs.isEmpty) {
math.max(from.value, queryUntil.maxOffset)
} else {
// Continue querying from the largest offset
xs.map(_.offset.value).max
}
Some(((nextStartingOffset, nextControl, s :+ nextStartingOffset), xs))
}
}
control match {
case Stop => Future.successful(None)
case Continue => retrieveNextBatch()
case ContinueDelayed =>
pekko.pattern.after(durableStateConfig.refreshInterval, system.scheduler)(retrieveNextBatch())
}
}
.mapConcat(identity)
}
private[jdbc] def maxStateStoreOffset(): Future[Long] =
db.run(queries.maxOffsetQuery.result)
private[jdbc] def stateStoreStateInfo(offset: Long, limit: Long): Source[(String, Long, Long), NotUsed] =
Source.fromPublisher(db.stream(queries.stateStoreStateQuery((offset, limit)).result))
private def toDurableStateChange(row: DurableStateTables.DurableStateRow): Try[DurableStateChange[A]] = {
PekkoSerialization
.fromDurableStateRow(serialization)(row)
.map(payload =>
new UpdatedDurableState(
row.persistenceId,
row.revision,
payload.asInstanceOf[A],
Offset.sequence(row.globalOffset),
row.stateTimestamp))
}
private def updateDurableState(row: DurableStateTables.DurableStateRow) = {
import queries._
for {
s <- getSequenceNextValueExpr()
u <- updateDbWithDurableState(row, s.head)
} yield u
}
private def insertDurableState(row: DurableStateTables.DurableStateRow) = {
import queries._
for {
s <- getSequenceNextValueExpr()
u <- insertDbWithDurableState(row, s.head)
} yield u
}
def deleteAllFromDb() = db.run(queries.deleteAllFromDb())
}