Try reorganised docs

This commit is contained in:
Peter Vlugter 2011-04-20 18:02:11 +12:00
parent 0f436f0738
commit bb8dca5b88
29 changed files with 29 additions and 79 deletions

573
akka-docs/scala/actors.rst Normal file
View file

@ -0,0 +1,573 @@
Actors
======
Module stability: **SOLID**
The `Actor Model <http://en.wikipedia.org/wiki/Actor_model>`_ provides a higher level of abstraction for writing concurrent and distributed systems. It alleviates the developer from having to deal with explicit locking and thread management, making it easier to write correct concurrent and parallel systems. Actors were defined in the 1973 paper by Carl Hewitt but have been popularized by the Erlang language, and used for example at Ericsson with great success to build highly concurrent and reliable telecom systems.
The API of Akkas Actors is similar to Scala Actors which has borrowed some of its syntax from Erlang.
The Akka 0.9 release introduced a new concept; ActorRef, which requires some refactoring. If you are new to Akka just read along, but if you have used Akka 0.6.x, 0.7.x and 0.8.x then you might be helped by the :doc:`0.8.x => 0.9.x migration guide <migration-guide-0.8.x-0.9.x>`
Creating Actors
---------------
Actors can be created either by:
* Extending the Actor class and implementing the receive method.
* Create an anonymous actor using one of the actor methods.
Defining an Actor class
^^^^^^^^^^^^^^^^^^^^^^^
Actor classes are implemented by extending the Actor class and implementing the ``receive`` method. The ``receive`` method should define a series of case statements (which has the type ``PartialFunction[Any, Unit]``) that defines which messages your Actor can handle, using standard Scala pattern matching, along with the implementation of how the messages should be processed.
Here is an example:
.. code-block:: scala
class MyActor extends Actor {
def receive = {
case "test" => EventHandler.info(this, "received test")
case _ => EventHandler.info(this, "received unknown message")
}
}
Please note that the Akka Actor ``receive`` message loop is exhaustive, which is different compared to Erlang and Scala Actors. This means that you need to provide a pattern match for all messages that it can accept and if you want to be able to handle unknown messages then you need to have a default case as in the example above.
Creating Actors
^^^^^^^^^^^^^^^
.. code-block:: scala
val myActor = Actor.actorOf[MyActor]
myActor.start()
Normally you would want to import the ``actorOf`` method like this:
.. code-block:: scala
import akka.actor.Actor._
val myActor = actorOf[MyActor]
To avoid prefixing it with ``Actor`` every time you use it.
You can also start it in the same statement:
.. code-block:: scala
val myActor = actorOf[MyActor].start()
The call to ``actorOf`` returns an instance of ``ActorRef``. This is a handle to the ``Actor`` instance which you can use to interact with the ``Actor``. The ``ActorRef`` is immutable and has a one to one relationship with the Actor it represents. The ``ActorRef`` is also serializable and network-aware. This means that you can serialize it, send it over the wire and use it on a remote host and it will still be representing the same Actor on the original node, across the network.
Creating Actors with non-default constructor
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
If your Actor has a constructor that takes parameters then you can't create it using ``actorOf[TYPE]``. Instead you can use a variant of ``actorOf`` that takes a call-by-name block in which you can create the Actor in any way you like.
Here is an example:
.. code-block:: scala
val a = actorOf(new MyActor(..)).start() // allows passing in arguments into the MyActor constructor
Running a block of code asynchronously
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Here we create a light-weight actor-based thread, that can be used to spawn off a task. Code blocks spawned up like this are always implicitly started, shut down and made eligible for garbage collection. The actor that is created "under the hood" is not reachable from the outside and there is no way of sending messages to it. It being an actor is only an implementation detail. It will only run the block in an event-based thread and exit once the block has run to completion.
.. code-block:: scala
spawn {
... // do stuff
}
Identifying Actors
------------------
Each Actor has two fields:
* ``self.uuid``
* ``self.id``
The difference is that the ``uuid`` is generated by the runtime, guaranteed to be unique and can't be modified. While the ``id`` is modifiable by the user, and defaults to the Actor class name. You can retrieve Actors by both UUID and ID using the ``ActorRegistry``, see the section further down for details.
Messages and immutability
-------------------------
**IMPORTANT**: Messages can be any kind of object but have to be immutable. Scala cant enforce immutability (yet) so this has to be by convention. Primitives like String, Int, Boolean are always immutable. Apart from these the recommended approach is to use Scala case classes which are immutable (if you dont explicitly expose the state) and works great with pattern matching at the receiver side.
Here is an example:
.. code-block:: scala
// define the case class
case class Register(user: User)
// create a new case class message
val message = Register(user)
Other good messages types are ``scala.Tuple2``, ``scala.List``, ``scala.Map`` which are all immutable and great for pattern matching.
Send messages
-------------
Messages are sent to an Actor through one of the “bang” methods.
* ! means “fire-and-forget”, e.g. send a message asynchronously and return immediately.
* !! means “send-and-reply-eventually”, e.g. send a message asynchronously and wait for a reply through aFuture. Here you can specify a timeout. Using timeouts is very important. If no timeout is specified then the actors default timeout (set by the this.timeout variable in the actor) is used. This method returns an ``Option[Any]`` which will be either ``Some(result)`` if returning successfully or None if the call timed out.
* !!! sends a message asynchronously and returns a ``Future``.
You can check if an Actor can handle a specific message by invoking the ``isDefinedAt`` method:
.. code-block:: scala
if (actor.isDefinedAt(message)) actor ! message
else ...
Fire-forget
^^^^^^^^^^^
This is the preferred way of sending messages. No blocking waiting for a message. This gives the best concurrency and scalability characteristics.
.. code-block:: scala
actor ! "Hello"
If invoked from within an Actor, then the sending actor reference will be implicitly passed along with the message and available to the receiving Actor in its ``sender: Option[AnyRef]`` member field. He can use this to reply to the original sender or use the ``reply(message: Any)`` method.
If invoked from an instance that is **not** an Actor there will be no implicit sender passed along the message and you will get an IllegalStateException if you call ``self.reply(..)``.
Send-And-Receive-Eventually
^^^^^^^^^^^^^^^^^^^^^^^^^^^
Using ``!!`` will send a message to the receiving Actor asynchronously but it will wait for a reply on a ``Future``, blocking the sender Actor until either:
* A reply is received, or
* The Future times out
You can pass an explicit time-out to the ``!!`` method and if none is specified then the default time-out defined in the sender Actor will be used.
The ``!!`` method returns an ``Option[Any]`` which will be either ``Some(result)`` if returning successfully, or ``None`` if the call timed out.
Here are some examples:
.. code-block:: scala
val resultOption = actor !! ("Hello", 1000)
if (resultOption.isDefined) ... // handle reply
else ... // handle timeout
val result: Option[String] = actor !! "Hello"
resultOption match {
case Some(reply) => ... // handle reply
case None => ... // handle timeout
}
val result = (actor !! "Hello").getOrElse(throw new RuntimeException("TIMEOUT"))
(actor !! "Hello").foreach(result => ...) // handle result
Send-And-Receive-Future
^^^^^^^^^^^^^^^^^^^^^^^
Using ``!!!`` will send a message to the receiving Actor asynchronously and will return a 'Future':
.. code-block:: scala
val future = actor !!! "Hello"
See `Futures <futures-scala>`_ for more information.
Forward message
^^^^^^^^^^^^^^^
You can forward a message from one actor to another. This means that the original sender address/reference is maintained even though the message is going through a 'mediator'. This can be useful when writing actors that work as routers, load-balancers, replicators etc.
.. code-block:: scala
actor.forward(message)
Receive messages
----------------
An Actor has to implement the ``receive`` method to receive messages:
.. code-block:: scala
protected def receive: PartialFunction[Any, Unit]
Note: Akka has an alias to the ``PartialFunction[Any, Unit]`` type called ``Receive`` (``akka.actor.Actor.Receive``), so you can use this type instead for clarity. But most often you don't need to spell it out.
This method should return a ``PartialFunction``, e.g. a match/case clause in which the message can be matched against the different case clauses using Scala pattern matching. Here is an example:
.. code-block:: scala
class MyActor extends Actor {
def receive = {
case "Hello" =>
log.info("Received 'Hello'")
case _ =>
throw new RuntimeException("unknown message")
}
}
Actor internal API
------------------
The Actor trait contains almost no member fields or methods to invoke, you just use the Actor trait to implement the:
#. ``receive`` message handler
#. life-cycle callbacks:
#. preStart
#. postStop
#. preRestart
#. postRestart
The ``Actor`` trait has one single member field (apart from the ``log`` field from the mixed in ``Logging`` trait):
.. code-block:: scala
val self: ActorRef
This ``self`` field holds a reference to its ``ActorRef`` and it is this reference you want to access the Actor's API. Here, for example, you find methods to reply to messages, send yourself messages, define timeouts, fault tolerance etc., start and stop etc.
However, for convenience you can import these functions and fields like below, which will allow you do drop the ``self`` prefix:
.. code-block:: scala
class MyActor extends Actor {
import self._
id = ...
dispatcher = ...
start
...
}
But in this documentation we will always prefix the calls with ``self`` for clarity.
Let's start by looking how we can reply to messages in a convenient way using this ``ActorRef`` API.
Reply to messages
-----------------
Reply using the reply and reply\_? methods
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
If you want to send a message back to the original sender of the message you just received then you can use the ``reply(..)`` method.
.. code-block:: scala
case request =>
val result = process(request)
self.reply(result)
In this case the ``result`` will be send back to the Actor that sent the ``request``.
The ``reply`` method throws an ``IllegalStateException`` if unable to determine what to reply to, e.g. the sender is not an actor. You can also use the more forgiving ``reply_?`` method which returns ``true`` if reply was sent, and ``false`` if unable to determine what to reply to.
.. code-block:: scala
case request =>
val result = process(request)
if (self.reply_?(result)) ...// success
else ... // handle failure
Reply using the sender reference
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
If the sender is an Actor then its reference will be implicitly passed along together with the message and will end up in the ``sender: Option[ActorRef]`` member field in the ``ActorRef``. This means that you can use this field to send a message back to the sender.
.. code-block:: scala
// receiver code
case request =>
val result = process(request)
self.sender.get ! result
It's important to know that ``sender.get`` will throw an exception if the ``sender`` is not defined, e.g. the ``Option`` is ``None``. You can check if it is defined by invoking the ``sender.isDefined`` method, but a more elegant solution is to use ``foreach`` which will only be executed if the sender is defined in the ``sender`` member ``Option`` field. If it is not, then the operation in the ``foreach`` method is ignored.
.. code-block:: scala
// receiver code
case request =>
val result = process(request)
self.sender.foreach(_ ! result)
The same pattern holds for using the ``senderFuture`` in the section below.
Reply using the sender future
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
If a message was sent with the ``!!`` or ``!!!`` methods, which both implements request-reply semantics using Future's, then you either have the option of replying using the ``reply`` method as above. This method will then resolve the Future. But you can also get a reference to the Future directly and resolve it yourself or if you would like to store it away to resolve it later, or pass it on to some other Actor to resolve it.
The reference to the Future resides in the ``senderFuture: Option[CompletableFuture[_]]`` member field in the ``ActorRef`` class.
Here is an example of how it can be used:
.. code-block:: scala
case request =>
try {
val result = process(request)
self.senderFuture.foreach(_.completeWithResult(result))
} catch {
case e =>
senderFuture.foreach(_.completeWithException(this, e))
}
Reply using the channel
^^^^^^^^^^^^^^^^^^^^^^^
If you want to have a handle to an object to whom you can reply to the message, you can use the ``Channel`` abstraction.
Simply call ``self.channel`` and then you can forward that to others, store it away or otherwise until you want to reply, which you do by ``Channel ! response``:
.. code-block:: scala
case request =>
val result = process(request)
self.channel ! result
.. code-block:: scala
case request =>
friend forward self.channel
Summary of reply semantics and options
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
* ``self.reply(...)`` can be used to reply to an ``Actor`` or a ``Future``.
* ``self.sender`` is a reference to the ``Actor`` you can reply to, if it exists
* ``self.senderFuture`` is a reference to the ``Future`` you can reply to, if it exists
* ``self.channel`` is a reference providing an abstraction to either ``self.sender`` or ``self.senderFuture`` if one is set, providing a single reference to store and reply to (the reference equivalent to the ``reply(...)`` method).
* ``self.sender`` and ``self.senderFuture`` will never be set at the same time, as there can only be one reference to accept a reply.
Initial receive timeout
-----------------------
A timeout mechanism can be used to receive a message when no initial message is received within a certain time. To receive this timeout you have to set the ``receiveTimeout`` property and declare a case handing the ReceiveTimeout object.
.. code-block:: scala
self.receiveTimeout = Some(30000L) // 30 seconds
def receive = {
case "Hello" =>
log.info("Received 'Hello'")
case ReceiveTimeout =>
throw new RuntimeException("received timeout")
}
This mechanism also work for hotswapped receive functions. Every time a ``HotSwap`` is sent, the receive timeout is reset and rescheduled.
Starting actors
---------------
Actors are started by invoking the ``start`` method.
.. code-block:: scala
val actor = actorOf[MyActor]
actor.start()
You can create and start the ``Actor`` in a oneliner like this:
.. code-block:: scala
val actor = actorOf[MyActor].start()
When you start the ``Actor`` then it will automatically call the ``def preStart`` callback method on the ``Actor`` trait. This is an excellent place to add initialization code for the actor.
.. code-block:: scala
override def preStart = {
... // initialization code
}
Stopping actors
---------------
Actors are stopped by invoking the ``stop`` method.
.. code-block:: scala
actor.stop()
When stop is called then a call to the ``def postStop`` callback method will take place. The ``Actor`` can use this callback to implement shutdown behavior.
.. code-block:: scala
override def postStop = {
... // clean up resources
}
You can shut down all Actors in the system by invoking:
.. code-block:: scala
Actor.registry.shutdownAll()
PoisonPill
----------
You can also send an actor the ``akka.actor.PoisonPill`` message, which will stop the actor when the message is processed.
If the sender is a ``Future`` (e.g. the message is sent with ``!!`` or ``!!!``), the ``Future`` will be completed with an ``akka.actor.ActorKilledException("PoisonPill")``.
HotSwap
-------
Upgrade
^^^^^^^
Akka supports hotswapping the Actors message loop (e.g. its implementation) at runtime. There are two ways you can do that:
* Send a ``HotSwap`` message to the Actor.
* Invoke the ``become`` method from within the Actor.
Both of these takes a ``ActorRef => PartialFunction[Any, Unit]`` that implements the new message handler. The hotswapped code is kept in a Stack which can be pushed and popped.
To hotswap the Actor body using the ``HotSwap`` message:
.. code-block:: scala
actor ! HotSwap( self => {
case message => self.reply("hotswapped body")
})
Using the ``HotSwap`` message for hotswapping has its limitations. You can not replace it with any code that uses the Actor's ``self`` reference. If you need to do that the the ``become`` method is better.
To hotswap the Actor using ``become``:
.. code-block:: scala
def angry: Receive = {
case "foo" => self reply "I am already angry!!!"
case "bar" => become(happy)
}
def happy: Receive = {
case "bar" => self reply "I am already happy :-)"
case "foo" => become(angry)
}
def receive = {
case "foo" => become(angry)
case "bar" => become(happy)
}
The ``become`` method is useful for many different things, but a particular nice example of it is in example where it is used to implement a Finite State Machine (FSM): `Dining Hakkers <http://github.com/jboner/akka/blob/master/akka-samples/akka-sample-fsm/src/main/scala/DiningHakkersOnBecome.scala>`_
Here is another little cute example of ``become`` and ``unbecome`` in action:
.. code-block:: scala
case object Swap
class Swapper extends Actor {
def receive = {
case Swap =>
println("Hi")
become {
case Swap =>
println("Ho")
unbecome() // resets the latest 'become' (just for fun)
}
}
}
val swap = actorOf[Swapper].start()
swap ! Swap // prints Hi
swap ! Swap // prints Ho
swap ! Swap // prints Hi
swap ! Swap // prints Ho
swap ! Swap // prints Hi
swap ! Swap // prints Ho
Encoding Scala Actors nested receives without accidentally leaking memory: `UnnestedReceive <https://gist.github.com/797035>`_
------------------------------------------------------------------------------------------------------------------------------
Downgrade
^^^^^^^^^
Since the hotswapped code is pushed to a Stack you can downgrade the code as well. There are two ways you can do that:
* Send the Actor a ``RevertHotswap`` message
* Invoke the ``unbecome`` method from within the Actor.
Both of these will pop the Stack and replace the Actor's implementation with the ``PartialFunction[Any, Unit]`` that is at the top of the Stack.
Revert the Actor body using the ``RevertHotSwap`` message:
.. code-block:: scala
actor ! RevertHotSwap
Revert the Actor body using the ``unbecome`` method:
.. code-block:: scala
def receive: Receive = {
case "revert" => unbecome()
}
Killing an Actor
----------------
You can kill an actor by sending a ``Kill`` message. This will restart the actor through regular supervisor semantics.
Use it like this:
.. code-block:: scala
// kill the actor called 'victim'
victim ! Kill
Actor life-cycle
----------------
The actor has a well-defined non-circular life-cycle.
::
NEW (newly created actor) - can't receive messages (yet)
=> STARTED (when 'start' is invoked) - can receive messages
=> SHUT DOWN (when 'exit' or 'stop' is invoked) - can't do anything
Extending Actors using PartialFunction chaining
-----------------------------------------------
A bit advanced but very useful way of defining a base message handler and then extend that, either through inheritance or delegation, is to use ``PartialFunction.orElse`` chaining.
In generic base Actor:
.. code-block:: scala
import akka.actor.Actor.Receive
abstract class GenericActor extends Actor {
// to be defined in subclassing actor
def specificMessageHandler: Receive
// generic message handler
def genericMessageHandler: Receive = {
case event => printf("generic: %s\n", event)
}
def receive = specificMessageHandler orElse genericMessageHandler
}
In subclassing Actor:
.. code-block:: scala
class SpecificActor extends GenericActor {
def specificMessageHandler = {
case event: MyMsg => printf("specific: %s\n", event.subject)
}
}
case class MyMsg(subject: String)

