Skip to content

Instantly share code, notes, and snippets.

@mathieuancelin
Last active January 29, 2020 13:30
Show Gist options
  • Save mathieuancelin/c43bb0eabbdcb05b49296f9a5896c121 to your computer and use it in GitHub Desktop.
Save mathieuancelin/c43bb0eabbdcb05b49296f9a5896c121 to your computer and use it in GitHub Desktop.
package otoroshi.plugins.defer
import akka.http.scaladsl.util.FastFuture
import akka.stream.Materializer
import env.Env
import org.joda.time.DateTime
import otoroshi.script._
import play.api.libs.json._
import play.api.mvc.Result
import scala.concurrent.duration._
import scala.concurrent._
class DeferPlugin extends RequestTransformer {
override def transformRequestWithCtx(
ctx: TransformerRequestContext
)(implicit env: Env, ec: ExecutionContext, mat: Materializer): Future[Either[Result, HttpRequest]] = {
val config = ctx.configFor("DeferPlugin")
val defaultTimeout = (config \ "defaultDefer").asOpt[Long].getOrElse(0L)
val headerTimeout = ctx.request.headers.get("X-Defer").map(_.toLong)
val queryTimeout = ctx.request.getQueryString("defer").map(_.toLong)
val timeout = headerTimeout.orElse(queryTimeout).getOrElse(defaultTimeout)
val elapsed = System.currentTimeMillis() - ctx.attrs
.get(otoroshi.plugins.Keys.RequestTimestampKey)
.getOrElse(DateTime.now())
.getMillis
if ((timeout - elapsed) <= 0L) {
FastFuture.successful(Right(ctx.otoroshiRequest))
} else {
val promise = Promise[Either[Result, HttpRequest]]
env.otoroshiScheduler.scheduleOnce((timeout - elapsed).millis) {
promise.trySuccess(Right(ctx.otoroshiRequest))
}
promise.future
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment