Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add IOLocalContextStorage #214

Merged
merged 30 commits into from
Dec 31, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
ac4175c
Experimental IOLocalContextStorage
rossabaker May 12, 2023
682abb6
Try typelevel/cats-effect#3636
rossabaker May 18, 2023
5f460ee
Apply suggestions from code review
rossabaker May 18, 2023
e522ac8
Get latest cats-effect branch
rossabaker May 18, 2023
d9a1079
Fine, have your headers
rossabaker May 18, 2023
c4410ab
Unused import
rossabaker May 19, 2023
6b542aa
Get testkit out of main dependenecies
rossabaker May 19, 2023
b6a75a0
Attmept at a ContextStorageProvider SPI
rossabaker May 19, 2023
978ccef
Use syncStep to initialize the local context
rossabaker May 19, 2023
9913704
Update Cats Effect snapshot
rossabaker May 22, 2023
b6c2b0f
Remove direct reference to IOLocalContextStorageProvider
rossabaker May 22, 2023
8c31136
Unbox IOLocal
rossabaker May 23, 2023
6e09fe2
Merge branch 'main' into context-storage
armanbilge Jun 28, 2023
fe7259e
Fix compile, update to CE snapshot
armanbilge Jun 28, 2023
d10303b
Merge branch 'main' into context-storage
NthPortal Oct 4, 2023
e60f793
Finish implementing `IOLocalContextStorage`
NthPortal Aug 31, 2023
39ba754
fixup! Finish implementing `IOLocalContextStorage`
NthPortal Oct 4, 2023
61d5af7
Merge branch 'upstream-main' into context-storage
iRevive Dec 13, 2024
713736b
Update cats-effect, fix implementation
iRevive Dec 13, 2024
b9b8fd9
Fix CI workflow
iRevive Dec 13, 2024
653ebf0
Use cats-effect 3.6.0-RC1
iRevive Dec 28, 2024
5cf5a4e
Fix docs
iRevive Dec 28, 2024
5ad342c
Merge branch 'upstream-main' into context-storage
iRevive Dec 31, 2024
44ddc9a
Add minimal documentation
iRevive Dec 31, 2024
05b886d
Run scalafix
iRevive Dec 31, 2024
45c08f6
Update doc example
iRevive Dec 31, 2024
b54341a
Regenerate ci.yml
iRevive Dec 31, 2024
333fd4e
Merge branch 'refs/heads/upstream-main' into context-storage
iRevive Dec 31, 2024
f1f0925
Regenerate ci.yml
iRevive Dec 31, 2024
5cd592f
Fix compilation issue
iRevive Dec 31, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -705,12 +705,11 @@ lazy val `oteljava-testkit` = project

