跳转至

状态

按「作用域 + 键路径」读写状态,支持点分嵌套、变更观察者与持久化。

from zoo_framework.statemachine import StateMachineManager

zoo_framework.statemachine.state_machine_manager.StateMachineManager

State machine manager.

源代码位于: zoo_framework/statemachine/state_machine_manager.py
@process_scoped(thread_safety=ThreadSafety.INSTANCE_GUARANTEED)
class StateMachineManager:
    """State machine manager."""

    def __init__(self):
        """Initialize the state machine manager."""
        # State scope mapping
        self._state_scope_map: ThreadSafeDict[str, StateScope] = ThreadSafeDict()

        # Whether the local store has been loaded
        self._local_store_loaded = False

        # Local store strategy
        self._local_store_strategy = None

        # Local store interval
        self._local_store_interval = 0

    def have_loaded(self):
        """Whether it has been loaded."""
        return self._local_store_loaded

    def load_state_machines(self, state_machine: ThreadSafeDict | dict | None = None) -> None:
        """Load the state machines.

        Restore semantics (adjudicated in change fix-state-restore / #72):
        **whole-table replacement**. The only current consume path is loading
        from disk after the process's first resolution (the instance is
        necessarily empty then), where replacement and merge are equivalent;
        an explicit reload on a non-empty state is a deliberate user action.

        Legacy defect (fixed): what got persisted was the `ThreadSafeDict`
        returned by `get_state_machines()`, and it is **not** a `dict`
        subclass - the old guard `isinstance(state_machine, dict)` was always
        false for the framework's own files, the assignment never ran, yet
        `_local_store_loaded` was set true: the state was never restored and
        the "loaded" illusion blocked retries (see
        tests/test_state_restore.py). The guard now dispatches on the real
        type:

        - `ThreadSafeDict`: restored as-is (the framework's own on-disk form)
        - plain `dict`: wrapped into a `ThreadSafeDict`, so the declared type
          is true on every path (compat entry for old files / manual
          injection; storing a plain dict would blow up `has_key()` at runtime)
        - any other non-None argument: rejected with an explicit `TypeError` -
          silent ignoring is the same family of defect as before; the
          `StateMachineWorker` error path falls back to a fresh state and
          leaves an error log

        Args:
            state_machine: the state scope mapping to restore; None means
                nothing to restore, going straight into new state

        Raises:
            TypeError: the argument is neither None nor a dict/ThreadSafeDict
        """
        if state_machine is not None:
            if isinstance(state_machine, ThreadSafeDict):
                self._state_scope_map = state_machine
            elif isinstance(state_machine, dict):
                self._state_scope_map = ThreadSafeDict(state_machine)
            else:
                raise TypeError(
                    f"the state machine argument must be a dict or ThreadSafeDict, got {type(state_machine).__name__}"
                )
        self._local_store_loaded = True

    def get_and_create_scope(self, scope: str):
        """Get and create the scope."""
        if self._state_scope_map.get(scope) is None:
            self.create_scope(scope)
        return self._state_scope_map[scope]

    def create_scope(self, scope: str):
        """Create the scope."""
        if self._state_scope_map.has_key(scope):
            return
        self._state_scope_map[scope] = StateScope()

    def get_scope_identity(self, scope: str) -> RunIdentity | None:
        """Query the owning run identity of a state scope.

        Ownership is determined by the run that **first wrote** the scope
        (see ``StateScope.set_state_node``). Returns None when the scope does
        not exist or has no identified write yet.

        Args:
            scope: the scope name

        Returns:
            The owning ``RunIdentity``; None when unowned
        """
        state_register = self._state_scope_map.get(scope)
        if state_register is None:
            return None
        return state_register.owner_identity

    def get_scope_session(self, scope: str) -> str | None:
        """Query the owning session identity of a state scope; None when unowned."""
        identity = self.get_scope_identity(scope)
        return identity.session_id if identity is not None else None

    def set_state(self, scope: str, key: str, value):
        """Set the value of a state node."""
        if self._state_scope_map.get(scope) is None:
            self.create_scope(scope)

        state_register = self._state_scope_map[scope]
        state_register.set_state_node(key, value)

    def get_state(self, scope: str, key: str) -> Any:
        """Get the state node."""
        if self._state_scope_map.get(scope) is None:
            return None

        state_register = self._state_scope_map[scope]
        node = state_register.get_state_node(key)
        if None is node:
            return None

        return node.get_value()

    def remove_state(self, scope: str, key: str):
        """Remove the state node."""
        if self._state_scope_map.get(scope) is None:
            return None

        # Fetch once and check: the original code first checked
        # `get_state_node(key) is None` and then fetched **again**, but the map
        # is a ThreadSafeDict - the node could be concurrently removed between
        # the two fetches, so there was a real window (where `node.get_value()`
        # would raise AttributeError). Merging into one fetch removes both the
        # window and the type error.
        state_register: StateScope = self._state_scope_map[scope]
        node = state_register.get_state_node(key)
        if node is None:
            return None

        value = node.get_value()
        state_register.remove_state_node(key)

        # If it is the top node, remove the scope
        if node.is_top():
            self._state_scope_map.pop(scope)

        return value

    def get_state_machines(self):
        """Get the state machines."""
        return self._state_scope_map

    def observe_state(self, scope: str, key: str, effect: Callable):
        """Observe a state node."""
        if self._state_scope_map.get(scope) is None:
            self.create_scope(scope)

        state_register: StateScope = self._state_scope_map[scope]
        state_register.observe_state_node(key, effect)

    def unobserve_state(self, scope: str, key: str, effect: Callable):
        """Remove a state node observer - fixes a memory leak.

        Args:
            scope: the scope name
            key: the state key name
            effect: the observer callback

        Raises:
            KeyError: when the scope or the state does not exist
        """
        if self._state_scope_map.get(scope) is None:
            raise KeyError(f"Scope '{scope}' not found")

        state_register: StateScope = self._state_scope_map[scope]
        state_register.unobserve_state_node(key, effect)

have_loaded

have_loaded()

Whether it has been loaded.

源代码位于: zoo_framework/statemachine/state_machine_manager.py
def have_loaded(self):
    """Whether it has been loaded."""
    return self._local_store_loaded

load_state_machines

load_state_machines(state_machine: ThreadSafeDict | dict | None = None) -> None

Load the state machines.

