diff --git a/assets/portal.data.js b/assets/portal.data.js index a6b5546..cc43b1c 100644 --- a/assets/portal.data.js +++ b/assets/portal.data.js @@ -241,7 +241,7 @@ window.PORTAL_DATA = { name: 'VLoop 项目学习(Go 短视频 Feed 系统)', path: 'project/VLoop/index.html', dir: 'project/VLoop', - desc: '围绕 feedsystem_video_go(VLoop)的项目学习站:六个篇、二十二章、137 个小节,从项目全景与前置知识,到逐模块源码拆解、面试追问与故障场景还原。【前言】【知识学习】两篇已完成,【项目拆解】篇的工程结构、数据模型、账号鉴权、视频发布、Feed 流、热榜与热度、点赞评论关注、消息队列与分片上传九章正文已完成,其余章节撰写中。', + desc: '围绕 feedsystem_video_go(VLoop)的项目学习站:六个篇、二十二章、137 个小节,从项目全景与前置知识,到逐模块源码拆解、面试追问与故障场景还原。【前言】【知识学习】两篇与【项目拆解】篇全十二章正文已完成,其余章节撰写中。', tags: ['Go', 'Feed', '项目拆解'], badges: ['6 篇 · 22 章', '顶栏篇章导航'], stats: [['6', '篇'], ['22', '章'], ['137', '小节']], diff --git a/project/VLoop/14-notify.html b/project/VLoop/14-notify.html index ba32ef0..b3eeed2 100644 --- a/project/VLoop/14-notify.html +++ b/project/VLoop/14-notify.html @@ -44,26 +44,409 @@
(本节内容待补充)
+通知不是 API 进程写出来的,而是业务事件在 MQ 上被复制了一份。三条正路都遵循同一形状:业务 worker 往 like.events / comment.events / social.events 发一条事件,topic 交换机把它投给所有匹配的绑定,于是同一份消息同时进入业务队列和通知队列:
| 事件 routing key | 业务队列(绑定键) | 通知队列(绑定键) | 消费者进程 |
|---|---|---|---|
like.like | like.events(like.*) | notification.like(like.like) | API |
comment.publish | comment.events(comment.*) | notification.comment(comment.publish) | API |
social.follow | social.events(social.*) | notification.social(social.follow) | API |
这三组拓扑登记在 API 进程里,注意队列名与绑定键都写成了字面量,而不是复用 publisher 的常量:
+ + // 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)")
+ }
+
+落库的形状是一张单表,三种通知共用,靠 type 区分:
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"`
+}
+
+收件人不是事件里带过来的,而是 worker 回查一次 videos 表拿作者。点赞这条分支的形状最有代表性:
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: "点赞了你的视频"}
+
+| 通知类型 | 收件人 | 发送人 | target_id 指向 | 正文 |
|---|---|---|---|---|
like | 视频作者(回查 videos) | 点赞人 | videos.id | 点赞了你的视频 |
comment | 视频作者(回查 videos) | 评论人 | videos.id | 评论了你的视频 |
follow | 被关注者(事件直接给出) | 关注者 | accounts.id(FollowerID) | 关注了你 |
mention | 被 @ 的用户(回查 accounts) | 评论作者 | videos.id | <用户名> 在评论中提到了你 |
三条正路都会被两个条件过滤掉:视频不存在(authorID == 0)与自己操作自己的视频(authorID == evt.UserID)。这两条都写作 return nil,也就是"处理成功、正常 Ack",不是错误。
mention 类型不在上面那张队列表里。它由评论服务在写评论成功后直接 INSERT,一行 Table("notifications").Create(¬if)(backend/internal/video/comment_service.go:154)。后果有两个:它拿不到 SSE 推送(因为 Push 是 worker 落库后显式调用的,见 14.3),也不受通知队列的重试与后续 DLX 改造保护,失败只留一行日志。这是全项目唯一一处绕过 MQ 直接写通知表的地方。
通知表可以完全由 likes / comments / socials 重算出来,但项目里没有任何对账或重建任务(ISSUES-REPORT 的 A-3)。因此 14.2 里那种"静默丢弃"一旦发生,除了用户自己发现少了通知,没有第二条发现路径。
(本节内容待补充)
+NotificationWorker 判断"这是什么事件"时,不看消息体,看信封:
+ +func (w *NotificationWorker) process(ctx context.Context, d amqp.Delivery) error {
+ body := d.Body
+ if len(body) == 0 {
+ return nil
+ }
+ routingKey := d.RoutingKey // 复用路由键充当事件类型标识
+
+ var notif *Notification
+
+ switch {
+ case routingKey == "like.like":
+
+这跟其余四个 worker 是反的。点赞、评论、关注 worker 都先 json.Unmarshal 出事件体,再 switch evt.Action;通知 worker 用的是 AMQP 传输层的 d.RoutingKey。之所以能这么写,是因为通知队列的绑定键是精确匹配的正向键——而业务队列绑的是通配的 like.*。一条消息最终进哪些队列,就是由这层差异决定的:
| routing key | 命中 like.* 之类的通配绑定? | 命中通知队列的精确绑定? | 通知 |
|---|---|---|---|
like.like | 是 | 是(like.like) | 产生 |
like.unlike | 是 | 否 | 不产生 |
comment.publish | 是 | 是(comment.publish) | 产生 |
comment.delete | 是 | 否 | 不产生 |
social.follow | 是 | 是(social.follow) | 产生 |
social.unfollow | 是 | 否 | 不产生 |
很多人会以为 process 里有一个 case "like.unlike": return。其实没有——like.unlike 根本就没被投进 notification.like,因为那个队列只绑了 like.like。这个取舍很划算:通知语义完全由 broker 侧的拓扑表达,消费者代码里没有任何"要不要通知"的分支。代价是这层语义只看代码读不出来,必须同时看 router.go 的拓扑登记和这里的 case。
同一个"通知类型"被表达了两次:backend/internal/http/router.go:239-241 的绑定键字面量,和 notificationworker.go:103/123/143 的 case 字符串。两处都是裸字符串,编译器不会帮你对齐。少登记一条绑定 → 队列收不到消息;多了一条 case 却没有对应绑定 → 那个分支永不触发;switch 落到 default(当前代码没有 default,notif 保持 nil)→ 走 if notif == nil { return nil },被当成"处理成功"正常 Ack 丢弃,日志里一个字都没有。
每条消息只 Unmarshal 一次(而且是在确定类型之后),省掉了"先解出一个带 Action 的公共壳、再按 Action 解第二遍"的写法。绑定关系本身就是文档:想知道什么事件会产生通知,去 router.go 看那三行绑定即可。
(本节内容待补充)
+落库之后要把通知推给还开着页面的用户,用的是 Server-Sent Events。承载它的 SSEHub 是一个纯内存的发布订阅表:一个用户 ID 对应若干个订阅 channel,每个打开的 SSE 连接就是一个 channel。
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 <- 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
+}
+
+三个细节决定了它的行为边界:channel 带 20 的缓冲;Push 用 select + default 做非阻塞投递;一个用户可以同时有多个连接(同账号多标签页),所以 value 是 slice 而不是单个 channel。
HTTP 侧是一个长期不返回的 handler,靠 select 在"客户端断开"、"有消息"、"30 秒到点"三件事之间转:
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 <-ctx.Done():
+ return
+ case n, ok := <-ch:
+ if !ok {
+ return
+ }
+ b, _ := json.Marshal(n)
+ fmt.Fprintf(c.Writer, "data: %s\n\n", b)
+ if flusher != nil {
+ flusher.Flush()
+ }
+ case <-time.After(30 * time.Second):
+ fmt.Fprintf(c.Writer, ": keepalive\n\n")
+ if flusher != nil {
+ flusher.Flush()
+ }
+ }
+ }
+
+线格式是最朴素的 SSE:消息帧是 data: <json>\n\n,保活帧是一个以冒号开头的注释行 : keepalive\n\n(注释帧会被浏览器忽略,只为把中间的代理和负载均衡的空闲超时顶掉)。Unsubscribe 会在移除订阅时 close(c),所以 handler 里那个 ok 判断是有意义的。
Push 的 select/default 意味着只要 20 格缓冲满了就直接扔掉这条通知——不重试、不落库、不打日志、没有计数器。什么时候会满?客户端 TCP 窗口收住(用户切走标签页、弱网、正在下载)导致 Flush 阻塞时,30 秒内来 20 条以上的通知就溢出了。Push 还持有读锁做投递,所以这里也没有等待的余地。真正兜底的是 /notification/list 那 50 条历史——也就是说实时通道被有意设计成"可丢的加速层",DB 才是事实源,这一点值得在面试里主动讲明。
clients 是 API 进程的堆内存。三个通知消费者也在这个进程里(14.1),所以"谁消费到消息、谁就推得出去"当前是成立的。但这个成立条件是部署形态而不是代码保证:一旦 API 水平扩到两个实例,消费者在多实例间竞争队列消息,用户连的却是其中一个实例——落在另一个实例上的通知就永远推不到这个连接上。ISSUES-REPORT 把它记作 A-5,并指出整个项目其实隐含"单 API 实例"这一约束。
另外,事件里没有 id 字段,前端也就无从发 Last-Event-ID:断线期间的通知不会补推,重连后只能靠 /notification/list 重新拉一遍。
backend/internal/http/router.go:231 创建 sseHub 之后,:247 把它注入了三个 NotificationWorker(NewNotificationWorker(ch, db, queue, sseHub)),:234 又用它注册路由。所以"落库"和"推送"是同一份内存状态的两个入口——这也是为什么 mention 通知绕开 MQ 就同时绕开了推送。
(本节内容待补充)
+浏览器的 EventSource 不能自定义请求头,所以 SSE 的鉴权中间件必须额外接受 query 参数里的 token:
func (h *SSEHub) SSERequireAuth() gin.HandlerFunc {
+ return func(c *gin.Context) {
+ token := c.Query("token")
+ if token == "" {
+ token = c.GetHeader("Authorization")
+ if len(token) > 7 && 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()
+ }
+}
+
+取值顺序是 query 优先、Header 兜底,Header 分支手动剥掉 Bearer 前缀。解析失败的分流沿用了 P0-1 的约定:密钥未配置是服务端故障,回 500 并打 FATAL,绝不伪装成 401。
整个 /notification 组只挂了这一个中间件,四个端点共用:
| 方法 | 路径 | 作用 | handler |
|---|---|---|---|
| GET | /notification/stream | SSE 长连接 | ssehub.go:109 |
| POST | /notification/list | 最近 50 条,created_at desc | ssehub.go:149 |
| POST | /notification/markRead | 按 id 或全量标记已读 | ssehub.go:171 |
| POST | /notification/unreadCount | 未读数 | ssehub.go:199 |
这是本章最值得记住的一条。项目里正常的鉴权中间件除了验签,还会拿 token 和 Redis 里 account:<id> 的值比对,以支持"改名/改密/登出即踢下线"(见第 7 章):
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
+ }
+而 SSERequireAuth 只调用了 auth.ParseToken,没有这一步。结果是:一个已经被改名/改密/登出作废的 token,签名依然有效、也没过期,于是它仍然能连上 /notification/stream、读 /list、改 /markRead。第 7 章讲的"三处 Redis 键支撑踢人",在通知这条链路上是不生效的。
因为整组共用 SSERequireAuth,/notification/list、/markRead、/unreadCount 这三个普通 POST 接口同样接受 ?token=xxx。这三个接口本来用 jwt.JWTAuth 就够了(前端 fetch 可以带头),把 token 放进 URL 的代价是会进入 nginx/反代的访问日志、以及浏览器的 Referer。同组的 SSERequireAuth 还不设置 username(check 会 c.Set("username", ...),这里只设 accountID),所以将来若有 handler 依赖用户名会直接拿不到。
(本节内容待补充)
+私信是整站唯一的纯同步写路径:没有 MQ、没有缓存、没有降级,请求进来直接 INSERT 然后返回。
+ +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"`
+}
+
+它也是唯一一个把 Repository、Service、Handler 三个类型塞进同一个文件的域。第 5 章讲过六种分层浓度,message 是最淡的那一档:Service 只是包了一层 repo,Handler 越级直接调 h.service.repo.Send(...)。
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
+}
+
+会话查询就是这条双向 OR:把 (A→B) 与 (B→A) 合起来按时间倒序取。limit 由 handler 写死为 50(backend/internal/message/handler.go:86),没有游标、没有 before_id,也就是说第 51 条以前的历史在接口上根本无法翻到。
| 域 | 写路径 | 缓存 | 层数 | 同步/异步 |
|---|---|---|---|---|
| like | MQ 优先,失败直写事务 | 热度先删缓存 | 4 层 | 异步 |
| comment | MQ 优先,失败直写事务 | 热度先删缓存 | 4 层 | 异步 |
| social | DB 优先,再发 MQ 通知 | 失效关注流整页缓存 | 4 层 | 同步 + 事后通知 |
| message | 直接 INSERT | 无 | 1 个文件 3 个类型 | 同步 |
① 不校验收件人是否存在:handler.go:59-62 只判 req.ToID == 0,ToID = 99999999 会照样写入一行指向不存在账号的私信;messages.to_id 上也没有任何 DB 外键兜底。② 可以发给自己:没有 ToID == fromID 的检查(前端在 MessageView.vue:77 用 peerId.value === myId.value 挡了一层,但那只约束了 UI)。③ 没有长度上限:Content 是 type:text,单条最大 64KB,应用层不做限制。is_read 字段虽然在表里,但没有任何接口会更新它。
表上只有 idx_message_from 与 idx_message_to 两个单列索引,而这条查询的过滤条件是两组 (from, to) 组合、排序键是 created_at。MySQL 只能对 OR 的两边各走一次索引再合并,排序必然要 filesort。数据量小的时候无感,但这是第 6 章"索引要覆盖过滤 + 排序"那条原则的一个反例。
(本节内容待补充)
+后端这条链路是完整可用的:队列有人消费、通知会落库、连接能建立、消息能推。但它没有任何客户端。在前端源码里搜索这条链路会用到的一切标识符,结果是零:
+ +| 搜索项 | 范围 | 命中 | 含义 |
|---|---|---|---|
EventSource | frontend/src/** | 0 | 没有任何地方建立 SSE 连接 |
event-stream | frontend/src/** | 0 | 没有对应的解析代码 |
notification / unreadCount / markRead | frontend/src/** | 0 | 四个端点全未被调用 |
api/notification.ts | frontend/src/api/ | 文件不存在 | api 目录只有 account / comment / feed / like / message / social / video 七个域 |
于是形成一个很典型的"后端做完了、产品上没有人看得见"的状态:点赞之后作者那一侧永远不会有任何提示——没有红点、没有未读数、没有 toast,也不会出现在任何页面里,因为通知列表接口同样没被调用。要观察到这条链路真的在工作,只能手工打接口:
+# 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=<作者的 token>"
+# 预期先看到保活注释帧 : 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=<token>"
+curl -s -X POST "http://127.0.0.1:8080/notification/list?token=<token>"
+把这条链路接进前端,需要的全部信息都已经在上面了:连接地址(/notification/stream?token=)、帧格式(data: <Notification>\n\n,注释帧可忽略)、落库对象的字段名,以及三个补充接口。真正需要设计决策的只有两件事:token 放在 query 里会进日志(14.4),以及这个 hub 只在单个 API 实例内有效(14.3)。换句话说,前端接入是小事,部署形态才是真问题。
第 14.5 节的私信同样没有推送,也没有轮询:MessageView.vue 只在进入会话时拉一次、发送成功后把新消息前插。换句话说我发出去的消息对面必须手动刷新页面才能看到。两条实时需求(通知、私信)目前都停在"后端有基础设施、前端没有消费"的同一种状态上。