DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Scalable Support Request Analysis Using Embeddings, HDBSCAN, and Tiny LLMs
  • KV Cache Implementation Inside vLLM
  • When Retries Become a Denial-of-Wallet
  • The Bill You Didn't See Coming

Trending

  • Building AI-Powered Java Applications With Jakarta EE and LangChain4j
  • Alternative Structured Concurrency
  • Jakarta EE 12: Entering the Data Age of Enterprise Java
  • RAG Is Not Enough: Advanced Retrieval Architectures Using Vertex AI Search on GCP
  1. DZone
  2. Coding
  3. Languages
  4. Scala 3: Using Context Functions for Request Context

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.

By 
Ivan Kurchenko user avatar
Ivan Kurchenko
·
Jul. 07, 21 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
6.0K Views

Join the DZone community and get the full member experience.

Join For Free

Introduction

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 for Task and Future.
  • 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:

Scala
 
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:

Scala
 
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:

Scala
 
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:

Scala
 
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:

Scala
 
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:

Scala
 
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.
Scala (programming language) Requests

Opinions expressed by DZone contributors are their own.

Related

  • Scalable Support Request Analysis Using Embeddings, HDBSCAN, and Tiny LLMs
  • KV Cache Implementation Inside vLLM
  • When Retries Become a Denial-of-Wallet
  • The Bill You Didn't See Coming

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook