Play WebSocketActor createHandler with custom name - scala

I am using (learning to) handle websockets in play application.
My controller is using WebSocket.acceptWithActor
def clientWS = WebSocket.acceptWithActor[JsValue, JsValue] { _ =>
upstream => ClientSesssionActor.props(upstream)
}
and all is well except some other "supervisor" actor needs to be able to use context.actorSelection(...) to communicate with all/some of those ClientSessionActors.
But all my ClientSessionActors are created with a path like this one :
[akka://application/system/websockets/ REQ_ID /handler]
Here is the line where WebsocketActorSupervisor creates them :
val webSocketActor = context.watch(context.actorOf(createHandler(self), "handler"))
That is where the "handler" part of the path comes from.
I would like to pass in a specific name for my ClientSessionActor instead of getting "handler".
Overloading the whole call stack with one more parameter seems inelegant: there is WebSocketActor.scala with Connect, WebSocketActorSupervisor(props and constructor), WebSocketsActor receive and then everything inside the WebSocket.scala.
I know I can pass the supervisor reference to the props, but what about the case when the "supervisor" has been restarted and needs to reconnect with his minions.
One more thing, I realize that I might be able to get all the "handler" actors, but there are more than 2 kinds of handlers. Yes I could have them ignore msgs directed at the other groups of handlers but this just feels so redundant sending out 3 times more msgs than I should have to.
Any suggestions ?
James ? :)
Thank you

How about each ClientSesssionActor sends a Register message to supervisor on preStart and store them in eg. val sessions = new HashMap[String, ActorRef].
And then unregister by sending Unregister in postStop

private class WebSocketsActor extends Actor {
import WebSocketsActor._
def receive = {
case c # Connect(requestId, enumerator, iteratee, createHandler) =>
implicit val mt = c.messageType
context.actorOf(WebSocketActorSupervisor.props(enumerator, iteratee, createHandler),
requestId.toString)
}
}
Here is code how play creates actors for handling websockets, it names with requestId.
I have also same question :) why not make it to name with custom names.

Related

Where to shutdown actors

we have a lot of actors that get created as
class BankActor extends Actor{
def receive ={
case CreateCustomer(message) => context.actorOf(Props[CustomerActor]) ! message
}
}
And CustomerActor creates other actors in a similar manner. Reason for creating actors in such a way is potentially there will be hundreds(or even thousands) of CreateCustomer messages that BankActor will be receiving in them. I thought creating them on the fly is a better way (given Actor is a low memory footprint). I didn't think having a "pool" of CustomerActor was a right thing to do because biz req is clear there will be lots and lots of "CreateCustomer" messages. can you share your thoughts on this? Now going back to question about stopping "CustomerActor" : where should I be doing context.stop(self) inside "CustomerActor"'s "receive" method, should it be the last thing in every "case" block in there? What's the best practice around this?
Avoid creating top-level actors unless you have a good reason to. (Use context.actorOf)
Send the newly created actor a PoisonPill after the "message" if you don't want to encode the shutdown within the created actor.
class BankActor extends Actor{
def receive = {
case CreateCustomer(message) =>
val customer = context.actorOf(Props[CustomerActor])
customer ! message
customer ! PoisonPill // message ordering is preserved on a per-sender basis (for all normal mailboxes)
}
}

Creating an in-memory storage using Akka actors

