Answers as Values
Asking an actor something can go wrong in more ways than calling a function: the actor may refuse, fail on the message, have stopped, or take too long. MLambda answers every ask with a value that says which:
ask :: Address a -> (Reply r -> Message a) -> Either Fault r
Right r is the answer. Left (Fault kind detail) is everything else, and the kind says what:
| Kind | Why |
|---|---|
your own (InsufficientFunds) |
The actor refused: refuse r (Fault kind detail) |
your own (Glitch) |
The actor failed on the message: failWith kind detail |
ActorStopped |
The actor had stopped, or stopped before answering |
Timeout |
No answer within askWithin’s time |
UnknownRoute |
No host runs the route asked |
CircuitBreakerOpen |
A breaker refused the call without making it |
No exceptions to catch
An ask never throws. The caller matches the answer, and the compiler sees the Either, so a failure cannot be
forgotten by accident:
case askWithin 500 account (\r -> Withdraw 30 r) of
Right balance -> showInt balance
Left (Fault "InsufficientFunds" owner) -> strcat "not enough money for " owner
Left (Fault "Timeout" detail) -> "the account is busy"
Left (Fault kind detail) -> kind
Why not futures or observables
An ask in MLambda simply waits. Every actor and every ask runs on a fiber of the runtime’s scheduler, and a fiber that waits is parked while the others run, so waiting is cheap. Code reads in order, without callbacks, and composing asks is composing functions:
transfer :: Address Account -> Address Account -> Int -> Either Fault Int
transfer from to n = case ask from (\r -> Withdraw n r) of
Left fault -> Left fault
Right left -> case ask to (\r -> Deposit n r) of
Left fault -> case ask from (\r -> Deposit n r) of -- put the money back
_ -> Left fault
Right _ -> Right left
For more steps, compensation and retries, a saga does the same with less code.
Refusing and failing are different
A refusal is an answer: the actor decided the request cannot be served and goes on. A failure is a fault in the actor: its asker is told, and its parent decides whether it resumes, restarts or stops (see Supervision). Refuse what is the caller’s problem; fail on what is the actor’s.