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 @@

14通知、SSE 与私信:实时推送链路

- 这一章解决什么:(待补充) + 这一章解决什么:点赞、评论、关注各自产生一条通知,这条通知怎么落库、怎么在用户还开着页面的那一刻推过去;私信为什么压根没走消息队列;以及为什么后端这条实时链路已经能跑通,前端页面上却一条通知都看不见。

14.1 通知的三种来源与落库

-

(本节内容待补充)

+

通知不是 API 进程写出来的,而是业务事件在 MQ 上被复制了一份。三条正路都遵循同一形状:业务 worker 往 like.events / comment.events / social.events 发一条事件,topic 交换机把它投给所有匹配的绑定,于是同一份消息同时进入业务队列和通知队列:

+ +
+ + + + + + + +
事件 routing key业务队列(绑定键)通知队列(绑定键)消费者进程
like.likelike.events(like.*)notification.like(like.like)API
comment.publishcomment.events(comment.*)notification.comment(comment.publish)API
social.followsocial.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",不是错误。

+ +
+第四种通知绕过了 MQ +

mention 类型不在上面那张队列表里。它由评论服务在写评论成功后直接 INSERT,一行 Table("notifications").Create(&notif)(backend/internal/video/comment_service.go:154)。后果有两个:它拿不到 SSE 推送(因为 Push 是 worker 落库后显式调用的,见 14.3),也不受通知队列的重试与后续 DLX 改造保护,失败只留一行日志。这是全项目唯一一处绕过 MQ 直接写通知表的地方。

+
+ +
+通知是纯派生数据 +

通知表可以完全由 likes / comments / socials 重算出来,但项目里没有任何对账或重建任务(ISSUES-REPORT 的 A-3)。因此 14.2 里那种"静默丢弃"一旦发生,除了用户自己发现少了通知,没有第二条发现路径。

+

14.2 用 routing key 充当事件类型的取舍

-

(本节内容待补充)

+

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 看那三行绑定即可。

+

14.3 SSEHub:进程内广播与 30 秒保活

-

(本节内容待补充)

+

落库之后要把通知推给还开着页面的用户,用的是 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 才是事实源,这一点值得在面试里主动讲明。

+
+ +
+进程内 map 天然只支持单实例 +

clients 是 API 进程的堆内存。三个通知消费者也在这个进程里(14.1),所以"谁消费到消息、谁就推得出去"当前是成立的。但这个成立条件是部署形态而不是代码保证:一旦 API 水平扩到两个实例,消费者在多实例间竞争队列消息,用户连的却是其中一个实例——落在另一个实例上的通知就永远推不到这个连接上。ISSUES-REPORT 把它记作 A-5,并指出整个项目其实隐含"单 API 实例"这一约束。

+

另外,事件里没有 id 字段,前端也就无从发 Last-Event-ID:断线期间的通知不会补推,重连后只能靠 /notification/list 重新拉一遍。

+
+ +
+同一个 hub 对象被两处引用 +

backend/internal/http/router.go:231 创建 sseHub 之后,:247 把它注入了三个 NotificationWorker(NewNotificationWorker(ch, db, queue, sseHub)),:234 又用它注册路由。所以"落库"和"推送"是同一份内存状态的两个入口——这也是为什么 mention 通知绕开 MQ 就同时绕开了推送。

+

14.4 SSE 鉴权:query token 与 Bearer

-

(本节内容待补充)

+

浏览器的 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/streamSSE 长连接ssehub.go:109
POST/notification/list最近 50 条,created_at descssehub.go:149
POST/notification/markRead按 id 或全量标记已读ssehub.go:171
POST/notification/unreadCount未读数ssehub.go:199
+
+ +
+SSE 这条鉴权路径没有做会话吊销检查 +

这是本章最值得记住的一条。项目里正常的鉴权中间件除了验签,还会拿 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 键支撑踢人",在通知这条链路上是不生效的。

+
+ +
+POST 端点也接受了 query 里的 token +

因为整组共用 SSERequireAuth,/notification/list、/markRead、/unreadCount 这三个普通 POST 接口同样接受 ?token=xxx。这三个接口本来用 jwt.JWTAuth 就够了(前端 fetch 可以带头),把 token 放进 URL 的代价是会进入 nginx/反代的访问日志、以及浏览器的 Referer。同组的 SSERequireAuth 还不设置 username(check 会 c.Set("username", ...),这里只设 accountID),所以将来若有 handler 依赖用户名会直接拿不到。

+

14.5 私信:同步写库与会话查询

-

(本节内容待补充)

+

私信是整站唯一的纯同步写路径:没有 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 条以前的历史在接口上根本无法翻到。

+ +
+ + + + + + + + +
域写路径缓存层数同步/异步
likeMQ 优先,失败直写事务热度先删缓存4 层异步
commentMQ 优先,失败直写事务热度先删缓存4 层异步
socialDB 优先,再发 MQ 通知失效关注流整页缓存4 层同步 + 事后通知
message直接 INSERT无1 个文件 3 个类型同步
+
+ +
+Send 的三个校验缺口(ISSUES-REPORT P3-31) +

① 不校验收件人是否存在: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 字段虽然在表里,但没有任何接口会更新它。

+
+ +
+双向 OR 与索引 +

表上只有 idx_message_from 与 idx_message_to 两个单列索引,而这条查询的过滤条件是两组 (from, to) 组合、排序键是 created_at。MySQL 只能对 OR 的两边各走一次索引再合并,排序必然要 filesort。数据量小的时候无感,但这是第 6 章"索引要覆盖过滤 + 排序"那条原则的一个反例。

+

14.6 前端的缺口:通知为什么看不见

-

(本节内容待补充)

+

后端这条链路是完整可用的:队列有人消费、通知会落库、连接能建立、消息能推。但它没有任何客户端。在前端源码里搜索这条链路会用到的一切标识符,结果是零:

+ +
+ + + + + + + + +
搜索项范围命中含义
EventSourcefrontend/src/**0没有任何地方建立 SSE 连接
event-streamfrontend/src/**0没有对应的解析代码
notification / unreadCount / markReadfrontend/src/**0四个端点全未被调用
api/notification.tsfrontend/src/api/文件不存在api 目录只有 account / comment / feed / like / message / social / video 七个域
+
+ +
+端到端断在最后一步(ISSUES-REPORT P1-9 / F-1) +

于是形成一个很典型的"后端做完了、产品上没有人看得见"的状态:点赞之后作者那一侧永远不会有任何提示——没有红点、没有未读数、没有 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 只在进入会话时拉一次、发送成功后把新消息前插。换句话说我发出去的消息对面必须手动刷新页面才能看到。两条实时需求(通知、私信)目前都停在"后端有基础设施、前端没有消费"的同一种状态上。

+