refactor: 工程化收尾——去 pyee、预计算解析计划与派生密钥、命名与接口一致化

以「语义可读、逻辑清晰、减少心智负担」为目标,不追求极致速度:

- **移除 pyee 依赖**:EventEmitter 改为内置的 `事件名 → handler 列表` 注册表
  (on() 追加、emit() 顺序遍历)。SDK 用不到 pyee 的 once/new_listener/错误
  事件机制,去掉后少一个依赖、分发语义一眼可读。注册语义不变(同函数重复
  注册只生效一次),并补测试锁定「重复注册只生效一次」「按注册顺序执行」。
  破坏性:once/remove_listener 等装饰性 API 不再提供。

- **去掉热路径上的重复计算**(纯缓存,不改语义):
  · payloads 按类缓存解析计划(字段名 + 是否嵌套 Author),不再每次事件重跑
    dataclasses.fields 与联合类型解包;未收录字段照旧忽略(新增回归测试,
    线上 payload 会带 author.union_openid 这类字段)。实测 7.5µs → 2.5µs。
  · crypto 按 AppSecret 缓存派生私钥(每个 webhook 请求都要验签,派生一次
    约 40µs);公钥派生只差 3µs,不再多缓存一层。

- **命名与接口一致性**:
  · WebsocketConnecter.reply_helper → send_helper(它从出站缓冲取帧发送,
    原名会让人误以为还有 reply 队列;model.py 的对应注释同步)
  · Connecter 由 typing.Protocol 改为 abc.ABC,与 BaseProtocol 风格统一

- **webhook 去重改摊还清理**:过期判定按当前 id 做(O(1),且 TTL 外重发的
  同一 id 仍按新事件处理——原先的写法在阈值清理下会误判为重复,已由测试
  抓出并修正),整表清过期项只在表长到阈值时执行,不再每请求 O(n) 扫描。

测试 85 全绿(新增未知字段/解析计划缓存/注册语义/去重摊还与 TTL 过期),
ruff check/format + pyright 干净。文档 ARCHITECTURE/API/CHANGELOG 同步。
This commit is contained in:
snowy-yang committed 2026-09-20 22:45:34 +08:00
1 parent 1a7111973b
commit 1552c5207b
13 files changed
+174 -52

No files matched your search

+32
View File
@@ -20,6 +20,38 @@ def test_sequence_only_moves_forward():
assert s.seq == 7
@pytest.mark.asyncio
async def test_same_handler_registered_twice_runs_once():
"""同名事件重复注册同一函数只生效一次(沿用 pyee 的语义)。"""
emitter = EventEmitter()
calls: list[str] = []
async def handler(_):
calls.append("hit")
emitter.on("READY", handler)
emitter.on("READY", handler)
await emitter.emit({"op": Opcode.DISPATCH, "t": "READY", "d": {}})
assert calls == ["hit"]
@pytest.mark.asyncio
async def test_handlers_run_in_registration_order():
emitter = EventEmitter()
order: list[int] = []
@emitter.on("READY")
async def first(_):
order.append(1)
@emitter.on("READY")
async def second(_):
order.append(2)
await emitter.emit({"op": Opcode.DISPATCH, "t": "READY", "d": {}})
assert order == [1, 2]
@pytest.mark.asyncio
async def test_handler_exception_is_isolated():
queue = EventQueue()