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 19 commits
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
26 changes: 23 additions & 3 deletions build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ ThisBuild / mergifyPrRules ++= Seq(
)

val CatsVersion = "2.11.0"
val CatsEffectVersion = "3.5.7"
val CatsEffectVersion = "3.6-28f8f29"
val CatsMtlVersion = "1.4.0"
val FS2Version = "3.11.0"
val MUnitVersion = "1.0.0"
Expand Down Expand Up @@ -153,7 +153,7 @@ lazy val root = tlCrossRootProject
`oteljava-trace`,
`oteljava-trace-testkit`,
`oteljava-testkit`,
oteljava,
`oteljava-context-storage`,
`semconv-stable`,
`semconv-experimental`,
`semconv-metrics-stable`,
Expand Down Expand Up @@ -703,14 +703,32 @@ lazy val `oteljava-testkit` = project
)
.settings(scalafixSettings)

lazy val `oteljava-context-storage` = project
.in(file("oteljava/context-storage"))
.dependsOn(`oteljava-common`)
.settings(munitDependencies)
.settings(
name := "otel4s-oteljava-context-storage",
libraryDependencies ++= Seq(
"org.typelevel" %%% "cats-effect-testkit" % CatsEffectVersion % Test,
),
Test / javaOptions ++= Seq(
"-Dotel.java.global-autoconfigure.enabled=true",
"-Dcats.effect.ioLocalPropagation=true",
),
Test / fork := true,
)
.settings(scalafixSettings)

lazy val oteljava = project
.in(file("oteljava/all"))
.dependsOn(
core.jvm,
`oteljava-metrics` % "compile->compile;test->test",
`oteljava-metrics-testkit` % Test,
`oteljava-trace` % "compile->compile;test->test",
`oteljava-trace-testkit` % Test
`oteljava-trace-testkit` % Test,
`oteljava-context-storage`
iRevive marked this conversation as resolved.
Show resolved Hide resolved
)
.settings(
name := "otel4s-oteljava",
Expand Down Expand Up @@ -850,6 +868,7 @@ lazy val examples = project
javaAgents += "io.opentelemetry.javaagent" % "opentelemetry-javaagent" % OpenTelemetryInstrumentationVersion % Runtime,
run / fork := true,
javaOptions += "-Dotel.java.global-autoconfigure.enabled=true",
javaOptions += "-Dcats.effect.ioLocalPropagation=true",
envVars ++= Map(
"OTEL_PROPAGATORS" -> "b3multi",
"OTEL_SERVICE_NAME" -> "Trace Example"
Expand Down Expand Up @@ -954,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
39 changes: 39 additions & 0 deletions examples/src/main/scala/ContextStorageExample.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/*
* 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.
*/

import cats.effect.IO
import cats.effect.IOApp
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

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}")
}
}
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ object Context {
Wrapped(context)

/** The root [[`Context`]], from which all other contexts are derived. */
val root: Context = wrap(JContext.root())
lazy val root: Context = wrap(JContext.root())

implicit object Contextual extends context.Contextual[Context] {
type Key[A] = Context.Key[A]
Expand Down
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
@@ -0,0 +1,44 @@
/*
* 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.SyncIO
import cats.syntax.all._
import io.opentelemetry.context.ContextStorage
import io.opentelemetry.context.ContextStorageProvider
import org.typelevel.otel4s.oteljava.context.Context

object IOLocalContextStorageProvider {
private lazy val localContext: IOLocal[Context] =
IOLocal[Context](Context.root)
.syncStep(100)
.flatMap(
_.leftMap(_ =>
new Error(
"Failed to initialize the local context of the IOLocalContextStorageProvider."
)
).liftTo[SyncIO]
)
.unsafeRunSync()
}

/** SPI implementation for [[`IOLocalContextStorage`]]. */
class IOLocalContextStorageProvider extends ContextStorageProvider {
def get(): ContextStorage =
new IOLocalContextStorage(() => IOLocalContextStorageProvider.localContext)
}
Loading
Loading