1. Building blocks
  2. State machines

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
Rendering diagram…

​
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)
OptionMeaning
initial=TrueWhere the machine starts. Exactly one state.
final=TrueWhere it ends. Nothing leaves a final state.
defer=[...]Events to keep for later instead of dropping them while in this state.

​
Transitions

WriteThe machine moves when
a.on("approved") >> bAn event named approved arrives
a.on("approved", payload=Approved) >> bThe same, and the event carries data
a.after(timedelta(days=3)) >> bIt 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 objectUse
m.stateThe current state
m.historyEvery transition so far
m.send(name, payload)Deliver an event
m.advance_time(timedelta(...))Fire timers without waiting