Scala Lift - Comet actor initialization message - scala

I have the following Comet actor:
class ChatComet extends CometActor with CometListener {
private var messages: List[ChatItem] = Nil
def registerWith = ChatServer
override def lowPriority = {
case v: List[ChatItem] =>
messages = v;
reRender()
}
def render = {
"li *" #> messages.map(message =>
".name *" #> message.name &
".text *" #> message.value
)
}
Which distributes messages around various rooms, what I don't have is a way to limit which messages end up where, so a message from RoomA ends up in RoomA not in RoomB.
I've heard you can initialize comet actors with some kind of message which in my case could serve as the room id.
Is this the right way of doing things? If so how would I go about doing it?
Thanks in advance for any help, much appreciated :)

In the template, name the comet actor, like so:
<div class="l:comet?type=CometActor;name=roomA"> stuff </div>
In your CometActor, then match on the name, like so:
def lowpriority = {
case NewComment(room, msg) => {
name.map(x => x match {
case "roomA" => {
stuff
}
}
}
Now, you probably don't have explicit names like "roomA" but you can keep a list of your room names, and then simply match against them.

Give your Comet Actors names associated with the chat rooms. Then a new Actor will be built per-room. You won't need to do any special handling in your Actor itself; unless you want to have special features depending on the room.
You can see a nice example referenced on the Lift wiki, which shows how you can use a snippet to assign the names to your Comet Actors.

For initializing CometActors in general, check out my answer on S.param within a CometActor. That being said, Dave and Tyler's answers seem more appropriate to what you want to do.

Related

Prioritizing message in Akka

I've been attempting to follow the example from Akka's docs on Dispatchers, which I found from this post originally.
After running a sample, I'm not convinced I have it setup correctly. I'm deviating from the example slightly. Instead of creating a new dispatcher entry in the application.conf, like the tutorial:
prio-dispatcher {
mailbox-type = "akka.docs.dispatcher.DispatcherDocSpec$MyPrioMailbox"
}
I want to overwrite the default dispatcher for ALL actors in my application. Therefore, I've done this:
default-dispatcher
{
mailbox-type = "LoggingPriorityMailbox"
}
And in Scala:
class LoggingPriorityMailbox
extends UnboundedPriorityMailbox(
PriorityGenerator {
case Debug(ts: Timestamp, s: String) => 10 // Lowest
...
case otherwise => 0 // Highest
}) {}
I've turned on log-config-on-start setting and verified the mailbox-type is set properly for the default-dispatcher. So I suppose it's at least being configured properly... Am I missing something? As I've read elsewhere for priority mailboxes, it might just be the case that my testing hasn't overloaded the mailboxes and actors enough to allow them to prioritize.

Changing Akka actor state by passing a method with arguments to "become"

I am having some trouble using become in my Akka actor. Basically, my actor has a structure like so:
// This is where I store information received by the actor
// In my real application it has more fields, though.
case class Information(list:List[AnyRef]) {
def received(x:AnyRef) = {
Information(list :+ x)
}
}
class MyActor extends Actor {
// Initial receive block that simply waits for a "start" signal
def receive = {
case Start => {
become(waiting(Information(List())))
}
}
// The main waiting state. In my real application, I have multiple of
// these which all have a parameter of type "Information"
def waiting(info:Information):Receive = {
// If a certain amount of messages was received, I decide what action
// to take next.
if(someCondition) {
decideNextState(x)
}
return {
case Bar(x) => {
//
// !!! Problem occurs here !!!
//
// This is where the problem occurs, apparently. After a decision has been
// made, (i.e. decideNextState was invoked), the info list should've been
// cleared. But when I check the size of the info list here, after a decision
// has been made, it appears to still contain all the messages received
// earlier.
//
become(waiting(info received x))
}
}
}
def decideNextState(info:Information) {
// Some logic, then the received information list is cleared and
// we enter a new state.
become(waiting((Information(List())))
}
}
Sorry for the long code snippet, but I couldn't really make it any smaller.
The part where the problem occurs is marked in the comments. I am passing a parameter to the method that returns the Receive partial function which is then passed to the become method. However, the created partial function seems to somehow preserve state from an earlier invocation. I find the problem a bit difficult to explain, but I did my best to do so in the comments in the code, so please read those and I'll answer anything that is unclear.
Your logic is a little convoluted but I'll take a shot at what could be the problem:
If someCondition is true then your actor steps into a state, let's call it S1 characterized by a value Information(List()). And then you return (by the way, avoid using return unless it is absolutely necessary) a receive method which will put your actor into a state S2 characterized by a list Information(somePreviousList :+ x). So at this point your stack of states has S1 on top. But when you receive a Bar(x) message the state S2 will be pushed, thus covering S1 and you actually transition into a state characterized by an Information with the old values + your new x.
Or something like that, the recursion in your actor is a bit mesmerizing.
But I'll suggest rewriting that code since it seems that the state which changes is something of type Information and you are manipulating this state using Akka's actor state transitions which is not at all the best tool to do that. become and unbecome are meant to be used to transition from different states of the actor's behavior. That is, an actor can have a different behavior at any time and you use become and unbecome to change between these behaviors.
Why not do something like this ?
class MyActor extends Actor {
private var info = Information(List.empty)
def receive = {
case Start => info = Information(List()) //a bit redundant, but it's just to match 1:1 with your code
case Bar(x) => {
if (someCondition) {
info = Information(List.empty)
}
info = info received x
}
}
}
I might not have captured your entire idea, but you get the picture.

AKKA: Painless Actor Error Notifications

Beautiful People Lifestyle
A component BEAUTIFUL is using her internal akka.actor.Actor to do certain things.. ( such as "acting up" for example )
There are other MAN components that would really like to "interact" with the BEAUTIFUL
When the BEAUTIFUL finds a MAN worthy, before "interacting" with him, she agrees to take in his phone number ( let's call it an ErrorHandler ), you know just to give him a call in case he left in the morning and forgot his Rolex on her bed side table
The BEAUTIFUL though is "high maintenance" ( aren't they all.. ), and every time something bad happens inside the BEAUTIFUL's internal Actor ( e.g. an OmgBrokenNailException, UglyPurseThrowable, etc.. ), she goes nuts, needs to stop completely and to call a MAN using that phone number ( e.g. errorHandler.getOnItNowHoney( message, throwable ) )
Beautiful People Problem
AKKA supervisors allow to register two types of FaultHandlers => OneForOneStrategy and AllForOneStrategy, where if the underlying Actor overrides preRestart/postRestart, it gets access to an actual "throwable" e.g.:
override def preRestart( reason: Throwable ) { // do with throwable... }
The problem is both of these strategies will try to restart the Actor(s), which is not something that I am looking for. I am looking for the Actor to call an external ErrorHandler with the "throwable" and stop.
If I don't use these strategies, when exception is thrown from within the Actor, a postStop is called on the Actor, which is cool, but it does not take in a "throwable":
override def postStop() { // no access to "throwable"... }
Help the MAN to get that throwable
In Akka 2 you should use DeathWatch
If I understand your problem correctly, I think it would make sense to wrap your message processing in a try/catch block and let the actor handle sending the Throwable and stopping itself.
def receive = {
case message => try { message match {
case ... //your actual message processing goes here
}} catch {
case t: Throwable => {
errorHandler ! t
self.stop
}
}
}

How to call the correct method in Scala/Java based the types of two objects without using a switch statement?

I am currently developing a game in Scala where I have a number of entities (e.g. GunBattery, Squadron, EnemyShip, EnemyFighter) that all inherit from a GameEntity class. Game entities broadcast things of interest to the game world and one another via an Event/Message system. There are are a number of EventMesssages (EntityDied, FireAtPosition, HullBreach).
Currently, each entity has a receive(msg:EventMessage) as well as more specific receive methods for each message type it responds to (e.g. receive(msg:EntityDiedMessage) ). The general receive(msg:EventMessage) method is just a switch statement that calls the appropriate receive method based on the type of message.
As the game is in development, the list of entities and messages (and which entities will respond to which messages) is fluid. Ideally if I want a game entity to be able to receive a new message type, I just want to be able to code the logic for the response, not do that and have to update a match statement else where.
One thought I had would be to pull the receive methods out of the Game entity hierarchy and have a series of functions like def receive(e:EnemyShip,m:ExplosionMessage) and def receive(e:SpaceStation,m:ExplosionMessage) but this compounds the problem as now I need a match statement to cover both the message and game entity types.
This seems related to the concepts of Double and Multiple dispatch and perhaps the Visitor pattern but I am having some trouble wrapping my head around it. I am not looking for an OOP solution per se, however I would like to avoid reflection if possible.
EDIT
Doing some more research, I think what I am looking for is something like Clojure's defmulti.
You can do something like:
(defmulti receive :entity :msgType)
(defmethod receive :fighter :explosion [] "fighter handling explosion message")
(defmethod receive :player-ship :hullbreach [] "player ship handling hull breach")
You can easily implement multiple dispatch in Scala, although it doesn't have first-class support. With the simple implementation below, you can encode your example as follows:
object Receive extends MultiMethod[(Entity, Message), String]("")
Receive defImpl { case (_: Fighter, _: Explosion) => "fighter handling explosion message" }
Receive defImpl { case (_: PlayerShip, _: HullBreach) => "player ship handling hull breach" }
You can use your multi-method like any other function:
Receive(fighter, explosion) // returns "fighter handling explosion message"
Note that each multi-method implementation (i.e. defImpl call) must be contained in a top-level definition (a class/object/trait body), and it's up to you to ensure that the relevant defImpl calls occur before the method is used. This implementation has lots of other limitations and shortcomings, but I'll leave those as an exercise for the reader.
Implementation:
class MultiMethod[A, R](default: => R) {
private var handlers: List[PartialFunction[A, R]] = Nil
def apply(args: A): R = {
handlers find {
_.isDefinedAt(args)
} map {
_.apply(args)
} getOrElse default
}
def defImpl(handler: PartialFunction[A, R]) = {
handlers +:= handler
}
}
If you're really worried about the effort it takes to create/maintain the switch statement, you could use metaprogramming to generate the switch statement by discovering all EventMessage types in your program. It's not ideal, but metaprogramming is generally one of the cleanest ways to introduce new constraints on your code; in this case that'd be the requirement that if an event type exists, there is a dispatcher for it, and a default (ignore?) handler that can be overridden.
If you don't want to go that route, you can make EventMessage a case class, which should allow the compiler to complain if you forget to handle a new message type in your switch statement. I wrote a game server that was used by ~1.5 million players, and used that kind of static typing to ensure that my dispatch was comprehensive, and it never caused an actual production bug.
Chain of Responsibility
A standard mechanism for this (not scala-specific) is a chain of handlers. For example:
trait Handler[Msg] {
handle(msg: Msg)
}
Then your entities just need to manage a list of handlers:
abstract class AbstractEntity {
def handlers: List[Handler]
def receive(msg: Msg) { handlers foreach handle }
}
Then your entities can declare the handlers inline, as follows:
class Tank {
lazy val handlers = List(
new Handler {
def handle(msg: Msg) = msg match {
case ied: IedMsg => //handle
case _ => //no-op
}
},
new Handler {
def handle(msg: Msg) = msg match {
case ef: EngineFailureMsg => //handle
case _ => //no-op
}
}
)
Of course the disadvantage here is that you lose readability, and you still have to remember the boilerplate which is a no-op catch-all case for each handler.
Actors
Personally I would stick with the duplication. What you have at the moment looks a lot like treating each entity as if it is an Actor. For example:
class Tank extends Entity with Actor {
def act() {
loop {
react {
case ied: IedMsg => //handle
case ied: EngineFailureMsg => //handle
case _ => //no-op
}
}
}
}
At least here you get into the habit of adding a case statement within the react loop. This can call another method in your actor class which takes the appropriate action. Of course, the benefit of this is that you take advantage of the concurrency model provided by the actor paradigm. You end up with a loop which looks like this:
react {
case ied: IedMsg => _explosion(ied)
case efm: EngineFailureMsg => _engineFailure(efm)
case _ =>
}
You might want to look at akka, which offers a more performant actor system with more configurable behaviour and more concurrency primitives (STM, agents, transactors etc)
No matter what, you have to do some updating; the application won't just magically know which response action to do based off of the event message.
Cases are well and good, but as the list of messages your object responds to gets longer, so does its response time. Here is a way to respond to messages that will respond at the same speed no matter how many your register with it. The example does need to use the Class object, but no other reflections are used.
public class GameEntity {
HashMap<Class, ActionObject> registeredEvents;
public void receiveMessage(EventMessage message) {
ActionObject action = registeredEvents.get(message.getClass());
if (action != null) {
action.performAction();
}
else {
//Code for if the message type is not registered
}
}
protected void registerEvent(EventMessage message, ActionObject action) {
Class messageClass = message.getClass();
registeredEventes.put(messageClass, action);
}
}
public class Ship extends GameEntity {
public Ship() {
//Do these 3 lines of code for every message you want the class to register for. This example is for a ship getting hit.
EventMessage getHitMessage = new GetHitMessage();
ActionObject getHitAction = new GetHitAction();
super.registerEvent(getHitMessage, getHitAction);
}
}
There are variations of this using Class.forName(fullPathName) and passing in the pathname strings instead of the objects themselves if you want.
Because the logic for performing an action is contained in the superclass, all you have to do to make a subclass is register what events it responds to and create an ActionObject that contains the logic for its response.
I'd be tempted to elevate every message type into a method signature and Interface. How this translates into Scala I'm not totally sure, but this is the Java approach I would take.
Killable, KillListener, Breachable, Breachlistener and so on will surface the logic of your objects and commonalities between them in a way which permits runtime inspection (instanceof) as well as helping with runtime performance. Things which don't process Kill events won't be put in a java.util.List<KillListener> to be notified. You can then avoid the creation of multiple new concrete objects all the time (your EventMessages) as well as lots of switching code.
public interface KillListener{
void notifyKill(Entity entity);
}
After all, a method in java is otherwise understood as a message - just use raw java syntax.

Finite State Machine and inter-FSM signaling

Recommendations for languages with native (so no FSM generation tools) support for state machine development and execution and passing of messages/signals. This is for telecoms, e.g implementation of FSMs of this level of complexity.
I have considered Erlang, but would love some feedback, suggestions, pointer to tutorials, alternatives, particularly Java based frameworks. Maybe Scala?
Open source only. I'm not looking for UML or regular expression related solutions.
As this is for the implementation of telecoms protocols the FSMs may be non-trivial. Many states, many transitions, signal based, input constraints/guards. Dynamic instantiation would be a plus. Switch statements are out of the question, it quickly nests to unusable. It's barely better that if/else.
I would prefer to not depend on graphical design; the format FSM description should be human readable/editable/manageable.
--
I have decided to focus on an Actor based solution for C++
For example, the Theron framework provides a starting point http://theron.ashtonmason.net/ and to avoid switch statements in the FSM based event handler this C++ FSM Template Framework looks useful http://satsky.spb.ru/articles/fsm/fsmEng.php
This particular application, telco protocol implementation, is what Erlang was built for. The initial applications of Erlang at Ericsson were telephone switches and the earliest commercial products were ATM switches supporting all manner of telco protocols.
OTP has a standard behaviour for implementing FSMs called gen_fsm. There's an example of its use in a non-trivial FSM in some of the OTP Documentation.
OSERL is an open souce SMPP implementation in Erlang and demonstrates how you can implement a telco protocol using gen_fsms. A good example to look at would be gen_esme_session.
While I can't point you to the code, I know there are quite a few Erlang companies selling telco oriented products: Corelatus, Synapse, Motivity among others.
I agree that switch statements should be out of the question... they eventually lead to maintenance nightmares. Can't you use the State Pattern to implement your FSM? Depending on your actual implementation, you could use actors (if you have multiple FSM collaborating - hm... is that possible?). The nice thing about actors is that the framework for passing messages is already there.
An example of using State would be:
trait State {
def changeState(message: Any): State
}
trait FSM extends Actor {
var state: State
def processMessage(message: Any) {
state = state.changeState(message)
}
override def act() {
loop {
react {
case m: Any => processMessage(m)
}
}
}
}
This is very basic code, but as I don't know more of the requirements, that's the most I can think of. The advantage of State is that every state is self-contained in one class.
I disagree that FSM are trivial to implement. This is very short-sighted, and shows either a lack of familiarity with the alternatives, or the lack of experience with complex state machines.
The fundamental problem is that a state machine graph is obvious, but FSM code is not. Once you get beyond a dozen states and a score of transitions, FSM code becomes ugly and difficult to follow.
There are tools whereby you draw the state machine, and generate Java code for it. I don't know of any open source tools for that, however.
Now, getting back to Erlang/Scala, Scala has Actors and message passing as well, and is based on the JVM, so it might be a better alternative than Erlang given your constraints.
There's a DFA/NFA library on Scala as well, though it is not particularly a good one. It supports conversion from arbitrary regular expressions (ie, the literals need not be characters) into DFA/NFA.
I'll post some code below using it. In this code, the idea is creating a FSM which will accept any sequential combination of arbitrary prefixes for a list of words, the idea being looking up menu options without predefined keybinds.
import scala.util.regexp._
import scala.util.automata._
// The goal of this object below is to create a class, MyChar, which will
// be the domain of the tokens used for transitions in the DFA. They could
// be integers, enumerations or even a set of case classes and objects. For
// this particular code, it's just Char.
object MyLang extends WordExp {
type _regexpT = RegExp
type _labelT = MyChar
case class MyChar(c:Char) extends Label
}
// We now need to import the types we defined, as well as any classes we
// created extending Label.
import MyLang._
// We also need an instance (singleton, in this case) of WordBerrySethi,
// which will convert the regular expression into an automatum. Notice the
// language being used is MyLang.
object MyBerrySethi extends WordBerrySethi {
override val lang = MyLang
}
// Last, a function which takes an input in the language we defined,
// and traverses the DFA, returning whether we are at a sink state or
// not. For other uses it will probably make more sense to test against
// both sink states and final states.
def matchDet(pat: DetWordAutom[MyChar], seq: Seq[Char]): Boolean =
!pat.isSink((0 /: seq) ((state, c) => pat.next(state, MyChar(c))))
// This converts a regular expression to a DFA, with using an intermediary NFA
def compile(pat: MyLang._regexpT) =
new SubsetConstruction(MyBerrySethi.automatonFrom(pat, 100000)).determinize
// Defines a "?" function, since it isn't provided by the library
def Quest(rs: _regexpT*) = Alt(Eps, Sequ(rs: _*)) // Quest(pat) = Eps|pat = (pat)?
// And now, the algorithm proper. It splits the string into words
// converts each character into Letter[MyChar[Char]],
// produce the regular expression desired for each word using Quest and Sequ,
// then the final regular expression by using Sequ with each subexpression.
def words(s : String) = s.split("\\W+")
def wordToRegex(w : String) : Seq[MyLang._regexpT] = w.map(c => Letter(MyChar(c)))
def wordRegex(w : String) = Quest(wordToRegex(w) reduceRight ((a,b) => Sequ(a, Quest(b))))
def phraseRegex(s : String) = Sequ(words(s).map(w => wordRegex(w)) : _*)
// This takes a list of strings, produce a DFA for each, and returns a list of
// of tuples formed by DFA and string.
def regexList(l : List[String]) = l.map(s => compile(phraseRegex(s)) -> s)
// The main function takes a list of strings, and returns a function that will
// traverse each DFA, and return all strings associated with DFAs that did not
// end up in a sink state.
def regexSearcher(l : List[String]) = {
val r = regexList(l)
(s : String) => r.filter(t => matchDet(t._1, s)).map(_._2)
}
I can hardly think of any language where implementing an FSM is non-trivial. Maybe this one.
...
if (currentState == STATE0 && event == EVENT0) return STATE1;
if (currentState == STATE1 && event == EVENT0) return STATE2;
...
The State pattern (using Java enums) is what we use in our telecom application, however we use small FSM's:
public class Controller{
private State itsState = State.IDLE;
public void setState(State aState){
itsState = aState;
}
public void action1(){
itsState.action1(this);
}
public void action2(){
itsState.action2(this);
}
public void doAction1(){
// code
}
public void doAction2(){
// code
}
}
public enum State{
IDLE{
#Override
public void action1(Controller aCtx){
aCtx.doAction1();
aCtx.setState(State.STATE1);
}
},
STATE1{
#Override
public void action2(Controller aCtx){
aCtx.doAction2();
aCtx.setState(State.IDLE);
}
},
public void action1(Controller aCtx){
throw new IllegalStateException();
}
public void action2(Controller aCtx){
throw new IllegalStateException();
}
}
FSM should be trivial to implement in any language that has a case statement.Your choice of language should be based on what that finite state machine needs to do.
For example, you state that you need to do this for telecom development and mention messages. I would look at systems/languages that support distributed message passing. Erlang does this, and I"m sure just about every other common language supports this through an API/library for the language.