8000 Do not mark cancelled subscription spans as errors by cquiroz · Pull Request #896 · gemini-hlsw/clue · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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: 4 additions & 2 deletions build.sbt
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
lazy val V = _root_.scalafix.sbt.BuildInfo

ThisBuild / tlBaseVersion := "0.62"
ThisBuild / tlBaseVersion := "0.63"
Global / onChangedBuildSource := ReloadOnSourceChanges

// The CI matrix covers Scala 3 only, which builds `sbt-clue` for sbt 2.x. Run the scripted tests
Expand Down Expand Up @@ -147,7 +147,9 @@ lazy val otel4s =
moduleName := "clue-otel4s",
libraryDependencies ++=
Settings.Libraries.Otel4s.value ++
Settings.Libraries.MUnit.value
Settings.Libraries.MUnit.value ++
Settings.Libraries.MUnitCatsEffect.value ++
Settings.Libraries.Otel4sTestkit.value
)
.dependsOn(core)

Expand Down
41 changes: 37 additions & 4 deletions otel4s/src/main/scala/clue/otel4s/Otel4sMiddleware.scala
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package clue.otel4s
import cats.Applicative
import cats.effect.Concurrent
import cats.effect.MonadCancelThrow
import cats.effect.Ref
import cats.effect.Resource
import cats.syntax.all.*
import clue.BuildInfo
Expand All @@ -29,6 +30,7 @@ import org.typelevel.otel4s.semconv.attributes.HttpAttributes
import org.typelevel.otel4s.semconv.experimental.attributes.GraphqlExperimentalAttributes
import org.typelevel.otel4s.trace.Span
import org.typelevel.otel4s.trace.SpanBuilder
import org.typelevel.otel4s.trace.SpanFinalizer
import org.typelevel.otel4s.trace.SpanKind
import org.typelevel.otel4s.trace.StatusCode
import org.typelevel.otel4s.trace.Tracer
Expand All @@ -42,6 +44,19 @@ object Otel4sMiddleware:
private def emptyAttrs[F[_]: Applicative]
: (GraphQLQuery, Option[JsonObject]) => F[List[Attribute[?]]] = (_, _) => List.empty.pure

private[otel4s] def errorMessage(e: Throwable): String =
Option(e.getMessage).getOrElse(e.toString)

private[otel4s] def exitCaseAttribute(exitCase: Resource.ExitCase): Attribute[String] =
val name = exitCase match
case Resource.ExitCase.Succeeded => "Succeeded"
case Resource.ExitCase.Errored(_) => "Errored"
case Resource.ExitCase.Canceled => "Canceled"
Attribute("clue.exitCase", name)

private[otel4s] def recordError[F[_]: Applicative](span: Span[F], e: Throwable): F[Unit] =
span.recordException(e) *> span.setStatus(StatusCode.Error, errorMessage(e))

// Supplied only here: the streaming clients extend `Otel4sFetchClient` but speak WebSocket, and
// must not describe their requests as HTTP.
private val httpAttributes: List[Attribute[?]] =
Expand Down Expand Up @@ -151,10 +166,12 @@ class Otel4sFetchClient[F[_]: {MonadCancelThrow, Tracer as T}, P: TraceHeaderInj
operation: String,
document: GraphQLQuery,
operationName: Option[String],
descriptor: Option[String]
descriptor: Option[String],
finalization: SpanFinalizer.Strategy = SpanFinalizer.Strategy.reportAbnormal
) = spanMod(
T.spanBuilder(Otel4sMiddleware.spanName(operation, document, descriptor))
.withSpanKind(SpanKind.Client)
.withFinalizationStrategy(finalization)
.addAttributes(Otel4sMiddleware.commonAttributes(document, operationName, descriptor)*)
)

Expand Down Expand Up @@ -221,8 +238,24 @@ class Otel4sStreamingClient[F[_]: {Concurrent, Tracer as T}, S](
descriptor: Option[String]
): Resource[F, fs2.Stream[F, GraphQLResponse[D]]] =
for
res <- traceSpan("subscribe", document, operationName, descriptor).build.resource
res <- traceSpan(
"subscribe",
document,
operationName,
descriptor,
SpanFinalizer.Strategy.empty
).build.resource
Comment thread
cquiroz marked this conversation as resolved.
Resolved
span = res.span
streamError <- Resource.eval(Ref.of[F, Option[Throwable]](None))
// Cancelling is how a subscription normally ends, so only real failures mark the span as
// errored. A stream error the consumer rethrows was already recorded by the stream.
_ <- Resource.onFinalizeCase:
case Resource.ExitCase.Errored(e) =>
streamError.get.flatMap: recorded =>
Otel4sMiddleware.recordError(span, e).unlessA(recorded.exists(_ eq e))
case exitCase @ Resource.ExitCase.Canceled =>
span.addAttribute(Otel4sMiddleware.exitCaseAttribute(exitCase))
case Resource.ExitCase.Succeeded => Applicative[F].unit
_ <- Resource.eval:
additionalAttributesF(document, variables).flatMap: attrs =>
span.addAttributes(attrs*)
Expand All @@ -243,10 +276,10 @@ class Otel4sStreamingClient[F[_]: {Concurrent, Tracer as T}, S](
descriptor
)
yield stream.onFinalizeCase: exitCase =>
span.addAttribute(Attribute("clue.exitCase", exitCase.toOutcome.toString)) *>
span.addAttribute(Otel4sMiddleware.exitCaseAttribute(exitCase)) *>
(exitCase match
case Resource.ExitCase.Errored(e) =>
span.setStatus(StatusCode.Error, Option(e.getMessage).getOrElse(e.toString))
streamError.set(Some(e)) *> Otel4sMiddleware.recordError(span, e)
case _ => Applicative[F].unit)

