Skip to content

Commit

Permalink
Merge pull request #648 from alexcardell/add-mapk
Browse files Browse the repository at this point in the history
Implement mapK syntax for EntryPoint and Span
  • Loading branch information
mpilquist authored Nov 19, 2022
2 parents 73bf08b + c2bcb52 commit bfa4e5c
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 3 deletions.
30 changes: 29 additions & 1 deletion modules/core/shared/src/main/scala/EntryPoint.scala
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

package natchez

import cats.~>
import cats.effect.MonadCancel
import cats.effect.Resource

/**
Expand All @@ -30,5 +32,31 @@ trait EntryPoint[F[_]] {
*/
def continueOrElseRoot(name: String, kernel: Kernel): Resource[F, Span[F]]


/**
* Converts this `EntryPoint[F]` to an `EntryPoint[G]` using an `F ~> G`.
*/
def mapK[G[_]](
f: F ~> G
)(implicit F: MonadCancel[F, _], G: MonadCancel[G, _]): EntryPoint[G] = {
val outer = this

def aux(r: Resource[F, Span[F]]): Resource[G, Span[G]] = r
.map(_.mapK(f))
.mapK(f)

new EntryPoint[G] {

override def root(name: String): Resource[G, Span[G]] = aux(outer.root(name))

override def continue(
name: String,
kernel: Kernel
): Resource[G, Span[G]] = aux(outer.continue(name, kernel))

override def continueOrElseRoot(
name: String,
kernel: Kernel
): Resource[G, Span[G]] = aux(outer.continueOrElseRoot(name, kernel))
}
}
}
30 changes: 28 additions & 2 deletions modules/core/shared/src/main/scala/Span.scala
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@

package natchez

import cats.{~>, Applicative}
import cats.syntax.applicative._
import cats.data.Kleisli
import cats.effect.MonadCancel
import cats.effect.Resource
import cats.effect.Resource.ExitCase
import cats.syntax.applicative._
import cats.{~>, Applicative}
import java.net.URI

/** An span that can be passed around and used to create child spans. */
Expand Down Expand Up @@ -44,6 +45,31 @@ trait Span[F[_]] {
*/
def traceUri: F[Option[URI]]

/** Converts this `Span[F]` to a `Span[G]` using a `F ~> G`. */
def mapK[G[_]](f: F ~> G)(
implicit F: MonadCancel[F, _],
G: MonadCancel[G, _]
): Span[G] = {
val outer = this
new Span[G] {
override def put(fields: (String, TraceValue)*): G[Unit] = f(
outer.put(fields: _*)
)

override def kernel: G[Kernel] = f(outer.kernel)

override def span(name: String): Resource[G, Span[G]] = outer
.span(name)
.map(_.mapK(f))
.mapK(f)

override def traceId: G[Option[String]] = f(outer.traceId)

override def spanId: G[Option[String]] = f(outer.spanId)

override def traceUri: G[Option[URI]] = f(outer.traceUri)
}
}
}

object Span {
Expand Down

0 comments on commit bfa4e5c

Please sign in to comment.