-
Notifications
You must be signed in to change notification settings - Fork 15
/
EventualJournal.scala
364 lines (281 loc) · 10.8 KB
/
EventualJournal.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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
package com.evolutiongaming.kafka.journal.eventual
import cats._
import cats.arrow.FunctionK
import cats.effect.Resource
import cats.syntax.all._
import com.evolutiongaming.catshelper.{Log, MeasureDuration, MonadThrowable}
import com.evolutiongaming.kafka.journal._
import com.evolutiongaming.kafka.journal.util.StreamHelper._
import com.evolutiongaming.skafka.{Offset, Partition, Topic}
import com.evolutiongaming.smetrics.MetricsHelper._
import com.evolutiongaming.smetrics._
import com.evolutiongaming.sstream.Stream
import scala.concurrent.duration.FiniteDuration
/** Reader of the replicated journal (Cassandra by default).
*
* This allows to access the data replicated from Kafka to Cassandara. Note,
* that all the methods of this class have eventual nature, i.e. there could be
* newer events already in Kafka, but not yet replicated to Cassandra.
*
* There could be other non-Cassandra implementations of this interface.
*/
trait EventualJournal[F[_]] {
/** Gets a last replicated [[PartitionOffset]] and [[SeqNr]] for specific journal [[Key]].
*
* @param key
* Unique identifier of a journal including a topic where it is stored
* in Kafka.
* @return
* [[JournalPointer]] containing a partition, an offset and sequence
* number of a last replicated event.
*/
def pointer(key: Key): F[Option[JournalPointer]]
/** Gets the last replicated offset for a partition topic.
*
* @param topic
* Kafka topic.
* @param partition
* Topic partition to get offset for.
* @return
* Partition offset, or `None` if such topic/partition pair never
* replicated.
*/
def offset(topic: Topic, partition: Partition): F[Option[Offset]]
/** Reads the replicated event journal.
*
* Streams all events already replicated to a storage (Cassandra by default).
* It does not keep streaming forever and ends the stream when the last
* replicated event is read.
*
* While it is possible to keep streaming forever by polling this method from
* time to time, the recommended way is to read Kafka instead.
*
* @param key
* Unique identifier of a journal including a topic where it is stored in
* Kafka.
* @param from
* First [[SeqNr]] to read.
* @return
* Stream of events found replicated to Cassandra ordered by [[SeqNr]].
*/
def read(key: Key, from: SeqNr): Stream[F, EventRecord[EventualPayloadAndType]]
/** Streams ids of journals replicated from a given topic.
*
* Streams all ids already replicated to a storage (Cassandra by default). It
* does not keep streaming forever and ends the stream when the last
* replicated journal is found.
*
* @param topic
* Kafka topic name where the journals are being stored in.
* @return
* Stream of ids found replicated to Cassandra.
*/
def ids(topic: Topic): Stream[F, String]
}
object EventualJournal {
def apply[F[_]](implicit F: EventualJournal[F]): EventualJournal[F] = F
private sealed abstract class Empty
def empty[F[_]: Applicative]: EventualJournal[F] = new Empty with EventualJournal[F] {
def read(key: Key, from: SeqNr) = Stream.empty[F, EventRecord[EventualPayloadAndType]]
def pointer(key: Key) = none[JournalPointer].pure[F]
def ids(topic: Topic) = Stream.empty[F, String]
def offset(topic: Topic, partition: Partition): F[Option[Offset]] = none[Offset].pure[F]
}
trait Metrics[F[_]] {
def offset(topic: Topic, latency: FiniteDuration): F[Unit]
def read(topic: Topic, latency: FiniteDuration): F[Unit]
def read(topic: Topic): F[Unit]
def pointer(topic: Topic, latency: FiniteDuration): F[Unit]
def ids(topic: Topic, latency: FiniteDuration): F[Unit]
}
object Metrics {
def empty[F[_] : Applicative]: Metrics[F] = const(Applicative[F].unit)
private sealed abstract class Const
def const[F[_]](unit: F[Unit]): Metrics[F] = new Const with Metrics[F] {
def read(topic: Topic, latency: FiniteDuration) = unit
def read(topic: Topic) = unit
def pointer(topic: Topic, latency: FiniteDuration) = unit
def ids(topic: Topic, latency: FiniteDuration) = unit
def offset(topic: Topic, latency: FiniteDuration): F[Unit] = unit
}
private sealed abstract class Main
def of[F[_]](
registry: CollectorRegistry[F],
prefix: String = "eventual_journal"
): Resource[F, Metrics[F]] = {
val latencySummary = registry.summary(
name = s"${ prefix }_topic_latency",
help = "Journal call latency in seconds",
quantiles = Quantiles.Default,
labels = LabelNames("topic", "type"))
val eventsSummary = registry.summary(
name = s"${ prefix }_events",
help = "Number of events",
quantiles = Quantiles.Empty,
labels = LabelNames("topic"))
for {
latencySummary <- latencySummary
eventsSummary <- eventsSummary
} yield {
def observeLatency(name: String, topic: Topic, latency: FiniteDuration) = {
latencySummary
.labels(topic, name)
.observe(latency.toNanos.nanosToSeconds)
}
new Main with Metrics[F] {
def read(topic: Topic, latency: FiniteDuration) = {
observeLatency(name = "read", topic = topic, latency = latency)
}
def read(topic: Topic) = {
eventsSummary.labels(topic).observe(1.0)
}
def pointer(topic: Topic, latency: FiniteDuration) = {
observeLatency(name = "pointer", topic = topic, latency = latency)
}
def ids(topic: Topic, latency: FiniteDuration) = {
observeLatency(name = "ids", topic = topic, latency = latency)
}
def offset(topic: Topic, latency: FiniteDuration): F[Unit] = {
observeLatency(name = "offset", topic = topic, latency = latency)
}
}
}
}
}
private sealed abstract class MapK
private sealed abstract class WithMetrics
private sealed abstract class WithLog
private sealed abstract class EnhanceError
implicit class EventualJournalOps[F[_]](val self: EventualJournal[F]) extends AnyVal {
def mapK[G[_]](fg: F ~> G, gf: G ~> F): EventualJournal[G] = new MapK with EventualJournal[G] {
def read(key: Key, from1: SeqNr) = self.read(key, from1).mapK(fg, gf)
def pointer(key: Key) = fg(self.pointer(key))
def ids(topic: Topic) = self.ids(topic).mapK(fg, gf)
def offset(topic: Topic, partition: Partition): G[Option[Offset]] = fg(self.offset(topic, partition))
}
def withLog(log: Log[F])(implicit F: FlatMap[F], measureDuration: MeasureDuration[F]): EventualJournal[F] = {
val functionKId = FunctionK.id[F]
new WithLog with EventualJournal[F] {
def read(key: Key, from: SeqNr) = {
val logging = new (F ~> F) {
def apply[A](fa: F[A]) = {
for {
d <- MeasureDuration[F].start
r <- fa
d <- d
_ <- log.debug(s"$key read in ${ d.toMillis }ms, from: $from, result: $r")
} yield r
}
}
self.read(key, from).mapK(logging, functionKId)
}
def pointer(key: Key) = {
for {
d <- MeasureDuration[F].start
r <- self.pointer(key)
d <- d
_ <- log.debug(s"$key pointer in ${ d.toMillis }ms, result: $r")
} yield r
}
def ids(topic: Topic) = {
val logging = new (F ~> F) {
def apply[A](fa: F[A]) = {
for {
d <- MeasureDuration[F].start
r <- fa
d <- d
_ <- log.debug(s"$topic ids in ${ d.toMillis }ms, result: $r")
} yield r
}
}
self.ids(topic).mapK(logging, functionKId)
}
def offset(topic: Topic, partition: Partition): F[Option[Offset]] = {
for {
d <- MeasureDuration[F].start
r <- self.offset(topic, partition)
d <- d
_ <- log.debug(s"$topic $partition offset in ${d.toMillis}ms, result: $r")
} yield r
}
}
}
def withMetrics(metrics: Metrics[F])(implicit F: FlatMap[F], measureDuration: MeasureDuration[F]): EventualJournal[F] = {
val functionKId = FunctionK.id[F]
new WithMetrics with EventualJournal[F] {
def read(key: Key, from: SeqNr) = {
val measure = new (F ~> F) {
def apply[A](fa: F[A]) = {
for {
d <- MeasureDuration[F].start
r <- fa
d <- d
_ <- metrics.read(topic = key.topic, latency = d)
} yield r
}
}
for {
a <- self.read(key, from).mapK(measure, functionKId)
_ <- metrics.read(key.topic).toStream
} yield a
}
def pointer(key: Key) = {
for {
d <- MeasureDuration[F].start
r <- self.pointer(key)
d <- d
_ <- metrics.pointer(key.topic, d)
} yield r
}
def ids(topic: Topic) = {
val measure = new (F ~> F) {
def apply[A](fa: F[A]) = {
for {
d <- MeasureDuration[F].start
r <- fa
d <- d
_ <- metrics.ids(topic, d)
} yield r
}
}
self.ids(topic).mapK(measure, functionKId)
}
def offset(topic: Topic, partition: Partition): F[Option[Offset]] = {
for {
d <- MeasureDuration[F].start
r <- self.offset(topic, partition)
d <- d
_ <- metrics.offset(topic, d)
} yield r
}
}
}
def enhanceError(implicit F: MonadThrowable[F]): EventualJournal[F] = {
def error[A](msg: String, cause: Throwable) = {
JournalError(s"EventualJournal.$msg failed with $cause", cause).raiseError[F, A]
}
new EnhanceError with EventualJournal[F] {
def read(key: Key, from: SeqNr) = {
self
.read(key, from)
.handleErrorWith { (a: Throwable) => error[EventRecord[EventualPayloadAndType]](s"read key: $key, from: $from", a).toStream }
}
def pointer(key: Key) = {
self
.pointer(key)
.handleErrorWith { a => error(s"pointer key: $key", a) }
}
def ids(topic: Topic) = {
self
.ids(topic)
.handleErrorWith { a => error[String](s"ids topic: $topic", a).toStream }
}
def offset(topic: Topic, partition: Partition): F[Option[Offset]] = {
self
.offset(topic, partition)
.handleErrorWith { a => error(s"offset topic: $topic, partition $partition", a) }
}
}
}
}
}