0

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.

Saksham
  • 127
  • 3
  • 9

2 Answers2

1

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
Ramón J Romero y Vigil
  • 17,373
  • 7
  • 77
  • 125