Scala 3: Using Context Functions for Request Context
Using Scala 3 new feature of contextual function on example of `X-Request-ID` header with http4s and log4cats.
Join the DZone community and get the full member experience.
Join For FreeIntroduction
During studying Scala 3 Context Functions first use case I thought about it, was X-Request-ID
, X-Correlation-ID
or similar headers identifying request context. So in this post, I wanted to show Context Function
usage on example of implementing wiring request context to logs in a simple application with http4s
and log4cats
.
Alternative Approaches
But first, let's consider alternative approaches of solving this problem:
- Java's
TheadLocal
possible for context propagation only in case of synchronous invocations; - Monix has
Local
implementation, which can deal with context propagation forTask
andFuture
. - ZIO has
FiberRef
for context propagation in terms of fiber - Cats Effect IO's recently got Fiber Locals similar to previous solutions
Context fFunction
Dotty's Context Functions on another hand, allows being independent of the underlying effect library because provides the capability to pass request context as a hidden implicit parameter.
Request Context Propagation
Fortunately, http4s provides middleware that does half of the job for us: create random UUID and add it as X-Request-ID
for into response. We need to retrieve it from Request[F]
attributes and pass it through the application.
First, let's define a simple model of our request context:
type Contextual[T] = RequestContext ?=> T
final case class RequestContext(requestId: String)
Since we need to use RequestContext
in logging, we need a special logger to do this job:
import cats.effect.*
import org.typelevel.log4cats.Logger
/**
* Wrapper around plain `Logger` in order to force user to use contextual logging, which is why made as not an `extention`
*/
class ContextualLogger[F[_]](loggger: Logger[F]):
private def contextual(message: => String): Contextual[String] = s"${summon[RequestContext].requestId} - $message"
def error(message: => String): Contextual[F[Unit]] = loggger.error(contextual(message))
def warn(message: => String): Contextual[F[Unit]] = loggger.warn(contextual(message))
def info(message: => String): Contextual[F[Unit]] = loggger.info(contextual(message))
def debug(message: => String): Contextual[F[Unit]] = loggger.debug(contextual(message))
def trace(message: => String): Contextual[F[Unit]] = loggger.trace(contextual(message))
def error(t: Throwable)(message: => String): Contextual[F[Unit]] = loggger.error(t)(contextual(message))
def warn(t: Throwable)(message: => String): Contextual[F[Unit]] = loggger.warn(t)(contextual(message))
def info(t: Throwable)(message: => String): Contextual[F[Unit]] = loggger.info(t)(contextual(message))
def debug(t: Throwable)(message: => String): Contextual[F[Unit]] = loggger.debug(t)(contextual(message))
def trace(t: Throwable)(message: => String): Contextual[F[Unit]] = loggger.trace(t)(contextual(message))
For sake of example, let's define simple service which contains some dummy business level login of handling abstract request:
import org.typelevel.log4cats.slf4j.Slf4jLogger
import cats.effect.*
import cats.implicits.*
class ApplicationService[F[_]](using F: Sync[F]):
//Note: we should not use plain `org.typelevel.log4cats.Logger` anymore
val logger: ContextualLogger[F] = ContextualLogger[F](Slf4jLogger.getLogger[F])
def handleRequest(name: String): Contextual[F[String]] =
logger.info(s"Received request to handle: $name") *> F.pure("OK")
In order to isolate the logic of retrieving and converting it to an implicit parameter let's define the next helper function:
import cats.effect.Sync
import org.http4s.Request
import org.http4s.Response
import org.http4s.server.middleware.RequestId
import java.util.UUID
object HttpRequestContextual:
def contextual[F[_]: Sync](request: Request[F])(f: Contextual[F[Response[F]]]): F[Response[F]] =
val context: RequestContext = request.attributes.lookup(RequestId.requestIdAttrKey).
fold(RequestContext(UUID.randomUUID.toString))(RequestContext.apply)
f(using context)
And use it in HTTP routes service:
import cats.effect.Sync
import cats.implicits._
import org.http4s.HttpRoutes
import org.http4s.dsl.Http4sDsl
import org.http4s.implicits.*
import org.http4s.blaze.server.*
import HttpRequestContextual.*
class ApplicationRotes[F[_]: Sync](service: ApplicationService[F])(implicit dsl: Http4sDsl[F]):
import dsl.{*, given}
val applicationRoutes = HttpRoutes.of[F] {
case request@GET -> Root / "contextual" / name =>
contextual(request) {
//further invocations goes with implicit RequestContext
for {
content <- service.handleRequest(name)
response <- Ok(content)
} yield response
}
}
Putting all pieces together in the final application:
import cats.effect.IO.Local
import cats.effect.*
import org.http4s.HttpRoutes
import org.http4s.server.middleware.{*, given}
import org.http4s.dsl.*
import org.http4s.implicits.{*, given}
import org.http4s.blaze.server.{*, given}
import scala.concurrent.ExecutionContext.global
object RequestIdApp extends IOApp:
def run(args: List[String]): IO[ExitCode] =
given Http4sDsl[IO] = org.http4s.dsl.io
val applicationRotes = ApplicationRotes[IO](ApplicationService[IO]())
val routes = RequestId(applicationRotes.applicationRoutes.orNotFound)
BlazeServerBuilder[IO](global)
.bindHttp(8080, "localhost")
.withHttpApp(routes)
.serve
.compile
.drain
.as(ExitCode.Success)
So let's run our application and test it:
curl -X GET http://localhost:8080/contextual/test -v
Note: Unnecessary use of -X or --request, GET is already inferred.
* Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 8080 (#0)
> GET /contextual/test HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.64.1
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Type: text/plain; charset=UTF-8
< X-Request-ID: f6e8d59e-ddd3-438c-88f6-1136d6838234
< Date: Sun, 30 May 2021 18:21:10 GMT
< Content-Length: 2
<
* Connection #0 to host localhost left intact
OK* Closing connection 0
So you can see X-Request-ID
is our request id in response with value: f6e8d59e-ddd3-438c-88f6-1136d6838234
. And logline in application logs with same request-id (rest of logs omitted):
...
21:21:09.972 [io-compute-7] INFO <empty>.ApplicationService - f6e8d59e-ddd3-438c-88f6-1136d6838234 - Received request to handle: test
....
Pros and Cons
From my perspective using context function over other approaches of context propagations (e.g. fiber locals) has next:
Pros:
- It is an invasive technic: context function type should be used across the whole project codebase, which might be harder to refactor, maintain and compose.
Cons:
- Contextual function prooves on type-level that certain context was provided.
Opinions expressed by DZone contributors are their own.
Comments