Skip to content

Commit

Permalink
Replace scala.util.Using with try/finally
Browse files Browse the repository at this point in the history
  • Loading branch information
iRevive committed Nov 4, 2023
1 parent c40c69f commit 09087e7
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 12 deletions.
16 changes: 9 additions & 7 deletions docs/instrumentation/tracing-java-interop.md
Original file line number Diff line number Diff line change
Expand Up @@ -152,24 +152,26 @@ import cats.mtl.Local
import cats.syntax.flatMap._
import org.typelevel.otel4s.java.context.Context
import io.opentelemetry.context.{Context => JContext}
import scala.util.Using

def useJContext[F[_]: Sync, A](use: JContext => A)(implicit L: Local[F, Context]): F[A] =
Local[F, Context].ask.flatMap { ctx => // <1>
Sync[F].defer {
Sync[F].fromTry {
val jContext: JContext = ctx.underlying // <2>
Using(jContext.makeCurrent())(_ => use(jContext)) // <3>
Sync[F].delay {
val jContext: JContext = ctx.underlying // <2>
val scope = jContext.makeCurrent() // <3>
try {
use(jContext)
} finally {
scope.close()
}
}
}
```

1) `Local[F, Context].ask` - get the current otel4s context
2) `ctx.underlying` - unwrap otel4s context and get `JContext`
3) `Using(jContext.makeCurrent())` - activate `JContext` within the current thread and run `use` afterward
3) `jContext.makeCurrent()` - activate `JContext` within the current thread

**Note:** here we use `Sync[F].defer` and `Sync[F].fromTry` to handle the side effects.
**Note:** we use `Sync[F].delay` to handle the side effects.
Depending on your use case, you may prefer `Sync[F].interruptible` or `Sync[F].blocking`.

Now we can run a slightly modified original 'problematic' example:
Expand Down
12 changes: 7 additions & 5 deletions examples/src/main/scala/PekkoHttpExample.scala
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ import org.typelevel.otel4s.trace.Tracer

import scala.concurrent.Future
import scala.concurrent.duration._
import scala.util.Using

/** This example relies on the OpenTelemetry Java agent. To make it work, add
* the following settings to your build:
Expand Down Expand Up @@ -179,10 +178,13 @@ object PekkoHttpExample extends IOApp.Simple {
L: Local[F, Context]
): F[A] =
Local[F, Context].ask.flatMap { ctx =>
Sync[F].defer {
Sync[F].fromTry {
val jContext: JContext = ctx.underlying
Using(jContext.makeCurrent())(_ => use(jContext))
Sync[F].delay {
val jContext: JContext = ctx.underlying
val scope = jContext.makeCurrent()
try {
use(jContext)
} finally {
scope.close()
}
}
}
Expand Down

0 comments on commit 09087e7

Please sign in to comment.