-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNewRelicCoroutineContext.kt
61 lines (56 loc) · 2.03 KB
/
NewRelicCoroutineContext.kt
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
import com.newrelic.api.agent.*
import kotlinx.coroutines.withContext
import kotlin.coroutines.AbstractCoroutineContextElement
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.coroutineContext
class NewRelicTransaction(val txn: Transaction) :
AbstractCoroutineContextElement(NewRelicTransaction) {
companion object Key : CoroutineContext.Key<NewRelicTransaction>
}
class NewRelicSegment(val segment: Segment) :
AbstractCoroutineContextElement(NewRelicSegment) {
companion object Key : CoroutineContext.Key<NewRelicSegment>
}
class NewRelicToken(val token: Token) : AbstractCoroutineContextElement(NewRelicToken) {
companion object Key : CoroutineContext.Key<NewRelicToken>
}
suspend fun <T> withNewRelicSegment(
name: String,
productName: String,
collectionName: String,
block: suspend () -> T
): T {
return runInAsyncTrace {
val token = coroutineContext[NewRelicToken]
token?.token?.link()
val segment = coroutineContext[NewRelicTransaction]?.let {
NewRelicSegment(it.txn.startSegment(name))
}
return@runInAsyncTrace if (token != null && segment != null) {
withContext(segment) {
try {
runInAsyncTrace {
val response = block()
token.token.link()
response
}
} finally {
segment.segment.reportAsExternal(
DatastoreParameters
.product(productName)
.collection(collectionName)
.operation(name)
.noInstance()
.databaseName(collectionName)
.build()
)
segment.segment.endAsync()
}
}
} else {
block()
}
}
}
@Trace(async = true)
private suspend fun <T> runInAsyncTrace(block: suspend () -> T): T = block()