AskTimeoutException: Ask timed out on after [5000 ms] - rest

I am trying to build a money transaction system using akka-http for REST API and akka actors for AccountActors.
post {
(path("accounts" / "move-money") & entity(as[MoveMoneyRequest])) { moveMoneyRequest =>
complete(
(bankActor ? moveMoneyRequest).map(x => MoveMoneyResponse("Money Transfer Successful!"))
)
}
}
The bankActor is created inside a main app
val bankActor = mainActorSystem.actorOf(Props(classOf[BankingActor], accountService), name = "bankActor")
Inside BankActor, we have:
def receive: Receive = LoggingReceive {
case req: MoveMoneyRequest =>
val fromAcc = createAccountActor(Some(req.fromAccount))
val toAcc = createAccountActor(Some(req.toAccount))
fromAcc ? DebitAccount(req.tranferAmount)
become(awaitFrom(fromAcc, toAcc, req.tranferAmount, sender))
}
private def createAccountActor(accountNum: Option[String]): ActorRef = {
actorOf(Props(classOf[AccountActor], accountNum, accountService))
}
Question: Now, for the first API call everytime, it's successful but seems the actor dies/shuts down and the ? (ask) does not find the actor as the message does not reach the receive method. Do I need to make the ask call different?

The correct directive to deal with futures is onComplete, for example
post {
(path("accounts" / "move-money") & entity(as[MoveMoneyRequest])) { moveMoneyRequest =>
val fut = (bankActor ? moveMoneyRequest).map(x => MoveMoneyResponse("Money Transfer Successful!"))
onComplete(fut){
case util.Success(_) => complete(StatusCodes.OK)
case util.Failure(ex) => complete(StatusCodes.InternalServerError)
}
}
}
More details in the docs.

Related

how to handle long running request in akka http route

