xtr_workflow ¶
Move objects through workflows and state machines.
A definition names the places an object can be in and the transitions that move it between them. In a workflow the object can sit in several places at once, and a transition consumes and produces weighted tokens; a state machine keeps it in exactly one place. Every step dispatches an event, so listeners can block a transition or react to it. Definitions are built in code, read from configuration or declared on a class, and dumped as Graphviz, PlantUML or Mermaid diagrams.
Arc
dataclass
¶
How many tokens a transition takes from one place, or puts in it.
On the way in, an arc's weight is both what the place must hold for the transition to be enabled and what applying it takes away; on the way out, it is what applying it puts in. A transition given a bare place name weighs it 1, which is all a state machine ever uses.
Attributes:
Definition ¶
Definition(places: Sequence[str], transitions: Sequence[Transition], initial_places: str | Sequence[str] | None = None, metadata_store: MetadataStoreInterface | None = None)
The places a subject can be in, and the transitions that move it between them.
A place a transition leaves or enters is a place of the definition even when it is not among the places given, so no transition leads nowhere. Places keep the order they first appear in — those given, then those the transitions bring — which is the order a dump draws them in.
A subject starts in the initial places, the first place unless told otherwise; a definition with no place has none. Nothing changes once it is built: what it returns is a copy.
Define places and transitions, a subject starting in initial_places.
Parameters:
-
places(Sequence[str]) –The places, in the order they are drawn.
-
transitions(Sequence[Transition]) –The transitions; a place one leaves or enters that is not among
placesis added after them. -
initial_places(str | Sequence[str] | None, default:None) –The place, or places, a subject starts in; the first place when
Noneor empty. -
metadata_store(MetadataStoreInterface | None, default:None) –Where the metadata of the workflow, of its places and of its transitions is read; an empty in-memory store when
None.
Raises:
-
LogicError–If an initial place is not a place of the definition.
get_initial_places ¶
Return the places a subject starts in, empty when there is no place.
get_places ¶
Return every place, keyed by its own name, in the order they first appeared.
Keyed so that a place can be looked up as well as listed.
get_transitions ¶
Return the transitions, in the order they were given.
get_metadata_store ¶
Return where the metadata of the workflow, its places and its transitions is read.
DefinitionBuilder ¶
Assembles a definition a step at a time, for code that finds its parts as it goes.
Every step returns the builder, so steps chain, and :meth:build can be
called as often as needed: each call builds a new definition from what
the builder holds then. The builder checks nothing itself; the definition
does, when it is built.
Start with places and transitions, as if each was added in turn.
build ¶
Build the definition of what the builder holds.
Raises:
-
LogicError–If an initial place is not a place of the definition.
clear ¶
Forget every place, transition, initial place and metadata store, to start over.
set_initial_places ¶
Start a subject in initial_places; None or empty starts it in the first place.
Set them once the places are added: adding the first place makes it the initial place, over any set before.
add_place ¶
Add place; the first place added is the initial place until told otherwise.
add_transitions ¶
Add each of transitions, in order.
add_transition ¶
Add transition; the places it leaves or enters become places when it is built.
set_metadata_store ¶
Read the definition's metadata from metadata_store instead of an empty store.
DumperInterface ¶
Bases: Protocol
Writes a definition out as the source of a diagram a drawing tool renders.
Each dumper speaks one diagram language; the options it reads are its own, and it ignores those it does not know, so one set of options can be handed to whichever dumper was picked.
dump ¶
dump(definition: Definition, marking: Marking | None = None, options: Mapping[str, object] | None = None) -> str
Return the diagram source of definition.
Parameters:
-
definition(Definition) –The places and transitions to draw.
-
marking(Marking | None, default:None) –Where a subject is, highlighted on the diagram; nothing is highlighted when
None. -
options(Mapping[str, object] | None, default:None) –What the dumper reads to style the diagram.
Marking ¶
How many tokens each place holds: where a subject is.
A place is in the marking while it holds a token, and leaves it with its last one. A state machine's marking is one token in one place; a workflow's can spread over several places, and pile several tokens in one. Places are kept in the order they were first marked.
The marking a workflow returns from applying a transition also carries the context the transition ran with.
Mark each of places with its number of tokens.
Parameters:
-
places(Mapping[str, int] | None, default:None) –The number of tokens by place name, each at least 1.
Raises:
-
InvalidArgumentError–If a number of tokens is below 1.
mark ¶
Put token_count tokens in place, on top of those it holds.
Raises:
-
InvalidArgumentError–If
token_countis below 1.
unmark ¶
Take token_count tokens from place; taking its last unmarks it.
Raises:
-
InvalidArgumentError–If
token_countis below 1,placeis not marked, or it holds fewer thantoken_counttokens.
get_token_count ¶
Return the number of tokens place holds, 0 when it is not marked.
get_places ¶
Return the number of tokens of every marked place, in the order they were marked.
A copy: changing it leaves the marking alone, so a count only ever
changes through :meth:mark and :meth:unmark, which keep it above 0.
set_context ¶
Keep the context the transition that produced this marking ran with.
For the workflow, once it has applied a transition; nothing else is meant to call it.
get_context ¶
Return the context the last transition applied ran with, empty before any.
A copy, like :meth:get_places.
MarkingStoreInterface ¶
Bases: Protocol
Reads the marking a subject is in, and records the one a transition moved it to.
It translates between a workflow's :class:~xtr_workflow.marking.Marking
and whatever keeps it — the subject's own attribute, or something else
entirely: a session, a cache, a remote service. That is why both methods
are coroutines: a store may have to wait on what keeps the marking.
MetadataStoreInterface ¶
Bases: Protocol
Reads the metadata of a workflow, of its places and of its transitions.
Metadata is what a definition carries for whoever reads it — a title a dump shows, a flag a listener checks — and moving a subject never looks at it. Each subject's metadata is a mapping of entries by name, empty for a subject that has none.
get_workflow_metadata ¶
Return the metadata of the workflow itself.
get_place_metadata ¶
Return the metadata of place, empty when it has none.
get_transition_metadata ¶
Return the metadata of transition, empty when it has none.
A transition is known by its identity, so one built alike is another transition, with metadata of its own.
get_metadata ¶
Return one entry of the metadata of the workflow, of a place or of a transition.
For a reader that wants a single entry and knows what it is about, whatever that is: the subject picks which of the three getters is read.
Parameters:
-
key(str) –The name of the entry.
-
subject(str | Transition | None, default:None) –Nonefor the workflow, a place name for that place, or a transition for that transition.
Returns:
-
object | None–The entry, or
Nonewhen the subject's metadata has none by that name.
Raises:
-
InvalidArgumentError–If
subjectis none of the three.
Registry ¶
Finds the workflows that move a subject, among those added to it.
Each workflow is added with a support strategy telling which subjects it moves. One subject can move through several workflows — a post can be published and moderated — so asking by subject alone finds one only while no other supports the subject too; asking by name as well tells them apart.
Errors name a subject's class by its bare name, as every error of this
package names a class: object for a plain object().
Nothing it does asks a listener, so nothing in it is a coroutine.
Hold no workflow until one is added.
add_workflow ¶
add_workflow(workflow: WorkflowInterface, support_strategy: WorkflowSupportStrategyInterface) -> None
Add workflow, for the subjects support_strategy supports.
has ¶
get ¶
Return the one workflow supporting subject.
Parameters:
-
subject(object) –The object to move.
-
workflow_name(str | None, default:None) –The name the workflow must have; any when
None.
Raises:
-
InvalidArgumentError–If no workflow supports
subject, or several do andworkflow_namedoes not pick one out.
all ¶
Return every workflow supporting subject, in the order they were added.
StateMachine ¶
StateMachine(definition: Definition, marking_store: MarkingStoreInterface | None = None, dispatcher: EventDispatcherInterface | None = None, name: str = 'unnamed', events_to_dispatch: Sequence[str] | None = None)
Bases: Workflow
A workflow whose subject is in exactly one place at a time.
It moves subjects as a workflow does; what differs is where it keeps them: unless given a store, the subject keeps the name of its one place rather than a dict of places. Several transitions may share a name — one for each place it leaves — and applying the name applies the one the subject's place enables.
Move subjects through definition, each keeping the name of its place.
Parameters:
-
definition(Definition) –The places and transitions.
-
marking_store(MarkingStoreInterface | None, default:None) –Where each subject's marking is kept; on the subject, as the name of its place, when
None. -
dispatcher(EventDispatcherInterface | None, default:None) –Where the events go; none is dispatched without one.
-
name(str, default:'unnamed') –The name of the state machine, narrowing the events' names.
-
events_to_dispatch(Sequence[str] | None, default:None) –Which events go out besides the guard, as :class:
~xtr_workflow.workflow.Workflowreads it.
Raises:
-
InvalidArgumentError–If
events_to_dispatchmixes listed and!-prefixed entries, or blocks the guard.
WorkflowSupportStrategyInterface ¶
Bases: Protocol
Tells whether a workflow moves a subject.
A workflow takes any object; which objects it is meant for is the application's to say, and a registry asks the strategy each workflow was added with to find the workflow of a subject.
Deciding reads the workflow and the subject alone, without asking a listener, so it is not a coroutine: a workflow is looked up wherever a subject is at hand.
supports ¶
Tell whether workflow moves subject.
Transition ¶
A named move that takes tokens from some places and puts tokens in others.
Each place it leaves or enters is an :class:Arc; a bare place name is
an arc of weight 1.
Several transitions may share a name — a state machine needs one for each pair of places it moves between, and a workflow asked to apply a name applies every enabled transition of that name — so a transition is known by its identity, not by its name or its places: two transitions built alike are two transitions, each with its own metadata.
Name a move from froms to tos.
Parameters:
-
name(str) –The name the transition is applied by.
-
froms(str | Arc | Sequence[str | Arc]) –The places it takes tokens from: one place name or arc, or a sequence of them.
-
tos(str | Arc | Sequence[str | Arc]) –The places it puts tokens in, likewise.
Raises:
-
TypeError–If an element of
fromsortosis neither a place name nor an arc. -
InvalidArgumentError–If a place name is empty.
get_froms ¶
Return the places the transition takes tokens from, in the order given.
Parameters:
-
as_arc(bool, default:False) –Return the arcs, weights included, rather than the place names.
TransitionBlocker ¶
A reason a transition cannot be applied to a subject, in words and as a code.
The message is for a person; the code — usually a UUID — is for code that has to tell one reason from another without parsing the message. The parameters carry whatever the condition that blocked was about, so a reader can say more than the message does: for "the distance must be over 5 miles", the 5.
Give the reason message, known to code as code.
Parameters:
-
message(str) –Why the transition is blocked, for a person.
-
code(str) –Which reason it is, for code; usually a UUID.
-
parameters(Mapping[str, object] | None, default:None) –The values the condition that blocked was about.
BLOCKED_BY_MARKING
class-attribute
instance-attribute
¶
The marking does not hold the tokens the transition takes.
BLOCKED_BY_EXPRESSION_GUARD_LISTENER
class-attribute
instance-attribute
¶
A guard configured on the transition refused it.
UNKNOWN
class-attribute
instance-attribute
¶
A listener blocked the transition without giving a code of its own.
create_blocked_by_marking
staticmethod
¶
Block a transition the subject is not in the places for.
A state machine's subject is not in the place the transition leaves; a workflow's lacks a token in one of the places it leaves, or enough of them.
create_blocked_by_expression_guard_listener
staticmethod
¶
Block a transition its configured guard refused.
Parameters:
-
expression(str) –Names the guard that refused it.
create_unknown
staticmethod
¶
Block a transition for a reason no code was given for.
Without a message, the reason names the class of the guard that blocked, when there is one, so whoever reads it knows where to look.
Parameters:
get_parameters ¶
Return the values the condition that blocked was about; a copy.
TransitionBlockerList ¶
Every reason a transition cannot be applied to a subject, in the order they were given.
Empty means nothing blocks it. Iterating it walks the blockers it held when the walk began, so a guard adding one meanwhile is not seen twice.
Hold blockers, in order.
DefinitionValidatorInterface ¶
Bases: Protocol
Checks that a definition can run as the workflow it is meant for.
A definition takes any places and any transitions; whether they can run depends on what runs them — a state machine moves its subject from one place to one place, a marking store keeping one place per subject has nowhere to put a second. A validator holds a definition to those rules before a workflow runs it, so a mistake shows where the definition is made rather than halfway through a move.
Checking reads nothing but the definition, so it is not a coroutine: a definition is checked wherever it is built, the container's build included.
validate ¶
Refuse definition unless the workflow name can run it.
Parameters:
-
definition(Definition) –The definition to check.
-
name(str) –The name of the workflow it defines, quoted in the error.
Raises:
-
InvalidDefinitionError–If the definition breaks one of the validator's rules.
Workflow ¶
Workflow(definition: Definition, marking_store: MarkingStoreInterface | None = None, dispatcher: EventDispatcherInterface | None = None, name: str = 'unnamed', events_to_dispatch: Sequence[str] | None = None)
Bases: WorkflowInterface
Moves a subject through a definition: a Petri net, where it can be in several places.
A transition is enabled when every place it leaves holds the tokens it takes, and no guard listener blocks it. Applying a name applies every transition of that name enabled at that moment, so a subject spread over several places can move out of all of them at once.
Each step goes out as an event, under three names — for every workflow,
for this one, and for the place or transition concerned — so listeners
hear exactly what they care about: guard before a transition is
applied or reported enabled, then, while applying it, leave,
transition (where a listener may replace the call's context),
enter, entered, completed and announce. Without a
dispatcher, nothing is asked and nothing told.
One transition is applied at a time per subject object: a second
apply of the same subject waits for the first, then weighs the
marking the first left — while a listener of the move applying to the
same subject goes straight through. That keeps the tasks of one process
apart; two processes, or two requests each loading the subject into an
object of its own, are kept apart only by a marking store implementing
:class:~xtr_workflow.marking_store.CompareAndSetMarkingStoreInterface,
which a transition then writes through. A write it refuses fails the
transition after leave, transition and enter went out; they
are not taken back.
Move subjects through definition, keeping their markings in marking_store.
Parameters:
-
definition(Definition) –The places and transitions.
-
marking_store(MarkingStoreInterface | None, default:None) –Where each subject's marking is kept; on the subject, as a dict of places, when
None. -
dispatcher(EventDispatcherInterface | None, default:None) –Where the events go; none is dispatched without one.
-
name(str, default:'unnamed') –The name of the workflow, narrowing the events' names.
-
events_to_dispatch(Sequence[str] | None, default:None) –Which of the :class:
WorkflowEventsgo out besides the guard, which always does: every one whenNone, none when empty, only those listed, or — when every entry starts with!— every one but those listed, so an event added later goes out too.
Raises:
-
InvalidArgumentError–If
events_to_dispatchmixes listed and!-prefixed entries, or blocks the guard.
DISABLE_LEAVE_EVENT
class-attribute
instance-attribute
¶
A true value under this context key keeps the call from dispatching leave.
DISABLE_TRANSITION_EVENT
class-attribute
instance-attribute
¶
A true value under this context key keeps the call from dispatching transition.
DISABLE_ENTER_EVENT
class-attribute
instance-attribute
¶
A true value under this context key keeps the call from dispatching enter.
DISABLE_ENTERED_EVENT
class-attribute
instance-attribute
¶
A true value under this context key keeps the call from dispatching entered.
DISABLE_COMPLETED_EVENT
class-attribute
instance-attribute
¶
A true value under this context key keeps the call from dispatching completed.
DISABLE_ANNOUNCE_EVENT
class-attribute
instance-attribute
¶
A true value under this context key keeps the call from dispatching announce.
DEFAULT_INITIAL_CONTEXT
class-attribute
instance-attribute
¶
The context of the entered event putting a subject in its initial places, when the
call gave none — so a listener can tell a subject's first marking from a move.
WorkflowEvents ¶
The name every workflow event goes out under for every workflow, in the order they come.
A workflow dispatches each event under this name, then narrowed to its
own name and to a place or transition (get_name on each event class
builds those). :attr:ALIASES lets a listener declare the event class
instead of the name.
GUARD
class-attribute
instance-attribute
¶
Listeners may block a transition; carries a :class:GuardEvent.
LEAVE
class-attribute
instance-attribute
¶
The subject is leaving a place; carries a :class:LeaveEvent.
TRANSITION
class-attribute
instance-attribute
¶
A transition is being applied; carries a :class:TransitionEvent.
ENTER
class-attribute
instance-attribute
¶
The subject is entering a place; carries an :class:EnterEvent.
ENTERED
class-attribute
instance-attribute
¶
The subject has entered a place; carries an :class:EnteredEvent.
COMPLETED
class-attribute
instance-attribute
¶
A transition has been applied; carries a :class:CompletedEvent.
ANNOUNCE
class-attribute
instance-attribute
¶
A transition is enabled after the move; carries an :class:AnnounceEvent.
ALIASES
class-attribute
instance-attribute
¶
ALIASES: Final[Mapping[type[Event], str]] = MappingProxyType({GuardEvent: GUARD, LeaveEvent: LEAVE, TransitionEvent: TRANSITION, EnterEvent: ENTER, EnteredEvent: ENTERED, CompletedEvent: COMPLETED, AnnounceEvent: ANNOUNCE})
Each event class, mapped to the name it is dispatched under for every workflow.
WorkflowInterface ¶
Bases: Protocol
Applies transitions to a subject, and tells which ones are enabled or blocked.
Everything that may ask listeners — reading a marking for the first time, checking or applying a transition — is a coroutine, because the events it dispatches are awaited; what only reads the workflow itself is not.
get_marking
async
¶
Return the marking subject is in.
A subject in no place yet is put in the initial places first, and an
entered event announces it.
Parameters:
-
subject(object) –The object the workflow moves.
-
context(Mapping[str, object] | None, default:None) –The context of that
enteredevent.
Raises:
-
LogicError–If the subject is in no place and the definition has no initial place, or it is in a place the definition lacks.
can
async
¶
Tell whether a transition named transition_name is enabled for subject.
build_transition_blocker_list
async
¶
Return why the transition named transition_name is blocked; empty when it is not.
Raises:
-
UndefinedTransitionError–If no transition has that name.
apply
async
¶
apply(subject: object, transition_name: str, context: Mapping[str, object] | None = None) -> Marking
Apply every enabled transition named transition_name to subject.
Parameters:
-
subject(object) –The object to move.
-
transition_name(str) –The name of the transition.
-
context(Mapping[str, object] | None, default:None) –Handed to every event and to the marking store.
Returns:
-
Marking–The marking the subject is in afterwards.
Raises:
-
LogicError–If the transition cannot be applied — it is undefined, or blocked.
get_enabled_transitions
async
¶
Return every transition enabled for subject.
get_enabled_transition
async
¶
Return the first transition named name enabled for subject, or None.
get_definition ¶
Return the places and transitions the workflow moves subjects through.
get_marking_store ¶
Return where the workflow reads and writes each subject's marking.
get_metadata_store ¶
Return where the metadata of the workflow, its places and its transitions is read.
WorkflowTrait ¶
Exposes every method of a workflow on the class that mixes this in.
Meant for a class decorated with @as_workflow: the class declares the
workflow and its listeners, and, once handed the workflow built from that
declaration, answers for it — so the code moving subjects depends on one
class carrying both its own helpers and the workflow's methods. The class
keeps any constructor it likes; the workflow comes through
:meth:set_workflow, which the workflow bundle calls after building it.
The workflow is kept under a name-mangled attribute, so a class mixing
this in is free to use _workflow for anything of its own.
get_marking
async
¶
Return the marking subject is in; see :meth:WorkflowInterface.get_marking.
can
async
¶
Tell whether a transition named transition_name is enabled for subject.
build_transition_blocker_list
async
¶
Return why the transition named transition_name is blocked; empty when it is not.
apply
async
¶
apply(subject: object, transition_name: str, context: Mapping[str, object] | None = None) -> Marking
Apply every enabled transition named transition_name to subject.
get_enabled_transitions
async
¶
Return every transition enabled for subject.
get_enabled_transition
async
¶
Return the first transition named name enabled for subject, or None.
get_definition ¶
Return the places and transitions the workflow moves subjects through.
get_marking_store ¶
Return where the workflow reads and writes each subject's marking.
get_metadata_store ¶
Return where the metadata of the workflow, its places and its transitions is read.