feat(vloop): 页面里的图改为 mermaid 渲染

9 个章节的 20 张 ASCII 图改为 mermaid 图。站点自带 mermaid 11.15.0,由 assets/doc.js 按需加载并渲染。
05 章的 import 边是邻接清单。63 条边画成一张图不可读,因此保留原文。
验证:node tools/build-nav.js 与 node tools/check-pages.js 均退出 0。headless Chrome 逐页渲染,svg 数与图块数一致。
This commit is contained in:
2026-11-03 21:49:47 +08:00
parent 142f4f8559
commit f171808072
20 changed files with 4089 additions and 433 deletions

View File

@@ -68,37 +68,39 @@
<p>这条链路是全项目最长的一条,跨了<strong>5 个固定端点 + N 次分片上传、一次数据库事务、一个轮询器、一个 MQ 队列和一个消费者</strong>。关键认知是:<strong>发布接口返回成功时,视频还没进推荐流</strong>——进流是另一条异步路径的事。</p>
<pre data-lang="text" data-name="发布链路:从点击到进入推荐流">【浏览器】
① 选文件后本地算整文件 MD5(2MiB 步长,主线程)
② POST /video/chunk/init → 拿 upload_id 与已传分片列表
③ POST /video/chunk/upload ×N → 并发度 3,每片 5MiB,带单片 MD5
④ POST /video/chunk/complete → 服务端按序合并 → 返回 play_url
⑤ POST /video/uploadCover → 返回 cover_url
⑥ POST /video/publish → 写库
【服务端:⑥ 是一次真事务(backend/internal/video/video_service.go 的 Publish)】
BEGIN
INSERT videos → 拿到自增 ID
INSERT outbox_msgs(status=pending)→ 同一事务内,保证"有视频必有待发事件"
for tag in ExtractTags(title + " " + desc):
INSERT tags ... ON DUPLICATE → FirstOrCreate
INSERT video_tags
COMMIT
【异步:Outbox 轮询器(跑在 API 进程)】
每 1 秒扫描 status='pending' ORDER BY create_time ASC LIMIT 100
→ PublishVideo(videoID, createTime) 发到 video.timeline.events
→ 单条发布 5 秒超时;成功后 DELETE outbox_msgs 对应行
→ 失败只打日志,行留在 pending 等下一轮
【异步:时间线消费者(也在 API 进程,prefetch 10)】
video.timeline.update.queue → ZADD feed:global_timeline
score = create_time 的毫秒值,member = videoID(幂等)
→ ZREMRANGEBYRANK 裁剪到 1000 条
→ 单条 Redis 操作 500ms 超时;失败 Nack(requeue=true),解码失败 ACK
【读:/feed/listLatest】
ZSET 里已有这条 → 走热路径,直接按分数区间取 ID</pre>
<pre class="mermaid" data-lang="mermaid" data-name="发布链路:从点击到进入推荐流">sequenceDiagram
participant B as 浏览器
participant A as API
participant DB as MySQL
participant MQ as RabbitMQ
participant W as Worker
participant R as Redis
Note over B: ① 选文件后本地算整文件 MD5,2MiB 步长,主线程
B->>A: ② POST /video/chunk/init
A-->>B: 返回 upload_id 与已传分片列表
B->>A: ③ POST /video/chunk/upload ×N,并发度 3,每片 5MiB,带单片 MD5
B->>A: ④ POST /video/chunk/complete
A-->>B: 服务端按序合并后返回 play_url
B->>A: ⑤ POST /video/uploadCover
A-->>B: 返回 cover_url
B->>A: ⑥ POST /video/publish,写库
Note over A,DB: ⑥ 是一次真事务,即 video_service.go 的 Publish
A->>DB: BEGIN
A->>DB: INSERT videos,拿到自增 ID
A->>DB: INSERT outbox_msgs,status=pending,同一事务内保证有视频必有待发事件
A->>DB: 对 ExtractTags 抽出的每个 tag 先 FirstOrCreate tags 再 INSERT video_tags
A->>DB: COMMIT
Note over A,MQ: 异步 Outbox 轮询器跑在 API 进程,每 1 秒扫 status=pending 并按 create_time 升序取 100 条
A->>MQ: 逐条 PublishVideo videoID 与 createTime,发到 video.timeline.events,单条 5 秒超时
A->>DB: 成功后 DELETE outbox_msgs 对应行
Note over A,DB: 失败只打日志,行留在 pending 等下一轮
MQ->>W: 投递到 video.timeline.update.queue,prefetch 10
Note over W: 时间线消费者也在 API 进程
W->>R: ZADD feed:global_timeline,score 为 create_time 的毫秒值,member 为 videoID,天然幂等
W->>R: ZREMRANGEBYRANK 裁剪到 1000 条
Note over W,R: 单条 Redis 操作 500ms 超时,失败 Nack 并 requeue=true,解码失败直接 ACK
B->>A: 读 GET /feed/listLatest
A->>R: ZSET 里已有这条就走热路径,直接按分数区间取 ID</pre>
<div class="tablewrap">
<table>
@@ -154,41 +156,42 @@
<p>点赞的同步段很短,异步段却容易讲错。当前实现里<strong>没有独立的「热度服务」</strong>:一次点赞只发一条 <code>like.events</code> 消息,它被扇出到两个队列,落库与热度更新都由 <code>LikeWorker</code> 在同一进程、同一条消息里完成。所以「点赞后详情页计数是旧值」的窗口通常只有<strong>消费时延</strong>,而不是缓存 TTL。</p>
<pre data-lang="text" data-name="点赞链路:一条消息,两个队列">【同步:POST /like/like(限流 30 次/分钟/账号)】
LikeService.Like:
1. VideoRepo.IsExist(videoID) → 不存在返回 "video not found"
2. LikeRepo.IsLiked(videoID, uid) → 已赞返回 "user has liked this video"
3. likeMQ.Like(uid, videoID, occurred_at) → 成功即 return nil(HTTP 200)
4. 入队失败才降级直写:
repo.ApplyLike 事务
· INSERT likes ... ON DUPLICATE KEY UPDATE(唯一索引吸收重复)
· likes_count + 1、popularity + 1(GREATEST 防负)
ApplyHotDelta(+1, occurred_at)(失败只日志)
【异步:like.events 扇出两个队列】
┌→ queue like.events → LikeWorker
│ · 再查一次视频是否存在
│ · ApplyLike(重复投递 created=false 直接返回)
│ · 同一条消息里 ApplyHotDelta(+1, evt.occurred_at)
│
└→ queue notification.like → NotificationWorker
· 回查 videos.author_id,自己赞自己不通知
· INSERT notifications(type=like),去重键含收件人与 event_id
· hub.Push(authorID, notif) → SSE 推给在线的作者
【热度怎么写(backend/internal/video/hot_window.go 的 ApplyHotDelta)】
· 先 DEL video:detail:id=&lt;id&gt; 与 video:entity:&lt;id&gt;(best-effort)
· ZINCRBY hot:video:1m:&lt;occurred_at 的 UTC 分钟&gt; &lt;12 位补零的 videoID&gt; +1
· EXPIRE 该窗口键 2 小时
· 未来时间夹到 now;早于 2 小时的迟到增量直接丢弃
· 不写数据库:DB 计数才是事实,窗口可由 reconcile 重建
【取消点赞】
同上,但把 +1 换成 -1,桶取「点赞那一行」的 created_at,
不能按此刻的钟回退——窗口里可能已经没有那个桶了。
【读:热榜 /feed/listByPopularity】
ZUNIONSTORE 合并最近 60 个分钟窗口 → 快照 → ZREVRANGEBYSCORE 取前 N</pre>
<pre class="mermaid" data-lang="mermaid" data-name="点赞链路:一条消息,两个队列">sequenceDiagram
participant B as 浏览器
participant A as API
participant DB as MySQL
participant MQ as RabbitMQ
participant W as Worker
participant R as Redis
participant N as NotificationWorker
Note over B,MQ: 同步段 POST /like/like,限流 30 次/分钟/账号
B->>A: 发起点赞
A->>DB: 1 IsExist,videoID 不存在则返回 video not found
A->>DB: 2 IsLiked,已赞则返回 user has liked this video
A->>MQ: 3 likeMQ.Like uid 与 videoID 与 occurred_at
MQ-->>A: 入队成功即 return nil,响应 HTTP 200
Note over A,DB: 4 只有入队失败才降级直写
A->>DB: repo.ApplyLike 事务,INSERT likes 带 on duplicate key update,唯一索引吸收重复
A->>DB: likes_count 加 1 与 popularity 加 1,GREATEST 防负
A->>R: ApplyHotDelta 加 1 与 occurred_at,失败只打日志
Note over MQ,W: 异步 like.events 扇出两个队列
MQ->>W: 队列 like.events 交给 LikeWorker
W->>DB: 再查一次视频是否存在
W->>DB: ApplyLike,重复投递时 created=false 直接返回
W->>R: 同一条消息里 ApplyHotDelta 加 1 与 evt.occurred_at
MQ->>N: 队列 notification.like 交给 NotificationWorker
N->>DB: 回查 videos.author_id,自己赞自己不通知
N->>DB: INSERT notifications,type=like,去重键含收件人与 event_id
N-->>B: hub.Push authorID 与 notif,经 SSE 推给在线的作者
Note over R: 热度怎么写,见 hot_window.go 的 ApplyHotDelta,先 DEL video:detail:id=ID 与 video:entity:ID,best-effort
Note over R: ZINCRBY hot:video:1m:分钟桶,member 为 12 位补零的 videoID,分值加 1,分钟取 occurred_at 的 UTC 分钟
Note over R: EXPIRE 该窗口键 2 小时
Note over R: 未来时间夹到 now,早于 2 小时的迟到增量直接丢弃
Note over R: 不写数据库,DB 计数才是事实,窗口可由 reconcile 重建
Note over B,R: 取消点赞同构,把加 1 换成减 1,桶取点赞那一行的 created_at
Note over B,R: 不能按此刻的钟回退,窗口里可能已经没有那个桶
B->>A: 读热榜 GET /feed/listByPopularity
A->>R: ZUNIONSTORE 合并最近 60 个分钟窗口得到快照,再 ZREVRANGEBYSCORE 取前 N</pre>
<div class="box note">
<span class="bt">降级只有一个开关,因为只剩一个目标</span>
@@ -241,44 +244,67 @@ return nil</pre>
<p>这条链路是一次纯读,但要在一个请求里连续做<strong>四五次判断</strong>。把它讲清楚的关键是画出一棵决策树,而不是罗列代码。</p>
<pre data-lang="text" data-name="listLatest 的决策树">POST /feed/listLatest { limit, latest_time }
│
├─ handler:limit &lt;= 0 或 &gt; 50 → 归一为 10
│ latest_time 按「毫秒」解析(注意:listByFollowing 用的是秒)
│ 匿名访问也能用(软鉴权)
│
├─ service:读 ZSET feed:global_timeline
│ │
│ ├─ ZSET 为空?
│ │ → singleflight 全局去重,从 MySQL 取最新 1000 条重建
│ │ → 数据库也空则返回 "EMPTY_DB" 防无限递归
│ │ → 重建后递归调用自身
│ │
│ ├─ 请求时间 &lt;= ZSET 最老成员的分数(watermark)?
│ │ → 【冷路径】直接查库,BY create_time DESC
│ │ → 刻意不回写 ZSET(防止冷数据污染热区)
│ │
│ └─ 否则【热路径】
│ → ZREVRANGEBYSCORE 取 max=(reqTime-1) .. min=-inf 的 ID
│ → 取 limit 个
│
├─ GetVideoByIDs(ids):三级缓存
│ L1 进程内 go-cache(5 秒)
│ L2 Redis video:entity:&lt;id&gt;(1 小时)
│ L3 MySQL,每个 ID 一个 goroutine + singleflight
│ → 异步回写 L2、同步回写 L1
│ → buildOrderedResult 按请求顺序重排(乱序回填必须重排)
│
├─ 热路径取到的不足 limit 条?
│ → 用本页最后一条的 create_time 作游标再查库补齐
│ → singleflight key 与冷路径不同(避免互相等待)
│
├─ buildFeedVideos:批量查 likes 表填 is_liked
│ (匿名请求直接短路,不查 likes)
│
└─ 返回 { video_list, next_time, has_more }
next_time = 本页最后一条的毫秒时间戳
has_more = (len == limit)</pre>
<pre class="mermaid" data-lang="mermaid" data-name="listLatest 的决策树">flowchart TB
START["POST /feed/listLatest,请求体含 limit 与 latest_time"]
H1["handler 归一 limit 为 10,条件是 limit ≤ 0 或大于 50"]
H2["latest_time 按毫秒解析,注意 listByFollowing 用的是秒"]
H3["匿名访问也能用,软鉴权"]
S1["service 读 ZSET feed:global_timeline"]
Q1{"ZSET 为空"}
R1["singleflight 全局去重,从 MySQL 取最新 1000 条重建"]
Q2{"数据库也空"}
R2["返回 EMPTY_DB 防无限递归"]
R3["重建后递归调用自身"]
Q3{"请求时间 ≤ ZSET 最老成员的分数 watermark"}
C1["冷路径,直接查库,按 create_time 降序"]
C2["刻意不回写 ZSET,防止冷数据污染热区"]
P1["热路径 ZREVRANGEBYSCORE 取 max=(reqTime-1) 到 min=-inf 的 ID"]
P2["取 limit 个"]
G1["GetVideoByIDs 走三级缓存"]
L1["L1 进程内 go-cache,5 秒"]
L2["L2 Redis video:entity:ID,1 小时"]
L3["L3 MySQL,每个 ID 一个 goroutine 加 singleflight"]
G2["异步回写 L2,同步回写 L1"]
G3["buildOrderedResult 按请求顺序重排,乱序回填必须重排"]
Q4{"热路径取到的不足 limit 条"}
F1["用本页最后一条的 create_time 作游标再查库补齐"]
F2["singleflight key 与冷路径不同,避免互相等待"]
B1["buildFeedVideos 批量查 likes 表填 is_liked"]
B2["匿名请求直接短路,不查 likes"]
OUT["返回 video_list 与 next_time 与 has_more"]
O1["next_time 等于本页最后一条的毫秒时间戳"]
O2["has_more 由 len 是否等于 limit 推测"]
START --> H1
H1 --> H2
H2 --> H3
H3 --> S1
S1 --> Q1
Q1 -->|是| R1
R1 --> Q2
Q2 -->|是| R2
Q2 -->|否| R3
R3 -.->|递归| START
Q1 -->|否| Q3
Q3 -->|是| C1
C1 --> C2
C2 --> G1
Q3 -->|否| P1
P1 --> P2
P2 --> G1
G1 --> L1
L1 --> L2
L2 --> L3
L3 --> G2
G2 --> G3
G3 --> Q4
Q4 -->|是| F1
F1 --> F2
F2 --> B1
Q4 -->|否| B1
B1 --> B2
B2 --> OUT
OUT --> O1
O1 --> O2</pre>
<div class="tablewrap">
<table>
@@ -329,37 +355,42 @@ return nil</pre>
<p>评论与点赞同属「MQ-first」,但多了两个东西:<strong>幂等键</strong>(客户端可以带 <code>request_id</code> 重试)和<strong>@ 提及通知</strong>(它不走 MQ,直接在 API 进程写 <code>notifications</code>)。理解这两点,才能解释「评论成功但列表里还没有」和「@ 了对方,对方马上收到通知」为什么同时成立。</p>
<pre data-lang="text" data-name="评论发布链路:幂等键 + 两条通知支路">【同步:POST /comment/publish(限流 10 次/分钟/账号)】
handler:content 为空 / video_id &lt;= 0 → 400;其余按 apierror 分类
CommentService.Publish:
1. 再校验一次参数(ErrValidation → 400)
2. ResolveIntentKey(request_id):为空则服务端生成一个
3. VideoRepo.IsExist(videoID) → 不存在返回 400
4. commentMQ.Publish(CommentEvent{EventID: key, Action: "publish", ...})
成功 → 不直写 DB,直接返回 200 + request_id(不返回评论 ID)
失败 → CreateIdempotentWithPopularity(comment, +1)
(唯一索引 uk_comments_author_key(author_id, idempotency_key) 去重)
只有真的插入了才 ApplyHotDelta(+1)
5. notifyMentions:正则 @(\w+) → 查用户名 → 直接 INSERT notifications
【异步支路 A:comment.events → queue comment.events → CommentWorker】
· event_id 即意图键;解码失败 Permanent(停泊)
· 视频不存在:视为处理完成,ACK
· CreateIdempotentWithPopularity(comment, +1)
created=false → 说明 API 已直写过,直接返回,不重复加热度
· ApplyHotDelta(+1, evt.occurred_at)
【异步支路 B:comment.events → queue notification.comment → NotificationWorker】
· 回查 videos.author_id;作者 == 评论人则跳过
· INSERT notifications(type=comment, "评论了你的视频")
· 去重键 = NotificationDedupeKey(type, event_id, recipient_id)
· 插入成功才 hub.Push(SSE)
【删除:POST /comment/delete】
· GetByID → 不存在 500;作者不符 → 401(apierror.ErrUnauthorized)
· commentMQ.Delete(commentID, 新意图键) → 成功即 return
· 失败:DeleteWithPopularity 事务删行 + popularity - 1
· Worker 侧:行已不在(重复投递)→ 空操作,热度不能再减</pre>
<pre class="mermaid" data-lang="mermaid" data-name="评论发布链路:幂等键 + 两条通知支路">sequenceDiagram
participant B as 浏览器
participant A as API
participant DB as MySQL
participant MQ as RabbitMQ
participant W as Worker
participant N as NotificationWorker
Note over B,MQ: 同步段 POST /comment/publish,限流 10 次/分钟/账号
B->>A: 发布评论
Note over A: handler 判 content 为空或 video_id ≤ 0 则返回 400,其余按 apierror 分类
A->>A: 1 再校验一次参数,ErrValidation 映射 400
A->>A: 2 ResolveIntentKey request_id,为空则服务端生成一个
A->>DB: 3 VideoRepo.IsExist videoID,不存在返回 400
A->>MQ: 4 commentMQ.Publish CommentEvent,EventID 为 key,Action 为 publish
MQ-->>A: 成功则不直写 DB,直接返回 200 与 request_id,不返回评论 ID
Note over A,DB: 4 失败则降级直写
A->>DB: CreateIdempotentWithPopularity comment 与加 1,靠唯一索引 uk_comments_author_key 去重
A->>DB: 只有真的插入了才 ApplyHotDelta 加 1
A->>DB: 5 notifyMentions 用正则匹配 @ 提及,查用户名后直接 INSERT notifications
MQ->>W: 异步支路 A,走 queue comment.events 交给 CommentWorker
Note over W: event_id 即意图键,解码失败按 Permanent 直接停泊
W->>DB: 视频不存在视为处理完成,直接 ACK
W->>DB: CreateIdempotentWithPopularity comment 与加 1
Note over W: created=false 说明 API 已直写过,直接返回不重复加热度
W->>DB: ApplyHotDelta 加 1 与 evt.occurred_at
MQ->>N: 异步支路 B,走 queue notification.comment 交给 NotificationWorker
N->>DB: 回查 videos.author_id,作者等于评论人则跳过
N->>DB: INSERT notifications,type=comment,内容是评论了你的视频
Note over N: 去重键等于 NotificationDedupeKey type 与 event_id 与 recipient_id
N-->>B: 插入成功才 hub.Push,走 SSE
B->>A: 删除 POST /comment/delete
A->>DB: GetByID,不存在返回 500,作者不符返回 401 apierror.ErrUnauthorized
A->>MQ: commentMQ.Delete commentID 与新意图键
MQ-->>A: 成功即 return
Note over A,DB: 失败则 DeleteWithPopularity 事务删行并 popularity 减 1
Note over W,DB: Worker 侧行已不在即重复投递,空操作,热度不能再减</pre>
<div class="tablewrap">
<table>
@@ -389,28 +420,32 @@ return nil</pre>
<p>关注是六条链路里最典型的「DB-first」写路径:<strong>先落库、再失效缓存、最后才发事件</strong>。这个顺序是有意的——关注关系本身必须立刻一致(否则用户刷新关注列表会看不到自己刚关注的人),而通知可以丢。但它<strong>不是唯一的一条</strong>:发布同样先提交事务、事后再异步发事件——<code>backend/internal/video/video_service.go</code> 的 <code>Publish</code> 把 <code>videos</code> 与 <code>outbox_msgs</code> 写在同一个事务里,<code>backend/internal/worker/outboxworker.go</code> 的 <code>StartOutboxPoller</code> 才把事件投出去,两条链路的差别只是「事件驱动谁」:关注的 <code>social.events</code> 只驱动通知,发布的 <code>video.timeline.events</code> 驱动时间线。真正与点赞、评论相反的是<strong>一致性由谁承担</strong>:关注把关系的一致性放在请求内,点赞与评论把落库的一致性与削峰都交给队列。</p>
<pre data-lang="text" data-name="关注链路:DB-first,MQ 只负责通知">【同步:POST /social/follow(限流 20 次/分钟/账号)】
SocialService.Follow:
1. 两个账号都存在(FindByID × 2)
2. 禁止自关注 → "can not follow self"
3. IsFollowed → 已关注返回 "already followed"
4. repo.Follow → INSERT socials(唯一索引兜底)
5. 失效关注流整页缓存:
DEL BY PATTERN feed:listByFollowing:*:accountID=&lt;follower&gt;:*
6. socialMQ.Follow(...) → 失败只 log,不影响返回
→ HTTP 200 {"message":"followed"}
【异步:social.events → queue notification.social → NotificationWorker】
· INSERT notifications(type=follow, "关注了你")
· 去重键含收件人与 event_id
· hub.Push(vloggerID) → SSE
【取关】同构:IsFollowed → 必须已关注 → repo.Unfollow → 失效缓存 → 发事件
Worker 侧再执行一次 Follow/Unfollow;1062(唯一键冲突)当作成功。
【读:/feed/listByFollowing】
整页缓存 = feed:listByFollowing:limit=&lt;n&gt;:accountID=&lt;id&gt;:before=&lt;秒&gt;
TTL 24 小时;未命中时 Redis 锁 + 5×20ms 等锁 + 查库兜底</pre>
<pre class="mermaid" data-lang="mermaid" data-name="关注链路:DB-first,MQ 只负责通知">sequenceDiagram
participant B as 浏览器
participant A as API
participant DB as MySQL
participant R as Redis
participant MQ as RabbitMQ
participant N as NotificationWorker
Note over B,MQ: 同步段 POST /social/follow,限流 20 次/分钟/账号
B->>A: 关注请求
A->>DB: 1 FindByID 查两个账号,两个都必须存在
A->>A: 2 禁止自关注,否则返回 can not follow self
A->>DB: 3 IsFollowed,已关注返回 already followed
A->>DB: 4 repo.Follow,INSERT socials,唯一索引兜底
A->>R: 5 失效关注流整页缓存,按模式 DEL feed:listByFollowing:*:accountID=follower:*
A->>MQ: 6 socialMQ.Follow
Note over A,MQ: 第 6 步失败只 log,不影响返回
A-->>B: HTTP 200,message 为 followed
MQ->>N: 异步 social.events 走 queue notification.social
N->>DB: INSERT notifications,type=follow,内容是关注了你
Note over N: 去重键含收件人与 event_id
N-->>B: hub.Push vloggerID,走 SSE
Note over B,DB: 取关同构,IsFollowed 必须已关注,然后 repo.Unfollow,再失效缓存,最后发事件
Note over N,DB: Worker 侧再执行一次 Follow 或 Unfollow,1062 唯一键冲突当作成功
B->>A: 读关注流 /feed/listByFollowing
A->>R: 整页缓存键为 feed:listByFollowing:limit=n:accountID=id:before=秒,TTL 24 小时
Note over A,R: 未命中时 Redis 锁 加 5 次 20ms 等锁 加 查库兜底</pre>
<div class="tablewrap">
<table>
@@ -436,43 +471,80 @@ return nil</pre>
<p>热榜读是一条纯读链路,但它要在一次请求里同时解决三个问题:<strong>窗口怎么定</strong>(最近 60 分钟)、<strong>翻页怎么稳</strong>(同一份快照内 offset 才可信)、<strong>Redis 不可用怎么办</strong>(DB 重算同一窗口)。答案是把「合并 60 个分钟桶」的结果固化成一份快照,再按 <code>as_of + offset</code> 翻页。</p>
<pre data-lang="text" data-name="listByPopularity 的请求处理">POST /feed/listByPopularity { limit, as_of?, offset? }
│
├─ handler:limit 归一(1..50,否则 10);as_of 单位是「秒」
│
├─ service:offset &lt; 0 先夹到 0(否则 SQL 的 OFFSET 负数会报 1690 → 500)
│
├─ 定 as_of:
│ 默认 = 上一个已闭合分钟(UTC 整分 - 1 分钟)
│ 请求带了 as_of 时,只接受「更早」且「不超过 1 小时」的值
│ 其余一律替换成默认值(响应会把真正的 as_of 回给客户端)
│
├─ Redis 路径(总预算 120ms):
│ dest = hot:video:merge:1m:&lt;as_of 所在分钟&gt;
│ ├─ dest 不存在 → ZUNIONSTORE tmp 60 个 hot:video:1m:* SUM
│ │ · 并集为空:删 tmp,直接落 DB(空快照不许发布)
│ │ · tmp 先 EXPIRE 60s(防崩溃泄漏)
│ │ · RENAMENX tmp dest:抢到才发布,抢不到删 tmp 用别人的
│ │ · 发布成功再 EXPIRE dest 1h;改 TTL 失败就删 dest
│ ├─ ZREVRANGEBYSCORE dest "+inf" "(0" LIMIT offset limit
│ │ (只取分数 &gt; 0 的成员:加减相抵的视频不该留在榜上)
│ ├─ 空且 offset &gt; 0 → 空终结页(next_offset 保持原值、has_more=false、ranking_source 仍是 "hot")
│ └─ 空且 offset == 0 → 交 DB 判一次「是不是真的空」
│
├─ 拼装:repo.GetByIDs 直查库 → buildFeedVideos(填 is_liked)
│ next_offset = offset + len(members)
│ has_more = len(members) == limit
│ ranking_source = "hot"
│ snapshot_rebuilt = 本次是否刚建快照(且 offset &gt; 0)
│
└─ DB 回退 listByHotWindowDB:
同一窗口内 likes + comments 各 GROUP BY(UNION ALL)
ORDER BY score DESC, video_id DESC
最多扫 5 批(hotDBMaxSweep),过滤已删视频
next_offset = offset + 扫过的 SQL 行数(含被过滤掉的已删视频)
has_more = 最后一批是否满 limit
窗口内无互动且 offset == 0 → 返回 latest(终结页:next_offset=0、has_more=false)
ranking_source = "hot_db" / "latest";snapshot_rebuilt 恒为 false(这条路径不建快照)</pre>
<pre class="mermaid" data-lang="mermaid" data-name="listByPopularity 的请求处理">flowchart TB
START["POST /feed/listByPopularity,请求体含 limit 与 as_of 与 offset"]
H1["handler 归一 limit,区间 1 到 50,否则取 10"]
H2["as_of 单位是秒"]
S1["service 把 offset 先夹到 0,否则 SQL 的 OFFSET 负数会报 1690 并变成 500"]
A1["定 as_of,默认取上一个已闭合分钟,即 UTC 整分减 1 分钟"]
A2["请求带了 as_of 时只接受更早且不超过 1 小时的值"]
A3["其余一律替换成默认值,响应把真正的 as_of 回给客户端"]
REDIS["进入 Redis 路径,总预算 120ms"]
K1["dest 为 hot:video:merge:1m:as_of 所在分钟"]
Q0{"dest 不存在"}
U1["ZUNIONSTORE tmp 合并 60 个 hot:video:1m:*,SUM"]
Q1{"并集为空"}
U2["删 tmp,直接落 DB,空快照不许发布"]
U3["tmp 先 EXPIRE 60s,防崩溃泄漏"]
U4["RENAMENX tmp dest,抢到才发布,抢不到删 tmp 用别人的"]
U5["发布成功再 EXPIRE dest 1h,改 TTL 失败就删 dest"]
Q2{"dest 已存在"}
Z1["ZREVRANGEBYSCORE dest 从 +inf 到 0 开区间,再取 LIMIT offset limit"]
Z2["只取分数大于 0 的成员,加减相抵的视频不该留在榜上"]
Q3{"结果为空"}
Q4{"offset 大于 0"}
E1["空终结页,next_offset 保持原值,has_more 为 false,ranking_source 仍是 hot"]
E2["交 DB 判一次是不是真的空"]
ASM["拼装 repo.GetByIDs 直查库,再 buildFeedVideos 填 is_liked"]
AS1["next_offset 等于 offset 加 len members"]
AS2["has_more 等于 len members 是否等于 limit"]
AS3["ranking_source 为 hot"]
AS4["snapshot_rebuilt 表示本次是否刚建快照,且 offset 大于 0"]
DB1["DB 回退 listByHotWindowDB"]
DB2["同一窗口内 likes 与 comments 各 GROUP BY 后 UNION ALL"]
DB3["ORDER BY score DESC 与 video_id DESC"]
DB4["最多扫 5 批 hotDBMaxSweep,过滤已删视频"]
DB5["next_offset 等于 offset 加扫过的 SQL 行数,含被过滤掉的已删视频"]
DB6["has_more 等于最后一批是否满 limit"]
DB7["若窗口内无互动且 offset 等于 0 则返回 latest,next_offset 为 0 且 has_more 为 false"]
DB8["ranking_source 为 hot_db 或 latest,snapshot_rebuilt 恒为 false,这条路径不建快照"]
START --> H1
H1 --> H2
H2 --> S1
S1 --> A1
A1 --> A2
A2 --> A3
A3 --> REDIS
REDIS --> K1
K1 --> Q0
Q0 -->|是| U1
U1 --> Q1
Q1 -->|是| U2
U2 --> DB1
Q1 -->|否| U3
U3 --> U4
U4 --> U5
U5 --> Q2
Q0 -->|否| Q2
Q2 -->|是| Z1
Z1 --> Z2
Z2 --> Q3
Q3 -->|是| Q4
Q4 -->|是| E1
Q4 -->|否| E2
E2 --> DB1
Q3 -->|否| ASM
ASM --> AS1
AS1 --> AS2
AS2 --> AS3
AS3 --> AS4
DB1 --> DB2
DB2 --> DB3
DB3 --> DB4
DB4 --> DB5
DB5 --> DB6
DB6 --> DB7
DB7 --> DB8</pre>
<div class="box danger">
<span class="bt">客户端必须把这三个信号当成「榜已换,从 0 重来」</span>
@@ -493,48 +565,56 @@ return nil</pre>
<p>上面六条是主干动作;系统里还有四条支线链路和两类横向机制。它们不需要每一条都画完整时序,但必须知道<strong>入口、同步段、落点与失败语义</strong>——故障排查时,问题经常不在主干上,而在这些支线里。</p>
<pre data-lang="text" data-name="通知与 SSE:从事件到浏览器">【生产者】like.like / comment.publish / social.follow
→ 三个 topic 交换机,各自绑定一个通知队列
→ notification.like / notification.comment / notification.social
→ 都在 API 进程消费(prefetch 10),与 Worker 进程无关
<pre class="mermaid" data-lang="mermaid" data-name="通知与 SSE:从事件到浏览器">sequenceDiagram
participant P as 生产者
participant MQ as RabbitMQ
participant N as NotificationWorker
participant H as SSEHub
participant B as 浏览器
Note over P: 生产者是 like.like 与 comment.publish 与 social.follow
P->>MQ: 发到三个 topic 交换机,每个交换机各自绑定一个通知队列
Note over MQ: 三个队列分别是 notification.like 与 notification.comment 与 notification.social
MQ->>N: 投递通知消息
Note over N: 都在 API 进程消费,prefetch 10,与 Worker 进程无关
N->>N: 队列与 body.action 双校验,重试会把 routing key 改写成队列名
N->>N: like 与 comment 回查 videos.author_id,为 0 或是自己就不通知
N->>N: follow 的收件人就是 vlogger
N->>N: INSERT notifications,去重键等于 type 加 event_id 加 recipient_id
Note over N: ON DUPLICATE DO NOTHING,RowsAffected 为 0 就结束,不重复推送
N->>H: 插入成功才 hub.Push
Note over H: 进程内分发,结构是 map 加 channel 切片,每个连接一个缓冲 20 的通道
Note over H: Push 用 select 与 default,客户端慢就丢这条,绝不阻塞消费者
B->>H: GET /notification/stream,token 走 query 或 Bearer
H-->>B: 每 30 秒发一次 keepalive
B->>H: POST /notification/list 取最近 50 条,markRead 支持单条或全部,还有 unreadCount
Note over H,B: hub 在进程内,多实例部署时 SSE 只能推到连接所在的那个实例
Note over H,B: list 读 DB 不受影响,但实时推送需要额外的广播层</pre>
【消费者 NotificationWorker】
· 队列 + body.action 双校验(重试会把 routing key 改写成队列名)
· like / comment:回查 videos.author_id;0 或自己 → 不通知
· follow:收件人 = vlogger
· INSERT notifications,去重键 = type + event_id + recipient_id
· ON DUPLICATE DO NOTHING;RowsAffected == 0 就结束,不重复推送
· 插入成功才 hub.Push
【进程内分发 SSEHub】
· map[uint][]chan *Notification,每个连接一个缓冲 20 的通道
· Push 用 select/default:客户端慢就丢这条,绝不阻塞消费者
· GET /notification/stream:token 走 query 或 Bearer,30 秒发一次 keepalive
· POST /notification/list(最近 50 条)、markRead(单条或全部)、unreadCount
【边界】hub 在进程内:多实例部署时,SSE 只能推到「连接所在的那个实例」;
list 读 DB 不受影响,但实时推送需要额外的广播层。</pre>
<pre data-lang="text" data-name="失败消息的停泊与落库">【消费失败:rabbitmq.ConsumeLoop 统一决策】
process 返回 nil → Ack
process 返回 Permanent(err) → 立即停泊
其他 error → 看 4 次尝试预算(MaxAttempts=4,来自 x-death 头,不靠进程内存)
attempts &lt; 4 → 发布到 retry.events.&lt;Q&gt;,经 &lt;Q&gt;.retry(TTL 5s)回到原队列
attempts &gt;= 4 → Park:publish 到 dlx.events(mandatory=true)
【停泊之后】
dlx.events → parked.&lt;source queue&gt; → failed.events
→ FailedEventWorker(Worker 进程,刻意不走 ConsumeLoop,避免递归停泊)
→ INSERT failed_events(event_id 去重,status=pending)
→ 落库失败:Nack(requeue=true) + 2 秒退避
【注意】
· 没有重放接口:failed_events 只是"证据",修复后要人工重放
· 时间线消费者与停泊消费者都不走 ConsumeLoop,前者自己 Nack,
后者自己退避;只有业务 worker 才有 4 次预算
· 日志关键字:
consume: 处理失败将重试 queue=... attempts=1/4
consume: 已停泊 queue=... attempts=4 last_error=...</pre>
<pre class="mermaid" data-lang="mermaid" data-name="失败消息的停泊与落库">sequenceDiagram
participant MQ as RabbitMQ
participant CL as ConsumeLoop
participant BIZ as 业务 process
participant FEW as FailedEventWorker
participant DB as MySQL
Note over MQ,CL: 消费失败由 rabbitmq.ConsumeLoop 统一决策
MQ->>CL: 投递消息
CL->>BIZ: 执行 process
BIZ-->>CL: 返回 nil
CL->>MQ: Ack
BIZ-->>CL: 返回 Permanent err
CL->>MQ: 立即停泊,publish 到 dlx.events,mandatory=true
BIZ-->>CL: 返回其他 error
Note over CL: 看 4 次尝试预算,MaxAttempts 为 4,次数来自 x-death 头,不靠进程内存
CL->>MQ: attempts 小于 4 时发布到 retry.events.Q
MQ->>MQ: 经 Q.retry 延迟队列,TTL 5s,回到原队列
CL->>MQ: attempts 大于等于 4 时 Park,publish 到 dlx.events,mandatory=true
MQ->>FEW: dlx.events 经 parked.source queue 路由到 failed.events
Note over FEW: 在 Worker 进程,刻意不走 ConsumeLoop,避免递归停泊
FEW->>DB: INSERT failed_events,event_id 去重,status=pending
FEW->>MQ: 落库失败则 Nack 并 requeue=true,退避 2 秒
Note over MQ,DB: 没有重放接口,failed_events 只是证据,修复后要人工重放
Note over MQ,DB: 时间线消费者与停泊消费者都不走 ConsumeLoop,前者自己 Nack,后者自己退避,只有业务 worker 才有 4 次预算
Note over MQ,DB: 日志关键字是 consume 处理失败将重试 queue 与 attempts=1/4,以及 consume 已停泊 queue 与 attempts=4 last_error</pre>
<div class="tablewrap">
<table>