class Otel4sPersistentStreamingClient[F[_]: Tracer: Concurrent, S, CP, CE](
Expand Down
110 changes: 110 additions & 0 deletions otel4s/src/test/scala/clue/otel4s/Otel4sSubscribeSpanSpec.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
// Copyright (c) 2016-2026 Association of Universities for Research in Astronomy, Inc. (AURA)
// For license information see LICENSE or https://opensource.org/licenses/BSD-3-Clause

package clue.otel4s

import cats.effect.Deferred
import cats.effect.IO
import cats.effect.Resource
import clue.StreamingClient
import clue.model.GraphQLQuery
import clue.model.GraphQLResponse
import fs2.Stream
import io.circe.Decoder
import io.circe.Json
import io.circe.JsonObject
import munit.CatsEffectSuite
import org.typelevel.otel4s.sdk.testkit.trace.TracesTestkit
import org.typelevel.otel4s.sdk.trace.data.SpanData
import org.typelevel.otel4s.sdk.trace.data.StatusData
import org.typelevel.otel4s.trace.Tracer

class Otel4sSubscribeSpanSpec extends CatsEffectSuite:

private type Subscription = Resource[IO, Stream[IO, GraphQLResponse[Json]]]

private val doc = GraphQLQuery("subscription Edits { edits { id } }")

private val boom = new RuntimeException("boom")

private def stubStream(events: Stream[IO, Nothing]): StreamingClient[IO, Unit] =
new StreamingClient[IO, Unit]:
protected[clue] def requestInternal[D: Decoder](
document: GraphQLQuery,
operationName: Option[String],
variables: Option[JsonObject],
extensions: Option[JsonObject],
modParams: Unit => Unit,
descriptor: Option[String]
): IO[GraphQLResponse[D]] =
IO.never
protected[clue] def subscribeInternal[D: Decoder](
document: GraphQLQuery,
operationName: Option[String],
variables: Option[JsonObject],
extensions: Option[JsonObject],
descriptor: Option[String]
): Resource[IO, Stream[IO, GraphQLResponse[D]]] =
Resource.pure(events)

private def subscribeSpan(
events: Stream[IO, Nothing],
run: Subscription => IO[Unit]
): IO[SpanData] =
TracesTestkit
.inMemory[IO]()
.use: testkit =>
for
tracer <- testkit.tracerProvider.get("test")
client =
given Tracer[IO] = tracer
Otel4sStreamingClient[IO, Unit](stubStream(events), identity, (_, _) => IO.pure(Nil))
_ <- run(client.subscribeInternal[Json](doc, None, None, None, None))
spans <- testkit.finishedSpans
yield spans
.map:
case List(span) => span
case other => fail(s"expected one span, got [$other]")

private def exitCase(span: SpanData): Option[String] =
span.attributes.elements.get[String]("clue.exitCase").map(_.value)

private def exceptionEvents(span: SpanData): Int =
span.events.elements.count(_.name == "exception")

test("a subscription cancelled before the stream is pulled is recorded but not an error"):
val cancel: Subscription => IO[Unit] = sub =>
Deferred[IO, Unit].flatMap: started =>
sub
.use(_ => started.complete(()) >> IO.never)
.start
.flatMap: fiber =>
started.get >> fiber.cancel
subscribeSpan(Stream.never[IO], cancel).map: span =>
assertEquals(span.status, StatusData.Unset)
assertEquals(exitCase(span), Some("Canceled"))

test("a subscription whose stream ends normally records a plain Succeeded exit case"):
subscribeSpan(Stream.empty, _.use(_.compile.drain)).map: span =>
assertEquals(span.status, StatusData.Unset)
assertEquals(exitCase(span), Some("Succeeded"))

test("a consumer failure marks the span as an error with the failure message"):
subscribeSpan(Stream.never[IO], _.use(_ => IO.raiseError(boom)).voidError).map: span =>
assertEquals(span.status, StatusData.Error(Some("boom")))
assertEquals(exceptionEvents(span), 1)

test("a stream failure marks the span as an error with the failure message"):
subscribeSpan(Stream.raiseError[IO](boom), _.use(_.compile.drain).voidError).map: span =>
assertEquals(span.status, StatusData.Error(Some("boom")))
assertEquals(exitCase(span), Some("Errored"))
assertEquals(exceptionEvents(span), 1)

test("a stream failure the consumer recovers from still records the exception"):
val recover: Subscription => IO[Unit] =
_.use(_.handleErrorWith(_ => Stream.empty).compile.drain)
subscribeSpan(Stream.raiseError[IO](boom), recover).map: span =>
assertEquals(span.status, StatusData.Error(Some("boom")))
assertEquals(exceptionEvents(span), 1)

end Otel4sSubscribeSpanSpec
3 changes: 2 additions & 1 deletion project/Settings.scala
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ object Settings {
val munit = "1.3.6"
val munitCatsEffect = "2.2.1"
val otel4s = "1.2.0"
val otel4sSdk = "0.19.5"
val http4sOtel4sMiddleware = "0.20.0"
val scalaFix = scalafix.sbt.BuildInfo.scalafixVersion
val scalaJsDom = "2.8.1"
Expand Down Expand Up @@ -151,7 +152,7 @@ object Settings {

val Otel4sTestkit = Def.setting(
Seq(
"org.typelevel" %%% "otel4s-sdk-testkit" % otel4s % "test"
"org.typelevel" %%% "otel4s-sdk-trace-testkit" % otel4sSdk % "test"
)
)

Expand Down
0