lazy val `oteljava-context-storage` = project
.in(file("oteljava/context-storage"))
.dependsOn(`java-common`)
.dependsOn(`oteljava-common`)
.settings(munitDependencies)
.settings(
name := "otel4s-java-context-storage",
name := "otel4s-oteljava-context-storage",
libraryDependencies ++= Seq(
"org.typelevel" %%% "cats-effect" % CatsEffectVersion,
"org.typelevel" %%% "cats-effect-testkit" % CatsEffectVersion % Test,
),
Test / javaOptions ++= Seq(
Expand Down Expand Up @@ -974,6 +973,7 @@ lazy val unidocs = project
`oteljava-trace`,
`oteljava-trace-testkit`,
`oteljava-testkit`,
`oteljava-context-storage`,
oteljava,
`semconv-stable`.jvm,
`semconv-experimental`.jvm,
Expand Down
41 changes: 16 additions & 25 deletions examples/src/main/scala/ContextStorageExample.scala
Original file line number Diff line number Diff line change
Expand Up @@ -16,33 +16,24 @@

import cats.effect.IO
import cats.effect.IOApp
import cats.effect.Resource
import io.opentelemetry.context.Context
import io.opentelemetry.context.ContextKey
import io.opentelemetry.context.ContextStorage

import java.util.logging._
import io.opentelemetry.api.trace.{Span => JSpan}
import org.typelevel.otel4s.context.LocalProvider
import org.typelevel.otel4s.oteljava.IOLocalContextStorage
import org.typelevel.otel4s.oteljava.OtelJava
import org.typelevel.otel4s.oteljava.context.Context

object ContextStorageExample extends IOApp.Simple {
NthPortal marked this conversation as resolved.
Show resolved Hide resolved

val key = ContextKey.named[String]("test")

val printKey =
IO(Option(Context.current().get(key))).flatMap(v => IO.println(v))

def run =
for {
_ <- IO {
val rootLog = Logger.getLogger("")
rootLog.setLevel(Level.FINE)
rootLog.getHandlers().head.setLevel(Level.FINE)
def run: IO[Unit] = {
implicit val provider: LocalProvider[IO, Context] = IOLocalContextStorage.localProvider[IO]
OtelJava.autoConfigured[IO]().use { otelJava =>
otelJava.tracerProvider.tracer("").get.flatMap { tracer =>
tracer.span("test").use { span => // start 'test' span using otel4s
val jSpanContext = JSpan.current().getSpanContext // get a span from a ThreadLocal var
IO.println(s"jCtx: ${jSpanContext}, Otel4s ctx: ${span.context}")
}
}
_ <- IO.println(ContextStorage.get.getClass())
_ <- Resource
.make(IO(Context.root().`with`(key, "hello").makeCurrent()))(scope =>
IO(scope.close())
)
.surround(printKey)
_ <- printKey
} yield ()
}
}

}

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
org.typelevel.otel4s.oteljava.IOLocalContextStorageProvider
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
/*
* Copyright 2022 Typelevel
*
* 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 org.typelevel.otel4s.oteljava

import cats.effect.IOLocal
import cats.effect.LiftIO
import cats.effect.MonadCancelThrow
import cats.mtl.Local
import io.opentelemetry.context.{Context => JContext}
import io.opentelemetry.context.ContextStorage
import io.opentelemetry.context.Scope
import org.typelevel.otel4s.context.LocalProvider
import org.typelevel.otel4s.instances.local._
import org.typelevel.otel4s.oteljava.context.Context
import org.typelevel.otel4s.oteljava.context.LocalContext

/** A `ContextStorage` backed by an [[cats.effect.IOLocal `IOLocal`]] of a
* [[org.typelevel.otel4s.oteljava.context.Context `Context`]] that also provides [[cats.mtl.Local `Local`]] instances
* that reflect the state of the backing `IOLocal`. Usage of `Local` and `ContextStorage` methods will be consistent
* and stay in sync as long as effects are threaded properly.
*/
class IOLocalContextStorage(_ioLocal: () => IOLocal[Context]) extends ContextStorage {
private[this] implicit lazy val ioLocal: IOLocal[Context] = _ioLocal()
private[this] lazy val unsafeThreadLocal = ioLocal.unsafeThreadLocal()

@inline private[this] def unsafeCurrent: Context =
unsafeThreadLocal.get()

override def attach(toAttach: JContext): Scope = {
val previous = unsafeCurrent
unsafeThreadLocal.set(Context.wrap(toAttach))
() => unsafeThreadLocal.set(previous)
}

override def current(): JContext =
unsafeCurrent.underlying

/** @return
* a [[cats.mtl.Local `Local`]] of a [[org.typelevel.otel4s.oteljava.context.Context `Context`]] that reflects the
* state of the backing `IOLocal`
*/
def local[F[_]: MonadCancelThrow: LiftIO]: LocalContext[F] = implicitly
}

object IOLocalContextStorage {

/** Returns a [[cats.mtl.Local `Local`]] of a [[org.typelevel.otel4s.oteljava.context.Context `Context`]] if an
* [[`IOLocalContextStorage`]] is configured to be used as the `ContextStorage` for the Java otel library.
*
* Raises an exception if an [[`IOLocalContextStorage`]] is __not__ configured to be used as the `ContextStorage` for
* the Java otel library, or if [[cats.effect.IOLocal `IOLocal`]] propagation is not enabled.
*
* @example
* {{{
* implicit val localProvider: LocalProvider[IO, Context] = IOLocalContextStorage.localProvider
* OtelJava.autoConfigured[IO].use { otel4s =>
* ...
* }
* }}}
*/
def localProvider[F[_]: LiftIO](implicit F: MonadCancelThrow[F]): LocalProvider[F, Context] =
new LocalProvider[F, Context] {
def local: F[Local[F, Context]] =
ContextStorage.get() match {
case storage: IOLocalContextStorage =>
if (IOLocal.isPropagating) {
F.pure(storage.local)
} else {
F.raiseError(
new IllegalStateException(
"IOLocal propagation must be enabled with: -Dcats.effect.ioLocalPropagation=true"
)
)
}
case _ =>
F.raiseError(
new IllegalStateException(
"IOLocalContextStorage is not configured for use as the ContextStorageProvider"
)
)
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,14 @@
* limitations under the License.
*/

package org.typelevel.otel4s.java
package org.typelevel.otel4s.oteljava

import cats.effect.IOLocal
import cats.effect.SyncIO
import cats.syntax.all._
import io.opentelemetry.context.ContextStorage
import io.opentelemetry.context.ContextStorageProvider
import org.typelevel.otel4s.java.context.Context
import org.typelevel.otel4s.oteljava.context.Context

object IOLocalContextStorageProvider {
private lazy val localContext: IOLocal[Context] =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
* limitations under the License.
*/

package org.typelevel.otel4s.java
package org.typelevel.otel4s.oteljava

import cats.effect.IO
import cats.effect.SyncIO
Expand All @@ -23,16 +23,16 @@ import io.opentelemetry.context.ContextStorage
import munit.CatsEffectSuite
import munit.Location
import org.typelevel.otel4s.context.Key
import org.typelevel.otel4s.java.context.Context
import org.typelevel.otel4s.java.context.LocalContext
import org.typelevel.otel4s.oteljava.context.Context
import org.typelevel.otel4s.oteljava.context.LocalContext

import scala.util.Using

class IOLocalContextStorageSuite extends CatsEffectSuite {
import IOLocalContextStorageSuite._

private val localF: IO[LocalContext[IO]] =
IOLocalContextStorage.providedLocal
private val localProvider: IO[LocalContext[IO]] =
IOLocalContextStorage.localProvider[IO].local

private def sCurrent[F[_]](implicit L: LocalContext[F]): F[Context] =
L.ask[Context]
Expand All @@ -46,7 +46,7 @@ class IOLocalContextStorageSuite extends CatsEffectSuite {
)(body: LocalContext[IO] => IO[Any])(implicit loc: Location): Unit =
test(name) {
for {
local <- localF
local <- localProvider
_ <- body(local)
} yield ()
}
Expand Down Expand Up @@ -78,7 +78,8 @@ class IOLocalContextStorageSuite extends CatsEffectSuite {
}
}

test("works as a Java-only ContextStorage") {
// see https://discord.com/channels/632277896739946517/839263556754472990/1317163027451088926
test("works as a Java-only ContextStorage".ignore) {
usingModifiedCtx(_.`with`(key1, "1")) {
assertEquals(Option(jCurrent.get(key1)), Some("1"))
assertEquals(Option(jCurrent.get(key2)), None)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ private[oteljava] final case class SpanBuilderImpl[F[_]: Sync] private (
Resource.eval(runnerContext).flatMap(ctx => runner.start(ctx))

override def use[A](f: Span[F] => F[A]): F[A] =
resource.use { res => res.trace(f(res.span)) }
resource.use(res => res.trace(Sync[F].defer(f(res.span))))
NthPortal marked this conversation as resolved.
Show resolved Hide resolved

override def use_ : F[Unit] = use(_ => Sync[F].unit)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

package org.typelevel.otel4s.sdk.autoconfigure

import cats.MonadThrow
import cats.effect.MonadCancelThrow
import cats.effect.Resource
import cats.syntax.monadError._

Expand Down Expand Up @@ -89,7 +89,7 @@ object AutoConfigure {
* @tparam A
* the type of the component
*/
abstract class WithHint[F[_]: MonadThrow, A](
abstract class WithHint[F[_]: MonadCancelThrow, A](
hint: String,
configKeys: Set[Config.Key[_]]
) extends AutoConfigure[F, A] {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

package org.typelevel.otel4s.sdk.metrics.autoconfigure

import cats.MonadThrow
import cats.effect.MonadCancelThrow
import cats.effect.Resource
import org.typelevel.otel4s.sdk.autoconfigure.AutoConfigure
import org.typelevel.otel4s.sdk.autoconfigure.Config
Expand All @@ -41,7 +41,7 @@ import org.typelevel.otel4s.sdk.metrics.exemplar.TraceContextLookup
* @see
* [[https://opentelemetry.io/docs/languages/java/configuration/#exemplars]]
*/
private final class ExemplarFilterAutoConfigure[F[_]: MonadThrow](
private final class ExemplarFilterAutoConfigure[F[_]: MonadCancelThrow](
lookup: TraceContextLookup
) extends AutoConfigure.WithHint[F, ExemplarFilter](
"ExemplarFilter",
Expand Down Expand Up @@ -118,7 +118,7 @@ private[sdk] object ExemplarFilterAutoConfigure {
* @param traceContextLookup
* used by the exemplar reservoir to extract tracing information from the context
*/
def apply[F[_]: MonadThrow](
def apply[F[_]: MonadCancelThrow](
traceContextLookup: TraceContextLookup
): AutoConfigure[F, ExemplarFilter] =
new ExemplarFilterAutoConfigure[F](traceContextLookup)
Expand Down
Loading
Loading