feat: 重构为 agent / channels / flows / db 分层架构
- agent: 新增 base.py 执行基类、execution.py 执行器、web.py 网络工具, middlewares/steering.py 中间件;移除旧的 agent.py - channels: 新增 ChannelManager、registry、models 与 IM 渠道(企业微信), 扩展 base.py - flows: 新增 agent_task / bus / cron / scheduler / service / stream / rpc / processor / tasks / model_settings / builtin;移除旧的 task.py - db: 新增 sqlite schema 与 repo 层 - docs: 新增架构说明、Channel × EventBus 设计、任务编写教程 - 依赖新增 aiosqlite / httpx / langgraph / primp / pydantic / ripgrep / wecom-aibot-sdk;新增 bot 命令入口 - 测试:232 passed
This commit is contained in:
1 parent
94421e5c2b
commit
fbb01c4c83
65 files changed
+15322
-173
No files matched your search
@@ -0,0 +1,489 @@
|
||||
# Channel × EventBus 重构设计(含 RPC 扩展)
|
||||
|
||||
- 状态:**阶段 1、2 已实施;阶段 3 待做**
|
||||
- 日期:2026-11-09(阶段 2 实施完成)
|
||||
- 范围:`src/bot042/channels/`、`src/bot042/flows/`、`docs/`
|
||||
- 目标读者:项目维护者
|
||||
|
||||
---
|
||||
|
||||
## 1. 背景
|
||||
|
||||
当前 `channels/` 与 `flows/` 各自维护了一套完整的消息调度:
|
||||
|
||||
- 通道层:`ChannelManager._queues` + `_worker_loop` + `_session_locks` + `_inflight` + `handle_inbound` 里的
|
||||
`processor` 异步生成器 + `MessageEvent` 投递。
|
||||
- 编排层:`EventBus`(`on/once/emit`)+ `TaskRunner`(`_Slot`、overlap、`TaskRun`、`runs/stats`)。
|
||||
|
||||
两套并存带来的实际问题:
|
||||
|
||||
| 能力 | 通道层现状 | 编排层现状 | 结果 |
|
||||
|---|---|---|---|
|
||||
| 串行 | `_session_locks`(按 subject) | `_Slot` + `overlap`(按任务) | 语义重复且不同,改一处不影响另一处 |
|
||||
| 排队/背压 | `asyncio.Queue`(默认无界) | `QUEUE` 积压上限 1 | 两个上限,都不适合聊天连发 |
|
||||
| 在途统计 | `_inflight` + `wait_idle()` | `runs()` / `stats()` | 收尾要分别等待,容易漏 |
|
||||
| 错误口径 | `MessageEvent.error_event` | `task.failed` 事件 | 两套可观测指标 |
|
||||
| 处理入口 | `processor` 生成器 | `Task.run()` | 同一件事两种写法 |
|
||||
|
||||
结论:消息处理逻辑实际上"藏在通道层",`EventBus` 只服务于脚本任务(`tasks/scheduler`),
|
||||
所以两个子系统关联很弱。
|
||||
|
||||
## 2. 设计目标
|
||||
|
||||
1. **EventBus 成为唯一分发面**:入站消息、出站发送、定时触发、任务结果都通过总线。
|
||||
2. **channel 退化为协议适配层**:连接、解析、发送原语;不再有队列、worker、会话锁、处理器。
|
||||
3. **执行统一收敛到 `TaskRunner`**:串行/排队/重试/统计只有一套实现。
|
||||
4. **给 EventBus 增加 RPC**:请求-响应语义,用来解决"事件化之后拿不到结果"的问题(尤其是发送失败反馈)。
|
||||
5. 保持 `channels` 不 `import bot042.flows`(依赖方向不变),通过注入回调解耦。
|
||||
|
||||
## 3. 非目标(本轮不做)
|
||||
|
||||
- 跨进程 / 跨机器消息(仍是进程内总线)。
|
||||
- RPC 多播聚合、流式响应、双向长连接。
|
||||
- 消息合批(`batch_window_ms`):本轮**放弃**,留作后续扩展点(见 §15)。
|
||||
- 通道 SDK 的重连、ACK、回调线程管理——这些必须留在 channel 内。
|
||||
- 持久化消息队列(进程重启丢在途消息,与现状一致)。
|
||||
|
||||
---
|
||||
|
||||
## 4. 总体架构
|
||||
|
||||
```
|
||||
┌─ 协议适配(channels/)──────────────────────────────────────────────┐
|
||||
│ BaseChannel: start/stop · parse_inbound · send_text/send_content │
|
||||
│ send_typing/send_delta/flush · _known_subjects │
|
||||
│ │
|
||||
│ 入站唯一出口: publish(InboundMessage) ← 注入的同步回调 │
|
||||
│ 出站唯一入口: send_text(...) ← 被 RPC server 调用 │
|
||||
│ 没有:队列 / worker / 会话锁 / processor / MessageEvent 流 │
|
||||
└───────────────────────────────┬──────────────────────────────────────┘
|
||||
│ bootstrap 注入的 publisher
|
||||
┌───────────────────────────────▼──────────────────────────────────────┐
|
||||
│ 分发(flows/bus.py + flows/rpc.py) │
|
||||
│ EventBus: publish / subscribe / once / error 路由 / 线程安全桥 │
|
||||
│ RpcHub: serve(method, handler) / await call(method, payload) │
|
||||
│ 事件空间: channel.inbound · channel.* · task.* · schedule.* · rpc.* │
|
||||
└───────────────────────────────┬──────────────────────────────────────┘
|
||||
│ 订阅 + 分区串行
|
||||
┌───────────────────────────────▼──────────────────────────────────────┐
|
||||
│ 执行(flows/tasks.py) │
|
||||
│ TaskRunner: 每 (task, partition_key) 一条串行链 │
|
||||
│ Task: run() 或 build_graph()+ainvoke;deps 注入外部服务 │
|
||||
└──────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
启动装配(伪代码):
|
||||
|
||||
```python
|
||||
bus = EventBus()
|
||||
bus.bind_loop()
|
||||
|
||||
registry = ChannelRegistry() # 原 ChannelManager 收缩后
|
||||
runner = TaskRunner(bus, deps=AppServices(channels=registry, settings=settings))
|
||||
|
||||
bus.serve("channel.send", registry.rpc_send) # 出站 RPC server
|
||||
publisher = lambda msg: bus.publish_threadsafe("channel.inbound", ChannelMessage.of(msg))
|
||||
registry.attach_all(publish=publisher) # 每个 channel 注入 publish
|
||||
|
||||
runner.register(AgentReply) # 内置任务
|
||||
runner.add_task("channel.agent", EventTrigger(event="channel.inbound"))
|
||||
await runner.start()
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. EventBus 扩展
|
||||
|
||||
### 5.1 保持不变的语义
|
||||
|
||||
- `emit`(fire-and-forget):handler 必须 `async`;异常路由到 `error` 事件;不向调用方抛。
|
||||
- `on/once` 注册;`wait_for_complete()`;`cancel()`。
|
||||
- 上一轮已修复的约束:重复注册同一 handler 抛 `BusError`;handler 同步异常不外泄。
|
||||
|
||||
### 5.2 新增别名
|
||||
|
||||
贴合"subscribe / publish"的叫法,纯别名、不改语义:
|
||||
|
||||
```python
|
||||
publish = emit # 方法别名
|
||||
subscribe = on
|
||||
subscribe_once = once
|
||||
```
|
||||
|
||||
### 5.3 线程安全桥(必须)
|
||||
|
||||
SDK 回调常在工作线程,`emit` 需要事件循环:
|
||||
|
||||
```python
|
||||
def bind_loop(self, loop: asyncio.AbstractEventLoop | None = None) -> None: ...
|
||||
def publish_threadsafe(self, event: str, *args: object) -> None:
|
||||
"""同线程直接 emit;跨线程用 loop.call_soon_threadsafe。未 bind 时抛 BusError。"""
|
||||
```
|
||||
|
||||
有了它,`ChannelManager` 的 `_queues`/`_worker_loop`/`enqueue` 才有条件删除。
|
||||
|
||||
### 5.4 RPC 封装(新增 `flows/rpc.py`)
|
||||
|
||||
#### 语义
|
||||
|
||||
"有返回值的 publish":调用方 `await` 拿到响应或异常,超时可控。**进程内**。
|
||||
|
||||
```python
|
||||
class RpcError(Exception): ...
|
||||
class RpcTimeoutError(RpcError): ...
|
||||
class RpcRemoteError(RpcError): # 远端 handler 抛异常
|
||||
remote_type: str
|
||||
remote_message: str
|
||||
class RpcAborted(RpcError): ... # 总线关闭 / cancel()
|
||||
|
||||
RpcHandler = Callable[[object], Awaitable[object]]
|
||||
|
||||
class RpcHub:
|
||||
def __init__(self, bus: EventBus, *, pending_limit: int = 1000) -> None: ...
|
||||
def serve(self, method: str, handler: RpcHandler) -> None: ...
|
||||
def unserve(self, method: str) -> None: ...
|
||||
def served(self) -> list[str]: ...
|
||||
async def call(self, method: str, payload: object = None, *, timeout: float | None = 5.0) -> object: ...
|
||||
def abort_all(self) -> None: ...
|
||||
```
|
||||
|
||||
#### 时序
|
||||
|
||||
```
|
||||
caller EventBus(+RpcHub) server handler
|
||||
│ call(m, p) ──创建 Future(cid)──► publish("rpc.request",
|
||||
│ RpcRequest(cid, m, p))
|
||||
│ │ RpcHub._on_request
|
||||
│ ├─ 查 method 路由 ──► await handler(p)
|
||||
│ │ │
|
||||
│ │◄── 返回值/异常 ─────────┘
|
||||
│ ├─ publish("rpc.reply",
|
||||
│ │ RpcReply(cid, ok, value|error))
|
||||
│◄── Future 解析 / 抛错 ◄────────────────┘
|
||||
```
|
||||
|
||||
- 只用**两个**总线事件:`rpc.request`、`rpc.reply`,方法名在载荷里路由。
|
||||
理由:避免动态事件名(`rpc.<method>`)污染事件空间,也不需要在 `EventBus` 里加通配订阅。
|
||||
- 同一时刻同一 `method` 只允许**一个** server(`serve` 重复注册报 `ValueError`)。
|
||||
- 默认 **first-response-wins**:响应到达即完成 Future,后续回复丢弃(单响应者场景已够)。
|
||||
- 请求方 `timeout` 到点:清理 pending 并抛 `RpcTimeoutError`;迟到响应被忽略。
|
||||
- `pending` 数量超 `pending_limit`:直接抛 `RpcError`(防泄漏)。
|
||||
- 总线 `cancel()` / 应用关停:`abort_all()` 让所有 pending 抛 `RpcAborted`。
|
||||
- 审计(可选,默认关闭):`rpc.audit` 事件带 method/耗时/结果,避免默认产生噪音。
|
||||
|
||||
#### 为什么用 RPC 而不是"两段事件"
|
||||
|
||||
普通事件化出站的痛点是**发送结果无法回传**:任务 `emit("channel.send", ...)` 之后不知道成功失败。
|
||||
RPC 让"事件化"与"能拿到结果"同时成立:
|
||||
|
||||
```python
|
||||
# 任务内
|
||||
await self.deps.bus.call(
|
||||
"channel.send",
|
||||
OutboundText(channel_id=cid, subject_id=uid, text=answer),
|
||||
timeout=10,
|
||||
)
|
||||
```
|
||||
|
||||
```python
|
||||
# bootstrap
|
||||
async def _send(payload: object) -> object:
|
||||
assert isinstance(payload, OutboundText)
|
||||
await registry.send_text(payload.channel_id, payload.subject_id, payload.text)
|
||||
return {"sent": True}
|
||||
|
||||
bus.serve("channel.send", _send)
|
||||
```
|
||||
|
||||
#### 与 TaskRunner 的关系
|
||||
|
||||
RPC 不替代任务触发:`task.*` / `schedule.*` / `channel.inbound` 仍是 fire-and-forget 事件;
|
||||
RPC 只用于"需要结果"的调用(出站发送、配置查询、工具调用代理)。
|
||||
`RpcHub` 是 `EventBus` 之上的**薄封装**,不引入新的调度器。
|
||||
|
||||
---
|
||||
|
||||
## 6. Channel 层重构
|
||||
|
||||
### 6.1 职责收缩
|
||||
|
||||
| 现有 | 处置 |
|
||||
|---|---|
|
||||
| `handle_inbound()` 的 processor 事件流(typing/delta/thinking/tool/text/error/completed 投递) | **删除**,替换为 `publish(raw)` |
|
||||
| `_processor` / `has_processor` / `attach(processor=)` | 删除 |
|
||||
| `MessageProcessor` / `MessageEvent` | 契约退役(`MessageEvent` 的投递语义由 §6.3 原语承担) |
|
||||
| `parse_inbound` / `_preprocess` / `_register_subject` | 保留 |
|
||||
| `_enqueue_callback` / `enqueue` | 保留为线程安全入口,内部转 `publish` |
|
||||
| `reply_text` / `reply_content` | 保留(出站 RPC server 调它) |
|
||||
| `_TypingKeepalive` | 保留为可选工具:`channel.typing(subject)` 上下文管理器 |
|
||||
| `get_session_key` / `should_batch_inbound` / `merge_inbound` | 保留(`get_session_key` 供分区键;后两个本轮不用) |
|
||||
|
||||
### 6.2 新的入站入口
|
||||
|
||||
```python
|
||||
class BaseChannel:
|
||||
def attach(self, publish: PublishFn) -> None:
|
||||
"""注入入站发布回调(由 registry 在注册时调用)。"""
|
||||
|
||||
def publish(self, raw: object) -> None:
|
||||
"""解析 → 预处理 → 主体登记 → 交给 publish 回调。线程安全。"""
|
||||
```
|
||||
|
||||
`publish` 回调在 bootstrap 里就是 `bus.publish_threadsafe("channel.inbound", ...)`,
|
||||
**channel 仍然不感知 EventBus**(不 import flows),保留可单测性。
|
||||
|
||||
### 6.3 `ChannelManager` → `ChannelRegistry`
|
||||
|
||||
保留:注册/启用/禁用/移除、运行时状态、`start/stop`、出站路由。
|
||||
删除:`_queues`、`_workers`、`_session_locks`、`_inflight`、`wait_idle`、`enqueue`、`_worker_loop`、`_drain_same_session`。
|
||||
|
||||
对外接口(新增):
|
||||
|
||||
```python
|
||||
def get_latest_message(
|
||||
self, channel_id: str, *, subject_id: str | None = None
|
||||
) -> InboundMessage | None: ...
|
||||
|
||||
async def send_text(self, channel_id: str, subject_id: str, text: str) -> None: ...
|
||||
async def send_content(
|
||||
self, channel_id: str, subject_id: str, parts: list[ContentPart]
|
||||
) -> None: ...
|
||||
|
||||
def resolve_subject(self, channel_id: str, subject_id: str) -> ChannelSubject: ...
|
||||
def list_subjects(self, channel_id: str) -> list[ChannelSubject]: ...
|
||||
```
|
||||
|
||||
- 最新消息:`_latest[(channel_id, subject_id)]` + `_latest_by_channel[channel_id]`,进程内,`model_copy(deep=True)` 返回。
|
||||
- 语义:**最近收到**的消息,不保证等于当前正在处理的那条(任务应以 `payload.message` 为准)。
|
||||
- `send_*`:`resolve_subject` 未登记时抛 `LookupError`(主动推送依赖首条消息登记路由)。
|
||||
|
||||
### 6.4 发送原语(替代 processor 的 delta 缓冲)
|
||||
|
||||
```python
|
||||
async def send_typing(self, subject: ChannelSubject) -> None: ...
|
||||
async def send_delta(self, subject: ChannelSubject, text: str) -> None: ...
|
||||
async def flush_delta(self, subject: ChannelSubject) -> None: ...
|
||||
```
|
||||
|
||||
任务需要流式输出时自行组合;`typing` 的周期刷新由 `channel.typing(subject)` 上下文管理器负责。
|
||||
|
||||
---
|
||||
|
||||
## 7. 消息处理任务化
|
||||
|
||||
### 7.1 分区串行("一个渠道一条链")
|
||||
|
||||
```python
|
||||
class Task:
|
||||
def partition_key(self, ctx: TaskContext) -> str:
|
||||
"""并发分区键;默认 ''(= 现有单槽行为)。"""
|
||||
return ""
|
||||
```
|
||||
|
||||
- `_slots` 键由 `task_name` 变为 `(task_name, key)`;`REPLACE` 的 `current` 同样按分区隔离。
|
||||
- 同一分区内:`QUEUE` 串行、`SKIP`/`PARALLEL`/`REPLACE` 语义不变(作用域变成分区)。
|
||||
- 不同分区完全并行。
|
||||
|
||||
内置消息任务:
|
||||
|
||||
```python
|
||||
class AgentReply(Task):
|
||||
name = "channel.agent"
|
||||
overlap = OverlapPolicy.QUEUE
|
||||
|
||||
def partition_key(self, ctx: TaskContext) -> str:
|
||||
env = ctx.payload
|
||||
return getattr(env, "db_session_id", "") or getattr(env, "channel_id", "")
|
||||
```
|
||||
|
||||
> 分区键必须与会话历史(`messages.session_id`)的键一致,内置任务取
|
||||
> `ChannelMessage.db_session_id`(群聊下是群 ID);**不要**用渠道锁键
|
||||
> `session_key`——群聊里它是发送者,会把同一会话拆成多条并发链。
|
||||
> 若希望"整条渠道全串行",返回 `channel_id` 即可,机制不变。
|
||||
|
||||
### 7.2 队列上限与溢出
|
||||
|
||||
现状 `QUEUE` 积压上限 1,对聊天等于丢消息。改为每分区一个 `deque`:
|
||||
|
||||
| 参数 | 默认 | 说明 |
|
||||
|---|---|---|
|
||||
| `queue_limit` | 100 | 每分区最大积压 |
|
||||
| `overflow` | `drop_new` | 可选 `drop_oldest` / `block` |
|
||||
|
||||
- `drop_new`:新触发记 `RunStatus.FAILED`(`error="queue overflow"`)并发 `task.failed`,便于告警。
|
||||
- `block`:`_dispatch` 变协程等待空位(会阻塞渠道 publisher → 需注意死锁,默认不用)。
|
||||
- `drop_oldest`:丢最早一条并记 `SKIPPED`。
|
||||
|
||||
### 7.3 依赖注入
|
||||
|
||||
```python
|
||||
@dataclass(frozen=True)
|
||||
class AppServices:
|
||||
channels: ChannelRegistry
|
||||
bus: EventBus
|
||||
settings: Settings
|
||||
|
||||
runner = TaskRunner(bus, deps=AppServices(...))
|
||||
# _execute 内:
|
||||
instance = task_cls(ctx)
|
||||
instance.deps = self._deps # 属性注入,不改子类构造函数(零破坏)
|
||||
```
|
||||
|
||||
- `Task.deps` 为类属性 `None` 默认;不放进 `TaskContext`(`ctx` 会随 `task.<名>` 事件外发,服务对象不可序列化且破坏 frozen 语义)。
|
||||
|
||||
### 7.4 内置任务 `channel.agent`
|
||||
|
||||
把现在 `flows/processor.py` 的逻辑搬进任务:
|
||||
|
||||
```
|
||||
payload(ChannelMessage) → 校验文本 → init_db/ensure_session
|
||||
→ list_messages → build_history(去悬空 user / 字符预算 / 首条 user)
|
||||
→ add_message(user) → run_task(cache=AgentCache)
|
||||
→ answer 非空才 add_message(assistant)
|
||||
→ bus.call("channel.send", OutboundText(...))
|
||||
```
|
||||
|
||||
失败 → 记录 `TaskRun.FAILED` + `task.failed` 事件;是否向用户回错误文案由任务决定
|
||||
(默认回一句"处理消息时出错,请稍后再试。",走同一个 `channel.send`)。
|
||||
|
||||
### 7.5 收尾顺序
|
||||
|
||||
```python
|
||||
await registry.start()
|
||||
await runner.start()
|
||||
await channel.wait_closed() # CLI: EOF/exit;IM: 显式关停
|
||||
await runner.wait_idle() # 新增:所有分区队列空 + 无在途(带 timeout)
|
||||
await runner.stop()
|
||||
await registry.stop()
|
||||
```
|
||||
|
||||
`runner.wait_idle()` 是新增接口;**不要**再用旧的 `manager.wait_idle()`(消息 emit 后它立刻认为空闲)。
|
||||
|
||||
---
|
||||
|
||||
## 8. 出站方案对比
|
||||
|
||||
| | A. 直调服务 | B. RPC 出站(推荐) |
|
||||
|---|---|---|
|
||||
| 写法 | `await self.deps.channels.send_text(...)` | `await self.deps.bus.call("channel.send", OutboundText(...))` |
|
||||
| 错误反馈 | try/except 直接拿到 | `RpcRemoteError` / `RpcTimeoutError` |
|
||||
| 可拦截(审计/脱敏/限流) | 需改任务或包一层 | 在 server 端统一拦截 |
|
||||
| 与总线的一致性 | 出入站不对称 | 入站事件、出站 RPC,同一套总线 |
|
||||
| 依赖 | 任务依赖 registry | 任务只依赖 bus |
|
||||
|
||||
推荐 **B**,并把 A 作为"没有 bus 的单元测试"替代路径保留。
|
||||
|
||||
---
|
||||
|
||||
## 9. 事件契约总表
|
||||
|
||||
| 事件 | 方向 | 载荷 | 说明 |
|
||||
|---|---|---|---|
|
||||
| `channel.inbound` | channel → bus | `ChannelMessage` | 已解析/已登记主体;fire-and-forget |
|
||||
| `channel.send` | 任务 → registry | `OutboundText` / `OutboundContent` | **RPC**,返回 `{"sent": True}` 或抛错 |
|
||||
| `schedule.<name>` | scheduler → bus | `Fire` | 定时触发 |
|
||||
| `schedule.fired` | scheduler → bus | `Fire` | 全局审计 |
|
||||
| `task.<name>` | runner → bus | `TaskContext` | 任务链 |
|
||||
| `task.done` / `task.failed` | runner → bus | `TaskRun` | 运行结果 |
|
||||
| `rpc.request` / `rpc.reply` | RpcHub 内部 | `RpcRequest` / `RpcReply` | 不建议业务直接订阅 |
|
||||
| `error` | bus 内部 | 异常 | handler 异常统一出口 |
|
||||
|
||||
```python
|
||||
class ChannelMessage(BaseModel):
|
||||
model_config = ConfigDict(frozen=True)
|
||||
channel_id: str
|
||||
channel_type: str
|
||||
subject_id: str
|
||||
session_key: str
|
||||
message: InboundMessage
|
||||
received_at: datetime
|
||||
|
||||
class OutboundText(BaseModel):
|
||||
channel_id: str
|
||||
subject_id: str
|
||||
text: str
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 10. 迁移计划
|
||||
|
||||
### 阶段 1:加桥,不改行为(✅ 已实施)
|
||||
|
||||
- `EventBus`:`bind_loop` / `publish_threadsafe` / `publish`·`subscribe` 别名。
|
||||
- `flows/rpc.py`:`RpcHub` + 单测(成功/超时/远端异常/未注册方法/并发)。
|
||||
- `BaseChannel.attach(publish=...)` 与旧 `processor` 双轨:`handle_inbound` 先 `publish` 再走旧逻辑。
|
||||
- `ChannelRegistry` 补 `get_latest_message` / `send_text` / `resolve_subject`(复用现有 `_known_subjects`)。
|
||||
|
||||
验收:现有 141 个测试全绿 + 新增 RPC 测试;行为无变化(旧 processor 仍在跑)。
|
||||
|
||||
### 阶段 2:切执行面(✅ 已实施)
|
||||
|
||||
- `TaskRunner`:分区槽、`queue_limit`/`overflow`、`wait_idle`、`deps`。
|
||||
- 内置 `AgentReply` 任务;`run_session` 改新链路;`processor` 仅保留未迁移调用方。
|
||||
- 出站 RPC server 注册。
|
||||
|
||||
验收:CLI 会话端到端可用;同一 session 消息严格串行、不同 session 并行;发送失败可在任务侧捕获。
|
||||
|
||||
### 阶段 3:拆通道
|
||||
|
||||
- 删除 `_queues`/`_workers`/`_session_locks`/`_inflight`/`wait_idle`/`_worker_loop`/`_drain_same_session`。
|
||||
- 删除 `MessageProcessor`/`MessageEvent` 契约与 `flows/processor.py`。
|
||||
- 重写 `tests/test_channels*`、迁移 `test_processor.py`。
|
||||
|
||||
验收:`channels` 中不再出现"队列/处理器"字样;全量测试与 lint 通过。
|
||||
|
||||
---
|
||||
|
||||
## 11. 影响面
|
||||
|
||||
| 文件 | 改动 |
|
||||
|---|---|
|
||||
| `flows/bus.py` | `bind_loop` / `publish_threadsafe` / 别名 / `abort` 钩子 |
|
||||
| `flows/rpc.py` | **新增** RpcHub 与错误类型 |
|
||||
| `flows/tasks.py` | 分区槽、队列上限、`wait_idle`、`deps`、`partition_key` |
|
||||
| `flows/builtin.py` | **新增** `AgentReply` 等内置任务 |
|
||||
| `flows/processor.py` | 逻辑迁出,阶段 3 删除 |
|
||||
| `flows/session.py` | 装配与收尾顺序重写 |
|
||||
| `flows/__init__.py` | 导出 `RpcHub`/错误类型/`ChannelMessage`/`OutboundText` |
|
||||
| `channels/base.py` | `publish` 入口;删除 processor 流;`typing/delta` 原语;`resolve_subject` |
|
||||
| `channels/manager.py` | 收缩为 `ChannelRegistry`;两个对外接口;RPC server 实现 |
|
||||
| `channels/models.py` | `MessageEvent`/`MessageProcessor` 退役 |
|
||||
| `__main__.py` | 装配调整(一次性任务路径不变) |
|
||||
| `tests/*` | 见 §12 |
|
||||
| `docs/task-tutorial.md` | 新增"渠道消息任务"一节,链接本文 |
|
||||
|
||||
## 12. 测试计划
|
||||
|
||||
| 模块 | 用例 |
|
||||
|---|---|
|
||||
| RPC | 正常往返;超时;远端异常映射;未注册方法;并发 100 次;超时后迟到响应被丢弃;`abort_all` |
|
||||
| EventBus | 线程安全发布(跨线程 emit);重复注册;handler 异常不外泄(已有) |
|
||||
| channel | `publish` 只调用一次;主体登记;线程安全;`resolve_subject` 未知时报错 |
|
||||
| registry | `get_latest_message` 返回副本;`send_text` 路由到正确 subject;未知 channel/subject 报错 |
|
||||
| TaskRunner | 同分区串行(顺序断言);跨分区并行(最大并发 > 1);队列溢出策略;`wait_idle` 真等到完成;`deps` 注入 |
|
||||
| 会话 | CLI 端到端:多条消息串行处理、回复经 RPC 发出、退出时冲刷 |
|
||||
|
||||
## 13. 风险与缓解
|
||||
|
||||
| 风险 | 缓解 |
|
||||
|---|---|
|
||||
| 删除 manager 队列后入站无背压 | TaskRunner 分区队列设上限 + 溢出告警;必要时 `overflow=block` |
|
||||
| `block` 策略可能导致 publisher 阻塞 → 渠道回调卡死 | 默认 `drop_new`;`block` 仅在显式配置时启用并加超时 |
|
||||
| RPC 增加一跳,延迟增加 | 进程内一跳(microtask 级),可忽略;出站若极端敏感可走直调 A |
|
||||
| 事件化后调试链路变长 | 统一 `run_id`/`correlation_id` 打日志;`rpc.audit` 可选开启 |
|
||||
| 阶段 1 双轨期存在两条处理路径 | 双轨仅一个阶段,验收标准明确(旧测试全绿 + 新事件被发布) |
|
||||
|
||||
## 14. 已确认决策(2026-11-09)
|
||||
|
||||
1. **分区键**:`session_key`(一用户/一群一条链,同渠道不同用户并行)。`channel_id` 作为 `session_key` 缺失时的兜底。
|
||||
2. **队列溢出**:`drop_new` —— 新触发记 `RunStatus.FAILED`(`error="queue overflow"`)+ 发 `task.failed`,不做背压阻塞。
|
||||
3. **出站**:采用 **RPC 出站**(§8 B),方法名 `channel.send`;直调 `registry.send_text` 保留为单元测试与无总线场景的替代路径。
|
||||
4. **RPC 命名**:方法名点分(`channel.send`);总线事件固定为 `rpc.request` / `rpc.reply`,不引入 `rpc.<method>` 动态事件。
|
||||
|
||||
## 15. 后续扩展(本轮不做)
|
||||
|
||||
- `batch_window_ms`:同分区短窗口合并多条入站消息再派发(替代原 `merge_inbound`)。
|
||||
- RPC 多响应者/聚合模式、服务发现(`served()` 已预留)。
|
||||
- 出站事件旁路审计:`channel.outbound`(只观测不发送)与 RPC 并存。
|
||||
- 任务级并发上限(每分区 `max_concurrency`)。
|
||||
Reference in new issue
Block a user