Restore semantics (adjudicated in change fix-state-restore / #72): whole-table replacement. The only current consume path is loading from disk after the process's first resolution (the instance is necessarily empty then), where replacement and merge are equivalent; an explicit reload on a non-empty state is a deliberate user action.

Legacy defect (fixed): what got persisted was the ThreadSafeDict returned by get_state_machines(), and it is not a dict subclass - the old guard isinstance(state_machine, dict) was always false for the framework's own files, the assignment never ran, yet _local_store_loaded was set true: the state was never restored and the "loaded" illusion blocked retries (see tests/test_state_restore.py). The guard now dispatches on the real type:

  • ThreadSafeDict: restored as-is (the framework's own on-disk form)
  • plain dict: wrapped into a ThreadSafeDict, so the declared type is true on every path (compat entry for old files / manual injection; storing a plain dict would blow up has_key() at runtime)
  • any other non-None argument: rejected with an explicit TypeError - silent ignoring is the same family of defect as before; the StateMachineWorker error path falls back to a fresh state and leaves an error log

参数:

名称 类型 描述 默认
state_machine ThreadSafeDict | dict | None

the state scope mapping to restore; None means nothing to restore, going straight into new state

None

引发:

类型 描述
TypeError

the argument is neither None nor a dict/ThreadSafeDict

源代码位于: zoo_framework/statemachine/state_machine_manager.py
def load_state_machines(self, state_machine: ThreadSafeDict | dict | None = None) -> None:
    """Load the state machines.

    Restore semantics (adjudicated in change fix-state-restore / #72):
    **whole-table replacement**. The only current consume path is loading
    from disk after the process's first resolution (the instance is
    necessarily empty then), where replacement and merge are equivalent;
    an explicit reload on a non-empty state is a deliberate user action.

    Legacy defect (fixed): what got persisted was the `ThreadSafeDict`
    returned by `get_state_machines()`, and it is **not** a `dict`
    subclass - the old guard `isinstance(state_machine, dict)` was always
    false for the framework's own files, the assignment never ran, yet
    `_local_store_loaded` was set true: the state was never restored and
    the "loaded" illusion blocked retries (see
    tests/test_state_restore.py). The guard now dispatches on the real
    type:

    - `ThreadSafeDict`: restored as-is (the framework's own on-disk form)
    - plain `dict`: wrapped into a `ThreadSafeDict`, so the declared type
      is true on every path (compat entry for old files / manual
      injection; storing a plain dict would blow up `has_key()` at runtime)
    - any other non-None argument: rejected with an explicit `TypeError` -
      silent ignoring is the same family of defect as before; the
      `StateMachineWorker` error path falls back to a fresh state and
      leaves an error log

    Args:
        state_machine: the state scope mapping to restore; None means
            nothing to restore, going straight into new state

    Raises:
        TypeError: the argument is neither None nor a dict/ThreadSafeDict
    """
    if state_machine is not None:
        if isinstance(state_machine, ThreadSafeDict):
            self._state_scope_map = state_machine
        elif isinstance(state_machine, dict):
            self._state_scope_map = ThreadSafeDict(state_machine)
        else:
            raise TypeError(
                f"the state machine argument must be a dict or ThreadSafeDict, got {type(state_machine).__name__}"
            )
    self._local_store_loaded = True

get_and_create_scope

get_and_create_scope(scope: str)

Get and create the scope.

源代码位于: zoo_framework/statemachine/state_machine_manager.py
def get_and_create_scope(self, scope: str):
    """Get and create the scope."""
    if self._state_scope_map.get(scope) is None:
        self.create_scope(scope)
    return self._state_scope_map[scope]

create_scope

create_scope(scope: str)

Create the scope.

源代码位于: zoo_framework/statemachine/state_machine_manager.py
def create_scope(self, scope: str):
    """Create the scope."""
    if self._state_scope_map.has_key(scope):
        return
    self._state_scope_map[scope] = StateScope()

get_scope_identity

get_scope_identity(scope: str) -> RunIdentity | None

Query the owning run identity of a state scope.

Ownership is determined by the run that first wrote the scope (see StateScope.set_state_node). Returns None when the scope does not exist or has no identified write yet.

参数:

名称 类型 描述 默认
scope str

the scope name

必需

返回:

类型 描述
RunIdentity | None

The owning RunIdentity; None when unowned

源代码位于: zoo_framework/statemachine/state_machine_manager.py
def get_scope_identity(self, scope: str) -> RunIdentity | None:
    """Query the owning run identity of a state scope.

    Ownership is determined by the run that **first wrote** the scope
    (see ``StateScope.set_state_node``). Returns None when the scope does
    not exist or has no identified write yet.

    Args:
        scope: the scope name

    Returns:
        The owning ``RunIdentity``; None when unowned
    """
    state_register = self._state_scope_map.get(scope)
    if state_register is None:
        return None
    return state_register.owner_identity

get_scope_session

get_scope_session(scope: str) -> str | None

Query the owning session identity of a state scope; None when unowned.

源代码位于: zoo_framework/statemachine/state_machine_manager.py
def get_scope_session(self, scope: str) -> str | None:
    """Query the owning session identity of a state scope; None when unowned."""
    identity = self.get_scope_identity(scope)
    return identity.session_id if identity is not None else None

set_state

set_state(scope: str, key: str, value)

Set the value of a state node.

源代码位于: zoo_framework/statemachine/state_machine_manager.py
def set_state(self, scope: str, key: str, value):
    """Set the value of a state node."""
    if self._state_scope_map.get(scope) is None:
        self.create_scope(scope)

    state_register = self._state_scope_map[scope]
    state_register.set_state_node(key, value)

get_state

get_state(scope: str, key: str) -> Any

Get the state node.

源代码位于: zoo_framework/statemachine/state_machine_manager.py
def get_state(self, scope: str, key: str) -> Any:
    """Get the state node."""
    if self._state_scope_map.get(scope) is None:
        return None

    state_register = self._state_scope_map[scope]
    node = state_register.get_state_node(key)
    if None is node:
        return None

    return node.get_value()

remove_state

remove_state(scope: str, key: str)

Remove the state node.

源代码位于: zoo_framework/statemachine/state_machine_manager.py
def remove_state(self, scope: str, key: str):
    """Remove the state node."""
    if self._state_scope_map.get(scope) is None:
        return None

    # Fetch once and check: the original code first checked
    # `get_state_node(key) is None` and then fetched **again**, but the map
    # is a ThreadSafeDict - the node could be concurrently removed between
    # the two fetches, so there was a real window (where `node.get_value()`
    # would raise AttributeError). Merging into one fetch removes both the
    # window and the type error.
    state_register: StateScope = self._state_scope_map[scope]
    node = state_register.get_state_node(key)
    if node is None:
        return None

    value = node.get_value()
    state_register.remove_state_node(key)

    # If it is the top node, remove the scope
    if node.is_top():
        self._state_scope_map.pop(scope)

    return value

get_state_machines

get_state_machines()

Get the state machines.

源代码位于: zoo_framework/statemachine/state_machine_manager.py
def get_state_machines(self):
    """Get the state machines."""
    return self._state_scope_map

observe_state

observe_state(scope: str, key: str, effect: Callable)

Observe a state node.

源代码位于: zoo_framework/statemachine/state_machine_manager.py
def observe_state(self, scope: str, key: str, effect: Callable):
    """Observe a state node."""
    if self._state_scope_map.get(scope) is None:
        self.create_scope(scope)

    state_register: StateScope = self._state_scope_map[scope]
    state_register.observe_state_node(key, effect)

unobserve_state

unobserve_state(scope: str, key: str, effect: Callable)

Remove a state node observer - fixes a memory leak.

参数:

名称 类型 描述 默认
scope str

the scope name

必需
key str

the state key name

必需
effect Callable

the observer callback

必需

引发:

类型 描述
KeyError

when the scope or the state does not exist

源代码位于: zoo_framework/statemachine/state_machine_manager.py
def unobserve_state(self, scope: str, key: str, effect: Callable):
    """Remove a state node observer - fixes a memory leak.

    Args:
        scope: the scope name
        key: the state key name
        effect: the observer callback

    Raises:
        KeyError: when the scope or the state does not exist
    """
    if self._state_scope_map.get(scope) is None:
        raise KeyError(f"Scope '{scope}' not found")

    state_register: StateScope = self._state_scope_map[scope]
    state_register.unobserve_state_node(key, effect)

作用域与节点

zoo_framework.statemachine.state_scope.StateScope

State scope - P2 optimized version.

P2 optimizations: 1. creates the index via a factory 2. supports multiple index implementations 3. supports switching the index type dynamically

属性:

名称 类型 描述
_state_index StateIndex

the state-node index

源代码位于: zoo_framework/statemachine/state_scope.py
class StateScope:
    """State scope - P2 optimized version.

    P2 optimizations:
    1. creates the index via a factory
    2. supports multiple index implementations
    3. supports switching the index type dynamically

    Attributes:
        _state_index: the state-node index
    """

    def __init__(self, index_type: str = "dict"):
        """Initialize the state scope.

        P2 optimization: creates the index via a factory.

        Args:
            index_type: the index type ("dict" or "hierarchical")
        """
        # P2 optimization: create the index via the factory
        self._state_index: StateIndex = StateIndexFactory.create_index(index_type)
        # Owner identity: the **first** writer becomes the owner and it is never
        # rewritten afterwards (see set_state_node). The full RunIdentity is
        # recorded, not just the session, so the "run identity" is queryable on
        # the state side too.
        self.owner_identity: RunIdentity | None = None

    @property
    def owner_session_id(self) -> str | None:
        """The owner session id; None when unowned."""
        return self.owner_identity.session_id if self.owner_identity is not None else None

    def observe_state_node(self, key: str, effect: Any) -> None:
        """Observe a state node.

        When the key does not exist yet, a placeholder node is created before
        the observer is registered: silently dropping the registration would
        break the primary usage of "declare the observer first, wait for the
        data". The asymmetry with `unobserve_state_node` is deliberate -
        unregistering an observer that never existed usually means the caller
        is wrong and it should surface.

        Args:
            key: the state key name
            effect: the observer callback
        """
        node = self.get_state_node(key)
        if node is None:
            self.register_node(key, None)
            node = self.get_state_node(key)
            if node is None:
                return
        node.add_effect(effect)

    def unobserve_state_node(self, key: str, effect: Any) -> None:
        """Remove a state node observer - fixes a memory leak.

        Args:
            key: the state key name
            effect: the observer callback function

        Raises:
            KeyError: when the state node does not exist
        """
        node = self.get_state_node(key)
        if node is None:
            raise KeyError(f"State node '{key}' not found")
        node.remove_effect(effect)

    def register_top_node(self, key: str, value: Any, effect: list | None = None) -> None:
        """Register a root node.

        Args:
            key: the node key name
            value: the node value
            effect: the side-effect list
        """
        node = StateNode(key, value, effect)
        self._state_index.set(node.get_key(), node)
        node.to_be_top()

    def register_node(self, key: str, value: Any, effect: list | None = None) -> None:
        """Register a state node.

        Args:
            key: the node key name
            value: the node value
            effect: the side-effect list
        """
        if len(key.split(".")) == 1:
            self.register_top_node(key, value, effect)
            return

        node = StateNode(key, value, effect)
        self._state_index.set(node.get_key(), node)

    def set_state_node(self, key: str, value: Any, effect: list | None = None) -> None:
        """Set the value of a state node.

        Args:
            key: the node key name
            value: the node value
            effect: the side-effect list
        """
        # The owner identity settles at the **first write**: a scope outlives a
        # single run; rewriting the ownership every time would make "whose
        # session state is this" meaningless. Never rewritten afterwards.
        if self.owner_identity is None:
            identity = current_identity()
            if identity is not None:
                self.owner_identity = identity

        # 1. split the key
        key_queue = key.split(".")

        if len(key_queue) > 1:
            self._check_and_build_tree(key_queue)
        else:
            # Top-level key: the same semantics as the nested-key branch - update
            # when present, register when absent. This used to return directly
            # when the node already existed, skipping set_value, silently
            # dropping repeated writes of a top-level key (and never firing
            # observers).
            node = self.get_state_node(key)
            if node is None:
                self.register_node(key, value, effect)
            else:
                node.set_value(value)
            return

        if StateNodeType.get_type_by_value(value) == StateNodeType.branch:
            for k, v in value.items():
                self.set_state_node(f"{key}.{k}", v, effect)
            return
        node = self.get_state_node(key)
        if node is None:
            self.register_node(key, value, effect)
        else:
            node.set_value(value)

    def update_state_node(self, key: str, node: StateNode) -> None:
        """Update a state node.

        Args:
            key: the node key name
            node: the state node
        """
        self._state_index.set(key, node)

    def _check_children(self, key: str) -> None:
        """Check the children."""
        pass

    def _check_and_build_tree(self, key_queue: list[str]) -> None:
        """Check and build the tree structure.

        Args:
            key_queue: the key queue
        """
        # 2. create the nodes in order
        current_key = key_queue[0]
        for i in range(len(key_queue)):
            if i != 0:
                current_key = f"{current_key}.{key_queue[i]}"
            if self.get_state_node(current_key) is None:
                self.register_node(current_key, None)

        #  3. set up the tree structure
        current_key = key_queue[0]
        for i in range(1, len(key_queue)):
            # [Known defect] The two narrowed annotations below do **not** hold:
            # this path really can produce None (an assert was tried once and the
            # test immediately went red, proving the premise "the loop above has
            # already registered the node" is **not always true**), while the
            # original code passes None to `add_child` - i.e. **hangs a None
            # child node on the tree**; the `current_key` of this loop also never
            # advances. Both belong to this same unresolved semantics question.
            # We deliberately do not guess a fix (changing semantics is someone
            # else's call; recorded in
            # openspec/changes/establish-type-gate/tasks.md 3.1); an anchored
            # ignore keeps the defect visible, not silently altered or deleted.
            node: StateNode = self.get_state_node(current_key)  # type: ignore[assignment]
            children_node: StateNode = self.get_state_node(f"{current_key}.{key_queue[i]}")  # type: ignore[assignment]

            # One key must not be added twice
            node.add_child(children_node)

    def get_state_node(self, key: str) -> StateNode | None:
        """Get a state node.

        Args:
            key: the node key name

        Returns:
            The state node, or None
        """
        return self._state_index.get(key)

    def get_state_value(self, key: str) -> Any:
        """Get a state node's value.

        Args:
            key: the node key name

        Returns:
            The node value
        """
        node = self.get_state_node(key)
        if node is None:
            return None
        return node.get_value()

    def get_state_children_value(self, key: str) -> Any:
        """Get a state node's children values.

        Args:
            key: the node key name

        Returns:
            A dict of child values
        """
        node = self.get_state_node(key)
        if node is None:
            return None
        return node.get_children_value()

    def move_state_node(self, key: str, target_key: str) -> None:
        """Move a state node.

        Args:
            key: the original key name
            target_key: the target key name
        """
        node = self.get_state_node(key)
        if node is None:
            # The arguments used to be swapped: LogUtils.error's signature is
            # (message, cls_name=None), and this passed the **class** as the
            # message and the message as cls_name - the log printed the class
            # object instead of this message.
            LogUtils.error(f"State is not exist, key: {key}", self.__class__.__name__)
            return

        node.set_key(target_key)
        self.set_state_node(target_key, node)
        # Delete the children
        self.remove_state_node(key)

    def remove_state_node(self, key: str) -> None:
        """Remove a state node.

        Args:
            key: the node key name
        """
        node = self.get_state_node(key)
        if node is None:
            # The arguments used to be swapped: LogUtils.error's signature is
            # (message, cls_name=None), and this passed the **class** as the
            # message and the message as cls_name - the log printed the class
            # object instead of this message.
            LogUtils.error(f"State is not exist, key: {key}", self.__class__.__name__)
            return

        if node.get_type() == StateNodeType.branch:
            # A branch node: delete all its children
            for child in node.get_children():
                self.remove_state_node(child.get_key())

        self.set_state_node(key, None)

    def copy_state_node(self, key: str, target_key: Any) -> None:
        """Copy a state node's value.

        Args:
            key: the original key name
            target_key: the target key name
        """
        node = self.get_state_node(key)
        if node is None:
            return
        new_node = copy.deepcopy(node)
        new_node.set_key(target_key)
        self.set_state_node(target_key, new_node)

    def get_all_nodes(self) -> dict:
        """Get all state nodes.

        P2 optimization: supports fetching all nodes.

        Returns:
            A dict of nodes
        """
        return self._state_index.get_all()

    def find_nodes_by_prefix(self, prefix: str) -> list:
        """Find nodes by key prefix.

        P2 optimization: supports prefix lookup.

        Args:
            prefix: the key prefix

        Returns:
            A list of nodes
        """
        return self._state_index.find_by_prefix(prefix)

owner_session_id property

owner_session_id: str | None

The owner session id; None when unowned.

observe_state_node

observe_state_node(key: str, effect: Any) -> None

Observe a state node.

When the key does not exist yet, a placeholder node is created before the observer is registered: silently dropping the registration would break the primary usage of "declare the observer first, wait for the data". The asymmetry with unobserve_state_node is deliberate - unregistering an observer that never existed usually means the caller is wrong and it should surface.

参数:

名称 类型 描述 默认
key str

the state key name

必需
effect Any

the observer callback

必需
源代码位于: zoo_framework/statemachine/state_scope.py
def observe_state_node(self, key: str, effect: Any) -> None:
    """Observe a state node.

    When the key does not exist yet, a placeholder node is created before
    the observer is registered: silently dropping the registration would
    break the primary usage of "declare the observer first, wait for the
    data". The asymmetry with `unobserve_state_node` is deliberate -
    unregistering an observer that never existed usually means the caller
    is wrong and it should surface.

    Args:
        key: the state key name
        effect: the observer callback
    """
    node = self.get_state_node(key)
    if node is None:
        self.register_node(key, None)
        node = self.get_state_node(key)
        if node is None:
            return
    node.add_effect(effect)

unobserve_state_node

unobserve_state_node(key: str, effect: Any) -> None

Remove a state node observer - fixes a memory leak.

参数:

名称 类型 描述 默认
key str

the state key name

必需
effect Any

the observer callback function

必需

引发:

类型 描述
KeyError

when the state node does not exist

源代码位于: zoo_framework/statemachine/state_scope.py
def unobserve_state_node(self, key: str, effect: Any) -> None:
    """Remove a state node observer - fixes a memory leak.

    Args:
        key: the state key name
        effect: the observer callback function

    Raises:
        KeyError: when the state node does not exist
    """
    node = self.get_state_node(key)
    if node is None:
        raise KeyError(f"State node '{key}' not found")
    node.remove_effect(effect)

register_top_node

register_top_node(key: str, value: Any, effect: list | None = None) -> None

Register a root node.

参数:

名称 类型 描述 默认
key str

the node key name

必需
value Any

the node value

必需
effect list | None

the side-effect list

None
源代码位于: zoo_framework/statemachine/state_scope.py
def register_top_node(self, key: str, value: Any, effect: list | None = None) -> None:
    """Register a root node.

    Args:
        key: the node key name
        value: the node value
        effect: the side-effect list
    """
    node = StateNode(key, value, effect)
    self._state_index.set(node.get_key(), node)
    node.to_be_top()

register_node

register_node(key: str, value: Any, effect: list | None = None) -> None

Register a state node.

参数:

名称 类型 描述 默认
key str

the node key name

必需
value Any

the node value

必需
effect list | None

the side-effect list

None
源代码位于: zoo_framework/statemachine/state_scope.py
def register_node(self, key: str, value: Any, effect: list | None = None) -> None:
    """Register a state node.

    Args:
        key: the node key name
        value: the node value
        effect: the side-effect list
    """
    if len(key.split(".")) == 1:
        self.register_top_node(key, value, effect)
        return

    node = StateNode(key, value, effect)
    self._state_index.set(node.get_key(), node)

set_state_node

set_state_node(key: str, value: Any, effect: list | None = None) -> None

Set the value of a state node.

参数:

名称 类型 描述 默认
key str

the node key name

必需
value Any

the node value

必需
effect list | None

the side-effect list

None
源代码位于: zoo_framework/statemachine/state_scope.py
def set_state_node(self, key: str, value: Any, effect: list | None = None) -> None:
    """Set the value of a state node.

    Args:
        key: the node key name
        value: the node value
        effect: the side-effect list
    """
    # The owner identity settles at the **first write**: a scope outlives a
    # single run; rewriting the ownership every time would make "whose
    # session state is this" meaningless. Never rewritten afterwards.
    if self.owner_identity is None:
        identity = current_identity()
        if identity is not None:
            self.owner_identity = identity

    # 1. split the key
    key_queue = key.split(".")

    if len(key_queue) > 1:
        self._check_and_build_tree(key_queue)
    else:
        # Top-level key: the same semantics as the nested-key branch - update
        # when present, register when absent. This used to return directly
        # when the node already existed, skipping set_value, silently
        # dropping repeated writes of a top-level key (and never firing
        # observers).
        node = self.get_state_node(key)
        if node is None:
            self.register_node(key, value, effect)
        else:
            node.set_value(value)
        return

    if StateNodeType.get_type_by_value(value) == StateNodeType.branch:
        for k, v in value.items():
            self.set_state_node(f"{key}.{k}", v, effect)
        return
    node = self.get_state_node(key)
    if node is None:
        self.register_node(key, value, effect)
    else:
        node.set_value(value)

update_state_node

update_state_node(key: str, node: StateNode) -> None

Update a state node.

参数:

名称 类型 描述 默认
key str

the node key name

必需
node StateNode

the state node

必需
源代码位于: zoo_framework/statemachine/state_scope.py
def update_state_node(self, key: str, node: StateNode) -> None:
    """Update a state node.

    Args:
        key: the node key name
        node: the state node
    """
    self._state_index.set(key, node)

get_state_node

get_state_node(key: str) -> StateNode | None

Get a state node.

参数:

名称 类型 描述 默认
key str

the node key name

必需

返回:

类型 描述
StateNode | None

The state node, or None

源代码位于: zoo_framework/statemachine/state_scope.py
def get_state_node(self, key: str) -> StateNode | None:
    """Get a state node.

    Args:
        key: the node key name

    Returns:
        The state node, or None
    """
    return self._state_index.get(key)

get_state_value

get_state_value(key: str) -> Any

Get a state node's value.

参数:

名称 类型 描述 默认
key str

the node key name

必需

返回:

类型 描述
Any

The node value

源代码位于: zoo_framework/statemachine/state_scope.py
def get_state_value(self, key: str) -> Any:
    """Get a state node's value.

    Args:
        key: the node key name

    Returns:
        The node value
    """
    node = self.get_state_node(key)
    if node is None:
        return None
    return node.get_value()

get_state_children_value

get_state_children_value(key: str) -> Any

Get a state node's children values.

参数:

名称 类型 描述 默认
key str

the node key name

必需

返回:

类型 描述
Any

A dict of child values

源代码位于: zoo_framework/statemachine/state_scope.py
def get_state_children_value(self, key: str) -> Any:
    """Get a state node's children values.

    Args:
        key: the node key name

    Returns:
        A dict of child values
    """
    node = self.get_state_node(key)
    if node is None:
        return None
    return node.get_children_value()

move_state_node

move_state_node(key: str, target_key: str) -> None

Move a state node.

参数:

名称 类型 描述 默认
key str

the original key name

必需
target_key str

the target key name

必需
源代码位于: zoo_framework/statemachine/state_scope.py
def move_state_node(self, key: str, target_key: str) -> None:
    """Move a state node.

    Args:
        key: the original key name
        target_key: the target key name
    """
    node = self.get_state_node(key)
    if node is None:
        # The arguments used to be swapped: LogUtils.error's signature is
        # (message, cls_name=None), and this passed the **class** as the
        # message and the message as cls_name - the log printed the class
        # object instead of this message.
        LogUtils.error(f"State is not exist, key: {key}", self.__class__.__name__)
        return

    node.set_key(target_key)
    self.set_state_node(target_key, node)
    # Delete the children
    self.remove_state_node(key)

remove_state_node

remove_state_node(key: str) -> None

Remove a state node.

参数:

名称 类型 描述 默认
key str

the node key name

必需
源代码位于: zoo_framework/statemachine/state_scope.py
def remove_state_node(self, key: str) -> None:
    """Remove a state node.

    Args:
        key: the node key name
    """
    node = self.get_state_node(key)
    if node is None:
        # The arguments used to be swapped: LogUtils.error's signature is
        # (message, cls_name=None), and this passed the **class** as the
        # message and the message as cls_name - the log printed the class
        # object instead of this message.
        LogUtils.error(f"State is not exist, key: {key}", self.__class__.__name__)
        return

    if node.get_type() == StateNodeType.branch:
        # A branch node: delete all its children
        for child in node.get_children():
            self.remove_state_node(child.get_key())

    self.set_state_node(key, None)

copy_state_node

copy_state_node(key: str, target_key: Any) -> None

Copy a state node's value.

参数:

名称 类型 描述 默认
key str

the original key name

必需
target_key Any

the target key name

必需
源代码位于: zoo_framework/statemachine/state_scope.py
def copy_state_node(self, key: str, target_key: Any) -> None:
    """Copy a state node's value.

    Args:
        key: the original key name
        target_key: the target key name
    """
    node = self.get_state_node(key)
    if node is None:
        return
    new_node = copy.deepcopy(node)
    new_node.set_key(target_key)
    self.set_state_node(target_key, new_node)

get_all_nodes

get_all_nodes() -> dict

Get all state nodes.

P2 optimization: supports fetching all nodes.

返回:

类型 描述
dict

A dict of nodes

源代码位于: zoo_framework/statemachine/state_scope.py
def get_all_nodes(self) -> dict:
    """Get all state nodes.

    P2 optimization: supports fetching all nodes.

    Returns:
        A dict of nodes
    """
    return self._state_index.get_all()

find_nodes_by_prefix

find_nodes_by_prefix(prefix: str) -> list

Find nodes by key prefix.

P2 optimization: supports prefix lookup.

参数:

名称 类型 描述 默认
prefix str

the key prefix

必需

返回:

类型 描述
list

A list of nodes

源代码位于: zoo_framework/statemachine/state_scope.py
def find_nodes_by_prefix(self, prefix: str) -> list:
    """Find nodes by key prefix.

    P2 optimization: supports prefix lookup.

    Args:
        prefix: the key prefix

    Returns:
        A list of nodes
    """
    return self._state_index.find_by_prefix(prefix)

zoo_framework.statemachine.state_node.StateNode

State node.

源代码位于: zoo_framework/statemachine/state_node.py
class StateNode:
    """State node."""

    def __init__(self, key: str, value: Any, effect_list: list[types.FunctionType] | None = None):
        # The annotation used to be `list[StateEffect]`, but what actually goes
        # into the list are **functions** (proven both by add_effect's
        # isinstance(effect, types.FunctionType) and by _perform_effect's
        # executor.submit(effect, ...)); and `StateEffect` has no __call__,
        # so that type could never be executed. Changed to the honest
        # `list[types.FunctionType]`.
        self._effect_list: list[types.FunctionType] = []
        self._version = int(time.time())
        self._is_top = False
        self._parent: Any | None = None
        self._children: list[Any] = []
        self._type = StateNodeType.string

        if effect_list is None:
            effect_list = []
        self._value = value
        self._effect_list = effect_list
        self.key = key

    def set_top(self, is_top: bool) -> None:
        """Set whether it is the root node."""
        self._is_top = is_top

    def is_top(self) -> bool:
        """Whether it is the root node."""
        return self._is_top

    def to_be_top(self) -> None:
        """Mark it as the root node."""
        self._is_top = True

    def get_key(self) -> str:
        """Get the state node key."""
        return self.key

    def add_child(self, child: Any) -> None:
        """Add a child node."""
        if child in self._children or child == self:
            return
        self._children.append(child)

    def get_type(self):
        """Get the state node type."""
        return self._type

    def get_value(self) -> Any:
        """Get the state node value."""
        if len(self._children) == 0:
            return self._value
        return self.get_children_value()

    def get_children_value(self) -> dict:
        """Get the children values."""
        _result: dict = {}
        i = 0
        for child in self._children:
            LogUtils.debug(f"${child.get_key}:{child.get_value()}")
            key = child.get_key
            if key is None:
                continue
            if key in _result:
                i += 1
                _result[f"{key}-{i}"] = child.get_value()
            else:
                _result[child.get_key()] = child.get_value()
        return _result

    def set_key(self, key: str) -> None:
        """Set the state node key."""
        self.key = key
        if self._type is StateNodeType.branch:
            self._update_children_key()

    def _update_children_key(self) -> None:
        """Update the children keys."""
        for i, child in enumerate(self._children):
            child.set_key(f"{self.key}.{i}")

    def set_value(self, value: Any) -> None:
        """Set the state node value."""
        version = int(time.time())
        self._type = StateNodeType.get_type_by_value(value)
        self._value = value
        self._update_version()
        self._perform_effect(value, version)

    def _perform_effect(self, value: Any, version: int) -> None:
        """Perform the state node effects.

        Effects run concurrently on the shared thread executor; the write
        waits synchronously within the timeout. An exception raised by an
        effect does not propagate to the writer but MUST be observable
        (logged).
        """
        if len(self._effect_list) == 0:
            return

        executor = _get_effect_executor()
        futures = [
            executor.submit(effect, {"value": value, "version": version})
            for effect in self._effect_list
        ]
        wait(futures, timeout=_EFFECT_JOIN_TIMEOUT_SECONDS)

        for f in futures:
            if not f.done():
                continue
            # After done(), exception() does not block; like gevent.joinall, it is not re-raised.
            exc = f.exception()
            if exc is not None:
                LogUtils.warning(f"state effect raised an exception: {exc!r}", "StateNode")

    def _update_version(self) -> None:
        """Update the state node version."""
        self.version = int(time.time())

    def get_state(self) -> Any:
        """Get the state node value."""
        return self._value

    def add_effect(self, effect: types.FunctionType | None) -> None:
        """Add an effect to the state node."""
        if effect is None:
            return
        if isinstance(effect, types.FunctionType) and effect not in self._effect_list:
            self._effect_list.append(effect)

    def remove_effect(self, effect: types.FunctionType | None) -> None:
        """Remove an effect from the state node - fixes a memory leak.

        Args:
            effect: the effect function to remove

        Raises:
            ValueError: when the effect is not in the list
        """
        if effect is None:
            return

        try:
            self._effect_list.remove(effect)
            LogUtils.debug(f"✅ Effect removed from state node '{self.key}'")
        except ValueError:
            LogUtils.warning(f"⚠️ Effect not found in state node '{self.key}'")

    def get_children(self) -> list[Any]:
        """Get the children."""
        return self._children

set_top

set_top(is_top: bool) -> None

Set whether it is the root node.

源代码位于: zoo_framework/statemachine/state_node.py
def set_top(self, is_top: bool) -> None:
    """Set whether it is the root node."""
    self._is_top = is_top

is_top

is_top() -> bool

Whether it is the root node.

源代码位于: zoo_framework/statemachine/state_node.py
def is_top(self) -> bool:
    """Whether it is the root node."""
    return self._is_top

to_be_top

to_be_top() -> None

Mark it as the root node.

源代码位于: zoo_framework/statemachine/state_node.py
def to_be_top(self) -> None:
    """Mark it as the root node."""
    self._is_top = True

get_key

get_key() -> str

Get the state node key.

源代码位于: zoo_framework/statemachine/state_node.py
def get_key(self) -> str:
    """Get the state node key."""
    return self.key

add_child

add_child(child: Any) -> None

Add a child node.

源代码位于: zoo_framework/statemachine/state_node.py
def add_child(self, child: Any) -> None:
    """Add a child node."""
    if child in self._children or child == self:
        return
    self._children.append(child)

get_type

get_type()

Get the state node type.

源代码位于: zoo_framework/statemachine/state_node.py
def get_type(self):
    """Get the state node type."""
    return self._type

get_value

get_value() -> Any

Get the state node value.

源代码位于: zoo_framework/statemachine/state_node.py
def get_value(self) -> Any:
    """Get the state node value."""
    if len(self._children) == 0:
        return self._value
    return self.get_children_value()

get_children_value

get_children_value() -> dict

Get the children values.

源代码位于: zoo_framework/statemachine/state_node.py
def get_children_value(self) -> dict:
    """Get the children values."""
    _result: dict = {}
    i = 0
    for child in self._children:
        LogUtils.debug(f"${child.get_key}:{child.get_value()}")
        key = child.get_key
        if key is None:
            continue
        if key in _result:
            i += 1
            _result[f"{key}-{i}"] = child.get_value()
        else:
            _result[child.get_key()] = child.get_value()
    return _result

set_key

set_key(key: str) -> None

Set the state node key.

源代码位于: zoo_framework/statemachine/state_node.py
def set_key(self, key: str) -> None:
    """Set the state node key."""
    self.key = key
    if self._type is StateNodeType.branch:
        self._update_children_key()

set_value

set_value(value: Any) -> None

Set the state node value.

源代码位于: zoo_framework/statemachine/state_node.py
def set_value(self, value: Any) -> None:
    """Set the state node value."""
    version = int(time.time())
    self._type = StateNodeType.get_type_by_value(value)
    self._value = value
    self._update_version()
    self._perform_effect(value, version)

get_state

get_state() -> Any

Get the state node value.

源代码位于: zoo_framework/statemachine/state_node.py
def get_state(self) -> Any:
    """Get the state node value."""
    return self._value

add_effect

add_effect(effect: FunctionType | None) -> None

Add an effect to the state node.

源代码位于: zoo_framework/statemachine/state_node.py
def add_effect(self, effect: types.FunctionType | None) -> None:
    """Add an effect to the state node."""
    if effect is None:
        return
    if isinstance(effect, types.FunctionType) and effect not in self._effect_list:
        self._effect_list.append(effect)

remove_effect

remove_effect(effect: FunctionType | None) -> None

Remove an effect from the state node - fixes a memory leak.

参数:

名称 类型 描述 默认
effect FunctionType | None

the effect function to remove

必需

引发:

类型 描述
ValueError

when the effect is not in the list

源代码位于: zoo_framework/statemachine/state_node.py
def remove_effect(self, effect: types.FunctionType | None) -> None:
    """Remove an effect from the state node - fixes a memory leak.

    Args:
        effect: the effect function to remove

    Raises:
        ValueError: when the effect is not in the list
    """
    if effect is None:
        return

    try:
        self._effect_list.remove(effect)
        LogUtils.debug(f"✅ Effect removed from state node '{self.key}'")
    except ValueError:
        LogUtils.warning(f"⚠️ Effect not found in state node '{self.key}'")

get_children

get_children() -> list[Any]

Get the children.

源代码位于: zoo_framework/statemachine/state_node.py
def get_children(self) -> list[Any]:
    """Get the children."""
    return self._children

zoo_framework.statemachine.base_state_machine.BaseStateMachine

Bases: dict

Base class for all state machines.

源代码位于: zoo_framework/statemachine/base_state_machine.py
class BaseStateMachine(dict):
    """Base class for all state machines."""

    topic = ""

    def __init__(self, topic):
        dict.__init__(self)
        self.topic = topic

    def next(self, topic):
        pass

索引与类型

zoo_framework.statemachine.state_node_type

StateNodeType

Bases: Enum

The state node type.

源代码位于: zoo_framework/statemachine/state_node_type.py
class StateNodeType(Enum):
    """The state node type."""

    string = "string"
    number = "number"
    datetime = "datetime"
    boolean = "boolean"
    array = "array"

    # Node branch, i.e. the dict type
    branch = "branch"

    @staticmethod
    def get_type_by_value(value):
        """Get the type by value."""
        if isinstance(value, str):
            return StateNodeType.string
        if isinstance(value, (int, float)):
            return StateNodeType.number
        if isinstance(value, bool):
            return StateNodeType.boolean
        if isinstance(value, list):
            return StateNodeType.array
        if isinstance(value, dict):
            return StateNodeType.branch
        return None

get_type_by_value staticmethod

get_type_by_value(value)

Get the type by value.

源代码位于: zoo_framework/statemachine/state_node_type.py
@staticmethod
def get_type_by_value(value):
    """Get the type by value."""
    if isinstance(value, str):
        return StateNodeType.string
    if isinstance(value, (int, float)):
        return StateNodeType.number
    if isinstance(value, bool):
        return StateNodeType.boolean
    if isinstance(value, list):
        return StateNodeType.array
    if isinstance(value, dict):
        return StateNodeType.branch
    return None

zoo_framework.statemachine.state_node_index

状态节点索引:按状态维护 effect 的记账副本。

历史缺陷(issue #208):StateEffectScheduler 自建立起就调用 add_state_effect / remove_state_effect,但本类并未实现这两个方法——该路径 一旦被构造即 AttributeError(此前无构造点,属死代码上的潜伏缺陷)。本类初始就 带有 state_effect_map / state_effect_set 两个空容器却无配套方法,二者当时都是 死状态;本次补齐接口,使其成为真正生效的记账结构。

StateNodeIndex

状态节点索引。

属性:

名称 类型 描述
state_node

关联的状态节点

state_effect_map dict[Any, set[Any]]

状态 -> 该状态下的 effect 集合

state_effect_set set[Any]

全部已登记 effect 的合集

id

索引实例标识

源代码位于: zoo_framework/statemachine/state_node_index.py
class StateNodeIndex:
    """状态节点索引。

    Attributes:
        state_node: 关联的状态节点
        state_effect_map: 状态 -> 该状态下的 effect 集合
        state_effect_set: 全部已登记 effect 的合集
        id: 索引实例标识
    """

    def __init__(self, state_node):
        self.state_node = state_node
        self.state_effect_map: dict[Any, set[Any]] = {}
        self.state_effect_set: set[Any] = set()
        self.id = id(self)

    def add_state_effect(self, state_effect: Any) -> None:
        """登记一个状态 effect:按状态入分组,同时并入全集。

        Args:
            state_effect: 待登记的状态 effect;以 ``state_effect.state`` 为分组键。
        """
        self.state_effect_map.setdefault(state_effect.state, set()).add(state_effect)
        self.state_effect_set.add(state_effect)

    def remove_state_effect(self, state_effect: Any) -> None:
        """移除一个状态 effect:同时从分组与全集中移除。

        幂等:目标不存在时不抛错——索引是调度器记账的**副本**,重复移除不应让调用方的
        簿记路径中断。

        Args:
            state_effect: 待移除的状态 effect。
        """
        bucket = self.state_effect_map.get(state_effect.state)
        if bucket is not None:
            bucket.discard(state_effect)
            if not bucket:
                del self.state_effect_map[state_effect.state]
        self.state_effect_set.discard(state_effect)

add_state_effect

add_state_effect(state_effect: Any) -> None

登记一个状态 effect:按状态入分组,同时并入全集。

参数:

名称 类型 描述 默认
state_effect Any

待登记的状态 effect;以 state_effect.state 为分组键。

必需
源代码位于: zoo_framework/statemachine/state_node_index.py
def add_state_effect(self, state_effect: Any) -> None:
    """登记一个状态 effect:按状态入分组,同时并入全集。

    Args:
        state_effect: 待登记的状态 effect;以 ``state_effect.state`` 为分组键。
    """
    self.state_effect_map.setdefault(state_effect.state, set()).add(state_effect)
    self.state_effect_set.add(state_effect)

remove_state_effect

remove_state_effect(state_effect: Any) -> None

移除一个状态 effect:同时从分组与全集中移除。

幂等:目标不存在时不抛错——索引是调度器记账的副本,重复移除不应让调用方的 簿记路径中断。

参数:

名称 类型 描述 默认
state_effect Any

待移除的状态 effect。

必需
源代码位于: zoo_framework/statemachine/state_node_index.py
def remove_state_effect(self, state_effect: Any) -> None:
    """移除一个状态 effect:同时从分组与全集中移除。

    幂等:目标不存在时不抛错——索引是调度器记账的**副本**,重复移除不应让调用方的
    簿记路径中断。

    Args:
        state_effect: 待移除的状态 effect。
    """
    bucket = self.state_effect_map.get(state_effect.state)
    if bucket is not None:
        bucket.discard(state_effect)
        if not bucket:
            del self.state_effect_map[state_effect.state]
    self.state_effect_set.discard(state_effect)

zoo_framework.statemachine.state_index_factory.StateIndexFactory

State index factory.

P2 optimization: create indexes via the factory pattern.

源代码位于: zoo_framework/statemachine/state_index_factory.py
class StateIndexFactory:
    """State index factory.

    P2 optimization: create indexes via the factory pattern.
    """

    _index_types: dict[str, type[StateIndex]] = {
        "dict": ThreadSafeDictIndex,
        "hierarchical": HierarchicalIndex,
    }

    @classmethod
    def create_index(cls, index_type: str = "dict") -> StateIndex:
        """Create an index.

        Args:
            index_type: the index type

        Returns:
            An index instance

        Raises:
            ValueError: when the index type does not exist
        """
        if index_type not in cls._index_types:
            raise ValueError(f"Unknown index type: {index_type}")

        return cls._index_types[index_type]()

    @classmethod
    def register_index_type(cls, name: str, index_class: type) -> None:
        """Register a new index type.

        Args:
            name: the type name
            index_class: the index class
        """
        cls._index_types[name] = index_class

    @classmethod
    def get_available_types(cls) -> list[str]:
        """Get the available index types."""
        return list(cls._index_types.keys())

create_index classmethod

create_index(index_type: str = 'dict') -> StateIndex

Create an index.

参数:

名称 类型 描述 默认
index_type str

the index type

'dict'

返回:

类型 描述
StateIndex

An index instance

引发:

类型 描述
ValueError

when the index type does not exist

源代码位于: zoo_framework/statemachine/state_index_factory.py
@classmethod
def create_index(cls, index_type: str = "dict") -> StateIndex:
    """Create an index.

    Args:
        index_type: the index type

    Returns:
        An index instance

    Raises:
        ValueError: when the index type does not exist
    """
    if index_type not in cls._index_types:
        raise ValueError(f"Unknown index type: {index_type}")

    return cls._index_types[index_type]()

register_index_type classmethod

register_index_type(name: str, index_class: type) -> None

Register a new index type.

参数:

名称 类型 描述 默认
name str

the type name

必需
index_class type

the index class

必需
源代码位于: zoo_framework/statemachine/state_index_factory.py
@classmethod
def register_index_type(cls, name: str, index_class: type) -> None:
    """Register a new index type.

    Args:
        name: the type name
        index_class: the index class
    """
    cls._index_types[name] = index_class

get_available_types classmethod

get_available_types() -> list[str]

Get the available index types.

源代码位于: zoo_framework/statemachine/state_index_factory.py
@classmethod
def get_available_types(cls) -> list[str]:
    """Get the available index types."""
    return list(cls._index_types.keys())

状态 effect

zoo_framework.statemachine.state_effect.StateEffect

The side effect of a state node.

源代码位于: zoo_framework/statemachine/state_effect.py
class StateEffect:
    """The side effect of a state node."""

    # The parameters MUST be annotated: previously they were bare, making
    # self.state / self.effect Any, and `__eq__`'s `==` with `and` would
    # propagate Any outward - Any returned from a function declared to return
    # bool. The types take the **actual semantics**: state is only compared /
    # printed / hashed (opaque value -> object), effect gets called via
    # `self.effect(*args, **kwargs)` (-> Callable).
    def __init__(self, state: object, effect: Callable[..., Any]) -> None:
        self.state = state
        self.effect = effect
        self.execute_count = 0
        self.always_execute = False

        # Response priority; a priority filter is to be added: per the
        # execution strategy it computes a priority and puts the
        # highest-priority effect into a priority queue
        self.priority = 0

        # Response count
        self.response_count = 0

    def get_priority(self):
        return self.priority

    def set_priority(self, priority):
        self.priority = priority

    def get_response_count(self):
        return self.response_count

    def set_response_count(self, response_count):
        self.response_count = response_count

    def __index__(self):
        return self.priority

    def set_always_execute(self, always_execute):
        self.always_execute = always_execute

    def execute(self, *args, **kwargs):
        self.execute_count += 1
        self.effect(*args, **kwargs)
        # TODO: report the system time and load at execution to the scheduler

    def __repr__(self) -> str:
        """:return: str"""
        return f"StateEffect(state={self.state}, effect={self.effect})"

    # `other` is annotated as the same class, not `object`: the body reads
    # `other.state` / `other.effect` **unconditionally**, i.e. it already
    # assumes the peer is a StateEffect - the annotation makes that
    # existing assumption checker-visible. It also violates LSP (the
    # parameter of `object.__eq__` is `object`), hence the targeted
    # ignore. The canonical form is `other: object` plus an `isinstance`
    # early return of `NotImplemented`, but that would change comparison
    # semantics for foreign types (AttributeError ->
    # NotImplemented/False), and `__ne__` would need rewriting in sync -
    # a behavior change, left as a separate decision.
    def __eq__(self, other: "StateEffect") -> bool:  # type: ignore[override]
        return self.state == other.state and self.effect == other.effect

    def __hash__(self) -> int:
        return hash((self.state, self.effect))

    def __ne__(self, other: "StateEffect") -> bool:  # type: ignore[override]
        # Same assumption and same LSP deviation as `__eq__` (rationale
        # above); the two MUST change together.
        return not self.__eq__(other)

zoo_framework.statemachine.state_effect_scheduler.StateEffectScheduler

The state effect scheduler.

源代码位于: zoo_framework/statemachine/state_effect_scheduler.py
class StateEffectScheduler:
    """The state effect scheduler."""

    # TODO: 通过管道管理器
    _event_channel = EventChannelManager().get_channel(__name__)

    # The historical class attribute `_response_list: set = set()` was
    # deleted (declare-debt-carriers): dead state with zero reads or writes
    # repo-wide, yet a class-level mutable shared - exposed once the scan
    # registration mechanism came online; removing it outright was better
    # than registering a dead carrier.

    def __init__(self, state_machine: Any) -> None:
        self.state_machine = state_machine
        self.state_effect_map: dict[object, set[StateEffect]] = {}
        self.state_effect_index: StateNodeIndex = StateNodeIndexFactory.create_index(
            self.state_machine
        )

    def add_state_effect(self, state_effect: StateEffect) -> None:
        """Add a state effect.

        Args:
            state_effect: the state effect
        """
        if state_effect.state not in self.state_effect_map:
            self.state_effect_map[state_effect.state] = set()
        self.state_effect_map[state_effect.state].add(state_effect)
        # 索引侧同步登记(issue #208 补齐 StateNodeIndex.add_state_effect)
        self.state_effect_index.add_state_effect(state_effect)

    def remove_state_effect(self, state_effect: StateEffect) -> None:
        """Remove a state effect.

        Args:
            state_effect: the state effect
        """
        if state_effect.state in self.state_effect_map:
            self.state_effect_map[state_effect.state].remove(state_effect)
            # 索引侧同步移除(issue #208 补齐 StateNodeIndex.remove_state_effect)
            self.state_effect_index.remove_state_effect(state_effect)

    def get_state_effect(self, state: object) -> set[StateEffect]:
        """Get the state effects for a state.

        Args:
            state: the state node
        """
        return self.state_effect_map.get(state, set())

    def get_state_effect_index(self) -> StateNodeIndex:
        """Get the state effect index.

        Returns:
            the state effect index
        """
        return self.state_effect_index

    def execute_state_effect(self, state: object, *args: Any, **kwargs: Any) -> None:
        """Execute the state effects for a state.

        Args:
            state: the state node
            *args: positional arguments passed to each effect
            **kwargs: keyword arguments passed to each effect
        """
        state_effect_set = self.get_state_effect(state)
        for state_effect in state_effect_set:
            state_effect.execute(*args, **kwargs)

add_state_effect

add_state_effect(state_effect: StateEffect) -> None

Add a state effect.

参数:

名称 类型 描述 默认
state_effect StateEffect

the state effect

必需
源代码位于: zoo_framework/statemachine/state_effect_scheduler.py
def add_state_effect(self, state_effect: StateEffect) -> None:
    """Add a state effect.

    Args:
        state_effect: the state effect
    """
    if state_effect.state not in self.state_effect_map:
        self.state_effect_map[state_effect.state] = set()
    self.state_effect_map[state_effect.state].add(state_effect)
    # 索引侧同步登记(issue #208 补齐 StateNodeIndex.add_state_effect)
    self.state_effect_index.add_state_effect(state_effect)

remove_state_effect

remove_state_effect(state_effect: StateEffect) -> None

Remove a state effect.

参数:

名称 类型 描述 默认
state_effect StateEffect

the state effect

必需
源代码位于: zoo_framework/statemachine/state_effect_scheduler.py
def remove_state_effect(self, state_effect: StateEffect) -> None:
    """Remove a state effect.

    Args:
        state_effect: the state effect
    """
    if state_effect.state in self.state_effect_map:
        self.state_effect_map[state_effect.state].remove(state_effect)
        # 索引侧同步移除(issue #208 补齐 StateNodeIndex.remove_state_effect)
        self.state_effect_index.remove_state_effect(state_effect)

get_state_effect

get_state_effect(state: object) -> set[StateEffect]

Get the state effects for a state.

参数:

名称 类型 描述 默认
state object

the state node

必需
源代码位于: zoo_framework/statemachine/state_effect_scheduler.py
def get_state_effect(self, state: object) -> set[StateEffect]:
    """Get the state effects for a state.

    Args:
        state: the state node
    """
    return self.state_effect_map.get(state, set())

get_state_effect_index

get_state_effect_index() -> StateNodeIndex

Get the state effect index.

返回:

类型 描述
StateNodeIndex

the state effect index

源代码位于: zoo_framework/statemachine/state_effect_scheduler.py
def get_state_effect_index(self) -> StateNodeIndex:
    """Get the state effect index.

    Returns:
        the state effect index
    """
    return self.state_effect_index

execute_state_effect

execute_state_effect(state: object, *args: Any, **kwargs: Any) -> None

Execute the state effects for a state.

参数:

名称 类型 描述 默认
state object

the state node

必需
*args Any

positional arguments passed to each effect

()
**kwargs Any

keyword arguments passed to each effect

{}
源代码位于: zoo_framework/statemachine/state_effect_scheduler.py
def execute_state_effect(self, state: object, *args: Any, **kwargs: Any) -> None:
    """Execute the state effects for a state.

    Args:
        state: the state node
        *args: positional arguments passed to each effect
        **kwargs: keyword arguments passed to each effect
    """
    state_effect_set = self.get_state_effect(state)
    for state_effect in state_effect_set:
        state_effect.execute(*args, **kwargs)