- Building blocks
- State machines
Building blocks
State machines
A state machine is a long-lived process that moves between states when events arrive.
A workflow runs from start to finish. A state machine waits: it sits in a state, does that state’s work, and moves on when an event or a timer says so. Use one for things that live for days, such as a ticket, an order or a pull request.
import avalanche as ava
class Ticket(ava.BaseInput):
id: int
class Approved(ava.BaseModel):
by: str
@ava.machine(input=Ticket, key=("id",))
def ticket():
pending = ava.state(open_ticket, initial=True)
done = ava.state(close_ticket, final=True)
pending.on("approved", payload=Approved) >> done
States
A state has a name (the variable name) and work: one step or one whole workflow. The work runs each time the machine enters the state.
pending = ava.state(open_ticket, initial=True)
review = ava.state(review_flow)
done = ava.state(close_ticket, final=True)
| Option | Meaning |
|---|---|
initial=True | Where the machine starts. Exactly one state. |
final=True | Where it ends. Nothing leaves a final state. |
defer=[...] | Events to keep for later instead of dropping them while in this state. |
Transitions
| Write | The machine moves when |
|---|---|
a.on("approved") >> b | An event named approved arrives |
a.on("approved", payload=Approved) >> b | The same, and the event carries data |
a.after(timedelta(days=3)) >> b | It has been in a for three days |
A state’s own work can also decide where to go, by returning an event:
@ava.step(emits=("accepted", "rejected"))
def triage(t: Ticket):
return ava.event("accepted" if t.id % 2 else "rejected", t.id)
Instances and keys
key=("id",) means one machine instance per ticket ID. Starting the machine again with the same
ID returns the existing instance instead of creating a second one.
Send an event
From another workflow:
ticket.send(key, "approved", Approved(by="ana"))
From outside, with the CLI:
ava machine send ticket approved --key id=1 --data '{"by": "ana"}'
Test it
machine.test() runs the machine in memory with fake time.
m = ticket.test(Ticket(id=1))
m.send("approved", Approved(by="ana"))
assert m.state == "done"
| On the test object | Use |
|---|---|
m.state | The current state |
m.history | Every transition so far |
m.send(name, payload) | Deliver an event |
m.advance_time(timedelta(...)) | Fire timers without waiting |
