2022-11-10 07:48:31 +01:00
|
|
|
from typing import Any, Callable, ClassVar, Dict, List, Optional, Set, Tuple, Type
|
2022-11-09 07:06:29 +01:00
|
|
|
|
|
|
|
|
|
|
|
class StateGraph:
|
|
|
|
"""
|
|
|
|
Represents a graph of possible states and transitions to attempt on them.
|
|
|
|
Does not support subclasses of existing graphs yet.
|
|
|
|
"""
|
|
|
|
|
|
|
|
states: ClassVar[Dict[str, "State"]]
|
2022-11-10 06:29:33 +01:00
|
|
|
choices: ClassVar[List[Tuple[object, str]]]
|
2022-11-09 07:06:29 +01:00
|
|
|
initial_state: ClassVar["State"]
|
|
|
|
terminal_states: ClassVar[Set["State"]]
|
2022-11-16 02:30:30 +01:00
|
|
|
automatic_states: ClassVar[Set["State"]]
|
2022-11-09 07:06:29 +01:00
|
|
|
|
|
|
|
def __init_subclass__(cls) -> None:
|
|
|
|
# Collect state memebers
|
|
|
|
cls.states = {}
|
|
|
|
for name, value in cls.__dict__.items():
|
|
|
|
if name in ["__module__", "__doc__", "states"]:
|
|
|
|
pass
|
|
|
|
elif name in ["initial_state", "terminal_states", "choices"]:
|
|
|
|
raise ValueError(f"Cannot name a state {name} - this is reserved")
|
|
|
|
elif isinstance(value, State):
|
|
|
|
value._add_to_graph(cls, name)
|
|
|
|
elif callable(value) or isinstance(value, classmethod):
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
raise ValueError(
|
|
|
|
f"Graph has item {name} of unallowed type {type(value)}"
|
|
|
|
)
|
|
|
|
# Check the graph layout
|
|
|
|
terminal_states = set()
|
2022-11-16 02:30:30 +01:00
|
|
|
automatic_states = set()
|
2022-11-09 07:06:29 +01:00
|
|
|
initial_state = None
|
|
|
|
for state in cls.states.values():
|
2022-11-10 07:48:31 +01:00
|
|
|
# Check for multiple initial states
|
2022-11-09 07:06:29 +01:00
|
|
|
if state.initial:
|
|
|
|
if initial_state:
|
|
|
|
raise ValueError(
|
|
|
|
f"The graph has more than one initial state: {initial_state} and {state}"
|
|
|
|
)
|
|
|
|
initial_state = state
|
2022-11-10 07:48:31 +01:00
|
|
|
# Collect terminal states
|
2022-11-09 07:06:29 +01:00
|
|
|
if state.terminal:
|
2022-11-11 07:42:43 +01:00
|
|
|
state.externally_progressed = True
|
2022-11-09 07:06:29 +01:00
|
|
|
terminal_states.add(state)
|
2022-11-10 07:48:31 +01:00
|
|
|
# Ensure they do NOT have a handler
|
|
|
|
try:
|
|
|
|
state.handler
|
|
|
|
except AttributeError:
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
raise ValueError(
|
|
|
|
f"Terminal state '{state}' should not have a handler method ({state.handler_name})"
|
|
|
|
)
|
|
|
|
else:
|
2022-11-11 07:42:43 +01:00
|
|
|
# Ensure non-terminal/manual states have a try interval and a handler
|
|
|
|
if not state.externally_progressed:
|
|
|
|
if not state.try_interval:
|
|
|
|
raise ValueError(
|
|
|
|
f"State '{state}' has no try_interval and is not terminal or manual"
|
|
|
|
)
|
|
|
|
try:
|
|
|
|
state.handler
|
|
|
|
except AttributeError:
|
|
|
|
raise ValueError(
|
|
|
|
f"State '{state}' does not have a handler method ({state.handler_name})"
|
|
|
|
)
|
2022-11-16 02:30:30 +01:00
|
|
|
automatic_states.add(state)
|
2022-11-09 07:06:29 +01:00
|
|
|
if initial_state is None:
|
|
|
|
raise ValueError("The graph has no initial state")
|
|
|
|
cls.initial_state = initial_state
|
|
|
|
cls.terminal_states = terminal_states
|
2022-11-16 02:30:30 +01:00
|
|
|
cls.automatic_states = automatic_states
|
2022-11-09 07:06:29 +01:00
|
|
|
# Generate choices
|
2022-11-10 07:48:31 +01:00
|
|
|
cls.choices = [(name, name) for name in cls.states.keys()]
|
2022-11-09 07:06:29 +01:00
|
|
|
|
|
|
|
|
|
|
|
class State:
|
|
|
|
"""
|
|
|
|
Represents an individual state
|
|
|
|
"""
|
|
|
|
|
2022-11-10 07:48:31 +01:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
try_interval: Optional[float] = None,
|
|
|
|
handler_name: Optional[str] = None,
|
2022-11-11 07:42:43 +01:00
|
|
|
externally_progressed: bool = False,
|
2022-11-10 07:48:31 +01:00
|
|
|
):
|
2022-11-09 07:06:29 +01:00
|
|
|
self.try_interval = try_interval
|
2022-11-10 07:48:31 +01:00
|
|
|
self.handler_name = handler_name
|
2022-11-11 07:42:43 +01:00
|
|
|
self.externally_progressed = externally_progressed
|
2022-11-09 07:06:29 +01:00
|
|
|
self.parents: Set["State"] = set()
|
2022-11-10 07:48:31 +01:00
|
|
|
self.children: Set["State"] = set()
|
2022-11-09 07:06:29 +01:00
|
|
|
|
2022-11-10 06:29:33 +01:00
|
|
|
def _add_to_graph(self, graph: Type[StateGraph], name: str):
|
2022-11-09 07:06:29 +01:00
|
|
|
self.graph = graph
|
|
|
|
self.name = name
|
|
|
|
self.graph.states[name] = self
|
2022-11-10 07:48:31 +01:00
|
|
|
if self.handler_name is None:
|
|
|
|
self.handler_name = f"handle_{self.name}"
|
2022-11-09 07:06:29 +01:00
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
return f"<State {self.name}>"
|
|
|
|
|
2022-11-10 07:48:31 +01:00
|
|
|
def __eq__(self, other):
|
|
|
|
if isinstance(other, State):
|
|
|
|
return self is other
|
|
|
|
return self.name == other
|
2022-11-09 07:06:29 +01:00
|
|
|
|
2022-11-10 07:48:31 +01:00
|
|
|
def __hash__(self):
|
|
|
|
return hash(id(self))
|
2022-11-09 07:06:29 +01:00
|
|
|
|
2022-11-10 07:48:31 +01:00
|
|
|
def transitions_to(self, other: "State"):
|
|
|
|
self.children.add(other)
|
|
|
|
other.parents.add(other)
|
2022-11-09 07:06:29 +01:00
|
|
|
|
|
|
|
@property
|
|
|
|
def initial(self):
|
|
|
|
return not self.parents
|
|
|
|
|
|
|
|
@property
|
|
|
|
def terminal(self):
|
|
|
|
return not self.children
|
|
|
|
|
2022-11-10 07:48:31 +01:00
|
|
|
@property
|
|
|
|
def handler(self) -> Callable[[Any], Optional[str]]:
|
2022-11-11 07:42:43 +01:00
|
|
|
# Retrieve it by name off the graph
|
2022-11-10 07:48:31 +01:00
|
|
|
if self.handler_name is None:
|
|
|
|
raise AttributeError("No handler defined")
|
|
|
|
return getattr(self.graph, self.handler_name)
|