refactor(types): govern event registry and snapshot contracts

This commit is contained in:
jxxghp
2026-10-16 11:08:28 +08:00
parent 37a5787bf3
commit e1b6d478e6
5 changed files with 44 additions and 34 deletions

View File

@@ -3,12 +3,20 @@
from __future__ import annotations
import inspect
from collections.abc import Callable
from typing import Any
from collections.abc import Callable, Mapping
from typing import Any, Optional, Union, cast
from app.runtime.log import logger
from app.schemas.types import ChainEventType, EventType
_EventHandler = Callable[..., object]
_BroadcastSubscribers = dict[EventType, dict[str, _EventHandler]]
_ChainSubscribers = dict[ChainEventType, dict[str, tuple[int, _EventHandler]]]
_SubscriberView = Mapping[
Union[EventType, ChainEventType],
Mapping[str, Union[_EventHandler, tuple[int, _EventHandler]]],
]
class EventRegistry:
"""集中管理事件处理器注册、启停和不可变调度快照。"""
@@ -17,10 +25,10 @@ class EventRegistry:
self,
*,
lock: Any,
broadcast_subscribers: Callable[[], dict],
chain_subscribers: Callable[[], dict],
disabled_handlers: Callable[[], set],
disabled_classes: Callable[[], set],
broadcast_subscribers: Callable[[], _BroadcastSubscribers],
chain_subscribers: Callable[[], _ChainSubscribers],
disabled_handlers: Callable[[], set[str]],
disabled_classes: Callable[[], set[str]],
) -> None:
"""绑定由兼容门面持有的存储,便于热重载和旧测试替换快照。"""
self._lock = lock
@@ -39,13 +47,13 @@ class EventRegistry:
return module.__name__ if module else "unknown_module"
@staticmethod
def handler_identifier(target: Callable | type) -> str:
def handler_identifier(target: Union[_EventHandler, type[object]]) -> str:
"""返回包含模块和限定名的稳定处理器标识。"""
module_name = EventRegistry._module_name(target)
return f"{module_name}.{target.__qualname__}"
@classmethod
def handler_class_identifier(cls, handler: Callable) -> str | None:
def handler_class_identifier(cls, handler: _EventHandler) -> str | None:
"""返回可调用对象所属类的稳定标识;自由函数返回空值。"""
if inspect.ismethod(handler) and hasattr(handler, "__self__"):
return cls.handler_identifier(handler.__self__.__class__)
@@ -57,7 +65,7 @@ class EventRegistry:
module_name = cls._module_name(handler)
return f"{module_name}.{'.'.join(qualname_parts[:-1])}"
def is_handler_enabled(self, handler: Callable) -> bool:
def is_handler_enabled(self, handler: _EventHandler) -> bool:
"""判断处理器及其所属类是否均处于启用状态。"""
handler_id = self.handler_identifier(handler)
class_id = self.handler_class_identifier(handler)
@@ -72,10 +80,10 @@ class EventRegistry:
def check(self, event_type: EventType | ChainEventType) -> bool:
"""检查指定事件是否存在启用的处理器。"""
if isinstance(event_type, ChainEventType):
handlers = self._chain_subscribers().get(event_type, {})
chain_handlers = self._chain_subscribers().get(event_type, {})
return any(
self.is_handler_enabled(handler)
for _, handler in handlers.values()
for _, handler in chain_handlers.values()
)
handlers = self._broadcast_subscribers().get(event_type, {})
return any(self.is_handler_enabled(handler) for handler in handlers.values())
@@ -83,17 +91,17 @@ class EventRegistry:
def add(
self,
event_type: EventType | ChainEventType,
handler: Callable,
handler: _EventHandler,
priority: int,
) -> None:
"""注册处理器,并为链式事件按优先级维护稳定顺序。"""
with self._lock:
handler_id = self.handler_identifier(handler)
if isinstance(event_type, ChainEventType):
subscribers = self._chain_subscribers()
handlers = subscribers.setdefault(event_type, {})
existed = handler_id in handlers
handlers.pop(handler_id, None)
chain_subscribers = self._chain_subscribers()
chain_handlers = chain_subscribers.setdefault(event_type, {})
existed = handler_id in chain_handlers
chain_handlers.pop(handler_id, None)
if not existed:
logger.debug(
"Subscribed to chain event: %s, Priority: %s - %s",
@@ -101,9 +109,9 @@ class EventRegistry:
priority,
handler_id,
)
handlers[handler_id] = (priority, handler)
subscribers[event_type] = dict(
sorted(handlers.items(), key=lambda item: item[1][0])
chain_handlers[handler_id] = (priority, handler)
chain_subscribers[event_type] = dict(
sorted(chain_handlers.items(), key=lambda item: item[1][0])
)
return
subscribers = self._broadcast_subscribers()
@@ -121,7 +129,7 @@ class EventRegistry:
def remove(
self,
event_type: EventType | ChainEventType,
handler: Callable,
handler: _EventHandler,
) -> None:
"""从指定事件中移除处理器。"""
with self._lock:
@@ -147,7 +155,7 @@ class EventRegistry:
handler_id,
)
def disable(self, target: Callable | type) -> None:
def disable(self, target: Union[_EventHandler, type[object]]) -> None:
"""禁用单个处理器或整个处理器类。"""
identifier = self.handler_identifier(target)
if isinstance(target, type):
@@ -157,7 +165,7 @@ class EventRegistry:
self._disabled_handlers().add(identifier)
logger.debug("Disabled event handler - %s", identifier)
def enable(self, target: Callable | type) -> None:
def enable(self, target: Union[_EventHandler, type[object]]) -> None:
"""重新启用单个处理器或整个处理器类。"""
identifier = self.handler_identifier(target)
if isinstance(target, type):
@@ -167,32 +175,36 @@ class EventRegistry:
self._disabled_handlers().discard(identifier)
logger.debug("Enabled event handler - %s", identifier)
def chain_snapshot(self, event_type: ChainEventType) -> tuple:
def chain_snapshot(
self, event_type: ChainEventType,
) -> tuple[tuple[str, tuple[int, _EventHandler]], ...]:
"""返回当前链式订阅快照,运行期变更从下一次事件生效。"""
with self._lock:
return tuple(self._chain_subscribers().get(event_type, {}).items())
def broadcast_snapshot(self, event_type: EventType) -> tuple:
def broadcast_snapshot(self, event_type: EventType) -> tuple[tuple[str, _EventHandler], ...]:
"""返回当前广播订阅快照,运行期变更从下一次事件生效。"""
with self._lock:
return tuple(
self._broadcast_subscribers().get(event_type, {}).items()
)
def visualize(self) -> list[dict]:
def visualize(self) -> list[dict[str, Union[str, int]]]:
"""导出所有订阅处理器的事件、优先级和启停状态。"""
result = []
# 两类注册表的键均属于事件类型联合;只读视图扩宽键域,保留 dict 合并的快照语义。
combined = {
**self._broadcast_subscribers(),
**self._chain_subscribers(),
**cast(_SubscriberView, self._broadcast_subscribers()),
**cast(_SubscriberView, self._chain_subscribers()),
}
for event_type, subscribers in combined.items():
for handler_id, handler_data in subscribers.items():
priority: Optional[int]
if isinstance(handler_data, tuple) and len(handler_data) == 2:
priority, handler = handler_data
else:
priority, handler = None, handler_data
item = {
item: dict[str, Union[str, int]] = {
"event_type": event_type.value,
"handler_identifier": handler_id,
"status": (

View File

@@ -75,7 +75,7 @@ uv run --locked --no-sync python scripts/architecture/complexity.py
回调和返回值类型;全仓错误计数为零并不保证单独纳入 strict frontier 后也为零。
2026-10-16 开始逐文件清理类型债务,`app/domain/title.py` 通过局部可空类型声明保留
既有搜索解析行为,并纳入严格清单;当前清单共 55 个文件(54 个生产文件和 1 个脚本)。
既有搜索解析行为,并纳入严格清单;当前清单共 56 个文件(55 个生产文件和 1 个脚本)。
每个治理提交只修改一个生产文件及其必要测试、门禁配置、真实下降基线和指标文档。
验收同时检查完整严格清单与全宿主 Linux 分析,避免 `follow_imports = skip` 隐藏依赖
签名冲突;不通过忽略诊断或放宽类型合同接受回退。最新文件清单以 `mypy.ini` 为准,

View File

@@ -106,9 +106,9 @@ ARCH-201 至 ARCH-204 均达到实现、验证、提交、推送和远端门禁
| Model/Oper 事务债务 | 0 | 自建 Session、自动事务装饰器、直接 commit/rollback 等基线均为零 |
| Module Contract | 215 specs / 211 methods / 263 calls | 动态方法名为 0;分类事实富化通过显式合同进入插件调度,旧 YAML 分类方法已移除;download 新增 custom_words 可选参数,旧 provider 签名通过显式合同兼容 |
| Event Contract | 53 | 均已有 payload model,但当前全部是 diagnostic enforcement |
| Python 源码量 | 371,940 行 | 本次重新扫描物理行数,排除 `app/plugins/**`;74 个文件超过 1,000 行,12 个超过 2,000 行;源码尺寸仅作观察 |
| Python 源码量 | 371,952 行 | 本次重新扫描物理行数,排除 `app/plugins/**`;74 个文件超过 1,000 行,12 个超过 2,000 行;源码尺寸仅作观察 |
| 长方法 | 309 个超过 80 行 | 本次 AST 扫描排除 `app/plugins/**`;61 个超过 150 行,17 个超过 250 行;新增函数仍受 C901/嵌套深度门禁约束 |
| 全量 mypy 历史债务 | 9,089 / 497 文件 | 通知排版补齐 Slack 消息块类型,历史债务减少 2 项;工作流资源过滤改用领域对象调用过滤链,恢复的节点输出在消费前归一化,并收紧可空资源列表的类型低水位;消息媒体交互类型债务已清零,canonical Facade 与 endpoint 类型边界已补齐,低水位只允许继续下降;微信 ClawBot 入站 item_list 媒体解析改为按子项键名分派后,类型错误减少 4 项;站点解析器分享率改用浮点初值,类型错误减少 20 项;本次下载与文件安全修复再减少 3 项,逐文件逐错误码无增长 |
| 全量 mypy 历史债务 | 9,075 / 496 文件 | 通知排版补齐 Slack 消息块类型,历史债务减少 2 项;工作流资源过滤改用领域对象调用过滤链,恢复的节点输出在消费前归一化,并收紧可空资源列表的类型低水位;消息媒体交互类型债务已清零,canonical Facade 与 endpoint 类型边界已补齐,低水位只允许继续下降;微信 ClawBot 入站 item_list 媒体解析改为按子项键名分派后,类型错误减少 4 项;站点解析器分享率改用浮点初值,类型错误减少 20 项;本次下载与文件安全修复再减少 3 项,逐文件逐错误码无增长 |
| Ruff 历史诊断 | 100 | 低水位门禁通过,但规则集只覆盖 `E4/E7/E9/F/I` |
| 覆盖率固定基线 | Application 80.00%,Domain 80.00% | Chain、Runtime、Agent、Adapter、Startup 未进入包级覆盖率门禁 |

View File

@@ -27,6 +27,7 @@ files =
app/runtime/thread.py,
app/runtime/tasks.py,
app/runtime/event/contracts.py,
app/runtime/event/registry.py,
app/runtime/event/errors.py,
app/runtime/extensions/module/contracts.py,
app/runtime/extensions/module/dispatcher.py,

View File

@@ -2420,9 +2420,6 @@
"app/runtime/event/dispatch.py": {
"type-arg": 5
},
"app/runtime/event/registry.py": {
"type-arg": 14
},
"app/runtime/events.py": {
"list-item": 1,
"misc": 1,