Riker Patterns
Overview
The patterns crate provides a collection of common patterns used in actor systems.
Currently this only includes the Ask pattern and a behavior change pattern that provides a transform!
macro.
The intention is to add many patterns, some of which are well documented in popular actor programming books, such as Reactive Messaging Patterns with the Actor Model.
Patterns:
Ask
The Ask pattern allows values to be sent by actors to outside of the actor system. The value is delivered as a Future
.
Let's look at how this works:
Cargo.toml
:
[]
= "0.3.0"
= "0.3.0"
main.rs
:
use RemoteHandle;
use *;
;
In the background Ask sets up a temporary intermediate actor that lives for the lifetime of the ask. Other actors see this temporary actor as the sender
and can send a message back to it. When the temporary ask actor receives a message it fulfills the outstanding future and performs a stop
on itself to cleanup.
Ask is particularly useful when you have part of an application that runs outside of the actor system, or in another actor system, such as a web server (e.g. Hyper) serving API requests. The resulting future can then be chained as part of the future stack.
Transform
Transform makes changing actor behavior based on its current state easier to reason about. Since actors maintain state, and indeed is a primary concern, being able to handle messages differently based on that state is important. The Transform pattern separates message handling by dedicating a receive function per state. This saves excessive match
ing to handle several possible states, i.e. handling behavior is pre-empted at the time of state change instead of on each message receive.
!!! info
If you're familair with Akka on the JVM, transform
resembles become
.
Example:
use *;
The transform!
macro expects the field name of the current receive function on self
to be named rec
. It's easy to use a different name and either use your own macro, or just set the fuction using standard code. The advantage of transform!
is that it is easy to read and identify when transformation is happening since it is distinct from standard code.