scalaakka-httptapir

Calculating Tapir output size


I am implementing custom metrics for Tapir + Akka http. Based on Tapir observability I was able to get endpoint method, status code and time. However, I'm seeking to get output masssage size. I understand that it won't be easy / possible for certain scenarios. However, my endpoints return just simple strings encoded by Circe. Any idea how to achieve that from EndpointOutput class or the other way? To add some context that's what I get when I log EndpointOutput from EndpointMetric class:

Pair(
    Empty(sttp.tapir.Codec$$anon$4@6b7de12,Info(None,List(),false,AttributeMap(Map()))),
    Body(StringBody(UTF-8),sttp.tapir.Codec$$anon$8@4e6dda7e,Info(None,List(),false,AttributeMap(Map()))),sttp.tapir.internal.package$$$Lambda$13005/0x00000001015c45a0@3204b602,sttp.tapir.internal.package$$$Lambda$13006/0x00000001015c4b50@6441d5a1)
)

Solution

  • EndpointOuput is a description of the shape of the output - the metadata - it doesn't include any of the values that are actually produced when invoking the endpoint. You can get the results that you need in another way, though.

    The EndpointMetric class contains the onResponseBody callback:

    onResponseBody: Option[(AnyEndpoint, ServerResponse[_]) => F[Unit]] = None,
    

    While the AnyEndpoint is the shape, the SeverResponse is the actual response produced by the endpoint. It contains the status code, headers, and the body, in case of the Akka interpreter the body type parameter is an Either[Flow[Message, Message, Any], ResponseEntity]; in ServerResponse this is additionally wrapped in an Option.

    If you have a non-streaming endpoint, you'll get the right-hand side, that is a ResponseEntity, from which you can calculate the response size (if available).