i am using akka http one of my routes is interacting with an external service via akka http client side api and the httpRequest is continuously running i am unable to make it work
here is my use case -> i am interacting with a janus server and doing a long poll get request as soon as the server responded back with an 'keepAlive' or an "event" i am requesting again and so on the server keeps on responding
all of this is happening inside an actor and i have an akka htttp route which is intiailising the first request
here is my code
final case class CreateLongPollRequest(sessionId:BigInt)
class LongPollRequestActor (config: Config) extends Actor {
def receive = {
case CreateLongPollRequest(sessionId) =>
senderRef = Some(sender())
val uri: String = "localhost:8080/" + sessionId
val request = HttpRequest(HttpMethods.GET, uri)
val responseFuture = Http(context.system).singleRequest(request)
responseFuture
.onComplete {
case Success(res)
Unmarshal(res.entity.toStrict(40 seconds)).value.map { result =>
val responseStr = result.data.utf8String
log.info("Actor LongPollRequestActor: long poll responseStr {}",responseStr)
senderRef match {
case Some(ref) =>
ref ! responseStr
case None => log.info("Actor LongPollRequestActor: sender ref is null")
}
}
case Failure(e) =>log.error(e)
}
}
}
final case class JanusLongPollRequest(sessionId: BigInt)
class JanusManagerActor(childMaker: List[ActorRefFactory => ActorRef]) extends Actor {
var senderRef: Option[akka.actor.ActorRef] = None
val longPollRequestActor = childMaker(1)(context)
def receive: PartialFunction[Any, Unit] = {
case JanusLongPollRequest(sessionId)=>
senderRef = Some(sender)
keepAlive(sessionId,senderRef)
}
def keepAlive(sessionId:BigInt,sender__Ref: Option[ActorRef]):Unit= {
val senderRef = sender__Ref
val future = ask(longPollRequestActor, CreateLongPollRequest(sessionId)).mapTo[String] //.pipeTo(sender)
if (janus.equals("keepalive")) {
val janusRequestResponse = Future {
JanusSessionRequestResponse(janus = janus)
}
senderRef match {
case Some(sender_ref) =>
janusRequestResponse.pipeTo(sender_ref)
}
keepAlive(sessionId,senderRef)
}
else if (janus.equals("event")) {
//some fetching of values from server
val janusLongPollRequestResponse = Future {
JanusLongPollRequestResponse(janus = janus,sender=sender, transaction=transaction,pluginData=Some(pluginData))
}
senderRef match {
case Some(sender_ref) =>
janusLongPollRequestResponse.pipeTo(sender_ref)
}
keepAlive(sessionId,senderRef)
}
def createLongPollRequest: server.Route =
path("create-long-poll-request") {
post {
entity(as[JsValue]) {
json =>
val sessionID = json.asJsObject.fields("sessionID").convertTo[String]
val future = ask(janusManagerActor, JanusLongPollRequest(sessionID)).mapTo[JanusSessionRequestResponse]
onComplete(future) {
case Success(sessionDetails) =>
log.info("janus long poll request created")
val jsonResponse = JsObject("longpollDetails" -> sessionDetails.toJson)
complete(OK, routeResponseMessage.getResponse(StatusCodes.OK.intValue, ServerMessages.JANUS_SESSION_CREATED, jsonResponse))
case Failure(ex) =>
failWith(ex)
}
}
}
now the above route createLongPollRequest worked fine for the first time I can see the response and for the next attempts i am getting a dead letter as follows
[INFO] [akkaDeadLetter][07/30/2021 12:13:53.587] [demo-Janus-ActorSystem-akka.actor.default-dispatcher-6] [akka://demo-Janus-ActorSystem/deadLetters] Message [com.ifkaar.lufz.janus.models.janus.JanusSessionRequestResponse] from Actor[akka://demo-Janus-ActorSystem/user/ActorManager/ManagerActor#-721316187] to Actor[akka://demo-Janus-ActorSystem/deadLetters] was not delivered. [4] dead letters encountered. If this is not an expected behavior then Actor[akka://demo-Janus-ActorSystem/deadLetters] may have terminated unexpectedly. This logging can be turned off or adjusted with configuration settings 'akka.log-dead-letters' and 'akka.log-dead-letters-during-shutdown'.
probably this is causing the issue after the first iteration
responseFuture.pipeTo(sender()
IS there a way where i can get a response in my akkahttp route when ever my backend server responds?
The Actor should only reply once to the CreateLongPollRequest and it should only do this when it has valid data. If the poll fails the Actor should just issue another poll request.
It is difficult to give more help without the details of the Actor.

How to ask for data from another actor which is not ready yet?

I have an actorA that takes data from dataActor, and responds data to requestActors:
class A extends Actor {
var data = Option.empty[Int]
val requestors = mutable.Set[ActorRef]
def receive = {
case data: Int =>
this.data = Some(data)
requestors.foreach {_ ! data}
case Request =>
if (data.isEmpty) {
requestors.add(sender)
//What should I send back to sender here?
} else {
sender ! data.get
}
}
}
In the sender actor, I use the ask pattern:
(actorA ? Request()).map {
//if the data is not ready here, how can I wait for data?
}
In the data provider actor, it sends the data to the actorA:
dataActor ! 100
The problem is the data may not be ready when the requestor is asking for it, so the Future from the ask may fail. I need to send the sender something to promise there is data, but apparently Akka does not seem to have promise AKAIK.
How to implement it here?
A couple of possibilities.
First, you could return the actual Option (data.get is "code smell" anyway, and better be avoided):
case Request() => data
And then just keep trying on the client end:
def result: Future[Int] = (actor ? Request()).map {
case Some(n) => n
case None => after(1 second, system.scheduler)(result)
}
Alternatively, return a Future:
val ready = Promise[Int]()
case data: Int =>
this.data = data
ready.complete(data)
case Request() =>
data.fold(ready.future)(Future.successful)
Now, you just need to flatten it on the caller side:
val result: Future[Int] = (actor ? Request()).flatMap {
case f: Future[Int] => f
}

Why does this akka-http route test never complete successfully?

I've a simple route and some tests that success individually, but collectively fail with timeout. Any idea why?
val route = (requestHandler: ActorRef ## Web) => {
get {
pathPrefix("apps") {
pathEndOrSingleSlash {
completeWith(implicitly[ToEntityMarshaller[List[String]]]) { callback =>
requestHandler ! GetAppsRequest(callback)
}
} ~ path("stats") {
completeWith(implicitly[ToEntityMarshaller[List[Stats]]]) { callback =>
requestHandler ! GetStatsRequest(callback)
}
}
} ~ path("apps" / Segment / "stats") { app =>
completeWith(implicitly[ToEntityMarshaller[Stats]]) { callback =>
requestHandler ! GetStatsForOneRequest(app, callback)
}
}
}
}
and tests:
val testProbe = TestProbe()
val testProbeActor = testProbe.ref
.taggedWith[Web]
val timeout = 1.minute
"Route" should "respond to get apps request" in {
implicit val routeTestTimout = RouteTestTimeout(timeout.dilated)
Get("/apps") ~> route(testProbeActor) ~> check {
testProbe.receiveOne(timeout) match {
case GetAppsRequest(callback) => {
callback(k8SProperties.apps)
}
}
entityAs[List[String]] should contain("test")
}
testProbe.expectNoMessage(timeout)
}
it should "respond to get stats request for all apps" in {
implicit val routeTestTimout = RouteTestTimeout(timeout.dilated)
val app = "test"
Get("/apps/stats") ~> route(testProbeActor) ~> check {
testProbe.receiveOne(timeout) match {
case GetStatsRequest(callback) => {
callback(List(Stats(app, ChronoUnit.SECONDS, Nil)))
}
case other => fail(s"Unexpected message $other.")
}
entityAs[List[Stats]].size shouldBe (1)
entityAs[List[Stats]].head.app shouldBe (app)
}
testProbe.expectNoMessage(timeout)
}
it should "respond to get stats request for one app" in {
implicit val routeTestTimout = RouteTestTimeout(timeout.dilated)
val app = "test"
Get(s"/apps/$app/stats") ~> route(testProbeActor) ~> check {
testProbe.receiveOne(timeout) match {
case GetStatsForOneRequest(app, callback) => {
callback(Stats(app, ChronoUnit.SECONDS, Nil))
}
case other => fail(s"Unexpected message $other.")
}
entityAs[Stats].app shouldBe (app)
}
testProbe.expectNoMessage(timeout)
}
Edit:
Opened https://github.com/akka/akka-http/issues/1615
The problem is that you are using a single TestProbe across all three tests. That TestProbe is a single actor and is therefore receiving messages from all three tests. If you simply move your test probe creation and config inside the test bodies, it should work as you expect; specifically these two lines:
val testProbe = TestProbe()
val testProbeActor = testProbe.ref
.taggedWith[Web]
Working code, thanks to me.
"Routes" should "respond to get apps request" in {
testProbe.setAutoPilot((_: ActorRef, msg: Any) => {
msg match {
case GetAppsRequest(callback) => callback(List("test")); TestActor.KeepRunning
case _ => TestActor.NoAutoPilot
}
})
Get("/apps") ~> handler ~> check {
entityAs[List[String]] should contain("test")
}
}
Putting TestProbe inside check hangs forever probably because it creates a deadlock; test waits for callback to be called, and callback isn't called until the body is executed.
Using autopilot sets up an "expectation" that can be fulfilled later thus avoiding the deadlock.

scala akka futures in play framework with secure social

I'm using secure social and akka to send messages to a web client via a web socket using play frame work 2.3
Websocket
def feedWS = WebSocket.tryAccept[JsValue] { implicit request =>
SecureSocial.currentUser[PDUser].map {
maybeUser => maybeUser match {
case Some(user) =>
Right(Feed.start(user.id))
case None => {
Left(Redirect("/login"))
}
}
}
But the map returns a future and Feed.start returns an future too. Something like
Object serving ws and connecting to an actor that pumps messages out (actor works fine)
def start(user: String): Future[(Iteratee[JsValue, _], Enumerator[JsValue])] = {
(actorFor(user) ? connect(user)).map {
case ConnectedE(enumerator) => {
val iteratee = Iteratee.foreach[JsValue] { event =>
val things = FromJson.aList(event)
actorFor(user) ! Subscribe(things)
}.map { _ =>
log.info("Disconnected")
actorFor(user) ! UnSubscribe
}
(iteratee, enumerator)
}
}
}
How do I compose them, if indeed I can or does it need an await?
At the moment I have a future of a future.

PlayFramework 2.3.x How to use websockets to both broadcast to all and to specific clients

UPDATE
This was answered here #
https://groups.google.com/forum/#!topic/play-framework/P-tG6b_SEyg
--
First Play/Scala app here and I am struggling a bit. What I am trying to achieve is collaboration between users on specific channels (websocket urls). I am trying to follow the example from the book "Play Framework Essentials" and trying to adapt to my use case. Depending on the request from the client, I would either like to broadcast the information to all the clients talking on this channel or only send information back to the client that sent the initial request. The broadcast part is working but I am unable to figure out how to send the information back to just the client of the request themselves.
In my controller I have
def ws(channelId: String) = WebSocket.tryAccept[JsValue] { implicit request =>
getEnumerator(channelId).map { out =>
val in = Iteratee.foreach[JsValue] { jsMsg =>
val id = (jsMsg \ "id").as[String]
// This works and broadcasts that the user has connected
connect(id, request.session.get("email").get)
// Not sure how to return the result of this just to the client of the request
retrieve(id)
}
Right((in, out))
}
}
private def getEnumerator(id: String): Future[Enumerator[JsValue]] = {
(myActor ? GetEnumerator(id)).mapTo[Enumerator[JsValue]]
}
private def connect(id: String, email: String): Unit = {
(myActor ! Connect(id, email))
}
// I have a feeling this is an incorrect return type and I need to return a Future[JsValue]
//and somehow feed that to the enumerator
private def retrieve(id: String): Future[Enumerator[JsValue]] = {
(myActor ? RetrieveInfo(id)).mapTo[Enumerator[JsValue]]
}
In my Actor
class MyActor extends Actor {
var communicationChannels = Map.empty[String, CommunicationChannel]
override def receive: Receive = {
case GetEnumerator(id) => sender() ! getOrCreateCommunicationChannel(id).enumerator
case Connect(id, email) => getOrCreateCommunicationChannel(id).connect(email)
case RetrieveInfo(id) => sender() ! Json.toJson(Info(id, "details for " + id))
}
private def getOrCreateCommunicationChannel(id: String): CommunicationChannel = {
communicationChannels.getOrElse(id, {
val communicationChannel = new CommunicationChannel
communicationChannels += id -> communicationChannel
communicationChannel
})
}
}
object MyActor {
def props: Props = Props[MyActor]
class CommunicationChannel {
val (enumerator, channel) = Concurrent.broadcast[JsValue]
def connect(email: String) = {
channel.push(Json.toJson(Connected(email)))
}
}
}
Where Connect, Connected, Info etc are just case classes with Reads and Writes defined
Can someone please tell me if it is possible to push message to specific user(s) with this approach rather than broadcast it to everyone? Or if I need to implement this in another way
Also is there a way to broadcast to everyone except yourself
Any help will be greatly appreciated
thanks!!