docs(vloop): 修正中危与低危条目的代码断言

第二轮按审计清单处理 20 章的 92 条中危与低危条目。
主要修正:包数与测试分布;AutoMigrate 只由 API 调用一次;预取档位 50/10/1;热榜快照 TTL 与索引列;锁键拼接;as_of 单位;行号引用改为文件加符号。

验证:node tools/build-nav.js 与 node tools/check-pages.js 退出 0,29 个页面全部通过。
This commit is contained in:
2026-11-03 13:07:55 +08:00
parent 8993f115b9
commit 476f225f4c
24 changed files with 244 additions and 199 deletions

View File

@@ -48,7 +48,7 @@
</div>
<h3 id="sec-14-1">14.1 通知的三种来源与落库</h3>
<p>通知不是 API 进程写出来的,而是<strong>业务事件在 MQ 上被复制了一份</strong>。三条正路都遵循同一形状:业务 worker 往 <code>like.events</code> / <code>comment.events</code> / <code>social.events</code> 发一条事件,topic 交换机把它投给所有匹配的绑定,于是同一份消息同时进入<em>业务队列</em>和<em>通知队列</em>:</p>
<p>通知不是 API 进程写出来的,而是<strong>业务事件在 MQ 上被复制了一份</strong>。三条正路都遵循同一形状:请求路径上的业务服务(<code>like_service.go</code> / <code>comment_service.go</code> / <code>social/service.go</code>)在写库成功后往 <code>like.events</code> / <code>comment.events</code> / <code>social.events</code> 发一条事件,topic 交换机把它投给所有匹配的绑定,于是同一份消息同时进入<em>业务队列</em>和<em>通知队列</em>:</p>
<div class="tablewrap">
<table>
@@ -61,20 +61,22 @@
</table>
</div>
<p>这三组拓扑登记在 API 进程里,注意队列名与绑定键都写成了字面量,而不是复用 publisher 的常量:</p>
<p>这三组拓扑登记在 API 进程里。交换机名、队列名与绑定键全部复用 <code>rabbitmq</code> 包的导出常量(<code>LikeExchange</code>、<code>NotificationLikeQueue</code>、<code>LikeLikeRK</code> 之类)——它们是跨进程的线缆契约,在这里再写一遍字面量就会与 Worker 侧悄悄漂移:</p>
<pre data-lang="go" data-name="backend/internal/http/router.go:236-249"> // 3 个 notification 消费者:拓扑登记后由管理器随每一代连接重放
<pre data-lang="go" data-name="backend/internal/http/router.go 的 RegisterTopology"> // 3 个 notification 消费者:拓扑登记后由管理器随每一代连接重放。
// 交换机名、队列名、路由键全部复用 rabbitmq 包的导出常量——它们是跨进程的
// 线缆契约,在这里再写一遍字面量就会与 Worker 侧悄悄漂移。
if rmq != nil {
rmq.RegisterTopology(
rabbitmq.Topology{Exchange: "like.events", Queue: "notification.like", BindingKey: "like.like"},
rabbitmq.Topology{Exchange: "comment.events", Queue: "notification.comment", BindingKey: "comment.publish"},
rabbitmq.Topology{Exchange: "social.events", Queue: "notification.social", BindingKey: "social.follow"},
rabbitmq.Topology{Exchange: rabbitmq.LikeExchange, Queue: rabbitmq.NotificationLikeQueue, BindingKey: rabbitmq.LikeLikeRK},
rabbitmq.Topology{Exchange: rabbitmq.CommentExchange, Queue: rabbitmq.NotificationCommentQueue, BindingKey: rabbitmq.CommentPublishRK},
rabbitmq.Topology{Exchange: rabbitmq.SocialExchange, Queue: rabbitmq.NotificationSocialQueue, BindingKey: rabbitmq.SocialFollowRK},
)
for _, q := range []string{"notification.like", "notification.comment", "notification.social"} {
for _, q := range []string{rabbitmq.NotificationLikeQueue, rabbitmq.NotificationCommentQueue, rabbitmq.NotificationSocialQueue} {
queue := q
go rabbitmq.RunConsumer(context.Background(), rmq, "notification-"+queue, 10,
func(ch *amqp.Channel) error {
return worker.NewNotificationWorker(ch, db, queue, sseHub).Run(context.Background())
return worker.NewNotificationWorker(ch, rmq, db, queue, sseHub).Run(context.Background())
})
}
} else {
@@ -83,33 +85,43 @@
<p>落库的形状是一张单表,三种通知共用,靠 <code>type</code> 区分:</p>
<pre data-lang="go" data-name="backend/internal/worker/notificationworker.go:15-24">type Notification struct {
<pre data-lang="go" data-name="backend/internal/notification/entity.go 的 Notification">type Notification struct {
ID uint `gorm:"primaryKey" json:"id"`
RecipientID uint `gorm:"index;not null" json:"recipient_id"`
SenderID uint `gorm:"not null" json:"sender_id"`
Type string `gorm:"type:varchar(50);not null" json:"type"`
TargetID uint `json:"target_id"`
TargetID uint `gorm:"column:target_id" json:"target_id"`
Content string `gorm:"type:varchar(255)" json:"content"`
IsRead bool `gorm:"default:false" json:"is_read"`
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
}</pre>
<p>收件人不是事件里带过来的,而是 worker <strong>回查一次 <code>videos</code> 表拿作者</strong>。点赞这条分支的形状最有代表性:</p>
<p>收件人不是事件里带过来的:点赞与评论两条都由 worker <strong>回查一次 <code>videos</code> 表拿作者</strong>,关注那条则直接取事件里的 <code>VloggerID</code>。点赞这条分支的形状最有代表性,它的四个出口正好覆盖"坏消息 / 无需通知 / 落库推送"三种处置:</p>
<pre data-lang="go" data-name="backend/internal/worker/notificationworker.go:108-121"> if evt.UserID == 0 || evt.VideoID == 0 {
return nil
}
var authorID uint
if err := w.db.WithContext(ctx).Model(&struct {
ID uint
AuthorID uint
}{}).Table("videos").Where("id = ?", evt.VideoID).Select("author_id").Scan(&authorID).Error; err != nil {
return err
}
if authorID == 0 || authorID == evt.UserID {
return nil
}
notif = &Notification{RecipientID: authorID, SenderID: evt.UserID, Type: "like", TargetID: evt.VideoID, Content: "点赞了你的视频"}</pre>
<pre data-lang="go" data-name="backend/internal/worker/notificationworker.go 的 applyLike">func (w *NotificationWorker) applyLike(ctx context.Context, body []byte) error {
var evt rabbitmq.LikeEvent
if err := json.Unmarshal(body, &evt); err != nil {
return rabbitmq.Permanent(fmt.Errorf("notification worker: decode like event: %w", err))
}
if evt.UserID == 0 || evt.VideoID == 0 {
return rabbitmq.Permanent(fmt.Errorf("notification worker: invalid like event user_id=%d video_id=%d", evt.UserID, evt.VideoID))
}
authorID, err := w.videoAuthorID(ctx, evt.VideoID)
if err != nil {
return err
}
if authorID == 0 || authorID == evt.UserID {
// 视频不存在,或自己赞自己:这两种都是"不需要通知"。
return nil
}
return w.persist(ctx, &notification.Notification{
RecipientID: authorID,
SenderID: evt.UserID,
Type: "like",
TargetID: evt.VideoID,
Content: "点赞了你的视频",
}, evt.EventID)
}</pre>
<div class="tablewrap">
<table>
@@ -123,11 +135,11 @@
</table>
</div>
<p>三条正路都会被两个条件过滤掉:<strong>视频不存在</strong>(<code>authorID == 0</code>)与<strong>自己操作自己的视频</strong>(<code>authorID == evt.UserID</code>)。这两条都写作 <code>return nil</code>,也就是"处理成功、正常 Ack",不是错误。</p>
<p>点赞与评论两条正路都会被两个条件过滤掉:<strong>视频不存在</strong>(<code>authorID == 0</code>)与<strong>自己操作自己的视频</strong>(<code>authorID == evt.UserID</code>)。这两条都写作 <code>return nil</code>,也就是"处理成功、正常 Ack",不是错误。关注这条没有作者可回查,只校验 <code>FollowerID</code> / <code>VloggerID</code> 非零,为 0 时按坏消息 <code>Permanent</code> 停泊。</p>
<div class="box warn">
<span class="bt">第四种通知绕过了 MQ</span>
<p><code>mention</code> 类型不在上面那张队列表里。它由评论服务在写评论成功后<strong>直接 INSERT</strong>,一行 <code>Table("notifications").Create(&amp;notif)</code>(<code>backend/internal/video/comment_service.go:154</code>)。后果有两个:它拿不到 SSE 推送(因为 <code>Push</code> 是 worker 落库后显式调用的,见 14.3),也不受通知队列的重试与后续 DLX 改造保护,失败只留一行日志。这是全项目唯一一处绕过 MQ 直接写通知表的地方。</p>
<p><code>mention</code> 类型不在上面那张队列表里。它由评论服务的 <code>notifyMentions</code> 在写评论成功后<strong>直接批量写入</strong>:先用一次 <code>FindAccountIDs</code> 把整条评论里的 <code>@用户名</code> 解析成账号 ID,再交给 <code>CommentRepository.CreateMentions</code> 带着 <code>clause.OnConflict{DoNothing: true}</code> 整批 INSERT(<code>backend/internal/video/comment_repo.go 的 CreateMentions</code>)。后果有两个:它拿不到 SSE 推送(因为 <code>Push</code> 是 worker 落库后显式调用的,见 14.3),也不受通知队列的重试与后续 DLX 改造保护,失败只在 <code>mention.create</code> 阶段留一行日志。这是全项目唯一一处绕过 MQ 直接写通知表的地方。</p>
</div>
<div class="box note">
@@ -217,17 +229,17 @@ var notificationActions = map[string]string{
<h3 id="sec-14-3">14.3 SSEHub:进程内广播与 30 秒保活</h3>
<p>落库之后要把通知推给还开着页面的用户,用的是 Server-Sent Events。承载它的 <code>SSEHub</code> 是一个<strong>纯内存的发布订阅表</strong>:一个用户 ID 对应若干个订阅 channel,每个打开的 SSE 连接就是一个 channel。</p>
<pre data-lang="go" data-name="backend/internal/worker/ssehub.go:19-50">type SSEHub struct {
<pre data-lang="go" data-name="backend/internal/worker/ssehub.go 的 SSEHub">type SSEHub struct {
mu sync.RWMutex
clients map[uint][]chan *Notification
clients map[uint][]chan *notification.Notification
db *gorm.DB
}
func NewSSEHub(db *gorm.DB) *SSEHub {
return &SSEHub{clients: make(map[uint][]chan *Notification), db: db}
return &SSEHub{clients: make(map[uint][]chan *notification.Notification), db: db}
}
func (h *SSEHub) Push(userID uint, n *Notification) {
func (h *SSEHub) Push(userID uint, n *notification.Notification) {
h.mu.RLock()
defer h.mu.RUnlock()
chs, ok := h.clients[userID]
@@ -242,8 +254,8 @@ func (h *SSEHub) Push(userID uint, n *Notification) {
}
}
func (h *SSEHub) Subscribe(userID uint) chan *Notification {
ch := make(chan *Notification, 20)
func (h *SSEHub) Subscribe(userID uint) chan *notification.Notification {
ch := make(chan *notification.Notification, 20)
h.mu.Lock()
h.clients[userID] = append(h.clients[userID], ch)
h.mu.Unlock()
@@ -254,7 +266,7 @@ func (h *SSEHub) Subscribe(userID uint) chan *Notification {
<p>HTTP 侧是一个长期不返回的 handler,靠 <code>select</code> 在"客户端断开"、"有消息"、"30 秒到点"三件事之间转:</p>
<pre data-lang="go" data-name="backend/internal/worker/ssehub.go:116-147"> c.Writer.Header().Set("Content-Type", "text/event-stream")
<pre data-lang="go" data-name="backend/internal/worker/ssehub.go 的 SSEHandler"> c.Writer.Header().Set("Content-Type", "text/event-stream")
c.Writer.Header().Set("Cache-Control", "no-cache")
c.Writer.Header().Set("Connection", "keep-alive")
c.Writer.WriteHeader(http.StatusOK)
@@ -301,13 +313,13 @@ func (h *SSEHub) Subscribe(userID uint) chan *Notification {
<div class="box note">
<span class="bt">同一个 hub 对象被两处引用</span>
<p><code>backend/internal/http/router.go:231</code> 创建 <code>sseHub</code> 之后,<code>:247</code> 把它注入了三个 NotificationWorker(<code>NewNotificationWorker(ch, db, queue, sseHub)</code>),<code>:234</code> 又用它注册路由。所以"落库"和"推送"是同一份内存状态的两个入口——这也是为什么 <code>mention</code> 通知绕开 MQ 就同时绕开了推送。</p>
<p><code>backend/internal/http/router.go</code> 里 <code>sseHub := worker.NewSSEHub(db)</code> 之后,<code>notifGroup</code> 先挂上 <code>sseHub.SSERequireAuth()</code> 再交给 <code>sseHub.RegisterRoutes</code>;同一段注册拓扑的循环又把它注入了三个 NotificationWorker(<code>NewNotificationWorker(ch, rmq, db, queue, sseHub)</code>)。所以"落库"和"推送"是同一份内存状态的两个入口——这也是为什么 <code>mention</code> 通知绕开 MQ 就同时绕开了推送。</p>
</div>
<h3 id="sec-14-4">14.4 SSE 鉴权:query token 与 Bearer</h3>
<p>浏览器的 <code>EventSource</code> <strong>不能自定义请求头</strong>,所以 SSE 的鉴权中间件必须额外接受 query 参数里的 token:</p>
<pre data-lang="go" data-name="backend/internal/worker/ssehub.go:79-107">func (h *SSEHub) SSERequireAuth() gin.HandlerFunc {
<pre data-lang="go" data-name="backend/internal/worker/ssehub.go 的 SSERequireAuth">func (h *SSEHub) SSERequireAuth() gin.HandlerFunc {
return func(c *gin.Context) {
token := c.Query("token")
if token == "" {
@@ -345,10 +357,10 @@ func (h *SSEHub) Subscribe(userID uint) chan *Notification {
<table>
<thead><tr><th>方法</th><th>路径</th><th>作用</th><th>handler</th></tr></thead>
<tbody>
<tr><td>GET</td><td><code>/notification/stream</code></td><td>SSE 长连接</td><td><code>ssehub.go:109</code></td></tr>
<tr><td>POST</td><td><code>/notification/list</code></td><td>最近 50 条,<code>created_at desc</code></td><td><code>ssehub.go:149</code></td></tr>
<tr><td>POST</td><td><code>/notification/markRead</code></td><td>按 id 或全量标记已读</td><td><code>ssehub.go:171</code></td></tr>
<tr><td>POST</td><td><code>/notification/unreadCount</code></td><td>未读数</td><td><code>ssehub.go:199</code></td></tr>
<tr><td>GET</td><td><code>/notification/stream</code></td><td>SSE 长连接</td><td><code>SSEHandler</code></td></tr>
<tr><td>POST</td><td><code>/notification/list</code></td><td>最近 50 条,<code>created_at desc</code></td><td><code>ListHandler</code></td></tr>
<tr><td>POST</td><td><code>/notification/markRead</code></td><td>按 id 或全量标记已读</td><td><code>MarkReadHandler</code></td></tr>
<tr><td>POST</td><td><code>/notification/unreadCount</code></td><td>未读数</td><td><code>UnreadCountHandler</code></td></tr>
</tbody>
</table>
</div>
@@ -356,7 +368,7 @@ func (h *SSEHub) Subscribe(userID uint) chan *Notification {
<div class="box danger">
<span class="bt">SSE 这条鉴权路径没有做会话吊销检查</span>
<p>这是本章最值得记住的一条。项目里正常的鉴权中间件除了验签,还会拿 token 和 Redis 里 <code>account:&lt;id&gt;</code> 的值比对,以支持"改名/改密/登出即踢下线"(见第 7 章):</p>
<pre data-lang="go" data-name="backend/internal/middleware/jwt/jwt.go:88-106">func check(c *gin.Context, claims *auth.Claims, tokenString string, accountRepo *account.AccountRepository, cache *rediscache.Client) {
<pre data-lang="go" data-name="backend/internal/middleware/jwt/jwt.go 的 check">func check(c *gin.Context, claims *auth.Claims, tokenString string, accountRepo *account.AccountRepository, cache *rediscache.Client) {
key := cache.Key("account:%d", claims.AccountID)
// 先查 Redis