Field Notes

Play WSClient, lesson 6: upstream config and a logging filter

Play WSClient, lesson 6: upstream config and a logging filter

At the end of lesson 5, my clients worked, but each one still had its base URL hard-coded as a string, a timeout as a default parameter, no authentication and no logging. Pointing them at a test environment meant editing code, and finding out why a page was slow meant guessing. This lesson moves those settings into application.conf and puts everything that applies to every call in one place.

Stack as before: Play 3.0.12, Scala 2.13, Guice, play-ahc-ws. The code is commit 823b2da in zakariahere/play-wsclient-lessons.

Upstreams in config

Each upstream gets a block under upstreams with its base URL, its timeout and, if it needs one, an API key:

upstreams {
  jsonplaceholder {
    base-url = "https://jsonplaceholder.typicode.com"
    timeout  = 5 seconds
  }
  httpbin {
    base-url = "https://httpbin.org"
    timeout  = 10 seconds
    api-key  = "dev-key-123"
    api-key  = ${?HTTPBIN_API_KEY}
  }
}

The two api-key lines are the HOCON pattern I use for secrets. The second line is an optional substitution: if the environment variable HTTPBIN_API_KEY exists, it overrides the line above, and otherwise the dev default stays. The repository only contains a dev value, and the real key comes from the environment in production. 5 seconds is a real duration that Play parses into a FiniteDuration, so nobody has to guess whether a number means milliseconds or seconds.

Typed, and loaded once

Left: the upstreams block from application.conf. Right: the UpstreamConfig case class with name, baseUrl, timeout and an optional apiKey, loaded with config.get for required keys and getOptional for the API key.
Only UpstreamConfig.load reads config keys. Everything else uses the case class.
final case class UpstreamConfig(name: String, baseUrl: String, timeout: FiniteDuration, apiKey: Option[String]) {
  def maskedKey: Option[String] = apiKey.map(k => k.take(3) + "***")
}

object UpstreamConfig {
  def load(config: Configuration, name: String): UpstreamConfig = {
    val c = config.get[Configuration](s"upstreams.$name")
    UpstreamConfig(
      name    = name,
      baseUrl = c.get[String]("base-url"),
      timeout = c.get[FiniteDuration]("timeout"),
      apiKey  = c.getOptional[String]("api-key")
    )
  }
}

The difference between get and getOptional is intentional. get throws when the key is missing, which is what I want for a base URL. The client is a singleton that loads its config when it is created, so a typo in a key name fails with a message naming that key, not on the first customer request. The API key is really optional, since JSONPlaceholder has none.

The clients inject Configuration and pass their slice to the base class. Their methods now only contain paths:

@Singleton
class JsonPlaceholderClient @Inject()(ws: WSClient, config: Configuration)(implicit ec: ExecutionContext)
  extends JsonHttp(ws, UpstreamConfig.load(config, "jsonplaceholder")) {

  def todo(id: Int): Upstream[Todo] = getJson[Todo](s"/todos/$id")
}

With compile-time DI, the wiring is new JsonPlaceholderClient(wsClient, configuration)(executionContext), and BuiltInComponents already provides configuration.

Global WSClient settings

Some settings belong to every call, whatever the upstream. Play reads them from play.ws:

play.ws {
  useragent = "playwscli/1.0 (lesson 6)"
  timeout.connection = 3 seconds
  timeout.idle       = 30 seconds
  timeout.request    = 30 seconds
}

connection covers the TCP and TLS connect, idle covers silence on an open connection, and request covers the whole call. A withRequestTimeout on a single request overrides request. I treat the global value as a safety net and the per-upstream timeout as the real contract.

One request builder

The base class now builds every request in one method, so the URL, timeout, filter and API key cannot be forgotten on one call and remembered on another:

abstract class JsonHttp(ws: WSClient, val upstream: UpstreamConfig)(implicit ec: ExecutionContext) {

  private val logging = new LoggingFilter(upstream.name)

  protected def request(path: String): WSRequest = {
    val base = ws.url(upstream.baseUrl + path)
      .withRequestTimeout(upstream.timeout)
      .withRequestFilter(logging)

    upstream.apiKey.fold(base)(key => base.addHttpHeaders("X-Api-Key" -> key))
  }
}

