docs: 同步进程职责与推送链路

AGENTS 改写 Dual Binary Split。Worker 是唯一异步进程,API 只做 HTTP 与 SSE 订阅。Workers 一节补充 SSEHub 的位置与 Redis 一跳,并禁止再用固定 sleep 当退出屏障。

README 新增进程分工表。API 可多副本,Worker 暂为单副本。表后说明 Redis 是通知实时性的必要条件,START_WORKER=0 时通知与 timeline 不再被消费。

两份设计文档同步消费者归属与 mq_topology 期望值:API 3,Worker 7。
This commit is contained in:
2026-11-08 14:44:41 +08:00
parent ffd33f981c
commit 239a98e1fa
4 changed files with 29 additions and 9 deletions

View File

@@ -62,7 +62,7 @@ CONFIG_PATH=configs/config.compose-local.yaml go run ./cmd/worker # Worker
### Dual Binary Split
- `backend/cmd/main.go` — Gin HTTP API server (port 8080, pprof on :6060)
- `backend/cmd/worker/main.go` — RabbitMQ consumer process (pprof on :6061). Runs the Social, Like, and Comment workers in independent goroutines; each gets its own AMQP channel from the shared connection manager and reconnects automatically. Interaction counts are written by the business transaction (`ApplyLike`/`ApplyUnlike`/`CreateIdempotentWithPopularity`/`DeleteWithPopularity`); the hot ranking is a derived 60-minute sliding window (`video.ApplyHotDelta`, best-effort after commit, rebuildable with `cmd/reconcile -rebuild-hot`). (Notification workers, the Outbox poller, and the timeline consumer currently live in the API process — see `router.go`.)
- `backend/cmd/worker/main.go` — the **only** async process (pprof on :6061). Runs every RabbitMQ consumer (Social, Like, Comment, the three Notification consumers, the parked-event consumer) plus the Outbox poller and the timeline consumer, each in its own goroutine with its own AMQP channel from the shared connection manager. Interaction counts are written by the business transaction (`ApplyLike`/`ApplyUnlike`/`CreateIdempotentWithPopularity`/`DeleteWithPopularity`); the hot ranking is a derived 60-minute sliding window (`video.ApplyHotDelta`, best-effort after commit, rebuildable with `cmd/reconcile -rebuild-hot`). The API process (`backend/cmd/main.go`) only serves HTTP: it writes Outbox rows and consumes Redis push messages for SSE — it never starts a consumer or a poller.
### Domain Layer Pattern
@@ -102,7 +102,11 @@ Three-tier: L1 in-process `go-cache` (3s) → L2 Redis JSON (1h) → L3 MySQL wi
### Workers
Consumers never touch `*amqp.Connection`. Each one runs `rabbitmq.RunConsumer(ctx, mgr, name, prefetch, fn)` — the single consume loop in the project. It blocks (no polling) while the connection is down, and on recovery rebuilds the channel, re-applies per-channel QoS, and re-runs `Consume`. Channel-level exceptions (queue deleted, 406 conflicts) trigger a topology replay rather than a reconnect. Topology is registered once (`RegisterTopology`) and replayed automatically on every new connection. `SSEHub` is an in-process pub/sub for real-time notification push to connected clients. Notification workers consume from `notification.like`, `notification.comment`, `notification.social` queues. Note: `notification` domain is handler-only — routes in `router.go`, worker-side logic in `worker/notificationworker.go`.
Consumers never touch `*amqp.Connection`. Each one runs `rabbitmq.RunConsumer(ctx, mgr, name, prefetch, fn)` — the single consume loop in the project. It blocks (no polling) while the connection is down, and on recovery rebuilds the channel, re-applies per-channel QoS, and re-runs `Consume`. Channel-level exceptions (queue deleted, 406 conflicts) trigger a topology replay rather than a reconnect. Topology is registered once (`RegisterTopology`) and replayed automatically on every new connection. Notification workers consume from `notification.like`, `notification.comment`, `notification.social` queues. Note: `notification` domain is handler-only — routes in `router.go`, worker-side logic in `worker/notificationworker.go`.
`SSEHub` (`worker/ssehub.go`) is the **API-side** in-process pub/sub for connected clients; it is not the delivery path. Delivery is cross-process: the Worker's `RedisNotificationPublisher` (`worker/notificationbus.go`) publishes `{user_id, notification}` to `v1:notification:push`, and every API instance's `StartNotificationSubscriber` forwards what it receives to its own hub. Without that hop a user connected to instance A never sees a notification produced on instance B. Pub/Sub is at-most-once — the `notifications` table stays the authoritative copy, and the SSE push only makes it appear without a refresh.
Both binaries own their shutdown: `signal.NotifyContext` in `cmd/main.go` and `cmd/worker/main.go`, `http.Server.Shutdown` for the API (SSE handlers return when the process ctx is cancelled) and a `WaitGroup` for the Worker. Never reintroduce a fixed `time.Sleep` as a shutdown barrier.
Inside that callback every business worker calls `rabbitmq.ConsumeLoop(ctx, ch, parker, queue, rabbitmq.MaxAttempts, process)`. It is the only place that decides Ack / retry / park: a `nil` error acks, `rabbitmq.Permanent(err)` parks immediately, and any other error goes back through the queue's own `<queue>.retry` delay queue until `MaxAttempts` is spent. Parking publishes to `dlx.events` with routing key `parked.<source queue>`, and `FailedEventWorker` persists those messages into the `failed_events` table. Retry counts come from the broker's `x-death` header, never from process memory. A worker dispatches on the message body (`action`) rather than `d.RoutingKey`: the retry hop rewrites the routing key to the queue name.
@@ -189,7 +193,7 @@ Host prerequisites: Git ≥ 2.34.1, **Node.js 22** (JavaScript actions such as `
- `backend/internal/http/router.go` — all route definitions and dependency wiring
- `backend/internal/middleware/rabbitmq/` — connection manager (reconnect + topology replay + `RunConsumer`), exchange declarations, DLX, per-domain MQ publishers
- `backend/internal/feed/service.go` — three-tier caching, hot/cold feed split
- `backend/internal/worker/` — all async workers and SSE hub
- `backend/internal/worker/` — all async workers, the SSE hub and the Redis notification bridge (`notificationbus.go`)
- `backend/internal/video/chunk_handler.go` — chunked upload logic
## Test-Driven Development (TDD)

View File

@@ -31,6 +31,22 @@ docker compose up -d --build
> 本地开发可直接沿用 `.env.example` 中的公开默认值;生产环境必须自行生成:`openssl rand -hex 32`。
> 另外 `docker-compose.prod.yml` 把该变量声明为必填,未设置时 `docker compose up` 会在部署阶段直接报错。
## 进程分工与扩展约束
| 进程 | 职责 | 能否多副本 |
|------|------|-----------|
| API(`go run ./cmd`) | HTTP 接口、SSE 连接、事务内写 `outbox` 行、订阅 Redis 推送并转给本实例的 SSE | 可以。唯一残留的进程内状态是 feed 的 L1 缓存(5 秒 TTL),多实例下同一 key 短时间内可能各读到一份旧值 |
| Worker(`go run ./cmd/worker`) | 全部 MQ 消费者(social / like / comment / notification ×3 / parked)、Outbox poller、timeline consumer | **暂只支持单副本**:Outbox poller 多副本会重复投递(下游 `ZADD` 幂等,不会产生脏数据,只是浪费投递) |
API 进程不再启动任何消费者或轮询器。实时通知的链路是:
```
Worker 落库 notifications → Redis Pub/Sub(v1:notification:push)
→ 每个 API 实例的订阅器 → 该实例上的 SSE 连接
```
所以 **Redis 是通知实时性的必要条件**:Redis 不可用时通知仍会落库,只是不会即时出现在页面上,刷新后可见。SSE 的权威数据始终是 `notifications` 表,Pub/Sub 只是"在线时尽快看到"。
## 脚本启动
```bash
@@ -41,7 +57,7 @@ docker compose up -d --build
```bash
START_FRONTEND=0 ./start.sh # API + Worker
START_WORKER=0 ./start.sh # API + 前端
START_WORKER=0 ./start.sh # 只起 API + 前端(通知与 timeline 不再被消费,仅适合调 HTTP 接口)
STOP_DOCKER=1 ./start.sh # 退出时停止脚本拉起的 compose 服务
CONFIG_PATH=configs/config.yaml ./start.sh
```

View File

@@ -2,7 +2,7 @@
本文说明异步写路径(点赞、评论、关注、热度、通知)在消息**处理失败**时的完整实现:消息怎么被重投、重试次数记在哪里、什么时候停止重试、停泊到哪、谁把停泊消息落库、出问题时看什么。
读者只需要知道本项目的写路径结构:API 把事件发到 RabbitMQ,Worker 进程(以及 API 进程里的通知消费者)把事件写成数据库行与 Redis 计数。
读者只需要知道本项目的写路径结构:API 把事件发到 RabbitMQ,Worker 进程把事件写成数据库行与 Redis 计数。
---
@@ -562,7 +562,7 @@ go mqrabbit.RunConsumer(ctx, rmqMgr, "LikeWorker", 50, func(ch *amqp.Channel) er
`*RabbitMQ` 实现了 `Parker` 接口,测试里可以换成假实现验证"停泊失败必须 requeue"。
通知消费者跑在 API 进程(`router.go`),三个队列各一个 goroutine,prefetch = 10,同样传 `rmq` 作 parker。它们产生的停泊消息落到同一个 durable 队列,由 Worker 进程落库——API 进程不需要知道 `failed_events` 的存在。
通知消费者同样跑在 Worker 进程(`cmd/worker/main.go`),三个队列各一个 goroutine,prefetch = 10,同样传 `rmq` 作 parker。它们产生的停泊消息落到同一个 durable 队列,由 `FailedEventWorker` 落库(P1-1 之前这三个消费者在 API 进程,现已整体迁出)。
建表入口只有一个:API 进程启动时的 `db.AutoMigrate`(`db.go` 的 `AutoMigrate`)里包含 `&failedevent.FailedEvent{}`。Worker 侧刻意不 `AutoMigrate`,否则多个消费者并发 `CREATE INDEX` 会撞 1061。

View File

@@ -12,7 +12,7 @@
| 持久化 | MySQL | 存储 `Account / Video / Like / Comment / Social / Tag / VideoTag / Message / Notification / OutboxMsg` 等表及统计字段(如 likes_count、popularity)。 |
| 缓存/排行榜 | Redis(可选) | Token/Refresh Token 缓存、Feed 时间线、视频实体缓存、视频详情缓存、热榜 ZSET、分片上传会话、接口限流计数。 |
| 消息队列 | RabbitMQ(可选) | Topic 事件总线:`like.events`、`comment.events`、`social.events`、`video.popularity.events`、`video.timeline.events`;队列均声明 `x-dead-letter-exchange=dlx.events`(死信重试链路尚未接线,见 P0-3);发布失败异常降级直写。连接由 `middleware/rabbitmq` 的连接管理器持有:断连自动重连、每一代连接自动重放拓扑(见“RabbitMQ 优化部分”)。 |
| 异步执行 | Worker(Go) | `cmd/worker`:LikeWorker/CommentWorker/SocialWorker/PopularityWorker;API 进程内启动 OutboxPoller、TimelineConsumer 与 NotificationWorker。 |
| 异步执行 | Worker(Go) | `cmd/worker`:全部 MQ 消费者(Like/Comment/Social/Notification×3/Parked)以及 OutboxPoller、TimelineConsumer。API 进程只做 HTTP 与 SSE,不启动任何消费者(P1-1)。 |
| 文件存储 | Local Disk(可替换对象存储) | 视频与封面文件存放本地目录(生产可替换为 OSS/S3/MinIO)。 |
| 容器化/依赖编排 | Docker / Docker Compose | 一键拉起 RabbitMQ 等依赖(可配合 `./start.sh`),便于本地联调与部署环境一致性。 |
| 接口调试 | Postman Collection | `test/postman.json`:预置变量、批量跑接口与部分断言脚本。 |
@@ -151,7 +151,7 @@
| Handler | POST `/notification/markRead` | `{id?}` -> `{message}` | MySQL ✅ | 传 `id` 标记单条,省略 `id` 标记当前用户全部通知。 |
| Handler | POST `/notification/unreadCount` | `{}` -> `{count}` | MySQL ✅ | 当前用户未读通知计数。 |
| Worker | `NotificationWorker` | MQ 事件 -> `notifications` + SSE Push | MQ ✅ / MySQL ✅ / SSE ✅ | 消费点赞、评论、关注事件,生成通知并推送在线连接。 |
| Service(建议命名) | `SSEHub/List/MarkRead/UnreadCount/Push` | - | - | `SSEHub` 在 API 进程内维护每个用户的连接通道。 |
| Service(建议命名) | `SSEHub/List/MarkRead/UnreadCount/Push` | - | - | `SSEHub` 维护本进程内每个用户的连接通道;通知由 Worker 经 Redis Pub/Sub 送达各 API 实例,再推给本地连接(P1-1)。 |
### 各个模块的关系
@@ -344,7 +344,7 @@ sequenceDiagram
| `mq_connected` | `conn != nil && !conn.IsClosed()` | 核心状态;断开时 `/readyz` 返回 503 |
| `mq_generation` | 成功连接的序号(`install` 时 +1) | 单调递增,可确认"确实重连过" |
| `mq_reconnects` | 重连次数 | 频繁断连的量化指标 |
| `mq_topology` | 已登记拓扑条数 | API 进程应为 8、Worker 进程应为 4;变小说明有拓扑漏登记 |
| `mq_topology` | 已登记拓扑条数 | API 进程应为 3(like/comment/social 三个 publisher)、Worker 进程应为 7(三个消费队列 + 三个通知队列 + timeline);变小说明有拓扑漏登记 |
# 整体架构