484
akka-docs/scala/fsm.rst Normal file
View file

@ -0,0 +1,484 @@
FSM
===
.. sidebar:: Contents
.. contents:: :local:
.. module:: FSM
:platform: Scala
:synopsis: Finite State Machine DSL on top of Actors
.. moduleauthor:: Irmo Manie, Roland Kuhn
.. versionadded:: 1.0
Module stability: **STABLE**
Overview
++++++++
The FSM (Finite State Machine) is available as a mixin for the akka Actor and
is best described in the `Erlang design principles
<http://www.erlang.org/documentation/doc-4.8.2/doc/design_principles/fsm.html>`_
A FSM can be described as a set of relations of the form:
**State(S) x Event(E) -> Actions (A), State(S')**
These relations are interpreted as meaning:
*If we are in state S and the event E occurs, we should perform the actions A and make a transition to the state S'.*
A Simple Example
++++++++++++++++
To demonstrate the usage of states we start with a simple FSM without state
data. The state can be of any type so for this example we create the states A,
B and C.
.. code-block:: scala
sealed trait ExampleState
case object A extends ExampleState
case object B extends ExampleState
case object C extends ExampleState
Now lets create an object representing the FSM and defining the behaviour.
.. code-block:: scala
import akka.actor.{Actor, FSM}
import akka.event.EventHandler
import FSM._
import akka.util.duration._
case object Move
class ABC extends Actor with FSM[ExampleState, Unit] {
startWith(A, Unit)
when(A) {
case Ev(Move) =>
EventHandler.info(this, "Go to B and move on after 5 seconds")
goto(B) forMax (5 seconds)
}
when(B) {
case Ev(StateTimeout) =>
EventHandler.info(this, "Moving to C")
goto(C)
}
when(C) {
case Ev(Move) =>
EventHandler.info(this, "Stopping")
stop
}
initialize // this checks validity of the initial state and sets up timeout if needed
}
Each state is described by one or more :func:`when(state)` blocks; if more than
one is given for the same state, they are tried in the order given until the
first is found which matches the incoming event. Events are matched using
either :func:`Ev(msg)` (if no state data are to be extracted) or
:func:`Event(msg, data)`, see below. The statements for each case are the
actions to be taken, where the final expression must describe the transition
into the next state. This can either be :func:`stay` when no transition is
needed or :func:`goto(target)` for changing into the target state. The
transition may be annotated with additional properties, where this example
includes a state timeout of 5 seconds after the transition into state B:
:func:`forMax(duration)` arranges for a :obj:`StateTimeout` message to be
scheduled, unless some other message is received first. The construction of the
FSM is finished by calling the :func:`initialize` method as last part of the
ABC constructor.
State Data
++++++++++
The FSM can also hold state data associated with the internal state of the
state machine. The state data can be of any type but to demonstrate let's look
at a lock with a :class:`String` as state data holding the entered unlock code.
First we need two states for the lock:
.. code-block:: scala
sealed trait LockState
case object Locked extends LockState
case object Open extends LockState
Now we can create a lock FSM that takes :class:`LockState` as a state and a
:class:`String` as state data:
.. code-block:: scala
class Lock(code: String) extends Actor with FSM[LockState, String] {
val emptyCode = ""
startWith(Locked, emptyCode)
when(Locked) {
// receive a digit and the code that we have so far
case Event(digit: Char, soFar) => {
// add the digit to what we have
soFar + digit match {
case incomplete if incomplete.length < code.length =>
// not enough digits yet so stay using the incomplete code as the new state data
stay using incomplete
case `code` =>
// code matched the one from the lock so go to Open state and reset the state data
goto(Open) using emptyCode forMax (1 seconds)
case wrong =>
// wrong code, stay Locked and reset the state data
stay using emptyCode
}
}
}
when(Open) {
case Ev(StateTimeout, _) => {
// after the timeout, go back to Locked state
goto(Locked)
}
}
initialize
}
This very simple example shows how the complete state of the FSM is encoded in
the :obj:`(State, Data)` pair and only explicitly updated during transitions.
This encapsulation is what makes state machines a powerful abstraction, e.g.
for handling socket states in a network server application.
Reference
+++++++++
This section describes the DSL in a more formal way, refer to `Examples`_ for more sample material.
The FSM Trait and Object
------------------------
The :class:`FSM` trait may only be mixed into an :class:`Actor`. Instead of
extending :class:`Actor`, the self type approach was chosen in order to make it
obvious that an actor is actually created. Importing all members of the
:obj:`FSM` object is recommended to receive useful implicits and directly
access the symbols like :obj:`StateTimeout`. This import is usually placed
inside the state machine definition:
.. code-block:: scala
class MyFSM extends Actor with FSM[State, Data] {
import FSM._
...
}
The :class:`FSM` trait takes two type parameters:
#. the supertype of all state names, usually a sealed trait with case objects
extending it,
#. the type of the state data which are tracked by the :class:`FSM` module
itself.
.. _fsm-philosophy:
.. note::
The state data together with the state name describe the internal state of
the state machine; if you stick to this scheme and do not add mutable fields
to the FSM class you have the advantage of making all changes of the
internal state explicit in a few well-known places.
Defining Timeouts
-----------------
The :class:`FSM` module uses :class:`akka.util.Duration` for all timing
configuration, which includes a mini-DSL:
.. code-block:: scala
import akka.util.duration._ // notice the small d
val fivesec = 5.seconds
val threemillis = 3.millis
val diff = fivesec - threemillis
.. note::
You may leave out the dot if the expression is clearly delimited (e.g.
within parentheses or in an argument list), but it is recommended to use it
if the time unit is the last token on a line, otherwise semi-colon inference
might go wrong, depending on what starts the next line.
Several methods, like :func:`when()` and :func:`startWith()` take a
:class:`FSM.Timeout`, which is an alias for :class:`Option[Duration]`. There is
an implicit conversion available in the :obj:`FSM` object which makes this
transparent, just import it into your FSM body.
Defining States
---------------
A state is defined by one or more invocations of the method
:func:`when(<name>[, stateTimeout = <timeout>])(stateFunction)`.
The given name must be an object which is type-compatible with the first type
parameter given to the :class:`FSM` trait. This object is used as a hash key,
so you must ensure that it properly implements :meth:`equals` and
:meth:`hashCode`; in particular it must not be mutable. The easiest fit for
these requirements are case objects.
If the :meth:`stateTimeout` parameter is given, then all transitions into this
state, including staying, receive this timeout by default. Initiating the
transition with an explicit timeout may be used to override this default, see
`Initiating Transitions`_ for more information. The state timeout of any state
may be changed during action processing with :func:`setStateTimeout(state,
duration)`. This enables runtime configuration e.g. via external message.
The :meth:`stateFunction` argument is a :class:`PartialFunction[Event, State]`,
which is conveniently given using the partial function literal syntax as
demonstrated below:
.. code-block:: scala
when(Idle) {
case Ev(Start(msg)) => // convenience extractor when state data not needed
goto(Timer) using (msg, self.channel)
}
when(Timer, stateTimeout = 12 seconds) {
case Event(StateTimeout, (msg, channel)) =>
channel ! msg
goto(Idle)
}
The :class:`Event(msg, data)` case class may be used directly in the pattern as
shown in state Idle, or you may use the extractor :obj:`Ev(msg)` when the state
data are not needed.
Defining the Initial State
--------------------------
Each FSM needs a starting point, which is declared using
:func:`startWith(state, data[, timeout])`
The optionally given timeout argument overrides any specification given for the
desired initial state. If you want to cancel a default timeout, use
:obj:`Duration.Inf`.
Unhandled Events
----------------
If a state doesn't handle a received event a warning is logged. If you want to
do something else in this case you can specify that with
:func:`whenUnhandled(stateFunction)`:
.. code-block:: scala
whenUnhandled {
case Event(x : X, data) =>
EventHandler.info(this, "Received unhandled event: " + x)
stay
case Ev(msg) =>
EventHandler.warn(this, "Received unknown event: " + x)
goto(Error)
}
**IMPORTANT**: This handler is not stacked, meaning that each invocation of
:func:`whenUnhandled` replaces the previously installed handler.
Initiating Transitions
----------------------
The result of any :obj:`stateFunction` must be a definition of the next state
unless terminating the FSM, which is described in `Termination`_. The state
definition can either be the current state, as described by the :func:`stay`
directive, or it is a different state as given by :func:`goto(state)`. The
resulting object allows further qualification by way of the modifiers described
in the following:
:meth:`forMax(duration)`
This modifier sets a state timeout on the next state. This means that a timer
is started which upon expiry sends a :obj:`StateTimeout` message to the FSM.
This timer is canceled upon reception of any other message in the meantime;
you can rely on the fact that the :obj:`StateTimeout` message will not be
processed after an intervening message.
This modifier can also be used to override any default timeout which is
specified for the target state. If you want to cancel the default timeout,
use :obj:`Duration.Inf`.
:meth:`using(data)`
This modifier replaces the old state data with the new data given. If you
follow the advice :ref:`above <fsm-philosophy>`, this is the only place where
internal state data are ever modified.
:meth:`replying(msg)`
This modifier sends a reply to the currently processed message and otherwise
does not modify the state transition.
All modifier can be chained to achieve a nice and concise description:
.. code-block:: scala
when(State) {
case Ev(msg) =>
goto(Processing) using (msg) forMax (5 seconds) replying (WillDo)
}
The parentheses are not actually needed in all cases, but they visually
distinguish between modifiers and their arguments and therefore make the code
even more pleasant to read for foreigners.
Monitoring Transitions
----------------------
Transitions occur "between states" conceptually, which means after any actions
you have put into the event handling block; this is obvious since the next
state is only defined by the value returned by the event handling logic. You do
not need to worry about the exact order with respect to setting the internal
state variable, as everything within the FSM actor is running single-threaded
anyway.
Internal Monitoring
*******************
Up to this point, the FSM DSL has been centered on states and events. The dual
view is to describe it as a series of transitions. This is enabled by the
method
:func:`onTransition(handler)`
which associates actions with a transition instead of with a state and event.
The handler is a partial function which takes a pair of states as input; no
resulting state is needed as it is not possible to modify the transition in
progress.
.. code-block:: scala
onTransition {
case Idle -> Active => setTimer("timeout")
case Active -> _ => cancelTimer("timeout")
case x -> Idle => EventHandler.info("entering Idle from "+x)
}
The convenience extractor :obj:`->` enables decomposition of the pair of states
with a clear visual reminder of the transition's direction. As usual in pattern
matches, an underscore may be used for irrelevant parts; alternatively you
could bind the unconstrained state to a variable, e.g. for logging as shown in
the last case.
It is also possible to pass a function object accepting two states to
:func:`onTransition`, in case your transition handling logic is implemented as
a method:
.. code-block:: scala
onTransition(handler _)
private def handler(from: State, to: State) {
...
}
The handlers registered with this method are stacked, so you can intersperse
:func:`onTransition` blocks with :func:`when` blocks as suits your design. It
should be noted, however, that *all handlers will be invoked for each
transition*, not only the first matching one. This is designed specifically so
you can put all transition handling for a certain aspect into one place without
having to worry about earlier declarations shadowing later ones; the actions
are still executed in declaration order, though.
.. note::
This kind of internal monitoring may be used to structure your FSM according
to transitions, so that for example the cancellation of a timer upon leaving
a certain state cannot be forgot when adding new target states.
External Monitoring
*******************
External actors may be registered to be notified of state transitions by
sending a message :class:`SubscribeTransitionCallBack(actorRef)`. The named
actor will be sent a :class:`CurrentState(self, stateName)` message immediately
and will receive :class:`Transition(actorRef, oldState, newState)` messages
whenever a new state is reached. External monitors may be unregistered by
sending :class:`UnsubscribeTransitionCallBack(actorRef)` to the FSM actor.
Registering a not-running listener generates a warning and fails gracefully.
Stopping a listener without unregistering will remove the listener from the
subscription list upon the next transition.
Timers
------
Besides state timeouts, FSM manages timers identified by :class:`String` names.
You may set a timer using
:func:`setTimer(name, msg, interval, repeat)`
where :obj:`msg` is the message object which will be sent after the duration
:obj:`interval` has elapsed. If :obj:`repeat` is :obj:`true`, then the timer is
scheduled at fixed rate given by the :obj:`interval` parameter. Timers may be
canceled using
:func:`cancelTimer(name)`
which is guaranteed to work immediately, meaning that the scheduled message
will not be processed after this call even if the timer already fired and
queued it. The status of any timer may be inquired with
:func:`timerActive_?(name)`
These named timers complement state timeouts because they are not affected by
intervening reception of other messages.
Termination
-----------
The FSM is stopped by specifying the result state as
:func:`stop([reason[, data]])`
The reason must be one of :obj:`Normal` (which is the default), :obj:`Shutdown`
or :obj:`Failure(reason)`, and the second argument may be given to change the
state data which is available during termination handling.
.. note::
It should be noted that :func:`stop` does not abort the actions and stop the
FSM immediately. The stop action must be returned from the event handler in
the same way as a state transition.
.. code-block:: scala
when(A) {
case Ev(Stop) =>
doCleanup()
stop()
}
You can use :func:`onTermination(handler)` to specify custom code that is
executed when the FSM is stopped. The handler is a partial function which takes
a :class:`StopEvent(reason, stateName, stateData)` as argument:
.. code-block:: scala
onTermination {
case StopEvent(Normal, s, d) => ...
case StopEvent(Shutdown, _, _) => ...
case StopEvent(Failure(cause), s, d) => ...
}
As for the :func:`whenUnhandled` case, this handler is not stacked, so each
invocation of :func:`onTermination` replaces the previously installed handler.
Examples
++++++++
A bigger FSM example can be found in the sources:
* `Dining Hakkers using FSM <https://github.com/jboner/akka/blob/master/akka-samples/akka-sample-fsm/src/main/scala/DiningHakkersOnFsm.scala#L1>`_
* `Dining Hakkers using become <https://github.com/jboner/akka/blob/master/akka-samples/akka-sample-fsm/src/main/scala/DiningHakkersOnBecome.scala#L1>`_

View file

@ -0,0 +1,8 @@
Scala API
=========
.. toctree::
:maxdepth: 2
actors
fsm