getJson calls request(path) and keeps the status and exception handling from lesson 4 unchanged.

A WSRequestFilter for correlation ids and timing

A WSRequestFilter is a function from one executor to another. It receives the request, can change it, calls next to really send it, and can observe the future that comes back. It is the same idea as a servlet filter or a Spring ClientHttpRequestInterceptor, and several of them chain around the call.

class LoggingFilter(upstream: String)(implicit ec: ExecutionContext) extends WSRequestFilter with LazyLogging {

  override def apply(next: WSRequestExecutor): WSRequestExecutor = WSRequestExecutor { request =>
    val correlationId = UUID.randomUUID().toString.take(8)
    val start = System.nanoTime()

    def tookMs = (System.nanoTime() - start) / 1000000

    next(request.addHttpHeaders("X-Correlation-Id" -> correlationId)).andThen {
      case Success(r) =>
        logger.info(s"[$correlationId] $upstream ${request.method} ${request.url} -> ${r.status} in ${tookMs}ms")
      case Failure(e) =>
        logger.warn(s"[$correlationId] $upstream ${request.method} ${request.url} -> FAILED ${e.getClass.getSimpleName} in ${tookMs}ms")
    }
  }
}

Three details matter here. andThen runs a side effect and returns the original future, so the filter cannot change what the caller receives, and a failed future stays failed. tookMs is a def, because a val would be computed immediately and always show about 0 ms. And the filter sees failures such as timeouts or refused connections as failed futures, before getJson's recover turns them into a Left. The filter sits closer to the network than my error model does. LazyLogging from scala-logging names the logger after the class, so the lines appear under clients.LoggingFilter.

Checking what the upstream received

httpbin's /headers endpoint returns the headers it received, so I added two small endpoints: /cfg/settings returns the loaded config with the key masked, and /cfg/headers calls httpbin and returns its answer.

GET /cfg/headers: httpbin received User-Agent playwscli/1.0 (lesson 6) from the global play.ws setting, X-Api-Key dev-key-123 from the httpbin upstream config, and X-Correlation-Id 10ca6359 from the LoggingFilter.
One request shows all three layers: global settings, per-upstream settings and the filter.

For /cfg/settings, JSONPlaceholder's apiKey came back as null. play-json writes a None inside Json.obj as JSON null and does not drop the field, which is fine for a debug endpoint but worth knowing for a public API.

I did not test the environment override, because it needs an sbt restart with HTTPBIN_API_KEY set. I expect /cfg/settings to show the first three characters of the new key, but I have not run it yet.

What the log showed

The log turned out to be more useful than I expected. After calling the profile endpoint from lesson 5 for user 1 and user 99, it contained this:

Log lines: for user 1, todos, posts and users calls each returned 200 in 79 to 98 ms. For user 99, todos and posts returned 200 in 22 and 23 ms, and users/99 returned 404 in 28 ms.
Both observations from lesson 5 are now visible without a debugger.

For user 1, the three calls took 79 to 98 ms each and were logged in the same second, so they ran in parallel as intended. For user 99, /users/99 returned a 404, and the todos and posts calls still ran. That is the trade-off I described in lesson 5: creating the futures before the EitherT comprehension saves latency, and costs calls whose results are thrown away. In lesson 5 it was an argument. Here it is three log lines.

The log also showed a gap. /errors/todo/1 from lesson 4 worked but was not logged, because that controller still calls ws directly instead of going through a client. A filter only covers the calls that go through the code that attaches it. That is a practical reason to finish moving the old controllers onto the client layer.

What I take from lesson 6

  • Base URLs, timeouts and keys go in application.conf, with ${?ENV_VAR} for values that differ in production.
  • Load config into a case class once, and use get for required keys so a mistake fails at startup.
  • play.ws holds the global defaults, and a per-request timeout overrides the request timeout.
  • Build every request in one method, so nothing is attached to one call and forgotten on another.
  • A WSRequestFilter with andThen can add headers and log without changing results. It only covers calls that go through it.

Next: testing. Fake clients for controller tests, an embedded Play server to test the real client, and every UpstreamError case covered without a network call.

Keep reading