|
| 1 | +from typing import TYPE_CHECKING |
| 2 | +from typing import Any |
| 3 | +from typing import Dict |
| 4 | +from typing import Mapping |
| 5 | +from typing import MutableSet |
| 6 | + |
| 7 | +from .exceptions import InvalidStateValue |
| 8 | +from .i18n import _ |
| 9 | +from .orderedset import OrderedSet |
| 10 | + |
| 11 | +_SENTINEL = object() |
| 12 | + |
| 13 | +if TYPE_CHECKING: |
| 14 | + from .state import State |
| 15 | + |
| 16 | + |
| 17 | +class Configuration: |
| 18 | + """Encapsulates the dual representation of the active state configuration. |
| 19 | +
|
| 20 | + Internally, ``current_state_value`` is either a scalar (single active state) |
| 21 | + or an ``OrderedSet`` (parallel regions). This class hides that detail behind |
| 22 | + a uniform interface for reading, mutating, and caching the resolved |
| 23 | + ``OrderedSet[State]``. |
| 24 | + """ |
| 25 | + |
| 26 | + __slots__ = ( |
| 27 | + "_instance_states", |
| 28 | + "_model", |
| 29 | + "_state_field", |
| 30 | + "_states_map", |
| 31 | + "_cached", |
| 32 | + "_cached_value", |
| 33 | + ) |
| 34 | + |
| 35 | + def __init__( |
| 36 | + self, |
| 37 | + instance_states: "Mapping[str, State]", |
| 38 | + model: Any, |
| 39 | + state_field: str, |
| 40 | + states_map: "Dict[Any, State]", |
| 41 | + ): |
| 42 | + self._instance_states = instance_states |
| 43 | + self._model = model |
| 44 | + self._state_field = state_field |
| 45 | + self._states_map = states_map |
| 46 | + self._cached: "OrderedSet[State] | None" = None |
| 47 | + self._cached_value: Any = _SENTINEL |
| 48 | + |
| 49 | + # -- Raw value (persisted on the model) ------------------------------------ |
| 50 | + |
| 51 | + @property |
| 52 | + def value(self) -> Any: |
| 53 | + """The raw state value stored on the model (scalar or ``OrderedSet``).""" |
| 54 | + return getattr(self._model, self._state_field, None) |
| 55 | + |
| 56 | + @value.setter |
| 57 | + def value(self, val: Any): |
| 58 | + self._invalidate() |
| 59 | + if val is not None and not isinstance(val, MutableSet) and val not in self._states_map: |
| 60 | + raise InvalidStateValue(val) |
| 61 | + setattr(self._model, self._state_field, val) |
| 62 | + |
| 63 | + @property |
| 64 | + def values(self) -> OrderedSet[Any]: |
| 65 | + """The set of raw state values currently active.""" |
| 66 | + v = self.value |
| 67 | + if isinstance(v, OrderedSet): |
| 68 | + return v |
| 69 | + return OrderedSet([v]) |
| 70 | + |
| 71 | + # -- Resolved states ------------------------------------------------------- |
| 72 | + |
| 73 | + @property |
| 74 | + def states(self) -> "OrderedSet[State]": |
| 75 | + """The set of currently active :class:`State` instances (cached).""" |
| 76 | + csv = self.value |
| 77 | + if self._cached is not None and self._cached_value is csv: |
| 78 | + return self._cached |
| 79 | + if csv is None: |
| 80 | + return OrderedSet() |
| 81 | + |
| 82 | + instance_states = self._instance_states |
| 83 | + if not isinstance(csv, MutableSet): |
| 84 | + result = OrderedSet([instance_states[self._states_map[csv].id]]) |
| 85 | + else: |
| 86 | + result = OrderedSet([instance_states[self._states_map[v].id] for v in csv]) |
| 87 | + |
| 88 | + self._cached = result |
| 89 | + self._cached_value = csv |
| 90 | + return result |
| 91 | + |
| 92 | + @states.setter |
| 93 | + def states(self, new_configuration: "OrderedSet[State]"): |
| 94 | + if len(new_configuration) == 0: |
| 95 | + self.value = None |
| 96 | + elif len(new_configuration) == 1: |
| 97 | + self.value = next(iter(new_configuration)).value |
| 98 | + else: |
| 99 | + self.value = OrderedSet(s.value for s in new_configuration) |
| 100 | + |
| 101 | + # -- Incremental mutation (used by the engine) ----------------------------- |
| 102 | + |
| 103 | + def add(self, state: "State"): |
| 104 | + """Add *state* to the configuration, maintaining the dual representation.""" |
| 105 | + csv = self.value |
| 106 | + if csv is None: |
| 107 | + self.value = state.value |
| 108 | + elif isinstance(csv, MutableSet): |
| 109 | + csv.add(state.value) |
| 110 | + self._invalidate() |
| 111 | + else: |
| 112 | + self.value = OrderedSet([csv, state.value]) |
| 113 | + |
| 114 | + def discard(self, state: "State"): |
| 115 | + """Remove *state* from the configuration, normalizing back to scalar.""" |
| 116 | + csv = self.value |
| 117 | + if isinstance(csv, MutableSet): |
| 118 | + csv.discard(state.value) |
| 119 | + self._invalidate() |
| 120 | + if len(csv) == 1: |
| 121 | + self.value = next(iter(csv)) |
| 122 | + elif len(csv) == 0: |
| 123 | + self.value = None |
| 124 | + elif csv == state.value: |
| 125 | + self.value = None |
| 126 | + |
| 127 | + # -- Deprecated v2 compat -------------------------------------------------- |
| 128 | + |
| 129 | + @property |
| 130 | + def current_state(self) -> "State | OrderedSet[State]": |
| 131 | + """Resolve the current state with validation. |
| 132 | +
|
| 133 | + Unlike ``states`` (which returns an empty set for ``None``), this |
| 134 | + raises ``InvalidStateValue`` when the value is ``None`` or not |
| 135 | + found in ``states_map`` — matching the v2 ``current_state`` contract. |
| 136 | + """ |
| 137 | + csv = self.value |
| 138 | + if csv is None: |
| 139 | + raise InvalidStateValue( |
| 140 | + csv, |
| 141 | + _( |
| 142 | + "There's no current state set. In async code, " |
| 143 | + "did you activate the initial state? " |
| 144 | + "(e.g., `await sm.activate_initial_state()`)" |
| 145 | + ), |
| 146 | + ) |
| 147 | + try: |
| 148 | + config = self.states |
| 149 | + if len(config) == 1: |
| 150 | + return next(iter(config)) |
| 151 | + return config |
| 152 | + except KeyError as err: |
| 153 | + raise InvalidStateValue(csv) from err |
| 154 | + |
| 155 | + # -- Internal -------------------------------------------------------------- |
| 156 | + |
| 157 | + def _invalidate(self): |
| 158 | + self._cached = None |
| 159 | + self._cached_value = _SENTINEL |
0 commit comments