/
StreamOps.scala
341 lines (292 loc) · 11.3 KB
/
StreamOps.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
/*
* Copyright 2014-2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.atlas.akka
import java.util.concurrent.TimeUnit
import akka.NotUsed
import akka.stream.ActorAttributes
import akka.stream.Attributes
import akka.stream.BoundedSourceQueue
import akka.stream.FlowShape
import akka.stream.Graph
import akka.stream.Inlet
import akka.stream.Materializer
import akka.stream.Outlet
import akka.stream.QueueOfferResult
import akka.stream.SourceShape
import akka.stream.Supervision
import akka.stream.scaladsl.Flow
import akka.stream.scaladsl.Source
import akka.stream.stage.GraphStage
import akka.stream.stage.GraphStageLogic
import akka.stream.stage.InHandler
import akka.stream.stage.OutHandler
import com.netflix.spectator.api.Clock
import com.netflix.spectator.api.Registry
import com.typesafe.scalalogging.StrictLogging
/**
* Utility functions for commonly used operations on Akka streams. Most of these are for
* the purpose of getting additional instrumentation into the behavior of the stream.
*/
object StreamOps extends StrictLogging {
/**
* Return attributes for running a stream with a supervision strategy that will provide
* some insight into exceptions.
*
* @param registry
* Registry to use for reporting metrics.
*/
def supervisionStrategy(registry: Registry): Attributes = {
ActorAttributes.withSupervisionStrategy { t =>
registry
.counter("akka.stream.exceptions", "error", t.getClass.getSimpleName)
.increment()
logger.warn(s"exception from stream stage", t)
Supervision.Stop
}
}
/**
* Creates a queue source based on a `BoundedSourceQueue`. Values offered to the queue
* will be emitted by the source. Can be used to get metrics when using `Source.queue(size)`
* that was introduced in [#29770].
*
* [#29770]: https://github.com/akka/akka/pull/29770
*
* The bounded source queue should be preferred to `Source.queue(*, strategy)`
* or `Source.actorRef` that can have unbounded memory use if the consumer cannot keep
* up with the rate of data being offered ([#25798]).
*
* [#25798]: https://github.com/akka/akka/issues/25798
*
* @param registry
* Spectator registry to manage metrics for this queue.
* @param id
* Dimension used to distinguish a particular queue usage.
* @param size
* Number of enqueued items to allow before triggering the overflow strategy.
* @return
* Source that emits values offered to the queue.
*/
def blockingQueue[T](registry: Registry, id: String, size: Int): Source[T, SourceQueue[T]] = {
Source.queue(size).mapMaterializedValue(q => new SourceQueue[T](registry, id, q))
}
final class SourceQueue[T] private[akka] (
registry: Registry,
id: String,
queue: BoundedSourceQueue[T]
) {
private val baseId = registry.createId("akka.stream.offeredToQueue", "id", id)
private val enqueued = registry.counter(baseId.withTag("result", "enqueued"))
private val dropped = registry.counter(baseId.withTag("result", "droppedQueueFull"))
private val closed = registry.counter(baseId.withTag("result", "droppedQueueClosed"))
private val failed = registry.counter(baseId.withTag("result", "droppedQueueFailure"))
@volatile private var completed: Boolean = false
/**
* Add the value into the queue if there is room. Returns true if the value was successfully
* enqueued.
*/
def offer(value: T): Boolean = {
queue.offer(value) match {
case QueueOfferResult.Enqueued => enqueued.increment(); true
case QueueOfferResult.Dropped => dropped.increment(); false
case QueueOfferResult.QueueClosed => closed.increment(); false
case QueueOfferResult.Failure(_) => failed.increment(); false
}
}
/**
* Indicate that the use of the queue is complete. This will allow the associated stream
* to finish processing elements and then shutdown. Any new elements offered to the queue
* will be dropped.
*/
def complete(): Unit = {
queue.complete()
completed = true
}
/** Check if the queue is open to take more data. */
def isOpen: Boolean = !completed
/** The approximate number of entries in the queue. */
def size: Int = queue.size()
}
/**
* Stage that measures the flow of data through the stream. It will keep track of three
* meters:
*
* - `akka.stream.numEvents`: a simple counter indicating the number of events that flow
* through the stream.
*
* - `akka.stream.downstreamDelay`: a timer measuring the delay for the downstream to
* request a new element from the stream after an item is pushed. This can be used to
* understand if the downstream cannot keep up and is introducing significant back
* pressure delays.
*
* - `akka.stream.upstreamDelay`: a timer measuring the delay for the upstream to push
* a new element after one has been requested.
*
* Updates to meters will be batched so the updates may be delayed if used for a low
* throughput stream.
*
* @param registry
* Spectator registry to manage metrics.
* @param id
* Dimension used to distinguish a particular usage.
*/
def monitorFlow[T](registry: Registry, id: String): Flow[T, T, NotUsed] = {
Flow[T].via(new MonitorFlow[T](registry, id))
}
private final class MonitorFlow[T](registry: Registry, id: String)
extends GraphStage[FlowShape[T, T]] {
private val numEvents = registry.counter("akka.stream.numEvents", "id", id)
private val upstreamTimer = registry.timer("akka.stream.upstreamDelay", "id", id)
private val downstreamTimer = registry.timer("akka.stream.downstreamDelay", "id", id)
private val in = Inlet[T]("MonitorBackpressure.in")
private val out = Outlet[T]("MonitorBackpressure.out")
override val shape: FlowShape[T, T] = FlowShape(in, out)
override def createLogic(inheritedAttributes: Attributes): GraphStageLogic = {
new GraphStageLogic(shape) with InHandler with OutHandler {
import MonitorFlow._
private var lastUpdate = registry.clock().monotonicTime()
private var upstreamIdx = 0
private val upstreamTimes = new Array[Long](MeterBatchSize)
private var downstreamIdx = 0
private val downstreamTimes = new Array[Long](MeterBatchSize)
private var upstreamStart = -1L
private var downstreamStart = -1L
override def onPush(): Unit = {
val now = registry.clock().monotonicTime()
if (upstreamStart != -1L) {
upstreamTimes(upstreamIdx) = now - upstreamStart
upstreamIdx += 1
upstreamStart = -1L
}
push(out, grab(in))
downstreamStart = now
if (upstreamIdx == MeterBatchSize || now - lastUpdate > MeterUpdateInterval) {
updateMeters(now)
}
}
override def onPull(): Unit = {
val now = registry.clock().monotonicTime()
if (downstreamStart != -1L) {
downstreamTimes(downstreamIdx) = now - downstreamStart
downstreamIdx += 1
downstreamStart = -1L
}
pull(in)
upstreamStart = now
if (downstreamIdx == MeterBatchSize) {
updateMeters(now)
}
}
override def onUpstreamFinish(): Unit = {
updateMeters(registry.clock().monotonicTime())
super.onUpstreamFinish()
}
private def updateMeters(now: Long): Unit = {
numEvents.increment(upstreamIdx)
upstreamTimer.record(upstreamTimes, upstreamIdx, TimeUnit.NANOSECONDS)
upstreamIdx = 0
downstreamTimer.record(downstreamTimes, downstreamIdx, TimeUnit.NANOSECONDS)
downstreamIdx = 0
lastUpdate = now
}
setHandlers(in, out, this)
}
}
}
private object MonitorFlow {
private val MeterBatchSize = 10000
private val MeterUpdateInterval = TimeUnit.SECONDS.toNanos(1L)
}
/**
* Map operation that passes in the materializer for the graph stage.
*
* @param f
* Function that maps the input value to a new value.
* @return
* Flow that applies the mapping function to each value.
*/
def map[V1, V2](f: (V1, Materializer) => V2): Flow[V1, V2, NotUsed] = {
Flow[V1].via(new MapFlow(f))
}
private final class MapFlow[V1, V2](f: (V1, Materializer) => V2)
extends GraphStage[FlowShape[V1, V2]] {
private val in = Inlet[V1]("MapFlow.in")
private val out = Outlet[V2]("MapFlow.out")
override val shape: FlowShape[V1, V2] = FlowShape(in, out)
override def createLogic(inheritedAttributes: Attributes): GraphStageLogic = {
new GraphStageLogic(shape) with InHandler with OutHandler {
override def onPush(): Unit = {
push(out, f(grab(in), materializer))
}
override def onPull(): Unit = {
pull(in)
}
setHandlers(in, out, this)
}
}
}
/**
* Flat map operation that passes in the materializer for the graph stage.
*
* @param f
* Function that maps the input value to a new value.
* @return
* Flow that applies the mapping function to each value.
*/
def flatMapConcat[V1, V2, M](
f: (V1, Materializer) => Graph[SourceShape[V2], M]
): Flow[V1, V2, NotUsed] = {
map(f).flatMapConcat(src => src)
}
/**
* Filter out repeated values in a stream. Similar to the unix `uniq` command.
*
* @param timeout
* Repeated value will still be emitted if elapsed time since last emit exceeds
* timeout. Unit is milliseconds.
*/
def unique[V](timeout: Long = Long.MaxValue, clock: Clock = Clock.SYSTEM): Flow[V, V, NotUsed] = {
Flow[V].via(new UniqueFlow[V](timeout, clock))
}
private final class UniqueFlow[V](timeout: Long, clock: Clock)
extends GraphStage[FlowShape[V, V]] {
private val in = Inlet[V]("UniqueFlow.in")
private val out = Outlet[V]("UniqueFlow.out")
override val shape: FlowShape[V, V] = FlowShape(in, out)
override def createLogic(inheritedAttributes: Attributes): GraphStageLogic = {
new GraphStageLogic(shape) with InHandler with OutHandler {
private var previous: V = _
private var lastPushedAt: Long = 0
private def isExpired: Boolean = {
lastPushedAt == 0 || clock.wallTime() - lastPushedAt > timeout
}
override def onPush(): Unit = {
val v = grab(in)
if (v == previous && !isExpired) {
pull(in)
} else {
previous = v
lastPushedAt = clock.wallTime()
push(out, v)
}
}
override def onPull(): Unit = {
pull(in)
}
setHandlers(in, out, this)
}
}
}
}