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:
@@ -263,25 +263,20 @@ $ find backend -name '*_test.go' | xargs wc -l | tail -1
|
||||
</div>
|
||||
<p>依赖拓扑可以画成一张图。注意最后一段:<strong>通知消费者、时间线消费者和 Outbox 轮询器都住在 API 进程里</strong>,
|
||||
不在 Worker 里——这是现状,不是笔误:</p>
|
||||
<pre data-lang="text" data-name="运行时依赖拓扑(实线=同步调用,虚线=异步消费)">前端 Vue (:5173) ──POST/GET──► API 进程 (:8080) ──────────► MySQL 8.0(11 张表)
|
||||
│ pprof :6060 ──────────► Redis 7(缓存 / 锁 / 分钟窗口 ZSET / 限流)
|
||||
│
|
||||
├─ 发布:INSERT outbox_msgs ──┐
|
||||
│ ▼
|
||||
│ Outbox 轮询器(API 进程内,1s 一轮)
|
||||
│ │ publish
|
||||
│ ▼
|
||||
└─ 写互动:publish ──► RabbitMQ ◄── 4 组业务交换机 + 每队列 retry.events.* 与 dlx.events
|
||||
│
|
||||
├──► Worker 进程(:6061),4 个消费者
|
||||
│ FailedEventWorker(prefetch 1)◄── failed.events
|
||||
│ Social / Like / Comment(各 prefetch 50)
|
||||
│ ├──► MySQL 写库(likes_count / popularity 同事务)
|
||||
│ └──► 热榜:video.ApplyHotDelta 写 Redis 分钟窗口
|
||||
│
|
||||
└──► API 进程内三个通知消费者 + Timeline 消费者
|
||||
└──► SSEHub ──SSE──► 浏览器
|
||||
(GET /notification/stream)</pre>
|
||||
<pre class="mermaid" data-lang="mermaid" data-name="运行时依赖拓扑:实线是同步调用,虚线是异步消费">
|
||||
flowchart LR
|
||||
FE["前端 Vue<br/>:5173"] -->|"POST / GET"| API["API 进程<br/>:8080 · pprof :6060"]
|
||||
API -->|"GORM"| DB[("MySQL 8.0<br/>11 张表")]
|
||||
API -->|"缓存 / 锁 / 分钟窗口 ZSET / 限流"| RD[("Redis 7")]
|
||||
API -->|"写互动:publish"| MQ{{"RabbitMQ<br/>4 组业务交换机<br/>每队列 retry.events.*"}}
|
||||
API -->|"发布:INSERT outbox_msgs"| OB["Outbox 轮询器<br/>1s 一轮,每轮 100 条"]
|
||||
OB -->|"publish"| MQ
|
||||
MQ --> W["Worker 进程 :6061<br/>FailedEvent / Social / Like / Comment"]
|
||||
W -->|"同事务写 likes_count、popularity"| DB
|
||||
W -->|"ApplyHotDelta"| RD
|
||||
MQ --> IN["API 进程内<br/>3 个通知消费者 + Timeline 消费者"]
|
||||
IN -->|"SSE /notification/stream"| FE
|
||||
W -.->|"第 4 次失败:Park"| DL[("dlx.events<br/>failed.events → failed_events")]</pre>
|
||||
<p>依赖为 nil 时各自降级到什么程度,是理解这个项目容错设计的关键。这张矩阵第 16 章会展开,
|
||||
这里先记住结论:<mark>只有 MySQL 和 JWT 密钥是硬依赖,其余全部可选</mark>:</p>
|
||||
<div class="tablewrap">
|
||||
@@ -316,17 +311,20 @@ $ find backend -name '*_test.go' | xargs wc -l | tail -1
|
||||
→ 投递到 <code>video.timeline.events</code> → Timeline 消费者执行
|
||||
<code>ZADD feed:global_timeline</code>,并把 ZSET 裁剪到 1000 条。
|
||||
这条链路的语义是<mark>最终一致</mark>:接口返回成功时,视频可能还没进时间线。</p>
|
||||
<pre data-lang="text" data-name="发布闭环:用 Outbox 把「写库」与「发消息」解耦">POST /video/publish
|
||||
└─ 事务开始
|
||||
├─ INSERT videos
|
||||
├─ INSERT outbox_msgs(status='pending')
|
||||
└─ INSERT video_tags(从标题与描述里抽 #话题)
|
||||
事务提交 ──► 接口立即返回
|
||||
└─ Outbox 轮询器(API 进程内,1s 一轮,每轮最多 100 条,单条 5s 超时)
|
||||
└─ publish → exchange video.timeline.events
|
||||
└─ Timeline 消费者
|
||||
├─ ZADD feed:global_timeline score=create_time member=video_id
|
||||
└─ ZREMRANGEBYRANK 保留最新 1000 条</pre>
|
||||
<pre class="mermaid" data-lang="mermaid" data-name="发布闭环:用 Outbox 把写库与发消息解耦">
|
||||
flowchart TB
|
||||
P["POST /video/publish"] --> TX["事务开始"]
|
||||
TX --> V["INSERT videos"]
|
||||
TX --> O["INSERT outbox_msgs<br/>status = pending"]
|
||||
TX --> T["INSERT video_tags<br/>从标题与描述抽 #话题"]
|
||||
V --> C["提交事务,接口立即返回"]
|
||||
O --> C
|
||||
T --> C
|
||||
C -.->|"1s 一轮 · 每轮 100 条 · 单条 5s 超时"| POLL["Outbox 轮询器(API 进程内)"]
|
||||
POLL -->|"publish"| EX["exchange video.timeline.events"]
|
||||
EX --> TC["Timeline 消费者"]
|
||||
TC --> Z["ZADD feed:global_timeline<br/>score = create_time · member = video_id"]
|
||||
Z --> TR["ZREMRANGEBYRANK 保留最新 1000 条"]</pre>
|
||||
<p><strong>闭环 B · 互动</strong>:点赞与评论是「MQ 优先」——先发事件,发失败才在本进程直写 DB;
|
||||
关注是「DB 优先」——先落库再发通知事件,MQ 失败只记日志。这两条路径的顺序是相反的,
|
||||
记混了就会答错「消息丢了怎么办」这类问题。</p>
|
||||
|
||||
@@ -267,19 +267,14 @@
|
||||
</div>
|
||||
<p>其中第 7 项「追问答案卡」值得单独说。这个项目的每处设计都能被追问三层,
|
||||
下面是三层追问的形状——本站的面试篇就是按这个模板组织的:</p>
|
||||
<pre data-lang="text" data-name="追问的三层形状(以点赞为例)">第 1 层:点赞的流程是什么?
|
||||
→ POST /like/like → LikeService.Like → 校验视频存在 → 查是否已赞
|
||||
→ 发一条 like.events(它同时驱动点赞行与热度窗口)→ 返回 200
|
||||
|
||||
第 2 层:如果 MQ 挂了会怎样?
|
||||
→ likeMQ 发布失败 → 降级为同步事务直写:likes 表 + likes_count+1 + popularity+1
|
||||
→ 没有第二条热度消息:正常路径与降级路径都调到同一处 ApplyHotDelta
|
||||
|
||||
第 3 层:那如果 MQ 没挂,但消息重复投递了两次呢?
|
||||
→ likes 表有唯一索引 idx_like_video_account,ApplyLike 用 ON CONFLICT DO NOTHING
|
||||
→ created=false 时 worker 直接跳过热度,计数不会翻倍
|
||||
→ 评论同样幂等:uk_comments_author_key(author_id, idempotency_key),request_id 相同只写一条
|
||||
(第 3 层的完整答案在第 11.2 节与第 19.2 节)</pre>
|
||||
<pre class="mermaid" data-lang="mermaid" data-name="追问的三层形状(以点赞为例)">
|
||||
flowchart TB
|
||||
L1["第 1 层:点赞的流程是什么?<br/>POST /like/like<br/>LikeService.Like<br/>校验视频存在<br/>查是否已赞<br/>发一条 like.events(它同时驱动点赞行与热度窗口)<br/>返回 200"]
|
||||
L2["第 2 层:如果 MQ 挂了会怎样?<br/>likeMQ 发布失败<br/>降级为同步事务直写:likes 表 + likes_count+1 + popularity+1<br/>没有第二条热度消息:正常路径与降级路径都调到同一处 ApplyHotDelta"]
|
||||
L3["第 3 层:那如果 MQ 没挂,但消息重复投递了两次呢?<br/>likes 表有唯一索引 idx_like_video_account,ApplyLike 用 ON CONFLICT DO NOTHING<br/>created=false 时 worker 直接跳过热度,计数不会翻倍<br/>评论同样幂等:uk_comments_author_key(author_id, idempotency_key),request_id 相同只写一条<br/>(第 3 层的完整答案在第 11.2 节与第 19.2 节)"]
|
||||
L1 -->|追问| L2
|
||||
L2 -->|追问| L3
|
||||
</pre>
|
||||
|
||||
<h3 id="sec-2-6">2.6 先把项目跑起来:最小启动路径</h3>
|
||||
<p>在读懂任何一行代码之前,先让它跑起来。原因很实际:这个项目的很多设计只有在
|
||||
|
||||
@@ -92,22 +92,26 @@ func AutoMigrate(db *gorm.DB) error {
|
||||
|
||||
<p>把这十一张表的逻辑指向关系画出来,结构其实很干净——三条「主表 + 关系表」的经典形状,加上三张消息表与一张停泊落库表:</p>
|
||||
|
||||
<pre data-lang="text" data-name="逻辑外键关系(应用层维护,数据库不强制)">accounts ──1:N──▶ videos (videos.author_id)
|
||||
│ │
|
||||
│ ├──1:N──▶ likes (likes.video_id)
|
||||
│ ├──1:N──▶ comments (comments.video_id)
|
||||
│ ├──1:N──▶ video_tags (video_tags.video_id)
|
||||
│ └──1:N──▶ outbox_msgs (outbox_msgs.video_id)
|
||||
│
|
||||
├──1:N──▶ likes (likes.account_id)
|
||||
├──1:N──▶ comments (comments.author_id)
|
||||
├──1:N──▶ socials (socials.follower_id 与 socials.vlogger_id 各一次)
|
||||
├──1:N──▶ messages (messages.from_id 与 messages.to_id 各一次)
|
||||
└──1:N──▶ notifications(notifications.recipient_id 与 sender_id)
|
||||
|
||||
tags ──1:N──▶ video_tags (video_tags.tag_id)
|
||||
|
||||
failed_events (无逻辑外键:source_queue + event_id 记停泊来源)</pre>
|
||||
<pre class="mermaid" data-lang="mermaid" data-name="逻辑外键关系(应用层维护,数据库不强制)">erDiagram
|
||||
accounts ||--o{ videos : "author_id"
|
||||
videos ||--o{ likes : "video_id"
|
||||
videos ||--o{ comments : "video_id"
|
||||
videos ||--o{ video_tags : "video_id"
|
||||
videos ||--o{ outbox_msgs : "video_id"
|
||||
accounts ||--o{ likes : "account_id"
|
||||
accounts ||--o{ comments : "author_id"
|
||||
accounts ||--o{ socials : "follower_id"
|
||||
accounts ||--o{ socials : "vlogger_id"
|
||||
accounts ||--o{ messages : "from_id"
|
||||
accounts ||--o{ messages : "to_id"
|
||||
accounts ||--o{ notifications : "recipient_id"
|
||||
accounts ||--o{ notifications : "sender_id"
|
||||
tags ||--o{ video_tags : "tag_id"
|
||||
%% failed_events 无逻辑外键,source_queue 与 event_id 记停泊来源
|
||||
failed_events {
|
||||
string source_queue
|
||||
string event_id
|
||||
}</pre>
|
||||
|
||||
<p>没有外键约束带来的直接后果有三个,读代码时要一直记着:<b>删除不级联</b>(删视频不会带走它的 likes/comments/video_tags,需要应用层自己清,而现状是<b>根本不清</b>,见 <code>docs/ISSUES-REPORT.md</code> 的 P1-7);<b>插入不校验</b>(往 <code>likes</code> 写一个不存在的 <code>video_id</code> 数据库不会拦,靠 service 层先 <code>IsExist</code>);<b>孤儿数据无人发现</b>(因为没有对账任务,见 A-3)。</p>
|
||||
|
||||
|
||||
@@ -188,21 +188,45 @@ func (h *ChunkUploadHandler) hashKey(accountID uint, fileHash string) string {
|
||||
|
||||
<p>四个接口构成一个明确的状态机:<code>init</code> 建会话 → <code>upload</code> 反复传片 → <code>complete</code> 合并。第四个 <code>status</code> 只读不写。</p>
|
||||
|
||||
<pre data-lang="text" data-name="分片上传状态机">POST /chunk/init 客户端:{filename, file_size, chunk_size, total_chunks, file_hash}
|
||||
→ 服务端:查 hash 索引 → 有则返回旧会话 / 无则建新会话
|
||||
← 200 {upload_id, uploaded_chunks: []}
|
||||
|
||||
POST /chunk/upload 客户端:multipart,{upload_id, chunk_index, chunk_hash, file: blob}
|
||||
→ 服务端:读会话 → 校验归属 → 校验下标 → 位图已置位则直接 200
|
||||
→ MD5(blob) 与 chunk_hash 比对 → 落盘 → 置位并写回会话
|
||||
← 200 {chunk_index}
|
||||
|
||||
POST /chunk/status 客户端:{upload_id}
|
||||
← 200 {upload_id, uploaded_chunks, total_chunks} (前端从不调用)
|
||||
|
||||
POST /chunk/complete 客户端:{upload_id}
|
||||
→ 服务端:IsComplete? → 按 index 顺序合并 → 删临时目录 → 删两个 Redis 键
|
||||
← 200 {url, play_url} 或 400 {error, missing, completed, total}</pre>
|
||||
<pre class="mermaid" data-lang="mermaid" data-name="分片上传状态机">
|
||||
stateDiagram-v2
|
||||
state "init 建会话" as Init
|
||||
state "upload 传分片" as Upload
|
||||
state "status 只读查询" as Status
|
||||
state "complete 合并落盘" as Complete
|
||||
[*] --> Init : POST /chunk/init
|
||||
Init --> Init : hash 命中 复用旧会话
|
||||
Init --> Upload : 200 upload_id 与空位图
|
||||
Upload --> Upload : 位图未满 继续传下一片
|
||||
Upload --> Complete : 位图全真 全部片段已上传
|
||||
Complete --> [*] : 200 url 与 play_url 或 400 缺片
|
||||
Init --> Status : 只读 前端从不调用
|
||||
Upload --> Status : 只读 前端从不调用
|
||||
Complete --> Status : 只读 前端从不调用
|
||||
note right of Init
|
||||
客户端 {filename, file_size, chunk_size, total_chunks, file_hash}
|
||||
服务端 查 hash 索引 有则返回旧会话 无则建新会话
|
||||
响应 200 {upload_id, uploaded_chunks 为空}
|
||||
end note
|
||||
note right of Upload
|
||||
客户端 multipart {upload_id, chunk_index, chunk_hash, file 为二进制}
|
||||
服务端 读会话 校验归属 校验下标
|
||||
位图已置位则直接返回 200 不再读表单
|
||||
MD5 比对 chunk_hash 落盘 置位并写回会话
|
||||
响应 200 {chunk_index}
|
||||
end note
|
||||
note right of Status
|
||||
客户端 {upload_id}
|
||||
响应 200 {upload_id, uploaded_chunks, total_chunks}
|
||||
前端从不调用
|
||||
end note
|
||||
note right of Complete
|
||||
客户端 {upload_id}
|
||||
服务端 IsComplete 判断 按 index 顺序合并
|
||||
删临时目录 删两个 Redis 键
|
||||
响应 200 {url, play_url} 或 400 {error, missing, completed, total}
|
||||
end note
|
||||
</pre>
|
||||
|
||||
<p>四个 handler 的错误响应用的是同一顺序:<b>先看 Redis 在不在(503),再绑参数(400),再取会话(404),再看鉴权(400),再查归属(403)</b>。把这条顺序记住,排障时看一眼状态码就知道走到哪一步了。</p>
|
||||
|
||||
@@ -383,11 +407,30 @@ const MAX_RETRIES = 3
|
||||
|
||||
<p>读(<code>:148</code>)和写(<code>:224</code>)之间隔着 MD5 计算与磁盘 IO,而 <code>saveSession</code> 是整值 <code>SET</code>——<b>没有 WATCH/MULTI,没有 Lua SETBIT,没有按分片的独立键,也没有锁</b>。两个并发请求会各自读到同一份「全是 false」的快照,然后各自把自己那一位改成 true 再整体覆盖:</p>
|
||||
|
||||
<pre data-lang="text" data-name="读-改-写覆盖的精确时序">请求 A:GET 会话 → {a:false, b:false}
|
||||
请求 B:GET 会话 → {a:false, b:false} ← 与 A 读到同一份
|
||||
请求 A:置 a → SET {a:true, b:false}
|
||||
请求 B:置 b → SET {a:false, b:true} ← 后写者胜,A 的置位被抹掉
|
||||
最终 Redis:bit a 丢失(虽然 A 的分片文件已经在磁盘上)</pre>
|
||||
<pre class="mermaid" data-lang="mermaid" data-name="读-改-写覆盖的精确时序">
|
||||
sequenceDiagram
|
||||
participant C as 客户端
|
||||
participant A as API
|
||||
participant R as Redis
|
||||
Note over C,R: 并发上传 请求 A 与请求 B 交错执行
|
||||
C->>A: 请求 A GET 会话
|
||||
A->>R: GET 会话
|
||||
R-->>A: 位图 a=false b=false
|
||||
A-->>C: 会话快照 a=false b=false
|
||||
Note over C,R: 请求 B 读到与 A 完全相同的快照
|
||||
C->>A: 请求 B GET 会话
|
||||
A->>R: GET 会话
|
||||
R-->>A: 位图 a=false b=false
|
||||
A-->>C: 会话快照 a=false b=false
|
||||
C->>A: 请求 A 置 a 为 true
|
||||
A->>R: SET 整体写回 a=true b=false
|
||||
R-->>A: OK
|
||||
C->>A: 请求 B 置 b 为 true
|
||||
A->>R: SET 整体写回 a=false b=true
|
||||
R-->>A: OK
|
||||
Note over C,R: 后写者胜 A 的置位被抹掉
|
||||
Note over C,R: 最终 Redis 中 bit a 丢失 虽然 A 的分片文件已在磁盘上
|
||||
</pre>
|
||||
|
||||
<p>把这个时序和前端对照:<b>并发度就是 3</b>(<code>VideoView.vue:123</code>),每片 5MB,三个在途 POST 几乎必然落在同一读写窗口里。所以对一份 200MB / 40 片的<b>全新上传</b>来说,「持久化位图里缺了几片」不是可能发生,而是<b>典型会发生</b>。</p>
|
||||
|
||||
|
||||
@@ -1343,19 +1343,35 @@ ORDER BY likes_count DESC, id DESC LIMIT 10;
|
||||
<summary>候选人回答 <span class="qa-hint">点此收起,自己先答一遍</span></summary>
|
||||
<div class="qa-body">
|
||||
<p><strong>会,而且是必然发生的。</strong>每个分片处理完都会把<strong>整份 session JSON</strong> 覆写回 Redis:先改内存位图,再整体 <code>SET</code>(<code>chunk_handler.go:223-224</code>)。前端并发池是 3(<code>VideoView.vue</code> 的 <code>MAX_CONCURRENT = 3</code>),后完成的请求会覆盖先完成的位图。</p>
|
||||
<pre data-lang="text" data-name="并发覆盖的精确时序(前端并发度 3)">T0 前端同时发起 chunk 0 / 1 / 2
|
||||
T1 chunk 0 处理完:读 session(位图 000…)→ 置位 [1,0,0,…] → 整份 JSON SET 回 Redis
|
||||
T2 chunk 1 处理完:若它的读发生在 T1 的 SET 之前,
|
||||
读到的是 000…,置位后写回 [0,1,0,…]
|
||||
T3 chunk 2 同理写回 [0,0,1,…]
|
||||
结果:Redis 里只剩最后一次写入,另外两个分片"看起来没上传"
|
||||
T4 complete:按位图发现缺失 → 400 not all chunks uploaded(missing: [...])
|
||||
|
||||
根因:读-改-写三步不是原子的,且存储单位是"整份会话"而不是"单个位"。
|
||||
两种修法:
|
||||
A) 位图改成 Redis Set / Bitmap,用 SADD / SETBIT 做单元素原子更新;
|
||||
B) 会话加版本号 + WATCH/MULTI 乐观锁,冲突则重读重试。
|
||||
A 更贴合现状:位图本来就只需要按 index 标记,不需要整份 JSON。</pre>
|
||||
<pre class="mermaid" data-lang="mermaid" data-name="并发覆盖的精确时序(前端并发度 3)">sequenceDiagram
|
||||
participant FE as 前端
|
||||
participant API as API
|
||||
participant R as Redis
|
||||
Note over FE,API: T0 前端同时发起 chunk 0 / 1 / 2
|
||||
FE->>API: chunk 0 请求
|
||||
FE->>API: chunk 1 请求
|
||||
FE->>API: chunk 2 请求
|
||||
Note over API: T1 chunk 0 处理完
|
||||
API->>R: 读 session,位图 000…
|
||||
API->>API: 置位 [1,0,0,…]
|
||||
API->>R: 整份 JSON SET 回 Redis
|
||||
Note over API: T2 chunk 1 处理完,若它的读发生在 T1 的 SET 之前
|
||||
API->>R: 读 session,仍是 000…
|
||||
API->>API: 置位 [0,1,0,…]
|
||||
API->>R: 整份 JSON SET 回 Redis
|
||||
Note over API: T3 chunk 2 同理写回 [0,0,1,…]
|
||||
API->>R: 读 session,仍是 000…
|
||||
API->>API: 置位 [0,0,1,…]
|
||||
API->>R: 整份 JSON SET 回 Redis
|
||||
Note over R: 结果 Redis 里只剩最后一次写入,另外两个分片「看起来没上传」
|
||||
Note over FE,API: T4 complete
|
||||
FE->>API: complete 请求
|
||||
API->>R: 读 session,按位图发现缺失
|
||||
API-->>FE: 400 not all chunks uploaded(missing […])
|
||||
Note over FE,DB: 根因 读-改-写三步不是原子的,且存储单位是整份会话而不是单个位
|
||||
Note over FE,DB: 修法 A 位图改成 Redis Set / Bitmap,用 SADD / SETBIT 做单元素原子更新
|
||||
Note over FE,DB: 修法 B 会话加版本号 + WATCH / MULTI 乐观锁,冲突则重读重试
|
||||
Note over FE,DB: A 更贴合现状,位图本来就只需要按 index 标记,不需要整份 JSON</pre>
|
||||
</div>
|
||||
</details>
|
||||
<div class="qa-follow">
|
||||
|
||||
@@ -268,30 +268,48 @@
|
||||
<summary>候选人回答 <span class="qa-hint">点此收起,自己先答一遍</span></summary>
|
||||
<div class="qa-body">
|
||||
<p>好,我按「入口 → 事务 → 投递 → 终态 → 读路径」画:</p>
|
||||
<pre data-lang="text" data-name="链路一:发布(写路径 + Outbox)">POST /video/publish
|
||||
│
|
||||
▼
|
||||
┌─────────────────────────────────────────────┐
|
||||
│ 一个数据库事务 │
|
||||
│ INSERT videos │
|
||||
│ INSERT outbox_msgs (status='pending') │
|
||||
│ INSERT tags / video_tags (FirstOrCreate) │
|
||||
└─────────────────────────────────────────────┘
|
||||
│ (事务提交后,事件才可能被投递)
|
||||
▼
|
||||
Outbox 轮询器(在 API 进程里,每轮 LIMIT 100,order create_time ASC)
|
||||
│ publish 成功 → DELETE 该行(物理删除)
|
||||
▼
|
||||
video.timeline.events ──► video.timeline.update.queue
|
||||
│
|
||||
▼
|
||||
时间线消费者:ZADD feed:global_timeline score=毫秒 member=videoID
|
||||
然后 ZREMRANGEBYRANK 0 -1001 → 只保留最近 1000 条
|
||||
│
|
||||
▼
|
||||
Feed 读取:ZSET 最老成员分数 = watermark
|
||||
├── 请求时间 <= watermark → 冷数据,直接查 MySQL(不回写 ZSET)
|
||||
└── 请求时间 > watermark → 热数据,按分数区间取 ID → 三级缓存组装</pre>
|
||||
<pre class="mermaid" data-lang="mermaid" data-name="链路一:发布(写路径 + Outbox)">
|
||||
sequenceDiagram
|
||||
participant C as 客户端
|
||||
participant A as API
|
||||
participant D as MySQL
|
||||
participant P as Outbox 轮询器
|
||||
participant X as 交换机 video.timeline.events
|
||||
participant Q as 队列 video.timeline.update.queue
|
||||
participant W as 时间线消费者
|
||||
participant R as Redis
|
||||
participant F as Feed 读取
|
||||
C->>A: POST /video/publish
|
||||
Note over A,D: 一个数据库事务
|
||||
A->>D: INSERT videos
|
||||
A->>D: INSERT outbox_msgs status='pending'
|
||||
A->>D: INSERT tags 与 video_tags FirstOrCreate
|
||||
D-->>A: 事务提交
|
||||
Note over A,P: 事务提交后 事件才可能被投递
|
||||
Note over P: 轮询器在 API 进程里 每轮 LIMIT 100 按 create_time ASC 取
|
||||
P->>D: 轮询 outbox_msgs 里待投递的行
|
||||
D-->>P: 待投递事件
|
||||
P->>X: publish 事件
|
||||
X-->>P: publish 成功
|
||||
P->>D: DELETE 该行 物理删除
|
||||
X->>Q: 路由到 video.timeline.update.queue
|
||||
Q->>W: 投递事件
|
||||
W->>R: ZADD feed/global_timeline score=毫秒 member=videoID
|
||||
W->>R: ZREMRANGEBYRANK 0 -1001 只保留最近 1000 条
|
||||
Note over F,R: Feed 读取 以 ZSET 最老成员分数作为 watermark
|
||||
F->>R: 取 ZSET 最老成员分数
|
||||
R-->>F: watermark
|
||||
alt 请求时间 小于等于 watermark
|
||||
Note over F,D: 冷数据 直接查 MySQL 不回写 ZSET
|
||||
F->>D: 直接查 MySQL
|
||||
D-->>F: 冷数据
|
||||
else 请求时间 大于 watermark
|
||||
Note over F,R: 热数据 按分数区间取 ID
|
||||
F->>R: 按分数区间取 videoID
|
||||
R-->>F: videoID 列表
|
||||
Note over F: 三级缓存组装
|
||||
end
|
||||
</pre>
|
||||
<p>画的时候有三处要停一下讲:第一,四张表——<code>videos</code>、<code>outbox_msgs</code>、<code>tags</code>、<code>video_tags</code>——在同一个事务里,事件和业务数据一起提交;第二,轮询器在 API 进程里,每轮 <code>LIMIT 100</code>、按 <code>create_time ASC</code> 取,发布成功就把那行物理删除;第三,终态是 ZSET,用视频 ID 当成员,裁剪到最近 1000 条。</p>
|
||||
</div>
|
||||
</details>
|
||||
@@ -321,21 +339,40 @@ Feed 读取:ZSET 最老成员分数 = watermark
|
||||
<summary>候选人回答 <span class="qa-hint">点此收起,自己先答一遍</span></summary>
|
||||
<div class="qa-body">
|
||||
<p>点赞这条线的关键是「一条消息、两处消费者、一个降级口」:</p>
|
||||
<pre data-lang="text" data-name="链路二:点赞(单发 + 降级直写)">POST /like/like
|
||||
│
|
||||
├─ 校验视频存在、未点过赞
|
||||
│
|
||||
├─► likeMQ.Like(...) → 成功:直接返回 200(落库在 Worker 侧)
|
||||
│
|
||||
└─► 失败 → 单个事务直写:INSERT likes + likes_count+1 + popularity+1
|
||||
└─ 再调 ApplyHotDelta(+1) 写分钟窗口
|
||||
|
||||
异步侧(两条队列靠交换机扇出,各消费各的):
|
||||
like.events ──┬─► like.events(业务队列)→ LikeWorker
|
||||
│ ├─ ApplyLike(ON CONFLICT DO NOTHING → created=false 即幂等)
|
||||
│ ├─ likes_count / popularity 在同一事务里 +1(GREATEST 防负)
|
||||
│ └─ ApplyHotDelta(+1):删详情/实体缓存 → ZINCRBY 分钟桶
|
||||
└─► notification.like → NotificationWorker → INSERT notifications → SSEHub</pre>
|
||||
<pre class="mermaid" data-lang="mermaid" data-name="链路二:点赞(单发 + 降级直写)">
|
||||
sequenceDiagram
|
||||
participant C as 客户端
|
||||
participant A as API
|
||||
participant X as 交换机 like.events
|
||||
participant LQ as 业务队列 like.events
|
||||
participant LW as LikeWorker
|
||||
participant NQ as 队列 notification.like
|
||||
participant NW as NotificationWorker
|
||||
participant D as MySQL
|
||||
participant R as Redis
|
||||
participant S as SSEHub
|
||||
C->>A: POST /like/like
|
||||
A->>A: 校验视频存在 且 未点过赞
|
||||
alt likeMQ.Like 发布成功
|
||||
A->>X: likeMQ.Like(...)
|
||||
X-->>A: 发布成功
|
||||
A-->>C: 直接返回 200 落库在 Worker 侧
|
||||
else likeMQ.Like 发布失败
|
||||
A->>D: 单个事务直写 INSERT likes 与 likes_count+1 与 popularity+1
|
||||
A->>R: 再调 ApplyHotDelta(+1) 写分钟窗口
|
||||
end
|
||||
Note over X,S: 异步侧 两条队列靠交换机扇出 各消费各的
|
||||
X->>LQ: 扇出到业务队列 like.events
|
||||
LQ->>LW: 投递点赞事件
|
||||
LW->>D: ApplyLike 用 ON CONFLICT DO NOTHING
|
||||
D-->>LW: created=false 即幂等 跳过热度
|
||||
LW->>D: likes_count 与 popularity 在同一事务里 +1 GREATEST 防负
|
||||
LW->>R: ApplyHotDelta(+1) 删详情与实体缓存 再 ZINCRBY 分钟桶
|
||||
X->>NQ: 扇出到 notification.like
|
||||
NQ->>NW: 投递通知事件
|
||||
NW->>D: INSERT notifications
|
||||
NW->>S: 推送通知
|
||||
</pre>
|
||||
<p>入口先做存在性校验:视频存在、没点过赞。然后只发一条 <code>like.events</code>——它既是落库消息,也是热度消息,不存在第二条热度 MQ。发布成功就直接返回 200,真正的落库在 Worker 侧;发布失败才走降级:一个事务里写 <code>likes</code> 行、<code>likes_count</code> 和 <code>popularity</code>,再调 <code>ApplyHotDelta</code> 写窗口。</p>
|
||||
<p>异步侧 <code>LikeWorker</code> 用 <code>ApplyLike</code> 的 <code>ON CONFLICT DO NOTHING</code> 挡重复(<code>created=false</code> 就跳过热度),两个计数列与点赞行在同一事务里更新;通知侧是 <code>notification.like</code> → <code>NotificationWorker</code> → 按 <code>dedupe_key</code> 去重插入 → <code>SSEHub</code>。</p>
|
||||
</div>
|
||||
@@ -366,27 +403,38 @@ like.events ──┬─► like.events(业务队列)→ LikeWorker
|
||||
<summary>候选人回答 <span class="qa-hint">点此收起,自己先答一遍</span></summary>
|
||||
<div class="qa-body">
|
||||
<p>登录时签两个 token,然后靠 Redis 里的「当前唯一有效 token」做校验和撤销:</p>
|
||||
<pre data-lang="text" data-name="链路三:鉴权与撤销">POST /account/login
|
||||
│
|
||||
├─ SELECT accounts WHERE username → bcrypt 比对
|
||||
├─ GenerateToken(HS256 JWT,默认 15m)
|
||||
├─ GenerateRefreshToken(32 字节 crypto/rand,不透明)
|
||||
│
|
||||
└─► Redis 三键:
|
||||
v1:account:<id> = 当前 access token (24h) ← 撤销的抓手
|
||||
v1:account:<id>:refresh = refresh token (7d)
|
||||
v1:refresh:<token> = accountID (7d) ← 反向索引
|
||||
|
||||
后续每个受保护请求:
|
||||
解析 JWT ──► 取 Redis v1:account:<id> ──► 与请求里的 token 比对
|
||||
│ │
|
||||
│ 未命中 / Redis 故障 │ 不相等
|
||||
▼ ▼
|
||||
退到 DB 比对 accounts.token 401 token has been revoked
|
||||
成功后回写 Redis 24h
|
||||
|
||||
撤销点:改名(换 token)、改密(清空)、登出(清空)
|
||||
缺口:/notification/* 走的是另一套只解析 JWT 的鉴权,不做上述比对</pre>
|
||||
<pre class="mermaid" data-lang="mermaid" data-name="链路三:鉴权与撤销">
|
||||
sequenceDiagram
|
||||
participant C as 客户端
|
||||
participant A as API
|
||||
participant D as MySQL
|
||||
participant R as Redis
|
||||
C->>A: POST /account/login
|
||||
A->>D: SELECT accounts WHERE username
|
||||
D-->>A: 账号记录
|
||||
A->>A: bcrypt 比对密码
|
||||
A->>A: GenerateToken 签发 HS256 JWT 默认 15m
|
||||
A->>A: GenerateRefreshToken 32 字节 crypto/rand 不透明
|
||||
A->>R: 写入 v1/account/{id} 等于当前 access token 24h 撤销的抓手
|
||||
A->>R: 写入 v1/account/{id}/refresh 等于 refresh token 7d
|
||||
A->>R: 写入 v1/refresh/{token} 等于 accountID 7d 作为反向索引
|
||||
Note over C,R: 后续每个受保护请求
|
||||
C->>A: 携带 token 的受保护请求
|
||||
A->>A: 解析 JWT
|
||||
A->>R: 取 v1/account/{id}
|
||||
R-->>A: 当前唯一有效 token
|
||||
alt 命中 且 与请求里的 token 相等
|
||||
A->>A: 比对通过 放行
|
||||
else 未命中 或 Redis 故障
|
||||
A->>D: 退到 DB 比对 accounts.token
|
||||
D-->>A: 命中
|
||||
A->>R: 成功后回写 24h
|
||||
else 不相等
|
||||
A-->>C: 401 token has been revoked
|
||||
end
|
||||
Note over A,D: 撤销点 改名换 token 改密清空 登出清空
|
||||
Note over A,D: 缺口 /notification/* 走的是另一套只解析 JWT 的鉴权 不做上述比对
|
||||
</pre>
|
||||
<p>登录先按用户名查 <code>accounts</code>、bcrypt 比对,然后签发 HS256 JWT(默认 15m)和 32 字节 <code>crypto/rand</code> 的不透明 refresh,再写三处 Redis 键:<code>v1:account:<id></code> 存当前 access token(24h,撤销的抓手)、<code>v1:account:<id>:refresh</code> 存 refresh(7d)、<code>v1:refresh:<token></code> 做反向索引到 accountID(7d)。</p>
|
||||
<p>后续每个受保护请求:解析 JWT → 取 Redis <code>v1:account:<id></code> → 与请求里的 token 比对。未命中或 Redis 故障就退到 DB 比对 <code>accounts.token</code>,成功后回写 Redis 24h;不相等直接 401 <code>token has been revoked</code>。撤销点三个:改名换 token、改密清空、登出清空。</p>
|
||||
</div>
|
||||
|
||||
@@ -448,25 +448,40 @@
|
||||
<summary>候选人回答 <span class="qa-hint">点此收起,自己先答一遍</span></summary>
|
||||
<div class="qa-body">
|
||||
<p>热度只有<strong>一个事件源、两种存储</strong>,不是两条互不相干的轨:</p>
|
||||
<pre data-lang="text" data-name="热度的两种存储">轨 A(Redis,窗口热度)
|
||||
事件:like.events / comment.events(同一条业务消息)
|
||||
消费:LikeWorker / CommentWorker 落库后调 ApplyHotDelta
|
||||
口径:最近 60 个分钟桶的增量之和 ← "一小时窗口"
|
||||
存储:hot:video:1m:<yyyyMMddHHmm>,桶 TTL 2 小时,快照 TTL 1 小时
|
||||
|
||||
轨 B(MySQL,生命周期计数)
|
||||
事件:同一条业务消息,同一个事务
|
||||
消费:ApplyLike / CreateIdempotentWithPopularity 里 popularity ± 1
|
||||
口径:GREATEST(popularity + ?, 0) ← 生命周期累计
|
||||
存储:videos.popularity 列
|
||||
|
||||
两者:
|
||||
· 同一个入口,不是两条独立的消息流,所以不会出现"一边收到一边没收到"
|
||||
· 差异只在量纲(窗口 vs 生命周期)与失败模式
|
||||
· 没有定时对账:reconcile -counters / -verify 是手工命令
|
||||
· 缓存不可用时轨 B 正常,轨 A 的 ZINCRBY 静默失败 → 窗口低估;
|
||||
读路径落 listByHotWindowDB 按窗口重算,仍是对的口径
|
||||
· 评论删除会 -1,且 ApplyHotDelta 用被删评论的 created_at 落回原分钟</pre>
|
||||
<pre class="mermaid" data-lang="mermaid" data-name="热度的两种存储">
|
||||
flowchart LR
|
||||
SRC["同一个入口 不是两条独立的消息流 · like.events / comment.events · 不会出现一边收到一边没收到"]
|
||||
subgraph TA["轨 A Redis 窗口热度"]
|
||||
direction TB
|
||||
A1["事件 · like.events / comment.events · 同一条业务消息"]
|
||||
A2["消费 · LikeWorker / CommentWorker 落库后调 ApplyHotDelta"]
|
||||
A3["口径 · 最近 60 个分钟桶的增量之和 · 一小时窗口"]
|
||||
A4["存储 · hot:video:1m:yyyyMMddHHmm · 桶 TTL 2 小时 · 快照 TTL 1 小时"]
|
||||
A1 --> A2
|
||||
A2 --> A3
|
||||
A3 --> A4
|
||||
end
|
||||
subgraph TB2["轨 B MySQL 生命周期计数"]
|
||||
direction TB
|
||||
B1["事件 · 同一条业务消息 同一个事务"]
|
||||
B2["消费 · ApplyLike / CreateIdempotentWithPopularity 里 popularity ± 1"]
|
||||
B3["口径 · GREATEST(popularity + ?, 0) · 生命周期累计"]
|
||||
B4["存储 · videos.popularity 列"]
|
||||
B1 --> B2
|
||||
B2 --> B3
|
||||
B3 --> B4
|
||||
end
|
||||
C1["两者 · 差异只在量纲(窗口 vs 生命周期)与失败模式"]
|
||||
C2["没有定时对账 · reconcile -counters / -verify 是手工命令"]
|
||||
C3["缓存不可用时轨 B 正常 · 轨 A 的 ZINCRBY 静默失败 导致窗口低估 · 读路径落 listByHotWindowDB 按窗口重算 仍是对的口径"]
|
||||
C4["评论删除会减 1 · 且 ApplyHotDelta 用被删评论的 created_at 落回原分钟"]
|
||||
SRC --> A1
|
||||
SRC --> B1
|
||||
A4 --> C1
|
||||
B4 --> C1
|
||||
C1 --> C2
|
||||
C2 --> C3
|
||||
C3 --> C4</pre>
|
||||
</div>
|
||||
</details>
|
||||
<div class="qa-follow">
|
||||
|
||||
@@ -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=<id> 与 video:entity:<id>(best-effort)
|
||||
· ZINCRBY hot:video:1m:<occurred_at 的 UTC 分钟> <12 位补零的 videoID> +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 <= 0 或 > 50 → 归一为 10
|
||||
│ latest_time 按「毫秒」解析(注意:listByFollowing 用的是秒)
|
||||
│ 匿名访问也能用(软鉴权)
|
||||
│
|
||||
├─ service:读 ZSET feed:global_timeline
|
||||
│ │
|
||||
│ ├─ ZSET 为空?
|
||||
│ │ → singleflight 全局去重,从 MySQL 取最新 1000 条重建
|
||||
│ │ → 数据库也空则返回 "EMPTY_DB" 防无限递归
|
||||
│ │ → 重建后递归调用自身
|
||||
│ │
|
||||
│ ├─ 请求时间 <= 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:<id>(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 <= 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=<follower>:*
|
||||
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=<n>:accountID=<id>:before=<秒>
|
||||
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 < 0 先夹到 0(否则 SQL 的 OFFSET 负数会报 1690 → 500)
|
||||
│
|
||||
├─ 定 as_of:
|
||||
│ 默认 = 上一个已闭合分钟(UTC 整分 - 1 分钟)
|
||||
│ 请求带了 as_of 时,只接受「更早」且「不超过 1 小时」的值
|
||||
│ 其余一律替换成默认值(响应会把真正的 as_of 回给客户端)
|
||||
│
|
||||
├─ Redis 路径(总预算 120ms):
|
||||
│ dest = hot:video:merge:1m:<as_of 所在分钟>
|
||||
│ ├─ 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
|
||||
│ │ (只取分数 > 0 的成员:加减相抵的视频不该留在榜上)
|
||||
│ ├─ 空且 offset > 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 > 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 < 4 → 发布到 retry.events.<Q>,经 <Q>.retry(TTL 5s)回到原队列
|
||||
attempts >= 4 → Park:publish 到 dlx.events(mandatory=true)
|
||||
|
||||
【停泊之后】
|
||||
dlx.events → parked.<source queue> → 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>
|
||||
|
||||
@@ -272,18 +272,23 @@ case DispositionPark:
|
||||
|
||||
<p>「假失败」仍然真实存在:<code>PublishJSON</code> 用 <code>mandatory=false</code> 且没有发布确认,broker 已经收下消息、API 却因为连接在确认前断开而返回错误。区别在于——<b>现在两条路都带着同一个幂等键</b>,重复写入会被数据库挡掉。</p>
|
||||
|
||||
<pre data-lang="text" data-name="假失败的时间线(评论)">t0 用户发评论,request_id = R
|
||||
t1 API 调 commentMQ.Publish(EventID = R) → 消息已进 broker
|
||||
t2 连接在确认前断开,API 认为发布失败(err != nil)
|
||||
t3 API 走降级:CreateIdempotentWithPopularity(comment{R}, +1)
|
||||
t4 API 返回 200,用户看到评论成功
|
||||
t5 CommentWorker 收到那条"以为失败"的消息
|
||||
t6 再调 CreateIdempotentWithPopularity(comment{R}, +1)
|
||||
→ uk_comments_author_key(author_id, idempotency_key) 命中
|
||||
→ RowsAffected = 0
|
||||
t7 created = false → 不加热度,Ack
|
||||
|
||||
结果:一条评论、一次热度。重复被唯一索引吸收。</pre>
|
||||
<pre class="mermaid" data-lang="mermaid" data-name="假失败的时间线(评论)">sequenceDiagram
|
||||
participant U as 用户
|
||||
participant API as API
|
||||
participant MQ as RabbitMQ
|
||||
participant CW as CommentWorker
|
||||
participant DB as MySQL
|
||||
U->>API: t0 用户发评论 request_id = R
|
||||
API->>MQ: t1 commentMQ.Publish(EventID = R) 消息已进 broker
|
||||
MQ-->>API: t2 连接在确认前断开 API 认为发布失败 err != nil
|
||||
API->>DB: t3 走降级 CreateIdempotentWithPopularity(comment{R} +1)
|
||||
API-->>U: t4 返回 200 用户看到评论成功
|
||||
MQ->>CW: t5 CommentWorker 收到那条「以为失败」的消息
|
||||
CW->>DB: t6 再调 CreateIdempotentWithPopularity(comment{R} +1)
|
||||
DB-->>CW: uk_comments_author_key(author_id, idempotency_key) 命中
|
||||
DB-->>CW: RowsAffected = 0
|
||||
CW->>CW: t7 created = false 不加热度 Ack
|
||||
Note over U,DB: 结果 一条评论、一次热度。重复被唯一索引吸收</pre>
|
||||
|
||||
<div class="tablewrap">
|
||||
<table>
|
||||
|
||||
@@ -419,3 +419,11 @@ details.qa-a[open]>summary::before{transform:rotate(90deg)}
|
||||
details.qa-a>summary{background:transparent}
|
||||
.qa,.qa-follow{break-inside:avoid}
|
||||
}
|
||||
|
||||
/* 图(mermaid):<pre class="mermaid"> 渲染后原地替换为 SVG,图题用 .figcap */
|
||||
.figcap{font-size:13px;color:var(--muted);margin:18px 0 6px;line-height:1.5}
|
||||
pre.mermaid{background:#fff;border:1px solid var(--line);border-radius:12px;padding:16px 12px;
|
||||
margin:0 0 18px;overflow:auto;text-align:center;color:#17212e;font-size:0}
|
||||
pre.mermaid svg{max-width:100%;height:auto}
|
||||
pre.mermaid[data-processed]{font-size:0}
|
||||
@media print{ pre.mermaid{break-inside:avoid} }
|
||||
|
||||
@@ -82,6 +82,7 @@
|
||||
|
||||
function enhanceCode() {
|
||||
$$("pre").forEach(function (pre) {
|
||||
if (pre.classList.contains("mermaid")) return; // 图交给 mermaid 渲染,不做代码块包装
|
||||
if (pre.parentNode && pre.parentNode.classList.contains("codewrap")) return;
|
||||
var lang = pre.dataset.lang || "text";
|
||||
var name = pre.dataset.name || "";
|
||||
@@ -126,6 +127,40 @@
|
||||
});
|
||||
}
|
||||
|
||||
/* ------------------------------ 图:mermaid ------------------------------
|
||||
页面里的图写成 <pre class="mermaid" data-lang="mermaid">,正文即 mermaid 源码。
|
||||
data-name 用作图题;渲染失败时 mermaid 会把错误画进容器,源码仍可读。 */
|
||||
function enhanceDiagram() {
|
||||
var nodes = $$("pre.mermaid");
|
||||
if (!nodes.length) return;
|
||||
nodes.forEach(function (n) {
|
||||
var name = n.dataset.name || "";
|
||||
if (name) {
|
||||
var cap = document.createElement("div");
|
||||
cap.className = "figcap";
|
||||
cap.textContent = name;
|
||||
n.parentNode.insertBefore(cap, n);
|
||||
}
|
||||
});
|
||||
var s = document.createElement("script");
|
||||
s.src = "assets/mermaid.min.js";
|
||||
s.onload = function () {
|
||||
if (!window.mermaid) return;
|
||||
mermaid.initialize({
|
||||
startOnLoad: false,
|
||||
securityLevel: "loose",
|
||||
theme: "neutral",
|
||||
fontFamily: '-apple-system, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif',
|
||||
flowchart: { useMaxWidth: true, htmlLabels: true, curve: "basis" },
|
||||
sequence: { useMaxWidth: true, wrap: true, mirrorActors: false },
|
||||
state: { useMaxWidth: true }
|
||||
});
|
||||
try { mermaid.run({ nodes: nodes }); } catch (e) { console.error("mermaid:", e); }
|
||||
};
|
||||
document.head.appendChild(s);
|
||||
}
|
||||
|
||||
|
||||
/* ------------------------- 卡片交互(目录页 / 篇章页) -------------------------
|
||||
页面上存在 .chapcard 时才启用:已读勾选(localStorage)、进度条、
|
||||
搜索过滤、展开/收起全部小节。章节页没有这些元素,整段逻辑自动空转。
|
||||
@@ -239,6 +274,7 @@
|
||||
function init() {
|
||||
initTheme();
|
||||
enhanceCode();
|
||||
enhanceDiagram();
|
||||
centerActive();
|
||||
initCards();
|
||||
initCardTools();
|
||||
|
||||
3405
project/VLoop/assets/mermaid.min.js
vendored
Normal file
3405
project/VLoop/assets/mermaid.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
@@ -51,7 +51,7 @@
|
||||
<button class="btn" id="expandAll">展开全部小节</button>
|
||||
<button class="btn" id="resetBtn">清空进度</button>
|
||||
<button class="btn" id="printBtn">打印</button>
|
||||
<!-- AUTO:prog -->
|
||||
<!-- AUTO:prog -->
|
||||
<div class="progwrap" data-chapters="1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22">
|
||||
<span>已读</span><div class="bar"><i></i></div><b>0%</b>
|
||||
</div>
|
||||
|
||||
@@ -39,7 +39,7 @@
|
||||
<span>篇 <b class="pos">0</b> / 6</span>
|
||||
</p>
|
||||
|
||||
<!-- AUTO:hero -->
|
||||
<!-- AUTO:hero -->
|
||||
<div class="modhero">
|
||||
<span class="mh-no">篇 0 / 6</span>
|
||||
<h1>前言 · 先建立地图</h1>
|
||||
@@ -57,7 +57,7 @@
|
||||
<button class="btn" id="expandAll">展开全部小节</button>
|
||||
<button class="btn" id="resetBtn">清空进度</button>
|
||||
<button class="btn" id="printBtn">打印</button>
|
||||
<!-- AUTO:prog -->
|
||||
<!-- AUTO:prog -->
|
||||
<div class="progwrap" data-chapters="1,2">
|
||||
<span>已读</span><div class="bar"><i></i></div><b>0%</b>
|
||||
</div>
|
||||
|
||||
@@ -39,7 +39,7 @@
|
||||
<span>篇 <b class="pos">1</b> / 6</span>
|
||||
</p>
|
||||
|
||||
<!-- AUTO:hero -->
|
||||
<!-- AUTO:hero -->
|
||||
<div class="modhero">
|
||||
<span class="mh-no">篇 1 / 6</span>
|
||||
<h1>知识学习 · 补齐前置</h1>
|
||||
@@ -57,7 +57,7 @@
|
||||
<button class="btn" id="expandAll">展开全部小节</button>
|
||||
<button class="btn" id="resetBtn">清空进度</button>
|
||||
<button class="btn" id="printBtn">打印</button>
|
||||
<!-- AUTO:prog -->
|
||||
<!-- AUTO:prog -->
|
||||
<div class="progwrap" data-chapters="3,4">
|
||||
<span>已读</span><div class="bar"><i></i></div><b>0%</b>
|
||||
</div>
|
||||
|
||||
@@ -39,7 +39,7 @@
|
||||
<span>篇 <b class="pos">2</b> / 6</span>
|
||||
</p>
|
||||
|
||||
<!-- AUTO:hero -->
|
||||
<!-- AUTO:hero -->
|
||||
<div class="modhero">
|
||||
<span class="mh-no">篇 2 / 6</span>
|
||||
<h1>项目拆解 · 追源码</h1>
|
||||
@@ -57,7 +57,7 @@
|
||||
<button class="btn" id="expandAll">展开全部小节</button>
|
||||
<button class="btn" id="resetBtn">清空进度</button>
|
||||
<button class="btn" id="printBtn">打印</button>
|
||||
<!-- AUTO:prog -->
|
||||
<!-- AUTO:prog -->
|
||||
<div class="progwrap" data-chapters="5,6,7,8,9,10,11,12,13,14,15,16">
|
||||
<span>已读</span><div class="bar"><i></i></div><b>0%</b>
|
||||
</div>
|
||||
|
||||
@@ -39,7 +39,7 @@
|
||||
<span>篇 <b class="pos">3</b> / 6</span>
|
||||
</p>
|
||||
|
||||
<!-- AUTO:hero -->
|
||||
<!-- AUTO:hero -->
|
||||
<div class="modhero">
|
||||
<span class="mh-no">篇 3 / 6</span>
|
||||
<h1>面试模拟 · 把项目讲出来</h1>
|
||||
@@ -57,7 +57,7 @@
|
||||
<button class="btn" id="expandAll">展开全部小节</button>
|
||||
<button class="btn" id="resetBtn">清空进度</button>
|
||||
<button class="btn" id="printBtn">打印</button>
|
||||
<!-- AUTO:prog -->
|
||||
<!-- AUTO:prog -->
|
||||
<div class="progwrap" data-chapters="17,18,19">
|
||||
<span>已读</span><div class="bar"><i></i></div><b>0%</b>
|
||||
</div>
|
||||
|
||||
@@ -39,7 +39,7 @@
|
||||
<span>篇 <b class="pos">4</b> / 6</span>
|
||||
</p>
|
||||
|
||||
<!-- AUTO:hero -->
|
||||
<!-- AUTO:hero -->
|
||||
<div class="modhero">
|
||||
<span class="mh-no">篇 4 / 6</span>
|
||||
<h1>场景还原 · 端到端与故障</h1>
|
||||
@@ -57,7 +57,7 @@
|
||||
<button class="btn" id="expandAll">展开全部小节</button>
|
||||
<button class="btn" id="resetBtn">清空进度</button>
|
||||
<button class="btn" id="printBtn">打印</button>
|
||||
<!-- AUTO:prog -->
|
||||
<!-- AUTO:prog -->
|
||||
<div class="progwrap" data-chapters="20,21">
|
||||
<span>已读</span><div class="bar"><i></i></div><b>0%</b>
|
||||
</div>
|
||||
|
||||
@@ -39,7 +39,7 @@
|
||||
<span>篇 <b class="pos">5</b> / 6</span>
|
||||
</p>
|
||||
|
||||
<!-- AUTO:hero -->
|
||||
<!-- AUTO:hero -->
|
||||
<div class="modhero">
|
||||
<span class="mh-no">篇 5 / 6</span>
|
||||
<h1>收尾 · 速查与自测</h1>
|
||||
@@ -57,7 +57,7 @@
|
||||
<button class="btn" id="expandAll">展开全部小节</button>
|
||||
<button class="btn" id="resetBtn">清空进度</button>
|
||||
<button class="btn" id="printBtn">打印</button>
|
||||
<!-- AUTO:prog -->
|
||||
<!-- AUTO:prog -->
|
||||
<div class="progwrap" data-chapters="22">
|
||||
<span>已读</span><div class="bar"><i></i></div><b>0%</b>
|
||||
</div>
|
||||
|
||||
@@ -110,12 +110,15 @@ for (const f of pages) {
|
||||
}
|
||||
}
|
||||
|
||||
/* 代码块结构(骨架期还没有代码块,data-lang 只在有时校验) */
|
||||
/* 代码块结构(骨架期还没有代码块,data-lang 只在有时校验)
|
||||
mermaid 块的标签换行合法地写成 <br/>,只允许这一种标签,其余 < 仍算未转义。 */
|
||||
const pres = markup.match(/<pre[\s\S]*?<\/pre>/g) || [];
|
||||
pres.forEach((blk, i) => {
|
||||
must(/data-lang=/.test(blk), `${f}: 第 ${i + 1} 个 <pre> 未标注 data-lang`);
|
||||
const body = blk.replace(/^<pre[^>]*>/, "").replace(/<\/pre>$/, "");
|
||||
must(!/</.test(body), `${f}: 第 ${i + 1} 个 <pre> 内有未转义的 <`);
|
||||
const isDiagram = /class="mermaid"|data-lang="mermaid"/.test(blk);
|
||||
must(!(isDiagram ? body.replace(/<br\s*\/?>/g, "") : body).includes("<"),
|
||||
`${f}: 第 ${i + 1} 个 <pre> 内有未转义的 <`);
|
||||
});
|
||||
|
||||
/* 标签配对 */
|
||||
|
||||
Reference in New Issue
Block a user