跳转至

事件

进程内事件管道:通道隔离、优先级排序、重试策略与死信记录。

from zoo_framework.core.aop import event

zoo_framework.event.event_channel.EventChannel

Event channel.

The queue and the reactor manager are both instance-level: EventChannel is created and cached by name in EventChannelRegister; the singleton belongs on the registrar (the name -> channel map), not on the queue each channel instance holds inside itself. Both used to be class attributes, making all channels share one queue.

源代码位于: zoo_framework/event/event_channel.py
class EventChannel:
    """Event channel.

    The queue and the reactor manager are both **instance-level**:
    `EventChannel` is created and cached by name in `EventChannelRegister`;
    the singleton belongs on the registrar (the name -> channel map), not on
    the queue each channel instance holds inside itself. Both used to be
    class attributes, making all channels share one queue.
    """

    # Dead-letter record cap, to avoid unbounded growth over long runs
    _DEAD_LETTER_LIMIT = 1000

    def __init__(self, channel_name):
        # The event queue (independent per channel)
        self._event_fifo: EventFIFO = EventFIFO()

        # The event reactor manager (process-level registration; every channel
        # holds the same reference; reactor registration is still global)
        self._reactor_manager = EventReactorManager()

        # Records of undeliverable events (dead letters)
        self._dead_letters: list = []

        # Whether public: a non-public channel can only trigger events via
        # reactors; if public, events can be triggered via the channel itself
        self.public = False
        # The channel name
        self.channel_name = channel_name

        # 推模型唤醒设施(add-event-push-model D1/D2):per-channel Condition,
        # 懒创建 + 开关门控——关闭时本属性恒 None,生产者路径零新增分支开销。
        from zoo_framework.params import EventParams

        self._condition: Condition | None = Condition() if EventParams.PUSH_MODEL_ENABLED else None

    # ---------------------------------------------------------------- 推模型

    @property
    def condition(self) -> Condition | None:
        """通道的推模型唤醒条件变量;未启用推模型时为 None."""
        return self._condition

    def _ensure_condition(self) -> Condition | None:
        """取唤醒条件变量;推模型未启用时返回 None.

        懒建兜底:通道可能在推模型开关打开**之前**创建(config 之外的运行期
        启用、测试替身、热部署)——此时首读参数决定是否补建,避免通道永久
        错过推模型。启用后不再回收(进程语义单向,回到关闭态由重建通道承担)。
        """
        if self._condition is None:
            from zoo_framework.params import EventParams

            if EventParams.PUSH_MODEL_ENABLED:
                self._condition = Condition()
        return self._condition

    def wait_ready(self, timeout: float) -> bool:
        """消费者挂起等待本通道有事件(推模型启用时).

        Args:
            timeout: 兜底超时(秒);超时后调用方恢复扫描(防生产者漏 notify)

        Returns:
            True 表示本次调用观察到队列非空(进入时已非空,或被 notify 唤醒);
            False 表示等满兜底超时后仍空,或推模型未启用
        """
        condition = self._ensure_condition()
        if condition is None:
            return False
        with condition:
            if self._event_fifo.size() > 0:
                return True
            condition.wait(timeout)
            return self._event_fifo.size() > 0

    def notify_ready(self) -> None:
        """生产者通知:入队成功后唤醒挂起的消费者(推模型启用时)."""
        condition = self._ensure_condition()
        if condition is None:
            return
        with condition:
            condition.notify_all()

    # 兼容别名:生产者挂点统一走 notify_ready 明名语义
    _notify_ready = notify_ready

    def get_reactors(self, topic: str) -> list[EventReactor]:
        """Get the event reactors."""
        return self._reactor_manager.get_reactor(topic)

    def get_channel_name(self):
        """Get the channel name."""
        return self.channel_name

    def set_public(self, public):
        """Set whether the channel is public."""
        self.public = public

    def is_public(self):
        """Whether the channel is public."""
        return self.public

    def size(self):
        """Get the size of the event queue."""
        return self._event_fifo.size()

    def pop_value(self) -> EventNode | None:
        """Pop an event from the event queue."""
        return self._event_fifo.pop_value()

    def get_top(self) -> EventNode | None:
        """Get the first event of the event queue; None when the queue is empty."""
        return self._event_fifo.get_top()

    def push_event(self, event: EventNode):
        """Push an event into the event queue.

        Push model: notify suspended consumers after a successful enqueue;
        a failed enqueue does not notify (the queue did not change).
        """
        try:
            self._event_fifo.push_value(event)
        except Exception as e:
            LogUtils.error(str(e), EventFIFO.__name__)
            return
        self._notify_ready()

    def dispatch(self, topic, content):
        """Push an event into the event queue (same push-model semantics as `push_event`)."""
        self._event_fifo.dispatch(topic, content, self.channel_name)
        self._notify_ready()

    def register_reactor(self, topic, reactor):
        """Register an event reactor.

        Also records the channels the reactor listens to - only the channel
        initiating the registration knows the channel's name. Previously only
        the topic binding was done without the channel registration, so the
        channel constraint declared by `@event(channel=...)` did not apply at
        all on the dispatch hot path: the channel manager found no
        registration and let everything through on the default channel.
        """
        self._reactor_manager.bind_topic_reactor(topic, reactor)
        self._reactor_manager.register_reactor_channels(reactor.reactor_name, [self.channel_name])

    def refresh_event(self, event):
        """Refresh an event."""
        # Decide whether the event already exists in the pipeline
        if self._event_fifo.has_event(event):  # if it exists
            # Replace the event
            self._event_fifo.replace(event)

    def push_dead_letter(self, event: EventNode, reason: str = "") -> None:
        """Record an event that cannot be delivered.

        An event taken from the queue MUST have a settled destination:
        delivered, requeued, or recorded here. "Popped and neither delivered
        nor requeued" MUST NOT happen - that is exactly how events get lost
        silently.

        Args:
            event: the event that could not be delivered
            reason: the reason it could not be delivered, for troubleshooting
        """
        LogUtils.error(
            f"event moved to dead-letter channel={self.channel_name} "
            f"topic={getattr(event, 'topic', None)} reason={reason}",
            EventChannel.__name__,
        )
        self._dead_letters.append(event)
        if len(self._dead_letters) > self._DEAD_LETTER_LIMIT:
            del self._dead_letters[: len(self._dead_letters) - self._DEAD_LETTER_LIMIT]

    def get_dead_letters(self) -> list:
        """Get the current channel's dead-letter records."""
        return list(self._dead_letters)

condition property

condition: Condition | None

通道的推模型唤醒条件变量;未启用推模型时为 None.

wait_ready

wait_ready(timeout: float) -> bool

消费者挂起等待本通道有事件(推模型启用时).

参数:

名称 类型 描述 默认
timeout float

兜底超时(秒);超时后调用方恢复扫描(防生产者漏 notify)

必需

返回:

类型 描述
bool

True 表示本次调用观察到队列非空(进入时已非空,或被 notify 唤醒);

bool

False 表示等满兜底超时后仍空,或推模型未启用

源代码位于: zoo_framework/event/event_channel.py
def wait_ready(self, timeout: float) -> bool:
    """消费者挂起等待本通道有事件(推模型启用时).

    Args:
        timeout: 兜底超时(秒);超时后调用方恢复扫描(防生产者漏 notify)

    Returns:
        True 表示本次调用观察到队列非空(进入时已非空,或被 notify 唤醒);
        False 表示等满兜底超时后仍空,或推模型未启用
    """
    condition = self._ensure_condition()
    if condition is None:
        return False
    with condition:
        if self._event_fifo.size() > 0:
            return True
        condition.wait(timeout)
        return self._event_fifo.size() > 0

