Skip to content

Commit

Permalink
Use cats UUID typeclass instead of our own (closes #187)
Browse files Browse the repository at this point in the history
  • Loading branch information
hejfelix committed Sep 19, 2023
1 parent 45f49b8 commit 29e505f
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package org.legogroup.woof.http4s

import cats.data.{Kleisli, NonEmptyList, OptionT}
import cats.effect.kernel.Sync
import cats.effect.std.UUIDGen
import cats.syntax.all.*
import cats.{Applicative, FlatMap, Monad}
import org.http4s.Header.Raw
Expand All @@ -16,23 +17,18 @@ object CorrelationIdMiddleware:

private val defaultTraceHeaderName: CIString = CIString("X-Trace-Id")

trait UUIDGen[F[_]]:
def gen: F[UUID]
given [F[_]: Sync]: UUIDGen[F] = new UUIDGen[F]:
def gen = Sync[F].delay(UUID.randomUUID)

private def getOrGenerate[F[_]: Applicative: UUIDGen](headerName: Option[CIString], request: Request[F]): F[String] =
val key = headerName.getOrElse(defaultTraceHeaderName)
request.headers
.get(key)
.map(_.head.value)
.fold(
summon[UUIDGen[F]].gen.map(_.toString),
summon[UUIDGen[F]].randomUUID.map(_.toString),
)(_.pure[F])

def middleware[F[_]: Logger: Monad: UUIDGen](headerName: Option[CIString] = None): HttpRoutes[F] => HttpRoutes[F] =
routes =>
Kleisli[([T] =>> OptionT[F, T]), Request[F], Response[F]] { request =>
Kleisli[[T] =>> OptionT[F, T], Request[F], Response[F]] { request =>
val key = headerName.getOrElse(defaultTraceHeaderName)
for
traceId <- OptionT.liftF(getOrGenerate(headerName, request))
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
package org.legogroup.woof.http4s

import cats.data.{Kleisli, OptionT}
import cats.effect.std.UUIDGen
import cats.effect.{Clock, IO}
import cats.syntax.all.*
import cats.{Applicative, Monad}
import munit.CatsEffectSuite
import org.http4s.{HttpRoutes, Request, Response}
import org.legogroup.woof.{*, given}
import org.legogroup.woof.http4s.CorrelationIdMiddleware.UUIDGen
import org.typelevel.ci.CIString

import java.time.ZoneId
Expand All @@ -24,9 +24,9 @@ class CorrelationIdMiddlewareSuite extends CatsEffectSuite:
given Printer = NoColorPrinter()
given Filter = Filter.everything

val testUuid = UUID.fromString("E20A27FE-5142-4E21-BA09-35BC6FB84591")
val testUuid: UUID = UUID.fromString("E20A27FE-5142-4E21-BA09-35BC6FB84591")
given UUIDGen[IO] with
def gen = testUuid.pure[IO]
def randomUUID: IO[UUID] = testUuid.pure[IO]

test("add trace id with middleware") {

Expand Down

0 comments on commit 29e505f

Please sign in to comment.