I'm trying to familiarize myself with Akka using a pet project. This is basically a tournament-style server, having a pool of players. On each round, it should fetch two random players from the pool, play them against each other, then update a scoreboard. The whole thing sits behind an HTTP server. Players are added via an HTTP Post message, and games are triggered via a 'Play' message that's to be sent from a JS client.
The way I thought of implementing it is as follows:
a PlayerPool actor handling two messages, 'AddPlayer' and 'Play'
a Round actor that takes a message with two players, plays a round, then updates the
GameResults actor, containing a list of played rounds and the winner of each round. It also sports the 'GetScore' message which returns the scoreboard.
The HTTP layer is a Spray Routing actor, exposing calls for 'GetScore', 'AddPlayer' and 'Play', talking to the PlayerPool and GameResults actors.
My problem is that two separate actors are talking to GameResults - both Spray directly, and the Round actor, and apparently two separate instances of GameResults are being created, so that while Round adds a result to one instance, Spray is reading the scoreboard from another instance. Obviously I'm missing something very basic and before attempting to resolve the issue, I'd like to understand what's the canonic way of doing this in Akka? basically this problem can be reduced to an actor that holds a state across different calls.
Would be glad to have someone point me in the right direction.
code snippet example how to pass messages from spray to your game result actor :
hope this helps
object SomeApp extends App{
//create a actor system
val yourSystem = ActorSystem("Your-System")
//init spray actor
val restHandler = yourSystem.actorOf(Props[RestHandler], name = "Rest-spray")
//init play pool actor
val playerPoolActor = yourSystem.actorOf(Props[PlayerPool], name = "playerPool")
//INIT ONLY 1 game result actor
val gameResultsActor = yourSystem.actorOf(Props[GameResults], name = "gameResults")
//spray listen to all IP on port 90210
IO(Http)(yourSystem) ! Http.Bind(restHandler, interface = "0.0.0.0" , port = 90210)
class RestHandler extends Actor with RestHandlerRoute {
def actorRefFactory = context
//nice to hold the route in a diffrent trait
def receive = runRoute(someRoute)
}
}
//only thing the trait is doing is configuring the routing and send message to relavant actor
trait RestHandlerRoute extends HttpService{me: Actor =>
import SomeApp._
val someRoute =
path("getGameResults") { get { respondWithMediaType(`text/html`) { complete {
//case the user requested http://someIP:90210/getGameResults spray will send a message to the game result actor
gameResultsActor ! getResult
} ~
}

Akka and java.nio. Non-blocking selector

I'm trying to write server which listen for tcp connection.
I'm using nonblockig java.nio.
My selector.select() starts when actor receive "STARTLISTEN" message and it's ok, but when i sent messages to actor it not receive messages until selector not received any data.
How to avoid this? For example i want to send message "STOP" to my actor to stop selecting?
Is only way to call select with timeout or selectNow()?
I'm not going to use akka.io.
It's not full code but it illustrates the problem:
class MyActor(val host: String, port: Int) extends Actor {
val serverChannel = ServerSocketChannel.open()
val channelSelector = Selector.open()
serverChannel.configureBlocking(false);
serverChannel.bind(new InetSocketAddress( InetAddress.getByName(host), port ))
serverChannel.register(channelSelector, SelectionKey.OP_ACCEPT);
override def receive = {
case "STARTLISTEN" => {
val keys = channelSelector.select()
// processing read write etc....
}
case "STOP" => {
// I want to stop selection here....
}
}
}
Even though you dismiss it out of hand, I’d like to point out (on the record) that using the proven implementation of exactly this which ships with Akka already is probably the better way to go. (I’m linking to the 2.3.0-RC2 documentation because some of the experimental features which were introduced in the 2.2.x series will not be part of Akka going forward—survival of the fittest.)
You might be able to accomplish this by splitting your actor into multiple actors. The first actor receives messages from outside, and the second blocks on select(). The first actor can use wakeup() to stop the second from blocking before sending it any messages.

Akka and Actor behavior interface

I just start trying myself out with Scala. I grow confident enough to start refactoring an ongoing multi-threaded application that i have been working on for about a year and half.
However something that somehow bother and i can't somehow figure it out, is how to expose the interface/contract/protocole of an Actor? In the OO mode, i have my public interface with synchronized method if necessary, and i know what i can do with that object. Now that i'm going to use actor, it seems that all of that won't be available anymore.
More specifically, I a KbService in my app with a set of method to work with that Kb. I want to make it an actor on its own. For that i need to make all the method private or protected given that now they will be only called by my received method. Hence the to expose the set of available behavior.
Is there some best practice for that ?
To tackle this issue I generally expose the set of messages that an Actor can receive via a "protocol" object.
class TestActor extends Actor {
def receive = {
case Action1 => ???
case Action2 => ???
}
}
object TestActorProtocol {
case object Action1
case object Action2
}
So when you want to communicate with TestActor you must send it a message from its protocol object.
import example.TestActorProtocol._
testActorRef ! TestActorProtocol.Action1
It can become heavy sometimes, but at least there is some kind of contract exposed.
Hope it helps

Any way of appending to the act method in scala?

First off, I am new to Scala:
I am writing a logging facility in Scala that will simply be a class that extends the Actor class. This way a user can just extend this class and the logging features will be available. Basically, I want to write to a log file every time an actor that extends this class sends or receives a message. For clarification every actor will have its own log file which can be collated later. I am taking a Lamport clocks style approach to ordering the events by having each Actor (who extends this class) have their own time variable that gets updated on a message send-receive and the actor will compare the current time variable (simply a positive integer) with the sender's and update its time variable with the greater of the two.
For now I chose to make it a simple method like
sendMessage(recipient, message)
For sending messages. This will just log to the file that the actor is going to send a message to X.
Now, the part that I am stumped on is doing logging when receiving messages. When an actor gets a message I simply want to log this event in a format like
myLogFile.writeLine(self.ToString+": Got a message from "+X+" at time: "+messageSendTime+", processed the message at" +Math.max(myCurrTime+1, messageSendTime+1))
However I need to know who sent this message, unless I force upon the user to include this info (namely the sender's name, time variable, etc) in the messages themselves, it gets hard(er). Is there any way to get the reference of the actual sender? I want this to work with remote actors as well. The only way I can think of is if I append to the act method that the user defines in his/her class with some extra case statements like:
def act {
case => // the user's case statements
...
//somehow I append these statements to the end for the Logger class's use
case (LoggerClassRegisterInboundMessage, message, timeStamp)
InboundMessagesMap.put(timeStamp, message)
}
By having this functionality I can do all the logging "behind the scenes" with these hidden messages being sent whenever the user sends a message. However this only works if the sender also uses the Logging facility. So a more general question is: is there a way in Scala to get the name/toString of a sender in Scala regardless of the sender's class?
I'm actually OK with going with the assumption that every class that sends messages will extend the Logger class. So if anyone knows how to append to the act like or something similar to the above example I will be equally grateful!
As it was said in the comments, Akka is the way to go. It's so much more powerful than the current Scala Actor API which will become deprecated with 2.10 anyway.
But, to attack your specific problem, you could create a trait for actors which support logging, in a way similar to this (I don't know if this actually works, but you can try it):
trait LoggingActor extends Actor {
override def receive[R](pf: PartialFunction[Any, R]): R = {
//we are appending to the partial function pf a case to handle messages with logging:
val loggingPf = pf orElse {
case (LoggerClassRegisterInboundMessage, message, timeStamp) => {
//do somthing with this log message.
message //returning the unwrapped result afterwards
}
}
super.receive(loggingPf)
}
//overriding the send as well
override def !(msg: Any): Unit {
//Wrap it in a logging message
super ! (LoggerClassRegisterInboundMessage, msg, getTimestamp())
}
}
And you would create your actors with something like this:
val myActor = new MyActor with LoggingActor
Hope it helps !