Files
materials/project/VLoop/14-notify.html

501 lines
36 KiB
HTML
Raw Normal View History

<!DOCTYPE html>
<html lang="zh-CN" data-theme="light">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>第 14 章 通知、SSE 与私信:实时推送链路 · VLoop 项目学习</title>
<meta name="description" content="从事件到浏览器:三类通知的落库、用 routing key 充当事件类型的取舍、进程内 SSEHub 的广播与保活、SSE 鉴权,以及私信与前端缺口。">
<meta name="keywords" content="通知,SSE,实时推送,EventSource,私信,Hub">
<link rel="stylesheet" href="assets/doc.css">
</head>
<body>
<header class="topbar">
<div class="tb-in">
<a class="brand" href="index.html"><span class="logo">VL</span><div>VLoop 项目学习<small>Go + Vue 全栈 · 源码拆解 / 面试模拟 / 场景还原</small></div></a>
<nav class="partnav" id="partnav"><a class="home" href="index.html">学习地图</a><span class="pn-sep"></span><a href="part-0.html">篇 0 前言</a><a href="part-1.html">篇 1 知识学习</a><a href="part-2.html" class="on">篇 2 项目拆解</a><a href="part-3.html">篇 3 面试模拟</a><a href="part-4.html">篇 4 场景还原</a><a href="part-5.html">篇 5 收尾</a></nav>
<div class="spacer"></div>
<button class="btn" id="tocToggle">☰ 导航</button>
<button class="btn" id="themeBtn" title="切换到深色主题">深色</button>
</div>
</header>
<div class="layout" id="layout">
<aside class="sidebar">
<h2>章节目录</h2>
<nav id="chapters"><div class="toc-scope"><span class="ts-label">篇 2</span><span class="ts-name">项目拆解</span><a class="ts-all" href="index.html">全部篇章 →</a></div><a class="toc-a" href="05-architecture.html"><i class="cn">5</i>工程结构与双进程:API 与 Worker 如何分工</a><a class="toc-a" href="06-datamodel.html"><i class="cn">6</i>数据模型与表关系:十一张表怎么设计</a><a class="toc-a" href="07-auth.html"><i class="cn">7</i>账号与鉴权:双 Token、会话撤销与限流</a><a class="toc-a" href="08-video.html"><i class="cn">8</i>视频发布:上传、封面、话题标签与 Outbox</a><a class="toc-a" href="09-feed.html"><i class="cn">9</i>Feed 流:三级缓存、冷热分离与游标分页</a><a class="toc-a" href="10-popularity.html"><i class="cn">10</i>热榜与热度:分钟窗口、快照合并与稳定分页</a><a class="toc-a" href="11-interaction.html"><i class="cn">11</i>点赞 / 评论 / 关注:三条写路径的差异与降级</a><a class="toc-a" href="12-mq.html"><i class="cn">12</i>消息队列与可靠性:连接管理器、拓扑重放与消费循环</a><a class="toc-a" href="13-chunk.html"><i class="cn">13</i>分片上传:会话、校验与断点续传</a><span class="toc-a active" aria-current="page"><i class="cn">14</i>通知、SSE 与私信:实时推送链路</span><div class="subnav current"><a class="toc-a lv3" href="#sec-14-1">14.1 通知的三种来源与落库</a><a class="toc-a lv3" href="#sec-14-2">14.2 用 routing key 充当事件类型的取舍</a><a class="toc-a lv3" href="#sec-14-3">14.3 SSEHub:进程内广播与 30 秒保活</a><a class="toc-a lv3" href="#sec-14-4">14.4 SSE 鉴权:query token 与 Bearer</a><a class="toc-a lv3" href="#sec-14-5">14.5 私信:同步写库与会话查询</a><a class="toc-a lv3" href="#sec-14-6">14.6 前端的缺口:通知为什么看不见</a></div><a class="toc-a" href="15-cache-limit.html"><i class="cn">15</i>缓存与限流:键空间、TTL、分布式锁与窗口算法</a><a class="toc-a" href="16-observability.html"><i class="cn">16</i>可观测性与部署:探针、pprof、Compose、start.sh 与 CI</a></nav>
<div class="side-foot">
<a class="btn" href="index.html">← 学习地图</a>
<a class="btn" href="22-cheatsheet.html">速查与自测</a>
</div>
</aside>
<div class="mask" id="mask"></div>
<main class="main-col">
<article>
<p class="chapnav">
<a href="index.html">VLoop 项目学习</a>
<span>·</span>
<a href="part-2.html">篇 2 项目拆解</a>
<span>·</span>
<span>第 <b class="pos">14</b> / 22 章</span>
</p>
<h2 id="ch14"><span class="n">14</span>通知、SSE 与私信:实时推送链路</h2>
<div class="lead">
<b>这一章解决什么:</b>点赞、评论、关注各自产生一条通知,这条通知怎么落库、怎么在用户还开着页面的那一刻推过去;私信为什么压根没走消息队列;以及为什么后端这条实时链路已经能跑通,前端页面上却一条通知都看不见。
</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>
<div class="tablewrap">
<table>
<thead><tr><th>事件 routing key</th><th>业务队列(绑定键)</th><th>通知队列(绑定键)</th><th>消费者进程</th></tr></thead>
<tbody>
<tr><td><code>like.like</code></td><td><code>like.events</code>(<code>like.*</code>)</td><td><code>notification.like</code>(<code>like.like</code>)</td><td>API</td></tr>
<tr><td><code>comment.publish</code></td><td><code>comment.events</code>(<code>comment.*</code>)</td><td><code>notification.comment</code>(<code>comment.publish</code>)</td><td>API</td></tr>
<tr><td><code>social.follow</code></td><td><code>social.events</code>(<code>social.*</code>)</td><td><code>notification.social</code>(<code>social.follow</code>)</td><td>API</td></tr>
</tbody>
</table>
</div>
<p>这三组拓扑登记在 API 进程里,注意队列名与绑定键都写成了字面量,而不是复用 publisher 的常量:</p>
<pre data-lang="go" data-name="backend/internal/http/router.go:236-249"> // 3 个 notification 消费者:拓扑登记后由管理器随每一代连接重放
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"},
)
for _, q := range []string{"notification.like", "notification.comment", "notification.social"} {
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())
})
}
} else {
log.Printf("Notification SSE disabled (MQ not available)")
}</pre>
<p>落库的形状是一张单表,三种通知共用,靠 <code>type</code> 区分:</p>
<pre data-lang="go" data-name="backend/internal/worker/notificationworker.go:15-24">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"`
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>
<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>
<div class="tablewrap">
<table>
<thead><tr><th>通知类型</th><th>收件人</th><th>发送人</th><th><code>target_id</code> 指向</th><th>正文</th></tr></thead>
<tbody>
<tr><td><code>like</code></td><td>视频作者(回查 <code>videos</code>)</td><td>点赞人</td><td><code>videos.id</code></td><td>点赞了你的视频</td></tr>
<tr><td><code>comment</code></td><td>视频作者(回查 <code>videos</code>)</td><td>评论人</td><td><code>videos.id</code></td><td>评论了你的视频</td></tr>
<tr><td><code>follow</code></td><td>被关注者(事件直接给出)</td><td>关注者</td><td><code>accounts.id</code>(<code>FollowerID</code>)</td><td>关注了你</td></tr>
<tr><td><code>mention</code></td><td>被 @ 的用户(回查 <code>accounts</code>)</td><td>评论作者</td><td><code>videos.id</code></td><td>&lt;用户名&gt; 在评论中提到了你</td></tr>
</tbody>
</table>
</div>
<p>三条正路都会被两个条件过滤掉:<strong>视频不存在</strong>(<code>authorID == 0</code>)与<strong>自己操作自己的视频</strong>(<code>authorID == evt.UserID</code>)。这两条都写作 <code>return nil</code>,也就是"处理成功、正常 Ack",不是错误。</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>
</div>
<div class="box note">
<span class="bt">通知是纯派生数据</span>
<p>通知表可以完全由 <code>likes</code> / <code>comments</code> / <code>socials</code> 重算出来,但项目里<strong>没有任何对账或重建任务</strong>(ISSUES-REPORT 的 A-3)。因此 14.2 里那种"绑定漏登记、消息压根没进队列"的静默丢失一旦发生,除了用户自己发现少了通知,没有第二条发现路径。</p>
</div>
<h3 id="sec-14-2">14.2 用 routing key 充当事件类型的取舍</h3>
<p>在拓扑层,routing key 就是事件类型:绑 <code>like.like</code> 的队列只会收到点赞事件。但消费者不能把这层约定当成分派依据。NotificationWorker 判断"这是什么事件"时,用的是<strong>队列名加上信封里的 <code>action</code></strong>:先按 <code>w.queue</code> 查出这个队列唯一期望的 action,再解出 body 里的 <code>envelope.Action</code> 比对。队列到 action 的映射就是这三行:</p>
<pre data-lang="go" data-name="backend/internal/worker/notificationworker.go:19-24">// 分派必须用队列 + body.action:重试回源会把 routing key 改写成队列名。
var notificationActions = map[string]string{
rabbitmq.NotificationLikeQueue: "like",
rabbitmq.NotificationCommentQueue: "publish",
rabbitmq.NotificationSocialQueue: "follow",
}</pre>
<p>拿到期望值之后才解析 body,对不上就说明这条消息不该出现在这个队列里,直接 <code>Permanent</code>;对齐了才按队列进入各自的 apply 分支:</p>
<pre data-lang="go" data-name="backend/internal/worker/notificationworker.go:53-81">func (w *NotificationWorker) process(ctx context.Context, d amqp.Delivery) error {
if len(d.Body) == 0 {
return rabbitmq.Permanent(errors.New("notification worker: empty body"))
}
want, ok := notificationActions[w.queue]
if !ok {
return rabbitmq.Permanent(fmt.Errorf("notification worker: unexpected queue %q", w.queue))
}
var envelope struct {
Action string `json:"action"`
}
if err := json.Unmarshal(d.Body, &envelope); err != nil {
return rabbitmq.Permanent(fmt.Errorf("notification worker: decode envelope: %w", err))
}
if envelope.Action != want {
return rabbitmq.Permanent(fmt.Errorf("notification worker: queue %q expects action %q, got %q", w.queue, want, envelope.Action))
}
switch w.queue {
case rabbitmq.NotificationLikeQueue:
return w.applyLike(ctx, d.Body)
case rabbitmq.NotificationCommentQueue:
return w.applyComment(ctx, d.Body)
case rabbitmq.NotificationSocialQueue:
return w.applySocial(ctx, d.Body)
}
return nil
}</pre>
<p>失败语义因此和"静默丢弃"相反。空 body、action 与队列不符、信封解不出来,以及事件里 <code>UserID</code> / <code>VideoID</code> 为 0(评论看 <code>AuthorID</code>,关注看 <code>FollowerID</code> / <code>VloggerID</code>),全部返回 <code>rabbitmq.Permanent(...)</code>:<code>ConsumeLoop</code> 一次都不重试,直接把消息停泊到 <code>dlx.events</code>(路由键 <code>parked.&lt;源队列&gt;</code>),进唯一的停泊队列 <code>failed.events</code>,再由 <code>FailedEventWorker</code> 落库到 <code>failed_events</code> 表,<code>source_queue</code>、<code>event_id</code>、<code>attempts</code>、<code>last_error</code> 与原始 body 都留着。真正会被 <code>nil</code> 静默吃掉的是点赞、评论两条分支里语义上"不需要通知"的两种情况:视频作者回查为空(视频已删)和自己操作自己的视频。这两种不是错误,正常 Ack。</p>
<p>这跟其余三个 worker 是同一个方向、不同形状。点赞、评论、关注 worker 都先 <code>json.Unmarshal</code> 出完整事件体,再 <code>switch evt.Action</code>;通知 worker 要回答的是"这个队列该收什么",所以在解析事件体之前就把期望值取出来了。真正决定"哪些事件会进通知队列"的仍然是绑定关系——通知队列绑的是精确匹配的正向键,业务队列绑的是通配的 <code>like.*</code>,一条消息最终进哪些队列由这层差异决定:</p>
<div class="tablewrap">
<table>
<thead><tr><th>routing key</th><th>命中 <code>like.*</code> 之类的通配绑定?</th><th>命中通知队列的精确绑定?</th><th>通知</th></tr></thead>
<tbody>
<tr><td><code>like.like</code></td><td>是</td><td>是(<code>like.like</code>)</td><td>产生</td></tr>
<tr><td><code>like.unlike</code></td><td>是</td><td>否</td><td>不产生</td></tr>
<tr><td><code>comment.publish</code></td><td>是</td><td>是(<code>comment.publish</code>)</td><td>产生</td></tr>
<tr><td><code>comment.delete</code></td><td>是</td><td>否</td><td>不产生</td></tr>
<tr><td><code>social.follow</code></td><td>是</td><td>是(<code>social.follow</code>)</td><td>产生</td></tr>
<tr><td><code>social.unfollow</code></td><td>是</td><td>否</td><td>不产生</td></tr>
</tbody>
</table>
</div>
<p><strong>那为什么不能像拓扑层那样直接看 <code>d.RoutingKey</code>?因为重试回源会把路由键改写成队列名。</strong>业务队列的 DLX 只指向自己那份 <code>retry.events.notification.like</code>,不设回源路由键,所以第一次被拒时消息保留的仍是 <code>like.like</code>;但重试队列 <code>notification.like.retry</code> 的 TTL 到期后走默认交换机 <code>""</code> 回源,路由键被显式写成队列名 <code>notification.like</code>。于是从第二次投递起,<code>d.RoutingKey</code> 等于队列名,不再等于事件类型。</p>
<p>按路由键分派的消费者在这一跳就会认不出消息:如果把"未知路由键"当坏消息处理,重试预算在第 2 次投递就被吃掉(默认 <code>MaxAttempts</code> 是 4),一次瞬时 DB 抖动就把通知直接送进 <code>failed_events</code>。队列名则不会漂移——它在构造 worker 时就固定,<code>applyLike</code> 之类的分支也只认自己那一份。这条约束在代码里压缩成了一行注释:<code>分派必须用队列 + body.action:重试回源会把 routing key 改写成队列名。</code></p>
<div class="box note">
<span class="bt">"取消点赞不通知"是绑定键决定的,不是代码判断出来的</span>
<p>很多人会以为 <code>process</code> 里有一个 <code>case "like.unlike": return</code>。其实没有——<code>like.unlike</code> 根本就没被投进 <code>notification.like</code>,因为那个队列只绑了 <code>like.like</code>。这个取舍很划算:通知语义完全由 broker 侧的拓扑表达,消费者代码里没有任何"要不要通知"的分支(<code>notificationActions</code> 只校验"该来的来没来",不负责决定要不要发)。代价是这层语义<strong>只看代码读不出来</strong>,必须同时看 <code>router.go</code> 的拓扑登记和那张队列到 action 的映射。</p>
</div>
<div class="box warn">
<span class="bt">类型契约散落两处,漏改即静默失效</span>
<p>同一个"通知类型"被表达了两次:<code>backend/internal/http/router.go</code> 里 <code>rabbitmq.LikeLikeRK</code> / <code>CommentPublishRK</code> / <code>SocialFollowRK</code> 三个绑定键常量,和 <code>notificationActions</code> 里 <code>like</code> / <code>publish</code> / <code>follow</code> 三个 action 字符串。两处都是裸字符串,编译器不会帮你对齐。少登记一条绑定 → 队列收不到消息,消息在 broker 层就没了,<code>failed_events</code> 里也不会有;绑定还在但 action 对不上 → <code>Permanent</code>,停泊进 <code>failed_events</code>;队列名写错 → <code>unexpected queue</code>,同样直接停泊。所以"没有通知"和"通知被停泊"是两种不同的现场,后者查表可见,前者只能靠用户自己发现。</p>
</div>
<div class="box tip">
<span class="bt">这种写法的实际收益</span>
<p>代价是 body 被解析两遍——信封一遍、事件体一遍。换来的是一个不会随重试漂移的分派依据:队列名在构造 worker 时就固定,重试只改路由键。校验也集中在一处,三个 apply 分支不用各自判断"这条该不该由我处理";绑定关系同时还是文档,想知道什么事件会产生通知,去 <code>router.go</code> 看那三行拓扑登记即可。</p>
</div>
<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 {
mu sync.RWMutex
clients map[uint][]chan *Notification
db *gorm.DB
}
func NewSSEHub(db *gorm.DB) *SSEHub {
return &SSEHub{clients: make(map[uint][]chan *Notification), db: db}
}
func (h *SSEHub) Push(userID uint, n *Notification) {
h.mu.RLock()
defer h.mu.RUnlock()
chs, ok := h.clients[userID]
if !ok {
return
}
for _, ch := range chs {
select {
case ch &lt;- n:
default:
}
}
}
func (h *SSEHub) Subscribe(userID uint) chan *Notification {
ch := make(chan *Notification, 20)
h.mu.Lock()
h.clients[userID] = append(h.clients[userID], ch)
h.mu.Unlock()
return ch
}</pre>
<p>三个细节决定了它的行为边界:channel <strong>带 20 的缓冲</strong>;<code>Push</code> 用 <code>select</code> + <code>default</code> 做<strong>非阻塞投递</strong>;一个用户可以同时有多个连接(同账号多标签页),所以 value 是 slice 而不是单个 channel。</p>
<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")
c.Writer.Header().Set("Cache-Control", "no-cache")
c.Writer.Header().Set("Connection", "keep-alive")
c.Writer.WriteHeader(http.StatusOK)
ch := h.Subscribe(userID)
defer h.Unsubscribe(userID, ch)
ctx := c.Request.Context()
flusher, _ := c.Writer.(http.Flusher)
for {
select {
case &lt;-ctx.Done():
return
case n, ok := &lt;-ch:
if !ok {
return
}
b, _ := json.Marshal(n)
fmt.Fprintf(c.Writer, "data: %s\n\n", b)
if flusher != nil {
flusher.Flush()
}
case &lt;-time.After(30 * time.Second):
fmt.Fprintf(c.Writer, ": keepalive\n\n")
if flusher != nil {
flusher.Flush()
}
}
}</pre>
<p>线格式是最朴素的 SSE:消息帧是 <code>data: &lt;json&gt;\n\n</code>,保活帧是一个以冒号开头的注释行 <code>: keepalive\n\n</code>(注释帧会被浏览器忽略,只为把中间的代理和负载均衡的空闲超时顶掉)。<code>Unsubscribe</code> 会在移除订阅时 <code>close(c)</code>,所以 handler 里那个 <code>ok</code> 判断是有意义的。</p>
<div class="box danger">
<span class="bt">丢事件是静默的</span>
<p><code>Push</code> 的 <code>select/default</code> 意味着<strong>只要 20 格缓冲满了就直接扔掉这条通知</strong>——不重试、不落库、不打日志、没有计数器。什么时候会满?客户端 TCP 窗口收住(用户切走标签页、弱网、正在下载)导致 Flush 阻塞时,30 秒内来 20 条以上的通知就溢出了。<code>Push</code> 还持有读锁做投递,所以这里也没有等待的余地。真正兜底的是 <code>/notification/list</code> 那 50 条历史——也就是说<strong>实时通道被有意设计成"可丢的加速层",DB 才是事实源</strong>,这一点值得在面试里主动讲明。</p>
</div>
<div class="box warn">
<span class="bt">进程内 map 天然只支持单实例</span>
<p><code>clients</code> 是 API 进程的堆内存。三个通知消费者也在这个进程里(14.1),所以"谁消费到消息、谁就推得出去"当前是成立的。但这个成立条件是<strong>部署形态</strong>而不是代码保证:一旦 API 水平扩到两个实例,消费者在多实例间竞争队列消息,用户连的却是其中一个实例——落在另一个实例上的通知就永远推不到这个连接上。ISSUES-REPORT 把它记作 A-5,并指出整个项目其实隐含"单 API 实例"这一约束。</p>
<p>另外,事件里没有 <code>id</code> 字段,前端也就无从发 <code>Last-Event-ID</code>:<strong>断线期间的通知不会补推</strong>,重连后只能靠 <code>/notification/list</code> 重新拉一遍。</p>
</div>
<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>
</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 {
return func(c *gin.Context) {
token := c.Query("token")
if token == "" {
token = c.GetHeader("Authorization")
if len(token) &gt; 7 &amp;&amp; token[:7] == "Bearer " {
token = token[7:]
}
}
if token == "" {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "missing token"})
return
}
claims, err := auth.ParseToken(token)
if err != nil {
// 与 middleware/jwt 保持一致:密钥未配置属服务端故障(500),不是客户端凭证问题。
if errors.Is(err, auth.ErrSecretNotConfigured) {
log.Printf("FATAL: JWT secret not configured; SSE %s rejected", c.Request.URL.Path)
c.AbortWithStatusJSON(http.StatusInternalServerError,
gin.H{"error": "server auth misconfigured"})
return
}
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid token"})
return
}
c.Set("accountID", claims.AccountID)
c.Next()
}
}</pre>
<p>取值顺序是 <strong>query 优先、Header 兜底</strong>,Header 分支手动剥掉 <code>Bearer </code> 前缀。解析失败的分流沿用了 P0-1 的约定:密钥未配置是服务端故障,回 500 并打 FATAL,绝不伪装成 401。</p>
<p>整个 <code>/notification</code> 组只挂了这一个中间件,四个端点共用:</p>
<div class="tablewrap">
<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>
</tbody>
</table>
</div>
<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) {
key := cache.Key("account:%d", claims.AccountID)
// 先查 Redis
if cache != nil {
cacheCtx, cancel := context.WithTimeout(c.Request.Context(), 50*time.Millisecond)
defer cancel()
b, err := cache.GetBytes(cacheCtx, key)
if err == nil {
if string(b) != tokenString {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "token has been revoked"})
return
}</pre>
<p>而 <code>SSERequireAuth</code> 只调用了 <code>auth.ParseToken</code>,<strong>没有这一步</strong>。结果是:一个已经被改名/改密/登出作废的 token,签名依然有效、也没过期,于是它仍然能连上 <code>/notification/stream</code>、读 <code>/list</code>、改 <code>/markRead</code>。第 7 章讲的"三处 Redis 键支撑踢人",在通知这条链路上是不生效的。</p>
</div>
<div class="box warn">
<span class="bt">POST 端点也接受了 query 里的 token</span>
<p>因为整组共用 <code>SSERequireAuth</code>,<code>/notification/list</code>、<code>/markRead</code>、<code>/unreadCount</code> 这三个普通 POST 接口同样接受 <code>?token=xxx</code>。这三个接口本来用 <code>jwt.JWTAuth</code> 就够了(前端 <code>fetch</code> 可以带头),把 token 放进 URL 的代价是会进入 nginx/反代的访问日志、以及浏览器的 Referer。同组的 <code>SSERequireAuth</code> 还<strong>不设置 <code>username</code></strong>(<code>check</code> 会 <code>c.Set("username", ...)</code>,这里只设 <code>accountID</code>),所以将来若有 handler 依赖用户名会直接拿不到。</p>
</div>
<h3 id="sec-14-5">14.5 私信:同步写库与会话查询</h3>
<p>私信是整站唯一的<strong>纯同步写路径</strong>:没有 MQ、没有缓存、没有降级,请求进来直接 INSERT 然后返回。</p>
<pre data-lang="go" data-name="backend/internal/message/entity.go:5-12">type Message struct {
ID uint `gorm:"primaryKey" json:"id"`
FromID uint `gorm:"index:idx_message_from;not null" json:"from_id"`
ToID uint `gorm:"index:idx_message_to;not null" json:"to_id"`
Content string `gorm:"type:text;not null" json:"content"`
IsRead bool `gorm:"default:false" json:"is_read"`
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
}</pre>
<p>它也是唯一一个把 <code>Repository</code>、<code>Service</code>、<code>Handler</code> 三个类型塞进同一个文件的域。第 5 章讲过六种分层浓度,message 是最淡的那一档:<code>Service</code> 只是包了一层 <code>repo</code>,<code>Handler</code> 越级直接调 <code>h.service.repo.Send(...)</code>。</p>
<pre data-lang="go" data-name="backend/internal/message/handler.go:29-46">func (r *Repository) Send(ctx context.Context, m *Message) error {
m.Content = strings.TrimSpace(m.Content)
if m.Content == "" {
return errors.New("content is required")
}
m.CreatedAt = time.Now()
return r.db.WithContext(ctx).Create(m).Error
}
func (r *Repository) List(ctx context.Context, userID, peerID uint, limit int) ([]Message, error) {
var msgs []Message
err := r.db.WithContext(ctx).
Where("(from_id = ? AND to_id = ?) OR (from_id = ? AND to_id = ?)", userID, peerID, peerID, userID).
Order("created_at desc").
Limit(limit).
Find(&msgs).Error
return msgs, err
}</pre>
<p>会话查询就是这条双向 OR:把 <code>(A→B)</code> 与 <code>(B→A)</code> 合起来按时间倒序取。<code>limit</code> 由 handler 写死为 <code>50</code>(<code>backend/internal/message/handler.go:86</code>),没有游标、没有 <code>before_id</code>,也就是说<strong>第 51 条以前的历史在接口上根本无法翻到</strong>。</p>
<div class="tablewrap">
<table>
<thead><tr><th>域</th><th>写路径</th><th>缓存</th><th>层数</th><th>同步/异步</th></tr></thead>
<tbody>
<tr><td>like</td><td>MQ 优先,失败直写事务</td><td>热度先删缓存</td><td>4 层</td><td>异步</td></tr>
<tr><td>comment</td><td>MQ 优先,失败直写事务</td><td>热度先删缓存</td><td>4 层</td><td>异步</td></tr>
<tr><td>social</td><td>DB 优先,再发 MQ 通知</td><td>失效关注流整页缓存</td><td>4 层</td><td>同步 + 事后通知</td></tr>
<tr><td>message</td><td>直接 INSERT</td><td>无</td><td>1 个文件 3 个类型</td><td>同步</td></tr>
</tbody>
</table>
</div>
<div class="box warn">
<span class="bt">Send 的三个校验缺口(ISSUES-REPORT P3-31)</span>
<p>① <strong>不校验收件人是否存在</strong>:<code>handler.go:59-62</code> 只判 <code>req.ToID == 0</code>,<code>ToID = 99999999</code> 会照样写入一行指向不存在账号的私信;<code>messages.to_id</code> 上也没有任何 DB 外键兜底。② <strong>可以发给自己</strong>:没有 <code>ToID == fromID</code> 的检查(前端在 <code>MessageView.vue:77</code> 用 <code>peerId.value === myId.value</code> 挡了一层,但那只约束了 UI)。③ <strong>没有长度上限</strong>:<code>Content</code> 是 <code>type:text</code>,单条最大 64KB,应用层不做限制。<code>is_read</code> 字段虽然在表里,但没有任何接口会更新它。</p>
</div>
<div class="box note">
<span class="bt">双向 OR 与索引</span>
<p>表上只有 <code>idx_message_from</code> 与 <code>idx_message_to</code> 两个单列索引,而这条查询的过滤条件是两组 <code>(from, to)</code> 组合、排序键是 <code>created_at</code>。MySQL 只能对 OR 的两边各走一次索引再合并,排序必然要 filesort。数据量小的时候无感,但这是第 6 章"索引要覆盖过滤 + 排序"那条原则的一个反例。</p>
</div>
<h3 id="sec-14-6">14.6 前端的缺口:通知为什么看不见</h3>
<p>后端这条链路是完整可用的:队列有人消费、通知会落库、连接能建立、消息能推。但它<strong>没有任何客户端</strong>。在前端源码里搜索这条链路会用到的一切标识符,结果是零:</p>
<div class="tablewrap">
<table>
<thead><tr><th>搜索项</th><th>范围</th><th>命中</th><th>含义</th></tr></thead>
<tbody>
<tr><td><code>EventSource</code></td><td><code>frontend/src/**</code></td><td>0</td><td>没有任何地方建立 SSE 连接</td></tr>
<tr><td><code>event-stream</code></td><td><code>frontend/src/**</code></td><td>0</td><td>没有对应的解析代码</td></tr>
<tr><td><code>notification</code> / <code>unreadCount</code> / <code>markRead</code></td><td><code>frontend/src/**</code></td><td>0</td><td>四个端点全未被调用</td></tr>
<tr><td><code>api/notification.ts</code></td><td><code>frontend/src/api/</code></td><td>文件不存在</td><td>api 目录只有 account / comment / feed / like / message / social / video 七个域</td></tr>
</tbody>
</table>
</div>
<div class="box danger">
<span class="bt">端到端断在最后一步(ISSUES-REPORT P1-9 / F-1)</span>
<p>于是形成一个很典型的"后端做完了、产品上没有人看得见"的状态:点赞之后作者那一侧<strong>永远不会有任何提示</strong>——没有红点、没有未读数、没有 toast,也不会出现在任何页面里,因为通知列表接口同样没被调用。要观察到这条链路真的在工作,只能手工打接口:</p>
<pre data-lang="bash" data-name="手工验证通知链路"># 1. 拿一个 token(登录接口返回 token 字段)
curl -s -X POST http://127.0.0.1:8080/account/login \
-H 'Content-Type: application/json' \
-d '{"username":"alice","password":"..."}'
# 2. 用作者自己的 token 挂上 SSE 长连接(curl -N 关闭缓冲,否则看不到流式输出)
curl -N "http://127.0.0.1:8080/notification/stream?token=&lt;作者的 token&gt;"
# 预期先看到保活注释帧 : keepalive(每 30 秒一次)
# 3. 用另一个账号给作者的一条视频点赞,第 2 步的终端里应立刻出现:
# data: {"id":1,"recipient_id":2,"sender_id":3,"type":"like","target_id":9,
# "content":"点赞了你的视频","is_read":false,"created_at":"..."}
# 4. 未读数与历史(注意这三个 POST 也接受 query token)
curl -s -X POST "http://127.0.0.1:8080/notification/unreadCount?token=&lt;token&gt;"
curl -s -X POST "http://127.0.0.1:8080/notification/list?token=&lt;token&gt;"</pre>
</div>
<div class="box tip">
<span class="bt">契约已经定好了,缺的只是调用方</span>
<p>把这条链路接进前端,需要的全部信息都已经在上面了:连接地址(<code>/notification/stream?token=</code>)、帧格式(<code>data: &lt;Notification&gt;\n\n</code>,注释帧可忽略)、落库对象的字段名,以及三个补充接口。真正需要设计决策的只有两件事:<strong>token 放在 query 里会进日志</strong>(14.4),以及<strong>这个 hub 只在单个 API 实例内有效</strong>(14.3)。换句话说,前端接入是小事,部署形态才是真问题。</p>
</div>
<div class="box note">
<span class="bt">顺带一提:私信也没有实时通道</span>
<p>第 14.5 节的私信同样没有推送,也没有轮询:<code>MessageView.vue</code> 只在进入会话时拉一次、发送成功后把新消息前插。换句话说我发出去的消息对面必须<strong>手动刷新页面</strong>才能看到。两条实时需求(通知、私信)目前都停在"后端有基础设施、前端没有消费"的同一种状态上。</p>
</div>
<nav class="pager">
<a class="prev" href="13-chunk.html"><span class="k">← 上一章</span><span class="v">第 13 章 · 分片上传:会话、校验与断点续传</span></a>
<a class="next" href="15-cache-limit.html"><span class="k">下一章 →</span><span class="v">第 15 章 · 缓存与限流:键空间、TTL、分布式锁与窗口算法</span></a>
</nav>
<p class="foot">
VLoop 项目学习 · 第 14 章 通知、SSE 与私信:实时推送链路<br>
<a href="index.html">学习地图</a> · <a href="part-2.html">篇 2 项目拆解</a> · <a href="22-cheatsheet.html">速查与自测</a>
</p>
</article>
</main>
</div>
<button id="toTop" title="回到顶部">↑</button>
<script src="assets/doc.js"></script>
<script src="../../assets/back.js" data-portal-back="project/VLoop" data-portal-label="工程项目 › VLoop 项目学习(Go 短视频 Feed 系统)"></script>
</body>
</html>