notify_ready

notify_ready() -> None

生产者通知:入队成功后唤醒挂起的消费者(推模型启用时).

源代码位于: zoo_framework/event/event_channel.py
def notify_ready(self) -> None:
    """生产者通知:入队成功后唤醒挂起的消费者(推模型启用时)."""
    condition = self._ensure_condition()
    if condition is None:
        return
    with condition:
        condition.notify_all()

get_reactors

get_reactors(topic: str) -> list[EventReactor]

Get the event reactors.

源代码位于: zoo_framework/event/event_channel.py
def get_reactors(self, topic: str) -> list[EventReactor]:
    """Get the event reactors."""
    return self._reactor_manager.get_reactor(topic)

get_channel_name

get_channel_name()

Get the channel name.

源代码位于: zoo_framework/event/event_channel.py
def get_channel_name(self):
    """Get the channel name."""
    return self.channel_name

set_public

set_public(public)

Set whether the channel is public.

源代码位于: zoo_framework/event/event_channel.py
def set_public(self, public):
    """Set whether the channel is public."""
    self.public = public

is_public

is_public()

Whether the channel is public.

源代码位于: zoo_framework/event/event_channel.py
def is_public(self):
    """Whether the channel is public."""
    return self.public

size

size()

Get the size of the event queue.

源代码位于: zoo_framework/event/event_channel.py
def size(self):
    """Get the size of the event queue."""
    return self._event_fifo.size()

pop_value

pop_value() -> EventNode | None

Pop an event from the event queue.

源代码位于: zoo_framework/event/event_channel.py
def pop_value(self) -> EventNode | None:
    """Pop an event from the event queue."""
    return self._event_fifo.pop_value()

get_top

get_top() -> EventNode | None

Get the first event of the event queue; None when the queue is empty.

源代码位于: zoo_framework/event/event_channel.py
def get_top(self) -> EventNode | None:
    """Get the first event of the event queue; None when the queue is empty."""
    return self._event_fifo.get_top()

push_event

push_event(event: EventNode)

Push an event into the event queue.

Push model: notify suspended consumers after a successful enqueue; a failed enqueue does not notify (the queue did not change).

源代码位于: zoo_framework/event/event_channel.py
def push_event(self, event: EventNode):
    """Push an event into the event queue.

    Push model: notify suspended consumers after a successful enqueue;
    a failed enqueue does not notify (the queue did not change).
    """
    try:
        self._event_fifo.push_value(event)
    except Exception as e:
        LogUtils.error(str(e), EventFIFO.__name__)
        return
    self._notify_ready()

dispatch

dispatch(topic, content)

Push an event into the event queue (same push-model semantics as push_event).

源代码位于: zoo_framework/event/event_channel.py
def dispatch(self, topic, content):
    """Push an event into the event queue (same push-model semantics as `push_event`)."""
    self._event_fifo.dispatch(topic, content, self.channel_name)
    self._notify_ready()

register_reactor

register_reactor(topic, reactor)

Register an event reactor.

Also records the channels the reactor listens to - only the channel initiating the registration knows the channel's name. Previously only the topic binding was done without the channel registration, so the channel constraint declared by @event(channel=...) did not apply at all on the dispatch hot path: the channel manager found no registration and let everything through on the default channel.

源代码位于: zoo_framework/event/event_channel.py
def register_reactor(self, topic, reactor):
    """Register an event reactor.

    Also records the channels the reactor listens to - only the channel
    initiating the registration knows the channel's name. Previously only
    the topic binding was done without the channel registration, so the
    channel constraint declared by `@event(channel=...)` did not apply at
    all on the dispatch hot path: the channel manager found no
    registration and let everything through on the default channel.
    """
    self._reactor_manager.bind_topic_reactor(topic, reactor)
    self._reactor_manager.register_reactor_channels(reactor.reactor_name, [self.channel_name])

refresh_event

refresh_event(event)

Refresh an event.

源代码位于: zoo_framework/event/event_channel.py
def refresh_event(self, event):
    """Refresh an event."""
    # Decide whether the event already exists in the pipeline
    if self._event_fifo.has_event(event):  # if it exists
        # Replace the event
        self._event_fifo.replace(event)

push_dead_letter

push_dead_letter(event: EventNode, reason: str = '') -> None

Record an event that cannot be delivered.

An event taken from the queue MUST have a settled destination: delivered, requeued, or recorded here. "Popped and neither delivered nor requeued" MUST NOT happen - that is exactly how events get lost silently.

参数:

名称 类型 描述 默认
event EventNode

the event that could not be delivered

必需
reason str

the reason it could not be delivered, for troubleshooting

''
源代码位于: zoo_framework/event/event_channel.py
def push_dead_letter(self, event: EventNode, reason: str = "") -> None:
    """Record an event that cannot be delivered.

    An event taken from the queue MUST have a settled destination:
    delivered, requeued, or recorded here. "Popped and neither delivered
    nor requeued" MUST NOT happen - that is exactly how events get lost
    silently.

    Args:
        event: the event that could not be delivered
        reason: the reason it could not be delivered, for troubleshooting
    """
    LogUtils.error(
        f"event moved to dead-letter channel={self.channel_name} "
        f"topic={getattr(event, 'topic', None)} reason={reason}",
        EventChannel.__name__,
    )
    self._dead_letters.append(event)
    if len(self._dead_letters) > self._DEAD_LETTER_LIMIT:
        del self._dead_letters[: len(self._dead_letters) - self._DEAD_LETTER_LIMIT]

get_dead_letters

get_dead_letters() -> list

Get the current channel's dead-letter records.

源代码位于: zoo_framework/event/event_channel.py
def get_dead_letters(self) -> list:
    """Get the current channel's dead-letter records."""
    return list(self._dead_letters)

zoo_framework.event.event_channel_register.EventChannelRegister

The event channel registrar.

