Saksham
Saksham

Reputation: 137

How to introduce a non blocking delay in akka-http using Flows based on the request parameters

I am starting a server and handling it like this using akka stream

connection.handleWith(handleRequest())

where handleRequest():Flow[HttpRequest,HttpRespnse,_] I need to create a delay in sending of response back to client based on the query parameter. I can extract the query parameter, I can't figure out, how can i create the delay using this.

Upvotes: 0

Views: 572

Answers (2)

Extending @KnowsNotMuch answer, assuming you have some criteria with which to decide whether or not to delay a request:

val shouldDelayRequest : (HttpRequest) => Boolean = ???

You can use this decider to create a DelayStrategy:

import scala.concurrent.duration.{FiniteDuration, TimeUnit}

val noDelay : FiniteDuration = FiniteDuration(0L, TimeUnit.SECONDS)

val createDelayStrategy : (FiniteDuration) => () => DelayStrategy[HttpRequest] = 
  (finiteDelay) => () => new DelayStrategy[HttpRequest] {
    override def nextDelay(elem: HttpRequest) : FiniteDuration = 
      if(shouldDelayRequest(elem))
        finiteDelay
      else
        noDelay
  }

You can use this function to create a DelayFlow:

import akka.stream.contrib.DelayFlow

val delay = FiniteDuration(42L, TimeUnit.Seconds)

val delayFlow : DelayFlow[HttpRequest] = DelayFlow(createDelayStrategy(delay))

This delayFlow can then be connected to whatever functionality you have to process a request into a response:

val requestToResponseFlow : Flow[HttpRequest, HttpResponse, _] = ???

val possibleDelayedResponseFlow  : Flow[HttpRequest, HttpResponse, _] = 
  delayFlow via requestToResponseFlow

Upvotes: 1

Related Questions