Registry ownership (absorb-debt-carriers / #50): _channel_map is state of the process-level instance (this class is registered into the framework container via process_scoped), no longer a class attribute; the previously self-declared [known debt] is lifted by the absorption. The historical dead attributes _single / _instance (legacy singleton markers with zero reads or writes repo-wide) are removed with it.

源代码位于: zoo_framework/event/event_channel_register.py
@process_scoped(thread_safety=ThreadSafety.INSTANCE_GUARANTEED)
class EventChannelRegister(metaclass=_ChannelMapProxyMeta):
    """The event channel registrar.

    Registry ownership (absorb-debt-carriers / #50): `_channel_map` is state
    of the **process-level instance** (this class is registered into the
    framework container via `process_scoped`), no longer a class attribute;
    the previously self-declared [known debt] is lifted by the absorption.
    The historical dead attributes `_single` / `_instance` (legacy singleton
    markers with zero reads or writes repo-wide) are removed with it.
    """

    def __init__(self):
        # The event channel map: instance state, empty at construction;
        # rebuilt on first resolution after a container reset.
        self._channel_map: ThreadSafeDict[str, EventChannel] = ThreadSafeDict()

    @classmethod
    def register(cls, channel_name):
        # get_channel creates in place on a miss and returns, so it never
        # returns None - the original None branch was therefore dead code
        # (proven by type checking) and has been removed. register and
        # get_channel now share one semantics.
        return cls.get_channel(channel_name)

    @classmethod
    def unregister(cls, channel_name):
        cls._channel_map.pop(channel_name)

    @classmethod
    def get_channel(cls, channel_name) -> EventChannel:
        # Use `__getitem__` (returns a non-Optional V) rather than `get()`
        # (returns V | None): on a miss the channel is created in place
        # first, so a value always exists here and no narrowing or cast is
        # needed on the type level.
        if channel_name not in cls._channel_map:
            cls._channel_map[channel_name] = EventChannel(channel_name)
        return cls._channel_map[channel_name]  # type: ignore[no-any-return]  # ThreadSafeDict.__getitem__ 经容器路径推为 Any

    @classmethod
    def get_all_channel(cls):
        return cls._channel_map.get_values()

    @classmethod
    def get_channel_name_list(cls):
        return cls._channel_map.get_keys()

    @classmethod
    def get_channel_count(cls):
        return len(cls._channel_map)

zoo_framework.event.event_register.EventRegister

The event registrar.

源代码位于: zoo_framework/event/event_register.py
@process_scoped(thread_safety=ThreadSafety.SINGLE_THREAD)
class EventRegister:
    """The event registrar."""

    def __init__(self):
        self.event_list = []

    def register(self, event):
        self.event_list.append(event)

    def unregister(self, event):
        self.event_list.remove(event)

    def get_event(self, event_name):
        for event in self.event_list:
            if event.name == event_name:
                return event
        return None

    def get_event_list(self):
        return self.event_list

    def get_event_name_list(self):
        event_name_list = []
        for event in self.event_list:
            event_name_list.append(event.name)
        return event_name_list

    def get_event_by_index(self, index):
        return self.event_list[index]

    def get_event_by_name(self, event_name):
        for event in self.event_list:
            if event.name == event_name:
                return event
        return None

    def get_event_index(self, event_name):
        for index, event in enumerate(self.event_list):
            if event.name == event_name:
                return index
        return None

    def get_event_name_by_index(self, index):
        return self.event_list[index].name

    def get_event_index_by_name(self, event_name):
        for index, event in enumerate(self.event_list):
            if event.name == event_name:
                return index
        return None

    def get_event_count(self):
        return len(self.event_list)

    def get_event_name_count(self):
        return len(self.get_event_name_list())

    def get_event_index_count(self):
        return len(self.get_event_index_list())

    def get_event_index_list(self):
        event_index_list = []
        for index, _event in enumerate(self.event_list):
            event_index_list.append(index)
        return event_index_list

    def get_event_name_index_list(self):
        event_name_index_list = []
        for index, event in enumerate(self.event_list):
            event_name_index_list.append((event.name, index))
        return event_name_index_list

    def get_event_index_by_name_index(self, event_name_index):
        for index, event in enumerate(self.event_list):
            if event.name == event_name_index[0] and index == event_name_index[1]:
                return index
        return None

    def get_event_name_by_index_index(self, event_index_index):
        for index, event in enumerate(self.event_list):
            if index == event_index_index[1] and event.name == event_index_index[0]:
                return event.name
        return None

反应器

zoo_framework.reactor.event_reactor.EventReactor

源代码位于: zoo_framework/reactor/event_reactor.py
class EventReactor:
    def __init__(self, reactor_name):
        self.error_callback = None

        # The event handler method set here - naming history: not 'callback',
        # should be 'event_handler'
        self.handle_callback = None
        # Set the reactor name
        self.reactor_name = reactor_name

        # The join-timeout exemption line (issue #232): 0 means undeclared -
        # follow the global `event:timeout`. A positive value declares the
        # reactor legitimately slow: EventWorker waits at least this long for
        # its future and does not report it as unfinished within that bound.
        # A long wait (e.g. interactive approval) MUST NOT live inside a
        # reactor - move it out of the reactor (see zoo-code-agent#31).
        self.event_timout: float = 0
        # Set the kernel priority (store the EventPriorities member itself,
        # not its .value)
        self.sys_priority: EventPriorities = EventPriorities.NORMAL
        # Set the user priority
        self.user_priority: EventPriorities = EventPriorities.NORMAL
        # The event handling strategy; default is retry once after failure.
        # Retry until success; give up after failure; retry a fixed number
        # of times after failure
        self.retry_strategy: EventRetryStrategy = EventRetryStrategy.RetryOnce
        # The callback after the event is handled successfully
        self.success_callback = None
        # The callback after the event handling fails
        self.retry_times = 0
        # The callback after completion
        self.done_callback = None

    def set_done_callback(self, callback: Callable):
        self.done_callback = callback

    def set_success_callback(self, callback: Callable):
        self.success_callback = callback

    def set_retry_strategy(self, retry_strategy: EventRetryStrategy, retry_times=0):
        """Set the retry strategy."""
        self.retry_times = retry_times
        self.retry_strategy = retry_strategy

    def set_event_callback(self, callback):
        self.handle_callback = callback

    def set_error_callback(self, callback):
        self.error_callback = callback

    @staticmethod
    def _priority_value(priority) -> int:
        """Normalize a priority into an integer.

        Accepts both an `EventPriorities` member and its integer value: the
        historical implementation assigned an int to `sys_priority`, so this
        stays compatible with that usage to keep the same crash from
        recurring.
        """
        if isinstance(priority, EventPriorities):
            return priority.value
        return int(priority)

    def get_priority(self) -> int:
        """The combined priority.

        Segmented encoding: the system priority takes the high bits (shifted
        left by 8), the user priority the low bits; together they decide
        ordering. This MUST be bitwise OR, not bitwise AND - `&` would zero
        the low segment under the high segment, degrading every reactor's
        combined priority to the same value.
        """
        return (self._priority_value(self.sys_priority) << 8) | self._priority_value(
            self.user_priority
        )

    def __index__(self):
        return self.get_priority()

    def set_event_timeout(self, timeout: float | None):
        """Set the join-timeout exemption line (issue #232).

        A non-positive value means undeclared: the reactor follows the global
        `event:timeout` (EVENT_JOIN_TIMEOUT). A positive value declares the
        reactor legitimately slow and exempts it from the "results were not
        collected" warning within that bound.

        Args:
            timeout: the effective timeout in seconds; None or <= 0
                means follow the global default
        """
        self.event_timout = timeout if timeout is not None and timeout > 0 else 0

    def _on_error(self, topic, content, exception: Exception):
        if self.error_callback is not None:
            self.error_callback(self.reactor_name, topic, content, exception)

    def _on_success(self, topic, content):
        if self.success_callback is not None:
            self.success_callback(self.reactor_name, topic, content)

    def _on_done(self, topic, content):
        if self.done_callback is not None:
            self.done_callback(self.reactor_name, topic, content)

    @staticmethod
    def _serialize_content(content):
        return content

    # Retry strategy semantics table (design D5):
    #   RetryOnce / RetryNever      the callback runs at most once; stop on failure
    #   RetryTimes                  the callback runs at most retry_times times
    #   RetryForever / RetryAlways  return only when the callback succeeds
    #                               (RetryAlways is an alias of RetryForever)
    _SINGLE_ATTEMPT_STRATEGIES = (
        EventRetryStrategy.RetryOnce,
        EventRetryStrategy.RetryNever,
    )
    _UNLIMITED_ATTEMPT_STRATEGIES = (
        EventRetryStrategy.RetryForever,
        EventRetryStrategy.RetryAlways,
    )

    # Execute the event according to the retry strategy
    def _execute(self, topic, content):
        req = EventReactorReq(topic, content, self.reactor_name)

        if self.retry_strategy in self._SINGLE_ATTEMPT_STRATEGIES:
            attempts = 1
        elif self.retry_strategy == EventRetryStrategy.RetryTimes:
            attempts = self.retry_times
        elif self.retry_strategy in self._UNLIMITED_ATTEMPT_STRATEGIES:
            attempts = None  # unlimited; return only on success
        else:
            raise Exception(f"unknown event retry strategy: {self.retry_strategy}")

        while attempts is None or attempts > 0:
            if attempts is not None:
                attempts -= 1
            try:
                if self.handle_callback is None:
                    # Give a readable reason when no callback is set; it
                    # falls into the except below all the same, going
                    # through the existing "log error + retry" path (the old
                    # code raised "NoneType is not callable" - same
                    # semantics, but the reason was unreadable).
                    raise ValueError(f"reactor {self.reactor_name} has no event callback set")
                self.handle_callback(req)
                return
            except Exception as e:
                self._on_error(topic, content, e)

    def execute(self, topic, content):
        """Execute the event."""
        # 获得执行方法
        event_handler = self.handle_callback

        if event_handler is None:
            return

        try:
            # 序列化事件内容
            _content = self._serialize_content(content)
            # 执行事件
            self._execute(topic, _content)
            # 执行成功后的回调
            self._on_success(topic, content)
        except Exception as e:
            # 执行失败后的回调
            self._on_error(topic, content, e)
        finally:
            # 执行完成后的回调
            self._on_done(topic, content)

set_retry_strategy

set_retry_strategy(retry_strategy: EventRetryStrategy, retry_times=0)

Set the retry strategy.

源代码位于: zoo_framework/reactor/event_reactor.py
def set_retry_strategy(self, retry_strategy: EventRetryStrategy, retry_times=0):
    """Set the retry strategy."""
    self.retry_times = retry_times
    self.retry_strategy = retry_strategy

get_priority

get_priority() -> int

The combined priority.

Segmented encoding: the system priority takes the high bits (shifted left by 8), the user priority the low bits; together they decide ordering. This MUST be bitwise OR, not bitwise AND - & would zero the low segment under the high segment, degrading every reactor's combined priority to the same value.

源代码位于: zoo_framework/reactor/event_reactor.py
def get_priority(self) -> int:
    """The combined priority.

    Segmented encoding: the system priority takes the high bits (shifted
    left by 8), the user priority the low bits; together they decide
    ordering. This MUST be bitwise OR, not bitwise AND - `&` would zero
    the low segment under the high segment, degrading every reactor's
    combined priority to the same value.
    """
    return (self._priority_value(self.sys_priority) << 8) | self._priority_value(
        self.user_priority
    )

set_event_timeout

set_event_timeout(timeout: float | None)

Set the join-timeout exemption line (issue #232).

A non-positive value means undeclared: the reactor follows the global event:timeout (EVENT_JOIN_TIMEOUT). A positive value declares the reactor legitimately slow and exempts it from the "results were not collected" warning within that bound.

参数:

名称 类型 描述 默认
timeout float | None

the effective timeout in seconds; None or <= 0 means follow the global default

必需
源代码位于: zoo_framework/reactor/event_reactor.py
def set_event_timeout(self, timeout: float | None):
    """Set the join-timeout exemption line (issue #232).

    A non-positive value means undeclared: the reactor follows the global
    `event:timeout` (EVENT_JOIN_TIMEOUT). A positive value declares the
    reactor legitimately slow and exempts it from the "results were not
    collected" warning within that bound.

    Args:
        timeout: the effective timeout in seconds; None or <= 0
            means follow the global default
    """
    self.event_timout = timeout if timeout is not None and timeout > 0 else 0

execute

execute(topic, content)

Execute the event.

源代码位于: zoo_framework/reactor/event_reactor.py
def execute(self, topic, content):
    """Execute the event."""
    # 获得执行方法
    event_handler = self.handle_callback

    if event_handler is None:
        return

    try:
        # 序列化事件内容
        _content = self._serialize_content(content)
        # 执行事件
        self._execute(topic, _content)
        # 执行成功后的回调
        self._on_success(topic, content)
    except Exception as e:
        # 执行失败后的回调
        self._on_error(topic, content, e)
    finally:
        # 执行完成后的回调
        self._on_done(topic, content)

zoo_framework.reactor.event_reactor_manager.EventReactorManager

Event reactor manager.

P1 task: event channel isolation.

Registry ownership (change absorb-debt-carriers / #50): reactor_map is the state of the process-level instance (this class is registered in the framework container via process_scoped), no longer a class attribute - the INSTANCE_GUARANTEED thread-safety declaration is thereby faithful to the implementation; a container reset resets it fully.

源代码位于: zoo_framework/reactor/event_reactor_manager.py
@process_scoped(thread_safety=ThreadSafety.INSTANCE_GUARANTEED)
class EventReactorManager(metaclass=_ReactorMapProxyMeta):
    """Event reactor manager.

    P1 task: event channel isolation.

    Registry ownership (change absorb-debt-carriers / #50): `reactor_map` is
    the state of the **process-level instance** (this class is registered in
    the framework container via `process_scoped`), no longer a class
    attribute - the `INSTANCE_GUARANTEED` thread-safety declaration is thereby
    faithful to the implementation; a container reset resets it fully.
    """

    # 注册表的读-改-写需要整体互斥:ThreadSafeDict 只保护单次操作,
    # 无法阻止两个线程同时为同一主题创建列表。锁留在类级:全进程只有一个
    # 实例(process_scoped),类级锁与实例级锁同粒度,且 classmethod 可直接引用。
    _registry_lock = threading.RLock()

    def __init__(self):
        from zoo_framework.params import EventParams

        # 注册表是实例状态:新建即空表。event_timout 已成为生效超时的自报字段
        # (fix-reactor-timeout / #232),注册 MUST NOT 再以全局值盖章——
        # 盖章会把"未声明"抹掉,运行期调整全局值也对已注册反应器失效。
        # 全局兜底由 EventWorker._effective_timeout 在读取现场解析。
        self.reactor_map: ThreadSafeDict[str, list[EventReactor]] = ThreadSafeDict()
        for reactors in self.reactor_map.values():
            for reactor in reactors:
                reactor.set_event_timeout(EventParams.EVENT_JOIN_TIMEOUT)

    @classmethod
    def dispatch(
        cls,
        topic: str,
        content: Any,
        reactor_name: str | None = None,
        channel: str = ChannelType.DEFAULT.value,
    ):
        """Dispatch an event.

        Executes each reactor under the topic that passes the channel
        validation. An exception raised by one reactor does not block the
        others; returns silently when no reactor matches the topic.

        Args:
            topic: the event topic
            content: the event content
            reactor_name: the reactor name; None means no filtering. The
                legacy sentinel value "default" is also treated as no
                filtering - it comes from this method's old signature and
                conflicts with `get_reactor`'s "filter by name" semantics
                (filtering a reactor named default can never match anything)
            channel: the channel name
        """
        # 显式收窄而非 `in (None, "default")` 三元式:语义完全相同,但后者在 mypy 1.7.1
        # (pre-commit 钉版)下推断为 list[str | None],与 get_reactor 的 list[str] 不符。
        name_filter: list[str] | None = None
        if reactor_name is not None and reactor_name != "default":
            name_filter = [reactor_name]

        for reactor in cls.get_reactor(topic, name_filter, channel):
            try:
                reactor.execute(topic, content)
            except Exception as e:
                LogUtils.error(f"❌ Reactor '{reactor.reactor_name}' execution failed: {e}")

    @classmethod
    def get_reactor(
        cls, topic: str, reactor_names: list[str] | None = None, channel: str | None = None
    ) -> list[Any]:
        """Get the event reactors.

        P1 task: filter event reactors by channel.

        Args:
            topic: the event topic
            reactor_names: the reactor name list
            channel: the channel name (added in P1)

        Returns:
            The reactor list
        """
        result = cls.reactor_map.get(topic)

        if result is None:
            return []

        # 复制一份再过滤:注册可能在其他线程进行,直接迭代原列表不安全
        filter_result = []
        for reactor in list(result):
            # P1:按名称过滤
            if reactor_names is not None and reactor.reactor_name not in reactor_names:
                continue

            # P1:按通道过滤
            if channel is not None and not cls._validate_channel(reactor.reactor_name, channel):
                continue

            filter_result.append(reactor)

        return filter_result

    @classmethod
    def _validate_channel(cls, reactor_name: str, channel: str) -> bool:
        """Check whether a reactor may handle events of the channel.

        Only performs the channel check and does not build a full event
        request object - the latter would generate a UUID per reactor, and
        this method sits on the dispatch hot path.

        Args:
            reactor_name: the reactor name
            channel: the channel name

        Returns:
            Whether it may handle the channel
        """
        return get_channel_manager().can_handle_channel(reactor_name, channel)

    @classmethod
    def register_reactor_channels(cls, reactor_name: str, channels: list[str]) -> None:
        """Register the channels a reactor listens to.

        P1 task: channel isolation configuration.

        Args:
            reactor_name: the reactor name
            channels: the list of listened channels
        """
        channel_manager = get_channel_manager()
        channel_manager.register_reactor_channels(reactor_name, channels)
        LogUtils.info(f"✅ Reactor '{reactor_name}' registered to channels: {channels}")

    @classmethod
    def get_reactor_name_list(cls):
        """Get the event reactor name list."""
        return cls.reactor_map.get_keys()

    @classmethod
    def bind_topic_reactor(cls, topic: str, reactor: EventReactor) -> bool:
        """Register an event reactor.

        **Idempotent**: when the same reactor object is registered for the
        same topic repeatedly, the reactor set under the topic stays
        unchanged - neither appended again nor renamed. The legacy
        implementation renamed and appended in that case, so each scheduler
        construction piled one more record under the topic and grew without
        bound within the process.

        This method may be overridden to implement different event
        registration styles, e.g. adding a retry mechanism.
        """
        with cls._registry_lock:
            reactors = cls.reactor_map.get(topic)
            if reactors is None:
                reactors = []
                cls.reactor_map[topic] = reactors

            if reactor in reactors:
                return True

            reactors.append(reactor)
            # event_timout 盖章已移除(fix-reactor-timeout / #232):该字段现在是
            # 生效超时的自报值,注册侧 MUST NOT 以全局值覆盖使用者的声明;
            # 未声明者的全局兜底由 EventWorker 在读取现场解析。
            return True

    @classmethod
    def dispatch_by_channel(
        cls, topic: str, content: Any, channel: str = ChannelType.DEFAULT.value
    ) -> None:
        """Dispatch an event by channel.

        P1 task: broadcast events by channel.

        Args:
            topic: the event topic
            content: the event content
            channel: the target channel
        """
        channel_manager = get_channel_manager()

        # 获取该通道下所有的响应器
        all_reactors = []
        for reactor_name in cls.get_reactor_name_list():
            if channel_manager.can_handle_channel(reactor_name, channel):
                reactors = cls.get_reactor(topic, [reactor_name], channel)
                all_reactors.extend(reactors)

        # 执行所有匹配的响应器
        for reactor in all_reactors:
            try:
                reactor.execute(topic, content)
            except Exception as e:
                LogUtils.error(f"❌ Reactor '{reactor.reactor_name}' execution failed: {e}")

dispatch classmethod

dispatch(topic: str, content: Any, reactor_name: str | None = None, channel: str = ChannelType.DEFAULT.value)

Dispatch an event.

Executes each reactor under the topic that passes the channel validation. An exception raised by one reactor does not block the others; returns silently when no reactor matches the topic.

参数:

名称 类型 描述 默认
topic str

the event topic

必需
content Any

the event content

必需
reactor_name str | None

the reactor name; None means no filtering. The legacy sentinel value "default" is also treated as no filtering - it comes from this method's old signature and conflicts with get_reactor's "filter by name" semantics (filtering a reactor named default can never match anything)

None
channel str

the channel name

DEFAULT.value
源代码位于: zoo_framework/reactor/event_reactor_manager.py
@classmethod
def dispatch(
    cls,
    topic: str,
    content: Any,
    reactor_name: str | None = None,
    channel: str = ChannelType.DEFAULT.value,
):
    """Dispatch an event.

    Executes each reactor under the topic that passes the channel
    validation. An exception raised by one reactor does not block the
    others; returns silently when no reactor matches the topic.

    Args:
        topic: the event topic
        content: the event content
        reactor_name: the reactor name; None means no filtering. The
            legacy sentinel value "default" is also treated as no
            filtering - it comes from this method's old signature and
            conflicts with `get_reactor`'s "filter by name" semantics
            (filtering a reactor named default can never match anything)
        channel: the channel name
    """
    # 显式收窄而非 `in (None, "default")` 三元式:语义完全相同,但后者在 mypy 1.7.1
    # (pre-commit 钉版)下推断为 list[str | None],与 get_reactor 的 list[str] 不符。
    name_filter: list[str] | None = None
    if reactor_name is not None and reactor_name != "default":
        name_filter = [reactor_name]

    for reactor in cls.get_reactor(topic, name_filter, channel):
        try:
            reactor.execute(topic, content)
        except Exception as e:
            LogUtils.error(f"❌ Reactor '{reactor.reactor_name}' execution failed: {e}")

get_reactor classmethod

get_reactor(topic: str, reactor_names: list[str] | None = None, channel: str | None = None) -> list[Any]

Get the event reactors.

P1 task: filter event reactors by channel.

参数:

名称 类型 描述 默认
topic str

the event topic

必需
reactor_names list[str] | None

the reactor name list

None
channel str | None

the channel name (added in P1)

None

返回:

类型 描述
list[Any]

The reactor list

源代码位于: zoo_framework/reactor/event_reactor_manager.py
@classmethod
def get_reactor(
    cls, topic: str, reactor_names: list[str] | None = None, channel: str | None = None
) -> list[Any]:
    """Get the event reactors.

    P1 task: filter event reactors by channel.

    Args:
        topic: the event topic
        reactor_names: the reactor name list
        channel: the channel name (added in P1)

    Returns:
        The reactor list
    """
    result = cls.reactor_map.get(topic)

    if result is None:
        return []

    # 复制一份再过滤:注册可能在其他线程进行,直接迭代原列表不安全
    filter_result = []
    for reactor in list(result):
        # P1:按名称过滤
        if reactor_names is not None and reactor.reactor_name not in reactor_names:
            continue

        # P1:按通道过滤
        if channel is not None and not cls._validate_channel(reactor.reactor_name, channel):
            continue

        filter_result.append(reactor)

    return filter_result

register_reactor_channels classmethod

register_reactor_channels(reactor_name: str, channels: list[str]) -> None

Register the channels a reactor listens to.

P1 task: channel isolation configuration.

参数:

名称 类型 描述 默认
reactor_name str

the reactor name

必需
channels list[str]

the list of listened channels

必需
源代码位于: zoo_framework/reactor/event_reactor_manager.py
@classmethod
def register_reactor_channels(cls, reactor_name: str, channels: list[str]) -> None:
    """Register the channels a reactor listens to.

    P1 task: channel isolation configuration.

    Args:
        reactor_name: the reactor name
        channels: the list of listened channels
    """
    channel_manager = get_channel_manager()
    channel_manager.register_reactor_channels(reactor_name, channels)
    LogUtils.info(f"✅ Reactor '{reactor_name}' registered to channels: {channels}")

get_reactor_name_list classmethod

get_reactor_name_list()

Get the event reactor name list.

源代码位于: zoo_framework/reactor/event_reactor_manager.py
@classmethod
def get_reactor_name_list(cls):
    """Get the event reactor name list."""
    return cls.reactor_map.get_keys()

bind_topic_reactor classmethod

bind_topic_reactor(topic: str, reactor: EventReactor) -> bool

Register an event reactor.

Idempotent: when the same reactor object is registered for the same topic repeatedly, the reactor set under the topic stays unchanged - neither appended again nor renamed. The legacy implementation renamed and appended in that case, so each scheduler construction piled one more record under the topic and grew without bound within the process.

This method may be overridden to implement different event registration styles, e.g. adding a retry mechanism.

源代码位于: zoo_framework/reactor/event_reactor_manager.py
@classmethod
def bind_topic_reactor(cls, topic: str, reactor: EventReactor) -> bool:
    """Register an event reactor.

    **Idempotent**: when the same reactor object is registered for the
    same topic repeatedly, the reactor set under the topic stays
    unchanged - neither appended again nor renamed. The legacy
    implementation renamed and appended in that case, so each scheduler
    construction piled one more record under the topic and grew without
    bound within the process.

    This method may be overridden to implement different event
    registration styles, e.g. adding a retry mechanism.
    """
    with cls._registry_lock:
        reactors = cls.reactor_map.get(topic)
        if reactors is None:
            reactors = []
            cls.reactor_map[topic] = reactors

        if reactor in reactors:
            return True

        reactors.append(reactor)
        # event_timout 盖章已移除(fix-reactor-timeout / #232):该字段现在是
        # 生效超时的自报值,注册侧 MUST NOT 以全局值覆盖使用者的声明;
        # 未声明者的全局兜底由 EventWorker 在读取现场解析。
        return True

dispatch_by_channel classmethod

dispatch_by_channel(topic: str, content: Any, channel: str = ChannelType.DEFAULT.value) -> None

Dispatch an event by channel.

P1 task: broadcast events by channel.

参数:

名称 类型 描述 默认
topic str

the event topic

必需
content Any

the event content

必需
channel str

the target channel

DEFAULT.value
源代码位于: zoo_framework/reactor/event_reactor_manager.py
@classmethod
def dispatch_by_channel(
    cls, topic: str, content: Any, channel: str = ChannelType.DEFAULT.value
) -> None:
    """Dispatch an event by channel.

    P1 task: broadcast events by channel.

    Args:
        topic: the event topic
        content: the event content
        channel: the target channel
    """
    channel_manager = get_channel_manager()

    # 获取该通道下所有的响应器
    all_reactors = []
    for reactor_name in cls.get_reactor_name_list():
        if channel_manager.can_handle_channel(reactor_name, channel):
            reactors = cls.get_reactor(topic, [reactor_name], channel)
            all_reactors.extend(reactors)

    # 执行所有匹配的响应器
    for reactor in all_reactors:
        try:
            reactor.execute(topic, content)
        except Exception as e:
            LogUtils.error(f"❌ Reactor '{reactor.reactor_name}' execution failed: {e}")

zoo_framework.reactor.waiter_result_reactor.WaiterResultReactor

Bases: EventReactor

The Waiter result reactor.

Subscribes to the unified result topic (WaiterConstant.WORKER_RESULT_TOPIC). The reactor itself does no business processing; it has two duties:

  • make that topic a first-class citizen on the event pipeline - bind_topic_reactor needs a registered target
  • provide a filter-by-worker-name entry point: set worker_names to receive results from only the named Workers

worker_names holds registration names (the suffix-free identity), so worker_names=['ok'] receives the results of Worker ok whatever its instance ordinal is (ok_1, ok_2, ...). Matching is exact, not prefix-based: ok MUST NOT match a Worker named ok2. The ordinal-bearing instance name may also be listed explicitly, for callers that already know it. An empty/None worker_names means receive from all Workers.

Received results are handed over via the optional on_result callback; the reactor itself never accumulates results, avoiding unbounded growth over long runs.

源代码位于: zoo_framework/reactor/waiter_result_reactor.py
@process_scoped(thread_safety=ThreadSafety.SINGLE_THREAD)
class WaiterResultReactor(EventReactor):
    """The Waiter result reactor.

    Subscribes to the unified result topic
    (``WaiterConstant.WORKER_RESULT_TOPIC``). The reactor itself does no
    business processing; it has two duties:

    - make that topic a first-class citizen on the event pipeline -
      ``bind_topic_reactor`` needs a registered target
    - provide a filter-by-worker-name entry point: set ``worker_names`` to
      receive results from only the named Workers

    ``worker_names`` holds **registration names** (the suffix-free identity),
    so ``worker_names=['ok']`` receives the results of Worker ``ok`` whatever
    its instance ordinal is (``ok_1``, ``ok_2``, ...). Matching is exact, not
    prefix-based: ``ok`` MUST NOT match a Worker named ``ok2``. The
    ordinal-bearing instance name may also be listed explicitly, for callers
    that already know it. An empty/None ``worker_names`` means receive from
    all Workers.

    Received results are handed over via the optional ``on_result`` callback;
    the reactor itself never accumulates results, avoiding unbounded growth
    over long runs.
    """

    def __init__(self):
        super().__init__("WaiterResultReactor")
        self._event_timeout = 0
        # Receive results from only these Workers; None means no filtering
        self.worker_names: list[str] | None = None
        # The optional receive callback, signature (WorkerResult) -> None
        self.on_result = None
        self.set_event_callback(self._on_result)

    def accepts(self, result: Any) -> bool:
        """Decide whether this result should be accepted by the reactor.

        The filter is declared with the Worker's **registration name**
        (``worker_names=['ok']``), while the result carries the instance name
        including the ordinal (``ok_1``). Matching therefore compares the
        ordinal-free identity rather than the raw instance name; comparing the
        two directly never matched, which silently filtered **everything**
        out (issue #229).

        A result is accepted when any of its identities is in the filter:
        ``registry_name`` (the suffix-free field), the trailing-ordinal-stripped
        form of ``worker_name`` (covers results built outside
        ``BaseWorker.run``), or ``worker_name`` itself (the exact instance
        name, kept for backward compatibility). Matching stays exact - this is
        a real filter, not a prefix match.

        Args:
            result: the Worker execution result

        Returns:
            whether to accept
        """
        if self.worker_names is None:
            return True
        return bool(set(self.worker_names) & self._identity_candidates(result))

    @staticmethod
    def _identity_candidates(result: Any) -> set[str]:
        """Collect the identities a result can be matched by.

        Args:
            result: the Worker execution result

        Returns:
            The candidate identity strings; empty when the result carries none
        """
        candidates: set[str] = set()

        registry_name = getattr(result, "registry_name", None)
        if registry_name:
            candidates.add(str(registry_name))

        worker_name = getattr(result, "worker_name", None)
        if worker_name:
            worker_name = str(worker_name)
            candidates.add(worker_name)
            stripped = _ORDINAL_SUFFIX_RE.sub("", worker_name)
            if stripped:
                candidates.add(stripped)

        return candidates

    def _on_result(self, req):
        result = req.content
        if not self.accepts(result):
            return
        if self.on_result is not None:
            self.on_result(result)

accepts

accepts(result: Any) -> bool

Decide whether this result should be accepted by the reactor.

The filter is declared with the Worker's registration name (worker_names=['ok']), while the result carries the instance name including the ordinal (ok_1). Matching therefore compares the ordinal-free identity rather than the raw instance name; comparing the two directly never matched, which silently filtered everything out (issue #229).

A result is accepted when any of its identities is in the filter: registry_name (the suffix-free field), the trailing-ordinal-stripped form of worker_name (covers results built outside BaseWorker.run), or worker_name itself (the exact instance name, kept for backward compatibility). Matching stays exact - this is a real filter, not a prefix match.

参数:

名称 类型 描述 默认
result Any

the Worker execution result

必需

返回:

类型 描述
bool

whether to accept

源代码位于: zoo_framework/reactor/waiter_result_reactor.py
def accepts(self, result: Any) -> bool:
    """Decide whether this result should be accepted by the reactor.

    The filter is declared with the Worker's **registration name**
    (``worker_names=['ok']``), while the result carries the instance name
    including the ordinal (``ok_1``). Matching therefore compares the
    ordinal-free identity rather than the raw instance name; comparing the
    two directly never matched, which silently filtered **everything**
    out (issue #229).

    A result is accepted when any of its identities is in the filter:
    ``registry_name`` (the suffix-free field), the trailing-ordinal-stripped
    form of ``worker_name`` (covers results built outside
    ``BaseWorker.run``), or ``worker_name`` itself (the exact instance
    name, kept for backward compatibility). Matching stays exact - this is
    a real filter, not a prefix match.

    Args:
        result: the Worker execution result

    Returns:
        whether to accept
    """
    if self.worker_names is None:
        return True
    return bool(set(self.worker_names) & self._identity_candidates(result))

zoo_framework.reactor.event_priorities

EventPriorities

Bases: Enum

Event priorities for the reactor.

源代码位于: zoo_framework/reactor/event_priorities.py
class EventPriorities(Enum):
    """Event priorities for the reactor."""

    # Lowest priority, executed first.
    LOWEST = 0

    # Low priority.
    LOW = 1

    # Normal priority.
    NORMAL = 2

    # High priority.
    HIGH = 3

    # Highest priority, executed last.
    HIGHEST = 4

    # Monitor priority, executed last.
    MONITOR = 5

zoo_framework.reactor.event_retry_strategy.EventRetryStrategy

Bases: Enum

The event retry strategy.

源代码位于: zoo_framework/reactor/event_retry_strategy.py
class EventRetryStrategy(Enum):
    """The event retry strategy."""

    RetryOnce = 0

    RetryAlways = 1

    RetryNever = 2

    RetryForever = 3

    RetryTimes = 4

队列

zoo_framework.fifo.base_fifo.BaseFIFO

Bases: Generic[_T]

FIFO base class.

源代码位于: zoo_framework/fifo/base_fifo.py
class BaseFIFO(Generic[_T]):
    """FIFO base class."""

    def __init__(self):
        self._fifo: deque[_T] = deque()

    def push_value(self, value: _T) -> None:
        """Enqueue."""
        self._fifo.append(value)

    def pop_value(self) -> _T | None:
        """Dequeue; returns None when the queue is empty."""
        if len(self._fifo) <= 0:
            return None

        return self._fifo.popleft()

    def push_values(self, values: list[_T]) -> None:
        """Enqueue in batch."""
        self._fifo.extend(values)

    def size(self) -> int:
        """The current queue length."""
        return len(self._fifo)

    def push_values_if_null(self, value: _T) -> None:
        """Enqueue only when the value is not already in the queue."""
        if value not in self._fifo:
            self._fifo.append(value)

push_value

push_value(value: _T) -> None

Enqueue.

源代码位于: zoo_framework/fifo/base_fifo.py
def push_value(self, value: _T) -> None:
    """Enqueue."""
    self._fifo.append(value)

pop_value

pop_value() -> _T | None

Dequeue; returns None when the queue is empty.

源代码位于: zoo_framework/fifo/base_fifo.py
def pop_value(self) -> _T | None:
    """Dequeue; returns None when the queue is empty."""
    if len(self._fifo) <= 0:
        return None

    return self._fifo.popleft()

push_values

push_values(values: list[_T]) -> None

Enqueue in batch.

源代码位于: zoo_framework/fifo/base_fifo.py
def push_values(self, values: list[_T]) -> None:
    """Enqueue in batch."""
    self._fifo.extend(values)

size

size() -> int

The current queue length.

源代码位于: zoo_framework/fifo/base_fifo.py
def size(self) -> int:
    """The current queue length."""
    return len(self._fifo)

push_values_if_null

push_values_if_null(value: _T) -> None

Enqueue only when the value is not already in the queue.

源代码位于: zoo_framework/fifo/base_fifo.py
def push_values_if_null(self, value: _T) -> None:
    """Enqueue only when the value is not already in the queue."""
    if value not in self._fifo:
        self._fifo.append(value)

zoo_framework.fifo.event_fifo.EventFIFO

Bases: BaseFIFO[EventNode]

The event queue.

源代码位于: zoo_framework/fifo/event_fifo.py
class EventFIFO(BaseFIFO[EventNode]):
    """The event queue."""

    def push_value(self, value):
        """Push an event into the event queue."""
        try:
            if isinstance(value, dict):
                node = EventNode(**value)
            elif isinstance(value, EventNode):
                node = value
            else:
                # For values that are neither dict nor EventNode, create a
                # default event node
                node = EventNode(topic="default", content=str(value))
            super().push_value(node)
        except Exception as e:
            LogUtils.error(str(e), EventFIFO.__name__)

    def dispatch(self, topic, content, provider_name="default"):
        """Push an event into the event queue.

        Note: `provider_name` MUST be written onto the event's
        `channel_name` - it decides which channel queue the event belongs
        to; dropping it would land all events on the default channel and
        channel isolation would break.
        """
        node = EventNode(topic=topic, content=content, channel_name=provider_name)
        super().push_value(node)

    def get_top(self) -> EventNode | None:
        """Get the first event of the event queue."""
        if self.size() > 0:
            return self._fifo[0]
        return None

    def has_event(self, event):
        """Whether the event exists.

        Membership check is required: `list.index()` raises `ValueError` on
        a miss rather than returning -1, and the normal path of this
        method's callers (`EventChannel.refresh_event`,
        `EventProvider.refresh`) is exactly "do nothing on a miss".
        """
        return event in self._fifo

    def replace(self, event):
        """Replace the event; do nothing when it does not exist."""
        if event not in self._fifo:
            return
        self._fifo[self._fifo.index(event)] = event

push_value

push_value(value)

Push an event into the event queue.

源代码位于: zoo_framework/fifo/event_fifo.py
def push_value(self, value):
    """Push an event into the event queue."""
    try:
        if isinstance(value, dict):
            node = EventNode(**value)
        elif isinstance(value, EventNode):
            node = value
        else:
            # For values that are neither dict nor EventNode, create a
            # default event node
            node = EventNode(topic="default", content=str(value))
        super().push_value(node)
    except Exception as e:
        LogUtils.error(str(e), EventFIFO.__name__)

dispatch

dispatch(topic, content, provider_name='default')

Push an event into the event queue.

Note: provider_name MUST be written onto the event's channel_name - it decides which channel queue the event belongs to; dropping it would land all events on the default channel and channel isolation would break.

源代码位于: zoo_framework/fifo/event_fifo.py
def dispatch(self, topic, content, provider_name="default"):
    """Push an event into the event queue.

    Note: `provider_name` MUST be written onto the event's
    `channel_name` - it decides which channel queue the event belongs
    to; dropping it would land all events on the default channel and
    channel isolation would break.
    """
    node = EventNode(topic=topic, content=content, channel_name=provider_name)
    super().push_value(node)

get_top

get_top() -> EventNode | None

Get the first event of the event queue.

源代码位于: zoo_framework/fifo/event_fifo.py
def get_top(self) -> EventNode | None:
    """Get the first event of the event queue."""
    if self.size() > 0:
        return self._fifo[0]
    return None

has_event

has_event(event)

Whether the event exists.

Membership check is required: list.index() raises ValueError on a miss rather than returning -1, and the normal path of this method's callers (EventChannel.refresh_event, EventProvider.refresh) is exactly "do nothing on a miss".

源代码位于: zoo_framework/fifo/event_fifo.py
def has_event(self, event):
    """Whether the event exists.

    Membership check is required: `list.index()` raises `ValueError` on
    a miss rather than returning -1, and the normal path of this
    method's callers (`EventChannel.refresh_event`,
    `EventProvider.refresh`) is exactly "do nothing on a miss".
    """
    return event in self._fifo

replace

replace(event)

Replace the event; do nothing when it does not exist.

源代码位于: zoo_framework/fifo/event_fifo.py
def replace(self, event):
    """Replace the event; do nothing when it does not exist."""
    if event not in self._fifo:
        return
    self._fifo[self._fifo.index(event)] = event

zoo_framework.fifo.delay_fifo.DelayFIFO

Bases: BaseFIFO[DelayFIFONode]

The delayed queue.

源代码位于: zoo_framework/fifo/delay_fifo.py
class DelayFIFO(BaseFIFO[DelayFIFONode]):
    """The delayed queue."""

    def __init__(self):
        super().__init__()
        # Same-shaped storage as the base class (align-execution-primitives:
        # deque, O(1) dequeue); this class historically reset it to a list
        # here, and the two sources of truth MUST be replaced in sync.
        self._fifo = deque()

    def push_value(self, value: DelayFIFONode):
        self._fifo.append(value)

    def pop_value(self):
        if len(self._fifo) <= 0:
            return None

        return self._fifo.popleft()

    def is_exist(self, value):
        return value in self._fifo

    def size(self):
        return len(self._fifo)

    def get_expire_values(self):
        """Get the expired values.

        The original signature carried ``current_time`` while the body called
        ``node.is_expire(current_time)`` - yet
        ``DelayFIFONode.is_expire()`` **takes no argument**: by design the
        node reads its own monotonic clock (its docstring notes that wall
        clock would be misled by NTP corrections or DST jumps), and that
        signature is directly exercised by multiple tests in
        tests/test_execution_time.py. So the old call raised TypeError at
        runtime. The method had no callers, which is why it never
        surfaced; the mismatch only became visible to type checking after
        `_fifo` was parameterized as `list[DelayFIFONode]`.
        """
        values = []
        for node in self._fifo:
            if node.is_expire():
                values.append(node)
        return values

get_expire_values

get_expire_values()

Get the expired values.

The original signature carried current_time while the body called node.is_expire(current_time) - yet DelayFIFONode.is_expire() takes no argument: by design the node reads its own monotonic clock (its docstring notes that wall clock would be misled by NTP corrections or DST jumps), and that signature is directly exercised by multiple tests in tests/test_execution_time.py. So the old call raised TypeError at runtime. The method had no callers, which is why it never surfaced; the mismatch only became visible to type checking after _fifo was parameterized as list[DelayFIFONode].

源代码位于: zoo_framework/fifo/delay_fifo.py
def get_expire_values(self):
    """Get the expired values.

    The original signature carried ``current_time`` while the body called
    ``node.is_expire(current_time)`` - yet
    ``DelayFIFONode.is_expire()`` **takes no argument**: by design the
    node reads its own monotonic clock (its docstring notes that wall
    clock would be misled by NTP corrections or DST jumps), and that
    signature is directly exercised by multiple tests in
    tests/test_execution_time.py. So the old call raised TypeError at
    runtime. The method had no callers, which is why it never
    surfaced; the mismatch only became visible to type checking after
    `_fifo` was parameterized as `list[DelayFIFONode]`.
    """
    values = []
    for node in self._fifo:
        if node.is_expire():
            values.append(node)
    return values

zoo_framework.fifo.single_fifo.SingleFIFO

Bases: BaseFIFO[Any]

A single-value queue: the same value enqueues once, with its position recorded.

Note: index_list is still a class attribute (shared across instances); left unchanged here - a known issue.

源代码位于: zoo_framework/fifo/single_fifo.py
class SingleFIFO(BaseFIFO[Any]):
    """A single-value queue: the same value enqueues once, with its position recorded.

    Note: `index_list` is still a **class attribute** (shared across
    instances); left unchanged here - a known issue.
    """

    index_list: dict = {}

    def __init__(self):
        BaseFIFO.__init__(self)
        self.pop_pointer = 0

    def push_value(self, value):
        """Enqueue (the same value only once); return the value's position.

        Two misuses corrected here:
        - `list.index()` raises `ValueError` on a miss; it cannot serve as a
          "membership check";
        - `list` has no `push` method; appending uses `append`.
        """
        if value not in self._fifo:
            self._fifo.append(value)
        index = self._fifo.index(value)
        self.index_list[value] = index
        return index

    def pop_value(self):
        if len(self._fifo) <= self.pop_pointer:
            raise Exception("no value to pop")
        value = self._fifo[self.pop_pointer]
        self.pop_pointer += 1
        return value

    def get_value_by_index(self, index):
        return self._fifo[index]

    def get_index(self, value):
        return self.index_list.get(value)

push_value

push_value(value)

Enqueue (the same value only once); return the value's position.

Two misuses corrected here: - list.index() raises ValueError on a miss; it cannot serve as a "membership check"; - list has no push method; appending uses append.

源代码位于: zoo_framework/fifo/single_fifo.py
def push_value(self, value):
    """Enqueue (the same value only once); return the value's position.

    Two misuses corrected here:
    - `list.index()` raises `ValueError` on a miss; it cannot serve as a
      "membership check";
    - `list` has no `push` method; appending uses `append`.
    """
    if value not in self._fifo:
        self._fifo.append(value)
    index = self._fifo.index(value)
    self.index_list[value] = index
    return index