Compare commits
93 Commits
8a18fdb924
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| af77a979ff | |||
| 52213c1d83 | |||
| f658b7e76e | |||
| c73c8861db | |||
| 73b1989bbf | |||
| 7454bf457e | |||
| 7d9cb061a2 | |||
| 5d05c147ed | |||
| 06e001a151 | |||
| fe3ad4a558 | |||
| 6e302be567 | |||
| 81259e5aff | |||
| 239a98e1fa | |||
| ffd33f981c | |||
| 814b94a0f1 | |||
| 97a6258ccc | |||
| 101f46f927 | |||
| b2d2e3d473 | |||
| 9bf3ffc9d8 | |||
| b3d381b0a0 | |||
| fc93ccfcf5 | |||
| 111fea0f0c | |||
| 327c46eb3b | |||
| 41b212dd65 | |||
| d782ccbb53 | |||
| 006ec5f196 | |||
| c5e2f0e30b | |||
| d542968ed4 | |||
| 9d9fdb91e5 | |||
| eda8237c36 | |||
| a0bd798d8a | |||
| 0fcbf3ae00 | |||
| bc1252e66c | |||
| 91c13ee022 | |||
| 5137639a00 | |||
| e2c2ec5454 | |||
| 85995f9f73 | |||
| 1b47c9f027 | |||
| c0210b61ba | |||
| 5384d55ca3 | |||
| 815760f5fb | |||
| 8122aeca9c | |||
| c210e75996 | |||
| c0ab69118a | |||
| 6e9146b216 | |||
| 151faf25fa | |||
| 07f3166ab7 | |||
| b0d52f7687 | |||
| 1191e15d64 | |||
| c0578988e1 | |||
| c2a8e45b50 | |||
| 49fc17c445 | |||
| 03d4301020 | |||
| e9f2e84b30 | |||
| a512bf6c61 | |||
| 953b609970 | |||
| 90a7feb6d3 | |||
| d734cc9e43 | |||
| a9c0340733 | |||
| 0df9f2dc51 | |||
| 14c75c6af6 | |||
| 5ae04934ae | |||
| cf6c3ba798 | |||
| 7fc3436892 | |||
| e0a21fab78 | |||
| 4e412a2c84 | |||
| 5f250fa7cd | |||
| a224651e4c | |||
| 6d5a7e529d | |||
| 277bca07ce | |||
| b2e56df42b | |||
| f08e0060d2 | |||
| 6ff2983f4b | |||
| 5f30f264f7 | |||
| 9b8a116852 | |||
| ff8b058409 | |||
| 243ae3fcfb | |||
| 8204f4659d | |||
| 405d31db96 | |||
| 21d5fee922 | |||
| 99d629bbfd | |||
| fcf93f09c9 | |||
| 3ab0851656 | |||
| 0b1f26f16a | |||
| ea134d6d71 | |||
| 4b7f707860 | |||
| 90b9e7e0ac | |||
| c94c9babdd | |||
| 2928269329 | |||
| ec9c53a80c | |||
| 65ca5c5218 | |||
| 87f6e91ed1 | |||
| e3ee3eee2f |
11
.env.example
11
.env.example
@@ -1,6 +1,4 @@
|
||||
# feedsystem_video_go 环境变量模板
|
||||
# 复制此文件为 .env 后修改实际值
|
||||
# .env 已被 .gitignore 忽略,不会提交到仓库
|
||||
|
||||
# MySQL
|
||||
MYSQL_ROOT_PASSWORD=123456
|
||||
@@ -14,10 +12,11 @@ RABBITMQ_USER=admin
|
||||
RABBITMQ_PASS=password123
|
||||
|
||||
# JWT
|
||||
# 必填,且长度至少 32 字节;不足 32 字节时进程会拒绝启动。
|
||||
# 生产环境请生成随机密钥:openssl rand -hex 32
|
||||
# 下面的值是公开的开发用默认值,切勿用于生产。
|
||||
# 必填, 长度至少 32 字节
|
||||
JWT_SECRET=feedsystem-dev-secret-key-do-not-use-in-prod
|
||||
|
||||
# 访问令牌有效期,支持 15m / 1h / 30s 写法(缺省 15m)
|
||||
# 访问令牌有效期,支持 15m / 1h / 30s 写法
|
||||
# JWT_ACCESS_TOKEN_TTL=15m
|
||||
|
||||
# 生产部署: docker-compose.prod.yml 映射到宿主机的对外端口
|
||||
# APP_PORT=9000
|
||||
|
||||
@@ -6,48 +6,160 @@ on:
|
||||
- main
|
||||
- master
|
||||
|
||||
# 同一分支的部署串行执行. 不要打开 cancel-in-progress:
|
||||
# 部署中断会把 compose 项目留在"部分容器已重建"的中间状态.
|
||||
concurrency:
|
||||
group: deploy-${{ gitea.ref }}
|
||||
cancel-in-progress: true
|
||||
cancel-in-progress: false
|
||||
|
||||
env:
|
||||
DEPLOY_DIR: /opt/vloop
|
||||
GO_IMAGE: golang:1.24.5
|
||||
NODE_IMAGE: node:24-alpine
|
||||
# Docker Hub 镜像加速前缀. 留空则直接拉 Docker Hub.
|
||||
# 拉取时先试 <IMAGE_MIRROR>/library/<image>, 成功后 retag 成原始名字,
|
||||
# 这样 Dockerfile 里的 FROM 和 docker run 都不用改.
|
||||
IMAGE_MIRROR: docker.m.daocloud.io
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
name: Deploy
|
||||
name: Verify and Deploy
|
||||
# host 模式 runner: 任务直接跑在 ECS 宿主机上,
|
||||
# 因此下面的 docker / rsync / /opt/vloop 都操作宿主机本身.
|
||||
runs-on: aliyun
|
||||
timeout-minutes: 45
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
# -- Backend: vet + test --
|
||||
- name: Install Go
|
||||
# -- 预拉取所有基础镜像 --
|
||||
# 国内直连 Docker Hub 很慢. 这里先按镜像源拉取, 再 retag 成本地原始名字,
|
||||
# 后续 docker run 和 compose build 直接命中本地镜像, 不再访问 Docker Hub.
|
||||
# 已经存在的镜像会跳过, 所以只有首次或镜像变更时才会真正下载.
|
||||
- name: Ensure base images
|
||||
run: |
|
||||
sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories
|
||||
apk add --no-cache go
|
||||
set -eu
|
||||
mirror="${IMAGE_MIRROR%/}"
|
||||
# docker/dockerfile 是 BuildKit 前端语法镜像, 不属于 library 命名空间.
|
||||
images="library/$GO_IMAGE library/$NODE_IMAGE library/alpine:3.21 library/nginx:1.27-alpine library/mysql:8.0 library/redis:7-alpine library/rabbitmq:3-management docker/dockerfile:1.7"
|
||||
|
||||
- name: Vet
|
||||
working-directory: backend
|
||||
run: go vet ./...
|
||||
pull_image() {
|
||||
ref="$1"
|
||||
image="${ref#library/}" # 只去掉 library/ 前缀, 保留 docker/ 命名空间
|
||||
if docker image inspect "$image" >/dev/null 2>&1; then
|
||||
echo "已存在, 跳过: $image"
|
||||
return 0
|
||||
fi
|
||||
if [ -n "$mirror" ] && docker pull "$mirror/$ref"; then
|
||||
docker tag "$mirror/$ref" "$image"
|
||||
echo "已从镜像源拉取: $image"
|
||||
return 0
|
||||
fi
|
||||
echo "镜像源不可用, 回退 Docker Hub: $image"
|
||||
docker pull "$image"
|
||||
}
|
||||
|
||||
- name: Test
|
||||
working-directory: backend
|
||||
run: go test -race -count=1 ./...
|
||||
for ref in $images; do
|
||||
pull_image "$ref"
|
||||
done
|
||||
|
||||
# -- Frontend: install + build --
|
||||
- name: Install Node
|
||||
run: apk add --no-cache nodejs npm
|
||||
|
||||
- name: Build Frontend
|
||||
working-directory: frontend
|
||||
# -- 后端: vet + test --
|
||||
# 用官方 Go 镜像而不是 apk add go:
|
||||
# 宿主机不是 Alpine, 没有 apk; 镜像里的 Go 版本与 go.mod 的 1.24.5 精确匹配, 且自带 gcc(-race 需要 cgo).
|
||||
- name: Backend vet and test
|
||||
run: |
|
||||
npm ci
|
||||
npm run build
|
||||
docker run --rm \
|
||||
-v "$PWD/backend:/src:ro" \
|
||||
-v vloop_ci_go_mod:/go/pkg/mod \
|
||||
-v vloop_ci_go_build:/root/.cache/go-build \
|
||||
-w /src \
|
||||
-e GOPROXY=https://goproxy.cn,direct \
|
||||
-e GOSUMDB=sum.golang.google.cn \
|
||||
"$GO_IMAGE" sh -c 'go vet ./... && go test -race -count=1 ./...'
|
||||
|
||||
# -- Deploy --
|
||||
- name: Deploy
|
||||
# -- 前端: install + build --
|
||||
# 复制到容器内 /tmp 再构建, 避免在宿主机工作区留下 root 属主的 node_modules/dist.
|
||||
- name: Frontend build
|
||||
run: |
|
||||
cp docker-compose.prod.yml /opt/vloop/
|
||||
cp -r backend /opt/vloop/
|
||||
cp -r frontend /opt/vloop/
|
||||
cd /opt/vloop
|
||||
docker compose -f docker-compose.prod.yml up -d --build --remove-orphans
|
||||
docker image prune -f
|
||||
docker run --rm \
|
||||
-v "$PWD/frontend:/src:ro" \
|
||||
-v vloop_ci_npm:/root/.npm \
|
||||
-e NPM_CONFIG_REGISTRY=https://registry.npmmirror.com \
|
||||
"$NODE_IMAGE" sh -c '
|
||||
set -e
|
||||
mkdir -p /tmp/app
|
||||
cp -a /src/. /tmp/app
|
||||
cd /tmp/app
|
||||
npm ci
|
||||
npm run build
|
||||
'
|
||||
|
||||
# -- 部署前检查 --
|
||||
- name: Check deploy env
|
||||
run: |
|
||||
test -f "$DEPLOY_DIR/.env" || {
|
||||
echo "ERROR: $DEPLOY_DIR/.env 不存在. 至少需要 MYSQL_ROOT_PASSWORD、MYSQL_DATABASE、REDIS_PASSWORD、RABBITMQ_USER、RABBITMQ_PASS、JWT_SECRET. "
|
||||
exit 1
|
||||
}
|
||||
grep -Eq '^JWT_SECRET=.*[^[:space:]]' "$DEPLOY_DIR/.env" || {
|
||||
echo "ERROR: $DEPLOY_DIR/.env 中缺少 JWT_SECRET. "
|
||||
exit 1
|
||||
}
|
||||
secret="$(sed -n 's/^JWT_SECRET=//p' "$DEPLOY_DIR/.env" | head -n1 | tr -d '\r')"
|
||||
if [ "${#secret}" -lt 32 ]; then
|
||||
echo "ERROR: JWT_SECRET 少于 32 字节, 后端会拒绝启动. 用 openssl rand -hex 32 生成. "
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# -- 同步源码 --
|
||||
# --delete 保证被删除/改名的文件不会残留在 /opt/vloop 里;
|
||||
# 排除 .env, 避免把服务器上的密钥删掉.
|
||||
- name: Sync source to deploy directory
|
||||
run: |
|
||||
command -v rsync >/dev/null 2>&1 || {
|
||||
echo "ERROR: 宿主机缺少 rsync, 请先安装(dnf install -y rsync / apt-get install -y rsync). "
|
||||
exit 1
|
||||
}
|
||||
: "${DEPLOY_DIR:?DEPLOY_DIR must be set}"
|
||||
mkdir -p "$DEPLOY_DIR"
|
||||
# 旧版 cp -r 可能留下 node_modules/dist, 先清掉, 避免撑大 Docker 构建上下文.
|
||||
rm -rf "$DEPLOY_DIR/frontend/node_modules" "$DEPLOY_DIR/frontend/dist" \
|
||||
"$DEPLOY_DIR/backend/.run" "$DEPLOY_DIR/.git"
|
||||
rsync -a --delete \
|
||||
--exclude=.git \
|
||||
--exclude=node_modules \
|
||||
--exclude=dist \
|
||||
--exclude=.run \
|
||||
--exclude=.env \
|
||||
./ "$DEPLOY_DIR"/
|
||||
|
||||
# -- 构建镜像 --
|
||||
# 单独一步 + --progress=plain: 卡在哪一层、每层花多久一眼能看出来.
|
||||
# 30 分钟仍没构建完说明线路有问题(元数据/模块下载), 直接失败并保留日志.
|
||||
- name: Build images
|
||||
run: |
|
||||
cd "$DEPLOY_DIR"
|
||||
docker compose -f docker-compose.prod.yml config -q
|
||||
timeout 1800 docker compose -f docker-compose.prod.yml build --progress=plain || {
|
||||
code=$?
|
||||
echo "::error::镜像构建失败或超时(exit $code), 见上方分层日志"
|
||||
exit "$code"
|
||||
}
|
||||
|
||||
# -- 启动容器 --
|
||||
- name: Restart services
|
||||
run: |
|
||||
cd "$DEPLOY_DIR"
|
||||
# --wait-timeout: 容器起不来(健康检查不过)时 10 分钟内失败并打印日志,
|
||||
# 而不是一直挂到 job 超时.
|
||||
if ! docker compose -f docker-compose.prod.yml up -d --wait --wait-timeout 600 --remove-orphans; then
|
||||
echo "---- compose ps ----"
|
||||
docker compose -f docker-compose.prod.yml ps || true
|
||||
echo "---- recent logs ----"
|
||||
docker compose -f docker-compose.prod.yml logs --tail=150 || true
|
||||
exit 1
|
||||
fi
|
||||
docker compose -f docker-compose.prod.yml ps
|
||||
# 只清理 7 天前的悬空镜像, 保留最近构建, 便于回滚.
|
||||
docker image prune -f --filter "until=168h"
|
||||
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -2,7 +2,6 @@
|
||||
backend/.run/
|
||||
data/
|
||||
.sisyphus/
|
||||
CLAUDE.md
|
||||
|
||||
#
|
||||
# Binaries for programs and plugins
|
||||
|
||||
95
AGENTS.md
Normal file
95
AGENTS.md
Normal file
@@ -0,0 +1,95 @@
|
||||
# AGENTS.md
|
||||
|
||||
本文件只写约束。项目是什么见 `README.md`,设计与决策见 `docs/design/`、`docs/solutions/`。
|
||||
|
||||
## 红线
|
||||
|
||||
- 新增消费者必须实现幂等的 `process`,失败处置只走 `rabbitmq.ConsumeLoop`(Ack / 重投 / 停泊)。不要自己写重试循环,也不要新增 `ch.Consume` 调用点。
|
||||
- `JWT_SECRET` 等密钥只从环境变量或 `.env` 读取,不得写入提交的 YAML。
|
||||
|
||||
## 命令
|
||||
|
||||
### 后端(在 `backend/` 下)
|
||||
|
||||
```bash
|
||||
go test -race -count=1 ./... # 推送前必跑
|
||||
go test -run TestName ./internal/package/...
|
||||
go vet ./...
|
||||
go run ./cmd # API
|
||||
go run ./cmd/worker # Worker
|
||||
```
|
||||
|
||||
### 前端(在 `frontend/` 下)
|
||||
|
||||
```bash
|
||||
npm ci
|
||||
npm run dev # localhost:5173,/api 代理到 127.0.0.1:8080
|
||||
npm run build # 前端唯一的验证手段
|
||||
```
|
||||
|
||||
### 起服务
|
||||
|
||||
```bash
|
||||
docker compose up -d mysql redis rabbitmq
|
||||
CONFIG_PATH=configs/config.compose-local.yaml go run ./cmd
|
||||
START_BACKEND=1 START_WORKER=1 START_FRONTEND=1 ./start.sh
|
||||
```
|
||||
|
||||
## TDD
|
||||
|
||||
`backend/` 下改行为默认 TDD。前端没有测试运行器,只跑 `npm run build` 再人工点页面,不要称其为 TDD。
|
||||
|
||||
1. **红**——写最小测试,跑,看它失败。确认失败原因是预期的那一个(值不对、没调用、状态码错),不是拼写或 fixture 坏了。
|
||||
2. **绿**——写最小实现,不加「顺手」的抽象和选项。
|
||||
3. **重构**——在绿的前提下清实现和测试名,每步重跑。
|
||||
|
||||
测试与实现同一次提交。改 bug 先写复现测试,把失败断言写进提交信息或 PR 说明。
|
||||
|
||||
## 测试
|
||||
|
||||
- 测试与被测代码同包同目录(`package http`、`package rabbitmq`),一个 `*_test.go` 放在旁边。只有要用公开 API 时才用 `_test` 包。
|
||||
- 命名 `TestSubject_ExpectedBehavior`。一个行为多种输入用表驱动 + `t.Run` + `name string` 字段。
|
||||
- 辅助函数标 `t.Helper()`;共享 fixture 只放 `_test.go`,不进生产包。
|
||||
- 保留意图注释:一句话说明这个不变量为什么存在,不复述 bug。测试注释用中文。
|
||||
- 没有 mock 框架。RabbitMQ 用窄接口手写 fake(如 `fakeConn`),Redis 用 `miniredis`,handler 用 `httptest` + `gin.CreateTestContext`,MySQL 没有 mock——抽窄接口做单测,或对着真库写并注明要先起 infra。
|
||||
- 断言可观察行为(状态码、响应体、落库行、发出的消息),不断言内部调用次数。
|
||||
- 集成测试放 `//go:build integration` 文件,端点走环境变量。缺前置条件就 `t.Skip` 并写原因,静默通过与跳过不等价。
|
||||
- 多个 MySQL fixture 包同时跑要加 `-p 1`,否则互相 `DropTable`。
|
||||
- 单测不碰真实网络,不拿 `time.Sleep` 当同步。测试要过 `-race`,且与执行顺序无关。
|
||||
- 不要为了让套件变快而改小文档化的时间守卫——`TestReadyz_MQEnabledButDisconnected_IsDistinguishable` 那 5 秒就是断言本身。
|
||||
- 覆盖率当评审输入,不当门禁。
|
||||
- 既有测试是契约:不为过审削弱、跳过或删除断言。不变量真变了,就在同一提交里改测试并说明原因。
|
||||
- 新测试需要摸私有字段、睡几秒或起容器,通常是边界画错了——注入依赖,别加脚手架。
|
||||
|
||||
## 文档
|
||||
|
||||
- 设计文档在 `docs/design/`,中文,写代码做什么、为什么。文档不是代码的规格:两者冲突时先改文档,除非代码确实坏了。
|
||||
- 永远不要用行号定位代码。写路径 + 标识符(函数、类型、常量、配置键、测试名、日志原文),不写 `service.go:496`;行号每次改动都会漂移,标识符不会。
|
||||
- 一个概念一个术语。同一篇文档不换同义词,术语在首次出现处定义。
|
||||
- 不写没验证过的内容。未验证的标 `TBD`,并写清怎么确认(问谁、跑哪条命令)。猜测不是事实。
|
||||
- 清单类内容取自源码,再校对:API 列表、配置键、错误码表来自 `go doc`、`router.go` 的路由注册、YAML schema 或常量;手写的部分逐条对照源码。
|
||||
- 不重复 README 的入门内容,给链接。每个事实只写一处。
|
||||
- 文档内引用代码片段时,头部只写文件名,不重复段落已提到的路径。
|
||||
- 行为变了,同一次改动里把对应文档改掉。表格或短片段优于复述代码的散文。
|
||||
|
||||
## 注释
|
||||
|
||||
注释只写代码说不出来的 why:不变量、非显然的取舍、失败模式、刻意省略。
|
||||
|
||||
- 不复述代码,不写变更日志,不写署名。
|
||||
- 一两行就够。需要五行为两行代码辩护,就去重构代码。
|
||||
- 留下承载理由的(`// RENAMENX 把临时键的 1 分钟 TTL 带给了 dest`),删掉复述的(`// 返回响应`)。
|
||||
- 用文件的语言:`backend/` 下用中文。
|
||||
|
||||
## 提交信息
|
||||
|
||||
中文,`type(scope): subject`,按 ASD-STE100 的结构写,约 80% 即可:短句,术语照代码拼写。
|
||||
|
||||
- 一次提交只做一件事。不把无关改动攒进一次提交,不 `git add .` 或 `git commit -a`。拆到单独可回滚、单独可验证的最小单元。
|
||||
- 提交前看 `git status` 与 `git diff --staged`。暂存区里只该有本次要的改动,多出来的拆到下一次。
|
||||
- 一句话一个意思。把 `——`、`;`、`:` 拆成独立句子。目标 ≤ 30 字。
|
||||
- 动词开头,主动语态。`只做声明` → `只声明`。
|
||||
- 一段讲一件事,首句给结论,用 `因此` / `所以` 起结论句。
|
||||
- 标识符原样保留:交换机、队列、路由键、类型名、函数名、测试名。不翻译、不改写、不缩写。
|
||||
- 术语是固定短语:代码注释或测试名里已有的说法就是项目词汇,原样沿用;非术语用平实词,不要造无法 grep 的隐喻。
|
||||
- 有验证命令时,结尾写一行 `验证:…`,如 `验证:go test -race -count=1 ./... 全绿`。
|
||||
3
CLAUDE.md
Normal file
3
CLAUDE.md
Normal file
@@ -0,0 +1,3 @@
|
||||
# CLAUDE.md
|
||||
|
||||
所有 Agent 规范都在 [AGENTS.md](AGENTS.md)。改规范请改 AGENTS.md,不要在本文件重复。
|
||||
70
README.md
70
README.md
@@ -31,6 +31,24 @@ docker compose up -d --build
|
||||
> 本地开发可直接沿用 `.env.example` 中的公开默认值;生产环境必须自行生成:`openssl rand -hex 32`。
|
||||
> 另外 `docker-compose.prod.yml` 把该变量声明为必填,未设置时 `docker compose up` 会在部署阶段直接报错。
|
||||
|
||||
## 进程分工与扩展约束
|
||||
|
||||
| 进程 | 职责 | 能否多副本 |
|
||||
|------|------|-----------|
|
||||
| API(`go run ./cmd`) | HTTP 接口、SSE 连接、事务内写 `outbox` 行、订阅 Redis 推送并转给本实例的 SSE | 可以。唯一残留的进程内状态是 feed 的 L1 缓存(5 秒 TTL),多实例下同一 key 短时间内可能各读到一份旧值 |
|
||||
| Worker(`go run ./cmd/worker`) | 全部 MQ 消费者(social / like / comment / notification ×3 / parked)、Outbox poller、timeline consumer | **暂只支持单副本**:Outbox poller 多副本会重复投递(下游 `ZADD` 幂等,不会产生脏数据,只是浪费投递) |
|
||||
|
||||
API 进程不再启动任何消费者或轮询器。实时通知的链路是:
|
||||
|
||||
```
|
||||
Worker 落库 notifications → Redis Pub/Sub(v1:notification:push)
|
||||
→ 每个 API 实例的订阅器 → 该实例上的 SSE 连接
|
||||
```
|
||||
|
||||
所以 **Redis 是通知实时性的必要条件**:Redis 不可用时通知仍会落库,只是不会即时出现在页面上,刷新后可见。SSE 的权威数据始终是 `notifications` 表,Pub/Sub 只是"在线时尽快看到"。
|
||||
|
||||
前端目前尚未接入 `EventSource`(见 [`docs/ISSUES-REPORT.md`](docs/ISSUES-REPORT.md) 的 P1-9),这条链路只到浏览器之前。
|
||||
|
||||
## 脚本启动
|
||||
|
||||
```bash
|
||||
@@ -41,7 +59,7 @@ docker compose up -d --build
|
||||
|
||||
```bash
|
||||
START_FRONTEND=0 ./start.sh # API + Worker
|
||||
START_WORKER=0 ./start.sh # API + 前端
|
||||
START_WORKER=0 ./start.sh # 只起 API + 前端(通知与 timeline 不再被消费,仅适合调 HTTP 接口)
|
||||
STOP_DOCKER=1 ./start.sh # 退出时停止脚本拉起的 compose 服务
|
||||
CONFIG_PATH=configs/config.yaml ./start.sh
|
||||
```
|
||||
@@ -64,12 +82,49 @@ cd frontend
|
||||
npm install && npm run dev
|
||||
```
|
||||
|
||||
## CI
|
||||
## CI/CD
|
||||
|
||||
GitHub Actions 配置位于 `.github/workflows/ci.yml`,在 Pull Request 以及推送到 `main`、`master` 时运行。
|
||||
Gitea Actions 配置位于 `.gitea/workflows/ci.yml`,推送到 `main`、`master` 时运行,并在同一个 job 内直接部署到生产 ECS:
|
||||
|
||||
- 后端:Go 1.24.x,执行 `go mod download`、`go vet ./...`、`go test -race -count=1 ./...`
|
||||
- 前端:Node.js 22,执行 `npm ci`、`npm run build`
|
||||
- 后端:在 `golang:1.24.5` 容器中执行 `go vet ./...`、`go test -race -count=1 ./...`
|
||||
- 前端:在 `node:24-alpine` 容器中执行 `npm ci`、`npm run build`
|
||||
- 部署:校验 `/opt/vloop/.env` 后,把工作区同步到 `/opt/vloop`,执行 `docker compose -f docker-compose.prod.yml up -d --build --wait`
|
||||
|
||||
`runs-on: aliyun` 是 host 模式 runner,任务直接运行在 ECS 宿主机上(不是容器)。宿主机需要 Git ≥ 2.34.1、**Node.js 22**(`actions/checkout` 等 JavaScript Action 依赖 PATH 中的 `node`)、Docker + Compose v2、`rsync`。
|
||||
|
||||
## 生产部署(阿里云 ECS)
|
||||
|
||||
访问地址:**http://goanchor.top:9000**(`docker-compose.prod.yml` 中 `frontend` 映射 `0.0.0.0:${APP_PORT:-9000} -> 80`)。
|
||||
|
||||
一次性准备:
|
||||
|
||||
```bash
|
||||
sudo mkdir -p /opt/vloop
|
||||
sudo cp .env.example /opt/vloop/.env
|
||||
sudo chmod 600 /opt/vloop/.env
|
||||
# 编辑 /opt/vloop/.env:换成生产密码,JWT_SECRET 用 openssl rand -hex 32 生成
|
||||
```
|
||||
|
||||
`/opt/vloop/.env` 至少包含:
|
||||
|
||||
```dotenv
|
||||
MYSQL_ROOT_PASSWORD=<强密码>
|
||||
MYSQL_DATABASE=feedsystem
|
||||
REDIS_PASSWORD=<强密码>
|
||||
RABBITMQ_USER=admin
|
||||
RABBITMQ_PASS=<强密码>
|
||||
JWT_SECRET=<openssl rand -hex 32 的输出>
|
||||
```
|
||||
|
||||
此外需要:
|
||||
|
||||
1. 阿里云安全组入方向放行 TCP **9000**;宿主机若启用 firewalld/ufw 同样放行。
|
||||
2. DNS 把 `goanchor.top` 的 A 记录指向 ECS 公网 IP。
|
||||
3. 宿主机安装 Docker Engine + Compose v2,并确保部署用户可访问 Docker daemon。
|
||||
|
||||
> 当前入口是明文 HTTP。若之后在 443 加 Caddy/Nginx 反向代理,把 compose 端口改成 `127.0.0.1:${APP_PORT:-9000}:80`,代理到该端口即可。
|
||||
>
|
||||
> 媒体 URL 是按请求的 `Host` 生成的绝对地址(见 `backend/internal/video/video_handler.go`、`backend/internal/account/handler.go`)。确定最终访问地址(是否上 HTTPS)后再上传生产媒体,否则历史记录里的 URL 会指向旧地址。
|
||||
|
||||
## 接口清单
|
||||
|
||||
@@ -169,8 +224,9 @@ GitHub Actions 配置位于 `.github/workflows/ci.yml`,在 Pull Request 以及
|
||||
|
||||
## 运维与可观测性
|
||||
|
||||
- `GET /healthz` 返回后端健康状态。
|
||||
- `GET /healthz` 返回后端存活状态,恒为 200。
|
||||
- `GET /readyz` 返回依赖就绪状态:RabbitMQ 断连时返回 503,并给出 `mq_enabled` / `mq_connected` / `mq_generation` / `mq_reconnects` / `mq_topology`。它**刻意与 `/healthz` 分开**——broker 故障期间 API 仍然可用(写路径降级为直写 DB),把 MQ 状态并入 `/healthz` 会让编排在故障期间反复重启健康实例。
|
||||
- 本地配置默认开启 pprof:API `localhost:6060`,Worker `localhost:6061`。
|
||||
- 上传文件写入 `backend/.run/uploads`;Docker 环境挂载到 `backend_uploads` volume。
|
||||
- Redis 用于 Token 缓存、视频实体缓存、Feed 时间线、热榜窗口、分片上传会话。
|
||||
- RabbitMQ Topic Exchange 覆盖点赞、评论、关注、热度、视频时间线事件,并配置 DLX。
|
||||
- RabbitMQ Topic Exchange 覆盖点赞、评论、关注、热度、视频时间线事件,并配置 DLX。连接由 `middleware/rabbitmq` 的连接管理器统一持有:**断连自动重连**(`NotifyClose` 事件驱动 + 指数退避与抖动)、**每一代新连接自动重放全部拓扑**,因此 broker 重启或队列丢失后消费者会自行恢复,无需人工重启进程。
|
||||
|
||||
@@ -40,7 +40,10 @@ RUN --mount=type=cache,target=/go/pkg/mod \
|
||||
go build -trimpath -ldflags="-s -w" -o /out/worker ./cmd/worker
|
||||
|
||||
FROM alpine:3.21 AS base
|
||||
RUN apk add --no-cache ca-certificates tzdata && adduser -D -H -s /sbin/nologin app
|
||||
# 国内构建走阿里云 apk 镜像
|
||||
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories \
|
||||
&& apk add --no-cache ca-certificates tzdata \
|
||||
&& adduser -D -H -s /sbin/nologin app
|
||||
WORKDIR /app
|
||||
COPY --from=source /src/backend/configs ./configs
|
||||
RUN mkdir -p ./.run/uploads && chown -R app:app /app
|
||||
|
||||
@@ -2,6 +2,7 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"feedsystem_video_go/internal/auth"
|
||||
"feedsystem_video_go/internal/config"
|
||||
"feedsystem_video_go/internal/db"
|
||||
@@ -10,8 +11,11 @@ import (
|
||||
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||||
"feedsystem_video_go/internal/observability"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strconv"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/joho/godotenv"
|
||||
@@ -100,10 +104,46 @@ func main() {
|
||||
defer pprofServer.Close()
|
||||
}
|
||||
|
||||
// 进程生命周期:SIGINT/SIGTERM 后先停止接收新请求,再等在途请求结束。
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
|
||||
// 设置路由
|
||||
r := apphttp.SetRouter(sqlDB, cache, rmq)
|
||||
log.Printf("Server is running on port %d", cfg.Server.Port)
|
||||
if err := r.Run(":" + strconv.Itoa(cfg.Server.Port)); err != nil {
|
||||
log.Fatalf("Failed to run server: %v", err)
|
||||
r := apphttp.SetRouter(ctx, sqlDB, cache, rmq)
|
||||
srv := &http.Server{
|
||||
Addr: ":" + strconv.Itoa(cfg.Server.Port),
|
||||
Handler: r,
|
||||
ReadHeaderTimeout: 10 * time.Second,
|
||||
}
|
||||
|
||||
// ListenAndServe 在 goroutine 里跑,主协程负责等待信号或启动失败。
|
||||
serverErr := make(chan error, 1)
|
||||
go func() {
|
||||
log.Printf("Server is running on port %d", cfg.Server.Port)
|
||||
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
serverErr <- err
|
||||
}
|
||||
}()
|
||||
|
||||
select {
|
||||
case err := <-serverErr:
|
||||
log.Printf("Failed to run server: %v", err)
|
||||
stop()
|
||||
_ = srv.Close()
|
||||
return
|
||||
case <-ctx.Done():
|
||||
}
|
||||
|
||||
// 恢复默认信号处理:第二次 Ctrl-C 立刻强杀,而不是卡在 Shutdown 里。
|
||||
stop()
|
||||
|
||||
log.Printf("API shutting down...")
|
||||
// SSE 连接已随 ctx 断开,这里等的是普通在途请求;超时则 Close 兜底。
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
if err := srv.Shutdown(shutdownCtx); err != nil {
|
||||
log.Printf("API graceful shutdown failed (forcing close): %v", err)
|
||||
_ = srv.Close()
|
||||
}
|
||||
log.Printf("API stopped")
|
||||
}
|
||||
|
||||
162
backend/cmd/reconcile/main.go
Normal file
162
backend/cmd/reconcile/main.go
Normal file
@@ -0,0 +1,162 @@
|
||||
// Command reconcile 是热度派生数据的运维入口:重算计数器、核对热榜、重建分钟桶。
|
||||
//
|
||||
// 三个动作的风险不同:counters 可重入,verify 只读,rebuild 与并发增量有竞态。
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"feedsystem_video_go/internal/config"
|
||||
"feedsystem_video_go/internal/db"
|
||||
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||||
"feedsystem_video_go/internal/video"
|
||||
|
||||
"github.com/joho/godotenv"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func main() {
|
||||
counters := flag.Bool("counters", false, "重算 videos.likes_count / videos.popularity(写操作)")
|
||||
verify := flag.Bool("verify", false, "逐桶核对热榜窗口与 DB 计数")
|
||||
rebuild := flag.Bool("rebuild-hot", false, "用 DB 重写热榜分钟桶(会与并发增量竞态)")
|
||||
from := flag.String("from", "", "窗口起点 RFC3339(默认 now-60m)")
|
||||
to := flag.String("to", "", "窗口终点 RFC3339,开区间(默认本分钟起点,即含上一个闭合分钟)")
|
||||
limit := flag.Int("limit", 200, "counters 每轮修正的视频数")
|
||||
flag.Parse()
|
||||
|
||||
if !*counters && !*verify && !*rebuild {
|
||||
flag.Usage()
|
||||
os.Exit(2)
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
gormDB := mustDB(ctx)
|
||||
// Redis 只在核对与重建时需要:counters 是纯 DB 操作。
|
||||
var cache *rediscache.Client
|
||||
if *verify || *rebuild {
|
||||
cache = mustCache(ctx)
|
||||
}
|
||||
|
||||
fromT, toT := resolveWindow(*from, *to, time.Now())
|
||||
failed := false
|
||||
|
||||
if *counters {
|
||||
checked, fixed, err := video.NewCounterReconciler(gormDB).Reconcile(ctx, *limit)
|
||||
res := countersResult{checked: checked, fixed: fixed, err: err}
|
||||
log.Printf("reconcile: %s", res)
|
||||
if res.failed() {
|
||||
failed = true
|
||||
}
|
||||
}
|
||||
|
||||
if *verify || *rebuild {
|
||||
admin := video.NewHotWindowAdmin(gormDB, cache)
|
||||
if *verify {
|
||||
buckets, drift, err := admin.Verify(ctx, fromT, toT)
|
||||
log.Printf("verify: buckets=%d drift=%d err=%v", buckets, drift, err)
|
||||
if err != nil || drift > 0 {
|
||||
failed = true
|
||||
}
|
||||
}
|
||||
if *rebuild {
|
||||
buckets, members, err := admin.Rebuild(ctx, fromT, toT)
|
||||
log.Printf("rebuild: buckets=%d members=%d err=%v", buckets, members, err)
|
||||
if err != nil {
|
||||
failed = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if failed {
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
// countersResult 是一次 -counters 巡检的结果。
|
||||
type countersResult struct {
|
||||
checked int
|
||||
fixed int
|
||||
err error
|
||||
}
|
||||
|
||||
// failed 只反映"巡检做没做成":修好漂移说明它起作用了,不是失败。
|
||||
// 需要"有没有漂移"这个只读信号时用 -verify。
|
||||
func (r countersResult) failed() bool { return r.err != nil }
|
||||
|
||||
func (r countersResult) String() string {
|
||||
return fmt.Sprintf("checked=%d fixed=%d err=%v", r.checked, r.fixed, r.err)
|
||||
}
|
||||
|
||||
// resolveWindow 解析 [from, to);空串取最近 60 分钟,右端是本分钟起点。
|
||||
func resolveWindow(from, to string, now time.Time) (fromT, toT time.Time) {
|
||||
now = now.UTC()
|
||||
fromT = now.Truncate(time.Minute).Add(-time.Duration(video.HotWindowMinutes) * time.Minute)
|
||||
toT = now.Truncate(time.Minute)
|
||||
|
||||
if from != "" {
|
||||
if t, err := time.Parse(time.RFC3339, from); err == nil {
|
||||
fromT = t.UTC()
|
||||
} else {
|
||||
log.Fatalf("invalid -from %q: %v", from, err)
|
||||
}
|
||||
}
|
||||
if to != "" {
|
||||
if t, err := time.Parse(time.RFC3339, to); err == nil {
|
||||
toT = t.UTC()
|
||||
} else {
|
||||
log.Fatalf("invalid -to %q: %v", to, err)
|
||||
}
|
||||
}
|
||||
if !toT.After(fromT) {
|
||||
log.Fatalf("empty window: from=%s to=%s", fromT.Format(time.RFC3339), toT.Format(time.RFC3339))
|
||||
}
|
||||
return fromT, toT
|
||||
}
|
||||
|
||||
func mustDB(ctx context.Context) *gorm.DB {
|
||||
if err := godotenv.Load(); err != nil {
|
||||
log.Println(".env not found; continuing")
|
||||
}
|
||||
configPath := os.Getenv("CONFIG_PATH")
|
||||
if configPath == "" {
|
||||
configPath = "configs/config.yaml"
|
||||
}
|
||||
cfg, usedDefault, err := config.LoadLocalDev(configPath)
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to load config: %v", err)
|
||||
}
|
||||
if usedDefault {
|
||||
log.Printf("Config file %s not found, using default local config", configPath)
|
||||
}
|
||||
gormDB, err := db.NewDB(cfg.Database)
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to connect MySQL: %v", err)
|
||||
}
|
||||
return gormDB
|
||||
}
|
||||
|
||||
func mustCache(ctx context.Context) *rediscache.Client {
|
||||
configPath := os.Getenv("CONFIG_PATH")
|
||||
if configPath == "" {
|
||||
configPath = "configs/config.yaml"
|
||||
}
|
||||
cfg, _, err := config.LoadLocalDev(configPath)
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to load config: %v", err)
|
||||
}
|
||||
cache, err := rediscache.NewFromEnv(&cfg.Redis)
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to connect Redis: %v", err)
|
||||
}
|
||||
pingCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer cancel()
|
||||
if err := cache.Ping(pingCtx); err != nil {
|
||||
log.Fatalf("Redis not available: %v", err)
|
||||
}
|
||||
return cache
|
||||
}
|
||||
31
backend/cmd/reconcile/main_test.go
Normal file
31
backend/cmd/reconcile/main_test.go
Normal file
@@ -0,0 +1,31 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// -counters 的职责就是修漂移:修到了说明巡检起作用了,不是失败。
|
||||
//
|
||||
// 旧实现把 fixed > 0 也并进 failed,于是"修好 3 条漂移"与"连不上数据库"
|
||||
// 返回同一个退出码,cron 告警永远响。
|
||||
func TestCountersResult_RepairedDriftIsNotFailure(t *testing.T) {
|
||||
boom := errors.New("db down")
|
||||
cases := []struct {
|
||||
name string
|
||||
in countersResult
|
||||
want bool
|
||||
}{
|
||||
{name: "没有漂移", in: countersResult{checked: 5, fixed: 0}, want: false},
|
||||
{name: "修好了漂移", in: countersResult{checked: 5, fixed: 3}, want: false},
|
||||
{name: "查询失败", in: countersResult{checked: 0, fixed: 0, err: boom}, want: true},
|
||||
{name: "修到一半失败", in: countersResult{checked: 3, fixed: 2, err: boom}, want: true},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
if got := c.in.failed(); got != c.want {
|
||||
t.Fatalf("failed() = %v, want %v(%+v)", got, c.want, c.in)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -5,16 +5,16 @@ import (
|
||||
"feedsystem_video_go/internal/auth"
|
||||
"feedsystem_video_go/internal/config"
|
||||
"feedsystem_video_go/internal/db"
|
||||
"feedsystem_video_go/internal/failedevent"
|
||||
mqrabbit "feedsystem_video_go/internal/middleware/rabbitmq"
|
||||
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||||
"feedsystem_video_go/internal/observability"
|
||||
"feedsystem_video_go/internal/social"
|
||||
"feedsystem_video_go/internal/video"
|
||||
"feedsystem_video_go/internal/worker"
|
||||
"log"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strconv"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
@@ -23,23 +23,8 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const (
|
||||
socialExchange = "social.events"
|
||||
socialQueue = "social.events"
|
||||
socialBindingKey = "social.*"
|
||||
|
||||
likeExchange = "like.events"
|
||||
likeQueue = "like.events"
|
||||
likeBindingKey = "like.*"
|
||||
|
||||
commentExchange = "comment.events"
|
||||
commentQueue = "comment.events"
|
||||
commentBindingKey = "comment.*"
|
||||
|
||||
popularityExchange = "video.popularity.events"
|
||||
popularityQueue = "video.popularity.events"
|
||||
popularityBindingKey = "video.popularity.*"
|
||||
)
|
||||
// 消费者正常毫秒级退出;超时说明 handler 卡在 I/O 上,不再无限等待。
|
||||
const workerShutdownTimeout = 10 * time.Second
|
||||
|
||||
// 带重试机制的基础设施连接函数
|
||||
func connectWithRetry(name string, maxRetries int, fn func() error) {
|
||||
@@ -57,38 +42,6 @@ func connectWithRetry(name string, maxRetries int, fn func() error) {
|
||||
log.Fatalf("%s: 超过最大重试次数", name)
|
||||
}
|
||||
|
||||
// runWorkerWithRetry 为每个 Worker 创建独立 Channel 并设置 QoS,断开后自动重连
|
||||
func runWorkerWithRetry(ctx context.Context, name string, conn *amqp.Connection, fn func(*amqp.Channel) error) {
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
default:
|
||||
}
|
||||
|
||||
ch, err := conn.Channel()
|
||||
if err != nil {
|
||||
log.Printf("%s: 创建 Channel 失败: %v, 5秒后重试", name, err)
|
||||
time.Sleep(5 * time.Second)
|
||||
continue
|
||||
}
|
||||
if err := ch.Qos(50, 0, false); err != nil {
|
||||
log.Printf("%s: QoS 设置失败: %v", name, err)
|
||||
}
|
||||
|
||||
log.Printf("%s started, consuming", name)
|
||||
if err := fn(ch); err != nil {
|
||||
if ctx.Err() != nil {
|
||||
ch.Close()
|
||||
return
|
||||
}
|
||||
log.Printf("%s: %v, 5秒后重连...", name, err)
|
||||
}
|
||||
ch.Close()
|
||||
time.Sleep(5 * time.Second)
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
// 加载 .env(本地开发)
|
||||
if err := godotenv.Load(); err != nil {
|
||||
@@ -110,8 +63,7 @@ func main() {
|
||||
log.Printf("Config loaded from file: %s", configPath)
|
||||
}
|
||||
|
||||
// JWT:Worker 虽不签发令牌,但必须与 API 使用同一密钥(否则两边 fingerprint
|
||||
// 不一致,且任何用到 auth 的路径都会静默 401)。缺失/过短直接拒绝启动。
|
||||
// JWT:Worker 必须与 API 使用同一密钥,缺失或过短直接拒绝启动。
|
||||
if err := auth.Configure(auth.Options{
|
||||
Secret: cfg.JWT.Secret,
|
||||
AccessTokenTTL: cfg.JWT.AccessTokenTTL,
|
||||
@@ -120,6 +72,7 @@ func main() {
|
||||
}
|
||||
log.Printf("JWT secret loaded (fingerprint=%s, access_ttl=%s)",
|
||||
auth.Fingerprint(), cfg.JWT.AccessTokenTTL)
|
||||
|
||||
// 连接数据库(带重试)
|
||||
var sqlDB *gorm.DB
|
||||
connectWithRetry("MySQL", 10, func() error {
|
||||
@@ -129,59 +82,42 @@ func main() {
|
||||
})
|
||||
defer db.CloseDB(sqlDB)
|
||||
|
||||
// 连接 Redis(用于流行度更新)
|
||||
// 连接 Redis(用于热榜窗口增量)
|
||||
cache, err := rediscache.NewFromEnv(&cfg.Redis)
|
||||
if err != nil {
|
||||
log.Printf("Redis config error (popularity worker disabled): %v", err)
|
||||
log.Printf("Redis config error (hot window disabled): %v", err)
|
||||
cache = nil
|
||||
} else {
|
||||
pingCtx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond)
|
||||
defer cancel()
|
||||
if err := cache.Ping(pingCtx); err != nil {
|
||||
log.Printf("Redis not available (popularity worker disabled): %v", err)
|
||||
log.Printf("Redis not available (hot window disabled): %v", err)
|
||||
_ = cache.Close()
|
||||
cache = nil
|
||||
} else {
|
||||
defer cache.Close()
|
||||
log.Printf("Redis connected (popularity worker enabled)")
|
||||
log.Printf("Redis connected (hot window enabled)")
|
||||
}
|
||||
}
|
||||
// 连接 RabbitMQ(带重试)
|
||||
url := "amqp://" + cfg.RabbitMQ.Username + ":" + cfg.RabbitMQ.Password + "@" + cfg.RabbitMQ.Host + ":" + strconv.Itoa(cfg.RabbitMQ.Port) + "/"
|
||||
var conn *amqp.Connection
|
||||
connectWithRetry("RabbitMQ", 10, func() error {
|
||||
var err error
|
||||
conn, err = amqp.Dial(url)
|
||||
return err
|
||||
})
|
||||
defer conn.Close()
|
||||
|
||||
// 用临时 Channel 声明拓扑(持久化队列,声明一次即可)
|
||||
topoCh, err := conn.Channel()
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to open topology channel: %v", err)
|
||||
// RabbitMQ 连接管理器:broker 未就绪时在这里持续等待,后续断连由管理器自愈。
|
||||
rmqMgr := mqrabbit.NewRabbitMQLazy(&cfg.RabbitMQ)
|
||||
if rmqMgr == nil {
|
||||
log.Fatalf("RabbitMQ config invalid: cannot start worker without a queue manager")
|
||||
}
|
||||
if err := mqrabbit.DeclareTopic(topoCh, socialExchange, socialQueue, socialBindingKey); err != nil {
|
||||
log.Fatalf("Failed to declare social topology: %v", err)
|
||||
}
|
||||
if err := mqrabbit.DeclareTopic(topoCh, likeExchange, likeQueue, likeBindingKey); err != nil {
|
||||
log.Fatalf("Failed to declare like topology: %v", err)
|
||||
}
|
||||
if err := mqrabbit.DeclareTopic(topoCh, commentExchange, commentQueue, commentBindingKey); err != nil {
|
||||
log.Fatalf("Failed to declare comment topology: %v", err)
|
||||
}
|
||||
if cache != nil {
|
||||
if err := mqrabbit.DeclareTopic(topoCh, popularityExchange, popularityQueue, popularityBindingKey); err != nil {
|
||||
log.Fatalf("Failed to declare popularity topology: %v", err)
|
||||
}
|
||||
}
|
||||
topoCh.Close()
|
||||
defer rmqMgr.Close()
|
||||
|
||||
// 登记拓扑:每一代连接都会重放。名字一律取自 rabbitmq 包的导出常量。
|
||||
rmqMgr.RegisterTopology(
|
||||
mqrabbit.Topology{Exchange: mqrabbit.LikeExchange, Queue: mqrabbit.LikeQueue, BindingKey: mqrabbit.LikeBindingKey},
|
||||
mqrabbit.Topology{Exchange: mqrabbit.CommentExchange, Queue: mqrabbit.CommentQueue, BindingKey: mqrabbit.CommentBindingKey},
|
||||
)
|
||||
|
||||
// 准备 repo
|
||||
socialRepo := social.NewSocialRepository(sqlDB)
|
||||
videoRepo := video.NewVideoRepository(sqlDB)
|
||||
likeRepo := video.NewLikeRepository(sqlDB)
|
||||
commentRepo := video.NewCommentRepository(sqlDB)
|
||||
failedEventRepo := failedevent.NewRepository(sqlDB)
|
||||
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
@@ -198,25 +134,79 @@ func main() {
|
||||
defer pprofServer.Close()
|
||||
}
|
||||
|
||||
// 每个 Worker 独立 Channel + 自动重连
|
||||
go runWorkerWithRetry(ctx, "SocialWorker", conn, func(ch *amqp.Channel) error {
|
||||
return worker.NewSocialWorker(ch, socialRepo, socialQueue).Run(ctx)
|
||||
// 这两类事件最终由本进程消费,拓扑因此在这里声明。
|
||||
rmqMgr.RegisterTopology(
|
||||
mqrabbit.Topology{Exchange: mqrabbit.LikeExchange, Queue: mqrabbit.NotificationLikeQueue, BindingKey: mqrabbit.LikeLikeRK},
|
||||
mqrabbit.Topology{Exchange: mqrabbit.CommentExchange, Queue: mqrabbit.NotificationCommentQueue, BindingKey: mqrabbit.CommentPublishRK},
|
||||
mqrabbit.Topology{Exchange: mqrabbit.SocialExchange, Queue: mqrabbit.NotificationSocialQueue, BindingKey: mqrabbit.SocialFollowRK},
|
||||
)
|
||||
|
||||
// Outbox 投递只有 Worker 一个执行者,不随 API 实例数复制。
|
||||
timelineMQ, err := mqrabbit.NewTimelineMQ(rmqMgr)
|
||||
if err != nil {
|
||||
log.Printf("timelineMQ init failed (timeline consumer disabled): %v", err)
|
||||
timelineMQ = nil
|
||||
}
|
||||
|
||||
// Worker 不持有 SSE 连接:通知经 Redis 广播给每个 API 实例。
|
||||
notificationHub := worker.NewRedisNotificationPublisher(cache)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
run := func(fn func()) {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
fn()
|
||||
}()
|
||||
}
|
||||
|
||||
// 停泊消费者排在最前面:它是最后一道防线,越早可用,停泊后无人接收的窗口越小。
|
||||
// prefetch=1 是刻意背压,落库慢时不要一次抓 10 条进内存。
|
||||
run(func() {
|
||||
mqrabbit.RunConsumer(ctx, rmqMgr, "FailedEventWorker", 1, func(ch *amqp.Channel) error {
|
||||
return worker.NewFailedEventWorker(ch, failedEventRepo, mqrabbit.ParkedQueue).Run(ctx)
|
||||
})
|
||||
})
|
||||
go runWorkerWithRetry(ctx, "LikeWorker", conn, func(ch *amqp.Channel) error {
|
||||
return worker.NewLikeWorker(ch, likeRepo, videoRepo, likeQueue).Run(ctx)
|
||||
run(func() {
|
||||
mqrabbit.RunConsumer(ctx, rmqMgr, "LikeWorker", 50, func(ch *amqp.Channel) error {
|
||||
return worker.NewLikeWorker(ch, rmqMgr, likeRepo, videoRepo, cache, mqrabbit.LikeQueue).Run(ctx)
|
||||
})
|
||||
})
|
||||
go runWorkerWithRetry(ctx, "CommentWorker", conn, func(ch *amqp.Channel) error {
|
||||
return worker.NewCommentWorker(ch, commentRepo, videoRepo, commentQueue).Run(ctx)
|
||||
run(func() {
|
||||
mqrabbit.RunConsumer(ctx, rmqMgr, "CommentWorker", 50, func(ch *amqp.Channel) error {
|
||||
return worker.NewCommentWorker(ch, rmqMgr, commentRepo, videoRepo, cache, mqrabbit.CommentQueue).Run(ctx)
|
||||
})
|
||||
})
|
||||
if cache != nil {
|
||||
go runWorkerWithRetry(ctx, "PopularityWorker", conn, func(ch *amqp.Channel) error {
|
||||
return worker.NewPopularityWorker(ch, cache, popularityQueue).Run(ctx)
|
||||
|
||||
// 通知消费者:三个队列各自一个 channel,一个队列阻塞不会拖住另外两个。
|
||||
for _, queue := range []string{
|
||||
mqrabbit.NotificationLikeQueue,
|
||||
mqrabbit.NotificationCommentQueue,
|
||||
mqrabbit.NotificationSocialQueue,
|
||||
} {
|
||||
run(func() {
|
||||
mqrabbit.RunConsumer(ctx, rmqMgr, "notification-"+queue, 10, func(ch *amqp.Channel) error {
|
||||
return worker.NewNotificationWorker(ch, rmqMgr, sqlDB, queue, notificationHub).Run(ctx)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// 等待退出信号
|
||||
run(func() { worker.StartOutboxPoller(ctx, sqlDB, timelineMQ) })
|
||||
run(func() { worker.StartConsumer(ctx, rmqMgr, mqrabbit.TimelineQueue, cache) })
|
||||
|
||||
// 等消费者真正返回,而不是用固定 sleep 猜。
|
||||
<-ctx.Done()
|
||||
log.Printf("Worker shutting down...")
|
||||
time.Sleep(2 * time.Second) // 等待正在处理的消息完成
|
||||
log.Printf("Worker stopped")
|
||||
|
||||
stopped := make(chan struct{})
|
||||
go func() {
|
||||
wg.Wait()
|
||||
close(stopped)
|
||||
}()
|
||||
select {
|
||||
case <-stopped:
|
||||
log.Printf("Worker stopped")
|
||||
case <-time.After(workerShutdownTimeout):
|
||||
log.Printf("Worker stopped (timeout waiting for consumers)")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ rabbitmq:
|
||||
password: 123456
|
||||
|
||||
jwt:
|
||||
# secret 只通过环境变量 JWT_SECRET 提供,不要写进受版本控制的 YAML
|
||||
# secret 只通过环境变量 JWT_SECRET 提供,不写入受版本控制的 YAML
|
||||
secret: ""
|
||||
# 访问令牌有效期,支持 15m / 1h / 30s 写法
|
||||
access_token_ttl: 15m
|
||||
|
||||
@@ -21,7 +21,7 @@ rabbitmq:
|
||||
password: 123456
|
||||
|
||||
jwt:
|
||||
# secret 只通过环境变量 JWT_SECRET 提供,不要写进受版本控制的 YAML
|
||||
# secret 只通过环境变量 JWT_SECRET 提供,不写入受版本控制的 YAML
|
||||
secret: ""
|
||||
# 访问令牌有效期,支持 15m / 1h / 30s 写法
|
||||
access_token_ttl: 15m
|
||||
|
||||
@@ -21,7 +21,7 @@ rabbitmq:
|
||||
password: 123456
|
||||
|
||||
jwt:
|
||||
# secret 只通过环境变量 JWT_SECRET 提供,不要写进受版本控制的 YAML
|
||||
# secret 只通过环境变量 JWT_SECRET 提供,不写入受版本控制的 YAML
|
||||
secret: ""
|
||||
# 访问令牌有效期,支持 15m / 1h / 30s 写法
|
||||
access_token_ttl: 15m
|
||||
|
||||
@@ -13,14 +13,14 @@ import (
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
// MinSecretBytes 是 HS256 签名密钥要求的最小字节长度(256 bit)。
|
||||
// 注意:这是"下限护栏",用于拦截空值/占位符/短口令这类部署事故,
|
||||
// 不能替代真正的随机熵——请用 `openssl rand -hex 32` 生成。
|
||||
// MinSecretBytes 是 HS256 签名密钥要求的最小字节长度(256 bit).
|
||||
// 注意:这是"下限护栏", 用于拦截空值/占位符/短口令这类部署事故,
|
||||
// 不能替代真正的随机熵, 可用 `openssl rand -hex 32` 生成.
|
||||
const MinSecretBytes = 32
|
||||
|
||||
var (
|
||||
// ErrSecretNotConfigured 表示 main 未调用 Configure。调用方应将其
|
||||
// 视为服务端配置错误(HTTP 500),而非客户端凭证错误(HTTP 401)。
|
||||
// ErrSecretNotConfigured 表示 main 未调用 Configure.调用方应将其
|
||||
// 视为服务端配置错误(HTTP 500), 而非客户端凭证错误(HTTP 401).
|
||||
ErrSecretNotConfigured = errors.New("auth: JWT secret is not configured (call auth.Configure at startup)")
|
||||
ErrSecretEmpty = errors.New("auth: JWT secret is empty")
|
||||
ErrAccessTTLInvalid = errors.New("auth: AccessTokenTTL must be > 0")
|
||||
@@ -30,18 +30,17 @@ var (
|
||||
accessTTL time.Duration
|
||||
)
|
||||
|
||||
// Options 是令牌签发策略,由 main 从 config 装载后一次性注入。
|
||||
// 用结构体而非多个位置参数,是为了后续新增 refresh TTL / issuer / 轮换密钥时
|
||||
// 不再改动函数签名。
|
||||
// Options 是令牌签发策略, 由 main 从 config 装载后一次性注入.
|
||||
// 用结构体而非多个位置参数, 后续新增 refresh TTL / issuer / 轮换密钥时不用改动函数签名.
|
||||
type Options struct {
|
||||
Secret string
|
||||
AccessTokenTTL time.Duration
|
||||
}
|
||||
|
||||
// Configure 设置 JWT 签名密钥与访问令牌有效期。必须在签发/校验任何 token
|
||||
// 之前调用一次,通常由 main 在加载配置后立即调用。
|
||||
// Configure 设置 JWT 签名密钥与访问令牌有效期.必须在签发/校验任何 token
|
||||
// 之前调用一次, 通常由 main 在加载配置后立即调用.
|
||||
//
|
||||
// 密钥按原始字节使用,不做任何派生或编码变换(保证升级不失效既有 token)。
|
||||
// 密钥按原始字节使用, 不做任何派生或编码变换(保证升级不失效既有 token).
|
||||
func Configure(opts Options) error {
|
||||
if opts.Secret == "" {
|
||||
return ErrSecretEmpty
|
||||
@@ -60,15 +59,15 @@ func Configure(opts Options) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// currentAccessTTL 返回已配置的访问令牌有效期。
|
||||
// currentAccessTTL 返回已配置的访问令牌有效期.
|
||||
func currentAccessTTL() time.Duration {
|
||||
secretMu.RLock()
|
||||
defer secretMu.RUnlock()
|
||||
return accessTTL
|
||||
}
|
||||
|
||||
// Fingerprint 返回密钥的不可逆指纹(sha256 前 8 个 hex 字符)。
|
||||
// 仅用于跨实例/跨进程核对"API 与 Worker 是否使用同一密钥",不泄露密钥本身。
|
||||
// Fingerprint 返回密钥的不可逆指纹(sha256 前 8 个 hex 字符).
|
||||
// 仅用于跨实例/跨进程核对"API 与 Worker 是否使用同一密钥", 不泄露密钥本身.
|
||||
func Fingerprint() string {
|
||||
secretMu.RLock()
|
||||
defer secretMu.RUnlock()
|
||||
@@ -79,7 +78,7 @@ func Fingerprint() string {
|
||||
return hex.EncodeToString(sum[:])[:8]
|
||||
}
|
||||
|
||||
// secret 返回已配置的密钥;未配置时返回 ErrSecretNotConfigured。
|
||||
// secret 返回已配置的密钥;未配置时返回 ErrSecretNotConfigured.
|
||||
func secret() ([]byte, error) {
|
||||
secretMu.RLock()
|
||||
defer secretMu.RUnlock()
|
||||
@@ -126,8 +125,8 @@ func GenerateRefreshToken(accountID uint) (string, error) {
|
||||
}
|
||||
|
||||
func ParseToken(tokenString string) (*Claims, error) {
|
||||
// 先取密钥:这样即使 token 本身畸形(keyfunc 不会被调用),
|
||||
// "密钥未配置"也能稳定地以 ErrSecretNotConfigured 返回。
|
||||
// 先取密钥:这样即使 token 本身畸形(keyfunc 不会被调用),
|
||||
// "密钥未配置"也能稳定地以 ErrSecretNotConfigured 返回.
|
||||
key, err := secret()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -142,7 +141,7 @@ func ParseToken(tokenString string) (*Claims, error) {
|
||||
}
|
||||
return key, nil
|
||||
},
|
||||
// 双保险:拒绝 HS256 之外的一切算法(含 alg=none 类攻击)。
|
||||
// 双保险:拒绝 HS256 之外的一切算法(含 alg=none 类攻击).
|
||||
jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Alg()}),
|
||||
)
|
||||
if err != nil {
|
||||
|
||||
@@ -46,18 +46,11 @@ type RabbitMQConfig struct {
|
||||
Password string `yaml:"password"`
|
||||
}
|
||||
|
||||
// JWTConfig 承载 JWT 签名与令牌有效期配置。
|
||||
// 约定:secret 只通过环境变量 JWT_SECRET 提供,不写入受版本控制的 YAML。
|
||||
type JWTConfig struct {
|
||||
Secret string `yaml:"secret"`
|
||||
// AccessTokenTTL 支持 YAML 的时长字符串写法("15m"/"1h"/"30s")。
|
||||
// 注意:yaml.v3 只接受这种字符串形式,写成纯数字(纳秒)会报
|
||||
// "cannot unmarshal !!int into time.Duration",因此无需自定义 UnmarshalYAML。
|
||||
Secret string `yaml:"secret"`
|
||||
AccessTokenTTL time.Duration `yaml:"access_token_ttl"`
|
||||
}
|
||||
|
||||
// DefaultAccessTokenTTL 与改动前的硬编码值一致,
|
||||
// 保证已有配置文件(尚无 jwt 段)升级后行为不变。
|
||||
const DefaultAccessTokenTTL = 15 * time.Minute
|
||||
|
||||
type ObservabilityConfig struct {
|
||||
@@ -151,7 +144,7 @@ func ApplyEnvOverrides(cfg *Config) {
|
||||
if d, err := time.ParseDuration(v); err == nil {
|
||||
cfg.JWT.AccessTokenTTL = d
|
||||
} else {
|
||||
// 注意:JWT_ACCESS_TOKEN_TTL=30(缺单位)会解析失败。
|
||||
// JWT_ACCESS_TOKEN_TTL=30(缺单位)会解析失败。
|
||||
// 此处保留原值并告警,不会静默解释成 30 纳秒。
|
||||
log.Printf("WARN: invalid JWT_ACCESS_TOKEN_TTL %q: %v (keep %v)", v, err, cfg.JWT.AccessTokenTTL)
|
||||
}
|
||||
@@ -159,8 +152,6 @@ func ApplyEnvOverrides(cfg *Config) {
|
||||
}
|
||||
|
||||
// applyDefaults 只在缺省时兜底,已显式配置的值一律不覆盖。
|
||||
// 注意:这里刻意不为 JWT.Secret 提供默认值——任何硬编码默认密钥都等于公开密钥,
|
||||
// 宁可让 auth.Configure 在启动期报错。
|
||||
func applyDefaults(cfg *Config) {
|
||||
if cfg == nil {
|
||||
return
|
||||
@@ -207,7 +198,6 @@ func DefaultLocalConfig() Config {
|
||||
Password: "password123",
|
||||
},
|
||||
JWT: JWTConfig{
|
||||
// 刻意不填 Secret:默认密钥等于公开密钥,交给 auth.Configure 在启动期拒绝。
|
||||
AccessTokenTTL: DefaultAccessTokenTTL,
|
||||
},
|
||||
ObservabilityConfig: ObservabilityConfig{
|
||||
|
||||
@@ -3,21 +3,28 @@ package db
|
||||
import (
|
||||
"feedsystem_video_go/internal/account"
|
||||
"feedsystem_video_go/internal/config"
|
||||
"feedsystem_video_go/internal/failedevent"
|
||||
"feedsystem_video_go/internal/message"
|
||||
"feedsystem_video_go/internal/notification"
|
||||
"feedsystem_video_go/internal/social"
|
||||
"feedsystem_video_go/internal/video"
|
||||
"feedsystem_video_go/internal/worker"
|
||||
"fmt"
|
||||
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func NewDB(dbcfg config.DatabaseConfig) (*gorm.DB, error) {
|
||||
dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
|
||||
// BuildDSN 组装 MySQL DSN。
|
||||
//
|
||||
// 不得开启 clientFoundRows:它会让 UPDATE 未改动行时也报告 1 行受影响,
|
||||
// 而判重依赖 RowsAffected==0。
|
||||
func BuildDSN(dbcfg config.DatabaseConfig) string {
|
||||
return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
|
||||
dbcfg.User, dbcfg.Password, dbcfg.Host, dbcfg.Port, dbcfg.DBName)
|
||||
}
|
||||
|
||||
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
|
||||
func NewDB(dbcfg config.DatabaseConfig) (*gorm.DB, error) {
|
||||
db, err := gorm.Open(mysql.Open(BuildDSN(dbcfg)), &gorm.Config{})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -29,7 +36,9 @@ func AutoMigrate(db *gorm.DB) error {
|
||||
return db.AutoMigrate(
|
||||
&account.Account{}, &video.Video{}, &video.Like{}, &video.Comment{},
|
||||
&social.Social{}, &video.OutboxMsg{}, &video.Tag{}, &video.VideoTag{},
|
||||
&message.Message{}, &worker.Notification{},
|
||||
&message.Message{}, ¬ification.Notification{},
|
||||
// 停泊消息的落库表;建表入口只有这一个。
|
||||
&failedevent.FailedEvent{},
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
43
backend/internal/db/dsn_test.go
Normal file
43
backend/internal/db/dsn_test.go
Normal file
@@ -0,0 +1,43 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"feedsystem_video_go/internal/config"
|
||||
)
|
||||
|
||||
func testDBConfig() config.DatabaseConfig {
|
||||
return config.DatabaseConfig{
|
||||
Host: "127.0.0.1",
|
||||
Port: 3307,
|
||||
User: "root",
|
||||
Password: "secret",
|
||||
DBName: "feedsystem",
|
||||
}
|
||||
}
|
||||
|
||||
// 这条断言是一个正确性护栏,不是风格检查。
|
||||
//
|
||||
// P0-4 用 RowsAffected==0 判断"这条意图已经落过库"。clientFoundRows 会让
|
||||
// 未改动任何行的 UPDATE 也报告 1 行受影响,从而把重复插入当成首次插入:
|
||||
// 评论会多一行、热度会多加一次,而且全程没有任何错误。它只能被这里钉住。
|
||||
func TestBuildDSN_DoesNotEnableClientFoundRows(t *testing.T) {
|
||||
dsn := BuildDSN(testDBConfig())
|
||||
if strings.Contains(strings.ToLower(dsn), "clientfoundrows") {
|
||||
t.Fatalf("DSN 不得包含 clientFoundRows(会破坏 RowsAffected 判重): %s", dsn)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildDSN_KeepsParseTimeAndCharset(t *testing.T) {
|
||||
dsn := BuildDSN(testDBConfig())
|
||||
for _, want := range []string{"charset=utf8mb4", "parseTime=True", "loc=Local"} {
|
||||
if !strings.Contains(dsn, want) {
|
||||
t.Fatalf("DSN 缺少 %q: %s", want, dsn)
|
||||
}
|
||||
}
|
||||
// parseTime=True 缺失会让 DATETIME 读成 []byte,CreatedAt 直接解析失败。
|
||||
if !strings.Contains(dsn, "root:secret@tcp(127.0.0.1:3307)/feedsystem") {
|
||||
t.Fatalf("DSN 拼装错误: %s", dsn)
|
||||
}
|
||||
}
|
||||
36
backend/internal/failedevent/entity.go
Normal file
36
backend/internal/failedevent/entity.go
Normal file
@@ -0,0 +1,36 @@
|
||||
// Package failedevent 存放"处理不了的消息"的持久化记录。
|
||||
package failedevent
|
||||
|
||||
import "time"
|
||||
|
||||
// 停泊记录的处置状态。
|
||||
const (
|
||||
// StatusPending 表示这条失败事件还没有被处理。
|
||||
StatusPending = "pending"
|
||||
// StatusReplayed 表示已经重放过。
|
||||
StatusReplayed = "replayed"
|
||||
// StatusDiscarded 表示确认不再重放。
|
||||
StatusDiscarded = "discarded"
|
||||
)
|
||||
|
||||
// FailedEvent 是一条停泊消息的落库记录。
|
||||
type FailedEvent struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
// SourceQueue + EventID 是复合唯一键:同一意图键的评论事件与热度事件来自不同源队列。
|
||||
SourceQueue string `gorm:"column:source_queue;type:varchar(100);not null;uniqueIndex:uk_failed_source_event,priority:1" json:"source_queue"`
|
||||
EventID *string `gorm:"column:event_id;type:varchar(64);uniqueIndex:uk_failed_source_event,priority:2" json:"event_id"`
|
||||
RoutingKey string `gorm:"column:routing_key;type:varchar(200)" json:"routing_key"`
|
||||
Attempts int `gorm:"column:attempts;not null" json:"attempts"`
|
||||
Body []byte `gorm:"column:body;type:mediumblob" json:"-"`
|
||||
Headers string `gorm:"column:headers;type:json" json:"-"`
|
||||
LastError string `gorm:"column:last_error;type:varchar(512)" json:"last_error"`
|
||||
|
||||
Status string `gorm:"column:status;type:varchar(20);default:'pending';index" json:"status"`
|
||||
ReplayCount int `gorm:"column:replay_count;default:0" json:"replay_count"`
|
||||
FirstFailedAt time.Time `gorm:"column:first_failed_at" json:"first_failed_at"`
|
||||
CreatedAt time.Time `gorm:"column:created_at" json:"created_at"`
|
||||
UpdatedAt time.Time `gorm:"column:updated_at" json:"updated_at"`
|
||||
}
|
||||
|
||||
// TableName 固定表名,避免类型改名后表名跟着漂移。
|
||||
func (FailedEvent) TableName() string { return "failed_events" }
|
||||
39
backend/internal/failedevent/repo.go
Normal file
39
backend/internal/failedevent/repo.go
Normal file
@@ -0,0 +1,39 @@
|
||||
package failedevent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
// Repository 是 failed_events 的存储层。
|
||||
type Repository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewRepository 构造仓储。
|
||||
func NewRepository(db *gorm.DB) *Repository {
|
||||
return &Repository{db: db}
|
||||
}
|
||||
|
||||
// Save 写入一条停泊记录,返回是否是本次新插入的。
|
||||
//
|
||||
// 去重键是 (source_queue, event_id);EventID 为 NULL 时不参与唯一索引,可多条共存。
|
||||
func (r *Repository) Save(ctx context.Context, e *FailedEvent) (bool, error) {
|
||||
if r == nil || r.db == nil {
|
||||
return false, errors.New("failedevent: repository is not initialized")
|
||||
}
|
||||
if e == nil {
|
||||
return false, errors.New("failedevent: entity is nil")
|
||||
}
|
||||
if e.EventID == nil {
|
||||
return true, r.db.WithContext(ctx).Create(e).Error
|
||||
}
|
||||
res := r.db.WithContext(ctx).Clauses(clause.OnConflict{DoNothing: true}).Create(e)
|
||||
if res.Error != nil {
|
||||
return false, res.Error
|
||||
}
|
||||
return res.RowsAffected > 0, nil
|
||||
}
|
||||
@@ -1,7 +1,5 @@
|
||||
package feed
|
||||
|
||||
import "time"
|
||||
|
||||
type FeedAuthor struct {
|
||||
ID uint `json:"id"`
|
||||
Username string `json:"username"`
|
||||
@@ -60,23 +58,23 @@ type ListByFollowingResponse struct {
|
||||
}
|
||||
|
||||
type ListByPopularityRequest struct {
|
||||
Limit int `json:"limit"`
|
||||
AsOf int64 `json:"as_of"` // 服务器返回的分钟时间戳;第一页传0
|
||||
Offset int `json:"offset"` // 下一页从这里开始;第一页传0
|
||||
LatestIDBefore *uint `json:"latest_id_before,omitempty"`
|
||||
|
||||
// DB fallback 用(可选)
|
||||
LatestPopularity int64 `json:"latest_popularity"`
|
||||
LatestBefore time.Time `json:"latest_before"`
|
||||
Limit int `json:"limit"`
|
||||
AsOf int64 `json:"as_of"` // 0 表示"上一个闭合分钟";只接受更早且不超过 hotSnapshotTTL 的值
|
||||
Offset int `json:"offset"` // 下一页从这里开始;第一页传 0
|
||||
}
|
||||
|
||||
type ListByPopularityResponse struct {
|
||||
VideoList []FeedVideoItem `json:"video_list"`
|
||||
AsOf int64 `json:"as_of"`
|
||||
AsOf int64 `json:"as_of"` // 本次快照的标识(分钟右端,必为已闭合分钟)
|
||||
NextOffset int `json:"next_offset"`
|
||||
HasMore bool `json:"has_more"`
|
||||
|
||||
NextLatestPopularity *int64 `json:"next_latest_popularity,omitempty"`
|
||||
NextLatestBefore *time.Time `json:"next_latest_before,omitempty"`
|
||||
NextLatestIDBefore *uint `json:"next_latest_id_before,omitempty"`
|
||||
// RankingSource 标出这一页来自哪里,同时是一个重置信号:
|
||||
// "hot" Redis 快照(正常)
|
||||
// "hot_db" MySQL 重算同一窗口(无快照,翻页只是近似稳定)
|
||||
// "latest" 窗口内无互动,返回最新视频(终结页,HasMore 恒为 false)
|
||||
// 与上一页不同即榜已换,客户端应从 offset 0 重来。
|
||||
RankingSource string `json:"ranking_source"`
|
||||
// SnapshotRebuilt 为 true 表示快照刚被重建(过期或被驱逐),
|
||||
// 这一页可能与上一页重叠,客户端应从 offset 0 重来。
|
||||
SnapshotRebuilt bool `json:"snapshot_rebuilt"`
|
||||
}
|
||||
|
||||
@@ -131,34 +131,12 @@ func (f *FeedHandler) ListByPopularity(c *gin.Context) {
|
||||
viewerAccountID = 0
|
||||
}
|
||||
|
||||
var latestPopularity int64
|
||||
var latestBefore time.Time
|
||||
var latestIDBefore uint
|
||||
|
||||
if req.LatestPopularity < 0 {
|
||||
c.JSON(400, gin.H{"error": "latest_popularity must be >= 0"})
|
||||
return
|
||||
}
|
||||
|
||||
anyCursor := !req.LatestBefore.IsZero() || req.LatestIDBefore != nil
|
||||
if anyCursor {
|
||||
if req.LatestBefore.IsZero() || req.LatestIDBefore == nil || *req.LatestIDBefore == 0 {
|
||||
c.JSON(400, gin.H{"error": "latest_before and latest_id_before must be provided together"})
|
||||
return
|
||||
}
|
||||
latestPopularity = req.LatestPopularity
|
||||
latestBefore = req.LatestBefore
|
||||
latestIDBefore = *req.LatestIDBefore
|
||||
}
|
||||
resp, err := f.service.ListByPopularity(
|
||||
c.Request.Context(),
|
||||
req.Limit,
|
||||
req.AsOf,
|
||||
req.Offset,
|
||||
viewerAccountID,
|
||||
latestPopularity,
|
||||
latestBefore,
|
||||
latestIDBefore,
|
||||
)
|
||||
if err != nil {
|
||||
c.JSON(500, gin.H{"error": err.Error()})
|
||||
|
||||
@@ -72,26 +72,33 @@ func (repo *FeedRepository) ListByFollowing(ctx context.Context, limit int, view
|
||||
return videos, nil
|
||||
}
|
||||
|
||||
// 查询热门视频. limit: 查询数量 popularityBefore: 查询热度低于此值的视频 timeBefore: 查询早于此时间的视频 idBefore: 查询ID小于此值的视频
|
||||
func (repo *FeedRepository) ListByPopularity(ctx context.Context, limit int, popularityBefore int64, timeBefore time.Time, idBefore uint) ([]*video.Video, error) {
|
||||
var videos []*video.Video
|
||||
query := repo.db.WithContext(ctx).Model(&video.Video{}).
|
||||
Order("popularity DESC, create_time DESC, id DESC")
|
||||
type HotWindowRow struct {
|
||||
VideoID uint `gorm:"column:video_id"`
|
||||
Score int64 `gorm:"column:score"`
|
||||
}
|
||||
|
||||
// 只有当游标完整提供时才加过滤(popularity 允许为 0)
|
||||
if !timeBefore.IsZero() && idBefore > 0 {
|
||||
query = query.Where(
|
||||
"(popularity < ?) OR (popularity = ? AND create_time < ?) OR (popularity = ? AND create_time = ? AND id < ?)",
|
||||
popularityBefore,
|
||||
popularityBefore, timeBefore,
|
||||
popularityBefore, timeBefore, idBefore,
|
||||
)
|
||||
}
|
||||
|
||||
if err := query.Limit(limit).Find(&videos).Error; err != nil {
|
||||
// ListHotWindow 在 MySQL 上重算热榜窗口。排序定义必须与 Redis 路径一致:
|
||||
// 分数降序,同分按 video_id 降序(ZSET 成员补零后就是同一个顺序)。
|
||||
//
|
||||
// 两个子查询各走一个 (created_at, video_id) 覆盖索引,UNION ALL 后再
|
||||
// GROUP BY,避免把两张大表 JOIN 起来。
|
||||
func (repo *FeedRepository) ListHotWindow(ctx context.Context, from, to time.Time, limit, offset int) ([]HotWindowRow, error) {
|
||||
const q = `
|
||||
SELECT video_id, CAST(SUM(cnt) AS SIGNED) AS score FROM (
|
||||
SELECT video_id, COUNT(*) AS cnt FROM likes
|
||||
WHERE created_at >= ? AND created_at < ? GROUP BY video_id
|
||||
UNION ALL
|
||||
SELECT video_id, COUNT(*) AS cnt FROM comments
|
||||
WHERE created_at >= ? AND created_at < ? GROUP BY video_id
|
||||
) t
|
||||
GROUP BY video_id
|
||||
ORDER BY score DESC, video_id DESC
|
||||
LIMIT ? OFFSET ?`
|
||||
var rows []HotWindowRow
|
||||
if err := repo.db.WithContext(ctx).Raw(q, from, to, from, to, limit, offset).Scan(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return videos, nil
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
func (repo *FeedRepository) GetByIDs(ctx context.Context, ids []uint) ([]*video.Video, error) {
|
||||
|
||||
121
backend/internal/feed/repo_integration_test.go
Normal file
121
backend/internal/feed/repo_integration_test.go
Normal file
@@ -0,0 +1,121 @@
|
||||
//go:build integration
|
||||
|
||||
package feed
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"feedsystem_video_go/internal/video"
|
||||
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
)
|
||||
|
||||
// 这些用例需要真实 MySQL:ListHotWindow 的排序定义(分数降序、同分按 id 降序)
|
||||
// 必须与 Redis 路径逐字一致,而 SQL 的 GROUP BY / CAST / ORDER BY 语义
|
||||
// 用替身验证等于什么都没验证。
|
||||
//
|
||||
// docker compose up -d mysql
|
||||
// MYSQL_TEST_DSN='root:123456@tcp(127.0.0.1:3306)/feedsystem_test?charset=utf8mb4&parseTime=True&loc=Local' \
|
||||
// go test -tags integration -count=1 ./internal/feed/
|
||||
|
||||
func newFeedTestDB(t *testing.T) *gorm.DB {
|
||||
t.Helper()
|
||||
dsn := os.Getenv("MYSQL_TEST_DSN")
|
||||
if dsn == "" {
|
||||
t.Skip("MYSQL_TEST_DSN 未设置:需要真实 MySQL(见本文件顶部注释)")
|
||||
}
|
||||
if strings.Contains(dsn, "clientFoundRows") {
|
||||
t.Fatalf("测试 DSN 不能带 clientFoundRows:它会破坏 RowsAffected 判重")
|
||||
}
|
||||
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
|
||||
Logger: logger.Default.LogMode(logger.Silent),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("connect mysql: %v", err)
|
||||
}
|
||||
if err := db.Migrator().DropTable(&video.Video{}, &video.Like{}, &video.Comment{}); err != nil {
|
||||
t.Fatalf("drop tables: %v", err)
|
||||
}
|
||||
if err := db.AutoMigrate(&video.Video{}, &video.Like{}, &video.Comment{}); err != nil {
|
||||
t.Fatalf("migrate: %v", err)
|
||||
}
|
||||
return db
|
||||
}
|
||||
|
||||
func seedFeedVideo(t *testing.T, db *gorm.DB) *video.Video {
|
||||
t.Helper()
|
||||
v := &video.Video{
|
||||
AuthorID: 1, Username: "author", Title: "t",
|
||||
PlayURL: "p", CoverURL: "c",
|
||||
}
|
||||
if err := db.Create(v).Error; err != nil {
|
||||
t.Fatalf("seed video: %v", err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func seedLikeAt(t *testing.T, db *gorm.DB, videoID, accountID uint, at time.Time) {
|
||||
t.Helper()
|
||||
if err := db.Create(&video.Like{VideoID: videoID, AccountID: accountID, CreatedAt: at}).Error; err != nil {
|
||||
t.Fatalf("seed like: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func seedCommentAt(t *testing.T, db *gorm.DB, videoID uint, at time.Time) {
|
||||
t.Helper()
|
||||
c := &video.Comment{Username: "alice", VideoID: videoID, AuthorID: 1, Content: "x", CreatedAt: at}
|
||||
if err := db.Create(c).Error; err != nil {
|
||||
t.Fatalf("seed comment: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Redis 路径用补零 member,同分时按 member 字符串降序 —— 也就是 id 降序。
|
||||
// DB 回退必须复刻同一个顺序,否则同一次请求在两条路径上看到两个榜。
|
||||
func TestListHotWindow_OrdersByScoreThenIDDesc(t *testing.T) {
|
||||
db := newFeedTestDB(t)
|
||||
repo := NewFeedRepository(db)
|
||||
ctx := context.Background()
|
||||
|
||||
low := seedFeedVideo(t, db)
|
||||
highA := seedFeedVideo(t, db)
|
||||
highB := seedFeedVideo(t, db)
|
||||
|
||||
asOf := time.Now().UTC().Truncate(time.Minute).Add(-time.Minute)
|
||||
at := asOf.Add(-5 * time.Minute)
|
||||
to := asOf.Add(time.Minute)
|
||||
|
||||
// 分数:highA = highB = 3(同分,按 id DESC 应 highB 在前),low = 1。
|
||||
for i := uint(1); i <= 3; i++ {
|
||||
seedLikeAt(t, db, highA.ID, i, at)
|
||||
}
|
||||
seedLikeAt(t, db, highB.ID, 1, at)
|
||||
seedCommentAt(t, db, highB.ID, at)
|
||||
seedCommentAt(t, db, highB.ID, at.Add(time.Second))
|
||||
seedLikeAt(t, db, low.ID, 1, at)
|
||||
|
||||
// 窗口外的互动不得进入结果。
|
||||
seedLikeAt(t, db, low.ID, 2, to)
|
||||
|
||||
rows, err := repo.ListHotWindow(ctx, asOf.Add(-59*time.Minute), to, 10, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("ListHotWindow: %v", err)
|
||||
}
|
||||
wantIDs := []uint{highB.ID, highA.ID, low.ID}
|
||||
if len(rows) != len(wantIDs) {
|
||||
t.Fatalf("rows = %+v, want %d 行", rows, len(wantIDs))
|
||||
}
|
||||
for i, want := range wantIDs {
|
||||
if rows[i].VideoID != want {
|
||||
t.Fatalf("第 %d 行 video_id = %d, want %d(分数降序,同分 id 降序)", i, rows[i].VideoID, want)
|
||||
}
|
||||
}
|
||||
if rows[0].Score != 3 || rows[2].Score != 1 {
|
||||
t.Fatalf("分数 = %d/%d, want 3/1", rows[0].Score, rows[2].Score)
|
||||
}
|
||||
}
|
||||
@@ -438,118 +438,247 @@ func (f *FeedService) ListByFollowing(ctx context.Context, limit int, latestBefo
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func (f *FeedService) ListByPopularity(ctx context.Context, limit int, reqAsOf int64, offset int, viewerAccountID uint, latestPopularity int64, latestBefore time.Time, latestIDBefore uint) (ListByPopularityResponse, error) {
|
||||
// Redis 热榜(稳定分页:as_of + offset)
|
||||
// hotSnapshotTTL 是一个 as_of 的快照寿命,要覆盖一次浏览会话。
|
||||
const hotSnapshotTTL = time.Hour
|
||||
|
||||
// lastClosedMinute 返回上一个已闭合的分钟(UTC)。
|
||||
//
|
||||
// 当前这一分钟仍在增长,不能当窗口右端,否则同一个 as_of 会在翻页过程中变大。
|
||||
func lastClosedMinute(now time.Time) time.Time {
|
||||
return now.UTC().Truncate(time.Minute).Add(-time.Minute)
|
||||
}
|
||||
|
||||
// hotWindowBounds 返回 [asOf-59m, asOf+1m),正好覆盖 60 个分钟桶。
|
||||
func hotWindowBounds(asOf time.Time) (from, to time.Time) {
|
||||
from = asOf.Add(-time.Duration(video.HotWindowMinutes-1) * time.Minute)
|
||||
to = asOf.Add(time.Minute)
|
||||
return
|
||||
}
|
||||
|
||||
func (f *FeedService) ListByPopularity(ctx context.Context, limit int, reqAsOf int64, offset int, viewerAccountID uint) (ListByPopularityResponse, error) {
|
||||
// offset 同时喂给 Redis 的 LIMIT 与 SQL 的 OFFSET,后者拿到负数会报
|
||||
// Error 1690,把"翻到头了"变成 500。夹在入口,挡住两条读路径。
|
||||
if offset < 0 {
|
||||
offset = 0
|
||||
}
|
||||
|
||||
asOf := lastClosedMinute(time.Now())
|
||||
if reqAsOf > 0 {
|
||||
want := time.Unix(reqAsOf, 0).UTC().Truncate(time.Minute)
|
||||
// 只接受更早、且仍在快照 TTL 内的 as_of;超龄的快照重建出来是另一个榜。
|
||||
if want.Before(asOf) && time.Since(want) <= hotSnapshotTTL {
|
||||
asOf = want
|
||||
}
|
||||
}
|
||||
|
||||
if f.rediscache != nil {
|
||||
// 将 as_of 截断到分钟级
|
||||
asOf := time.Now().UTC().Truncate(time.Minute)
|
||||
if reqAsOf > 0 {
|
||||
asOf = time.Unix(reqAsOf, 0).UTC().Truncate(time.Minute)
|
||||
resp, ok, err := f.listByHotWindowRedis(ctx, limit, offset, asOf, viewerAccountID)
|
||||
if err != nil {
|
||||
return ListByPopularityResponse{}, err
|
||||
}
|
||||
|
||||
// 创建时间窗口,获取过去 60 分钟的 ZSET
|
||||
const win = 60
|
||||
keys := make([]string, 0, win)
|
||||
for i := 0; i < win; i++ {
|
||||
keys = append(keys, f.rediscache.Key("hot:video:1m:%s", asOf.Add(-time.Duration(i)*time.Minute).Format("200601021504")))
|
||||
if ok {
|
||||
return resp, nil
|
||||
}
|
||||
}
|
||||
return f.listByHotWindowDB(ctx, limit, offset, asOf, viewerAccountID)
|
||||
}
|
||||
|
||||
// 创建快照key:同一个as_of页内复用
|
||||
dest := f.rediscache.Key("hot:video:merge:1m:%s", asOf.Format("200601021504"))
|
||||
opCtx, cancel := context.WithTimeout(ctx, 80*time.Millisecond)
|
||||
defer cancel()
|
||||
func (f *FeedService) listByHotWindowRedis(ctx context.Context, limit, offset int, asOf time.Time, viewer uint) (ListByPopularityResponse, bool, error) {
|
||||
from, _ := hotWindowBounds(asOf)
|
||||
keys := make([]string, 0, video.HotWindowMinutes)
|
||||
for t := from; !t.After(asOf); t = t.Add(time.Minute) {
|
||||
keys = append(keys, f.rediscache.Key("hot:video:1m:%s", video.HotBucket(t)))
|
||||
}
|
||||
dest := f.rediscache.Key("hot:video:merge:1m:%s", video.HotBucket(asOf))
|
||||
|
||||
exists, _ := f.rediscache.Exists(opCtx, dest) // 检查合并快照是否已存在
|
||||
if !exists {
|
||||
_ = f.rediscache.ZUnionStore(opCtx, dest, keys, "SUM")
|
||||
_ = f.rediscache.Expire(opCtx, dest, 2*time.Minute) // 给翻页留时间
|
||||
// 120ms 覆盖 5 次往返(含 ZUNIONSTORE 60 个键)。超时就落 DB 回退,
|
||||
// 而那条路是最贵的查询,所以超时率要能观测。
|
||||
opCtx, cancel := context.WithTimeout(ctx, 120*time.Millisecond)
|
||||
defer cancel()
|
||||
exists, err := f.rediscache.Exists(opCtx, dest)
|
||||
if err != nil {
|
||||
return ListByPopularityResponse{}, false, nil // Redis 抖动:交给 DB 窗口
|
||||
}
|
||||
if !exists {
|
||||
// 快照只建一次:直接 ZUnionStore 到 dest 会让并发的后到者覆盖先到者,
|
||||
// 先用临时键算,再用 RENAMENX 原子占位。
|
||||
tmp := dest + ":build:" + strconv.FormatInt(time.Now().UnixNano(), 36)
|
||||
n, err := f.rediscache.ZUnionStore(opCtx, tmp, keys, "SUM")
|
||||
if err != nil {
|
||||
return ListByPopularityResponse{}, false, nil
|
||||
}
|
||||
|
||||
start := int64(offset)
|
||||
stop := start + int64(limit) - 1
|
||||
members, err := f.rediscache.ZRevRange(opCtx, dest, start, stop)
|
||||
if err == nil && len(members) == 0 {
|
||||
if offset > 0 {
|
||||
return ListByPopularityResponse{
|
||||
VideoList: []FeedVideoItem{},
|
||||
AsOf: asOf.Unix(),
|
||||
NextOffset: offset,
|
||||
HasMore: false,
|
||||
}, nil
|
||||
}
|
||||
if n == 0 {
|
||||
// 空表不能发布:否则该 as_of 在 TTL 内每次命中空快照,永远落 DB
|
||||
// 却报告 snapshot_rebuilt=false。
|
||||
_ = f.rediscache.Del(opCtx, tmp)
|
||||
return ListByPopularityResponse{}, false, nil
|
||||
}
|
||||
if err == nil && len(members) > 0 {
|
||||
// 将字符串 ID 转换为 uint
|
||||
ids := make([]uint, 0, len(members))
|
||||
for _, m := range members {
|
||||
u, err := strconv.ParseUint(m, 10, 64)
|
||||
if err == nil && u > 0 {
|
||||
ids = append(ids, uint(u))
|
||||
}
|
||||
}
|
||||
|
||||
// 根据 ID 批量获取视频信息
|
||||
videos, err := f.repo.GetByIDs(ctx, ids)
|
||||
if err == nil {
|
||||
byID := make(map[uint]*video.Video, len(videos))
|
||||
for _, v := range videos {
|
||||
byID[v.ID] = v
|
||||
}
|
||||
ordered := make([]*video.Video, 0, len(ids))
|
||||
for _, id := range ids { // 按 Redis 返回的顺序重新排列
|
||||
if v := byID[id]; v != nil {
|
||||
ordered = append(ordered, v)
|
||||
}
|
||||
}
|
||||
items, err := f.buildFeedVideos(ctx, ordered, viewerAccountID)
|
||||
if err != nil {
|
||||
return ListByPopularityResponse{}, err
|
||||
}
|
||||
resp := ListByPopularityResponse{
|
||||
VideoList: items,
|
||||
AsOf: asOf.Unix(),
|
||||
NextOffset: offset + len(items),
|
||||
HasMore: len(items) == limit,
|
||||
}
|
||||
if len(ordered) > 0 { // 准备最后一条视频的游标信息,供 DB fallback 使用
|
||||
last := ordered[len(ordered)-1]
|
||||
nextPopularity := last.Popularity
|
||||
nextBefore := last.CreateTime
|
||||
nextID := last.ID
|
||||
resp.NextLatestPopularity = &nextPopularity
|
||||
resp.NextLatestBefore = &nextBefore
|
||||
resp.NextLatestIDBefore = &nextID
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
// 临时键留短 TTL:进程若在 RENAMENX 前崩溃,它不会永久留下。
|
||||
if err := f.rediscache.Expire(opCtx, tmp, time.Minute); err != nil {
|
||||
log.Printf("feed: expire hot snapshot tmp %s failed (non-fatal): %v", tmp, err)
|
||||
}
|
||||
won, err := f.rediscache.RenameNX(opCtx, tmp, dest)
|
||||
if err != nil {
|
||||
return ListByPopularityResponse{}, false, nil
|
||||
}
|
||||
if !won {
|
||||
_ = f.rediscache.Del(opCtx, tmp) // 别人先建好了,用他的
|
||||
} else if err := f.rediscache.Expire(opCtx, dest, hotSnapshotTTL); err != nil {
|
||||
// RENAMENX 把临时键的 1 分钟 TTL 带给了 dest;改不成快照寿命就删掉,
|
||||
// 否则 dest 一分钟后消失 → 反复重建 → 客户端永远翻不到第 2 页。
|
||||
log.Printf("feed: expire hot snapshot %s failed, dropping it: %v", dest, err)
|
||||
_ = f.rediscache.Del(opCtx, dest)
|
||||
}
|
||||
}
|
||||
|
||||
// DB fallback(游标分页:latestPopularity + latestBefore + latestIDBefore)
|
||||
videos, err := f.repo.ListByPopularity(ctx, limit, latestPopularity, latestBefore, latestIDBefore)
|
||||
// 只取分数 > 0 的成员:加减相抵的视频不该留在榜上,DB 路径同样只返回
|
||||
// 窗口内有行的视频。
|
||||
members, err := f.rediscache.ZRevRangeByScore(opCtx, dest, "+inf", "(0", int64(offset), int64(limit))
|
||||
if err != nil {
|
||||
return ListByPopularityResponse{}, false, nil
|
||||
}
|
||||
if len(members) == 0 {
|
||||
if offset > 0 {
|
||||
return ListByPopularityResponse{
|
||||
VideoList: []FeedVideoItem{},
|
||||
AsOf: asOf.Unix(),
|
||||
NextOffset: offset,
|
||||
HasMore: false,
|
||||
RankingSource: "hot",
|
||||
SnapshotRebuilt: !exists,
|
||||
}, true, nil
|
||||
}
|
||||
// 空榜:可能是真的空,也可能是丢桶。都交给 DB 窗口判一次。
|
||||
return ListByPopularityResponse{}, false, nil
|
||||
}
|
||||
|
||||
ids := parseHotMembers(members)
|
||||
videos, err := f.repo.GetByIDs(ctx, ids)
|
||||
if err != nil {
|
||||
return ListByPopularityResponse{}, false, err
|
||||
}
|
||||
byID := make(map[uint]*video.Video, len(videos))
|
||||
for _, v := range videos {
|
||||
byID[v.ID] = v
|
||||
}
|
||||
ordered := make([]*video.Video, 0, len(ids))
|
||||
for _, id := range ids {
|
||||
if v := byID[id]; v != nil {
|
||||
ordered = append(ordered, v)
|
||||
}
|
||||
}
|
||||
items, err := f.buildFeedVideos(ctx, ordered, viewer)
|
||||
if err != nil {
|
||||
return ListByPopularityResponse{}, false, err
|
||||
}
|
||||
return ListByPopularityResponse{
|
||||
VideoList: items,
|
||||
AsOf: asOf.Unix(),
|
||||
// 按 ZSET 返回的 member 数推进:视频被删后 member 仍在,
|
||||
// 按存活视频数推进会重复读到已经跳过的位置。
|
||||
NextOffset: offset + len(members),
|
||||
HasMore: len(members) == limit,
|
||||
RankingSource: "hot",
|
||||
SnapshotRebuilt: !exists && offset > 0,
|
||||
}, true, nil
|
||||
}
|
||||
|
||||
func parseHotMembers(members []string) []uint {
|
||||
ids := make([]uint, 0, len(members))
|
||||
for _, m := range members {
|
||||
u, err := strconv.ParseUint(m, 10, 64) // 兼容补零与旧格式
|
||||
if err == nil && u > 0 {
|
||||
ids = append(ids, uint(u))
|
||||
}
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
// hotDBMaxSweep 限制一次翻页最多扫几批:窗口里全是已删视频时,无上限的扫描
|
||||
// 会把一次请求变成几十次查询。
|
||||
const hotDBMaxSweep = 5
|
||||
|
||||
func (f *FeedService) listByHotWindowDB(ctx context.Context, limit, offset int, asOf time.Time, viewer uint) (ListByPopularityResponse, error) {
|
||||
from, to := hotWindowBounds(asOf)
|
||||
|
||||
// 整页都被 GetByIDs 过滤掉时按 SQL 行推进游标继续取,直到凑到视频或取到不满一页。
|
||||
var (
|
||||
consumed int
|
||||
ordered []*video.Video
|
||||
more bool
|
||||
)
|
||||
for sweep := 0; sweep < hotDBMaxSweep; sweep++ {
|
||||
rows, err := f.repo.ListHotWindow(ctx, from, to, limit, offset+consumed)
|
||||
if err != nil {
|
||||
return ListByPopularityResponse{}, err
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
more = false
|
||||
break
|
||||
}
|
||||
consumed += len(rows)
|
||||
more = len(rows) == limit
|
||||
|
||||
ids := make([]uint, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
ids = append(ids, r.VideoID)
|
||||
}
|
||||
videos, err := f.repo.GetByIDs(ctx, ids)
|
||||
if err != nil {
|
||||
return ListByPopularityResponse{}, err
|
||||
}
|
||||
byID := make(map[uint]*video.Video, len(videos))
|
||||
for _, v := range videos {
|
||||
byID[v.ID] = v
|
||||
}
|
||||
for _, id := range ids {
|
||||
if v := byID[id]; v != nil {
|
||||
ordered = append(ordered, v)
|
||||
}
|
||||
}
|
||||
if len(ordered) > 0 || !more {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if consumed == 0 && offset == 0 {
|
||||
// 窗口内没有互动:给"最新",不给空页面。
|
||||
latest, err := f.repo.ListLatest(ctx, limit, time.Time{})
|
||||
if err != nil {
|
||||
return ListByPopularityResponse{}, err
|
||||
}
|
||||
items, err := f.buildFeedVideos(ctx, latest, viewer)
|
||||
if err != nil {
|
||||
return ListByPopularityResponse{}, err
|
||||
}
|
||||
return ListByPopularityResponse{
|
||||
VideoList: items, AsOf: asOf.Unix(),
|
||||
// ListLatest 不收 offset,回一个 next_offset 会让第 2 页落到空热榜上。
|
||||
NextOffset: 0, HasMore: false, RankingSource: "latest",
|
||||
}, nil
|
||||
}
|
||||
if len(ordered) == 0 {
|
||||
// 翻到末尾,或连续几批只剩已删视频:终结页。
|
||||
return ListByPopularityResponse{
|
||||
VideoList: []FeedVideoItem{},
|
||||
AsOf: asOf.Unix(),
|
||||
NextOffset: offset + consumed,
|
||||
HasMore: false,
|
||||
RankingSource: "hot_db",
|
||||
}, nil
|
||||
}
|
||||
|
||||
items, err := f.buildFeedVideos(ctx, ordered, viewer)
|
||||
if err != nil {
|
||||
return ListByPopularityResponse{}, err
|
||||
}
|
||||
items, err := f.buildFeedVideos(ctx, videos, viewerAccountID)
|
||||
if err != nil {
|
||||
return ListByPopularityResponse{}, err
|
||||
}
|
||||
resp := ListByPopularityResponse{
|
||||
VideoList: items,
|
||||
AsOf: 0,
|
||||
NextOffset: 0,
|
||||
HasMore: len(items) == limit,
|
||||
}
|
||||
if len(videos) > 0 {
|
||||
last := videos[len(videos)-1]
|
||||
nextPopularity := last.Popularity
|
||||
nextBefore := last.CreateTime
|
||||
nextID := last.ID
|
||||
resp.NextLatestPopularity = &nextPopularity
|
||||
resp.NextLatestBefore = &nextBefore
|
||||
resp.NextLatestIDBefore = &nextID
|
||||
}
|
||||
return resp, nil
|
||||
return ListByPopularityResponse{
|
||||
VideoList: items, AsOf: asOf.Unix(),
|
||||
// 游标按 SQL 行推进(含被跳过的已删视频),否则第 2 页会重复读到已消费的位置。
|
||||
NextOffset: offset + consumed,
|
||||
HasMore: more,
|
||||
RankingSource: "hot_db",
|
||||
}, nil
|
||||
}
|
||||
|
||||
// 将 Video 列表转换为 FeedVideoItem 列表,并批量查询填充当前用户对所有视频的点赞状态
|
||||
|
||||
451
backend/internal/feed/service_integration_test.go
Normal file
451
backend/internal/feed/service_integration_test.go
Normal file
@@ -0,0 +1,451 @@
|
||||
//go:build integration
|
||||
|
||||
package feed
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||||
"feedsystem_video_go/internal/video"
|
||||
|
||||
"github.com/alicebob/miniredis/v2"
|
||||
goredis "github.com/redis/go-redis/v9"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type feedFixture struct {
|
||||
svc *FeedService
|
||||
db *gorm.DB
|
||||
cache *rediscache.Client
|
||||
mr *miniredis.Miniredis
|
||||
asOf time.Time
|
||||
at time.Time // 窗口内的互动时间
|
||||
}
|
||||
|
||||
func newFeedFixture(t *testing.T, opts ...goredis.Hook) *feedFixture {
|
||||
t.Helper()
|
||||
db := newFeedTestDB(t)
|
||||
mr := miniredis.RunT(t)
|
||||
rdb := goredis.NewClient(&goredis.Options{Addr: mr.Addr()})
|
||||
t.Cleanup(func() { _ = rdb.Close() })
|
||||
for _, h := range opts {
|
||||
rdb.AddHook(h)
|
||||
}
|
||||
cache := rediscache.NewClient(rdb, "test:")
|
||||
svc := NewFeedService(NewFeedRepository(db), video.NewLikeRepository(db), cache)
|
||||
|
||||
asOf := lastClosedMinute(time.Now())
|
||||
return &feedFixture{svc: svc, db: db, cache: cache, mr: mr, asOf: asOf, at: asOf.Add(-5 * time.Minute)}
|
||||
}
|
||||
|
||||
func (f *feedFixture) seedHot(t *testing.T, likes int) *video.Video {
|
||||
t.Helper()
|
||||
v := seedFeedVideo(t, f.db)
|
||||
for i := 1; i <= likes; i++ {
|
||||
seedLikeAt(t, f.db, v.ID, uint(i), f.at)
|
||||
}
|
||||
// DB 行与热榜桶必须成对出现:桶是行的物化视图,只插行会让读侧
|
||||
// 只剩 DB 回退路径,快照/并集相关的断言就失去被测对象。
|
||||
if err := video.ApplyHotDelta(context.Background(), f.cache, v.ID, int64(likes), f.at); err != nil {
|
||||
t.Fatalf("seed hot: %v", err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func ids(items []FeedVideoItem) []uint {
|
||||
out := make([]uint, 0, len(items))
|
||||
for _, it := range items {
|
||||
out = append(out, it.ID)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (f *feedFixture) snapshotKey() string {
|
||||
return f.cache.Key("hot:video:merge:1m:%s", video.HotBucket(f.asOf))
|
||||
}
|
||||
|
||||
// 翻页不得重复:旧实现用 offset+len(items) 推进,视频被删后 items 比 members 短,
|
||||
// 下一次请求会从已经返回过的位置开始。
|
||||
func TestListByPopularity_PaginatesWithoutOverlap(t *testing.T) {
|
||||
f := newFeedFixture(t)
|
||||
ctx := context.Background()
|
||||
f.seedHot(t, 3)
|
||||
f.seedHot(t, 2)
|
||||
f.seedHot(t, 1)
|
||||
|
||||
page1, err := f.svc.ListByPopularity(ctx, 2, f.asOf.Unix(), 0, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("page1: %v", err)
|
||||
}
|
||||
if page1.RankingSource != "hot" {
|
||||
t.Fatalf("page1 ranking_source = %q, want hot", page1.RankingSource)
|
||||
}
|
||||
if len(page1.VideoList) != 2 || !page1.HasMore || page1.NextOffset != 2 {
|
||||
t.Fatalf("page1 = %d 条 has_more=%v next=%d, want 2 条/true/2",
|
||||
len(page1.VideoList), page1.HasMore, page1.NextOffset)
|
||||
}
|
||||
|
||||
page2, err := f.svc.ListByPopularity(ctx, 2, f.asOf.Unix(), page1.NextOffset, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("page2: %v", err)
|
||||
}
|
||||
if len(page2.VideoList) != 1 || page2.HasMore {
|
||||
t.Fatalf("page2 = %d 条 has_more=%v, want 1 条/false", len(page2.VideoList), page2.HasMore)
|
||||
}
|
||||
seen := make(map[uint]bool)
|
||||
for _, id := range append(ids(page1.VideoList), ids(page2.VideoList)...) {
|
||||
if seen[id] {
|
||||
t.Fatalf("视频 %d 在两页里重复出现", id)
|
||||
}
|
||||
seen[id] = true
|
||||
}
|
||||
}
|
||||
|
||||
// 快照只建一次:第一个请求算出并原子发布,之后的请求读同一份副本。
|
||||
func TestListByPopularity_SnapshotIsBuiltOnce(t *testing.T) {
|
||||
f := newFeedFixture(t)
|
||||
ctx := context.Background()
|
||||
f.seedHot(t, 2)
|
||||
f.seedHot(t, 1)
|
||||
|
||||
first, err := f.svc.ListByPopularity(ctx, 10, f.asOf.Unix(), 0, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("first: %v", err)
|
||||
}
|
||||
if first.SnapshotRebuilt {
|
||||
t.Fatal("首次请求是建快照,不是重建")
|
||||
}
|
||||
dest := f.snapshotKey()
|
||||
if !f.mr.Exists(dest) {
|
||||
t.Fatalf("快照键 %s 不存在", dest)
|
||||
}
|
||||
if ttl := f.mr.TTL(dest); ttl != hotSnapshotTTL {
|
||||
t.Fatalf("快照 TTL = %v, want %v(继承临时键的 1 分钟 TTL 会让第 2 页永远翻不到)",
|
||||
ttl, hotSnapshotTTL)
|
||||
}
|
||||
|
||||
second, err := f.svc.ListByPopularity(ctx, 10, f.asOf.Unix(), 0, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("second: %v", err)
|
||||
}
|
||||
if second.SnapshotRebuilt {
|
||||
t.Fatal("快照已存在,第二次不得报告重建")
|
||||
}
|
||||
if got, want := ids(second.VideoList), ids(first.VideoList); len(got) != len(want) || got[0] != want[0] {
|
||||
t.Fatalf("第二次结果 = %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// 迟到增量会改写仍在窗口内的桶,但已发布的快照不得重算:
|
||||
// 同一个 as_of 在快照活着的时候是同一个榜。
|
||||
func TestListByPopularity_LateDeltaDoesNotChangeSnapshot(t *testing.T) {
|
||||
f := newFeedFixture(t)
|
||||
ctx := context.Background()
|
||||
top := f.seedHot(t, 2)
|
||||
bottom := f.seedHot(t, 1)
|
||||
|
||||
first, err := f.svc.ListByPopularity(ctx, 10, f.asOf.Unix(), 0, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("first: %v", err)
|
||||
}
|
||||
if got := ids(first.VideoList); len(got) != 2 || got[0] != top.ID {
|
||||
t.Fatalf("首屏顺序 = %v, want [%d %d]", got, top.ID, bottom.ID)
|
||||
}
|
||||
|
||||
// 往窗口内的桶补写,把 bottom 顶到第一。
|
||||
bucketKey := f.cache.Key("hot:video:1m:%s", video.HotBucket(f.at))
|
||||
if err := f.cache.ZincrBy(ctx, bucketKey, video.HotMember(bottom.ID), 10); err != nil {
|
||||
t.Fatalf("zincrby: %v", err)
|
||||
}
|
||||
|
||||
second, err := f.svc.ListByPopularity(ctx, 10, f.asOf.Unix(), 0, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("second: %v", err)
|
||||
}
|
||||
if got := ids(second.VideoList); len(got) != 2 || got[0] != top.ID {
|
||||
t.Fatalf("迟到增量改写了快照:顺序 = %v, want [%d %d]", got, top.ID, bottom.ID)
|
||||
}
|
||||
}
|
||||
|
||||
// Redis 缺席或丢键时退回 DB 重算同一窗口,并明确告诉客户端来源不同。
|
||||
func TestListByPopularity_FallsBackToDBWindow(t *testing.T) {
|
||||
f := newFeedFixture(t)
|
||||
ctx := context.Background()
|
||||
f.seedHot(t, 2)
|
||||
|
||||
f.mr.FlushAll() // 桶与快照一起丢:模拟 Redis 被清空
|
||||
|
||||
resp, err := f.svc.ListByPopularity(ctx, 10, f.asOf.Unix(), 0, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("ListByPopularity: %v", err)
|
||||
}
|
||||
if resp.RankingSource != "hot_db" {
|
||||
t.Fatalf("ranking_source = %q, want hot_db", resp.RankingSource)
|
||||
}
|
||||
if len(resp.VideoList) != 1 {
|
||||
t.Fatalf("video_list = %d 条, want 1", len(resp.VideoList))
|
||||
}
|
||||
}
|
||||
|
||||
// 窗口内没有任何互动时给"最新",且这一支是终结页:不回 next_offset,
|
||||
// 否则第 2 页会落到 ListHotWindow 的空结果上返回空页。
|
||||
func TestListByPopularity_LatestBranchIsTerminal(t *testing.T) {
|
||||
f := newFeedFixture(t)
|
||||
ctx := context.Background()
|
||||
seedFeedVideo(t, f.db) // 有视频,但窗口内没有互动
|
||||
|
||||
resp, err := f.svc.ListByPopularity(ctx, 10, f.asOf.Unix(), 0, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("ListByPopularity: %v", err)
|
||||
}
|
||||
if resp.RankingSource != "latest" {
|
||||
t.Fatalf("ranking_source = %q, want latest", resp.RankingSource)
|
||||
}
|
||||
if resp.NextOffset != 0 || resp.HasMore {
|
||||
t.Fatalf("next_offset=%d has_more=%v, want 0/false(latest 是终结页)", resp.NextOffset, resp.HasMore)
|
||||
}
|
||||
if len(resp.VideoList) != 1 {
|
||||
t.Fatalf("video_list = %d 条, want 1", len(resp.VideoList))
|
||||
}
|
||||
}
|
||||
|
||||
// 视频被硬删后互动行还在(DeleteVideo 不级联),整页都被 GetByIDs 过滤掉时
|
||||
// 不能直接回空页,游标必须越过被跳过的行继续取。
|
||||
func TestListByPopularity_DBWindowSkipsDeletedVideos(t *testing.T) {
|
||||
f := newFeedFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
alive := f.seedHot(t, 1)
|
||||
for _, likes := range []int{5, 4} {
|
||||
gone := f.seedHot(t, likes)
|
||||
if err := f.db.Delete(&video.Video{}, gone.ID).Error; err != nil {
|
||||
t.Fatalf("硬删视频 %d: %v", gone.ID, err)
|
||||
}
|
||||
}
|
||||
f.mr.FlushAll() // 桶与快照一起丢:强制走 DB 窗口
|
||||
|
||||
resp, err := f.svc.ListByPopularity(ctx, 2, f.asOf.Unix(), 0, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("ListByPopularity: %v", err)
|
||||
}
|
||||
if got := ids(resp.VideoList); len(got) != 1 || got[0] != alive.ID {
|
||||
t.Fatalf("首屏 = %v, want [%d](整页已删视频不能吃掉分页位置)", got, alive.ID)
|
||||
}
|
||||
if resp.HasMore {
|
||||
t.Fatalf("has_more = true(next_offset=%d):跳过已删视频后窗口已经到底", resp.NextOffset)
|
||||
}
|
||||
if resp.NextOffset != 3 {
|
||||
t.Fatalf("next_offset = %d, want 3(游标要越过被跳过的 2 行,否则第 2 页重复读)", resp.NextOffset)
|
||||
}
|
||||
}
|
||||
|
||||
// 按客户端方式翻到底:整页已删视频后不重不漏,并且能终止。
|
||||
func TestListByPopularity_DBWindowPaginatesPastDeletedVideos(t *testing.T) {
|
||||
f := newFeedFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
// 分数严格递减:4 个高分视频(会被删)排在 2 个存活视频之前。
|
||||
want := map[uint]bool{}
|
||||
for i := 0; i < 2; i++ {
|
||||
want[f.seedHot(t, 2).ID] = true
|
||||
}
|
||||
for i := 0; i < 4; i++ {
|
||||
gone := f.seedHot(t, 10+i)
|
||||
if err := f.db.Delete(&video.Video{}, gone.ID).Error; err != nil {
|
||||
t.Fatalf("硬删视频 %d: %v", gone.ID, err)
|
||||
}
|
||||
}
|
||||
f.mr.FlushAll()
|
||||
|
||||
got := map[uint]bool{}
|
||||
offset := 0
|
||||
for page := 0; page < 10; page++ {
|
||||
resp, err := f.svc.ListByPopularity(ctx, 2, f.asOf.Unix(), offset, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("第 %d 页: %v", page+1, err)
|
||||
}
|
||||
for _, id := range ids(resp.VideoList) {
|
||||
if got[id] {
|
||||
t.Fatalf("第 %d 页重复返回视频 %d(offset=%d)", page+1, id, offset)
|
||||
}
|
||||
got[id] = true
|
||||
}
|
||||
if !resp.HasMore {
|
||||
break
|
||||
}
|
||||
if resp.NextOffset <= offset {
|
||||
t.Fatalf("has_more=true 但 next_offset(%d) 没前进(offset=%d):翻页会死循环", resp.NextOffset, offset)
|
||||
}
|
||||
offset = resp.NextOffset
|
||||
}
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("翻完拿到 %v, want %v(漏了存活视频)", got, want)
|
||||
}
|
||||
for id := range want {
|
||||
if !got[id] {
|
||||
t.Fatalf("翻完没拿到存活视频 %d", id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 连续 hotDBMaxSweep 批都只剩已删视频时收尾,更靠后的视频留到下一次 as_of。
|
||||
func TestListByPopularity_DBWindowStopsAfterSweepLimit(t *testing.T) {
|
||||
f := newFeedFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
alive := f.seedHot(t, 1) // 分数最低,排在最后
|
||||
for i := 0; i < 12; i++ {
|
||||
gone := f.seedHot(t, 10+i) // 分数 10..21,全部排在前面
|
||||
if err := f.db.Delete(&video.Video{}, gone.ID).Error; err != nil {
|
||||
t.Fatalf("硬删视频 %d: %v", gone.ID, err)
|
||||
}
|
||||
}
|
||||
f.mr.FlushAll()
|
||||
|
||||
// limit=2 → 5 批只够越过 10 行,第 11、12 行与存活的 alive 都还在后面。
|
||||
resp, err := f.svc.ListByPopularity(ctx, 2, f.asOf.Unix(), 0, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("ListByPopularity: %v", err)
|
||||
}
|
||||
if len(resp.VideoList) != 0 || resp.HasMore {
|
||||
t.Fatalf("视频列表 = %v has_more=%v, want 空/false(撞到扫批上限后收尾)",
|
||||
ids(resp.VideoList), resp.HasMore)
|
||||
}
|
||||
if want := 2 * hotDBMaxSweep; resp.NextOffset != want {
|
||||
t.Fatalf("next_offset = %d, want %d(游标只越过 5 批 rows,alive=%d 留到下一个 as_of)",
|
||||
resp.NextOffset, want, alive.ID)
|
||||
}
|
||||
}
|
||||
|
||||
// 60 个空桶的并集是"空表",不能把它发布成快照:否则这个 as_of 在 TTL 内
|
||||
// 每次都会命中"存在的空快照","真的空榜"与"快照丢了"从此分不开。
|
||||
func TestListByPopularity_EmptyUnionIsNotPublished(t *testing.T) {
|
||||
f := newFeedFixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
resp, err := f.svc.ListByPopularity(ctx, 10, f.asOf.Unix(), 10, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("ListByPopularity: %v", err)
|
||||
}
|
||||
if resp.NextOffset != 10 || resp.HasMore {
|
||||
t.Fatalf("next_offset=%d has_more=%v, want 10/false", resp.NextOffset, resp.HasMore)
|
||||
}
|
||||
if f.mr.Exists(f.snapshotKey()) {
|
||||
t.Fatal("空并集不得发布成快照")
|
||||
}
|
||||
}
|
||||
|
||||
// EXPIRE 失败时 dest 会继承临时键的 1 分钟 TTL:第 2 页因此重建快照、
|
||||
// 客户端重置。宁可删掉让下一次请求干净重建。
|
||||
type failExpireOnPrefixHook struct {
|
||||
prefix string
|
||||
}
|
||||
|
||||
func (h *failExpireOnPrefixHook) DialHook(next goredis.DialHook) goredis.DialHook { return next }
|
||||
|
||||
func (h *failExpireOnPrefixHook) ProcessHook(next goredis.ProcessHook) goredis.ProcessHook {
|
||||
return func(ctx context.Context, cmd goredis.Cmder) error {
|
||||
if strings.EqualFold(cmd.Name(), "expire") && len(cmd.Args()) >= 2 {
|
||||
if key, ok := cmd.Args()[1].(string); ok && strings.HasPrefix(key, h.prefix) {
|
||||
return errors.New("injected expire failure")
|
||||
}
|
||||
}
|
||||
return next(ctx, cmd)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *failExpireOnPrefixHook) ProcessPipelineHook(next goredis.ProcessPipelineHook) goredis.ProcessPipelineHook {
|
||||
return next
|
||||
}
|
||||
|
||||
func TestListByPopularity_SnapshotExpireFailureDropsKey(t *testing.T) {
|
||||
f := newFeedFixture(t, &failExpireOnPrefixHook{
|
||||
prefix: rediscache.NewClient(nil, "test:").Key("hot:video:merge:1m:"),
|
||||
})
|
||||
ctx := context.Background()
|
||||
f.seedHot(t, 1)
|
||||
|
||||
if _, err := f.svc.ListByPopularity(ctx, 10, f.asOf.Unix(), 0, 0); err != nil {
|
||||
t.Fatalf("ListByPopularity: %v", err)
|
||||
}
|
||||
if f.mr.Exists(f.snapshotKey()) {
|
||||
t.Fatal("EXPIRE 失败必须删除快照键:留着它只活 1 分钟,客户端永远翻不到第 2 页")
|
||||
}
|
||||
}
|
||||
|
||||
// 过期的 as_of 与未来的 as_of 都不能被采纳。
|
||||
//
|
||||
// 前者:快照已过 TTL,重建出来是另一个榜,交回同一个 as_of 会让客户端
|
||||
// 以为还能续页。后者:那一分钟还没闭合,窗口仍在增长。
|
||||
func TestListByPopularity_StaleAsOfIsReplaced(t *testing.T) {
|
||||
f := newFeedFixture(t)
|
||||
ctx := context.Background()
|
||||
f.seedHot(t, 1)
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
asOf int64
|
||||
}{
|
||||
{name: "超出快照 TTL", asOf: f.asOf.Add(-3 * time.Hour).Unix()},
|
||||
{name: "未来分钟", asOf: time.Now().UTC().Add(10 * time.Minute).Unix()},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
resp, err := f.svc.ListByPopularity(ctx, 10, c.asOf, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("ListByPopularity: %v", err)
|
||||
}
|
||||
if want := f.asOf.Unix(); resp.AsOf != want {
|
||||
t.Fatalf("as_of = %d, want %d(不可采纳的 as_of 必须换成上一个闭合分钟)", resp.AsOf, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 非整分钟的 as_of 不是非法输入:截断到整分钟再采纳,由客户端按返回的 as_of 重置。
|
||||
func TestListByPopularity_NonWholeMinuteAsOfIsTruncated(t *testing.T) {
|
||||
f := newFeedFixture(t)
|
||||
ctx := context.Background()
|
||||
f.seedHot(t, 1)
|
||||
|
||||
requested := f.asOf.Add(-5*time.Minute + 30*time.Second)
|
||||
resp, err := f.svc.ListByPopularity(ctx, 10, requested.Unix(), 0, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("ListByPopularity: %v", err)
|
||||
}
|
||||
if want := f.asOf.Add(-5 * time.Minute).Unix(); resp.AsOf != want {
|
||||
t.Fatalf("as_of = %d, want %d(非整分钟必须先截断再采纳,不是退回默认值)",
|
||||
resp.AsOf, want)
|
||||
}
|
||||
}
|
||||
|
||||
// 负 offset 是非法游标,必须在读路径入口夹到 0。
|
||||
//
|
||||
// 不夹的话它一路走到 SQL:GORM 把 -1 绑成 OFFSET 的参数,MySQL 抛
|
||||
// Error 1690(signed integer value is out of range in 'mysqld_stmt_execute'),
|
||||
// 接口从"翻到头了"变成 500。
|
||||
func TestListByPopularity_NegativeOffsetIsClamped(t *testing.T) {
|
||||
f := newFeedFixture(t)
|
||||
f.seedHot(t, 2)
|
||||
|
||||
// cache 为 nil:强制走 DB 窗口,offset 直接进 SQL,不经过 Redis 分页。
|
||||
svc := NewFeedService(NewFeedRepository(f.db), video.NewLikeRepository(f.db), nil)
|
||||
ctx := context.Background()
|
||||
|
||||
first, err := svc.ListByPopularity(ctx, 10, 0, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("offset=0: %v", err)
|
||||
}
|
||||
got, err := svc.ListByPopularity(ctx, 10, 0, -1, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("offset=-1 应当夹到 0,却返回错误: %v", err)
|
||||
}
|
||||
if len(got.VideoList) != len(first.VideoList) {
|
||||
t.Fatalf("offset=-1 返回 %d 条,offset=0 返回 %d 条:负游标没有被夹到 0",
|
||||
len(got.VideoList), len(first.VideoList))
|
||||
}
|
||||
}
|
||||
85
backend/internal/feed/service_test.go
Normal file
85
backend/internal/feed/service_test.go
Normal file
@@ -0,0 +1,85 @@
|
||||
package feed
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// 窗口右端必须是"已闭合的分钟":当前这一分钟还在增长,拿它当右端
|
||||
// 会让同一个 as_of 的榜在翻页过程中自己变大(N6)。
|
||||
func TestLastClosedMinute_NeverReturnsOpenMinute(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
now time.Time
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "分钟内",
|
||||
now: time.Date(2026, 3, 4, 5, 6, 7, 900_000_000, time.FixedZone("UTC+8", 8*3600)),
|
||||
want: "2026-03-03T21:05:00Z",
|
||||
},
|
||||
{
|
||||
name: "整分边界",
|
||||
now: time.Date(2026, 3, 4, 12, 0, 0, 0, time.UTC),
|
||||
want: "2026-03-04T11:59:00Z",
|
||||
},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
got := lastClosedMinute(c.now)
|
||||
if want := mustParse(t, c.want); !got.Equal(want) {
|
||||
t.Fatalf("lastClosedMinute(%v) = %v, want %v", c.now, got.Format(time.RFC3339), c.want)
|
||||
}
|
||||
if got.Location() != time.UTC {
|
||||
t.Fatalf("location = %v, want UTC(桶名按 UTC 编码)", got.Location())
|
||||
}
|
||||
if !got.Before(c.now.UTC().Truncate(time.Minute)) {
|
||||
t.Fatalf("返回值 %v 不早于当前分钟:开放分钟不能当窗口右端", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 窗口必须正好覆盖 60 个分钟桶:少一个就漏掉最老的桶,多一个就跨出滑窗。
|
||||
func TestHotWindowBounds_Covers60Buckets(t *testing.T) {
|
||||
asOf := mustParse(t, "2026-03-04T12:05:00Z")
|
||||
from, to := hotWindowBounds(asOf)
|
||||
|
||||
if !to.Equal(asOf.Add(time.Minute)) {
|
||||
t.Fatalf("to = %v, want asOf+1m(右端开区间)", to)
|
||||
}
|
||||
if !from.Equal(asOf.Add(-59 * time.Minute)) {
|
||||
t.Fatalf("from = %v, want asOf-59m", from)
|
||||
}
|
||||
|
||||
var buckets int
|
||||
for m := from; m.Before(to); m = m.Add(time.Minute) {
|
||||
buckets++
|
||||
}
|
||||
if buckets != 60 {
|
||||
t.Fatalf("窗口内分钟桶 = %d, want 60", buckets)
|
||||
}
|
||||
}
|
||||
|
||||
// 补零的 member 与旧实现的十进制 member 都要能读:上线时旧键还在。
|
||||
func TestParseHotMembers_TolerantToPaddingAndGarbage(t *testing.T) {
|
||||
got := parseHotMembers([]string{"000000000007", "42", "0", "abc", "", "-1"})
|
||||
want := []uint{7, 42}
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("parseHotMembers = %v, want %v", got, want)
|
||||
}
|
||||
for i := range want {
|
||||
if got[i] != want[i] {
|
||||
t.Fatalf("parseHotMembers = %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func mustParse(t *testing.T, s string) time.Time {
|
||||
t.Helper()
|
||||
parsed, err := time.Parse(time.RFC3339, s)
|
||||
if err != nil {
|
||||
t.Fatalf("parse %q: %v", s, err)
|
||||
}
|
||||
return parsed
|
||||
}
|
||||
@@ -13,20 +13,43 @@ import (
|
||||
"feedsystem_video_go/internal/video"
|
||||
"feedsystem_video_go/internal/worker"
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func SetRouter(db *gorm.DB, cache *rediscache.Client, rmq *rabbitmq.RabbitMQ) *gin.Engine {
|
||||
// SetRouter 只装配 HTTP 入口;ctx 是进程生命周期,订阅器与 SSE 连接随它退出。
|
||||
func SetRouter(ctx context.Context, db *gorm.DB, cache *rediscache.Client, rmq *rabbitmq.RabbitMQ) *gin.Engine {
|
||||
r := gin.Default()
|
||||
if err := r.SetTrustedProxies(nil); err != nil {
|
||||
log.Printf("SetTrustedProxies failed: %v", err)
|
||||
}
|
||||
// /healthz 只表示"进程存活",永远 200。
|
||||
r.GET("/healthz", func(c *gin.Context) {
|
||||
c.JSON(200, gin.H{"status": "ok"})
|
||||
})
|
||||
// /readyz 表示"依赖就绪",MQ 断连时返回 503(P0-2 配套的可观测性)。
|
||||
//
|
||||
// 刻意与 /healthz 分开:broker 故障期间 API 本身仍然是可用的——写路径有
|
||||
// "MQ 发布失败则直写 DB"的降级,读路径不依赖 MQ。若把 MQ 状态塞进 /healthz
|
||||
// 并返回非 200,容器编排/负载均衡可能把仍然健康的实例反复重启或摘除,把
|
||||
// "异步能力降级"放大成"整站不可用"。故障可见 ≠ 故障致命,两者的处置通道必须分开。
|
||||
r.GET("/readyz", func(c *gin.Context) {
|
||||
st := rmq.Stats() // nil 接收者安全:返回零值
|
||||
status := http.StatusOK
|
||||
if !st.Connected {
|
||||
status = http.StatusServiceUnavailable
|
||||
}
|
||||
c.JSON(status, gin.H{
|
||||
"mq_enabled": rmq != nil, // 区分"未启用 MQ"与"已启用但当前断开"
|
||||
"mq_connected": st.Connected,
|
||||
"mq_generation": st.Generation,
|
||||
"mq_reconnects": st.Reconnects,
|
||||
"mq_topology": st.Topology,
|
||||
})
|
||||
})
|
||||
r.Static("/static", "./.run/uploads")
|
||||
// rate_limit
|
||||
loginLimiter := ratelimit.Limit(cache, "account_login", 10, time.Minute, ratelimit.KeyByIP)
|
||||
@@ -59,12 +82,7 @@ func SetRouter(db *gorm.DB, cache *rediscache.Client, rmq *rabbitmq.RabbitMQ) *g
|
||||
}
|
||||
// video
|
||||
videoRepository := video.NewVideoRepository(db)
|
||||
popularityMQ, err := rabbitmq.NewPopularityMQ(rmq)
|
||||
if err != nil {
|
||||
log.Printf("PopularityMQ init failed (mq disabled): %v", err)
|
||||
popularityMQ = nil
|
||||
}
|
||||
videoService := video.NewVideoService(videoRepository, cache, popularityMQ)
|
||||
videoService := video.NewVideoService(videoRepository, cache)
|
||||
videoHandler := video.NewVideoHandler(videoService, accountService)
|
||||
chunkHandler := video.NewChunkUploadHandler(cache)
|
||||
videoGroup := r.Group("/video")
|
||||
@@ -90,7 +108,7 @@ func SetRouter(db *gorm.DB, cache *rediscache.Client, rmq *rabbitmq.RabbitMQ) *g
|
||||
likeMQ = nil
|
||||
}
|
||||
likeRepository := video.NewLikeRepository(db)
|
||||
likeService := video.NewLikeService(likeRepository, videoRepository, cache, likeMQ, popularityMQ)
|
||||
likeService := video.NewLikeService(likeRepository, videoRepository, cache, likeMQ)
|
||||
likeHandler := video.NewLikeHandler(likeService)
|
||||
likeGroup := r.Group("/like")
|
||||
protectedLikeGroup := likeGroup.Group("")
|
||||
@@ -108,7 +126,7 @@ func SetRouter(db *gorm.DB, cache *rediscache.Client, rmq *rabbitmq.RabbitMQ) *g
|
||||
log.Printf("CommentMQ init failed (mq disabled): %v", err)
|
||||
commentMQ = nil
|
||||
}
|
||||
commentService := video.NewCommentService(commentRepository, videoRepository, cache, commentMQ, popularityMQ)
|
||||
commentService := video.NewCommentService(commentRepository, videoRepository, cache, commentMQ)
|
||||
commentHandler := video.NewCommentHandler(commentService, accountService)
|
||||
commentGroup := r.Group("/comment")
|
||||
{
|
||||
@@ -194,62 +212,23 @@ func SetRouter(db *gorm.DB, cache *rediscache.Client, rmq *rabbitmq.RabbitMQ) *g
|
||||
protectedMessageGroup.POST("/send", messageHandler.Send)
|
||||
protectedMessageGroup.POST("/list", messageHandler.List)
|
||||
}
|
||||
//worker
|
||||
timelineMQ, err := rabbitmq.NewTimelineMQ(rmq)
|
||||
if err != nil {
|
||||
log.Printf("timelineMQ init failed (mq disabled): %v", err)
|
||||
timelineMQ = nil
|
||||
}
|
||||
worker.StartOutboxPoller(db, timelineMQ)
|
||||
worker.StartConsumer(timelineMQ, "video.timeline.update.queue", cache, rmq)
|
||||
|
||||
// SSE notification
|
||||
if rmq != nil {
|
||||
if notifCh, err := rmq.NewChannel(); err == nil {
|
||||
if err := rabbitmq.DeclareTopic(notifCh, "like.events", "notification.like", "like.like"); err != nil {
|
||||
log.Printf("notification like topic init failed: %v", err)
|
||||
}
|
||||
if err := rabbitmq.DeclareTopic(notifCh, "comment.events", "notification.comment", "comment.publish"); err != nil {
|
||||
log.Printf("notification comment topic init failed: %v", err)
|
||||
}
|
||||
if err := rabbitmq.DeclareTopic(notifCh, "social.events", "notification.social", "social.follow"); err != nil {
|
||||
log.Printf("notification social topic init failed: %v", err)
|
||||
}
|
||||
notifCh.Close()
|
||||
}
|
||||
}
|
||||
sseHub := worker.NewSSEHub(db)
|
||||
// 通知由 Worker 落库并发布到 Redis,本进程只把它推给本地连接。
|
||||
sseHub := worker.NewSSEHub(ctx, db)
|
||||
notifGroup := r.Group("/notification")
|
||||
notifGroup.Use(sseHub.SSERequireAuth())
|
||||
sseHub.RegisterRoutes(r, notifGroup)
|
||||
worker.StartNotificationSubscriber(ctx, cache, sseHub)
|
||||
|
||||
go func() {
|
||||
if rmq != nil {
|
||||
hub := sseHub
|
||||
ctx := context.Background()
|
||||
// 每个 notification worker 独立 Channel + 自动重连
|
||||
for _, q := range []string{"notification.like", "notification.comment", "notification.social"} {
|
||||
go func(queue string) {
|
||||
for {
|
||||
ch, err := rmq.NewChannel()
|
||||
if err != nil {
|
||||
log.Printf("notification-%s: 创建 Channel 失败: %v, 5秒后重试", queue, err)
|
||||
time.Sleep(5 * time.Second)
|
||||
continue
|
||||
}
|
||||
w := worker.NewNotificationWorker(ch, db, queue, hub)
|
||||
if err := w.Run(ctx); err != nil {
|
||||
log.Printf("notification-%s: %v, 5秒后重连...", queue, err)
|
||||
}
|
||||
ch.Close()
|
||||
time.Sleep(5 * time.Second)
|
||||
}
|
||||
}(q)
|
||||
}
|
||||
} else {
|
||||
log.Printf("Notification SSE disabled (MQ not available)")
|
||||
// 所有 publisher / consumer 都已登记拓扑:在【当前】连接上立即声明一遍。
|
||||
// 重连时管理器会自动重放,因此这里只需处理"首次连接早于拓扑登记"的启动顺序。
|
||||
// 用带超时的 ctx,避免连接恰在此刻断开时把 API 启动挂住。
|
||||
if rmq != nil {
|
||||
initCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
if err := rmq.EnsureTopology(initCtx); err != nil {
|
||||
log.Printf("rabbitmq topology init failed (will be redeclared on reconnect): %v", err)
|
||||
}
|
||||
}()
|
||||
cancel()
|
||||
}
|
||||
|
||||
return r
|
||||
}
|
||||
|
||||
106
backend/internal/http/router_test.go
Normal file
106
backend/internal/http/router_test.go
Normal file
@@ -0,0 +1,106 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"feedsystem_video_go/internal/config"
|
||||
mqrabbit "feedsystem_video_go/internal/middleware/rabbitmq"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func doGet(t *testing.T, r *gin.Engine, path string) (int, map[string]any) {
|
||||
t.Helper()
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil))
|
||||
|
||||
var body map[string]any
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
|
||||
t.Fatalf("%s: cannot parse body %q: %v", path, w.Body.String(), err)
|
||||
}
|
||||
return w.Code, body
|
||||
}
|
||||
|
||||
func newRouterForTest(t *testing.T, rmq *mqrabbit.RabbitMQ) *gin.Engine {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
return SetRouter(context.Background(), nil, nil, rmq)
|
||||
}
|
||||
|
||||
// 消费者搬到 Worker 之后,SSE 与列表/已读接口仍必须留在 API。
|
||||
func TestRouter_NotificationRoutesRegistered(t *testing.T) {
|
||||
r := newRouterForTest(t, nil)
|
||||
|
||||
want := []string{
|
||||
"GET /notification/stream",
|
||||
"POST /notification/list",
|
||||
"POST /notification/markRead",
|
||||
"POST /notification/unreadCount",
|
||||
}
|
||||
registered := make(map[string]bool, len(want))
|
||||
for _, route := range r.Routes() {
|
||||
registered[route.Method+" "+route.Path] = true
|
||||
}
|
||||
for _, route := range want {
|
||||
if !registered[route] {
|
||||
t.Errorf("route %q is not registered", route)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 这是 /readyz 存在的全部意义所在,也是最容易被后人"顺手合并"掉的不变式:
|
||||
// MQ 断连时 /healthz 必须仍然是 200,否则容器编排会在 broker 故障期间反复重启
|
||||
// 仍然健康的实例,把"异步能力降级"放大成"整站不可用"。
|
||||
func TestReadyz_MQDisabled_HealthzStaysOK(t *testing.T) {
|
||||
r := newRouterForTest(t, nil)
|
||||
|
||||
code, body := doGet(t, r, "/healthz")
|
||||
if code != http.StatusOK {
|
||||
t.Fatalf("/healthz must stay 200 regardless of MQ state, got %d (%v)", code, body)
|
||||
}
|
||||
|
||||
code, body = doGet(t, r, "/readyz")
|
||||
if code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("/readyz must be 503 when MQ is not connected, got %d (%v)", code, body)
|
||||
}
|
||||
if body["mq_enabled"] != false || body["mq_connected"] != false {
|
||||
t.Fatalf("disabled MQ must report mq_enabled=false, mq_connected=false: %v", body)
|
||||
}
|
||||
}
|
||||
|
||||
// "已启用但当前断开"必须与"根本没启用"可区分——两者的处置动作完全不同。
|
||||
//
|
||||
// 注意本用例约需 5 秒:SetRouter 末尾的启动期 EnsureTopology 有 5 秒超时
|
||||
// (避免连接恰在启动时断开把 API 启动挂住),而这里的管理器连不上,
|
||||
// 因此会等满这 5 秒。这 5 秒本身就是该护栏生效的证据,不要为此改短生产超时。
|
||||
func TestReadyz_MQEnabledButDisconnected_IsDistinguishable(t *testing.T) {
|
||||
// 指向必然连不上的端口:管理器会持续重连,当前状态即"已启用、未连接"。
|
||||
mgr := mqrabbit.NewRabbitMQLazy(&config.RabbitMQConfig{
|
||||
Host: "127.0.0.1", Port: 1, Username: "u", Password: "p",
|
||||
})
|
||||
if mgr == nil {
|
||||
t.Fatal("lazy manager must not be nil for a valid config")
|
||||
}
|
||||
t.Cleanup(func() { _ = mgr.Close() })
|
||||
|
||||
r := newRouterForTest(t, mgr)
|
||||
|
||||
if code, _ := doGet(t, r, "/healthz"); code != http.StatusOK {
|
||||
t.Fatalf("/healthz must stay 200 while MQ is down, got %d", code)
|
||||
}
|
||||
|
||||
code, body := doGet(t, r, "/readyz")
|
||||
if code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("/readyz must be 503 while disconnected, got %d (%v)", code, body)
|
||||
}
|
||||
if body["mq_enabled"] != true {
|
||||
t.Fatalf("mq_enabled must distinguish disabled from disconnected: %v", body)
|
||||
}
|
||||
if body["mq_reconnects"] != float64(0) {
|
||||
t.Fatalf("a manager that never connected must report 0 reconnects: %v", body)
|
||||
}
|
||||
}
|
||||
@@ -4,21 +4,20 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
)
|
||||
|
||||
// CommentMQ 通过连接管理器发布评论事件。
|
||||
type CommentMQ struct {
|
||||
ch *amqp.Channel
|
||||
mgr *RabbitMQ
|
||||
}
|
||||
|
||||
const (
|
||||
commentExchange = "comment.events"
|
||||
commentQueue = "comment.events"
|
||||
commentBindingKey = "comment.*"
|
||||
CommentExchange = "comment.events"
|
||||
CommentQueue = "comment.events"
|
||||
CommentBindingKey = "comment.*"
|
||||
|
||||
commentPublishRK = "comment.publish"
|
||||
commentDeleteRK = "comment.delete"
|
||||
CommentPublishRK = "comment.publish"
|
||||
CommentDeleteRK = "comment.delete"
|
||||
)
|
||||
|
||||
type CommentEvent struct {
|
||||
@@ -36,42 +35,34 @@ func NewCommentMQ(base *RabbitMQ) (*CommentMQ, error) {
|
||||
if base == nil {
|
||||
return nil, errors.New("rabbitmq base is nil")
|
||||
}
|
||||
ch, err := base.NewChannel()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := DeclareTopic(ch, commentExchange, commentQueue, commentBindingKey); err != nil {
|
||||
ch.Close()
|
||||
return nil, err
|
||||
}
|
||||
return &CommentMQ{ch: ch}, nil
|
||||
base.RegisterTopology(Topology{Exchange: CommentExchange, Queue: CommentQueue, BindingKey: CommentBindingKey})
|
||||
return &CommentMQ{mgr: base}, nil
|
||||
}
|
||||
|
||||
func (c *CommentMQ) Publish(ctx context.Context, username string, videoID, authorID uint, content string) error {
|
||||
return c.publish(ctx, "publish", commentPublishRK, CommentEvent{
|
||||
Username: username,
|
||||
VideoID: videoID,
|
||||
AuthorID: authorID,
|
||||
Content: content,
|
||||
})
|
||||
// Publish 接收完整事件;EventID 由调用方生成,仅为空时补一个随机值。
|
||||
func (c *CommentMQ) Publish(ctx context.Context, evt CommentEvent) error {
|
||||
return c.publish(ctx, "publish", CommentPublishRK, evt)
|
||||
}
|
||||
|
||||
func (c *CommentMQ) Delete(ctx context.Context, commentID uint) error {
|
||||
return c.publish(ctx, "delete", commentDeleteRK, CommentEvent{
|
||||
func (c *CommentMQ) Delete(ctx context.Context, commentID uint, intentKey string) error {
|
||||
return c.publish(ctx, "delete", CommentDeleteRK, CommentEvent{
|
||||
CommentID: commentID,
|
||||
EventID: intentKey,
|
||||
})
|
||||
}
|
||||
|
||||
func (c *CommentMQ) publish(ctx context.Context, action, routingKey string, evt CommentEvent) error {
|
||||
if c == nil || c.ch == nil {
|
||||
if c == nil || c.mgr == nil {
|
||||
return errors.New("comment mq is not initialized")
|
||||
}
|
||||
id, err := newEventID(16)
|
||||
if err != nil {
|
||||
return err
|
||||
if evt.EventID == "" {
|
||||
id, err := newEventID(16)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
evt.EventID = id
|
||||
}
|
||||
evt.EventID = id
|
||||
evt.Action = action
|
||||
evt.OccurredAt = time.Now().UTC()
|
||||
return PublishJSON(ctx, c.ch, commentExchange, routingKey, evt)
|
||||
return c.mgr.PublishJSON(ctx, CommentExchange, routingKey, evt)
|
||||
}
|
||||
|
||||
55
backend/internal/middleware/rabbitmq/constants_test.go
Normal file
55
backend/internal/middleware/rabbitmq/constants_test.go
Normal file
@@ -0,0 +1,55 @@
|
||||
package rabbitmq
|
||||
|
||||
import "testing"
|
||||
|
||||
// TestTopologyConstants_WireNamesAreStable 锁定 broker 侧的"线缆名称"。
|
||||
//
|
||||
// 这些字符串是运行中集群里的持久实体名:改名等于新开一套交换机/队列,
|
||||
// 旧队列里的消息与消费者会静默失联。导出给 cmd/worker 与 http 层复用之后,
|
||||
// 重命名变得更容易,所以用一条测试把值钉住——改名必须是一次有意的、
|
||||
// 带迁移的动作,而不是顺手"整理命名"。
|
||||
func TestTopologyConstants_WireNamesAreStable(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
got string
|
||||
want string
|
||||
}{
|
||||
{"LikeExchange", LikeExchange, "like.events"},
|
||||
{"LikeQueue", LikeQueue, "like.events"},
|
||||
{"LikeBindingKey", LikeBindingKey, "like.*"},
|
||||
{"LikeLikeRK", LikeLikeRK, "like.like"},
|
||||
{"LikeUnlikeRK", LikeUnlikeRK, "like.unlike"},
|
||||
|
||||
{"CommentExchange", CommentExchange, "comment.events"},
|
||||
{"CommentQueue", CommentQueue, "comment.events"},
|
||||
{"CommentBindingKey", CommentBindingKey, "comment.*"},
|
||||
{"CommentPublishRK", CommentPublishRK, "comment.publish"},
|
||||
{"CommentDeleteRK", CommentDeleteRK, "comment.delete"},
|
||||
|
||||
{"SocialExchange", SocialExchange, "social.events"},
|
||||
{"SocialFollowRK", SocialFollowRK, "social.follow"},
|
||||
|
||||
{"TimelineExchange", TimelineExchange, "video.timeline.events"},
|
||||
{"TimelineQueue", TimelineQueue, "video.timeline.update.queue"},
|
||||
{"TimelineBindingKey", TimelineBindingKey, "video.timeline.*"},
|
||||
{"TimelinePublishRK", TimelinePublishRK, "video.timeline.publish"},
|
||||
|
||||
{"NotificationLikeQueue", NotificationLikeQueue, "notification.like"},
|
||||
{"NotificationCommentQueue", NotificationCommentQueue, "notification.comment"},
|
||||
{"NotificationSocialQueue", NotificationSocialQueue, "notification.social"},
|
||||
|
||||
// 停泊链路(批次 0)。failed.events 是运维真正会去查的队列名,
|
||||
// dlx.events 沿用了改造前就存在的名字,因此改名同样等同于一次迁移。
|
||||
{"DLXExchange", DLXExchange, "dlx.events"},
|
||||
{"ParkedQueue", ParkedQueue, "failed.events"},
|
||||
{"ParkedKeyPrefix", ParkedKeyPrefix, "parked."},
|
||||
// 重试链路(批次 2 启用,但名字属于线缆契约,与常量同批锁定)。
|
||||
{"RetryExchangePrefix", RetryExchangePrefix, "retry.events."},
|
||||
{"RetryQueueSuffix", RetryQueueSuffix, ".retry"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if c.got != c.want {
|
||||
t.Errorf("%s = %q, want %q(broker 线缆契约被改动,需配套迁移)", c.name, c.got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
287
backend/internal/middleware/rabbitmq/consume_test.go
Normal file
287
backend/internal/middleware/rabbitmq/consume_test.go
Normal file
@@ -0,0 +1,287 @@
|
||||
package rabbitmq
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
)
|
||||
|
||||
// ackAction 记录一次 Ack/Nack/Reject,用于断言"消息到底被怎么处置了"。
|
||||
type ackAction struct {
|
||||
nack bool
|
||||
requeue bool
|
||||
}
|
||||
|
||||
type fakeAcknowledger struct {
|
||||
acks int
|
||||
action []ackAction
|
||||
}
|
||||
|
||||
func (a *fakeAcknowledger) Ack(uint64, bool) error {
|
||||
a.acks++
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *fakeAcknowledger) Nack(_ uint64, _, requeue bool) error {
|
||||
a.action = append(a.action, ackAction{nack: true, requeue: requeue})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *fakeAcknowledger) Reject(_ uint64, requeue bool) error {
|
||||
a.action = append(a.action, ackAction{nack: true, requeue: requeue})
|
||||
return nil
|
||||
}
|
||||
|
||||
// deliveryWith 构造一条被拒绝过 retryCount 次的投递:x-death 里只有一条
|
||||
// rejected 记录,足够驱动 GetRetryCount。
|
||||
func deliveryWith(acks *fakeAcknowledger, retryCount int) amqp.Delivery {
|
||||
d := amqp.Delivery{Acknowledger: acks, DeliveryTag: 1, RoutingKey: "like.like"}
|
||||
if retryCount > 0 {
|
||||
d.Headers = amqp.Table{
|
||||
"x-death": []interface{}{
|
||||
amqp.Table{"reason": "rejected", "count": int64(retryCount)},
|
||||
},
|
||||
}
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
type fakeParker struct {
|
||||
calls int
|
||||
queue string
|
||||
attempt int
|
||||
cause error
|
||||
err error
|
||||
}
|
||||
|
||||
func (p *fakeParker) Park(_ context.Context, sourceQueue string, _ amqp.Delivery, attempts int, cause error) error {
|
||||
p.calls++
|
||||
p.queue = sourceQueue
|
||||
p.attempt = attempts
|
||||
p.cause = cause
|
||||
return p.err
|
||||
}
|
||||
|
||||
func withShortParkBackoff(t *testing.T) {
|
||||
t.Helper()
|
||||
old := parkRequeueBackoff
|
||||
parkRequeueBackoff = 10 * time.Millisecond
|
||||
t.Cleanup(func() { parkRequeueBackoff = old })
|
||||
}
|
||||
|
||||
func TestDecide_Table(t *testing.T) {
|
||||
acks := &fakeAcknowledger{}
|
||||
boom := errors.New("db down")
|
||||
cases := []struct {
|
||||
name string
|
||||
err error
|
||||
retryCount int
|
||||
maxAttempts int
|
||||
want Disposition
|
||||
}{
|
||||
{name: "成功即 Ack", err: nil, retryCount: 3, maxAttempts: 4, want: DispositionAck},
|
||||
{name: "首次失败且可重试", err: boom, retryCount: 0, maxAttempts: 4, want: DispositionRetry},
|
||||
{name: "第二次失败仍可重试", err: boom, retryCount: 1, maxAttempts: 4, want: DispositionRetry},
|
||||
{name: "第三次失败仍可重试", err: boom, retryCount: 2, maxAttempts: 4, want: DispositionRetry},
|
||||
// 首次 + 3 次重试 = 4 次尝试,与改造前的 for i := 0; i <= 3 等价。
|
||||
{name: "第四次失败耗尽预算", err: boom, retryCount: 3, maxAttempts: 4, want: DispositionPark},
|
||||
{name: "永久错误立即停泊", err: Permanent(boom), retryCount: 0, maxAttempts: 4, want: DispositionPark},
|
||||
{name: "永久错误即使已重试也停泊", err: Permanent(boom), retryCount: 2, maxAttempts: 4, want: DispositionPark},
|
||||
{name: "零预算时首次失败即停泊", err: boom, retryCount: 0, maxAttempts: 1, want: DispositionPark},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
d := deliveryWith(acks, tc.retryCount)
|
||||
if got := Decide(d, tc.maxAttempts, tc.err); got != tc.want {
|
||||
t.Fatalf("Decide() = %v, want %v", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 安全网:一条被 requeue 回来的消息可能已经超过预算(上一轮停泊失败),
|
||||
// 此时无论下一个错误是什么都不该再重试。
|
||||
func TestExhausted_SafetyNet(t *testing.T) {
|
||||
acks := &fakeAcknowledger{}
|
||||
if Exhausted(deliveryWith(acks, 2), 4) {
|
||||
t.Fatal("3 次尝试(retry=2)不应判定为耗尽")
|
||||
}
|
||||
if !Exhausted(deliveryWith(acks, 3), 4) {
|
||||
t.Fatal("4 次尝试(retry=3)应判定为耗尽")
|
||||
}
|
||||
if !Exhausted(deliveryWith(acks, 99), 4) {
|
||||
t.Fatal("超过预算的消息必须判定为耗尽")
|
||||
}
|
||||
if Exhausted(deliveryWith(acks, 0), 0) {
|
||||
t.Fatal("maxAttempts<=0 时应回退到 MaxAttempts,首次失败必须仍可重试")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPermanent_MarksAndDetects(t *testing.T) {
|
||||
boom := errors.New("bad body")
|
||||
if IsPermanent(boom) {
|
||||
t.Fatal("普通错误不应被判为永久错误")
|
||||
}
|
||||
marked := Permanent(boom)
|
||||
if !IsPermanent(marked) {
|
||||
t.Fatal("Permanent 标记后应被识别")
|
||||
}
|
||||
if !errors.Is(marked, boom) {
|
||||
t.Fatal("标记后必须仍能用 errors.Is 找到原始错误")
|
||||
}
|
||||
if Permanent(nil) != nil {
|
||||
t.Fatal("Permanent(nil) 必须是 nil,否则成功路径会被误判为失败")
|
||||
}
|
||||
if twice := Permanent(marked); twice != marked {
|
||||
t.Fatal("重复标记不应再包一层")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleOne_AcksOnSuccess(t *testing.T) {
|
||||
acks := &fakeAcknowledger{}
|
||||
parker := &fakeParker{}
|
||||
handleOne(context.Background(), parker, "like.events", 4, deliveryWith(acks, 0),
|
||||
func(context.Context, amqp.Delivery) error { return nil })
|
||||
|
||||
if acks.acks != 1 || len(acks.action) != 0 || parker.calls != 0 {
|
||||
t.Fatalf("成功应只 Ack:acks=%d actions=%v park=%d", acks.acks, acks.action, parker.calls)
|
||||
}
|
||||
}
|
||||
|
||||
// 可重试失败必须 Nack(requeue=false):requeue=true 会立刻重投,等于没有退避,
|
||||
// 而 requeue=false 才会让消息进入重试队列并吃 TTL。
|
||||
func TestHandleOne_RetryNacksWithoutRequeue(t *testing.T) {
|
||||
acks := &fakeAcknowledger{}
|
||||
parker := &fakeParker{}
|
||||
boom := errors.New("db down")
|
||||
handleOne(context.Background(), parker, "like.events", 4, deliveryWith(acks, 0),
|
||||
func(context.Context, amqp.Delivery) error { return boom })
|
||||
|
||||
if acks.acks != 0 {
|
||||
t.Fatal("可重试失败不能 Ack(Ack 就是丢弃)")
|
||||
}
|
||||
if len(acks.action) != 1 || acks.action[0].requeue {
|
||||
t.Fatalf("应 Nack(requeue=false),实际 %v", acks.action)
|
||||
}
|
||||
if parker.calls != 0 {
|
||||
t.Fatal("预算未用尽时不应停泊")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleOne_ParksWhenBudgetUsed(t *testing.T) {
|
||||
withShortParkBackoff(t)
|
||||
acks := &fakeAcknowledger{}
|
||||
parker := &fakeParker{}
|
||||
boom := errors.New("db down")
|
||||
handleOne(context.Background(), parker, "like.events", 4, deliveryWith(acks, 3),
|
||||
func(context.Context, amqp.Delivery) error { return boom })
|
||||
|
||||
if parker.calls != 1 {
|
||||
t.Fatalf("预算用尽应停泊一次,实际 %d", parker.calls)
|
||||
}
|
||||
if parker.queue != "like.events" || parker.attempt != 4 {
|
||||
t.Fatalf("停泊信息错误:queue=%q attempts=%d", parker.queue, parker.attempt)
|
||||
}
|
||||
if acks.acks != 1 || len(acks.action) != 0 {
|
||||
t.Fatalf("停泊成功后应 Ack 原消息:acks=%d actions=%v", acks.acks, acks.action)
|
||||
}
|
||||
}
|
||||
|
||||
// 不可重试的消息第一次失败就停泊,attempts 必须是 1(它没有浪费重试预算)。
|
||||
func TestHandleOne_PermanentParksImmediately(t *testing.T) {
|
||||
withShortParkBackoff(t)
|
||||
acks := &fakeAcknowledger{}
|
||||
parker := &fakeParker{}
|
||||
handleOne(context.Background(), parker, "comment.events", 4, deliveryWith(acks, 0),
|
||||
func(context.Context, amqp.Delivery) error { return Permanent(errors.New("bad json")) })
|
||||
|
||||
if parker.calls != 1 || parker.attempt != 1 {
|
||||
t.Fatalf("永久错误应立即停泊且 attempts=1,实际 calls=%d attempts=%d", parker.calls, parker.attempt)
|
||||
}
|
||||
if acks.acks != 1 {
|
||||
t.Fatal("停泊成功后必须 Ack")
|
||||
}
|
||||
}
|
||||
|
||||
// 停泊失败必须 requeue,且先退避:停泊链路的故障会让 Park 快速失败,
|
||||
// 不退避就是一个热循环。
|
||||
func TestParkOrRequeue_ParkFailureRequeues(t *testing.T) {
|
||||
withShortParkBackoff(t)
|
||||
acks := &fakeAcknowledger{}
|
||||
parker := &fakeParker{err: errors.New("queue not found")}
|
||||
|
||||
start := time.Now()
|
||||
parkOrRequeue(context.Background(), parker, "like.events", deliveryWith(acks, 3), 4, errors.New("db down"))
|
||||
elapsed := time.Since(start)
|
||||
|
||||
if acks.acks != 0 {
|
||||
t.Fatal("停泊失败时绝不能 Ack(那等于丢弃)")
|
||||
}
|
||||
if len(acks.action) != 1 || !acks.action[0].requeue {
|
||||
t.Fatalf("停泊失败应 Nack(requeue=true),实际 %v", acks.action)
|
||||
}
|
||||
if elapsed < parkRequeueBackoff {
|
||||
t.Fatalf("requeue 之前必须退避:elapsed=%v backoff=%v", elapsed, parkRequeueBackoff)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParkOrRequeue_NoParkerRequeues(t *testing.T) {
|
||||
withShortParkBackoff(t)
|
||||
acks := &fakeAcknowledger{}
|
||||
parkOrRequeue(context.Background(), nil, "like.events", deliveryWith(acks, 3), 4, errors.New("db down"))
|
||||
|
||||
if acks.acks != 0 {
|
||||
t.Fatal("没有 parker 时也不能 Ack")
|
||||
}
|
||||
if len(acks.action) != 1 || !acks.action[0].requeue {
|
||||
t.Fatalf("没有 parker 应 Nack(requeue=true),实际 %v", acks.action)
|
||||
}
|
||||
}
|
||||
|
||||
// 停泊成功必须先确认、后 Ack:这个顺序是"不丢消息"的全部保证。
|
||||
func TestParkOrRequeue_SuccessAcks(t *testing.T) {
|
||||
acks := &fakeAcknowledger{}
|
||||
parker := &fakeParker{}
|
||||
cause := errors.New("db down")
|
||||
parkOrRequeue(context.Background(), parker, "like.events", deliveryWith(acks, 3), 4, cause)
|
||||
|
||||
if parker.calls != 1 {
|
||||
t.Fatalf("应停泊一次,实际 %d", parker.calls)
|
||||
}
|
||||
if parker.cause != cause {
|
||||
t.Fatal("停泊必须带上原始失败原因")
|
||||
}
|
||||
if acks.acks != 1 || len(acks.action) != 0 {
|
||||
t.Fatalf("停泊成功后应 Ack:acks=%d actions=%v", acks.acks, acks.action)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConsumeLoop_RejectsInvalidArguments(t *testing.T) {
|
||||
process := func(context.Context, amqp.Delivery) error { return nil }
|
||||
if err := ConsumeLoop(context.Background(), nil, nil, "q", 4, process); err == nil {
|
||||
t.Fatal("nil channel 必须报错(否则会静默不消费)")
|
||||
}
|
||||
if err := ConsumeLoop(context.Background(), &amqp.Channel{}, nil, "", 4, process); err == nil {
|
||||
t.Fatal("空队列名必须报错")
|
||||
}
|
||||
if err := ConsumeLoop(context.Background(), &amqp.Channel{}, nil, "q", 4, nil); err == nil {
|
||||
t.Fatal("nil process 必须报错")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDisposition_String(t *testing.T) {
|
||||
cases := map[Disposition]string{
|
||||
DispositionAck: "ack",
|
||||
DispositionRetry: "retry",
|
||||
DispositionPark: "park",
|
||||
Disposition(99): "unknown",
|
||||
}
|
||||
for d, want := range cases {
|
||||
if got := d.String(); got != want {
|
||||
t.Fatalf("Disposition(%d).String() = %q, want %q", int(d), got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
104
backend/internal/middleware/rabbitmq/consumer.go
Normal file
104
backend/internal/middleware/rabbitmq/consumer.go
Normal file
@@ -0,0 +1,104 @@
|
||||
package rabbitmq
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
)
|
||||
|
||||
// RunConsumer 在连接管理器上运行一个消费循环。
|
||||
//
|
||||
// 连接断开期间阻塞在 WaitReady;恢复后重建 channel、重设 QoS、重新 Consume。
|
||||
// fn 应在 deliveries channel 关闭或 ctx 取消时返回。
|
||||
func RunConsumer(ctx context.Context, mgr *RabbitMQ, name string, prefetch int, fn func(*amqp.Channel) error) {
|
||||
if mgr == nil {
|
||||
log.Printf("%s: rabbitmq manager is nil, consumer disabled", name)
|
||||
return
|
||||
}
|
||||
if fn == nil {
|
||||
log.Printf("%s: consume func is nil, consumer disabled", name)
|
||||
return
|
||||
}
|
||||
|
||||
opts := mgr.opts
|
||||
backoff := opts.MinBackoff
|
||||
|
||||
// 消费前先确保拓扑存在,覆盖"连接建立早于拓扑登记"的启动顺序。
|
||||
if err := mgr.EnsureTopology(ctx); err != nil && ctx.Err() == nil {
|
||||
log.Printf("%s: 初始拓扑声明失败: %v", name, err)
|
||||
}
|
||||
|
||||
for ctx.Err() == nil {
|
||||
sess, err := mgr.Session(ctx)
|
||||
if err != nil {
|
||||
if ctx.Err() != nil || errors.Is(err, ErrManagerClosed) {
|
||||
return
|
||||
}
|
||||
log.Printf("%s: 获取 channel 失败: %v(%v 后重试)", name, err, backoff)
|
||||
if !sleepCtx(ctx, backoff) {
|
||||
return
|
||||
}
|
||||
backoff = nextBackoff(backoff, opts)
|
||||
continue
|
||||
}
|
||||
|
||||
// QoS 是 channel 级状态,每次重建 channel 后都必须重设。
|
||||
if prefetch > 0 {
|
||||
if err := sess.Ch.Qos(prefetch, 0, false); err != nil {
|
||||
log.Printf("%s: QoS 设置失败: %v", name, err)
|
||||
}
|
||||
}
|
||||
|
||||
log.Printf("%s started, consuming", name)
|
||||
runErr := fn(sess.Ch)
|
||||
_ = sess.Ch.Close()
|
||||
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
|
||||
// 不能只看 sess.Done:库先派发 NotifyClose、后关闭 deliveries,
|
||||
// 那一瞬 sess.Done 往往还没关闭。直接复查连接状态更准确。
|
||||
connLost := false
|
||||
select {
|
||||
case <-sess.Done:
|
||||
connLost = true
|
||||
default:
|
||||
connLost = !mgr.Healthy()
|
||||
}
|
||||
|
||||
if connLost {
|
||||
if err := mgr.WaitReady(ctx); err != nil {
|
||||
return
|
||||
}
|
||||
backoff = opts.MinBackoff
|
||||
continue
|
||||
}
|
||||
|
||||
// 连接仍健康 → channel 级异常(队列或绑定丢失、声明冲突等)
|
||||
if runErr != nil {
|
||||
log.Printf("%s: %v;连接仍健康,重放拓扑后重试", name, runErr)
|
||||
}
|
||||
if err := mgr.EnsureTopology(ctx); err != nil && ctx.Err() == nil {
|
||||
log.Printf("%s: 重放拓扑失败: %v", name, err)
|
||||
}
|
||||
if !sleepCtx(ctx, backoff) {
|
||||
return
|
||||
}
|
||||
backoff = nextBackoff(backoff, opts)
|
||||
}
|
||||
}
|
||||
|
||||
func sleepCtx(ctx context.Context, d time.Duration) bool {
|
||||
t := time.NewTimer(d)
|
||||
defer t.Stop()
|
||||
select {
|
||||
case <-t.C:
|
||||
return true
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -1,53 +1,350 @@
|
||||
package rabbitmq
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
)
|
||||
|
||||
const (
|
||||
DLXExchange = "dlx.events"
|
||||
// DLXExchange 是停泊专用交换机。
|
||||
DLXExchange = "dlx.events"
|
||||
// ParkedQueue 是唯一的停泊队列,由 FailedEventWorker 落库到 failed_events。
|
||||
ParkedQueue = "failed.events"
|
||||
// ParkedKeyPrefix 后接源队列名,构成停泊路由键 parked.<queue>。
|
||||
ParkedKeyPrefix = "parked."
|
||||
// RetryExchangePrefix 让每个业务队列有独立的重试入口。
|
||||
RetryExchangePrefix = "retry.events."
|
||||
// RetryQueueSuffix 让每个业务队列有独立的延迟队列。
|
||||
RetryQueueSuffix = ".retry"
|
||||
|
||||
// MaxRetryCount 与既有行为一致:首次投递 + 3 次重试。
|
||||
MaxRetryCount = 3
|
||||
|
||||
// HeaderSourceQueue 记录消息来自哪个队列。
|
||||
HeaderSourceQueue = "x-vloop-source-queue"
|
||||
// HeaderAttempts 记录停泊时已经用掉的尝试次数。
|
||||
HeaderAttempts = "x-vloop-attempts"
|
||||
// HeaderLastError 记录最后一次失败原因,截断到 512 字节。
|
||||
HeaderLastError = "x-vloop-last-error"
|
||||
|
||||
// parkTimeout 是一次停泊操作的硬上限。
|
||||
parkTimeout = 5 * time.Second
|
||||
)
|
||||
|
||||
// DeclareDLX 声明死信交换机和对应的死信队列
|
||||
func DeclareDLX(ch *amqp.Channel, queueName string) error {
|
||||
if ch == nil {
|
||||
return nil
|
||||
// parkRequeueBackoff 是停泊失败后退回 requeue 之前的退避。
|
||||
//
|
||||
// 变量而非常量:单测把它压到毫秒级,否则"退避确实发生了"这条断言会让每次跑测试多等一秒。
|
||||
var parkRequeueBackoff = time.Second
|
||||
|
||||
// MaxAttempts 是一次投递被允许的最大尝试次数。
|
||||
const MaxAttempts = MaxRetryCount + 1
|
||||
|
||||
// DefaultRetryDelay 是重试队列的队列级 TTL。
|
||||
const DefaultRetryDelay = 5 * time.Second
|
||||
|
||||
// RetryExchange 返回某队列专属的重试交换机名。
|
||||
func RetryExchange(queue string) string { return RetryExchangePrefix + queue }
|
||||
|
||||
// RetryQueueName 返回某队列专属的重试队列名。
|
||||
func RetryQueueName(queue string) string { return queue + RetryQueueSuffix }
|
||||
|
||||
// declareParking 声明停泊链路:DLX 交换机、唯一停泊队列、parked.# 绑定。
|
||||
func declareParking(d declarer) error {
|
||||
if d == nil {
|
||||
return fmt.Errorf("declare park: no declarer")
|
||||
}
|
||||
if err := ch.ExchangeDeclare(
|
||||
DLXExchange, "topic", true, false, false, false, nil,
|
||||
); err != nil {
|
||||
return err
|
||||
if err := d.ExchangeDeclare(DLXExchange, "topic", true, false, false, false, nil); err != nil {
|
||||
return fmt.Errorf("declare park exchange %s: %w", DLXExchange, err)
|
||||
}
|
||||
dlxQueue := queueName + ".dlx"
|
||||
_, err := ch.QueueDeclare(
|
||||
dlxQueue, true, false, false, false, nil, // 死信队列不设置 DLX
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
if _, err := d.QueueDeclare(ParkedQueue, true, false, false, false, nil); err != nil {
|
||||
return fmt.Errorf("declare park queue %s: %w", ParkedQueue, err)
|
||||
}
|
||||
if err := ch.QueueBind(dlxQueue, "#", DLXExchange, false, nil); err != nil {
|
||||
return err
|
||||
if err := d.QueueBind(ParkedQueue, ParkedKeyPrefix+"#", DLXExchange, false, nil); err != nil {
|
||||
return fmt.Errorf("bind park queue %s: %w", ParkedQueue, err)
|
||||
}
|
||||
log.Printf("DLX ready: exchange=%s queue=%s", DLXExchange, dlxQueue)
|
||||
log.Printf("DLX ready: exchange=%s queue=%s", DLXExchange, ParkedQueue)
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetRetryCount 从 AMQP x-death header 中提取当前消息已被重试的次数
|
||||
// RetryArgs 装配业务队列,只把 DLX 指向本队列专属的重试交换机。
|
||||
func RetryArgs(queue string) amqp.Table {
|
||||
return amqp.Table{"x-dead-letter-exchange": RetryExchange(queue)}
|
||||
}
|
||||
|
||||
// RetryQueueArgs 装配重试队列:队列级 TTL,到期经默认交换机精确回源。
|
||||
func RetryQueueArgs(queue string, delay time.Duration) amqp.Table {
|
||||
if delay <= 0 {
|
||||
delay = DefaultRetryDelay
|
||||
}
|
||||
return amqp.Table{
|
||||
"x-message-ttl": int64(delay / time.Millisecond),
|
||||
"x-dead-letter-exchange": "",
|
||||
"x-dead-letter-routing-key": queue,
|
||||
}
|
||||
}
|
||||
|
||||
// GetRetryCount 返回这条消息被拒绝过的次数,只统计 reason == "rejected"。
|
||||
func GetRetryCount(d amqp.Delivery) int {
|
||||
deaths, ok := d.Headers["x-death"].([]interface{})
|
||||
if !ok || len(deaths) == 0 {
|
||||
return 0
|
||||
}
|
||||
death, ok := deaths[0].(amqp.Table)
|
||||
if !ok {
|
||||
return 0
|
||||
}
|
||||
count, ok := death["count"].(int64)
|
||||
if !ok {
|
||||
return 0
|
||||
total := 0
|
||||
for _, raw := range deaths {
|
||||
entry, ok := raw.(amqp.Table)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if reason, _ := entry["reason"].(string); reason != "rejected" {
|
||||
continue
|
||||
}
|
||||
total += intField(entry["count"])
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
||||
// intField 把 AMQP table 里的整数值统一成 int,lib 在不同路径上给出不同宽度。
|
||||
func intField(v any) int {
|
||||
switch n := v.(type) {
|
||||
case int:
|
||||
return n
|
||||
case int32:
|
||||
return int(n)
|
||||
case int64:
|
||||
return int(n)
|
||||
case uint32:
|
||||
return int(n)
|
||||
case uint64:
|
||||
return int(n)
|
||||
case float64:
|
||||
return int(n)
|
||||
default:
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
// ParkedInfo 是一条停泊消息的自描述信息。
|
||||
type ParkedInfo struct {
|
||||
SourceQueue string
|
||||
Attempts int
|
||||
LastError string
|
||||
EventID string
|
||||
}
|
||||
|
||||
// ParseParkedInfo 从停泊消息上还原来源与失败原因,header 缺失时从路由键反推。
|
||||
func ParseParkedInfo(d amqp.Delivery) ParkedInfo {
|
||||
info := ParkedInfo{EventID: EventIDOf(d.Body), Attempts: 1}
|
||||
if d.Headers != nil {
|
||||
info.SourceQueue = stringField(d.Headers[HeaderSourceQueue])
|
||||
if n := intField(d.Headers[HeaderAttempts]); n > 0 {
|
||||
info.Attempts = n
|
||||
}
|
||||
info.LastError = stringField(d.Headers[HeaderLastError])
|
||||
}
|
||||
if info.SourceQueue == "" {
|
||||
info.SourceQueue = sourceQueueFromParkedKey(d.RoutingKey)
|
||||
}
|
||||
return info
|
||||
}
|
||||
|
||||
// EventIDOf 只解析 event_id 一个字段,解析失败返回空串。
|
||||
func EventIDOf(body []byte) string {
|
||||
var probe struct {
|
||||
EventID string `json:"event_id"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &probe); err != nil {
|
||||
return ""
|
||||
}
|
||||
return probe.EventID
|
||||
}
|
||||
|
||||
func stringField(v any) string {
|
||||
if s, ok := v.(string); ok {
|
||||
return s
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func sourceQueueFromParkedKey(key string) string {
|
||||
return strings.TrimPrefix(key, ParkedKeyPrefix)
|
||||
}
|
||||
|
||||
// PermanentError 标记"重试也不会成功"的失败。
|
||||
type PermanentError struct {
|
||||
Err error
|
||||
}
|
||||
|
||||
func (e *PermanentError) Error() string { return e.Err.Error() }
|
||||
|
||||
func (e *PermanentError) Unwrap() error { return e.Err }
|
||||
|
||||
// Permanent 把错误标记为不可重试,nil 原样返回,已标记的不重复包装。
|
||||
func Permanent(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if IsPermanent(err) {
|
||||
return err
|
||||
}
|
||||
return &PermanentError{Err: err}
|
||||
}
|
||||
|
||||
// IsPermanent 判断错误是否被 Permanent 标记过。
|
||||
func IsPermanent(err error) bool {
|
||||
var p *PermanentError
|
||||
return errors.As(err, &p)
|
||||
}
|
||||
|
||||
// Disposition 是一条消息处理完之后该做什么。
|
||||
type Disposition int
|
||||
|
||||
const (
|
||||
// DispositionAck 表示处理成功。
|
||||
DispositionAck Disposition = iota
|
||||
// DispositionRetry 表示可重试失败,交给重试队列。
|
||||
DispositionRetry
|
||||
// DispositionPark 表示预算耗尽或不可重试,落到停泊队列。
|
||||
DispositionPark
|
||||
)
|
||||
|
||||
func (d Disposition) String() string {
|
||||
switch d {
|
||||
case DispositionAck:
|
||||
return "ack"
|
||||
case DispositionRetry:
|
||||
return "retry"
|
||||
case DispositionPark:
|
||||
return "park"
|
||||
default:
|
||||
return "unknown"
|
||||
}
|
||||
}
|
||||
|
||||
// Exhausted 报告这条消息的尝试次数是否已经用完。
|
||||
func Exhausted(d amqp.Delivery, maxAttempts int) bool {
|
||||
if maxAttempts <= 0 {
|
||||
maxAttempts = MaxAttempts
|
||||
}
|
||||
return GetRetryCount(d)+1 >= maxAttempts
|
||||
}
|
||||
|
||||
// Decide 是重试策略的唯一定义点:输入一次处理结果,输出该做什么。
|
||||
func Decide(d amqp.Delivery, maxAttempts int, err error) Disposition {
|
||||
if err == nil {
|
||||
return DispositionAck
|
||||
}
|
||||
if IsPermanent(err) || Exhausted(d, maxAttempts) {
|
||||
return DispositionPark
|
||||
}
|
||||
return DispositionRetry
|
||||
}
|
||||
|
||||
// ConsumeLoop 是全项目唯一的消费循环:取消息、调用 process、按 Decide 处置。
|
||||
func ConsumeLoop(
|
||||
ctx context.Context,
|
||||
ch *amqp.Channel,
|
||||
parker Parker,
|
||||
queue string,
|
||||
maxAttempts int,
|
||||
process func(context.Context, amqp.Delivery) error,
|
||||
) error {
|
||||
if ch == nil {
|
||||
return errors.New("consume: channel is nil")
|
||||
}
|
||||
if queue == "" {
|
||||
return errors.New("consume: queue is empty")
|
||||
}
|
||||
if process == nil {
|
||||
return errors.New("consume: process is nil")
|
||||
}
|
||||
if maxAttempts <= 0 {
|
||||
maxAttempts = MaxAttempts
|
||||
}
|
||||
|
||||
deliveries, err := ch.Consume(queue, "", false, false, false, false, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("consume %s: %w", queue, err)
|
||||
}
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil
|
||||
case d, ok := <-deliveries:
|
||||
if !ok {
|
||||
// channel 被关闭:交给 RunConsumer 重建。
|
||||
return nil
|
||||
}
|
||||
handleOne(ctx, parker, queue, maxAttempts, d, process)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// handleOne 处置一条消息,Ack/Nack 失败只记日志。
|
||||
func handleOne(
|
||||
ctx context.Context,
|
||||
parker Parker,
|
||||
queue string,
|
||||
maxAttempts int,
|
||||
d amqp.Delivery,
|
||||
process func(context.Context, amqp.Delivery) error,
|
||||
) {
|
||||
err := process(ctx, d)
|
||||
attempts := GetRetryCount(d) + 1
|
||||
|
||||
switch Decide(d, maxAttempts, err) {
|
||||
case DispositionAck:
|
||||
if ackErr := d.Ack(false); ackErr != nil {
|
||||
log.Printf("consume: ack 失败 queue=%s err=%v", queue, ackErr)
|
||||
}
|
||||
case DispositionRetry:
|
||||
log.Printf("consume: 处理失败将重试 queue=%s attempts=%d/%d err=%v", queue, attempts, maxAttempts, err)
|
||||
// requeue=false 才会进重试队列吃 TTL;true 会立刻重投,等于没有退避。
|
||||
if nackErr := d.Nack(false, false); nackErr != nil {
|
||||
log.Printf("consume: nack 失败 queue=%s err=%v", queue, nackErr)
|
||||
}
|
||||
case DispositionPark:
|
||||
parkOrRequeue(ctx, parker, queue, d, attempts, err)
|
||||
}
|
||||
}
|
||||
|
||||
// parkOrRequeue 停泊一条消息,停泊失败时退避后 requeue。
|
||||
func parkOrRequeue(ctx context.Context, parker Parker, queue string, d amqp.Delivery, attempts int, cause error) {
|
||||
if parker == nil {
|
||||
log.Printf("consume: 无 parker,退回 requeue queue=%s attempts=%d err=%v", queue, attempts, cause)
|
||||
if !sleepCtx(ctx, parkRequeueBackoff) {
|
||||
return
|
||||
}
|
||||
if nackErr := d.Nack(false, true); nackErr != nil {
|
||||
log.Printf("consume: nack 失败 queue=%s err=%v", queue, nackErr)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
parkCtx, cancel := context.WithTimeout(ctx, parkTimeout)
|
||||
defer cancel()
|
||||
|
||||
if err := parker.Park(parkCtx, queue, d, attempts, cause); err != nil {
|
||||
log.Printf("consume: 停泊失败,退回 requeue queue=%s attempts=%d err=%v", queue, attempts, err)
|
||||
// 退避后再重投:停泊链路故障时 Park 会立刻失败,不退避就是热循环。
|
||||
if !sleepCtx(ctx, parkRequeueBackoff) {
|
||||
return
|
||||
}
|
||||
if nackErr := d.Nack(false, true); nackErr != nil {
|
||||
log.Printf("consume: nack 失败 queue=%s err=%v", queue, nackErr)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("consume: 已停泊 queue=%s attempts=%d last_error=%v", queue, attempts, cause)
|
||||
if ackErr := d.Ack(false); ackErr != nil {
|
||||
log.Printf("consume: ack 失败 queue=%s err=%v", queue, ackErr)
|
||||
}
|
||||
return int(count)
|
||||
}
|
||||
|
||||
277
backend/internal/middleware/rabbitmq/integration_test.go
Normal file
277
backend/internal/middleware/rabbitmq/integration_test.go
Normal file
@@ -0,0 +1,277 @@
|
||||
//go:build integration
|
||||
|
||||
package rabbitmq
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/exec"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"feedsystem_video_go/internal/config"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
)
|
||||
|
||||
// 这些用例需要真实 broker,因此用 integration 构建标签隔离:
|
||||
//
|
||||
// docker compose up -d rabbitmq
|
||||
// go test -tags integration -count=1 -timeout 300s -v ./internal/middleware/rabbitmq/
|
||||
//
|
||||
// 环境变量:
|
||||
//
|
||||
// RABBITMQ_TEST_URL 默认 amqp://guest:guest@127.0.0.1:5672/
|
||||
// RABBITMQ_TEST_RESTART_CMD 重启 broker 的命令(如 "docker compose restart rabbitmq")。
|
||||
// 未设置时跳过"重启恢复"用例——无法模拟重启就没有验证价值。
|
||||
// RABBITMQ_TEST_DELETE_QUEUE_CMD
|
||||
// 删除指定队列的命令模板,%s 会被替换为队列名。
|
||||
// 如:docker compose exec -T rabbitmq rabbitmqctl delete_queue %s
|
||||
func integrationTestManager(t *testing.T) (*RabbitMQ, config.RabbitMQConfig) {
|
||||
t.Helper()
|
||||
|
||||
raw := os.Getenv("RABBITMQ_TEST_URL")
|
||||
if raw == "" {
|
||||
raw = "amqp://guest:guest@127.0.0.1:5672/"
|
||||
}
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil {
|
||||
t.Fatalf("bad RABBITMQ_TEST_URL %q: %v", raw, err)
|
||||
}
|
||||
port := 5672
|
||||
if u.Port() != "" {
|
||||
if port, err = strconv.Atoi(u.Port()); err != nil {
|
||||
t.Fatalf("bad port in RABBITMQ_TEST_URL: %v", err)
|
||||
}
|
||||
}
|
||||
cfg := config.RabbitMQConfig{Host: u.Hostname(), Port: port}
|
||||
if u.User != nil {
|
||||
cfg.Username = u.User.Username()
|
||||
cfg.Password, _ = u.User.Password()
|
||||
}
|
||||
|
||||
// 测试用更激进的退避,避免等待时间过长
|
||||
opts := ReconnectOptions{
|
||||
MinBackoff: 200 * time.Millisecond,
|
||||
MaxBackoff: 2 * time.Second,
|
||||
Jitter: 0.1,
|
||||
DialTimeout: 3 * time.Second,
|
||||
}
|
||||
mgr, err := newManager(&cfg, opts, true)
|
||||
if err != nil {
|
||||
t.Fatalf("cannot connect to broker at %s: %v", raw, err)
|
||||
}
|
||||
t.Cleanup(func() { _ = mgr.Close() })
|
||||
return mgr, cfg
|
||||
}
|
||||
|
||||
// runShell 执行由环境变量提供的"模拟故障"命令(重启 broker / 删除队列)。
|
||||
// 这些命令在 Windows 开发机与 Unix CI 上都要能跑,因此按 GOOS 选择 shell——
|
||||
// 硬编码 "sh -c" 会让本用例在 Windows 上直接失败。
|
||||
func runShell(cmdline string) ([]byte, error) {
|
||||
if runtime.GOOS == "windows" {
|
||||
return exec.Command("cmd", "/c", cmdline).CombinedOutput()
|
||||
}
|
||||
return exec.Command("sh", "-c", cmdline).CombinedOutput()
|
||||
}
|
||||
|
||||
func randSuffix(t *testing.T) string {
|
||||
t.Helper()
|
||||
b := make([]byte, 6)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
t.Fatalf("rand: %v", err)
|
||||
}
|
||||
return hex.EncodeToString(b)
|
||||
}
|
||||
|
||||
// TestIntegration_ConsumerRecoversAfterBrokerRestart 是 P0-2 的核心验收用例:
|
||||
//
|
||||
// broker 重启后,消费者必须在退避窗口内自动恢复消费,且不需要人工重启进程。
|
||||
//
|
||||
// 修复前的行为:conn 永久 closed,conn.Channel() 永远返回 ErrClosed,
|
||||
// 消费者每 5 秒刷一行日志、永不恢复——本用例会一直等到超时并失败。
|
||||
func TestIntegration_ConsumerRecoversAfterBrokerRestart(t *testing.T) {
|
||||
restartCmd := os.Getenv("RABBITMQ_TEST_RESTART_CMD")
|
||||
if restartCmd == "" {
|
||||
t.Skip("RABBITMQ_TEST_RESTART_CMD not set: cannot simulate a broker restart")
|
||||
}
|
||||
|
||||
mgr, _ := integrationTestManager(t)
|
||||
suffix := randSuffix(t)
|
||||
topo := Topology{Exchange: "p0-2.test.events", Queue: "p0-2.test." + suffix, BindingKey: "p0-2.test.*"}
|
||||
mgr.RegisterTopology(topo)
|
||||
if err := mgr.EnsureTopology(context.Background()); err != nil {
|
||||
t.Fatalf("EnsureTopology: %v", err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if sess, err := mgr.Session(context.Background()); err == nil {
|
||||
_, _ = sess.Ch.QueueDelete(topo.Queue, false, false, false)
|
||||
_ = sess.Ch.Close()
|
||||
}
|
||||
})
|
||||
|
||||
received := make(chan string, 64)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
go RunConsumer(ctx, mgr, "integration-consumer", 10, func(ch *amqp.Channel) error {
|
||||
msgs, err := ch.Consume(topo.Queue, "", false, false, false, false, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case m, ok := <-msgs:
|
||||
if !ok {
|
||||
return fmt.Errorf("deliveries closed")
|
||||
}
|
||||
received <- string(m.Body)
|
||||
_ = m.Ack(false)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// 基线:重启前必须能正常消费
|
||||
publishAndExpect(t, mgr, topo, received, "before-restart")
|
||||
|
||||
// —— 制造故障:重启 broker ——
|
||||
genBefore := mgr.Stats().Generation
|
||||
t.Logf("restarting broker: %s", restartCmd)
|
||||
if out, err := runShell(restartCmd); err != nil {
|
||||
t.Fatalf("restart command failed: %v\n%s", err, out)
|
||||
}
|
||||
|
||||
// —— 必须在退避窗口内自愈 ——
|
||||
deadline := time.Now().Add(90 * time.Second)
|
||||
for {
|
||||
if mgr.Stats().Generation > genBefore {
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("P0-2: consumer did not reconnect within 90s (generation stuck at %d)", genBefore)
|
||||
}
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
}
|
||||
t.Logf("reconnected: generation=%d reconnects=%d", mgr.Stats().Generation, mgr.Stats().Reconnects)
|
||||
|
||||
// 恢复后必须真的能继续消费(不只是日志好看)
|
||||
publishAndExpect(t, mgr, topo, received, "after-restart")
|
||||
}
|
||||
|
||||
// TestIntegration_TopologyIsRedeclaredAfterQueueDeleted 覆盖报告未提及的第二种卡死模式:
|
||||
// 连接始终健康,但队列没了。此时永远不会触发连接重连,
|
||||
// 只有"channel 级异常 → 重放拓扑"这条路能救回来。
|
||||
func TestIntegration_TopologyIsRedeclaredAfterQueueDeleted(t *testing.T) {
|
||||
deleteCmd := os.Getenv("RABBITMQ_TEST_DELETE_QUEUE_CMD")
|
||||
if deleteCmd == "" {
|
||||
t.Skip("RABBITMQ_TEST_DELETE_QUEUE_CMD not set: cannot simulate topology loss")
|
||||
}
|
||||
|
||||
mgr, _ := integrationTestManager(t)
|
||||
suffix := randSuffix(t)
|
||||
topo := Topology{Exchange: "p0-2.test.events", Queue: "p0-2.topology." + suffix, BindingKey: "p0-2.test.*"}
|
||||
mgr.RegisterTopology(topo)
|
||||
if err := mgr.EnsureTopology(context.Background()); err != nil {
|
||||
t.Fatalf("EnsureTopology: %v", err)
|
||||
}
|
||||
|
||||
received := make(chan string, 64)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
go RunConsumer(ctx, mgr, "integration-topology-consumer", 10, func(ch *amqp.Channel) error {
|
||||
msgs, err := ch.Consume(topo.Queue, "", false, false, false, false, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case m, ok := <-msgs:
|
||||
if !ok {
|
||||
return fmt.Errorf("deliveries closed")
|
||||
}
|
||||
received <- string(m.Body)
|
||||
_ = m.Ack(false)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
publishAndExpect(t, mgr, topo, received, "before-delete")
|
||||
|
||||
// —— 在连接健康的情况下删掉队列 ——
|
||||
genBefore := mgr.Stats().Generation
|
||||
cmd := fmt.Sprintf(deleteCmd, topo.Queue)
|
||||
t.Logf("deleting queue: %s", cmd)
|
||||
if out, err := runShell(cmd); err != nil {
|
||||
t.Fatalf("delete command failed: %v\n%s", err, out)
|
||||
}
|
||||
|
||||
// 删除队列会让 broker 取消消费者;连接本身仍然健康,
|
||||
// 因此修复后的行为是"重放拓扑 + 重新 Consume",而不是重连。
|
||||
deadline := time.Now().Add(90 * time.Second)
|
||||
for {
|
||||
if err := mgr.EnsureTopology(context.Background()); err == nil {
|
||||
// 拓扑重放成功后,确认队列真的可以消费了
|
||||
if canConsume(t, mgr, topo, received, "after-delete") {
|
||||
break
|
||||
}
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("P0-2: consumer did not recover after queue deletion (generation=%d, was %d)",
|
||||
mgr.Stats().Generation, genBefore)
|
||||
}
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
}
|
||||
|
||||
func publishAndExpect(t *testing.T, mgr *RabbitMQ, topo Topology, received <-chan string, payload string) {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if err := mgr.PublishJSON(ctx, topo.Exchange, "p0-2.test.msg", map[string]string{"payload": payload}); err != nil {
|
||||
t.Fatalf("PublishJSON(%s): %v", payload, err)
|
||||
}
|
||||
select {
|
||||
case got := <-received:
|
||||
var env map[string]string
|
||||
if err := json.Unmarshal([]byte(got), &env); err != nil {
|
||||
t.Fatalf("unmarshal %q: %v", got, err)
|
||||
}
|
||||
if env["payload"] != payload {
|
||||
t.Fatalf("payload mismatch: want %q, got %q", payload, env["payload"])
|
||||
}
|
||||
case <-time.After(30 * time.Second):
|
||||
t.Fatalf("P0-2: message %q was never consumed", payload)
|
||||
}
|
||||
}
|
||||
|
||||
func canConsume(t *testing.T, mgr *RabbitMQ, topo Topology, received <-chan string, payload string) bool {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if err := mgr.PublishJSON(ctx, topo.Exchange, "p0-2.test.msg", map[string]string{"payload": payload}); err != nil {
|
||||
return false
|
||||
}
|
||||
select {
|
||||
case <-received:
|
||||
return true
|
||||
case <-time.After(5 * time.Second):
|
||||
// 消费掉可能残留的旧消息,避免影响后续判定
|
||||
select {
|
||||
case <-received:
|
||||
default:
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -4,21 +4,23 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
)
|
||||
|
||||
// LikeMQ 通过连接管理器发布点赞事件。
|
||||
// 它不再持有长生命周期 channel——连接断开后由管理器重建,发布自动恢复。
|
||||
type LikeMQ struct {
|
||||
ch *amqp.Channel
|
||||
mgr *RabbitMQ
|
||||
}
|
||||
|
||||
// 拓扑常量导出:交换机名 / 队列名 / 绑定键是跨进程的"线缆契约",
|
||||
// cmd/worker 与 http 层登记拓扑时必须复用同一份定义,不能再各自写字符串字面量。
|
||||
const (
|
||||
likeExchange = "like.events"
|
||||
likeQueue = "like.events"
|
||||
likeBindingKey = "like.*"
|
||||
LikeExchange = "like.events"
|
||||
LikeQueue = "like.events"
|
||||
LikeBindingKey = "like.*"
|
||||
|
||||
likeLikeRK = "like.like" // 点赞路由键
|
||||
likeUnlikeRK = "like.unlike" // 取消点赞路由键
|
||||
LikeLikeRK = "like.like" // 点赞路由键
|
||||
LikeUnlikeRK = "like.unlike" // 取消点赞路由键
|
||||
)
|
||||
|
||||
type LikeEvent struct {
|
||||
@@ -33,35 +35,35 @@ func NewLikeMQ(base *RabbitMQ) (*LikeMQ, error) {
|
||||
if base == nil {
|
||||
return nil, errors.New("rabbitmq base is nil")
|
||||
}
|
||||
ch, err := base.NewChannel()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := DeclareTopic(ch, likeExchange, likeQueue, likeBindingKey); err != nil {
|
||||
ch.Close()
|
||||
return nil, err
|
||||
}
|
||||
return &LikeMQ{ch: ch}, nil
|
||||
// 拓扑交给管理器登记:每一代连接都会自动重放,不再只声明一次
|
||||
base.RegisterTopology(Topology{Exchange: LikeExchange, Queue: LikeQueue, BindingKey: LikeBindingKey})
|
||||
return &LikeMQ{mgr: base}, nil
|
||||
}
|
||||
|
||||
func (l *LikeMQ) Like(ctx context.Context, userID, videoID uint) error {
|
||||
return l.publish(ctx, "like", likeLikeRK, userID, videoID)
|
||||
// Like / Unlike 的 intentKey 只作为 LikeEvent.EventID:调用方用它把日志与
|
||||
// 一条用户意图对齐,判重仍由 likes 表的唯一索引负责(见 ApplyLike)。
|
||||
func (l *LikeMQ) Like(ctx context.Context, userID, videoID uint, intentKey string) error {
|
||||
return l.publish(ctx, "like", LikeLikeRK, userID, videoID, intentKey)
|
||||
}
|
||||
|
||||
func (l *LikeMQ) Unlike(ctx context.Context, userID, videoID uint) error {
|
||||
return l.publish(ctx, "unlike", likeUnlikeRK, userID, videoID)
|
||||
func (l *LikeMQ) Unlike(ctx context.Context, userID, videoID uint, intentKey string) error {
|
||||
return l.publish(ctx, "unlike", LikeUnlikeRK, userID, videoID, intentKey)
|
||||
}
|
||||
|
||||
func (l *LikeMQ) publish(ctx context.Context, action, routingKey string, userID, videoID uint) error {
|
||||
if l == nil || l.ch == nil {
|
||||
func (l *LikeMQ) publish(ctx context.Context, action, routingKey string, userID, videoID uint, intentKey string) error {
|
||||
if l == nil || l.mgr == nil {
|
||||
return errors.New("like mq is not initialized")
|
||||
}
|
||||
if userID == 0 || videoID == 0 {
|
||||
return errors.New("userID and videoID are required")
|
||||
}
|
||||
id, err := newEventID(16)
|
||||
if err != nil {
|
||||
return err
|
||||
id := intentKey
|
||||
if id == "" {
|
||||
var err error
|
||||
id, err = newEventID(16)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
event := LikeEvent{
|
||||
EventID: id,
|
||||
@@ -70,5 +72,5 @@ func (l *LikeMQ) publish(ctx context.Context, action, routingKey string, userID,
|
||||
VideoID: videoID,
|
||||
OccurredAt: time.Now(),
|
||||
}
|
||||
return PublishJSON(ctx, l.ch, likeExchange, routingKey, event)
|
||||
return l.mgr.PublishJSON(ctx, LikeExchange, routingKey, event)
|
||||
}
|
||||
|
||||
21
backend/internal/middleware/rabbitmq/notification.go
Normal file
21
backend/internal/middleware/rabbitmq/notification.go
Normal file
@@ -0,0 +1,21 @@
|
||||
package rabbitmq
|
||||
|
||||
// 通知队列复用 like / comment / social 三个 exchange,但用单一路由键只订阅
|
||||
// "需要提醒用户"的那一个动作:
|
||||
//
|
||||
// like.events --like.like--> notification.like
|
||||
// comment.events --comment.publish--> notification.comment
|
||||
// social.events --social.follow--> notification.social
|
||||
//
|
||||
// 与主队列的区别:主队列用通配键(like.* 等)收全部动作,因为 DB 需要同步
|
||||
// 点赞与取消点赞两个方向;通知只关心"发生过",取关 / 删评论不需要推送。
|
||||
// 关注没有 DB 同步队列:写库在 API 内完成,social.events 只承载通知。
|
||||
//
|
||||
// 这三个队列原先以字符串字面量写在 internal/http/router.go 里,导致
|
||||
// rabbitmq 包与 http 包各存一份"线缆契约"。改为导出常量后,登记拓扑
|
||||
// 与启动消费者共用同一份定义。
|
||||
const (
|
||||
NotificationLikeQueue = "notification.like"
|
||||
NotificationCommentQueue = "notification.comment"
|
||||
NotificationSocialQueue = "notification.social"
|
||||
)
|
||||
302
backend/internal/middleware/rabbitmq/p03_e2e_integration_test.go
Normal file
302
backend/internal/middleware/rabbitmq/p03_e2e_integration_test.go
Normal file
@@ -0,0 +1,302 @@
|
||||
//go:build integration
|
||||
|
||||
package rabbitmq
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
)
|
||||
|
||||
// 这三条用例验证 P0-3 的对外承诺,而不是内部函数。
|
||||
//
|
||||
// 单元测试能证明 Decide 返回 "retry",只有真实 broker 能证明消息确实
|
||||
// 走过 <queue>.retry、按 x-message-ttl 延迟、耗尽后确实停在 failed.events。
|
||||
// 因此它们放在 integration 构建标签下:
|
||||
//
|
||||
// RABBITMQ_TEST_URL=amqp://admin:123456@127.0.0.1:5672/ \
|
||||
// go test -tags integration -count=1 -run TestP0_3 ./internal/middleware/rabbitmq/
|
||||
|
||||
// p03Declare 建一条唯一命名的测试拓扑,并登记清理。
|
||||
//
|
||||
// 队列名带随机后缀:用例失败时残留对象不会污染下一次运行,
|
||||
// 也不会影响 failed.events 上其他用例的断言。
|
||||
func p03Declare(t *testing.T, mgr *RabbitMQ, delay time.Duration) Topology {
|
||||
t.Helper()
|
||||
topo := Topology{
|
||||
Exchange: "p0_3.e2e.events." + randSuffix(t),
|
||||
Queue: "p0_3.e2e.queue." + randSuffix(t),
|
||||
BindingKey: "#",
|
||||
RetryDelay: delay,
|
||||
}
|
||||
mgr.RegisterTopology(topo)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
if err := mgr.EnsureTopology(ctx); err != nil {
|
||||
t.Fatalf("EnsureTopology: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { p03Cleanup(mgr, topo) })
|
||||
return topo
|
||||
}
|
||||
|
||||
func p03Cleanup(mgr *RabbitMQ, topo Topology) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
sess, err := mgr.Session(ctx)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer sess.Ch.Close()
|
||||
_, _ = sess.Ch.QueueDelete(topo.Queue, false, false, false)
|
||||
_, _ = sess.Ch.QueueDelete(RetryQueueName(topo.Queue), false, false, false)
|
||||
_ = sess.Ch.ExchangeDelete(topo.Exchange, false, false)
|
||||
_ = sess.Ch.ExchangeDelete(RetryExchange(topo.Queue), false, false)
|
||||
}
|
||||
|
||||
func p03Publish(t *testing.T, mgr *RabbitMQ, topo Topology, eventID string) {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
if err := mgr.PublishJSON(ctx, topo.Exchange, "p0_3.e2e", map[string]string{"event_id": eventID}); err != nil {
|
||||
t.Fatalf("publish: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// p03WaitParked 在 failed.events 上等待属于 sourceQueue 的停泊消息。
|
||||
//
|
||||
// 两个细节都是被真实 broker 打出来的教训:
|
||||
//
|
||||
// 1. 必须在 channel 关闭前确认。关闭后 Ack 返回 ErrClosed,被 `_ =` 吞掉,
|
||||
// 消息留在队列里——上一版正是这样把"已确认"变成了一句空话。
|
||||
// 2. 不属于本用例的消息要确认掉,不能 requeue。停泊队列只有一个,Get 总是
|
||||
// 取队头,requeue 会把同一条消息反复放回队头,形成饥饿:后面的消息永远
|
||||
// 读不到。用例在同一包里串行执行,没有别的并发生产者,所以确认掉是安全的。
|
||||
func p03WaitParked(t *testing.T, mgr *RabbitMQ, sourceQueue string, timeout time.Duration) amqp.Delivery {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(timeout)
|
||||
for time.Now().Before(deadline) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
sess, err := mgr.Session(ctx)
|
||||
if err != nil {
|
||||
cancel()
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
continue
|
||||
}
|
||||
msg, ok, getErr := sess.Ch.Get(ParkedQueue, false)
|
||||
var ackErr error
|
||||
ours := getErr == nil && ok && p03StringHeader(msg, HeaderSourceQueue) == sourceQueue
|
||||
if getErr == nil && ok {
|
||||
// 必须在 channel 仍然打开时确认。关闭后再 Ack 会返回 ErrClosed,
|
||||
// 被 `_ =` 吞掉,消息留在队列里——上一版正是这样把"已确认"变成空话。
|
||||
ackErr = msg.Ack(false)
|
||||
}
|
||||
_ = sess.Ch.Close()
|
||||
cancel()
|
||||
if ours {
|
||||
if ackErr != nil {
|
||||
t.Fatalf("确认停泊消息失败: %v", ackErr)
|
||||
}
|
||||
return msg
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
t.Fatalf("等待停泊消息超时(source_queue=%s)", sourceQueue)
|
||||
return amqp.Delivery{}
|
||||
}
|
||||
|
||||
func p03StringHeader(d amqp.Delivery, key string) string {
|
||||
v, ok := d.Headers[key].(string)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func p03IntHeader(d amqp.Delivery, key string) int {
|
||||
switch v := d.Headers[key].(type) {
|
||||
case int32:
|
||||
return int(v)
|
||||
case int64:
|
||||
return int(v)
|
||||
case int:
|
||||
return v
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
func p03QueueLen(t *testing.T, mgr *RabbitMQ, queue string) int {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
sess, err := mgr.Session(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("Session: %v", err)
|
||||
}
|
||||
defer sess.Ch.Close()
|
||||
q, err := sess.Ch.QueueInspect(queue)
|
||||
if err != nil {
|
||||
t.Fatalf("QueueInspect(%s): %v", queue, err)
|
||||
}
|
||||
return q.Messages
|
||||
}
|
||||
|
||||
// 瞬时失败一次后必须自愈:消息经 <queue>.retry 延迟重投,第二次处理成功。
|
||||
//
|
||||
// 同时钉住"重试计数来自 broker":第二次投递上 GetRetryCount 必须是 1,
|
||||
// 而不是进程内存里的某个计数器。
|
||||
func TestP0_3_TransientFailureRecoversAfterRetryDelay(t *testing.T) {
|
||||
mgr, _ := integrationTestManager(t)
|
||||
const delay = 300 * time.Millisecond
|
||||
topo := p03Declare(t, mgr, delay)
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
sess, err := mgr.Session(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("Session: %v", err)
|
||||
}
|
||||
defer sess.Ch.Close()
|
||||
|
||||
var mu sync.Mutex
|
||||
var retryCounts []int
|
||||
start := time.Now()
|
||||
var once sync.Once
|
||||
processed := make(chan time.Duration, 1)
|
||||
|
||||
go func() {
|
||||
_ = ConsumeLoop(ctx, sess.Ch, mgr, topo.Queue, 4, func(_ context.Context, d amqp.Delivery) error {
|
||||
mu.Lock()
|
||||
retryCounts = append(retryCounts, GetRetryCount(d))
|
||||
n := len(retryCounts)
|
||||
mu.Unlock()
|
||||
if n == 1 {
|
||||
return errors.New("handler: transient failure")
|
||||
}
|
||||
once.Do(func() { processed <- time.Since(start) })
|
||||
return nil
|
||||
})
|
||||
}()
|
||||
|
||||
p03Publish(t, mgr, topo, "transient")
|
||||
|
||||
select {
|
||||
case elapsed := <-processed:
|
||||
if elapsed < delay {
|
||||
t.Fatalf("第二次投递只用了 %v,短于 RetryDelay=%v:说明消息没有经过重试队列", elapsed, delay)
|
||||
}
|
||||
case <-time.After(30 * time.Second):
|
||||
t.Fatal("超时:消息没有在重试后恢复处理")
|
||||
}
|
||||
|
||||
mu.Lock()
|
||||
got := append([]int(nil), retryCounts...)
|
||||
mu.Unlock()
|
||||
if len(got) != 2 {
|
||||
t.Fatalf("投递次数 = %d (%v), want 2", len(got), got)
|
||||
}
|
||||
if got[0] != 0 || got[1] != 1 {
|
||||
t.Fatalf("GetRetryCount 序列 = %v, want [0 1](第二次必须是 broker 的 x-death 计数)", got)
|
||||
}
|
||||
if n := p03QueueLen(t, mgr, topo.Queue); n != 0 {
|
||||
t.Fatalf("业务队列剩余 %d 条,want 0", n)
|
||||
}
|
||||
}
|
||||
|
||||
// 毒消息耗尽预算后必须停泊,而不是被 Ack 丢弃。
|
||||
func TestP0_3_PoisonEndsInParkedQueue(t *testing.T) {
|
||||
mgr, _ := integrationTestManager(t)
|
||||
const delay = 300 * time.Millisecond
|
||||
topo := p03Declare(t, mgr, delay)
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
sess, err := mgr.Session(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("Session: %v", err)
|
||||
}
|
||||
defer sess.Ch.Close()
|
||||
|
||||
var mu sync.Mutex
|
||||
handlerCalls := 0
|
||||
go func() {
|
||||
_ = ConsumeLoop(ctx, sess.Ch, mgr, topo.Queue, 2, func(_ context.Context, _ amqp.Delivery) error {
|
||||
mu.Lock()
|
||||
handlerCalls++
|
||||
mu.Unlock()
|
||||
return errors.New("handler: db down")
|
||||
})
|
||||
}()
|
||||
|
||||
p03Publish(t, mgr, topo, "poison")
|
||||
|
||||
msg := p03WaitParked(t, mgr, topo.Queue, 30*time.Second)
|
||||
|
||||
if got := p03StringHeader(msg, HeaderSourceQueue); got != topo.Queue {
|
||||
t.Fatalf("source_queue = %q, want %q", got, topo.Queue)
|
||||
}
|
||||
if got := p03IntHeader(msg, HeaderAttempts); got != 2 {
|
||||
t.Fatalf("attempts = %d, want 2(首次 + 1 次重试)", got)
|
||||
}
|
||||
if got := p03StringHeader(msg, HeaderLastError); !strings.Contains(got, "db down") {
|
||||
t.Fatalf("last_error = %q, want 含最后的处理错误", got)
|
||||
}
|
||||
if got := GetRetryCount(msg); got < 1 {
|
||||
t.Fatalf("停泊消息的 rejected 计数 = %d, want ≥1", got)
|
||||
}
|
||||
if !strings.Contains(string(msg.Body), "poison") {
|
||||
t.Fatalf("停泊消息体 = %q, want 保留原始 body", string(msg.Body))
|
||||
}
|
||||
|
||||
mu.Lock()
|
||||
calls := handlerCalls
|
||||
mu.Unlock()
|
||||
if calls < 2 {
|
||||
t.Fatalf("处理次数 = %d, want ≥2(预算用满才停泊)", calls)
|
||||
}
|
||||
if n := p03QueueLen(t, mgr, topo.Queue); n != 0 {
|
||||
t.Fatalf("业务队列剩余 %d 条,want 0", n)
|
||||
}
|
||||
}
|
||||
|
||||
// 不可重试的失败必须立即停泊:不进重试队列,attempts 为 1。
|
||||
func TestP0_3_PermanentGoesStraightToParked(t *testing.T) {
|
||||
mgr, _ := integrationTestManager(t)
|
||||
const delay = 10 * time.Second // 故意设长:一旦进重试队列,本用例会超时失败
|
||||
topo := p03Declare(t, mgr, delay)
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
sess, err := mgr.Session(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("Session: %v", err)
|
||||
}
|
||||
defer sess.Ch.Close()
|
||||
|
||||
start := time.Now()
|
||||
go func() {
|
||||
_ = ConsumeLoop(ctx, sess.Ch, mgr, topo.Queue, 4, func(_ context.Context, _ amqp.Delivery) error {
|
||||
return Permanent(errors.New("handler: malformed event"))
|
||||
})
|
||||
}()
|
||||
|
||||
p03Publish(t, mgr, topo, "permanent")
|
||||
|
||||
msg := p03WaitParked(t, mgr, topo.Queue, 15*time.Second)
|
||||
if elapsed := time.Since(start); elapsed > delay/2 {
|
||||
t.Fatalf("停泊耗时 %v:不可重试的错误不应进入 %v 的重试队列", elapsed, delay)
|
||||
}
|
||||
if got := p03IntHeader(msg, HeaderAttempts); got != 1 {
|
||||
t.Fatalf("attempts = %d, want 1", got)
|
||||
}
|
||||
if got := p03StringHeader(msg, HeaderLastError); !strings.Contains(got, "malformed") {
|
||||
t.Fatalf("last_error = %q, want 含原始错误", got)
|
||||
}
|
||||
}
|
||||
21
backend/internal/middleware/rabbitmq/park_test.go
Normal file
21
backend/internal/middleware/rabbitmq/park_test.go
Normal file
@@ -0,0 +1,21 @@
|
||||
package rabbitmq
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestTruncateString(t *testing.T) {
|
||||
cases := []struct {
|
||||
in string
|
||||
max int
|
||||
want string
|
||||
}{
|
||||
{"short", 10, "short"},
|
||||
{"0123456789", 4, "0123"},
|
||||
{"exact", 5, "exact"},
|
||||
{"anything", 0, "anything"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := truncateString(c.in, c.max); got != c.want {
|
||||
t.Fatalf("truncateString(%q, %d) = %q, want %q", c.in, c.max, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
170
backend/internal/middleware/rabbitmq/parking_test.go
Normal file
170
backend/internal/middleware/rabbitmq/parking_test.go
Normal file
@@ -0,0 +1,170 @@
|
||||
package rabbitmq
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
)
|
||||
|
||||
// —— 停泊链路 ——
|
||||
|
||||
// TestDeclareTopologies_DeclaresParkingBeforeBusinessTopology 守护"停泊链路先于业务拓扑"。
|
||||
//
|
||||
// 为什么顺序重要:停泊是业务队列的 DLX 目的地。链路晚一步,就有一段时间窗口
|
||||
// 里被拒绝的消息无处可去——broker 直接丢弃,而 worker 以为自己已经处理完了。
|
||||
func TestDeclareTopologies_DeclaresParkingBeforeBusinessTopology(t *testing.T) {
|
||||
f := &fakeDeclarer{}
|
||||
topo := []Topology{{Exchange: LikeExchange, Queue: LikeQueue, BindingKey: LikeBindingKey}}
|
||||
|
||||
if err := DeclareTopologies(f, topo); err != nil {
|
||||
t.Fatalf("DeclareTopologies: %v", err)
|
||||
}
|
||||
|
||||
want := []string{
|
||||
"exchange:" + DLXExchange,
|
||||
"queue:" + ParkedQueue,
|
||||
"bind:" + ParkedQueue + "<-" + DLXExchange + "/" + ParkedKeyPrefix + "#",
|
||||
}
|
||||
if len(f.calls) < len(want) {
|
||||
t.Fatalf("calls = %v, want at least %v", f.calls, want)
|
||||
}
|
||||
if !reflect.DeepEqual(f.calls[:len(want)], want) {
|
||||
t.Fatalf("前三个声明 = %v, want %v", f.calls[:len(want)], want)
|
||||
}
|
||||
|
||||
parked := f.indexOf("queue:" + ParkedQueue)
|
||||
// 只断言"停泊链路早于业务队列",不锁死业务侧还声明了什么。
|
||||
business := f.indexOf("queue:" + LikeQueue)
|
||||
if parked < 0 || business < 0 || parked > business {
|
||||
t.Fatalf("停泊队列下标=%d 业务队列下标=%d,停泊链路必须先声明", parked, business)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeclareTopologies_ParkingFailureStopsReplay(t *testing.T) {
|
||||
f := &fakeDeclarer{failOn: "exchange:" + DLXExchange, failErr: errors.New("ACCESS_REFUSED")}
|
||||
err := DeclareTopologies(f, []Topology{{Exchange: LikeExchange, Queue: LikeQueue, BindingKey: LikeBindingKey}})
|
||||
if err == nil {
|
||||
t.Fatal("期望返回错误")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "declare parking") {
|
||||
t.Fatalf("err = %v, 期望包含 declare parking", err)
|
||||
}
|
||||
if got := f.indexOf("queue:" + LikeQueue); got >= 0 {
|
||||
t.Fatalf("停泊链路失败后不应继续声明业务队列,calls = %v", f.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeclareParking_IsIdempotentOnReplay(t *testing.T) {
|
||||
f := &fakeDeclarer{}
|
||||
for i := 0; i < 3; i++ {
|
||||
if err := declareParking(f); err != nil {
|
||||
t.Fatalf("第 %d 次 declareParking: %v", i+1, err)
|
||||
}
|
||||
}
|
||||
if got := len(f.calls); got != 9 {
|
||||
t.Fatalf("三次声明共 %d 次调用, want 9(每代连接都重放,必须幂等)", got)
|
||||
}
|
||||
}
|
||||
|
||||
// —— 重试队列参数 ——
|
||||
|
||||
func TestRetryQueueArgs_TTLAndDefaultExchange(t *testing.T) {
|
||||
args := RetryQueueArgs("like.events", 5*time.Second)
|
||||
|
||||
if got, ok := args["x-message-ttl"].(int64); !ok || got != 5000 {
|
||||
t.Fatalf("x-message-ttl = %#v, want int64(5000)", args["x-message-ttl"])
|
||||
}
|
||||
// 空串就是默认交换机:按队列名精确投递,不可能被 topic 扇出成多份。
|
||||
if got := args["x-dead-letter-exchange"]; got != "" {
|
||||
t.Fatalf("x-dead-letter-exchange = %#v, want \"\"(默认交换机)", got)
|
||||
}
|
||||
if got := args["x-dead-letter-routing-key"]; got != "like.events" {
|
||||
t.Fatalf("x-dead-letter-routing-key = %#v, want 队列名", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRetryQueueArgs_NonPositiveDelayFallsBackToDefault(t *testing.T) {
|
||||
for _, delay := range []time.Duration{0, -time.Second} {
|
||||
args := RetryQueueArgs("comment.events", delay)
|
||||
if got := args["x-message-ttl"]; got != int64(DefaultRetryDelay/time.Millisecond) {
|
||||
t.Fatalf("delay=%v 时 x-message-ttl = %#v, want 默认延迟", delay, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestRetryArgs_OnlyOverridesDeadLetterExchange 防止有人"顺手"加上
|
||||
// x-dead-letter-routing-key:那会让第 1 次被拒绝时路由键也被改写,
|
||||
// 而消费者在第一次投递时依赖原路由键(见 §6.8.6 的 N13)。
|
||||
func TestRetryArgs_OnlyOverridesDeadLetterExchange(t *testing.T) {
|
||||
args := RetryArgs("social.events")
|
||||
if len(args) != 1 {
|
||||
t.Fatalf("args = %#v, want 只有 x-dead-letter-exchange", args)
|
||||
}
|
||||
if got := args["x-dead-letter-exchange"]; got != RetryExchange("social.events") {
|
||||
t.Fatalf("x-dead-letter-exchange = %#v, want %q", got, RetryExchange("social.events"))
|
||||
}
|
||||
}
|
||||
|
||||
func TestRetryNames_PerQueue(t *testing.T) {
|
||||
if got := RetryExchange("like.events"); got != "retry.events.like.events" {
|
||||
t.Fatalf("RetryExchange = %q", got)
|
||||
}
|
||||
if got := RetryQueueName("like.events"); got != "like.events.retry" {
|
||||
t.Fatalf("RetryQueueName = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// —— 停泊消息的解析 ——
|
||||
|
||||
func TestParseParkedInfo_FromHeaders(t *testing.T) {
|
||||
d := amqp.Delivery{
|
||||
RoutingKey: "parked.comment.events",
|
||||
Body: []byte(`{"event_id":"abc123","action":"publish"}`),
|
||||
Headers: amqp.Table{
|
||||
HeaderSourceQueue: "notification.comment",
|
||||
HeaderAttempts: int32(4),
|
||||
HeaderLastError: "db: connection refused",
|
||||
},
|
||||
}
|
||||
info := ParseParkedInfo(d)
|
||||
|
||||
if info.SourceQueue != "notification.comment" {
|
||||
t.Fatalf("SourceQueue = %q", info.SourceQueue)
|
||||
}
|
||||
if info.Attempts != 4 {
|
||||
t.Fatalf("Attempts = %d, want 4", info.Attempts)
|
||||
}
|
||||
if info.LastError != "db: connection refused" {
|
||||
t.Fatalf("LastError = %q", info.LastError)
|
||||
}
|
||||
if info.EventID != "abc123" {
|
||||
t.Fatalf("EventID = %q", info.EventID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseParkedInfo_FallsBackToRoutingKey(t *testing.T) {
|
||||
d := amqp.Delivery{RoutingKey: "parked.social.events", Body: []byte(`{}`)}
|
||||
info := ParseParkedInfo(d)
|
||||
|
||||
if info.SourceQueue != "social.events" {
|
||||
t.Fatalf("SourceQueue = %q, want 从 parked. 前缀反推", info.SourceQueue)
|
||||
}
|
||||
if info.Attempts != 1 {
|
||||
t.Fatalf("Attempts = %d, want 默认 1", info.Attempts)
|
||||
}
|
||||
if info.EventID != "" {
|
||||
t.Fatalf("EventID = %q, want 空(坏消息没有意图键)", info.EventID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseParkedInfo_MalformedBodyDoesNotPanic(t *testing.T) {
|
||||
info := ParseParkedInfo(amqp.Delivery{RoutingKey: "parked.x", Body: []byte("not json")})
|
||||
if info.EventID != "" {
|
||||
t.Fatalf("EventID = %q, want 空", info.EventID)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,63 +0,0 @@
|
||||
package rabbitmq
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
)
|
||||
|
||||
type PopularityMQ struct {
|
||||
ch *amqp.Channel
|
||||
}
|
||||
|
||||
const (
|
||||
popularityExchange = "video.popularity.events"
|
||||
popularityQueue = "video.popularity.events"
|
||||
popularityBindingKey = "video.popularity.*"
|
||||
|
||||
popularityUpdateRK = "video.popularity.update"
|
||||
)
|
||||
|
||||
type PopularityEvent struct {
|
||||
EventID string `json:"event_id"`
|
||||
VideoID uint `json:"video_id"`
|
||||
Change int64 `json:"change"`
|
||||
OccurredAt time.Time `json:"occurred_at"`
|
||||
}
|
||||
|
||||
func NewPopularityMQ(base *RabbitMQ) (*PopularityMQ, error) {
|
||||
if base == nil {
|
||||
return nil, errors.New("rabbitmq base is nil")
|
||||
}
|
||||
ch, err := base.NewChannel()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := DeclareTopic(ch, popularityExchange, popularityQueue, popularityBindingKey); err != nil {
|
||||
ch.Close()
|
||||
return nil, err
|
||||
}
|
||||
return &PopularityMQ{ch: ch}, nil
|
||||
}
|
||||
|
||||
func (p *PopularityMQ) Update(ctx context.Context, videoID uint, change int64) error {
|
||||
if p == nil || p.ch == nil {
|
||||
return errors.New("popularity mq is not initialized")
|
||||
}
|
||||
if videoID == 0 || change == 0 {
|
||||
return errors.New("videoID and change are required")
|
||||
}
|
||||
id, err := newEventID(16)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
event := PopularityEvent{
|
||||
EventID: id,
|
||||
VideoID: videoID,
|
||||
Change: change,
|
||||
OccurredAt: time.Now().UTC(),
|
||||
}
|
||||
return PublishJSON(ctx, p.ch, popularityExchange, popularityUpdateRK, event)
|
||||
}
|
||||
@@ -6,112 +6,699 @@ import (
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"feedsystem_video_go/internal/config"
|
||||
"fmt"
|
||||
"log"
|
||||
mrand "math/rand/v2"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"feedsystem_video_go/internal/config"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
)
|
||||
|
||||
// RabbitMQ 只管理 Connection,Channel 由各组件按需创建
|
||||
type RabbitMQ struct {
|
||||
Conn *amqp.Connection
|
||||
// defaultHeartbeat 与 amqp091-go 的默认值一致(connection.go:28)。
|
||||
// 显式写出是为了让"半开连接(无 FIN 的网络中断)最长多久被发现"成为可见常量。
|
||||
const defaultHeartbeat = 10 * time.Second
|
||||
|
||||
var (
|
||||
// ErrManagerClosed 表示管理器已被 Close(),不会再建立任何连接。
|
||||
ErrManagerClosed = errors.New("rabbitmq: manager is closed")
|
||||
// ErrNotConnected 表示当前没有可用连接(仅 NewChannel 返回)。
|
||||
ErrNotConnected = errors.New("rabbitmq: no active connection")
|
||||
)
|
||||
|
||||
// ReconnectOptions 控制重连退避。
|
||||
type ReconnectOptions struct {
|
||||
MinBackoff time.Duration // 首次重试间隔
|
||||
MaxBackoff time.Duration // 退避上限
|
||||
Jitter float64 // 抖动比例(0.2 = ±20%)
|
||||
DialTimeout time.Duration // 单次拨号超时
|
||||
}
|
||||
|
||||
// DefaultReconnectOptions 返回默认重连参数。
|
||||
func DefaultReconnectOptions() ReconnectOptions {
|
||||
return ReconnectOptions{
|
||||
MinBackoff: 500 * time.Millisecond,
|
||||
MaxBackoff: 30 * time.Second,
|
||||
Jitter: 0.2,
|
||||
DialTimeout: 5 * time.Second,
|
||||
}
|
||||
}
|
||||
|
||||
// Stats 是管理器状态快照,供日志、健康检查与指标使用。
|
||||
type Stats struct {
|
||||
Connected bool
|
||||
Generation uint64
|
||||
Reconnects uint64
|
||||
Topology int
|
||||
LastUpAt time.Time
|
||||
LastDownAt time.Time
|
||||
}
|
||||
|
||||
// Session 是一次"连接代"内的 channel 句柄。
|
||||
//
|
||||
// Ch 与 Done 必须成对使用:Done 在本代连接结束时关闭。
|
||||
// 若先取 Ch、事后再去查询"当前是哪一代",就可能拿到新一代的令牌而持有
|
||||
// 旧一代的 channel,表现为永久挂起——与 P0-2 的原始症状无法区分。
|
||||
type Session struct {
|
||||
Ch *amqp.Channel
|
||||
Done <-chan struct{}
|
||||
}
|
||||
|
||||
// connection 是 *amqp.Connection 的最小接口。
|
||||
//
|
||||
// 抽出它的唯一目的是可测性:连接代状态机(谁被唤醒、代令牌何时关闭、
|
||||
// 重复 close 是否会 panic)是本方案里最容易藏"永久挂起"类缺陷的地方,
|
||||
// 有了这个接口就能在没有 broker 的情况下把它测出来。
|
||||
type connection interface {
|
||||
Channel() (*amqp.Channel, error)
|
||||
NotifyClose(chan *amqp.Error) chan *amqp.Error
|
||||
IsClosed() bool
|
||||
Close() error
|
||||
}
|
||||
|
||||
// RabbitMQ 管理 RabbitMQ 连接的生命周期(P0-2)。
|
||||
//
|
||||
// 不变式:
|
||||
// 1. Connection 只在 supervise 协程里被创建;其他任何 goroutine 只能通过
|
||||
// Session() 取 channel——不存在"在已关闭连接上重试"的代码路径。
|
||||
// 2. 任何一次成功连接都对应唯一的"连接代":gen 在本代结束时关闭。
|
||||
// 3. 已登记的拓扑在每一代连接上都会被完整重放,且重放完成前不对外宣告可用。
|
||||
// 4. ready 只是"状态已变化"的广播通道,**就绪与否一律以 conn 为准**——
|
||||
// 这样就不存在"ready 与 conn 不一致"的可能(等待者醒来后总是重新判定)。
|
||||
type RabbitMQ struct {
|
||||
url string
|
||||
opts ReconnectOptions
|
||||
|
||||
mu sync.Mutex
|
||||
conn connection // 当前连接;nil 表示断连中
|
||||
gen chan struct{} // 当前代的结束信号(关闭 = 本代结束)
|
||||
ready chan struct{} // 状态变化广播:关闭后立即替换为新 channel
|
||||
pubCh *amqp.Channel // 每个连接代复用一个发布 channel
|
||||
topology []Topology // 需要在每一代上重放的拓扑
|
||||
closed chan struct{} // 管理器永久关闭信号
|
||||
closeOne sync.Once
|
||||
|
||||
generation uint64
|
||||
reconnects uint64
|
||||
lastUpAt time.Time
|
||||
lastDownAt time.Time
|
||||
}
|
||||
|
||||
// NewRabbitMQ 建立连接管理器。首次拨号失败即返回 error,从而保留
|
||||
// 调用方原有的"RabbitMQ 不可用则 MQ 相关功能降级"的语义。
|
||||
// 首次成功之后,后续所有断连都由内部 supervise 协程自动恢复。
|
||||
func NewRabbitMQ(cfg *config.RabbitMQConfig) (*RabbitMQ, error) {
|
||||
return newManager(cfg, DefaultReconnectOptions(), true)
|
||||
}
|
||||
|
||||
// NewRabbitMQLazy 与 NewRabbitMQ 的唯一区别:首次拨号失败不返回错误,
|
||||
// 而是让 supervise 在后台持续重试。适用于"进程的职责就是消费"的 Worker:
|
||||
// broker 未就绪时应当等待,而不是让进程退出。
|
||||
func NewRabbitMQLazy(cfg *config.RabbitMQConfig) *RabbitMQ {
|
||||
r, err := newManager(cfg, DefaultReconnectOptions(), false)
|
||||
if err != nil {
|
||||
log.Printf("rabbitmq: %v (MQ disabled)", err)
|
||||
return nil
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
func newManager(cfg *config.RabbitMQConfig, opts ReconnectOptions, eager bool) (*RabbitMQ, error) {
|
||||
if cfg == nil {
|
||||
return nil, errors.New("rabbitmq config is nil")
|
||||
}
|
||||
url := "amqp://" + cfg.Username + ":" + cfg.Password + "@" + cfg.Host + ":" + strconv.Itoa(cfg.Port) + "/"
|
||||
conn, err := amqp.Dial(url)
|
||||
if opts.MinBackoff <= 0 {
|
||||
opts.MinBackoff = 500 * time.Millisecond
|
||||
}
|
||||
if opts.MaxBackoff < opts.MinBackoff {
|
||||
opts.MaxBackoff = 30 * time.Second
|
||||
}
|
||||
if opts.DialTimeout <= 0 {
|
||||
opts.DialTimeout = 5 * time.Second
|
||||
}
|
||||
if opts.Jitter < 0 {
|
||||
opts.Jitter = 0
|
||||
}
|
||||
|
||||
r := &RabbitMQ{
|
||||
// 注意:url 含密码,任何日志都不要打印它
|
||||
url: "amqp://" + cfg.Username + ":" + cfg.Password + "@" + cfg.Host + ":" + strconv.Itoa(cfg.Port) + "/",
|
||||
opts: opts,
|
||||
gen: make(chan struct{}),
|
||||
ready: make(chan struct{}),
|
||||
closed: make(chan struct{}),
|
||||
}
|
||||
|
||||
if !eager {
|
||||
go r.supervise(nil, nil)
|
||||
return r, nil
|
||||
}
|
||||
|
||||
conn, err := r.dial()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &RabbitMQ{Conn: conn}, nil
|
||||
// 关键:NotifyClose 必须使用带缓冲(1)的 channel。
|
||||
// 库在 shutdown 中【持连接锁同步】向每个接收者发送(connection.go:604-618),
|
||||
// 无缓冲且无人接收会让整条连接关闭路径卡死——比原缺陷更难排查。
|
||||
notifyClose := conn.NotifyClose(make(chan *amqp.Error, 1))
|
||||
r.install(conn)
|
||||
go r.supervise(conn, notifyClose)
|
||||
return r, nil
|
||||
}
|
||||
|
||||
// dial 使用与首次完全相同的 URL,保证重连后 vhost/认证语义不变。
|
||||
func (r *RabbitMQ) dial() (*amqp.Connection, error) {
|
||||
conn, err := amqp.DialConfig(r.url, amqp.Config{
|
||||
Heartbeat: defaultHeartbeat,
|
||||
Dial: amqp.DefaultDial(r.opts.DialTimeout),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("dial: %w", err)
|
||||
}
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
// supervise 是唯一的连接创建者。
|
||||
// 它先等待当前连接死亡,再进入重连循环(首次立即尝试,失败后退避)。
|
||||
func (r *RabbitMQ) supervise(conn connection, notifyClose <-chan *amqp.Error) {
|
||||
backoff := r.opts.MinBackoff
|
||||
|
||||
for {
|
||||
if conn != nil {
|
||||
select {
|
||||
case <-r.closed:
|
||||
_ = conn.Close()
|
||||
return
|
||||
case amqpErr := <-notifyClose:
|
||||
if amqpErr != nil {
|
||||
log.Printf("rabbitmq: 连接断开 code=%d reason=%q", amqpErr.Code, amqpErr.Reason)
|
||||
} else {
|
||||
log.Printf("rabbitmq: 连接已被关闭")
|
||||
}
|
||||
r.markDown()
|
||||
}
|
||||
}
|
||||
|
||||
// —— 重连循环 ——
|
||||
for {
|
||||
newConn, err := r.dial()
|
||||
if err != nil {
|
||||
log.Printf("rabbitmq: 重连失败: %v(%v 后重试)", err, backoff)
|
||||
if !r.sleepOrClosed(backoff) {
|
||||
return
|
||||
}
|
||||
backoff = nextBackoff(backoff, r.opts)
|
||||
continue
|
||||
}
|
||||
|
||||
newNotify := newConn.NotifyClose(make(chan *amqp.Error, 1))
|
||||
|
||||
// 顺序不可换:拨号 → 注册关闭通知 → 重放拓扑 → 才宣告就绪。
|
||||
// 若拓扑重放失败,这一代不对外发布,避免消费者拿到一个"连接健康但队列不存在"的伪可用连接。
|
||||
if err := r.declareAll(newConn); err != nil {
|
||||
log.Printf("rabbitmq: 重放拓扑失败: %v(%v 后重试)", err, backoff)
|
||||
_ = newConn.Close()
|
||||
if !r.sleepOrClosed(backoff) {
|
||||
return
|
||||
}
|
||||
backoff = nextBackoff(backoff, r.opts)
|
||||
continue
|
||||
}
|
||||
|
||||
r.install(newConn)
|
||||
backoff = r.opts.MinBackoff
|
||||
log.Printf("rabbitmq: 重连成功(第 %d 次重连)", r.bumpReconnects())
|
||||
|
||||
conn, notifyClose = newConn, newNotify
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (r *RabbitMQ) bumpReconnects() uint64 {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
r.reconnects++
|
||||
return r.reconnects
|
||||
}
|
||||
|
||||
// install 发布新一代连接:结束上一代、唤醒等待者。调用方须保证拓扑已重放完毕。
|
||||
func (r *RabbitMQ) install(conn connection) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
|
||||
closeIfOpen(r.gen) // 结束上一代:唤醒持有旧 channel 的消费者
|
||||
r.gen = make(chan struct{})
|
||||
|
||||
closeIfOpen(r.ready) // 广播状态变化:唤醒所有在 WaitReady 上的等待者
|
||||
r.ready = make(chan struct{})
|
||||
|
||||
r.conn = conn
|
||||
r.pubCh = nil
|
||||
r.generation++
|
||||
r.lastUpAt = time.Now()
|
||||
}
|
||||
|
||||
// markDown 标记连接已失效:立即唤醒所有消费者,让它们回到 WaitReady 阻塞等待。
|
||||
func (r *RabbitMQ) markDown() {
|
||||
r.mu.Lock()
|
||||
pubCh := r.pubCh
|
||||
r.pubCh = nil
|
||||
|
||||
closeIfOpen(r.gen)
|
||||
r.gen = make(chan struct{})
|
||||
closeIfOpen(r.ready)
|
||||
r.ready = make(chan struct{})
|
||||
|
||||
r.conn = nil
|
||||
r.lastDownAt = time.Now()
|
||||
r.mu.Unlock()
|
||||
|
||||
if pubCh != nil {
|
||||
_ = pubCh.Close()
|
||||
}
|
||||
}
|
||||
|
||||
// Close 永久关闭管理器:停止重连协程、唤醒所有等待者、关闭当前连接。幂等。
|
||||
func (r *RabbitMQ) Close() error {
|
||||
if r == nil {
|
||||
return nil
|
||||
}
|
||||
if r.Conn != nil {
|
||||
return r.Conn.Close()
|
||||
}
|
||||
return nil
|
||||
var err error
|
||||
r.closeOne.Do(func() {
|
||||
close(r.closed)
|
||||
r.mu.Lock()
|
||||
conn := r.conn
|
||||
r.mu.Unlock()
|
||||
if conn != nil {
|
||||
err = conn.Close()
|
||||
}
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
// WaitReady 阻塞直到当前存在可用连接。
|
||||
//
|
||||
// 只读语义:就绪与否一律以 conn 为准,ready 仅用于唤醒。
|
||||
// 因此断连期间它不会返回,调用方无需轮询,也不会空转刷日志。
|
||||
func (r *RabbitMQ) WaitReady(ctx context.Context) error {
|
||||
if r == nil {
|
||||
return errors.New("rabbitmq manager is nil")
|
||||
}
|
||||
for {
|
||||
r.mu.Lock()
|
||||
ready := r.ready
|
||||
conn := r.conn
|
||||
r.mu.Unlock()
|
||||
|
||||
if conn != nil && !conn.IsClosed() {
|
||||
return nil
|
||||
}
|
||||
|
||||
select {
|
||||
case <-ready:
|
||||
// 状态已变化,回到循环顶部重新判定
|
||||
case <-r.closed:
|
||||
return ErrManagerClosed
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Session 返回"当前连接代"上的一个 channel 及其代令牌。
|
||||
func (r *RabbitMQ) Session(ctx context.Context) (*Session, error) {
|
||||
if r == nil {
|
||||
return nil, errors.New("rabbitmq manager is nil")
|
||||
}
|
||||
for {
|
||||
if err := r.WaitReady(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// conn 与 gen 必须在同一把锁内读取,保证二者配对
|
||||
r.mu.Lock()
|
||||
conn, gen := r.conn, r.gen
|
||||
r.mu.Unlock()
|
||||
|
||||
if conn == nil {
|
||||
continue // 与 markDown 的竞态:回到 WaitReady 重新等待
|
||||
}
|
||||
|
||||
ch, err := conn.Channel()
|
||||
if err == nil {
|
||||
return &Session{Ch: ch, Done: gen}, nil
|
||||
}
|
||||
|
||||
if conn.IsClosed() {
|
||||
// 连接级失效:等这一代真正结束(supervise 会拉起新一代)再重试
|
||||
select {
|
||||
case <-gen:
|
||||
case <-r.closed:
|
||||
return nil, ErrManagerClosed
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
continue
|
||||
}
|
||||
// 非连接级错误(如 channel id 耗尽):交给调用方退避,不在内部空转
|
||||
return nil, fmt.Errorf("create channel: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// NewChannel 在当前连接上取一个 channel。
|
||||
//
|
||||
// 保留此方法仅为向后兼容;新代码请使用 Session——它同时返回代令牌,
|
||||
// 能让调用方正确判断"我手上的 channel 属于哪一代"。
|
||||
// 与 Session 不同,它在断连时【立即返回错误】而不是阻塞等待。
|
||||
func (r *RabbitMQ) NewChannel() (*amqp.Channel, error) {
|
||||
if r == nil || r.Conn == nil {
|
||||
return nil, errors.New("rabbitmq connection is not initialized")
|
||||
if r == nil {
|
||||
return nil, errors.New("rabbitmq manager is nil")
|
||||
}
|
||||
return r.Conn.Channel()
|
||||
r.mu.Lock()
|
||||
conn := r.conn
|
||||
r.mu.Unlock()
|
||||
if conn == nil {
|
||||
return nil, ErrNotConnected
|
||||
}
|
||||
return conn.Channel()
|
||||
}
|
||||
|
||||
func DeclareTopic(ch *amqp.Channel, exchange string, queue string, bindingKey string) error {
|
||||
if ch == nil {
|
||||
return errors.New("channel is not initialized")
|
||||
// RegisterTopology 只登记拓扑,不做任何 I/O。适合"连接尚未建立"的启动阶段。
|
||||
func (r *RabbitMQ) RegisterTopology(topo ...Topology) {
|
||||
if r == nil {
|
||||
return
|
||||
}
|
||||
if exchange == "" || queue == "" || bindingKey == "" {
|
||||
return errors.New("exchange/queue/bindingKey is required")
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
for _, t := range topo {
|
||||
if t.Exchange == "" || t.Queue == "" || t.BindingKey == "" {
|
||||
log.Printf("rabbitmq: 忽略非法拓扑 exchange=%q queue=%q key=%q", t.Exchange, t.Queue, t.BindingKey)
|
||||
continue
|
||||
}
|
||||
if existing, ok := findTopology(r.topology, t); ok {
|
||||
// RetryDelay 不参与去重:同一队列两种延迟会产生两次不等价声明(406)。
|
||||
if existing.RetryDelay != t.RetryDelay {
|
||||
log.Printf("rabbitmq: 拓扑 %s/%s 已登记,忽略重复登记的 RetryDelay=%v(保留 %v)",
|
||||
t.Exchange, t.Queue, t.RetryDelay, existing.RetryDelay)
|
||||
}
|
||||
continue
|
||||
}
|
||||
r.topology = append(r.topology, t)
|
||||
}
|
||||
}
|
||||
|
||||
if err := ch.ExchangeDeclare(
|
||||
exchange,
|
||||
"topic",
|
||||
true, // 持久化参数
|
||||
false, // autoDelete 是否在未使用时自动删除
|
||||
false, // internal 是否交给其他交换机用而不直接收消息
|
||||
false, // noWait 是否不等待 broker 确认
|
||||
nil,
|
||||
); err != nil {
|
||||
return err
|
||||
// AddTopology 登记并立即在当前连接上声明(幂等)。
|
||||
func (r *RabbitMQ) AddTopology(ctx context.Context, topo ...Topology) error {
|
||||
if r == nil {
|
||||
return errors.New("rabbitmq manager is nil")
|
||||
}
|
||||
r.RegisterTopology(topo...)
|
||||
return r.EnsureTopology(ctx)
|
||||
}
|
||||
|
||||
q, err := ch.QueueDeclare(
|
||||
queue, // 队列名称
|
||||
true, // 持久化
|
||||
false, // autoDelete 是否在未使用时自动删除
|
||||
false, // exclusive 是否排他(允许多个消费者共享)
|
||||
false, // noWait 是否不等待 broker 确认
|
||||
amqp.Table{"x-dead-letter-exchange": DLXExchange}, // 死信交换机
|
||||
)
|
||||
// EnsureTopology 在活连接上重放全部已登记拓扑。
|
||||
//
|
||||
// 消费侧在遇到 channel 级异常(404 NOT_FOUND / 406 PRECONDITION_FAILED)时调用它,
|
||||
// 以覆盖"连接仍然健康但队列/绑定已丢失"这一类失效——那种情况下永远不会触发连接重连。
|
||||
func (r *RabbitMQ) EnsureTopology(ctx context.Context) error {
|
||||
sess, err := r.Session(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := ch.QueueBind(
|
||||
q.Name,
|
||||
bindingKey,
|
||||
exchange,
|
||||
false, // noWait
|
||||
nil, // args
|
||||
); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := DeclareDLX(ch, queue); err != nil {
|
||||
log.Printf("DLX declare failed for %s: %v", queue, err)
|
||||
}
|
||||
return nil
|
||||
defer sess.Ch.Close()
|
||||
return DeclareTopologies(sess.Ch, r.Topology())
|
||||
}
|
||||
|
||||
func PublishJSON(ctx context.Context, ch *amqp.Channel, exchange string, routingKey string, payload any) error {
|
||||
if ch == nil {
|
||||
return errors.New("channel is not initialized")
|
||||
// Topology 返回已登记拓扑的副本。
|
||||
func (r *RabbitMQ) Topology() []Topology {
|
||||
if r == nil {
|
||||
return nil
|
||||
}
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
return append([]Topology(nil), r.topology...)
|
||||
}
|
||||
|
||||
// declareAll 在新连接上重放拓扑。重放完毕前 install 不会被调用。
|
||||
func (r *RabbitMQ) declareAll(conn connection) error {
|
||||
topo := r.Topology()
|
||||
if len(topo) == 0 {
|
||||
return nil
|
||||
}
|
||||
ch, err := conn.Channel()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer ch.Close()
|
||||
return DeclareTopologies(ch, topo)
|
||||
}
|
||||
|
||||
// Healthy 报告当前是否持有一条可用连接。
|
||||
func (r *RabbitMQ) Healthy() bool {
|
||||
if r == nil {
|
||||
return false
|
||||
}
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
return r.conn != nil && !r.conn.IsClosed()
|
||||
}
|
||||
|
||||
// Stats 返回状态快照。
|
||||
func (r *RabbitMQ) Stats() Stats {
|
||||
if r == nil {
|
||||
return Stats{}
|
||||
}
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
return Stats{
|
||||
Connected: r.conn != nil && !r.conn.IsClosed(),
|
||||
Generation: r.generation,
|
||||
Reconnects: r.reconnects,
|
||||
Topology: len(r.topology),
|
||||
LastUpAt: r.lastUpAt,
|
||||
LastDownAt: r.lastDownAt,
|
||||
}
|
||||
}
|
||||
|
||||
// —— 发布路径 ——
|
||||
|
||||
// publisherChannel 返回本代可复用的发布 channel。
|
||||
// amqp091-go 的 Publish 内部持锁(channel.go),因此多 goroutine 复用同一 channel
|
||||
// 发布是安全的(只是串行化)。
|
||||
func (r *RabbitMQ) publisherChannel(ctx context.Context) (*amqp.Channel, error) {
|
||||
r.mu.Lock()
|
||||
ch, conn := r.pubCh, r.conn
|
||||
r.mu.Unlock()
|
||||
|
||||
if ch != nil && conn != nil && !conn.IsClosed() {
|
||||
return ch, nil
|
||||
}
|
||||
|
||||
sess, err := r.Session(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
r.mu.Lock()
|
||||
if r.pubCh != nil {
|
||||
// 并发下已有人装上发布 channel:复用它,关掉我们刚取的这个
|
||||
existing := r.pubCh
|
||||
r.mu.Unlock()
|
||||
_ = sess.Ch.Close()
|
||||
return existing, nil
|
||||
}
|
||||
r.pubCh = sess.Ch
|
||||
r.mu.Unlock()
|
||||
return sess.Ch, nil
|
||||
}
|
||||
|
||||
// PublishJSON 经连接管理器发布一条 JSON 消息。
|
||||
//
|
||||
// 失败时丢弃缓存的发布 channel(下一代会重建)并如实返回错误,由服务层
|
||||
// 按既有 "MQ 失败则直写 DB" 路径降级。
|
||||
//
|
||||
// 刻意【不】在 ErrClosed 时自动重发:那会在 P0-4 的双写窗口之上再叠加一次
|
||||
// 不确定性。幂等应当由事件层(event_id)解决,而不是由发布层猜测
|
||||
// 消息是否已经到达 broker。
|
||||
func (r *RabbitMQ) PublishJSON(ctx context.Context, exchange string, routingKey string, payload any) error {
|
||||
if r == nil {
|
||||
return errors.New("rabbitmq manager is nil")
|
||||
}
|
||||
if exchange == "" || routingKey == "" {
|
||||
return errors.New("exchange and routingKey are required")
|
||||
}
|
||||
b, err := json.Marshal(payload)
|
||||
|
||||
pub, err := buildPublishing(payload)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return ch.PublishWithContext(ctx, exchange, routingKey, false, false, amqp.Publishing{
|
||||
|
||||
ch, err := r.publisherChannel(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := ch.PublishWithContext(ctx, exchange, routingKey, false, false, pub); err != nil {
|
||||
r.invalidatePublisherChannel(ch)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Parker 由连接管理器实现,抽成接口是为了在没有 broker 的单测里验证停泊失败必须 requeue。
|
||||
type Parker interface {
|
||||
Park(ctx context.Context, sourceQueue string, d amqp.Delivery, attempts int, cause error) error
|
||||
}
|
||||
|
||||
// Park 把一条无法处理的消息停泊到 failed.events,调用方须在返回 nil 后才 Ack 原消息。
|
||||
func (r *RabbitMQ) Park(ctx context.Context, sourceQueue string, d amqp.Delivery, attempts int, cause error) error {
|
||||
if r == nil {
|
||||
return errors.New("rabbitmq manager is nil")
|
||||
}
|
||||
if sourceQueue == "" {
|
||||
return errors.New("park: source queue is required")
|
||||
}
|
||||
parkCtx, cancel := context.WithTimeout(ctx, parkTimeout)
|
||||
defer cancel()
|
||||
|
||||
sess, err := r.Session(parkCtx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("park: %w", err)
|
||||
}
|
||||
ch := sess.Ch
|
||||
defer ch.Close()
|
||||
|
||||
if err := ch.Confirm(false); err != nil {
|
||||
return fmt.Errorf("park: enable confirm: %w", err)
|
||||
}
|
||||
confirms := ch.NotifyPublish(make(chan amqp.Confirmation, 1))
|
||||
returns := ch.NotifyReturn(make(chan amqp.Return, 1))
|
||||
|
||||
headers := amqp.Table{}
|
||||
for k, v := range d.Headers {
|
||||
headers[k] = v
|
||||
}
|
||||
headers[HeaderSourceQueue] = sourceQueue
|
||||
headers[HeaderAttempts] = int32(attempts)
|
||||
if cause != nil {
|
||||
headers[HeaderLastError] = truncateString(cause.Error(), 512)
|
||||
}
|
||||
|
||||
pub := amqp.Publishing{
|
||||
ContentType: "application/json",
|
||||
DeliveryMode: amqp.Persistent,
|
||||
Timestamp: time.Now(),
|
||||
Headers: headers,
|
||||
Body: d.Body,
|
||||
}
|
||||
|
||||
if err := ch.PublishWithContext(parkCtx, DLXExchange, ParkedKeyPrefix+sourceQueue, true /*mandatory*/, false, pub); err != nil {
|
||||
return fmt.Errorf("park: publish: %w", err)
|
||||
}
|
||||
|
||||
select {
|
||||
case c, ok := <-confirms:
|
||||
if !ok || !c.Ack {
|
||||
return errors.New("park: broker rejected the message (nack)")
|
||||
}
|
||||
// broker 先发 basic.return 再发 basic.ack,确认后需非阻塞复查一次。
|
||||
select {
|
||||
case ret := <-returns:
|
||||
return fmt.Errorf("park: unroutable code=%d text=%q", ret.ReplyCode, ret.ReplyText)
|
||||
default:
|
||||
}
|
||||
return nil
|
||||
case ret := <-returns:
|
||||
return fmt.Errorf("park: unroutable code=%d text=%q", ret.ReplyCode, ret.ReplyText)
|
||||
case <-parkCtx.Done():
|
||||
return fmt.Errorf("park: %w", parkCtx.Err())
|
||||
}
|
||||
}
|
||||
|
||||
func truncateString(s string, max int) string {
|
||||
if max <= 0 || len(s) <= max {
|
||||
return s
|
||||
}
|
||||
return s[:max]
|
||||
}
|
||||
|
||||
func (r *RabbitMQ) invalidatePublisherChannel(ch *amqp.Channel) {
|
||||
if ch == nil {
|
||||
return
|
||||
}
|
||||
r.mu.Lock()
|
||||
if r.pubCh == ch {
|
||||
r.pubCh = nil
|
||||
}
|
||||
r.mu.Unlock()
|
||||
_ = ch.Close()
|
||||
}
|
||||
|
||||
func buildPublishing(payload any) (amqp.Publishing, error) {
|
||||
b, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return amqp.Publishing{}, err
|
||||
}
|
||||
return amqp.Publishing{
|
||||
ContentType: "application/json", // 消息格式
|
||||
DeliveryMode: amqp.Persistent, // 消息持久化到磁盘, 值为 1 则不持久化, 值为 2 则持久化, amqp.Presistent 为 2
|
||||
Timestamp: time.Now(), // 消息产生的时间戳
|
||||
Body: b, // 实际消息内容(JSON字节)
|
||||
})
|
||||
DeliveryMode: amqp.Persistent, // 持久化(2 = 落盘)
|
||||
Timestamp: time.Now(), // 消息产生时间戳
|
||||
Body: b, // 实际消息内容
|
||||
}, nil
|
||||
}
|
||||
|
||||
// —— 内部工具 ——
|
||||
|
||||
func closeIfOpen(ch chan struct{}) {
|
||||
select {
|
||||
case <-ch:
|
||||
default:
|
||||
close(ch)
|
||||
}
|
||||
}
|
||||
|
||||
// findTopology 按 (Exchange, Queue, BindingKey) 三元组查找已登记的拓扑,RetryDelay 不参与比较。
|
||||
func findTopology(list []Topology, t Topology) (Topology, bool) {
|
||||
for _, x := range list {
|
||||
if x.Exchange == t.Exchange && x.Queue == t.Queue && x.BindingKey == t.BindingKey {
|
||||
return x, true
|
||||
}
|
||||
}
|
||||
return Topology{}, false
|
||||
}
|
||||
|
||||
// sleepOrClosed 休眠 d;管理器关闭时返回 false。
|
||||
// 绝不直接使用 time.Sleep——否则 Close() 会被最长 MaxBackoff 的休眠拖住。
|
||||
func (r *RabbitMQ) sleepOrClosed(d time.Duration) bool {
|
||||
t := time.NewTimer(d)
|
||||
defer t.Stop()
|
||||
select {
|
||||
case <-t.C:
|
||||
return true
|
||||
case <-r.closed:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// nextBackoff 指数增长 + 上限 + 抖动。
|
||||
func nextBackoff(cur time.Duration, opts ReconnectOptions) time.Duration {
|
||||
next := cur * 2
|
||||
if next > opts.MaxBackoff {
|
||||
next = opts.MaxBackoff
|
||||
}
|
||||
if opts.Jitter > 0 {
|
||||
delta := float64(next) * opts.Jitter
|
||||
next = time.Duration(float64(next) - delta + mrand.Float64()*2*delta)
|
||||
}
|
||||
if next <= 0 {
|
||||
next = opts.MinBackoff
|
||||
}
|
||||
return next
|
||||
}
|
||||
|
||||
func newEventID(n int) (string, error) {
|
||||
|
||||
525
backend/internal/middleware/rabbitmq/rabbitmq_test.go
Normal file
525
backend/internal/middleware/rabbitmq/rabbitmq_test.go
Normal file
@@ -0,0 +1,525 @@
|
||||
package rabbitmq
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
)
|
||||
|
||||
// —— 测试替身 ——
|
||||
|
||||
// fakeConn 实现 connection 接口,让连接代状态机可以脱离 broker 被测试。
|
||||
// 它不参与任何网络 I/O:Channel() 只在"健康"时返回 (nil, nil)。
|
||||
type fakeConn struct {
|
||||
mu sync.Mutex
|
||||
closed bool
|
||||
}
|
||||
|
||||
func (f *fakeConn) Channel() (*amqp.Channel, error) {
|
||||
if f.IsClosed() {
|
||||
return nil, amqp.ErrClosed
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (f *fakeConn) NotifyClose(c chan *amqp.Error) chan *amqp.Error { return c }
|
||||
|
||||
func (f *fakeConn) IsClosed() bool {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return f.closed
|
||||
}
|
||||
|
||||
func (f *fakeConn) Close() error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.closed = true
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeConn) markClosed() {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.closed = true
|
||||
}
|
||||
|
||||
// newTestManager 构造一个不建立任何连接的裸管理器(只用于状态机测试)。
|
||||
func newTestManager() *RabbitMQ {
|
||||
return &RabbitMQ{
|
||||
opts: DefaultReconnectOptions(),
|
||||
gen: make(chan struct{}),
|
||||
ready: make(chan struct{}),
|
||||
closed: make(chan struct{}),
|
||||
}
|
||||
}
|
||||
|
||||
func isClosed(ch chan struct{}) bool {
|
||||
select {
|
||||
case <-ch:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// —— 退避策略 ——
|
||||
|
||||
func TestNextBackoff_ExponentialCappedJittered(t *testing.T) {
|
||||
opts := ReconnectOptions{MinBackoff: 500 * time.Millisecond, MaxBackoff: 4 * time.Second, Jitter: 0.2}
|
||||
|
||||
d := opts.MinBackoff
|
||||
for i := 0; i < 20; i++ {
|
||||
d = nextBackoff(d, opts)
|
||||
if d <= 0 {
|
||||
t.Fatalf("backoff must stay positive, got %v", d)
|
||||
}
|
||||
// 抖动上限:不超过 MaxBackoff * (1+Jitter)
|
||||
if max := time.Duration(float64(opts.MaxBackoff) * (1 + opts.Jitter)); d > max {
|
||||
t.Fatalf("backoff %v exceeds jittered cap %v", d, max)
|
||||
}
|
||||
}
|
||||
if d < opts.MaxBackoff/2 {
|
||||
t.Fatalf("backoff must converge to MaxBackoff, got %v", d)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNextBackoff_NoJitterIsExact(t *testing.T) {
|
||||
opts := ReconnectOptions{MinBackoff: time.Second, MaxBackoff: 8 * time.Second}
|
||||
want := []time.Duration{2 * time.Second, 4 * time.Second, 8 * time.Second, 8 * time.Second}
|
||||
|
||||
d := opts.MinBackoff
|
||||
for i, w := range want {
|
||||
d = nextBackoff(d, opts)
|
||||
if d != w {
|
||||
t.Fatalf("step %d: want %v, got %v", i, w, d)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// —— 连接代状态机(P0-2 的核心) ——
|
||||
|
||||
// 断连期间 WaitReady 必须"阻塞",而不是空转返回——这是 96 行/分钟日志噪声的根源。
|
||||
func TestWaitReady_BlocksWhileDisconnected_ReturnsWhenConnected(t *testing.T) {
|
||||
r := newTestManager()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
|
||||
defer cancel()
|
||||
if err := r.WaitReady(ctx); !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("disconnected: want DeadlineExceeded, got %v", err)
|
||||
}
|
||||
|
||||
r.install(&fakeConn{})
|
||||
if err := r.WaitReady(context.Background()); err != nil {
|
||||
t.Fatalf("connected: want nil, got %v", err)
|
||||
}
|
||||
|
||||
r.markDown()
|
||||
ctx2, cancel2 := context.WithTimeout(context.Background(), 50*time.Millisecond)
|
||||
defer cancel2()
|
||||
if err := r.WaitReady(ctx2); !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("after markDown: want DeadlineExceeded, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// 最危险的一类回归:install 忘记唤醒等待者 → 消费者永久挂起,
|
||||
// 症状与"根本没修"无法区分。
|
||||
func TestInstall_WakesConsumersBlockedInWaitReady(t *testing.T) {
|
||||
r := newTestManager()
|
||||
r.markDown()
|
||||
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- r.WaitReady(context.Background()) }()
|
||||
time.Sleep(20 * time.Millisecond) // 让 goroutine 进入 select
|
||||
|
||||
r.install(&fakeConn{})
|
||||
|
||||
select {
|
||||
case err := <-done:
|
||||
if err != nil {
|
||||
t.Fatalf("waiter must be woken by install: %v", err)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("P0-2: install must wake consumers blocked in WaitReady (they would hang forever)")
|
||||
}
|
||||
}
|
||||
|
||||
// markDown 必须结束当前代(唤醒持有旧 channel 的消费者)并广播状态变化。
|
||||
func TestMarkDown_ClosesGenerationAndBroadcastsStateChange(t *testing.T) {
|
||||
r := newTestManager()
|
||||
r.install(&fakeConn{})
|
||||
|
||||
r.mu.Lock()
|
||||
genBefore, readyBefore := r.gen, r.ready
|
||||
r.mu.Unlock()
|
||||
|
||||
r.markDown()
|
||||
|
||||
if !isClosed(genBefore) {
|
||||
t.Fatal("P0-2: markDown must close the current generation to wake consumers")
|
||||
}
|
||||
r.mu.Lock()
|
||||
genAfter, readyAfter := r.gen, r.ready
|
||||
r.mu.Unlock()
|
||||
|
||||
if genAfter == genBefore {
|
||||
t.Fatal("markDown must install a fresh generation channel")
|
||||
}
|
||||
if !isClosed(readyBefore) {
|
||||
t.Fatal("markDown must broadcast a state change so WaitReady re-evaluates")
|
||||
}
|
||||
if readyAfter == readyBefore {
|
||||
t.Fatal("markDown must install a fresh ready channel")
|
||||
}
|
||||
}
|
||||
|
||||
// 代令牌必须与 channel 配对:连接代结束时 sess.Done 必须关闭,
|
||||
// 否则消费者无法区分"连接级失效"与"channel 级异常"。
|
||||
func TestSession_GenerationTokenClosesWhenItsConnectionEnds(t *testing.T) {
|
||||
r := newTestManager()
|
||||
r.install(&fakeConn{})
|
||||
|
||||
sess, err := r.Session(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("Session: %v", err)
|
||||
}
|
||||
|
||||
select {
|
||||
case <-sess.Done:
|
||||
t.Fatal("generation token must not be closed while the connection is alive")
|
||||
default:
|
||||
}
|
||||
|
||||
r.markDown()
|
||||
|
||||
select {
|
||||
case <-sess.Done:
|
||||
default:
|
||||
t.Fatal("P0-2: session token must close when its own connection generation ends")
|
||||
}
|
||||
}
|
||||
|
||||
// 连接已失效但 manager 尚未感知(NotifyClose 还没派发)时,
|
||||
// Session 不允许返回一个死连接上的 channel,必须等到下一代。
|
||||
func TestSession_WaitsForNextGenerationWhenConnectionIsAlreadyClosed(t *testing.T) {
|
||||
r := newTestManager()
|
||||
conn := &fakeConn{}
|
||||
r.install(conn)
|
||||
conn.markClosed() // manager 尚未 markDown
|
||||
|
||||
got := make(chan *Session, 1)
|
||||
go func() {
|
||||
s, err := r.Session(context.Background())
|
||||
if err != nil {
|
||||
got <- nil
|
||||
return
|
||||
}
|
||||
got <- s
|
||||
}()
|
||||
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
select {
|
||||
case <-got:
|
||||
t.Fatal("Session must not hand out a channel from a dead connection")
|
||||
default:
|
||||
}
|
||||
|
||||
// 新的一代到来:Session 必须恢复
|
||||
r.markDown()
|
||||
r.install(&fakeConn{})
|
||||
|
||||
select {
|
||||
case s := <-got:
|
||||
if s == nil {
|
||||
t.Fatal("Session must succeed on the next generation")
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("P0-2: Session must resume once a new generation is installed")
|
||||
}
|
||||
}
|
||||
|
||||
// 重复 close 会 panic 并杀掉进程:install / markDown 必须可重入。
|
||||
func TestInstallAndMarkDown_DoNotDoubleCloseChannels(t *testing.T) {
|
||||
r := newTestManager()
|
||||
|
||||
r.install(&fakeConn{})
|
||||
r.install(&fakeConn{}) // 重复 install 不得 panic
|
||||
r.markDown()
|
||||
r.markDown() // 重复 markDown 不得 panic
|
||||
r.install(&fakeConn{})
|
||||
}
|
||||
|
||||
func TestClose_IsIdempotentAndUnblocksWaiters(t *testing.T) {
|
||||
r := newTestManager()
|
||||
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- r.WaitReady(context.Background()) }()
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
|
||||
if err := r.Close(); err != nil {
|
||||
t.Fatalf("Close: %v", err)
|
||||
}
|
||||
if err := r.Close(); err != nil {
|
||||
t.Fatalf("Close must be idempotent: %v", err)
|
||||
}
|
||||
|
||||
select {
|
||||
case err := <-done:
|
||||
if !errors.Is(err, ErrManagerClosed) {
|
||||
t.Fatalf("want ErrManagerClosed, got %v", err)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("Close must unblock WaitReady")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewChannel_RequiresActiveConnection(t *testing.T) {
|
||||
r := newTestManager()
|
||||
|
||||
if _, err := r.NewChannel(); !errors.Is(err, ErrNotConnected) {
|
||||
t.Fatalf("disconnected: want ErrNotConnected, got %v", err)
|
||||
}
|
||||
|
||||
r.install(&fakeConn{})
|
||||
if _, err := r.NewChannel(); err != nil {
|
||||
t.Fatalf("connected: want nil, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNilManager_DoesNotPanic(t *testing.T) {
|
||||
var r *RabbitMQ
|
||||
|
||||
if r.Healthy() {
|
||||
t.Fatal("nil manager must not report healthy")
|
||||
}
|
||||
if (r.Stats() != Stats{}) {
|
||||
t.Fatal("nil manager must return zero stats")
|
||||
}
|
||||
if err := r.Close(); err != nil {
|
||||
t.Fatalf("nil manager Close must be a no-op, got %v", err)
|
||||
}
|
||||
if err := r.PublishJSON(context.Background(), "e", "k", nil); err == nil {
|
||||
t.Fatal("nil manager PublishJSON must return an error")
|
||||
}
|
||||
r.RegisterTopology(Topology{Exchange: "e", Queue: "q", BindingKey: "k"}) // 不得 panic
|
||||
}
|
||||
|
||||
// —— 拓扑登记 ——
|
||||
|
||||
func TestRegisterTopology_DedupAndValidate(t *testing.T) {
|
||||
r := newTestManager()
|
||||
good := Topology{Exchange: "e", Queue: "q", BindingKey: "k"}
|
||||
|
||||
r.RegisterTopology(good, good)
|
||||
if got := r.Stats().Topology; got != 1 {
|
||||
t.Fatalf("duplicate topology must be deduped, got %d", got)
|
||||
}
|
||||
|
||||
r.RegisterTopology(Topology{Exchange: "", Queue: "q", BindingKey: "k"})
|
||||
r.RegisterTopology(Topology{Exchange: "e", Queue: "", BindingKey: "k"})
|
||||
r.RegisterTopology(Topology{Exchange: "e", Queue: "q", BindingKey: ""})
|
||||
if got := r.Stats().Topology; got != 1 {
|
||||
t.Fatalf("invalid topology must be ignored, got %d", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTopology_ReturnsCopyNotInternalSlice(t *testing.T) {
|
||||
r := newTestManager()
|
||||
r.RegisterTopology(Topology{Exchange: "e", Queue: "q", BindingKey: "k"})
|
||||
|
||||
got := r.Topology()
|
||||
if len(got) != 1 {
|
||||
t.Fatalf("want 1 topology, got %d", len(got))
|
||||
}
|
||||
got[0].Exchange = "mutated"
|
||||
|
||||
if again := r.Topology(); again[0].Exchange != "e" {
|
||||
t.Fatal("Topology() must return a copy; internal state was mutated")
|
||||
}
|
||||
}
|
||||
|
||||
// —— 拓扑声明(假 declarer,无需 broker) ——
|
||||
|
||||
type queueDecl struct {
|
||||
name string
|
||||
args amqp.Table
|
||||
}
|
||||
|
||||
type fakeDeclarer struct {
|
||||
mu sync.Mutex
|
||||
calls []string
|
||||
queues []queueDecl
|
||||
|
||||
// failOn / failErr 让某个具体声明步骤失败,用于验证"停泊链路失败即终止重放"。
|
||||
// 取值形如 "exchange:dlx.events"、"queue:failed.events"、"bind:failed.events"。
|
||||
failOn string
|
||||
failErr error
|
||||
}
|
||||
|
||||
func (f *fakeDeclarer) ExchangeDeclare(name, kind string, durable, autoDelete, internal, noWait bool, args amqp.Table) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.calls = append(f.calls, "exchange:"+name)
|
||||
if f.failOn == "exchange:"+name {
|
||||
return f.failErr
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeDeclarer) QueueDeclare(name string, durable, autoDelete, exclusive, noWait bool, args amqp.Table) (amqp.Queue, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.calls = append(f.calls, "queue:"+name)
|
||||
f.queues = append(f.queues, queueDecl{name: name, args: args})
|
||||
if f.failOn == "queue:"+name {
|
||||
return amqp.Queue{}, f.failErr
|
||||
}
|
||||
return amqp.Queue{Name: name}, nil
|
||||
}
|
||||
|
||||
func (f *fakeDeclarer) QueueBind(name, key, exchange string, noWait bool, args amqp.Table) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.calls = append(f.calls, "bind:"+name+"<-"+exchange+"/"+key)
|
||||
if f.failOn == "bind:"+name {
|
||||
return f.failErr
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// indexOf 返回某次声明的下标(不存在为 -1),用于断言声明顺序。
|
||||
func (f *fakeDeclarer) indexOf(call string) int {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
for i, c := range f.calls {
|
||||
if c == call {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
// queueArgs 返回指定队列被声明时使用的参数。
|
||||
func (f *fakeDeclarer) queueArgs(name string) (amqp.Table, bool) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
for _, q := range f.queues {
|
||||
if q.name == name {
|
||||
return q.args, true
|
||||
}
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
func TestDeclareTopologies_OrderAndDeadLetterExchange(t *testing.T) {
|
||||
f := &fakeDeclarer{}
|
||||
err := DeclareTopologies(f, []Topology{
|
||||
{Exchange: "like.events", Queue: "like.events", BindingKey: "like.*"},
|
||||
{Exchange: "comment.events", Queue: "comment.events", BindingKey: "comment.*"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("DeclareTopologies: %v", err)
|
||||
}
|
||||
|
||||
joined := strings.Join(f.calls, " ")
|
||||
// 批次 0 起,停泊链路先于业务拓扑声明:消息被拒绝的那一刻,
|
||||
// 停泊交换机与队列必须已经存在,否则 broker 静默丢弃(§6.7.5)。
|
||||
if !strings.HasPrefix(joined, "exchange:dlx.events queue:failed.events bind:failed.events<-dlx.events/parked.#") {
|
||||
t.Fatalf("停泊链路必须先于业务拓扑: %v", f.calls)
|
||||
}
|
||||
// 业务侧顺序固定:交换机 → 重试交换机 → 业务队列 → 绑定 →
|
||||
// 重试队列 → 重试绑定。重试交换机必须先于业务队列:队列被拒绝的那一刻
|
||||
// 若找不到 DLX,broker 会直接丢弃消息,只在日志里留一行 warning。
|
||||
start := f.indexOf("exchange:like.events")
|
||||
if start < 0 {
|
||||
t.Fatalf("业务交换机从未被声明: %v", f.calls)
|
||||
}
|
||||
wantBefore := "exchange:like.events exchange:retry.events.like.events queue:like.events bind:like.events<-like.events/like.*"
|
||||
if business := strings.Join(f.calls[start:], " "); !strings.HasPrefix(business, wantBefore) {
|
||||
t.Fatalf("unexpected declare order: %v", f.calls)
|
||||
}
|
||||
|
||||
for _, q := range []string{"like.events", "comment.events"} {
|
||||
args, ok := f.queueArgs(q)
|
||||
if !ok {
|
||||
t.Fatalf("queue %s was never declared", q)
|
||||
}
|
||||
// 业务队列的死信去向必须是本队列专属的重试交换机。若仍指向共享的
|
||||
// dlx.events,重试消息会跨队列回源(notification.comment 的重试
|
||||
// 落回 comment.events 会再插一条评论)。
|
||||
if args == nil || args["x-dead-letter-exchange"] != RetryExchange(q) {
|
||||
t.Fatalf("queue %s 的 DLX 必须指向 %s: %v", q, RetryExchange(q), args)
|
||||
}
|
||||
// 不设 routing-key,第 1 次被拒时原路由键才能保留
|
||||
if _, ok := args["x-dead-letter-routing-key"]; ok {
|
||||
t.Fatalf("queue %s 不应设 x-dead-letter-routing-key: %v", q, args)
|
||||
}
|
||||
// 旧的每队列死信队列是扇出缺陷的源头,不能再声明
|
||||
if _, ok := f.queueArgs(q + ".dlx"); ok {
|
||||
t.Fatalf("%s.dlx 不应再被声明: %v", q, f.calls)
|
||||
}
|
||||
|
||||
retryArgs, ok := f.queueArgs(RetryQueueName(q))
|
||||
if !ok {
|
||||
t.Fatalf("retry queue %s was never declared", RetryQueueName(q))
|
||||
}
|
||||
// 经默认交换机回源:空 exchange + 队列名做 routing-key
|
||||
if retryArgs["x-dead-letter-exchange"] != "" {
|
||||
t.Fatalf("retry queue 必须经默认交换机回源: %v", retryArgs)
|
||||
}
|
||||
if retryArgs["x-dead-letter-routing-key"] != q {
|
||||
t.Fatalf("retry queue 必须精确回源到 %s: %v", q, retryArgs)
|
||||
}
|
||||
if retryArgs["x-message-ttl"] != int64(DefaultRetryDelay/time.Millisecond) {
|
||||
t.Fatalf("retry queue 默认延迟必须是 %v: %v", DefaultRetryDelay, retryArgs)
|
||||
}
|
||||
}
|
||||
|
||||
if !strings.Contains(joined, "bind:like.events.retry<-retry.events.like.events/#") {
|
||||
t.Fatalf("retry queue not bound to retry exchange: %v", f.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeclareTopology_ValidatesInput(t *testing.T) {
|
||||
f := &fakeDeclarer{}
|
||||
|
||||
if err := DeclareTopology(nil, Topology{Exchange: "e", Queue: "q", BindingKey: "k"}); err == nil {
|
||||
t.Fatal("nil declarer must be rejected")
|
||||
}
|
||||
if err := DeclareTopology(f, Topology{Exchange: "", Queue: "q", BindingKey: "k"}); err == nil {
|
||||
t.Fatal("empty exchange must be rejected")
|
||||
}
|
||||
// 类型化的 nil channel 无法被接口判断拦住,因此入口保留了自己的检查
|
||||
if err := DeclareTopic(nil, "e", "q", "k"); err == nil {
|
||||
t.Fatal("DeclareTopic(nil channel) must be rejected, not panic")
|
||||
}
|
||||
// 合法输入必须通过,并经 fakeDeclarer 观察到声明动作
|
||||
if err := DeclareTopic(nil, "e", "q", "k"); err == nil {
|
||||
t.Fatal("DeclareTopic must validate before touching the channel")
|
||||
}
|
||||
}
|
||||
|
||||
// 去重键是 (Exchange, Queue, BindingKey) 三元组,RETRY delay 不参与。
|
||||
//
|
||||
// 若把 RetryDelay 也算进去,同一个队列登记两种延迟就会产生两次不等价的
|
||||
// queue declare。broker 对参数不一致的重复声明回 406,而 P0-2 的不变式是
|
||||
// "拓扑重放失败则这一代连接不 install" —— 8 个消费者会全部不启动。
|
||||
func TestRegisterTopology_DedupIgnoresRetryDelay(t *testing.T) {
|
||||
r := newTestManager()
|
||||
defer r.Close()
|
||||
|
||||
r.RegisterTopology(Topology{Exchange: "e", Queue: "q", BindingKey: "k", RetryDelay: 5 * time.Second})
|
||||
r.RegisterTopology(Topology{Exchange: "e", Queue: "q", BindingKey: "k", RetryDelay: 30 * time.Second})
|
||||
|
||||
got := r.Topology()
|
||||
if len(got) != 1 {
|
||||
t.Fatalf("同队列两种延迟只能登记一条: %d", len(got))
|
||||
}
|
||||
if got[0].RetryDelay != 5*time.Second {
|
||||
t.Fatalf("应保留先登记的延迟: %v", got[0].RetryDelay)
|
||||
}
|
||||
}
|
||||
64
backend/internal/middleware/rabbitmq/retrycount_test.go
Normal file
64
backend/internal/middleware/rabbitmq/retrycount_test.go
Normal file
@@ -0,0 +1,64 @@
|
||||
package rabbitmq
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
)
|
||||
|
||||
// TestGetRetryCount_CountsOnlyRejected 守护两个曾经让计数恒为 0 的坑:
|
||||
// 读 deaths[0](真实链路里常常是重试队列的 expired),以及把 count 断言成 int64。
|
||||
func TestGetRetryCount_CountsOnlyRejected(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
headers amqp.Table
|
||||
want int
|
||||
}{
|
||||
{"无 x-death", amqp.Table{}, 0},
|
||||
{"x-death 类型不对", amqp.Table{"x-death": "nope"}, 0},
|
||||
{
|
||||
name: "只有 expired 不算重试",
|
||||
headers: amqp.Table{"x-death": []interface{}{
|
||||
amqp.Table{"queue": "like.events.retry", "reason": "expired", "count": int64(1)},
|
||||
}},
|
||||
want: 0,
|
||||
},
|
||||
{
|
||||
name: "int64 计数的 rejected",
|
||||
headers: amqp.Table{"x-death": []interface{}{
|
||||
amqp.Table{"queue": "like.events", "reason": "rejected", "count": int64(2)},
|
||||
}},
|
||||
want: 2,
|
||||
},
|
||||
{
|
||||
name: "int32 计数的 rejected",
|
||||
headers: amqp.Table{"x-death": []interface{}{
|
||||
amqp.Table{"queue": "like.events", "reason": "rejected", "count": int32(1)},
|
||||
}},
|
||||
want: 1,
|
||||
},
|
||||
{
|
||||
name: "rejected 与 expired 混合时只累加 rejected",
|
||||
headers: amqp.Table{"x-death": []interface{}{
|
||||
amqp.Table{"queue": "like.events.retry", "reason": "expired", "count": int64(3)},
|
||||
amqp.Table{"queue": "like.events", "reason": "rejected", "count": int64(3)},
|
||||
}},
|
||||
want: 3,
|
||||
},
|
||||
{
|
||||
name: "多条 rejected 累加",
|
||||
headers: amqp.Table{"x-death": []interface{}{
|
||||
amqp.Table{"queue": "a", "reason": "rejected", "count": int64(1)},
|
||||
amqp.Table{"queue": "b", "reason": "rejected", "count": int64(2)},
|
||||
}},
|
||||
want: 3,
|
||||
},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
if got := GetRetryCount(amqp.Delivery{Headers: c.headers}); got != c.want {
|
||||
t.Fatalf("GetRetryCount = %d, want %d", got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -4,21 +4,18 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
)
|
||||
|
||||
// SocialMQ 通过连接管理器发布关注事件(不再持有长生命周期 channel)。
|
||||
type SocialMQ struct {
|
||||
ch *amqp.Channel
|
||||
mgr *RabbitMQ
|
||||
}
|
||||
|
||||
// 拓扑常量导出:见 likeMQ.go 中的说明。
|
||||
const (
|
||||
socialExchange = "social.events"
|
||||
socialQueue = "social.events"
|
||||
socialBindingKey = "social.*"
|
||||
SocialExchange = "social.events"
|
||||
|
||||
socialFollowRK = "social.follow"
|
||||
socialUnfollowRK = "social.unfollow"
|
||||
SocialFollowRK = "social.follow"
|
||||
)
|
||||
|
||||
type SocialEvent struct {
|
||||
@@ -29,31 +26,21 @@ type SocialEvent struct {
|
||||
OccurredAt time.Time `json:"occurred_at"`
|
||||
}
|
||||
|
||||
// NewSocialMQ 只登记关注通知的落点:服务层已先写库,事件不再承担写库职责。
|
||||
func NewSocialMQ(base *RabbitMQ) (*SocialMQ, error) {
|
||||
if base == nil {
|
||||
return nil, errors.New("rabbitmq base is nil")
|
||||
}
|
||||
ch, err := base.NewChannel()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := DeclareTopic(ch, socialExchange, socialQueue, socialBindingKey); err != nil {
|
||||
ch.Close()
|
||||
return nil, err
|
||||
}
|
||||
return &SocialMQ{ch: ch}, nil
|
||||
base.RegisterTopology(Topology{Exchange: SocialExchange, Queue: NotificationSocialQueue, BindingKey: SocialFollowRK})
|
||||
return &SocialMQ{mgr: base}, nil
|
||||
}
|
||||
|
||||
func (s *SocialMQ) Follow(ctx context.Context, followerID, vloggerID uint) error {
|
||||
return s.publish(ctx, "follow", socialFollowRK, followerID, vloggerID)
|
||||
}
|
||||
|
||||
func (s *SocialMQ) UnFollow(ctx context.Context, followerID, vloggerID uint) error {
|
||||
return s.publish(ctx, "unfollow", socialUnfollowRK, followerID, vloggerID)
|
||||
return s.publish(ctx, "follow", SocialFollowRK, followerID, vloggerID)
|
||||
}
|
||||
|
||||
func (s *SocialMQ) publish(ctx context.Context, action, routingKey string, followerID, vloggerID uint) error {
|
||||
if s == nil || s.ch == nil {
|
||||
if s == nil || s.mgr == nil {
|
||||
return errors.New("social mq is not initialized")
|
||||
}
|
||||
if followerID == 0 || vloggerID == 0 {
|
||||
@@ -70,5 +57,5 @@ func (s *SocialMQ) publish(ctx context.Context, action, routingKey string, follo
|
||||
VloggerID: vloggerID,
|
||||
OccurredAt: time.Now().UTC(),
|
||||
}
|
||||
return PublishJSON(ctx, s.ch, socialExchange, routingKey, evt)
|
||||
return s.mgr.PublishJSON(ctx, SocialExchange, routingKey, evt)
|
||||
}
|
||||
|
||||
@@ -4,19 +4,21 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
)
|
||||
|
||||
// TimelineMQ 通过连接管理器发布时间线事件(不再持有长生命周期 channel)。
|
||||
type TimelineMQ struct {
|
||||
ch *amqp.Channel
|
||||
mgr *RabbitMQ
|
||||
}
|
||||
|
||||
// 拓扑常量导出:见 likeMQ.go 中的说明。
|
||||
// 注意 TimelineQueue 与 TimelineExchange 刻意不同名:时间线交换机将来可能
|
||||
// 挂多个队列(全局时间线、关注时间线…),队列名需要自带语义。
|
||||
const (
|
||||
timelineExchange = "video.timeline.events"
|
||||
timelineQueue = "video.timeline.update.queue"
|
||||
timelineBindingKey = "video.timeline.*"
|
||||
timelinePublishRK = "video.timeline.publish"
|
||||
TimelineExchange = "video.timeline.events"
|
||||
TimelineQueue = "video.timeline.update.queue"
|
||||
TimelineBindingKey = "video.timeline.*"
|
||||
TimelinePublishRK = "video.timeline.publish"
|
||||
)
|
||||
|
||||
type TimelineEvent struct {
|
||||
@@ -30,19 +32,12 @@ func NewTimelineMQ(base *RabbitMQ) (*TimelineMQ, error) {
|
||||
if base == nil {
|
||||
return nil, errors.New("rabbitmq base is nil")
|
||||
}
|
||||
ch, err := base.NewChannel()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := DeclareTopic(ch, timelineExchange, timelineQueue, timelineBindingKey); err != nil {
|
||||
ch.Close()
|
||||
return nil, err
|
||||
}
|
||||
return &TimelineMQ{ch: ch}, nil
|
||||
base.RegisterTopology(Topology{Exchange: TimelineExchange, Queue: TimelineQueue, BindingKey: TimelineBindingKey})
|
||||
return &TimelineMQ{mgr: base}, nil
|
||||
}
|
||||
|
||||
func (t *TimelineMQ) PublishVideo(ctx context.Context, videoID uint, createTime time.Time) error {
|
||||
if t == nil || t.ch == nil {
|
||||
if t == nil || t.mgr == nil {
|
||||
return errors.New("timeline mq is not initialized")
|
||||
}
|
||||
if videoID == 0 {
|
||||
@@ -58,5 +53,5 @@ func (t *TimelineMQ) PublishVideo(ctx context.Context, videoID uint, createTime
|
||||
CreateTime: createTime.UnixMilli(),
|
||||
OccurredAt: time.Now(),
|
||||
}
|
||||
return PublishJSON(ctx, t.ch, timelineExchange, timelinePublishRK, timeline)
|
||||
return t.mgr.PublishJSON(ctx, TimelineExchange, TimelinePublishRK, timeline)
|
||||
}
|
||||
|
||||
93
backend/internal/middleware/rabbitmq/topology.go
Normal file
93
backend/internal/middleware/rabbitmq/topology.go
Normal file
@@ -0,0 +1,93 @@
|
||||
package rabbitmq
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
)
|
||||
|
||||
// Topology 描述一组"交换机 + 队列 + 绑定键",是可重复声明的幂等单元。
|
||||
type Topology struct {
|
||||
Exchange string
|
||||
Queue string
|
||||
BindingKey string
|
||||
// RetryDelay 是本队列重试队列的 TTL,零值取 DefaultRetryDelay;不参与去重。
|
||||
RetryDelay time.Duration
|
||||
}
|
||||
|
||||
// declarer 是拓扑声明所需方法的最小集合,抽出接口只为可测性。
|
||||
type declarer interface {
|
||||
ExchangeDeclare(name, kind string, durable, autoDelete, internal, noWait bool, args amqp.Table) error
|
||||
QueueDeclare(name string, durable, autoDelete, exclusive, noWait bool, args amqp.Table) (amqp.Queue, error)
|
||||
QueueBind(name, key, exchange string, noWait bool, args amqp.Table) error
|
||||
}
|
||||
|
||||
// DeclareTopology 按固定顺序声明一组拓扑。
|
||||
//
|
||||
// 顺序不可换:业务队列被拒绝时必须能找到一个已存在的 DLX,否则 broker 直接丢弃消息。
|
||||
func DeclareTopology(d declarer, t Topology) error {
|
||||
if d == nil {
|
||||
return errors.New("channel is not initialized")
|
||||
}
|
||||
if t.Exchange == "" || t.Queue == "" || t.BindingKey == "" {
|
||||
return errors.New("exchange/queue/bindingKey is required")
|
||||
}
|
||||
|
||||
// 1. 业务交换机
|
||||
if err := d.ExchangeDeclare(t.Exchange, "topic", true, false, false, false, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 2. 本队列专属的重试交换机,必须先于业务队列
|
||||
retryExchange := RetryExchange(t.Queue)
|
||||
if err := d.ExchangeDeclare(retryExchange, "topic", true, false, false, false, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 3. 业务队列:DLX 指向重试交换机
|
||||
q, err := d.QueueDeclare(t.Queue, true, false, false, false, RetryArgs(t.Queue))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 4. 业务绑定
|
||||
if err := d.QueueBind(q.Name, t.BindingKey, t.Exchange, false, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 5. 重试队列:没有消费者,靠 TTL 到期经默认交换机回源
|
||||
delay := t.RetryDelay
|
||||
if delay <= 0 {
|
||||
delay = DefaultRetryDelay
|
||||
}
|
||||
rq, err := d.QueueDeclare(RetryQueueName(t.Queue), true, false, false, false, RetryQueueArgs(t.Queue, delay))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 6. 重试绑定:第 1 次被拒时保留的是原路由键,一条 # 绑定覆盖全部
|
||||
return d.QueueBind(rq.Name, "#", retryExchange, false, nil)
|
||||
}
|
||||
|
||||
// DeclareTopologies 先声明停泊链路,再逐个声明业务拓扑。
|
||||
func DeclareTopologies(d declarer, topo []Topology) error {
|
||||
if err := declareParking(d); err != nil {
|
||||
return fmt.Errorf("declare parking: %w", err)
|
||||
}
|
||||
for _, t := range topo {
|
||||
if err := DeclareTopology(d, t); err != nil {
|
||||
return fmt.Errorf("declare %s/%s: %w", t.Exchange, t.Queue, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeclareTopic 保留原有签名。
|
||||
func DeclareTopic(ch *amqp.Channel, exchange string, queue string, bindingKey string) error {
|
||||
if ch == nil {
|
||||
return errors.New("channel is not initialized")
|
||||
}
|
||||
return DeclareTopology(ch, Topology{Exchange: exchange, Queue: queue, BindingKey: bindingKey})
|
||||
}
|
||||
@@ -27,6 +27,15 @@ func (c *Client) Del(ctx context.Context, key string) error {
|
||||
return c.rdb.Del(ctx, key).Err()
|
||||
}
|
||||
|
||||
// SetNX 仅在 key 不存在时写入;key 由调用方拼好。
|
||||
// 失败必须返回 error,调用方据此判断占位是否生效。
|
||||
func (c *Client) SetNX(ctx context.Context, key string, value []byte, ttl time.Duration) (bool, error) {
|
||||
if c == nil || c.rdb == nil {
|
||||
return false, errors.New("redis client not initialized")
|
||||
}
|
||||
return c.rdb.SetNX(ctx, key, value, ttl).Result()
|
||||
}
|
||||
|
||||
func (c *Client) DelByPattern(ctx context.Context, pattern string) error {
|
||||
if c == nil || c.rdb == nil {
|
||||
return nil
|
||||
|
||||
@@ -103,6 +103,27 @@ func (c *Client) Unlock(ctx context.Context, key string, token string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// 频道名由调用方用 Key 加前缀,多环境共享同一 Redis 时不串台。
|
||||
func (c *Client) Publish(ctx context.Context, channel string, payload []byte) error {
|
||||
if c == nil || c.rdb == nil {
|
||||
return errors.New("redis client not initialized")
|
||||
}
|
||||
return c.rdb.Publish(ctx, channel, payload).Err()
|
||||
}
|
||||
|
||||
// Subscribe 返回前等 broker 确认订阅生效,避免丢第一批消息;PubSub 由调用方 Close。
|
||||
func (c *Client) Subscribe(ctx context.Context, channel string) (*redis.PubSub, error) {
|
||||
if c == nil || c.rdb == nil {
|
||||
return nil, errors.New("redis client not initialized")
|
||||
}
|
||||
ps := c.rdb.Subscribe(ctx, channel)
|
||||
if _, err := ps.Receive(ctx); err != nil {
|
||||
_ = ps.Close()
|
||||
return nil, err
|
||||
}
|
||||
return ps, nil
|
||||
}
|
||||
|
||||
func (c *Client) IncrementWithExpire(ctx context.Context, key string, expire time.Duration) (int64, error) {
|
||||
if c == nil || c.rdb == nil {
|
||||
return 0, nil
|
||||
|
||||
60
backend/internal/middleware/redis/setnx_test.go
Normal file
60
backend/internal/middleware/redis/setnx_test.go
Normal file
@@ -0,0 +1,60 @@
|
||||
package redis
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
miniredis "github.com/alicebob/miniredis/v2"
|
||||
goredis "github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
// SetNX 是"同一把锁最多被一个持有者拿到"这个互斥的原语。
|
||||
// 两个性质必须钉住:只有第一次能拿到占位;后到的调用不得刷新 TTL,
|
||||
// 否则反复重试的调用方会让占位永不过期。
|
||||
func TestSetNX_ClaimsOnlyOnce(t *testing.T) {
|
||||
mr, err := miniredis.Run()
|
||||
if err != nil {
|
||||
t.Fatalf("start miniredis: %v", err)
|
||||
}
|
||||
defer mr.Close()
|
||||
|
||||
client := &Client{rdb: goredis.NewClient(&goredis.Options{Addr: mr.Addr()})}
|
||||
defer client.Close()
|
||||
|
||||
ctx := context.Background()
|
||||
key := "lock:feed:hot:abc123"
|
||||
ttl := time.Hour
|
||||
|
||||
ok, err := client.SetNX(ctx, key, []byte("1"), ttl)
|
||||
if err != nil {
|
||||
t.Fatalf("first SetNX: %v", err)
|
||||
}
|
||||
if !ok {
|
||||
t.Fatal("第一次 SetNX 应拿到占位(返回 true)")
|
||||
}
|
||||
|
||||
mr.FastForward(10 * time.Minute)
|
||||
ttlBefore := mr.TTL(key)
|
||||
|
||||
ok, err = client.SetNX(ctx, key, []byte("2"), ttl)
|
||||
if err != nil {
|
||||
t.Fatalf("second SetNX: %v", err)
|
||||
}
|
||||
if ok {
|
||||
t.Fatal("第二次 SetNX 不应拿到占位(返回 false)")
|
||||
}
|
||||
if got, _ := mr.Get(key); got != "1" {
|
||||
t.Fatalf("第二次 SetNX 不应覆盖已有值,得到 %q", got)
|
||||
}
|
||||
if ttlAfter := mr.TTL(key); ttlAfter != ttlBefore {
|
||||
t.Fatalf("第二次 SetNX 不应刷新 TTL:%s → %s", ttlBefore, ttlAfter)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetNX_NilClientReturnsError(t *testing.T) {
|
||||
var client *Client
|
||||
if _, err := client.SetNX(context.Background(), "k", []byte("1"), time.Second); err == nil {
|
||||
t.Fatal("nil client 应返回错误,而不是静默成功")
|
||||
}
|
||||
}
|
||||
@@ -49,16 +49,29 @@ func (c *Client) Expire(ctx context.Context, key string, ttl time.Duration) erro
|
||||
return c.rdb.Expire(ctx, key, ttl).Err()
|
||||
}
|
||||
|
||||
// ZUnionStore 计算 keys 指定的多个有序集合的并集,将结果存入 dst。
|
||||
// aggregate 控制分数聚合方式,可选 "SUM"、"MIN" 或 "MAX"。
|
||||
func (c *Client) ZUnionStore(ctx context.Context, dst string, keys []string, aggregate string) error {
|
||||
// ZUnionStore 计算 keys 的并集存入 dst,aggregate 可选 "SUM"/"MIN"/"MAX"。
|
||||
//
|
||||
// 返回基数:ZUNIONSTORE 在无成员时仍会写出空 key,调用方要靠它区分
|
||||
// "空结果"与"已写入的空集合"。
|
||||
func (c *Client) ZUnionStore(ctx context.Context, dst string, keys []string, aggregate string) (int64, error) {
|
||||
if c == nil || c.rdb == nil {
|
||||
return nil
|
||||
return 0, nil
|
||||
}
|
||||
return c.rdb.ZUnionStore(ctx, dst, &redis.ZStore{
|
||||
Keys: keys,
|
||||
Aggregate: aggregate,
|
||||
}).Err()
|
||||
}).Result()
|
||||
}
|
||||
|
||||
// RenameNX 仅在 dst 不存在时把 src 改名为 dst。
|
||||
//
|
||||
// 它是"快照只建一次"的关键:EXISTS + ZUNIONSTORE 是 check-then-act,
|
||||
// 并发请求会各自判定"不存在"并互相覆盖;RENAMENX 把占位与发布合成一次原子操作。
|
||||
func (c *Client) RenameNX(ctx context.Context, src, dst string) (bool, error) {
|
||||
if c == nil || c.rdb == nil {
|
||||
return false, errors.New("redis client not initialized")
|
||||
}
|
||||
return c.rdb.RenameNX(ctx, src, dst).Result()
|
||||
}
|
||||
|
||||
// Exists 判断 key 是否存在于 Redis 中。
|
||||
|
||||
21
backend/internal/notification/entity.go
Normal file
21
backend/internal/notification/entity.go
Normal file
@@ -0,0 +1,21 @@
|
||||
// Package notification 存放 notifications 表的实体定义。
|
||||
// worker 与 video 都依赖它,因此列标签只有一处。
|
||||
package notification
|
||||
|
||||
import "time"
|
||||
|
||||
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 `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"`
|
||||
|
||||
// DedupeKey 用 *string:无意图键的通知写 NULL,不参与唯一约束。
|
||||
DedupeKey *string `gorm:"column:dedupe_key;type:varchar(128);uniqueIndex:uk_notifications_dedupe" json:"-"`
|
||||
}
|
||||
|
||||
func (Notification) TableName() string { return "notifications" }
|
||||
@@ -1,6 +1,7 @@
|
||||
package social
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"feedsystem_video_go/internal/account"
|
||||
"feedsystem_video_go/internal/apierror"
|
||||
"feedsystem_video_go/internal/middleware/jwt"
|
||||
@@ -9,6 +10,14 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// classifySocialError 只补一条本地语义:自关注是客户端错误,不是数据库故障。
|
||||
func classifySocialError(err error) int {
|
||||
if errors.Is(err, ErrCannotFollowSelf) {
|
||||
return http.StatusBadRequest
|
||||
}
|
||||
return apierror.ClassifyHTTPStatus(err)
|
||||
}
|
||||
|
||||
type SocialHandler struct {
|
||||
service *SocialService
|
||||
}
|
||||
@@ -36,11 +45,12 @@ func (h *SocialHandler) Follow(c *gin.Context) {
|
||||
FollowerID: FollowerID,
|
||||
VloggerID: req.VloggerID,
|
||||
}
|
||||
if err := h.service.Follow(c.Request.Context(), social); err != nil {
|
||||
c.JSON(apierror.ClassifyHTTPStatus(err), gin.H{"error": err.Error()})
|
||||
created, err := h.service.Follow(c.Request.Context(), social)
|
||||
if err != nil {
|
||||
c.JSON(classifySocialError(err), gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"message": "followed"})
|
||||
c.JSON(http.StatusOK, gin.H{"message": "followed", "created": created})
|
||||
}
|
||||
|
||||
func (h *SocialHandler) Unfollow(c *gin.Context) {
|
||||
@@ -62,11 +72,12 @@ func (h *SocialHandler) Unfollow(c *gin.Context) {
|
||||
FollowerID: FollowerID,
|
||||
VloggerID: req.VloggerID,
|
||||
}
|
||||
if err := h.service.Unfollow(c.Request.Context(), social); err != nil {
|
||||
c.JSON(apierror.ClassifyHTTPStatus(err), gin.H{"error": err.Error()})
|
||||
deleted, err := h.service.Unfollow(c.Request.Context(), social)
|
||||
if err != nil {
|
||||
c.JSON(classifySocialError(err), gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"message": "unfollowed"})
|
||||
c.JSON(http.StatusOK, gin.H{"message": "unfollowed", "deleted": deleted})
|
||||
}
|
||||
|
||||
func (h *SocialHandler) GetAllFollowers(c *gin.Context) {
|
||||
|
||||
85
backend/internal/social/handler_test.go
Normal file
85
backend/internal/social/handler_test.go
Normal file
@@ -0,0 +1,85 @@
|
||||
package social
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func newTestHandler(t *testing.T) (*SocialHandler, *fakeStore) {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
store := newFakeStore()
|
||||
notifier := &fakeNotifier{}
|
||||
return NewSocialHandler(newTestService(store, fakeAccounts{}, notifier)), store
|
||||
}
|
||||
|
||||
func postSocial(t *testing.T, h *SocialHandler, accountID uint, action, body string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/social/"+action, strings.NewReader(body))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
c.Set("accountID", accountID)
|
||||
if action == "follow" {
|
||||
h.Follow(c)
|
||||
} else {
|
||||
h.Unfollow(c)
|
||||
}
|
||||
return w
|
||||
}
|
||||
|
||||
func TestSocialHandler_Follow_SelfReturnsBadRequest(t *testing.T) {
|
||||
h, _ := newTestHandler(t)
|
||||
|
||||
w := postSocial(t, h, 1, "follow", `{"vlogger_id":1}`)
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("自关注状态码 = %d,想要 %d", w.Code, http.StatusBadRequest)
|
||||
}
|
||||
if !strings.Contains(w.Body.String(), "can not follow self") {
|
||||
t.Fatalf("响应体 = %s,想要包含 can not follow self", w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSocialHandler_Follow_DuplicateReturnsOK(t *testing.T) {
|
||||
h, store := newTestHandler(t)
|
||||
store.rows[[2]uint{1, 2}] = true
|
||||
|
||||
w := postSocial(t, h, 1, "follow", `{"vlogger_id":2}`)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("重复关注状态码 = %d,想要 %d", w.Code, http.StatusOK)
|
||||
}
|
||||
var resp struct {
|
||||
Message string `json:"message"`
|
||||
Created bool `json:"created"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("解析响应体失败: %v", err)
|
||||
}
|
||||
if resp.Message != "followed" || resp.Created {
|
||||
t.Fatalf("重复关注响应 = %+v,想要 message=followed created=false", resp)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSocialHandler_Unfollow_DuplicateReturnsOK(t *testing.T) {
|
||||
h, _ := newTestHandler(t)
|
||||
|
||||
w := postSocial(t, h, 1, "unfollow", `{"vlogger_id":2}`)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("重复取关状态码 = %d,想要 %d", w.Code, http.StatusOK)
|
||||
}
|
||||
var resp struct {
|
||||
Message string `json:"message"`
|
||||
Deleted bool `json:"deleted"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("解析响应体失败: %v", err)
|
||||
}
|
||||
if resp.Message != "unfollowed" || resp.Deleted {
|
||||
t.Fatalf("重复取关响应 = %+v,想要 message=unfollowed deleted=false", resp)
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"feedsystem_video_go/internal/account"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
type SocialRepository struct {
|
||||
@@ -15,14 +16,27 @@ func NewSocialRepository(db *gorm.DB) *SocialRepository {
|
||||
return &SocialRepository{db: db}
|
||||
}
|
||||
|
||||
func (r *SocialRepository) Follow(ctx context.Context, social *Social) error {
|
||||
return r.db.WithContext(ctx).Create(social).Error
|
||||
// Follow 返回本次是否真的插入关系:重复关注是幂等成功,不是错误。
|
||||
// 判重交给唯一索引 idx_social_follower_vlogger,OnConflict 把冲突变成一次不报错的 SQL。
|
||||
func (r *SocialRepository) Follow(ctx context.Context, social *Social) (bool, error) {
|
||||
res := r.db.WithContext(ctx).
|
||||
Clauses(clause.OnConflict{DoNothing: true}).
|
||||
Create(social)
|
||||
if res.Error != nil {
|
||||
return false, res.Error
|
||||
}
|
||||
return res.RowsAffected > 0, nil
|
||||
}
|
||||
|
||||
func (r *SocialRepository) Unfollow(ctx context.Context, social *Social) error {
|
||||
return r.db.WithContext(ctx).
|
||||
// Unfollow 用影响行数回答"这次是否真的删掉":第二次取关是空操作。
|
||||
func (r *SocialRepository) Unfollow(ctx context.Context, social *Social) (bool, error) {
|
||||
res := r.db.WithContext(ctx).
|
||||
Where("follower_id = ? AND vlogger_id = ?", social.FollowerID, social.VloggerID).
|
||||
Delete(&Social{}).Error
|
||||
Delete(&Social{})
|
||||
if res.Error != nil {
|
||||
return false, res.Error
|
||||
}
|
||||
return res.RowsAffected > 0, nil
|
||||
}
|
||||
|
||||
func (r *SocialRepository) GetAllFollowers(ctx context.Context, VloggerID uint) ([]*account.Account, error) {
|
||||
|
||||
87
backend/internal/social/repo_integration_test.go
Normal file
87
backend/internal/social/repo_integration_test.go
Normal file
@@ -0,0 +1,87 @@
|
||||
//go:build integration
|
||||
|
||||
package social
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
)
|
||||
|
||||
// 判重由唯一索引 idx_social_follower_vlogger 裁决,"这次有没有真的写入"只能对着
|
||||
// 真实 MySQL 验证:没有数据库就没有被测对象。
|
||||
//
|
||||
// MYSQL_TEST_DSN='root:123456@tcp(127.0.0.1:3306)/feedsystem_test?charset=utf8mb4&parseTime=True&loc=Local' \
|
||||
// go test -tags integration -count=1 ./internal/social/
|
||||
|
||||
func newSocialTestDB(t *testing.T) *gorm.DB {
|
||||
t.Helper()
|
||||
dsn := os.Getenv("MYSQL_TEST_DSN")
|
||||
if dsn == "" {
|
||||
t.Skip("MYSQL_TEST_DSN 未设置:需要真实 MySQL(见本文件顶部注释)")
|
||||
}
|
||||
if strings.Contains(dsn, "clientFoundRows") {
|
||||
t.Fatalf("测试 DSN 不能带 clientFoundRows:它会让 RowsAffected 判重失效")
|
||||
}
|
||||
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
|
||||
Logger: logger.Default.LogMode(logger.Silent),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("connect mysql: %v", err)
|
||||
}
|
||||
if err := db.Migrator().DropTable(&Social{}); err != nil {
|
||||
t.Fatalf("drop table: %v", err)
|
||||
}
|
||||
if err := db.AutoMigrate(&Social{}); err != nil {
|
||||
t.Fatalf("migrate: %v", err)
|
||||
}
|
||||
return db
|
||||
}
|
||||
|
||||
func TestSocialRepository_Follow_DuplicateReportsNotCreated(t *testing.T) {
|
||||
db := newSocialTestDB(t)
|
||||
repo := NewSocialRepository(db)
|
||||
ctx := context.Background()
|
||||
|
||||
created, err := repo.Follow(ctx, &Social{FollowerID: 1, VloggerID: 2})
|
||||
if err != nil || !created {
|
||||
t.Fatalf("首次关注 = (%v, %v),想要 (true, nil)", created, err)
|
||||
}
|
||||
|
||||
created, err = repo.Follow(ctx, &Social{FollowerID: 1, VloggerID: 2})
|
||||
if err != nil || created {
|
||||
t.Fatalf("重复关注 = (%v, %v),想要 (false, nil)", created, err)
|
||||
}
|
||||
|
||||
var count int64
|
||||
if err := db.Model(&Social{}).Count(&count).Error; err != nil {
|
||||
t.Fatalf("count: %v", err)
|
||||
}
|
||||
if count != 1 {
|
||||
t.Fatalf("socials 行数 = %d,想要 1", count)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSocialRepository_Unfollow_SecondCallReportsNotDeleted(t *testing.T) {
|
||||
db := newSocialTestDB(t)
|
||||
repo := NewSocialRepository(db)
|
||||
ctx := context.Background()
|
||||
if _, err := repo.Follow(ctx, &Social{FollowerID: 3, VloggerID: 4}); err != nil {
|
||||
t.Fatalf("准备关注失败: %v", err)
|
||||
}
|
||||
|
||||
deleted, err := repo.Unfollow(ctx, &Social{FollowerID: 3, VloggerID: 4})
|
||||
if err != nil || !deleted {
|
||||
t.Fatalf("首次取关 = (%v, %v),想要 (true, nil)", deleted, err)
|
||||
}
|
||||
|
||||
deleted, err = repo.Unfollow(ctx, &Social{FollowerID: 3, VloggerID: 4})
|
||||
if err != nil || deleted {
|
||||
t.Fatalf("重复取关 = (%v, %v),想要 (false, nil)", deleted, err)
|
||||
}
|
||||
}
|
||||
@@ -4,91 +4,92 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"feedsystem_video_go/internal/account"
|
||||
"feedsystem_video_go/internal/middleware/rabbitmq"
|
||||
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||||
"log"
|
||||
)
|
||||
|
||||
// ErrCannotFollowSelf 是客户端错误:自关注不写库,也不发消息。
|
||||
var ErrCannotFollowSelf = errors.New("can not follow self")
|
||||
|
||||
// socialStore 只声明 SocialService 用到的方法,测试里用 fake 驱动。
|
||||
type socialStore interface {
|
||||
Follow(ctx context.Context, social *Social) (bool, error)
|
||||
Unfollow(ctx context.Context, social *Social) (bool, error)
|
||||
IsFollowed(ctx context.Context, social *Social) (bool, error)
|
||||
GetAllFollowers(ctx context.Context, vloggerID uint) ([]*account.Account, error)
|
||||
GetAllVloggers(ctx context.Context, followerID uint) ([]*account.Account, error)
|
||||
CountFollowers(ctx context.Context, vloggerID uint) (int64, error)
|
||||
CountVloggers(ctx context.Context, followerID uint) (int64, error)
|
||||
}
|
||||
|
||||
type accountFinder interface {
|
||||
FindByID(ctx context.Context, id uint) (*account.Account, error)
|
||||
}
|
||||
|
||||
// followNotifier 只暴露关注通知。真实实现 *rabbitmq.SocialMQ 在 nil 接收者上返回 error,
|
||||
// 所以 MQ 未启用时这里只会多一条日志。
|
||||
type followNotifier interface {
|
||||
Follow(ctx context.Context, followerID, vloggerID uint) error
|
||||
}
|
||||
|
||||
type SocialService struct {
|
||||
repo *SocialRepository
|
||||
accountrepo *account.AccountRepository
|
||||
socialMQ *rabbitmq.SocialMQ
|
||||
repo socialStore
|
||||
accountrepo accountFinder
|
||||
socialMQ followNotifier
|
||||
cache *rediscache.Client
|
||||
}
|
||||
|
||||
func NewSocialService(repo *SocialRepository, accountrepo *account.AccountRepository, socialMQ *rabbitmq.SocialMQ, cache *rediscache.Client) *SocialService {
|
||||
func NewSocialService(repo socialStore, accountrepo accountFinder, socialMQ followNotifier, cache *rediscache.Client) *SocialService {
|
||||
return &SocialService{repo: repo, accountrepo: accountrepo, socialMQ: socialMQ, cache: cache}
|
||||
}
|
||||
|
||||
func (s *SocialService) Follow(ctx context.Context, social *Social) error {
|
||||
_, err := s.accountrepo.FindByID(ctx, social.FollowerID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = s.accountrepo.FindByID(ctx, social.VloggerID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Follow 返回本次是否真的插入关系:重复关注返回 (false, nil)。
|
||||
func (s *SocialService) Follow(ctx context.Context, social *Social) (bool, error) {
|
||||
if social.FollowerID == social.VloggerID {
|
||||
return errors.New("can not follow self")
|
||||
return false, ErrCannotFollowSelf
|
||||
}
|
||||
isFollowed, err := s.repo.IsFollowed(ctx, social)
|
||||
if _, err := s.accountrepo.FindByID(ctx, social.FollowerID); err != nil {
|
||||
return false, err
|
||||
}
|
||||
if _, err := s.accountrepo.FindByID(ctx, social.VloggerID); err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
created, err := s.repo.Follow(ctx, social)
|
||||
if err != nil {
|
||||
return err
|
||||
return false, err
|
||||
}
|
||||
if isFollowed {
|
||||
return errors.New("already followed")
|
||||
if !created {
|
||||
// 关系已在,缓存和通知都已经是“已关注”状态。
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// 先写 DB,确保数据持久化
|
||||
if err := s.repo.Follow(ctx, social); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// DB 成功后,失效该用户的关注列表缓存
|
||||
s.invalidateFollowingFeedCache(context.Background(), social.FollowerID)
|
||||
|
||||
// 最后发 MQ(用于通知),失败只记日志不影响业务
|
||||
if s.socialMQ != nil {
|
||||
if err := s.socialMQ.Follow(ctx, social.FollowerID, social.VloggerID); err != nil {
|
||||
log.Printf("social MQ Follow 发布失败: %v", err)
|
||||
}
|
||||
if err := s.socialMQ.Follow(ctx, social.FollowerID, social.VloggerID); err != nil {
|
||||
log.Printf("social MQ Follow 发布失败: %v", err)
|
||||
}
|
||||
return nil
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (s *SocialService) Unfollow(ctx context.Context, social *Social) error {
|
||||
_, err := s.accountrepo.FindByID(ctx, social.FollowerID)
|
||||
if err != nil {
|
||||
return err
|
||||
// Unfollow 返回本次是否真的删掉关系:重复取关返回 (false, nil)。
|
||||
func (s *SocialService) Unfollow(ctx context.Context, social *Social) (bool, error) {
|
||||
if _, err := s.accountrepo.FindByID(ctx, social.FollowerID); err != nil {
|
||||
return false, err
|
||||
}
|
||||
_, err = s.accountrepo.FindByID(ctx, social.VloggerID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
isFollowed, err := s.repo.IsFollowed(ctx, social)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !isFollowed {
|
||||
return errors.New("not followed")
|
||||
if _, err := s.accountrepo.FindByID(ctx, social.VloggerID); err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
// 先写 DB
|
||||
if err := s.repo.Unfollow(ctx, social); err != nil {
|
||||
return err
|
||||
deleted, err := s.repo.Unfollow(ctx, social)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if !deleted {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// 失效缓存
|
||||
s.invalidateFollowingFeedCache(context.Background(), social.FollowerID)
|
||||
|
||||
// 最后发 MQ
|
||||
if s.socialMQ != nil {
|
||||
if err := s.socialMQ.UnFollow(ctx, social.FollowerID, social.VloggerID); err != nil {
|
||||
log.Printf("social MQ UnFollow 发布失败: %v", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// 失效关注列表缓存,确保下次查询时能获取到最新的关注列表
|
||||
|
||||
193
backend/internal/social/service_test.go
Normal file
193
backend/internal/social/service_test.go
Normal file
@@ -0,0 +1,193 @@
|
||||
package social
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"feedsystem_video_go/internal/account"
|
||||
)
|
||||
|
||||
// fakeStore 用内存行模拟 socials 表:返回值就是"这张表这次有没有变"。
|
||||
type fakeStore struct {
|
||||
rows map[[2]uint]bool
|
||||
err error
|
||||
}
|
||||
|
||||
func newFakeStore() *fakeStore {
|
||||
return &fakeStore{rows: map[[2]uint]bool{}}
|
||||
}
|
||||
|
||||
func (f *fakeStore) Follow(ctx context.Context, social *Social) (bool, error) {
|
||||
if f.err != nil {
|
||||
return false, f.err
|
||||
}
|
||||
key := [2]uint{social.FollowerID, social.VloggerID}
|
||||
if f.rows[key] {
|
||||
return false, nil
|
||||
}
|
||||
f.rows[key] = true
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) Unfollow(ctx context.Context, social *Social) (bool, error) {
|
||||
if f.err != nil {
|
||||
return false, f.err
|
||||
}
|
||||
key := [2]uint{social.FollowerID, social.VloggerID}
|
||||
if !f.rows[key] {
|
||||
return false, nil
|
||||
}
|
||||
delete(f.rows, key)
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) IsFollowed(ctx context.Context, social *Social) (bool, error) {
|
||||
return f.rows[[2]uint{social.FollowerID, social.VloggerID}], nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) GetAllFollowers(ctx context.Context, vloggerID uint) ([]*account.Account, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) GetAllVloggers(ctx context.Context, followerID uint) ([]*account.Account, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) CountFollowers(ctx context.Context, vloggerID uint) (int64, error) {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) CountVloggers(ctx context.Context, followerID uint) (int64, error) {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
type fakeAccounts struct {
|
||||
err error
|
||||
}
|
||||
|
||||
func (f fakeAccounts) FindByID(ctx context.Context, id uint) (*account.Account, error) {
|
||||
if f.err != nil {
|
||||
return nil, f.err
|
||||
}
|
||||
return &account.Account{ID: id}, nil
|
||||
}
|
||||
|
||||
// fakeNotifier 记录真正发出去的通知事件,而不是调用次数。
|
||||
type fakeNotifier struct {
|
||||
published [][2]uint
|
||||
err error
|
||||
}
|
||||
|
||||
func (f *fakeNotifier) Follow(ctx context.Context, followerID, vloggerID uint) error {
|
||||
f.published = append(f.published, [2]uint{followerID, vloggerID})
|
||||
return f.err
|
||||
}
|
||||
|
||||
func newTestService(store socialStore, accounts accountFinder, notifier followNotifier) *SocialService {
|
||||
return NewSocialService(store, accounts, notifier, nil)
|
||||
}
|
||||
|
||||
func TestSocialService_Follow_SecondCallIsNoop(t *testing.T) {
|
||||
store := newFakeStore()
|
||||
notifier := &fakeNotifier{}
|
||||
svc := newTestService(store, fakeAccounts{}, notifier)
|
||||
rel := &Social{ID: 1, FollowerID: 7, VloggerID: 9}
|
||||
|
||||
created, err := svc.Follow(context.Background(), rel)
|
||||
if err != nil || !created {
|
||||
t.Fatalf("首次关注 = (%v, %v),想要 (true, nil)", created, err)
|
||||
}
|
||||
|
||||
created, err = svc.Follow(context.Background(), &Social{FollowerID: 7, VloggerID: 9})
|
||||
if err != nil || created {
|
||||
t.Fatalf("重复关注 = (%v, %v),想要 (false, nil)", created, err)
|
||||
}
|
||||
if len(store.rows) != 1 {
|
||||
t.Fatalf("socials 行数 = %d,想要 1", len(store.rows))
|
||||
}
|
||||
// 重复点击不该产生第二条通知。
|
||||
if len(notifier.published) != 1 {
|
||||
t.Fatalf("通知事件数 = %d,想要 1", len(notifier.published))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSocialService_Follow_SelfIsRejected(t *testing.T) {
|
||||
store := newFakeStore()
|
||||
notifier := &fakeNotifier{}
|
||||
svc := newTestService(store, fakeAccounts{}, notifier)
|
||||
|
||||
created, err := svc.Follow(context.Background(), &Social{FollowerID: 3, VloggerID: 3})
|
||||
if created || !errors.Is(err, ErrCannotFollowSelf) {
|
||||
t.Fatalf("自关注 = (%v, %v),想要 (false, ErrCannotFollowSelf)", created, err)
|
||||
}
|
||||
if len(store.rows) != 0 {
|
||||
t.Fatalf("自关注写入了 %d 行,想要 0", len(store.rows))
|
||||
}
|
||||
if len(notifier.published) != 0 {
|
||||
t.Fatalf("自关注发出了 %d 条通知,想要 0", len(notifier.published))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSocialService_Follow_RepoErrorPropagates(t *testing.T) {
|
||||
repoErr := errors.New("db is down")
|
||||
store := newFakeStore()
|
||||
store.err = repoErr
|
||||
notifier := &fakeNotifier{}
|
||||
svc := newTestService(store, fakeAccounts{}, notifier)
|
||||
|
||||
created, err := svc.Follow(context.Background(), &Social{FollowerID: 1, VloggerID: 2})
|
||||
if created || !errors.Is(err, repoErr) {
|
||||
t.Fatalf("仓储报错 = (%v, %v),想要 (false, db is down)", created, err)
|
||||
}
|
||||
if len(notifier.published) != 0 {
|
||||
t.Fatalf("仓储报错仍发出了 %d 条通知,想要 0", len(notifier.published))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSocialService_Follow_NotifyFailureKeepsSuccess(t *testing.T) {
|
||||
store := newFakeStore()
|
||||
notifier := &fakeNotifier{err: errors.New("mq is down")}
|
||||
svc := newTestService(store, fakeAccounts{}, notifier)
|
||||
|
||||
created, err := svc.Follow(context.Background(), &Social{FollowerID: 1, VloggerID: 2})
|
||||
if !created || err != nil {
|
||||
t.Fatalf("通知失败时 Follow = (%v, %v),想要 (true, nil)", created, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSocialService_Follow_AccountLookupErrorPropagates(t *testing.T) {
|
||||
lookupErr := errors.New("account not found")
|
||||
store := newFakeStore()
|
||||
svc := newTestService(store, fakeAccounts{err: lookupErr}, &fakeNotifier{})
|
||||
|
||||
created, err := svc.Follow(context.Background(), &Social{FollowerID: 1, VloggerID: 2})
|
||||
if created || !errors.Is(err, lookupErr) {
|
||||
t.Fatalf("账号校验失败 = (%v, %v),想要 (false, account not found)", created, err)
|
||||
}
|
||||
if len(store.rows) != 0 {
|
||||
t.Fatalf("账号校验失败仍写入了 %d 行,想要 0", len(store.rows))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSocialService_Unfollow_SecondCallIsNoop(t *testing.T) {
|
||||
store := newFakeStore()
|
||||
notifier := &fakeNotifier{}
|
||||
svc := newTestService(store, fakeAccounts{}, notifier)
|
||||
if _, err := svc.Follow(context.Background(), &Social{FollowerID: 7, VloggerID: 9}); err != nil {
|
||||
t.Fatalf("准备关注失败: %v", err)
|
||||
}
|
||||
|
||||
deleted, err := svc.Unfollow(context.Background(), &Social{FollowerID: 7, VloggerID: 9})
|
||||
if err != nil || !deleted {
|
||||
t.Fatalf("首次取关 = (%v, %v),想要 (true, nil)", deleted, err)
|
||||
}
|
||||
|
||||
deleted, err = svc.Unfollow(context.Background(), &Social{FollowerID: 7, VloggerID: 9})
|
||||
if err != nil || deleted {
|
||||
t.Fatalf("重复取关 = (%v, %v),想要 (false, nil)", deleted, err)
|
||||
}
|
||||
if len(store.rows) != 0 {
|
||||
t.Fatalf("取关后还有 %d 行,想要 0", len(store.rows))
|
||||
}
|
||||
}
|
||||
@@ -2,18 +2,27 @@ package video
|
||||
|
||||
import "time"
|
||||
|
||||
// Comment 的 (created_at, video_id) 覆盖索引 idx_comments_created_video
|
||||
// 服务热榜窗口查询与 DB 回退排序:范围扫描走 created_at,video_id 留在
|
||||
// 索引里避免回表。
|
||||
type Comment struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
Username string `gorm:"index" json:"username"`
|
||||
VideoID uint `gorm:"index" json:"video_id"`
|
||||
AuthorID uint `gorm:"index" json:"author_id"`
|
||||
VideoID uint `gorm:"index;index:idx_comments_created_video,priority:2" json:"video_id"`
|
||||
AuthorID uint `gorm:"index;uniqueIndex:uk_comments_author_key,priority:1" json:"author_id"`
|
||||
Content string `gorm:"type:text" json:"content"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime;index:idx_comments_created_video,priority:1" json:"created_at"`
|
||||
|
||||
// IdempotencyKey 必须是 *string:空串会互撞唯一索引,NULL 不会。
|
||||
IdempotencyKey *string `gorm:"column:idempotency_key;type:varchar(64);uniqueIndex:uk_comments_author_key,priority:2" json:"-"`
|
||||
}
|
||||
|
||||
type PublishCommentRequest struct {
|
||||
VideoID uint `json:"video_id"`
|
||||
Content string `json:"content"`
|
||||
|
||||
// RequestID 由客户端为一次发送动作生成,重试时复用;为空则服务端生成。
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
|
||||
type DeleteCommentRequest struct {
|
||||
|
||||
@@ -46,11 +46,20 @@ func (h *CommentHandler) PublishComment(c *gin.Context) {
|
||||
AuthorID: authorId,
|
||||
Content: req.Content,
|
||||
}
|
||||
if req.RequestID != "" {
|
||||
requestID := req.RequestID
|
||||
comment.IdempotencyKey = &requestID
|
||||
}
|
||||
if err := h.service.Publish(c.Request.Context(), comment); err != nil {
|
||||
c.JSON(apierror.ClassifyHTTPStatus(err), gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(200, gin.H{"message": "comment published successfully"})
|
||||
// 回显 request_id,供客户端重试时复用;不返回评论 ID,因为它可能尚未落库。
|
||||
resp := gin.H{"message": "comment published successfully"}
|
||||
if comment.IdempotencyKey != nil {
|
||||
resp["request_id"] = *comment.IdempotencyKey
|
||||
}
|
||||
c.JSON(200, resp)
|
||||
}
|
||||
|
||||
func (h *CommentHandler) DeleteComment(c *gin.Context) {
|
||||
|
||||
@@ -2,8 +2,13 @@ package video
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"feedsystem_video_go/internal/notification"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
type CommentRepository struct {
|
||||
@@ -18,8 +23,71 @@ func (r *CommentRepository) CreateComment(ctx context.Context, comment *Comment)
|
||||
return r.db.WithContext(ctx).Create(comment).Error
|
||||
}
|
||||
|
||||
func (r *CommentRepository) DeleteComment(ctx context.Context, comment *Comment) error {
|
||||
return r.db.WithContext(ctx).Delete(comment).Error
|
||||
// CreateIdempotentWithPopularity 由 uk_comments_author_key 判重,
|
||||
// 热度增量与插入同事务,只在 created=true 时执行。
|
||||
//
|
||||
// DSN 不能开 clientFoundRows,否则 RowsAffected 恒为 1,判重失效。
|
||||
func (r *CommentRepository) CreateIdempotentWithPopularity(ctx context.Context, c *Comment, delta int64) (bool, error) {
|
||||
var created bool
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
res := tx.Clauses(clause.OnConflict{DoNothing: true}).Create(c)
|
||||
if res.Error != nil {
|
||||
return res.Error
|
||||
}
|
||||
if res.RowsAffected == 0 {
|
||||
return nil
|
||||
}
|
||||
created = true
|
||||
if delta == 0 {
|
||||
return nil
|
||||
}
|
||||
return tx.Model(&Video{}).
|
||||
Where("id = ?", c.VideoID).
|
||||
UpdateColumn("popularity", gorm.Expr("GREATEST(popularity + ?, 0)", delta)).Error
|
||||
})
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return created, nil
|
||||
}
|
||||
|
||||
// DeleteWithPopularity 删除评论,并在同一事务里把所属视频的 popularity 减 1。
|
||||
//
|
||||
// 返回被删的行:调用方要它的 created_at 落桶、要 video_id 定位视频,
|
||||
// 这两个值从库里取比从事件里取可信。
|
||||
func (r *CommentRepository) DeleteWithPopularity(ctx context.Context, id uint) (*Comment, bool, error) {
|
||||
if id == 0 {
|
||||
return nil, false, nil
|
||||
}
|
||||
var deleted *Comment
|
||||
ok := false
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var row Comment
|
||||
if err := tx.First(&row, id).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
res := tx.Delete(&Comment{}, row.ID)
|
||||
if res.Error != nil {
|
||||
return res.Error
|
||||
}
|
||||
if res.RowsAffected == 0 {
|
||||
return nil
|
||||
}
|
||||
deleted = &row
|
||||
ok = true
|
||||
|
||||
return tx.Model(&Video{}).
|
||||
Where("id = ?", row.VideoID).
|
||||
UpdateColumn("popularity", gorm.Expr("GREATEST(popularity - 1, 0)")).Error
|
||||
})
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
return deleted, ok, nil
|
||||
}
|
||||
|
||||
func (r *CommentRepository) GetAllComments(ctx context.Context, videoID uint) ([]Comment, error) {
|
||||
@@ -53,3 +121,48 @@ func (r *CommentRepository) GetByID(ctx context.Context, id uint) (*Comment, err
|
||||
}
|
||||
return &comment, nil
|
||||
}
|
||||
|
||||
func (r *CommentRepository) CreateMentions(ctx context.Context, mentions []Mention) error {
|
||||
if len(mentions) == 0 {
|
||||
return nil
|
||||
}
|
||||
now := time.Now()
|
||||
rows := make([]notification.Notification, 0, len(mentions))
|
||||
for _, m := range mentions {
|
||||
rows = append(rows, notification.Notification{
|
||||
RecipientID: m.RecipientID,
|
||||
SenderID: m.SenderID,
|
||||
Type: "mention",
|
||||
TargetID: m.TargetID,
|
||||
Content: m.Content,
|
||||
CreatedAt: now,
|
||||
DedupeKey: nilIfEmpty(m.DedupeKey),
|
||||
})
|
||||
}
|
||||
return r.db.WithContext(ctx).
|
||||
Clauses(clause.OnConflict{DoNothing: true}).
|
||||
Create(&rows).Error
|
||||
}
|
||||
|
||||
// FindAccountIDs 一次查询解析一批用户名;不存在的用户名不出现在结果里。
|
||||
func (r *CommentRepository) FindAccountIDs(ctx context.Context, usernames []string) (map[string]uint, error) {
|
||||
out := make(map[string]uint, len(usernames))
|
||||
if len(usernames) == 0 {
|
||||
return out, nil
|
||||
}
|
||||
var rows []struct {
|
||||
ID uint
|
||||
Username string
|
||||
}
|
||||
if err := r.db.WithContext(ctx).
|
||||
Table("accounts").
|
||||
Select("id, username").
|
||||
Where("username IN ?", usernames).
|
||||
Scan(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, row := range rows {
|
||||
out[row.Username] = row.ID
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
295
backend/internal/video/comment_repo_integration_test.go
Normal file
295
backend/internal/video/comment_repo_integration_test.go
Normal file
@@ -0,0 +1,295 @@
|
||||
//go:build integration
|
||||
|
||||
package video
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"feedsystem_video_go/internal/notification"
|
||||
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
)
|
||||
|
||||
// 这些用例需要真实 MySQL:本仓库没有 DB mock,而"判重与写入是同一条 SQL"
|
||||
// 这个性质的正确性完全取决于 MySQL 的 ON DUPLICATE KEY 语义与 RowsAffected,
|
||||
// 用内存替身验证等于什么都没验证。
|
||||
//
|
||||
// docker compose up -d mysql
|
||||
// MYSQL_TEST_DSN='root:123456@tcp(127.0.0.1:3306)/feedsystem_test?charset=utf8mb4&parseTime=True&loc=Local' \
|
||||
// go test -tags integration -count=1 ./internal/video/
|
||||
|
||||
// testAccount 只是 comments 提及解析的目标表投影(FindAccountIDs 查 accounts)。
|
||||
type testAccount struct {
|
||||
ID uint `gorm:"primaryKey"`
|
||||
Username string `gorm:"column:username;type:varchar(255);not null;uniqueIndex"`
|
||||
}
|
||||
|
||||
func (testAccount) TableName() string { return "accounts" }
|
||||
|
||||
func newTestDB(t *testing.T) *gorm.DB {
|
||||
t.Helper()
|
||||
dsn := os.Getenv("MYSQL_TEST_DSN")
|
||||
if dsn == "" {
|
||||
t.Skip("MYSQL_TEST_DSN 未设置:需要真实 MySQL(见本文件顶部注释)")
|
||||
}
|
||||
// clientFoundRows 会让"行未变化"的 UPDATE 也返回 1 行受影响,
|
||||
// 从而把"重复插入"误判成"插入成功",去重静默失效。生产 DSN
|
||||
// (internal/db/db.go)同样不能打开它,那里另有单测钉住。
|
||||
if strings.Contains(dsn, "clientFoundRows") {
|
||||
t.Fatalf("测试 DSN 不能带 clientFoundRows:它会破坏 RowsAffected 判重")
|
||||
}
|
||||
|
||||
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
|
||||
Logger: logger.Default.LogMode(logger.Silent),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("connect mysql: %v", err)
|
||||
}
|
||||
if err := db.Migrator().DropTable(&Comment{}, &Video{}, &Like{}, ¬ification.Notification{}, &testAccount{}); err != nil {
|
||||
t.Fatalf("drop tables: %v", err)
|
||||
}
|
||||
if err := db.AutoMigrate(&testAccount{}, &Video{}, &Comment{}, &Like{}, ¬ification.Notification{}); err != nil {
|
||||
t.Fatalf("migrate: %v", err)
|
||||
}
|
||||
return db
|
||||
}
|
||||
|
||||
func seedVideo(t *testing.T, db *gorm.DB, popularity int64) *Video {
|
||||
t.Helper()
|
||||
v := &Video{
|
||||
AuthorID: 1, Username: "author", Title: "t",
|
||||
PlayURL: "p", CoverURL: "c", Popularity: popularity,
|
||||
}
|
||||
if err := db.Create(v).Error; err != nil {
|
||||
t.Fatalf("seed video: %v", err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func intPtr(s string) *string { return &s }
|
||||
|
||||
// 同一意图键第二次写入必须报告 created=false,并且不得再次加热度。
|
||||
// 这条断言同时是 DSN 护栏:若 clientFoundRows 被打开,第二次插入会
|
||||
// 报告 1 行受影响,热度变成 +2。
|
||||
func TestP0_4_DuplicateInsertReportsZeroRows(t *testing.T) {
|
||||
db := newTestDB(t)
|
||||
repo := NewCommentRepository(db)
|
||||
ctx := context.Background()
|
||||
v := seedVideo(t, db, 0)
|
||||
|
||||
first := &Comment{Username: "u", VideoID: v.ID, AuthorID: 7, Content: "好看", IdempotencyKey: intPtr("intent-0001")}
|
||||
created, err := repo.CreateIdempotentWithPopularity(ctx, first, 1)
|
||||
if err != nil {
|
||||
t.Fatalf("第一次写入: %v", err)
|
||||
}
|
||||
if !created {
|
||||
t.Fatal("第一次写入必须返回 created=true")
|
||||
}
|
||||
|
||||
second := &Comment{Username: "u", VideoID: v.ID, AuthorID: 7, Content: "好看", IdempotencyKey: intPtr("intent-0001")}
|
||||
created, err = repo.CreateIdempotentWithPopularity(ctx, second, 1)
|
||||
if err != nil {
|
||||
t.Fatalf("第二次写入应静默去重而不是报错: %v", err)
|
||||
}
|
||||
if created {
|
||||
t.Fatal("同一意图键的第二次写入必须返回 created=false(否则热度会 +2)")
|
||||
}
|
||||
|
||||
var count int64
|
||||
db.Model(&Comment{}).Count(&count)
|
||||
if count != 1 {
|
||||
t.Fatalf("comments 行数 = %d, want 1", count)
|
||||
}
|
||||
var got Video
|
||||
if err := db.First(&got, v.ID).Error; err != nil {
|
||||
t.Fatalf("reload video: %v", err)
|
||||
}
|
||||
if got.Popularity != 1 {
|
||||
t.Fatalf("popularity = %d, want 1(只有首次写入加热度)", got.Popularity)
|
||||
}
|
||||
}
|
||||
|
||||
// 并发下"先 SELECT 再 INSERT"必然漏判;本用例保证判重确实是数据库唯一索引
|
||||
// 在做,而不是应用层的检查。同时钉住:并发里只有一个执行者加热度。
|
||||
func TestP0_4_ConcurrentInsertSingleRow(t *testing.T) {
|
||||
db := newTestDB(t)
|
||||
repo := NewCommentRepository(db)
|
||||
ctx := context.Background()
|
||||
v := seedVideo(t, db, 0)
|
||||
|
||||
const workers = 8
|
||||
var wg sync.WaitGroup
|
||||
var mu sync.Mutex
|
||||
createdCount := 0
|
||||
errs := make([]error, 0, workers)
|
||||
|
||||
for i := 0; i < workers; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
c := &Comment{Username: "u", VideoID: v.ID, AuthorID: 7, Content: "并发", IdempotencyKey: intPtr("intent-0002")}
|
||||
created, err := repo.CreateIdempotentWithPopularity(ctx, c, 1)
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if err != nil {
|
||||
errs = append(errs, err)
|
||||
return
|
||||
}
|
||||
if created {
|
||||
createdCount++
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
if len(errs) > 0 {
|
||||
t.Fatalf("并发写入出现错误: %v", errs)
|
||||
}
|
||||
if createdCount != 1 {
|
||||
t.Fatalf("created 次数 = %d, want 1", createdCount)
|
||||
}
|
||||
var count int64
|
||||
db.Model(&Comment{}).Count(&count)
|
||||
if count != 1 {
|
||||
t.Fatalf("comments 行数 = %d, want 1", count)
|
||||
}
|
||||
var got Video
|
||||
if err := db.First(&got, v.ID).Error; err != nil {
|
||||
t.Fatalf("reload video: %v", err)
|
||||
}
|
||||
if got.Popularity != 1 {
|
||||
t.Fatalf("popularity = %d, want 1", got.Popularity)
|
||||
}
|
||||
}
|
||||
|
||||
// 存量行与旧 Worker 写入的行 idempotency_key 为 NULL,多个 NULL 必须共存,
|
||||
// 否则迁移一上线,第二条无键评论就会撞唯一索引。
|
||||
func TestP0_4_LegacyNullKeysCoexist(t *testing.T) {
|
||||
db := newTestDB(t)
|
||||
repo := NewCommentRepository(db)
|
||||
ctx := context.Background()
|
||||
v := seedVideo(t, db, 0)
|
||||
|
||||
for i := 0; i < 3; i++ {
|
||||
c := &Comment{Username: "u", VideoID: v.ID, AuthorID: 7, Content: "同一条内容"}
|
||||
created, err := repo.CreateIdempotentWithPopularity(ctx, c, 1)
|
||||
if err != nil {
|
||||
t.Fatalf("第 %d 条无键评论写入失败: %v", i+1, err)
|
||||
}
|
||||
if !created {
|
||||
t.Fatalf("第 %d 条无键评论应被插入(NULL 不参与判重)", i+1)
|
||||
}
|
||||
}
|
||||
var count int64
|
||||
db.Model(&Comment{}).Count(&count)
|
||||
if count != 3 {
|
||||
t.Fatalf("comments 行数 = %d, want 3", count)
|
||||
}
|
||||
}
|
||||
|
||||
// 提及通知必须带 CreatedAt,且重复投递不得产生第二行。
|
||||
func TestP0_4_MentionNotificationDedupe(t *testing.T) {
|
||||
db := newTestDB(t)
|
||||
repo := NewCommentRepository(db)
|
||||
ctx := context.Background()
|
||||
|
||||
mention := Mention{
|
||||
RecipientID: 2, SenderID: 1, TargetID: 9,
|
||||
Content: "@b 在评论中提到了你",
|
||||
DedupeKey: NotificationDedupeKey("mention", "intent-0003", 2),
|
||||
}
|
||||
for i := 0; i < 2; i++ {
|
||||
if err := repo.CreateMentions(ctx, []Mention{mention}); err != nil {
|
||||
t.Fatalf("第 %d 次写入提及通知: %v", i+1, err)
|
||||
}
|
||||
}
|
||||
|
||||
var rows []notification.Notification
|
||||
if err := db.Find(&rows).Error; err != nil {
|
||||
t.Fatalf("查询 notifications: %v", err)
|
||||
}
|
||||
if len(rows) != 1 {
|
||||
t.Fatalf("notifications 行数 = %d, want 1(去重键生效)", len(rows))
|
||||
}
|
||||
if rows[0].CreatedAt.IsZero() {
|
||||
t.Fatal("CreatedAt 必须被显式写入(P2-16 ①)")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFindAccountIDs_BatchResolve(t *testing.T) {
|
||||
db := newTestDB(t)
|
||||
repo := NewCommentRepository(db)
|
||||
ctx := context.Background()
|
||||
|
||||
if err := db.Create(&testAccount{Username: "alice"}).Error; err != nil {
|
||||
t.Fatalf("seed alice: %v", err)
|
||||
}
|
||||
if err := db.Create(&testAccount{Username: "bob"}).Error; err != nil {
|
||||
t.Fatalf("seed bob: %v", err)
|
||||
}
|
||||
|
||||
ids, err := repo.FindAccountIDs(ctx, []string{"alice", "bob", "nobody"})
|
||||
if err != nil {
|
||||
t.Fatalf("FindAccountIDs: %v", err)
|
||||
}
|
||||
if len(ids) != 2 {
|
||||
t.Fatalf("解析到 %d 个账号, want 2(不存在的用户名不应出现)", len(ids))
|
||||
}
|
||||
if ids["alice"] == 0 || ids["bob"] == 0 || ids["alice"] == ids["bob"] {
|
||||
t.Fatalf("解析结果异常: %+v", ids)
|
||||
}
|
||||
}
|
||||
|
||||
// P2-20:删除评论必须回退热度,且只能回退一次。
|
||||
//
|
||||
// 旧实现只删行(DeleteByID),popularity 永远停在原值。这里双击一次判重:
|
||||
// 第一次返回 deleted=true 并减 1,第二次读不到行、deleted=false,不得再减。
|
||||
func TestDeleteWithPopularity_DecrementsOnce(t *testing.T) {
|
||||
db := newTestDB(t)
|
||||
repo := NewCommentRepository(db)
|
||||
ctx := context.Background()
|
||||
v := seedVideo(t, db, 5)
|
||||
|
||||
c := &Comment{Username: "alice", VideoID: v.ID, AuthorID: 1, Content: "x"}
|
||||
if _, err := repo.CreateIdempotentWithPopularity(ctx, c, 1); err != nil {
|
||||
t.Fatalf("seed comment: %v", err)
|
||||
}
|
||||
|
||||
row, deleted, err := repo.DeleteWithPopularity(ctx, c.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("DeleteWithPopularity: %v", err)
|
||||
}
|
||||
if !deleted {
|
||||
t.Fatal("首次删除必须报告 deleted=true")
|
||||
}
|
||||
if row == nil || row.VideoID != v.ID {
|
||||
t.Fatalf("返回行 = %+v, want video_id=%d(热度减到哪个视频必须由行决定)", row, v.ID)
|
||||
}
|
||||
if row.CreatedAt.IsZero() {
|
||||
t.Fatal("返回行必须带原始 created_at:热榜 -1 要落回创建那一分钟")
|
||||
}
|
||||
|
||||
var got Video
|
||||
if err := db.First(&got, v.ID).Error; err != nil {
|
||||
t.Fatalf("reload video: %v", err)
|
||||
}
|
||||
if got.Popularity != 5 {
|
||||
t.Fatalf("popularity = %d, want 5(5+1-1,删除只减一次)", got.Popularity)
|
||||
}
|
||||
|
||||
if _, deleted, err := repo.DeleteWithPopularity(ctx, c.ID); err != nil || deleted {
|
||||
t.Fatalf("重复删除 = deleted:%v err:%v, want false/nil", deleted, err)
|
||||
}
|
||||
if err := db.First(&got, v.ID).Error; err != nil {
|
||||
t.Fatalf("reload video: %v", err)
|
||||
}
|
||||
if got.Popularity != 5 {
|
||||
t.Fatalf("重复删除后 popularity = %d, want 5(空操作不能再减)", got.Popularity)
|
||||
}
|
||||
}
|
||||
@@ -3,95 +3,107 @@ package video
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"feedsystem_video_go/internal/apierror"
|
||||
"feedsystem_video_go/internal/middleware/rabbitmq"
|
||||
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||||
"fmt"
|
||||
"log"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"feedsystem_video_go/internal/apierror"
|
||||
"feedsystem_video_go/internal/middleware/rabbitmq"
|
||||
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||||
)
|
||||
|
||||
// CommentPublisher 只暴露评论服务用到的两个动作,便于在测试里注入发布失败。
|
||||
// 真实实现必须在 nil 接收者上返回 error:nil 装进接口后 != nil 仍为 true。
|
||||
type CommentPublisher interface {
|
||||
Publish(ctx context.Context, evt rabbitmq.CommentEvent) error
|
||||
Delete(ctx context.Context, commentID uint, intentKey string) error
|
||||
}
|
||||
|
||||
// videoExister 由 *VideoRepository 满足,因此 router.go 无需改动。
|
||||
type videoExister interface {
|
||||
IsExist(ctx context.Context, id uint) (bool, error)
|
||||
}
|
||||
|
||||
type CommentService struct {
|
||||
repo *CommentRepository
|
||||
VideoRepository *VideoRepository
|
||||
cache *rediscache.Client
|
||||
commentMQ *rabbitmq.CommentMQ
|
||||
popularityMQ *rabbitmq.PopularityMQ
|
||||
store CommentStore
|
||||
videos videoExister
|
||||
cache *rediscache.Client
|
||||
commentMQ CommentPublisher
|
||||
}
|
||||
|
||||
func NewCommentService(repo *CommentRepository, videoRepo *VideoRepository, cache *rediscache.Client, commentMQ *rabbitmq.CommentMQ, popularityMQ *rabbitmq.PopularityMQ) *CommentService {
|
||||
return &CommentService{repo: repo, VideoRepository: videoRepo, cache: cache, commentMQ: commentMQ, popularityMQ: popularityMQ}
|
||||
func NewCommentService(store CommentStore, videos videoExister, cache *rediscache.Client, commentMQ CommentPublisher) *CommentService {
|
||||
return &CommentService{
|
||||
store: store,
|
||||
videos: videos,
|
||||
cache: cache,
|
||||
commentMQ: commentMQ,
|
||||
}
|
||||
}
|
||||
|
||||
// Publish 先入队,入队失败才直写;热度只由"这次插入是否真的落库"驱动。
|
||||
func (s *CommentService) Publish(ctx context.Context, comment *Comment) error {
|
||||
if comment == nil {
|
||||
return errors.New("comment is nil")
|
||||
}
|
||||
comment.Username = strings.TrimSpace(comment.Username)
|
||||
comment.Content = strings.TrimSpace(comment.Content)
|
||||
if comment.VideoID == 0 || comment.AuthorID == 0 {
|
||||
return errors.New("video_id and author_id are required")
|
||||
}
|
||||
if comment.Content == "" {
|
||||
return errors.New("content is required")
|
||||
comment.Username = strings.TrimSpace(comment.Username)
|
||||
if comment.Content == "" || comment.VideoID == 0 || comment.AuthorID == 0 {
|
||||
return fmt.Errorf("%w: video_id, author_id and content are required", apierror.ErrValidation)
|
||||
}
|
||||
|
||||
exists, err := s.VideoRepository.IsExist(ctx, comment.VideoID)
|
||||
key, err := ResolveIntentKey(comment.IdempotencyKey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !exists {
|
||||
return errors.New("video not found")
|
||||
comment.IdempotencyKey = &key
|
||||
span := logIntent("comment.publish", key, comment.AuthorID, comment.VideoID)
|
||||
|
||||
if ok, err := s.videos.IsExist(ctx, comment.VideoID); err != nil {
|
||||
return err
|
||||
} else if !ok {
|
||||
return fmt.Errorf("%w: video not found", apierror.ErrValidation)
|
||||
}
|
||||
|
||||
mysqlEnqueued := false
|
||||
redisEnqueued := false
|
||||
if s.commentMQ != nil {
|
||||
if err := s.commentMQ.Publish(ctx, comment.Username, comment.VideoID, comment.AuthorID, comment.Content); err == nil {
|
||||
mysqlEnqueued = true
|
||||
}
|
||||
}
|
||||
if s.popularityMQ != nil {
|
||||
if err := s.popularityMQ.Update(ctx, comment.VideoID, 1); err == nil {
|
||||
redisEnqueued = true
|
||||
}
|
||||
}
|
||||
if mysqlEnqueued && redisEnqueued {
|
||||
s.notifyMentions(ctx, comment)
|
||||
return nil
|
||||
// 行时间只在直写分支用到;worker 用消息里的 occurred_at。
|
||||
comment.CreatedAt = time.Now().UTC()
|
||||
|
||||
commentEnqueued := false
|
||||
if err := s.commentMQ.Publish(ctx, rabbitmq.CommentEvent{
|
||||
EventID: key,
|
||||
Action: "publish",
|
||||
Username: comment.Username,
|
||||
VideoID: comment.VideoID,
|
||||
AuthorID: comment.AuthorID,
|
||||
Content: comment.Content,
|
||||
}); err == nil {
|
||||
commentEnqueued = true
|
||||
} else {
|
||||
log.Printf("%s enqueue comment failed, fallback to direct write: %v", span, err)
|
||||
}
|
||||
|
||||
// Fallback: direct MySQL write when comment MQ publish fails.
|
||||
if !mysqlEnqueued {
|
||||
if err := s.repo.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Select("id").First(&Video{}, comment.VideoID).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return errors.New("video not found")
|
||||
}
|
||||
return err
|
||||
// 入队成功时不直写,避免正常路径上稳定双写。
|
||||
if !commentEnqueued {
|
||||
created, err := s.store.CreateIdempotentWithPopularity(ctx, comment, 1)
|
||||
if err != nil {
|
||||
return fmt.Errorf("fallback create comment: %w", err)
|
||||
}
|
||||
log.Printf("%s fallback write dedupe=%s", span, dedupeLabel(created))
|
||||
// 只有真的插入了才加热度:重复意图已经被唯一索引挡掉。
|
||||
if created {
|
||||
if err := ApplyHotDelta(ctx, s.cache, comment.VideoID, 1, comment.CreatedAt); err != nil {
|
||||
log.Printf("%s hot window update failed (degraded): %v", span, err)
|
||||
}
|
||||
if err := tx.Create(comment).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Model(&Video{}).Where("id = ?", comment.VideoID).
|
||||
UpdateColumn("popularity", gorm.Expr("popularity + 1")).Error
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: direct Redis update when popularity MQ publish fails.
|
||||
if !redisEnqueued {
|
||||
UpdatePopularityCache(ctx, s.cache, comment.VideoID, 1)
|
||||
}
|
||||
s.notifyMentions(ctx, comment)
|
||||
s.notifyMentions(ctx, comment, key)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *CommentService) Delete(ctx context.Context, commentID uint, accountID uint) error {
|
||||
comment, err := s.repo.GetByID(ctx, commentID)
|
||||
comment, err := s.store.GetByID(ctx, commentID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -101,58 +113,111 @@ func (s *CommentService) Delete(ctx context.Context, commentID uint, accountID u
|
||||
if comment.AuthorID != accountID {
|
||||
return apierror.ErrUnauthorized
|
||||
}
|
||||
|
||||
if s.commentMQ != nil {
|
||||
if err := s.commentMQ.Delete(ctx, commentID); err == nil {
|
||||
key, keyErr := NewIntentKey()
|
||||
if keyErr != nil {
|
||||
key = ""
|
||||
}
|
||||
err := s.commentMQ.Delete(ctx, commentID, key)
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
log.Printf("comment_id=%d stage=comment.delete enqueue failed, fallback to direct write: %v", commentID, err)
|
||||
}
|
||||
return s.repo.DeleteComment(ctx, comment)
|
||||
|
||||
deleted, ok, err := s.store.DeleteWithPopularity(ctx, commentID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok {
|
||||
// 已经被删除(重复投递或另一条路径先到):空操作,热度不能再减。
|
||||
return nil
|
||||
}
|
||||
if err := ApplyHotDelta(ctx, s.cache, deleted.VideoID, -1, deleted.CreatedAt); err != nil {
|
||||
log.Printf("comment_id=%d stage=comment.delete hot window update failed (degraded): %v", commentID, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *CommentService) GetAll(ctx context.Context, videoID uint) ([]Comment, error) {
|
||||
exists, err := s.VideoRepository.IsExist(ctx, videoID)
|
||||
exists, err := s.videos.IsExist(ctx, videoID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !exists {
|
||||
return nil, errors.New("video not found")
|
||||
return nil, fmt.Errorf("%w: video not found", apierror.ErrValidation)
|
||||
}
|
||||
return s.repo.GetAllComments(ctx, videoID)
|
||||
return s.store.GetAllComments(ctx, videoID)
|
||||
}
|
||||
|
||||
var mentionRegex = regexp.MustCompile(`@(\w+)`)
|
||||
|
||||
func (s *CommentService) notifyMentions(ctx context.Context, comment *Comment) {
|
||||
// notifyMentions 批量解析用户名并写入带去重键的提及通知。
|
||||
// 去重键必须含收件人:同一次评论可能通知多个人。
|
||||
func (s *CommentService) notifyMentions(ctx context.Context, comment *Comment, intentKey string) {
|
||||
matches := mentionRegex.FindAllStringSubmatch(comment.Content, -1)
|
||||
if len(matches) == 0 {
|
||||
return
|
||||
}
|
||||
seen := make(map[string]bool)
|
||||
|
||||
seen := make(map[string]struct{}, len(matches))
|
||||
names := make([]string, 0, len(matches))
|
||||
for _, m := range matches {
|
||||
username := m[1]
|
||||
if seen[username] || username == comment.Username {
|
||||
name := m[1]
|
||||
if name == comment.Username {
|
||||
continue
|
||||
}
|
||||
seen[username] = true
|
||||
var accID uint
|
||||
if err := s.repo.db.WithContext(ctx).Table("accounts").Where("username = ?", username).Select("id").Scan(&accID).Error; err != nil || accID == 0 {
|
||||
if _, dup := seen[name]; dup {
|
||||
continue
|
||||
}
|
||||
notif := struct {
|
||||
RecipientID uint
|
||||
SenderID uint
|
||||
Type string
|
||||
TargetID uint
|
||||
Content string
|
||||
}{
|
||||
RecipientID: accID,
|
||||
seen[name] = struct{}{}
|
||||
names = append(names, name)
|
||||
}
|
||||
if len(names) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
ids, err := s.store.FindAccountIDs(ctx, names)
|
||||
if err != nil {
|
||||
log.Printf("intent_key=%s stage=mention.lookup err=%v", intentKey, err)
|
||||
return
|
||||
}
|
||||
|
||||
mentions := make([]Mention, 0, len(ids))
|
||||
for _, name := range names {
|
||||
id, ok := ids[name]
|
||||
if !ok || id == 0 {
|
||||
continue
|
||||
}
|
||||
if id == comment.AuthorID {
|
||||
continue
|
||||
}
|
||||
mentions = append(mentions, Mention{
|
||||
RecipientID: id,
|
||||
SenderID: comment.AuthorID,
|
||||
Type: "mention",
|
||||
TargetID: comment.VideoID,
|
||||
Content: comment.Username + " 在评论中提到了你",
|
||||
}
|
||||
if err := s.repo.db.WithContext(ctx).Table("notifications").Create(¬if).Error; err != nil {
|
||||
log.Printf("create mention notification failed: %v", err)
|
||||
}
|
||||
DedupeKey: NotificationDedupeKey("mention", intentKey, id),
|
||||
})
|
||||
}
|
||||
if len(mentions) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
// 通知是派生副作用:失败不改变"评论已发布",但必须留痕。
|
||||
if err := s.store.CreateMentions(ctx, mentions); err != nil {
|
||||
log.Printf("intent_key=%s stage=mention.create err=%v", intentKey, err)
|
||||
}
|
||||
}
|
||||
|
||||
func logIntent(stage, key string, authorID, videoID uint) string {
|
||||
return fmt.Sprintf("intent_key=%s stage=%s author_id=%d video_id=%d", key, stage, authorID, videoID)
|
||||
}
|
||||
|
||||
func dedupeLabel(created bool) string {
|
||||
if created {
|
||||
return "miss"
|
||||
}
|
||||
return "hit"
|
||||
}
|
||||
|
||||
303
backend/internal/video/comment_service_test.go
Normal file
303
backend/internal/video/comment_service_test.go
Normal file
@@ -0,0 +1,303 @@
|
||||
package video
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"feedsystem_video_go/internal/apierror"
|
||||
"feedsystem_video_go/internal/middleware/rabbitmq"
|
||||
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||||
|
||||
"github.com/alicebob/miniredis/v2"
|
||||
)
|
||||
|
||||
type fakeVideoExister struct {
|
||||
exists bool
|
||||
err error
|
||||
}
|
||||
|
||||
func (f *fakeVideoExister) IsExist(_ context.Context, _ uint) (bool, error) {
|
||||
return f.exists, f.err
|
||||
}
|
||||
|
||||
type fakeCommentStore struct {
|
||||
createCalls int
|
||||
created bool
|
||||
createErr error
|
||||
lastComment *Comment
|
||||
lastDelta int64
|
||||
|
||||
// 删除路径:byID 是 GetByID 的返回,deleteRow/deleted 是 DeleteWithPopularity 的返回。
|
||||
byID *Comment
|
||||
deleteCalls int
|
||||
deleteRow *Comment
|
||||
deleted bool
|
||||
deleteErr error
|
||||
|
||||
findNames []string
|
||||
ids map[string]uint
|
||||
findErr error
|
||||
|
||||
mentions []Mention
|
||||
mentionsErr error
|
||||
}
|
||||
|
||||
func (f *fakeCommentStore) CreateIdempotentWithPopularity(_ context.Context, c *Comment, delta int64) (bool, error) {
|
||||
f.createCalls++
|
||||
f.lastComment = c
|
||||
f.lastDelta = delta
|
||||
return f.created, f.createErr
|
||||
}
|
||||
|
||||
func (f *fakeCommentStore) GetByID(_ context.Context, _ uint) (*Comment, error) {
|
||||
return f.byID, nil
|
||||
}
|
||||
|
||||
func (f *fakeCommentStore) DeleteWithPopularity(_ context.Context, _ uint) (*Comment, bool, error) {
|
||||
f.deleteCalls++
|
||||
return f.deleteRow, f.deleted, f.deleteErr
|
||||
}
|
||||
|
||||
func (f *fakeCommentStore) GetAllComments(_ context.Context, _ uint) ([]Comment, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (f *fakeCommentStore) CreateMentions(_ context.Context, m []Mention) error {
|
||||
f.mentions = append(f.mentions, m...)
|
||||
return f.mentionsErr
|
||||
}
|
||||
|
||||
func (f *fakeCommentStore) FindAccountIDs(_ context.Context, names []string) (map[string]uint, error) {
|
||||
f.findNames = names
|
||||
return f.ids, f.findErr
|
||||
}
|
||||
|
||||
type fakeCommentPublisher struct {
|
||||
events []rabbitmq.CommentEvent
|
||||
pubErr error
|
||||
delErr error
|
||||
}
|
||||
|
||||
func (f *fakeCommentPublisher) Publish(_ context.Context, evt rabbitmq.CommentEvent) error {
|
||||
f.events = append(f.events, evt)
|
||||
return f.pubErr
|
||||
}
|
||||
|
||||
func (f *fakeCommentPublisher) Delete(_ context.Context, _ uint, _ string) error { return f.delErr }
|
||||
|
||||
type commentFixture struct {
|
||||
svc *CommentService
|
||||
store *fakeCommentStore
|
||||
comments *fakeCommentPublisher
|
||||
cache *rediscache.Client
|
||||
mr *miniredis.Miniredis
|
||||
}
|
||||
|
||||
func newCommentFixture(t *testing.T) *commentFixture {
|
||||
t.Helper()
|
||||
store := &fakeCommentStore{created: true, ids: map[string]uint{}}
|
||||
comments := &fakeCommentPublisher{}
|
||||
cache, mr := newTestCache(t)
|
||||
svc := NewCommentService(store, &fakeVideoExister{exists: true}, cache, comments)
|
||||
return &commentFixture{svc: svc, store: store, comments: comments, cache: cache, mr: mr}
|
||||
}
|
||||
|
||||
// hotScoreAt 返回某个视频在某一分钟桶里的分数;桶不存在时返回 0。
|
||||
func (f *commentFixture) hotScoreAt(t *testing.T, videoID uint, at time.Time) float64 {
|
||||
t.Helper()
|
||||
score, err := f.mr.ZScore(f.cache.Key("hot:video:1m:%s", HotBucket(at)), HotMember(videoID))
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return score
|
||||
}
|
||||
|
||||
func newComment(videoID, authorID uint, content string) *Comment {
|
||||
return &Comment{VideoID: videoID, AuthorID: authorID, Username: "alice", Content: content}
|
||||
}
|
||||
|
||||
// 评论事件发出去之后,API 绝不能再写一次库:否则"MQ 正常"的常规路径
|
||||
// 会稳定产生两条评论——这正是 P0-4 的核心症状之一。
|
||||
func TestCommentService_Publish_Enqueued_SkipsLocalWriteAndHot(t *testing.T) {
|
||||
f := newCommentFixture(t)
|
||||
c := newComment(7, 1, "hello")
|
||||
if err := f.svc.Publish(context.Background(), c); err != nil {
|
||||
t.Fatalf("Publish: %v", err)
|
||||
}
|
||||
if f.store.createCalls != 0 {
|
||||
t.Fatalf("store.CreateIdempotentWithPopularity 调用 %d 次, want 0", f.store.createCalls)
|
||||
}
|
||||
if len(f.comments.events) != 1 || f.comments.events[0].EventID == "" {
|
||||
t.Fatalf("评论事件 = %+v, want 1 条且带 event_id", f.comments.events)
|
||||
}
|
||||
// 热榜由 worker 在事务提交后写:API 提前加一次就是双计。
|
||||
if got := f.hotScoreAt(t, 7, c.CreatedAt); got != 0 {
|
||||
t.Fatalf("入队成功的路径不得改热榜,实际分数 %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// 评论事件发不出去时才直写,且直写必须带着同一个意图键——
|
||||
// 这样"消息其实进了队列、稍后被消费"与"API 已经直写"能收敛成一行。
|
||||
func TestCommentService_Publish_CommentPublishFails_WritesLocallyWithIntentKey(t *testing.T) {
|
||||
f := newCommentFixture(t)
|
||||
f.comments.pubErr = errors.New("broker down")
|
||||
|
||||
c := newComment(7, 1, "hello")
|
||||
if err := f.svc.Publish(context.Background(), c); err != nil {
|
||||
t.Fatalf("Publish: %v", err)
|
||||
}
|
||||
if f.store.createCalls != 1 {
|
||||
t.Fatalf("兜底写入 %d 次, want 1", f.store.createCalls)
|
||||
}
|
||||
written := f.store.lastComment.IdempotencyKey
|
||||
if written == nil || *written == "" {
|
||||
t.Fatal("兜底写入的评论必须带上意图键,否则 worker 侧无法判重")
|
||||
}
|
||||
if f.store.lastDelta != 1 {
|
||||
t.Fatalf("热度增量 = %d, want 1", f.store.lastDelta)
|
||||
}
|
||||
// 事务真的插入了行,热榜才 +1,且落在评论的 created_at 分钟。
|
||||
if got := f.hotScoreAt(t, 7, f.store.lastComment.CreatedAt); got != 1 {
|
||||
t.Fatalf("兜底路径热榜分数 = %v, want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
// 兜底写入命中唯一索引(created=false)说明这一行早就存在,计数与热榜
|
||||
// 都已经被那次写驱动过:此时再加一次就是重复。
|
||||
func TestCommentService_Publish_FallbackDedupeHit_DoesNotTouchHot(t *testing.T) {
|
||||
f := newCommentFixture(t)
|
||||
f.comments.pubErr = errors.New("broker down")
|
||||
f.store.created = false
|
||||
|
||||
c := newComment(7, 1, "hello")
|
||||
if err := f.svc.Publish(context.Background(), c); err != nil {
|
||||
t.Fatalf("Publish: %v", err)
|
||||
}
|
||||
if f.store.createCalls != 1 {
|
||||
t.Fatalf("兜底写入 %d 次, want 1", f.store.createCalls)
|
||||
}
|
||||
if got := f.hotScoreAt(t, 7, c.CreatedAt); got != 0 {
|
||||
t.Fatalf("判重命中时热榜不得变化,实际分数 %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// 删除入队成功时 API 不碰库:热度回退由 worker 在同一事务后做。
|
||||
func TestCommentService_Delete_Enqueued_SkipsLocalWrite(t *testing.T) {
|
||||
f := newCommentFixture(t)
|
||||
f.store.byID = &Comment{ID: 5, VideoID: 7, AuthorID: 1}
|
||||
|
||||
if err := f.svc.Delete(context.Background(), 5, 1); err != nil {
|
||||
t.Fatalf("Delete: %v", err)
|
||||
}
|
||||
if f.store.deleteCalls != 0 {
|
||||
t.Fatalf("删除已入队,不得直写库,实际调用 %d 次", f.store.deleteCalls)
|
||||
}
|
||||
}
|
||||
|
||||
// 删除事件发不出去时走兜底:删行与热度 -1 都发生,且 -1 落回评论创建的那一分钟
|
||||
// (P2-20:旧实现只删行、不减热度)。
|
||||
func TestCommentService_Delete_FallbackRevertsHotAtOriginalBucket(t *testing.T) {
|
||||
f := newCommentFixture(t)
|
||||
f.comments.delErr = errors.New("broker down")
|
||||
createdAt := time.Now().UTC().Add(-20 * time.Minute).Truncate(time.Minute)
|
||||
f.store.byID = &Comment{ID: 5, VideoID: 7, AuthorID: 1}
|
||||
f.store.deleted = true
|
||||
f.store.deleteRow = &Comment{ID: 5, VideoID: 7, AuthorID: 1, CreatedAt: createdAt}
|
||||
|
||||
if err := f.svc.Delete(context.Background(), 5, 1); err != nil {
|
||||
t.Fatalf("Delete: %v", err)
|
||||
}
|
||||
if f.store.deleteCalls != 1 {
|
||||
t.Fatalf("兜底删除 %d 次, want 1", f.store.deleteCalls)
|
||||
}
|
||||
if got := f.hotScoreAt(t, 7, createdAt); got != -1 {
|
||||
t.Fatalf("原桶分数 = %v, want -1(回退必须落回创建那一分钟)", got)
|
||||
}
|
||||
}
|
||||
|
||||
// 重复删除是空操作:deleted=false 时不能再减一次热度。
|
||||
func TestCommentService_Delete_RepeatIsNoop(t *testing.T) {
|
||||
f := newCommentFixture(t)
|
||||
f.comments.delErr = errors.New("broker down")
|
||||
f.store.byID = &Comment{ID: 5, VideoID: 7, AuthorID: 1}
|
||||
f.store.deleted = false
|
||||
|
||||
if err := f.svc.Delete(context.Background(), 5, 1); err != nil {
|
||||
t.Fatalf("Delete: %v", err)
|
||||
}
|
||||
if got := f.hotScoreAt(t, 7, time.Now()); got != 0 {
|
||||
t.Fatalf("重复删除不得改热榜,实际分数 %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// 同一个意图键重复提交是正常语义(客户端重试),不能报错、也不能新增行。
|
||||
func TestCommentService_Publish_RepeatSameIntent_DoesNotError(t *testing.T) {
|
||||
f := newCommentFixture(t)
|
||||
f.comments.pubErr = errors.New("broker down")
|
||||
f.store.created = false // 第二次:唯一索引命中
|
||||
|
||||
first := newComment(7, 1, "hello")
|
||||
key := "intent-repeat-1"
|
||||
first.IdempotencyKey = &key
|
||||
if err := f.svc.Publish(context.Background(), first); err != nil {
|
||||
t.Fatalf("首次 Publish: %v", err)
|
||||
}
|
||||
|
||||
second := newComment(7, 1, "hello")
|
||||
second.IdempotencyKey = &key
|
||||
if err := f.svc.Publish(context.Background(), second); err != nil {
|
||||
t.Fatalf("重复 Publish 不应报错: %v", err)
|
||||
}
|
||||
if f.store.createCalls != 2 {
|
||||
t.Fatalf("两次都应尝试写入(由唯一索引判重),实际 %d 次", f.store.createCalls)
|
||||
}
|
||||
}
|
||||
|
||||
// 非法的 request_id 是客户端错误,必须落 400 而不是 500。
|
||||
func TestCommentService_Publish_InvalidRequestID(t *testing.T) {
|
||||
f := newCommentFixture(t)
|
||||
bad := "bad key with spaces"
|
||||
c := newComment(7, 1, "hello")
|
||||
c.IdempotencyKey = &bad
|
||||
|
||||
err := f.svc.Publish(context.Background(), c)
|
||||
if err == nil {
|
||||
t.Fatal("非法 request_id 必须报错")
|
||||
}
|
||||
if got := apierror.ClassifyHTTPStatus(err); got != 400 {
|
||||
t.Fatalf("HTTP 状态 = %d, want 400 (err=%v)", got, err)
|
||||
}
|
||||
if f.store.createCalls != 0 {
|
||||
t.Fatal("非法键不得写入任何一行")
|
||||
}
|
||||
}
|
||||
|
||||
// 提及通知的去重键必须绑定到同一次意图,且只查一次库、跳过自己。
|
||||
func TestCommentService_NotifyMentions_DedupeKeyBoundToIntent(t *testing.T) {
|
||||
f := newCommentFixture(t)
|
||||
f.store.ids = map[string]uint{"alice": 1, "bob": 2}
|
||||
|
||||
c := newComment(7, 1, "@alice @bob @bob hi")
|
||||
key := "intent-mention-1"
|
||||
c.IdempotencyKey = &key
|
||||
if err := f.svc.Publish(context.Background(), c); err != nil {
|
||||
t.Fatalf("Publish: %v", err)
|
||||
}
|
||||
|
||||
// 自己(alice)不进查询;@bob 出现两次只查一次。
|
||||
if len(f.store.findNames) != 1 || f.store.findNames[0] != "bob" {
|
||||
t.Fatalf("用户名去重后应只查 [bob],实际 %v", f.store.findNames)
|
||||
}
|
||||
if len(f.store.mentions) != 1 {
|
||||
t.Fatalf("提及通知 = %+v, want 1 条(alice 是自己)", f.store.mentions)
|
||||
}
|
||||
m := f.store.mentions[0]
|
||||
if m.RecipientID != 2 || m.SenderID != 1 || m.TargetID != 7 {
|
||||
t.Fatalf("提及通知字段 = %+v", m)
|
||||
}
|
||||
if want := "mention:" + key + ":2"; m.DedupeKey != want {
|
||||
t.Fatalf("去重键 = %q, want %q", m.DedupeKey, want)
|
||||
}
|
||||
}
|
||||
38
backend/internal/video/comment_store.go
Normal file
38
backend/internal/video/comment_store.go
Normal file
@@ -0,0 +1,38 @@
|
||||
package video
|
||||
|
||||
import (
|
||||
"context"
|
||||
)
|
||||
|
||||
// Mention 是一条待写入的提及通知。
|
||||
type Mention struct {
|
||||
RecipientID uint
|
||||
SenderID uint
|
||||
TargetID uint
|
||||
Content string
|
||||
DedupeKey string
|
||||
}
|
||||
|
||||
type CommentStore interface {
|
||||
// CreateIdempotentWithPopularity 同事务插入评论并给热度加 delta;
|
||||
// created=false 表示该意图已落库,调用方不得再加热度。
|
||||
CreateIdempotentWithPopularity(ctx context.Context, c *Comment, delta int64) (created bool, err error)
|
||||
|
||||
GetByID(ctx context.Context, id uint) (*Comment, error)
|
||||
|
||||
// DeleteWithPopularity 同事务删除评论并给热度 -1,返回被删的行。
|
||||
DeleteWithPopularity(ctx context.Context, id uint) (row *Comment, deleted bool, err error)
|
||||
|
||||
GetAllComments(ctx context.Context, videoID uint) ([]Comment, error)
|
||||
|
||||
CreateMentions(ctx context.Context, mentions []Mention) error
|
||||
FindAccountIDs(ctx context.Context, usernames []string) (map[string]uint, error)
|
||||
}
|
||||
|
||||
// nilIfEmpty 供可空唯一列使用:空串会互撞,NULL 才是"没有这个键"。
|
||||
func nilIfEmpty(s string) *string {
|
||||
if s == "" {
|
||||
return nil
|
||||
}
|
||||
return &s
|
||||
}
|
||||
71
backend/internal/video/counters_reconcile.go
Normal file
71
backend/internal/video/counters_reconcile.go
Normal file
@@ -0,0 +1,71 @@
|
||||
package video
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type CounterReconciler struct{ db *gorm.DB }
|
||||
|
||||
func NewCounterReconciler(db *gorm.DB) *CounterReconciler { return &CounterReconciler{db: db} }
|
||||
|
||||
// Reconcile 找出计数与源行不一致的视频,逐条重算。
|
||||
//
|
||||
// 先 SELECT ... FOR UPDATE 再 COUNT:业务事务的顺序是"插行 → UPDATE videos",
|
||||
// 后者会拿行锁,所以锁住这一行就能让 COUNT 读到稳定值。
|
||||
func (r *CounterReconciler) Reconcile(ctx context.Context, limit int) (checked, fixed int, err error) {
|
||||
const q = `
|
||||
SELECT v.id FROM videos v
|
||||
LEFT JOIN (SELECT video_id, COUNT(*) c FROM likes GROUP BY video_id) l ON l.video_id = v.id
|
||||
LEFT JOIN (SELECT video_id, COUNT(*) c FROM comments GROUP BY video_id) c ON c.video_id = v.id
|
||||
WHERE v.likes_count <> COALESCE(l.c, 0)
|
||||
OR v.popularity <> COALESCE(l.c, 0) + COALESCE(c.c, 0)
|
||||
ORDER BY v.id
|
||||
LIMIT ?`
|
||||
var ids []uint
|
||||
if err := r.db.WithContext(ctx).Raw(q, limit).Scan(&ids).Error; err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
for _, id := range ids {
|
||||
checked++
|
||||
ok, err := r.fixOne(ctx, id)
|
||||
if err != nil {
|
||||
return checked, fixed, err
|
||||
}
|
||||
if ok {
|
||||
fixed++
|
||||
}
|
||||
}
|
||||
return checked, fixed, nil
|
||||
}
|
||||
|
||||
func (r *CounterReconciler) fixOne(ctx context.Context, id uint) (bool, error) {
|
||||
fixed := false
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var locked uint
|
||||
if err := tx.Raw("SELECT id FROM videos WHERE id = ? FOR UPDATE", id).Scan(&locked).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if locked == 0 {
|
||||
return nil // 视频在这期间被删了
|
||||
}
|
||||
var likes, comments int64
|
||||
if err := tx.Model(&Like{}).Where("video_id = ?", id).Count(&likes).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.Model(&Comment{}).Where("video_id = ?", id).Count(&comments).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
res := tx.Model(&Video{}).Where("id = ?", id).UpdateColumns(map[string]any{
|
||||
"likes_count": likes,
|
||||
"popularity": likes + comments,
|
||||
})
|
||||
if res.Error != nil {
|
||||
return res.Error
|
||||
}
|
||||
fixed = res.RowsAffected > 0
|
||||
return nil
|
||||
})
|
||||
return fixed, err
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
//go:build integration
|
||||
|
||||
package video
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// 派生计数没有对账就只能靠"写路径永远正确"来保证,而写路径会崩、
|
||||
// 会被手工改库、会在回滚期间落后。这个用例先用直插行制造漂移,
|
||||
// 再断言 Reconcile 把两列拉回 COUNT,并且可以安全重跑。
|
||||
func TestReconcile_FixesDrift(t *testing.T) {
|
||||
db := newTestDB(t)
|
||||
ctx := context.Background()
|
||||
v := seedVideo(t, db, 0) // likes_count=0, popularity=0,行数为 0
|
||||
|
||||
now := time.Now().UTC()
|
||||
for _, account := range []uint{1, 2} {
|
||||
if err := db.Create(&Like{VideoID: v.ID, AccountID: account, CreatedAt: now}).Error; err != nil {
|
||||
t.Fatalf("seed like %d: %v", account, err)
|
||||
}
|
||||
}
|
||||
if err := db.Create(&Comment{Username: "alice", VideoID: v.ID, AuthorID: 1, Content: "x", CreatedAt: now}).Error; err != nil {
|
||||
t.Fatalf("seed comment: %v", err)
|
||||
}
|
||||
|
||||
checked, fixed, err := NewCounterReconciler(db).Reconcile(ctx, 10)
|
||||
if err != nil {
|
||||
t.Fatalf("Reconcile: %v", err)
|
||||
}
|
||||
if checked != 1 || fixed != 1 {
|
||||
t.Fatalf("checked=%d fixed=%d, want 1/1(这条视频的两个计数都偏了)", checked, fixed)
|
||||
}
|
||||
|
||||
var got Video
|
||||
if err := db.First(&got, v.ID).Error; err != nil {
|
||||
t.Fatalf("reload video: %v", err)
|
||||
}
|
||||
if got.LikesCount != 2 || got.Popularity != 3 {
|
||||
t.Fatalf("likes_count=%d popularity=%d, want 2/3(点赞 2 + 评论 1)", got.LikesCount, got.Popularity)
|
||||
}
|
||||
|
||||
// fixOne 是"锁行 + 重算",可以安全重跑:修好之后再跑不应再发现漂移。
|
||||
checked, fixed, err = NewCounterReconciler(db).Reconcile(ctx, 10)
|
||||
if err != nil {
|
||||
t.Fatalf("第二次 Reconcile: %v", err)
|
||||
}
|
||||
if checked != 0 || fixed != 0 {
|
||||
t.Fatalf("第二次 checked=%d fixed=%d, want 0/0", checked, fixed)
|
||||
}
|
||||
}
|
||||
71
backend/internal/video/hot_window.go
Normal file
71
backend/internal/video/hot_window.go
Normal file
@@ -0,0 +1,71 @@
|
||||
package video
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||||
)
|
||||
|
||||
const (
|
||||
// HotWindowMinutes 是热榜窗口覆盖的分钟桶数。
|
||||
HotWindowMinutes = 60
|
||||
|
||||
// HotWindowTTL 必须大于读窗口:迟到增量会落在窗口内的旧桶上,
|
||||
// 桶在滑出窗口之前不能被驱逐。
|
||||
HotWindowTTL = 2 * time.Hour
|
||||
|
||||
hotOpTimeout = 100 * time.Millisecond
|
||||
)
|
||||
|
||||
// HotBucket 返回时刻所属的分钟桶名(UTC)。
|
||||
func HotBucket(t time.Time) string {
|
||||
return t.UTC().Truncate(time.Minute).Format("200601021504")
|
||||
}
|
||||
|
||||
// HotMember 补零到 12 位:ZSET 同分按字典序返回,补零后字典序等于数值序,
|
||||
// 才能与 MySQL 的 "ORDER BY score DESC, video_id DESC" 给出同一个顺序。
|
||||
func HotMember(videoID uint) string {
|
||||
return fmt.Sprintf("%012d", videoID)
|
||||
}
|
||||
|
||||
// ApplyHotDelta 把一次互动写进 occurredAt 所属的分钟桶。
|
||||
//
|
||||
// 只写派生缓存:失败不回滚任何东西,DB 计数是事实,桶可由 cmd/reconcile 重建。
|
||||
func ApplyHotDelta(ctx context.Context, cache *rediscache.Client, videoID uint, delta int64, occurredAt time.Time) error {
|
||||
if cache == nil || videoID == 0 || delta == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
now := time.Now().UTC()
|
||||
if occurredAt.IsZero() {
|
||||
// 兼容不带 occurred_at 的旧消息。
|
||||
occurredAt = now
|
||||
}
|
||||
if occurredAt.After(now) {
|
||||
// 未来的桶读窗口永远覆盖不到。
|
||||
occurredAt = now
|
||||
}
|
||||
if now.Sub(occurredAt) > HotWindowTTL {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 缓存失效是 best-effort,不占 opCtx 预算。
|
||||
_ = cache.Del(context.Background(), cache.Key("video:detail:id=%d", videoID))
|
||||
_ = cache.Del(context.Background(), cache.Key("video:entity:%d", videoID))
|
||||
|
||||
opCtx, cancel := context.WithTimeout(ctx, hotOpTimeout)
|
||||
defer cancel()
|
||||
|
||||
key := cache.Key("hot:video:1m:%s", HotBucket(occurredAt))
|
||||
if err := cache.ZincrBy(opCtx, key, HotMember(videoID), float64(delta)); err != nil {
|
||||
return fmt.Errorf("hot window: zincrby video=%d delta=%d key=%s: %w", videoID, delta, key, err)
|
||||
}
|
||||
|
||||
if err := cache.Expire(opCtx, key, HotWindowTTL); err != nil {
|
||||
log.Printf("hot window: expire %s failed (non-fatal): %v", key, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
112
backend/internal/video/hot_window_admin.go
Normal file
112
backend/internal/video/hot_window_admin.go
Normal file
@@ -0,0 +1,112 @@
|
||||
package video
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||||
|
||||
goredis "github.com/redis/go-redis/v9"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type HotWindowAdmin struct {
|
||||
db *gorm.DB
|
||||
cache *rediscache.Client
|
||||
}
|
||||
|
||||
func NewHotWindowAdmin(db *gorm.DB, cache *rediscache.Client) *HotWindowAdmin {
|
||||
return &HotWindowAdmin{db: db, cache: cache}
|
||||
}
|
||||
|
||||
// hotCountRow 是本包自己的扫描目标,不复用 feed 包的结构体以免跨包依赖。
|
||||
type hotCountRow struct {
|
||||
VideoID uint `gorm:"column:video_id"`
|
||||
Score int64 `gorm:"column:score"`
|
||||
}
|
||||
|
||||
// counts 返回某分钟内每个视频的互动数,与 ApplyHotDelta 落桶的口径一致。
|
||||
func (a *HotWindowAdmin) counts(ctx context.Context, from, to time.Time) (map[uint]int64, error) {
|
||||
const q = `
|
||||
SELECT video_id, CAST(SUM(cnt) AS SIGNED) AS score FROM (
|
||||
SELECT video_id, COUNT(*) AS cnt FROM likes
|
||||
WHERE created_at >= ? AND created_at < ? GROUP BY video_id
|
||||
UNION ALL
|
||||
SELECT video_id, COUNT(*) AS cnt FROM comments
|
||||
WHERE created_at >= ? AND created_at < ? GROUP BY video_id
|
||||
) t GROUP BY video_id`
|
||||
var rows []hotCountRow
|
||||
if err := a.db.WithContext(ctx).Raw(q, from, to, from, to).Scan(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make(map[uint]int64, len(rows))
|
||||
for _, r := range rows {
|
||||
out[r.VideoID] = r.Score
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Verify 逐桶比对 ZSET 与 DB。只读,可以随时跑。
|
||||
func (a *HotWindowAdmin) Verify(ctx context.Context, from, to time.Time) (buckets, drift int, err error) {
|
||||
for m := from.UTC().Truncate(time.Minute); m.Before(to); m = m.Add(time.Minute) {
|
||||
buckets++
|
||||
want, err := a.counts(ctx, m, m.Add(time.Minute))
|
||||
if err != nil {
|
||||
return buckets, drift, err
|
||||
}
|
||||
key := a.cache.Key("hot:video:1m:%s", HotBucket(m))
|
||||
zs, err := a.cache.ZRangeWithScores(ctx, key, 0, -1)
|
||||
if err != nil {
|
||||
return buckets, drift, err
|
||||
}
|
||||
for _, z := range zs {
|
||||
id, _ := strconv.ParseUint(fmt.Sprint(z.Member), 10, 64)
|
||||
if want[uint(id)] != int64(z.Score) {
|
||||
drift++
|
||||
log.Printf("hot verify: bucket=%s video=%d redis=%v db=%d", HotBucket(m), id, z.Score, want[uint(id)])
|
||||
}
|
||||
delete(want, uint(id))
|
||||
}
|
||||
for id, c := range want {
|
||||
drift++
|
||||
log.Printf("hot verify: bucket=%s video=%d redis=missing db=%d", HotBucket(m), id, c)
|
||||
}
|
||||
}
|
||||
return buckets, drift, nil
|
||||
}
|
||||
|
||||
// Rebuild 用 DB 重写一个区间内的分钟桶。
|
||||
//
|
||||
// 与并发增量有竞态:Del 之后、ZAdd 之前到达的增量会被覆盖,
|
||||
// 所以只在窗口冷却后手工执行,跑完用 Verify 复核。
|
||||
func (a *HotWindowAdmin) Rebuild(ctx context.Context, from, to time.Time) (buckets, members int, err error) {
|
||||
for m := from.UTC().Truncate(time.Minute); m.Before(to); m = m.Add(time.Minute) {
|
||||
buckets++
|
||||
want, err := a.counts(ctx, m, m.Add(time.Minute))
|
||||
if err != nil {
|
||||
return buckets, members, err
|
||||
}
|
||||
key := a.cache.Key("hot:video:1m:%s", HotBucket(m))
|
||||
if err := a.cache.Del(ctx, key); err != nil {
|
||||
return buckets, members, err
|
||||
}
|
||||
if len(want) == 0 {
|
||||
continue
|
||||
}
|
||||
zs := make([]goredis.Z, 0, len(want))
|
||||
for id, c := range want {
|
||||
zs = append(zs, goredis.Z{Score: float64(c), Member: HotMember(id)})
|
||||
members++
|
||||
}
|
||||
if err := a.cache.ZAdd(ctx, key, zs...); err != nil {
|
||||
return buckets, members, err
|
||||
}
|
||||
if err := a.cache.Expire(ctx, key, HotWindowTTL); err != nil {
|
||||
log.Printf("hot rebuild: expire %s failed: %v", key, err)
|
||||
}
|
||||
}
|
||||
return buckets, members, nil
|
||||
}
|
||||
134
backend/internal/video/hot_window_test.go
Normal file
134
backend/internal/video/hot_window_test.go
Normal file
@@ -0,0 +1,134 @@
|
||||
package video
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||||
|
||||
"github.com/alicebob/miniredis/v2"
|
||||
goredis "github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
func newTestCache(t *testing.T) (*rediscache.Client, *miniredis.Miniredis) {
|
||||
t.Helper()
|
||||
mr := miniredis.RunT(t)
|
||||
rdb := goredis.NewClient(&goredis.Options{Addr: mr.Addr()})
|
||||
t.Cleanup(func() { _ = rdb.Close() })
|
||||
return rediscache.NewClient(rdb, "test:"), mr
|
||||
}
|
||||
|
||||
// 桶名必须是那一分钟的 UTC 起始时刻:非 UTC 时区或未截断都会让同一次
|
||||
// 互动落进不同的桶,-verify 与 -rebuild-hot 也就对不上。
|
||||
func TestHotBucket_TruncatesToUTC(t *testing.T) {
|
||||
at := time.Date(2026, 3, 4, 5, 6, 7, 800_000_000, time.FixedZone("UTC+8", 8*3600))
|
||||
|
||||
got := HotBucket(at)
|
||||
want := "202603032106" // 05:06:07+08:00 == 21:06:07Z,截断到分钟
|
||||
if got != want {
|
||||
t.Fatalf("HotBucket(%v) = %q, want %q", at, got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// 补零到 12 位让 ZSET 的字典序等同数值序:同分时才能与 DB 的
|
||||
// "ORDER BY score DESC, video_id DESC" 给出同一个顺序。
|
||||
func TestHotMember_PadsToTwelveDigits(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
id uint
|
||||
want string
|
||||
}{
|
||||
{"small", 7, "000000000007"},
|
||||
{"large", 123456789012, "123456789012"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
if got := HotMember(c.id); got != c.want {
|
||||
t.Fatalf("HotMember(%d) = %q, want %q", c.id, got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 增量落在 occurredAt 那一分钟,而不是"现在"。
|
||||
// 这是本方案与旧实现的根本区别:积压 10 分钟的 worker 不能把 10 分钟前的
|
||||
// 点赞记成此刻的尖峰。
|
||||
func TestApplyHotDelta_WritesToOccurredBucket(t *testing.T) {
|
||||
cache, mr := newTestCache(t)
|
||||
at := time.Now().UTC().Add(-10 * time.Minute).Truncate(time.Minute)
|
||||
|
||||
if err := ApplyHotDelta(context.Background(), cache, 42, 1, at); err != nil {
|
||||
t.Fatalf("ApplyHotDelta: %v", err)
|
||||
}
|
||||
|
||||
key := cache.Key("hot:video:1m:%s", HotBucket(at))
|
||||
if !mr.Exists(key) {
|
||||
t.Fatalf("桶 %s 不存在:增量没有落在 occurredAt 那一分钟", key)
|
||||
}
|
||||
if score, err := mr.ZScore(key, HotMember(42)); err != nil || score != 1 {
|
||||
t.Fatalf("桶内分数 = %v, err = %v, want 1", score, err)
|
||||
}
|
||||
if nowKey := cache.Key("hot:video:1m:%s", HotBucket(time.Now())); mr.Exists(nowKey) {
|
||||
t.Fatalf("增量不得落进当前分钟的桶 %s(那是消费时刻,不是事件时刻)", nowKey)
|
||||
}
|
||||
}
|
||||
|
||||
// 没有 cache(Redis 未启用)时不得报错:调用方是 best-effort 路径,
|
||||
// 让它返回错误会把"本来就没有热榜"的部署变成失败请求。
|
||||
func TestApplyHotDelta_NilCacheIsNoop(t *testing.T) {
|
||||
if err := ApplyHotDelta(context.Background(), nil, 42, 1, time.Now()); err != nil {
|
||||
t.Fatalf("nil cache 不应返回错误: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// 超过桶寿命的迟到增量直接丢弃:落下去也会在读到它之前过期,
|
||||
// 留着只会让 -verify 把它当成"应该存在"的桶。
|
||||
func TestApplyHotDelta_StaleBucketIsSkipped(t *testing.T) {
|
||||
cache, mr := newTestCache(t)
|
||||
at := time.Now().UTC().Add(-HotWindowTTL - time.Minute)
|
||||
|
||||
if err := ApplyHotDelta(context.Background(), cache, 43, 1, at); err != nil {
|
||||
t.Fatalf("ApplyHotDelta: %v", err)
|
||||
}
|
||||
for _, key := range mr.Keys() {
|
||||
t.Fatalf("超期增量不得写入任何桶,却发现 key=%s", key)
|
||||
}
|
||||
}
|
||||
|
||||
// 未来时间戳按当前分钟处理:否则增量会落进读窗口永远到不了的未来桶。
|
||||
func TestApplyHotDelta_FutureTimestampUsesCurrentBucket(t *testing.T) {
|
||||
cache, mr := newTestCache(t)
|
||||
future := time.Now().UTC().Add(24 * time.Hour)
|
||||
|
||||
if err := ApplyHotDelta(context.Background(), cache, 44, 1, future); err != nil {
|
||||
t.Fatalf("ApplyHotDelta: %v", err)
|
||||
}
|
||||
if mr.Exists(cache.Key("hot:video:1m:%s", HotBucket(future))) {
|
||||
t.Fatal("未来时间戳不得落进未来的桶")
|
||||
}
|
||||
if score, err := mr.ZScore(cache.Key("hot:video:1m:%s", HotBucket(time.Now())), HotMember(44)); err != nil || score != 1 {
|
||||
t.Fatalf("当前分钟桶内分数 = %v, err = %v, want 1", score, err)
|
||||
}
|
||||
}
|
||||
|
||||
// 缓存失效是 best-effort:热度变了,详情与实体缓存里的旧数字必须消失。
|
||||
func TestApplyHotDelta_InvalidatesDetailAndEntity(t *testing.T) {
|
||||
cache, mr := newTestCache(t)
|
||||
ctx := context.Background()
|
||||
detail := cache.Key("video:detail:id=%d", 46)
|
||||
entity := cache.Key("video:entity:%d", 46)
|
||||
if err := cache.SetBytes(ctx, detail, []byte("x"), time.Hour); err != nil {
|
||||
t.Fatalf("seed detail: %v", err)
|
||||
}
|
||||
if err := cache.SetBytes(ctx, entity, []byte("y"), time.Hour); err != nil {
|
||||
t.Fatalf("seed entity: %v", err)
|
||||
}
|
||||
|
||||
if err := ApplyHotDelta(ctx, cache, 46, 1, time.Now()); err != nil {
|
||||
t.Fatalf("ApplyHotDelta: %v", err)
|
||||
}
|
||||
if mr.Exists(detail) || mr.Exists(entity) {
|
||||
t.Fatalf("详情/实体缓存必须被失效")
|
||||
}
|
||||
}
|
||||
60
backend/internal/video/idempotency.go
Normal file
60
backend/internal/video/idempotency.go
Normal file
@@ -0,0 +1,60 @@
|
||||
package video
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"feedsystem_video_go/internal/apierror"
|
||||
)
|
||||
|
||||
const (
|
||||
// MaxIntentKeyLen 与 comments.idempotency_key 的列宽一致。
|
||||
MaxIntentKeyLen = 64
|
||||
minIntentKeyLen = 8
|
||||
// intentKeyAlphabet 不含 ':',它是通知去重键的分隔符。
|
||||
intentKeyAlphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_"
|
||||
)
|
||||
|
||||
func NewIntentKey() (string, error) {
|
||||
b := make([]byte, 16)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", fmt.Errorf("generate intent key: %w", err)
|
||||
}
|
||||
return hex.EncodeToString(b), nil
|
||||
}
|
||||
|
||||
func ResolveIntentKey(raw *string) (string, error) {
|
||||
if raw == nil || strings.TrimSpace(*raw) == "" {
|
||||
return NewIntentKey()
|
||||
}
|
||||
key := strings.TrimSpace(*raw)
|
||||
if err := validateIntentKey(key); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return key, nil
|
||||
}
|
||||
|
||||
// validateIntentKey 的错误必须包 apierror.ErrValidation,否则会落 500。
|
||||
func validateIntentKey(key string) error {
|
||||
if len(key) < minIntentKeyLen || len(key) > MaxIntentKeyLen {
|
||||
return fmt.Errorf("%w: request_id must be %d-%d characters",
|
||||
apierror.ErrValidation, minIntentKeyLen, MaxIntentKeyLen)
|
||||
}
|
||||
for _, r := range key {
|
||||
if !strings.ContainsRune(intentKeyAlphabet, r) {
|
||||
return fmt.Errorf("%w: request_id contains invalid character %q",
|
||||
apierror.ErrValidation, r)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// NotificationDedupeKey 返回空串表示"这条通知不参与去重"。
|
||||
func NotificationDedupeKey(notifType, intentKey string, recipientID uint) string {
|
||||
if intentKey == "" {
|
||||
return ""
|
||||
}
|
||||
return fmt.Sprintf("%s:%s:%d", notifType, intentKey, recipientID)
|
||||
}
|
||||
100
backend/internal/video/idempotency_test.go
Normal file
100
backend/internal/video/idempotency_test.go
Normal file
@@ -0,0 +1,100 @@
|
||||
package video
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"feedsystem_video_go/internal/apierror"
|
||||
)
|
||||
|
||||
// 意图键是"一次用户想发一条评论"的唯一身份,它的格式一旦被放宽,
|
||||
// 判重就会静默失效(不同重试生成不同键 = 每次都是新意图)。因此这里
|
||||
// 逐条钉住边界:长度上下限、允许字符、以及非法输入必须是 400 而不是 500。
|
||||
func TestNewIntentKey_Format(t *testing.T) {
|
||||
t.Helper()
|
||||
seen := make(map[string]struct{}, 4)
|
||||
for i := 0; i < 4; i++ {
|
||||
key, err := NewIntentKey()
|
||||
if err != nil {
|
||||
t.Fatalf("NewIntentKey() error = %v", err)
|
||||
}
|
||||
if len(key) != 32 {
|
||||
t.Fatalf("NewIntentKey() len = %d, want 32 (16 字节 hex)", len(key))
|
||||
}
|
||||
if err := validateIntentKey(key); err != nil {
|
||||
t.Fatalf("NewIntentKey() 生成了自己都不接受的键 %q: %v", key, err)
|
||||
}
|
||||
if _, dup := seen[key]; dup {
|
||||
t.Fatalf("NewIntentKey() 连续生成重复键 %q", key)
|
||||
}
|
||||
seen[key] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveIntentKey_Table(t *testing.T) {
|
||||
ptr := func(s string) *string { return &s }
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
raw *string
|
||||
want string // 期望的原样返回;空串表示"应当生成新键"
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "nil 生成新键", raw: nil, want: ""},
|
||||
{name: "空白生成新键", raw: ptr(" "), want: ""},
|
||||
{name: "合法键原样返回", raw: ptr("abcdefgh"), want: "abcdefgh"},
|
||||
{name: "首尾空白被裁掉", raw: ptr(" abcdefgh1234 "), want: "abcdefgh1234"},
|
||||
{name: "恰好 64 字符可接受", raw: ptr(strings.Repeat("a", MaxIntentKeyLen)), want: strings.Repeat("a", MaxIntentKeyLen)},
|
||||
{name: "7 字符过短", raw: ptr("abcdefg"), wantErr: true},
|
||||
{name: "65 字符过长", raw: ptr(strings.Repeat("a", MaxIntentKeyLen+1)), wantErr: true},
|
||||
{name: "含空格非法", raw: ptr("abc defgh"), wantErr: true},
|
||||
{name: "含冒号非法", raw: ptr("abc:defgh"), wantErr: true},
|
||||
{name: "含斜杠非法", raw: ptr("abc/defgh"), wantErr: true},
|
||||
{name: "含中文非法", raw: ptr("意图键意图键"), wantErr: true},
|
||||
{name: "允许连字符与下划线", raw: ptr("abc-def_gh"), want: "abc-def_gh"},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Helper()
|
||||
got, err := ResolveIntentKey(tc.raw)
|
||||
if tc.wantErr {
|
||||
if err == nil {
|
||||
t.Fatalf("ResolveIntentKey(%v) 期望报错,得到 %q", tc.raw, got)
|
||||
}
|
||||
// 非法 request_id 是客户端的错,必须落 400;500 会让前端把
|
||||
// "参数写错"显示成"服务端故障",也污染错误率指标。
|
||||
if status := apierror.ClassifyHTTPStatus(err); status != 400 {
|
||||
t.Fatalf("ClassifyHTTPStatus(%v) = %d, want 400", err, status)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("ResolveIntentKey(%v) error = %v", tc.raw, err)
|
||||
}
|
||||
if tc.want == "" {
|
||||
if len(got) != 32 {
|
||||
t.Fatalf("期望生成 32 字符新键,得到 %q", got)
|
||||
}
|
||||
return
|
||||
}
|
||||
if got != tc.want {
|
||||
t.Fatalf("ResolveIntentKey(%v) = %q, want %q", tc.raw, got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 通知去重键的格式必须稳定:它同时是唯一索引值,写成别的形状会让
|
||||
// "同一条评论的两次投递"算出两个键,去重直接失效。
|
||||
func TestNotificationDedupeKey_Format(t *testing.T) {
|
||||
t.Helper()
|
||||
if got, want := NotificationDedupeKey("mention", "abc12345", 12), "mention:abc12345:12"; got != want {
|
||||
t.Fatalf("NotificationDedupeKey() = %q, want %q", got, want)
|
||||
}
|
||||
// 空意图键返回空串:该列可空,多个 NULL 共存,退化为"不去重",
|
||||
// 而不是把所有无键通知挤到同一个键上只留一条。
|
||||
if got := NotificationDedupeKey("mention", "", 12); got != "" {
|
||||
t.Fatalf("空意图键应返回空串,得到 %q", got)
|
||||
}
|
||||
}
|
||||
@@ -2,11 +2,16 @@ package video
|
||||
|
||||
import "time"
|
||||
|
||||
// Like 的两个索引都承载语义,不能删:
|
||||
// - idx_like_video_account(video_id, account_id,唯一)是 ApplyLike 的判重门闩:
|
||||
// RowsAffected==0 表示这条互动已经存在,计数与热榜都不得再加。
|
||||
// - idx_likes_created_video(created_at, video_id)让热榜窗口查询只走索引,
|
||||
// 不回表。created_at 是事件时间,撤销点赞要减回同一分钟。
|
||||
type Like struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
VideoID uint `gorm:"uniqueIndex:idx_like_video_account;not null" json:"video_id"`
|
||||
VideoID uint `gorm:"uniqueIndex:idx_like_video_account;index:idx_likes_created_video,priority:2;not null" json:"video_id"`
|
||||
AccountID uint `gorm:"uniqueIndex:idx_like_video_account;not null" json:"account_id"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
CreatedAt time.Time `gorm:"index:idx_likes_created_video,priority:1" json:"created_at"`
|
||||
}
|
||||
|
||||
type LikeRequest struct {
|
||||
|
||||
@@ -4,8 +4,8 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/go-sql-driver/mysql"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
type LikeRepository struct {
|
||||
@@ -16,39 +16,77 @@ func NewLikeRepository(db *gorm.DB) *LikeRepository {
|
||||
return &LikeRepository{db: db}
|
||||
}
|
||||
|
||||
func (r *LikeRepository) Like(ctx context.Context, like *Like) error {
|
||||
return r.db.WithContext(ctx).Create(like).Error
|
||||
}
|
||||
|
||||
func (r *LikeRepository) Unlike(ctx context.Context, like *Like) error {
|
||||
return r.db.WithContext(ctx).
|
||||
Where("video_id = ? AND account_id = ?", like.VideoID, like.AccountID).
|
||||
Delete(&Like{}).Error
|
||||
}
|
||||
|
||||
func (r *LikeRepository) LikeIgnoreDuplicate(ctx context.Context, like *Like) (created bool, err error) {
|
||||
// ApplyLike 插入点赞行,同一事务里给 likes_count 与 popularity 各 +1。
|
||||
//
|
||||
// 判重交给唯一索引,不做"先查再插":并发下必然漏判。
|
||||
// created=false 表示行本来就存在,此时两个计数都不能再动。
|
||||
//
|
||||
// DSN 不能开 clientFoundRows,否则 RowsAffected 恒为 1,判重失效。
|
||||
func (r *LikeRepository) ApplyLike(ctx context.Context, like *Like) (created bool, err error) {
|
||||
if like == nil || like.VideoID == 0 || like.AccountID == 0 {
|
||||
return false, nil
|
||||
}
|
||||
err = r.db.WithContext(ctx).Create(like).Error
|
||||
if err == nil {
|
||||
return true, nil
|
||||
err = r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
res := tx.Clauses(clause.OnConflict{DoNothing: true}).Create(like)
|
||||
if res.Error != nil {
|
||||
return res.Error
|
||||
}
|
||||
if res.RowsAffected == 0 {
|
||||
return nil
|
||||
}
|
||||
created = true
|
||||
|
||||
if err := tx.Model(&Video{}).Where("id = ?", like.VideoID).
|
||||
UpdateColumn("likes_count", gorm.Expr("GREATEST(likes_count + 1, 0)")).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Model(&Video{}).Where("id = ?", like.VideoID).
|
||||
UpdateColumn("popularity", gorm.Expr("GREATEST(popularity + 1, 0)")).Error
|
||||
})
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
var mysqlErr *mysql.MySQLError
|
||||
if errors.As(err, &mysqlErr) && mysqlErr.Number == 1062 {
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
return created, nil
|
||||
}
|
||||
|
||||
func (r *LikeRepository) DeleteByVideoAndAccount(ctx context.Context, videoID, accountID uint) (deleted bool, err error) {
|
||||
// ApplyUnlike 删除点赞行并把两个计数各 -1,返回被删的那一行。
|
||||
//
|
||||
// created_at 必须来自库里:取消点赞要把分数减回点赞那一刻的桶,
|
||||
// 用调用方此刻的钟会留下一个永远偏高的旧桶。
|
||||
func (r *LikeRepository) ApplyUnlike(ctx context.Context, videoID, accountID uint) (like *Like, deleted bool, err error) {
|
||||
if videoID == 0 || accountID == 0 {
|
||||
return false, nil
|
||||
return nil, false, nil
|
||||
}
|
||||
res := r.db.WithContext(ctx).
|
||||
Where("video_id = ? AND account_id = ?", videoID, accountID).
|
||||
Delete(&Like{})
|
||||
return res.RowsAffected > 0, res.Error
|
||||
err = r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var row Like
|
||||
if err := tx.Where("video_id = ? AND account_id = ?", videoID, accountID).First(&row).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
res := tx.Delete(&Like{}, row.ID)
|
||||
if res.Error != nil {
|
||||
return res.Error
|
||||
}
|
||||
if res.RowsAffected == 0 {
|
||||
return nil
|
||||
}
|
||||
deleted = true
|
||||
like = &row
|
||||
|
||||
if err := tx.Model(&Video{}).Where("id = ?", videoID).
|
||||
UpdateColumn("likes_count", gorm.Expr("GREATEST(likes_count - 1, 0)")).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Model(&Video{}).Where("id = ?", videoID).
|
||||
UpdateColumn("popularity", gorm.Expr("GREATEST(popularity - 1, 0)")).Error
|
||||
})
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
return like, deleted, nil
|
||||
}
|
||||
|
||||
func (r *LikeRepository) IsLiked(ctx context.Context, videoID, accountID uint) (bool, error) {
|
||||
|
||||
118
backend/internal/video/like_repo_integration_test.go
Normal file
118
backend/internal/video/like_repo_integration_test.go
Normal file
@@ -0,0 +1,118 @@
|
||||
//go:build integration
|
||||
|
||||
package video
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ApplyLike 是"点赞一行 + 两个计数"的唯一写者:判重、计数、行时间必须在
|
||||
// 同一个事务里一次算清。这里断言的是幂等性与 created_at 的保真——
|
||||
// 后者决定热榜增量落在哪个分钟桶(见 ApplyHotDelta)。
|
||||
|
||||
func TestApplyLike_InsertsAndCountsOnce(t *testing.T) {
|
||||
db := newTestDB(t)
|
||||
repo := NewLikeRepository(db)
|
||||
ctx := context.Background()
|
||||
v := seedVideo(t, db, 0)
|
||||
|
||||
// 用 10 分钟前的时间,模拟"消息积压后消费":桶必须按行时间落,而不是按消费时刻。
|
||||
at := time.Now().UTC().Add(-10 * time.Minute).Truncate(time.Second)
|
||||
|
||||
created, err := repo.ApplyLike(ctx, &Like{VideoID: v.ID, AccountID: 7, CreatedAt: at})
|
||||
if err != nil {
|
||||
t.Fatalf("ApplyLike: %v", err)
|
||||
}
|
||||
if !created {
|
||||
t.Fatal("首次点赞必须报告 created=true")
|
||||
}
|
||||
|
||||
var row Like
|
||||
if err := db.Where("video_id = ? AND account_id = ?", v.ID, 7).First(&row).Error; err != nil {
|
||||
t.Fatalf("load like: %v", err)
|
||||
}
|
||||
if !row.CreatedAt.Equal(at) {
|
||||
t.Fatalf("created_at = %v, want %v(热榜桶按行时间落)", row.CreatedAt.UTC(), at)
|
||||
}
|
||||
|
||||
var got Video
|
||||
if err := db.First(&got, v.ID).Error; err != nil {
|
||||
t.Fatalf("reload video: %v", err)
|
||||
}
|
||||
if got.LikesCount != 1 || got.Popularity != 1 {
|
||||
t.Fatalf("likes_count=%d popularity=%d, want 1/1", got.LikesCount, got.Popularity)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyLike_DuplicateDoesNotCount(t *testing.T) {
|
||||
db := newTestDB(t)
|
||||
repo := NewLikeRepository(db)
|
||||
ctx := context.Background()
|
||||
v := seedVideo(t, db, 0)
|
||||
|
||||
like := &Like{VideoID: v.ID, AccountID: 7, CreatedAt: time.Now().UTC()}
|
||||
if created, err := repo.ApplyLike(ctx, like); err != nil || !created {
|
||||
t.Fatalf("首次 ApplyLike = created:%v err:%v", created, err)
|
||||
}
|
||||
// 同一账户重复投递:唯一索引吸收,计数不得再动。
|
||||
created, err := repo.ApplyLike(ctx, &Like{VideoID: v.ID, AccountID: 7, CreatedAt: time.Now().UTC()})
|
||||
if err != nil {
|
||||
t.Fatalf("重复 ApplyLike: %v", err)
|
||||
}
|
||||
if created {
|
||||
t.Fatal("重复点赞必须报告 created=false")
|
||||
}
|
||||
|
||||
var got Video
|
||||
if err := db.First(&got, v.ID).Error; err != nil {
|
||||
t.Fatalf("reload video: %v", err)
|
||||
}
|
||||
if got.LikesCount != 1 || got.Popularity != 1 {
|
||||
t.Fatalf("likes_count=%d popularity=%d, want 1/1(判重命中不得计数)", got.LikesCount, got.Popularity)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyUnlike_RestoresOriginalBucket(t *testing.T) {
|
||||
db := newTestDB(t)
|
||||
repo := NewLikeRepository(db)
|
||||
ctx := context.Background()
|
||||
v := seedVideo(t, db, 2)
|
||||
|
||||
// 点赞发生在 20 分钟前的桶:取消时必须把 -1 记回同一分钟。
|
||||
likedAt := time.Now().UTC().Add(-20 * time.Minute).Truncate(time.Second)
|
||||
if created, err := repo.ApplyLike(ctx, &Like{VideoID: v.ID, AccountID: 7, CreatedAt: likedAt}); err != nil || !created {
|
||||
t.Fatalf("seed ApplyLike = created:%v err:%v", created, err)
|
||||
}
|
||||
|
||||
row, deleted, err := repo.ApplyUnlike(ctx, v.ID, 7)
|
||||
if err != nil {
|
||||
t.Fatalf("ApplyUnlike: %v", err)
|
||||
}
|
||||
if !deleted {
|
||||
t.Fatal("首次取消点赞必须报告 deleted=true")
|
||||
}
|
||||
if row == nil || !row.CreatedAt.Equal(likedAt) {
|
||||
t.Fatalf("返回行 = %+v, want created_at=%v(-1 要落回点赞那一分钟)", row, likedAt)
|
||||
}
|
||||
|
||||
var got Video
|
||||
if err := db.First(&got, v.ID).Error; err != nil {
|
||||
t.Fatalf("reload video: %v", err)
|
||||
}
|
||||
if got.LikesCount != 0 || got.Popularity != 2 {
|
||||
t.Fatalf("likes_count=%d popularity=%d, want 0/2", got.LikesCount, got.Popularity)
|
||||
}
|
||||
|
||||
// 重复投递:行已不在,空操作。
|
||||
if _, deleted, err := repo.ApplyUnlike(ctx, v.ID, 7); err != nil || deleted {
|
||||
t.Fatalf("重复 ApplyUnlike = deleted:%v err:%v, want false/nil", deleted, err)
|
||||
}
|
||||
if err := db.First(&got, v.ID).Error; err != nil {
|
||||
t.Fatalf("reload video: %v", err)
|
||||
}
|
||||
if got.LikesCount != 0 || got.Popularity != 2 {
|
||||
t.Fatalf("重复取消后 likes_count=%d popularity=%d, want 0/2", got.LikesCount, got.Popularity)
|
||||
}
|
||||
}
|
||||
@@ -5,27 +5,19 @@ import (
|
||||
"errors"
|
||||
"feedsystem_video_go/internal/middleware/rabbitmq"
|
||||
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/go-sql-driver/mysql"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type LikeService struct {
|
||||
repo *LikeRepository
|
||||
VideoRepo *VideoRepository
|
||||
cache *rediscache.Client
|
||||
likeMQ *rabbitmq.LikeMQ
|
||||
popularityMQ *rabbitmq.PopularityMQ
|
||||
repo *LikeRepository
|
||||
VideoRepo *VideoRepository
|
||||
cache *rediscache.Client
|
||||
likeMQ *rabbitmq.LikeMQ
|
||||
}
|
||||
|
||||
func NewLikeService(repo *LikeRepository, videoRepo *VideoRepository, cache *rediscache.Client, likeMQ *rabbitmq.LikeMQ, popularityMQ *rabbitmq.PopularityMQ) *LikeService {
|
||||
return &LikeService{repo: repo, VideoRepo: videoRepo, cache: cache, likeMQ: likeMQ, popularityMQ: popularityMQ}
|
||||
}
|
||||
|
||||
func isDupKey(err error) bool {
|
||||
var me *mysql.MySQLError
|
||||
return errors.As(err, &me) && me.Number == 1062
|
||||
func NewLikeService(repo *LikeRepository, videoRepo *VideoRepository, cache *rediscache.Client, likeMQ *rabbitmq.LikeMQ) *LikeService {
|
||||
return &LikeService{repo: repo, VideoRepo: videoRepo, cache: cache, likeMQ: likeMQ}
|
||||
}
|
||||
|
||||
func (s *LikeService) Like(ctx context.Context, like *Like) error {
|
||||
@@ -55,52 +47,35 @@ func (s *LikeService) Like(ctx context.Context, like *Like) error {
|
||||
}
|
||||
|
||||
like.CreatedAt = time.Now()
|
||||
mysqlEnqueued := false
|
||||
redisEnqueued := false
|
||||
|
||||
// 意图键只用于日志关联,不参与去重:判重由唯一索引在事务里做。
|
||||
intentKey, err := NewIntentKey()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
enqueued := false
|
||||
if s.likeMQ != nil {
|
||||
if err := s.likeMQ.Like(ctx, like.AccountID, like.VideoID); err == nil {
|
||||
mysqlEnqueued = true
|
||||
if err := s.likeMQ.Like(ctx, like.AccountID, like.VideoID, intentKey); err != nil {
|
||||
log.Printf("like: enqueue like failed, fallback to direct write: %v", err)
|
||||
} else {
|
||||
enqueued = true
|
||||
}
|
||||
}
|
||||
if s.popularityMQ != nil {
|
||||
if err := s.popularityMQ.Update(ctx, like.VideoID, 1); err == nil {
|
||||
redisEnqueued = true
|
||||
}
|
||||
}
|
||||
if mysqlEnqueued && redisEnqueued {
|
||||
if enqueued {
|
||||
// 入队成功即返回:落库与热榜都由 worker 在同一条事务路径上完成。
|
||||
return nil
|
||||
}
|
||||
|
||||
// Fallback: direct MySQL write when like MQ publish fails.
|
||||
if !mysqlEnqueued {
|
||||
err := s.repo.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Select("id").First(&Video{}, like.VideoID).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return errors.New("video not found")
|
||||
}
|
||||
return err
|
||||
}
|
||||
if err := tx.Create(like).Error; err != nil {
|
||||
if isDupKey(err) {
|
||||
return errors.New("user has liked this video")
|
||||
}
|
||||
return err
|
||||
}
|
||||
if err := tx.Model(&Video{}).Where("id = ?", like.VideoID).
|
||||
UpdateColumn("likes_count", gorm.Expr("likes_count + 1")).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Model(&Video{}).Where("id = ?", like.VideoID).
|
||||
UpdateColumn("popularity", gorm.Expr("popularity + 1")).Error
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
created, err := s.repo.ApplyLike(ctx, like)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Fallback: direct Redis update when popularity MQ publish fails.
|
||||
if !redisEnqueued {
|
||||
UpdatePopularityCache(ctx, s.cache, like.VideoID, 1)
|
||||
if !created {
|
||||
return errors.New("user has liked this video")
|
||||
}
|
||||
if err := ApplyHotDelta(ctx, s.cache, like.VideoID, 1, like.CreatedAt); err != nil {
|
||||
log.Printf("like: 热榜更新失败(已降级)video=%d: %v", like.VideoID, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -131,48 +106,33 @@ func (s *LikeService) Unlike(ctx context.Context, like *Like) error {
|
||||
return errors.New("user has not liked this video")
|
||||
}
|
||||
|
||||
mysqlEnqueued := false
|
||||
redisEnqueued := false
|
||||
intentKey, err := NewIntentKey()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
enqueued := false
|
||||
if s.likeMQ != nil {
|
||||
if err := s.likeMQ.Unlike(ctx, like.AccountID, like.VideoID); err == nil {
|
||||
mysqlEnqueued = true
|
||||
if err := s.likeMQ.Unlike(ctx, like.AccountID, like.VideoID, intentKey); err != nil {
|
||||
log.Printf("unlike: enqueue unlike failed, fallback to direct write: %v", err)
|
||||
} else {
|
||||
enqueued = true
|
||||
}
|
||||
}
|
||||
if s.popularityMQ != nil {
|
||||
if err := s.popularityMQ.Update(ctx, like.VideoID, -1); err == nil {
|
||||
redisEnqueued = true
|
||||
}
|
||||
}
|
||||
if mysqlEnqueued && redisEnqueued {
|
||||
if enqueued {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Fallback: direct MySQL write when like MQ publish fails.
|
||||
if !mysqlEnqueued {
|
||||
err := s.repo.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
del := tx.Where("video_id = ? AND account_id = ?", like.VideoID, like.AccountID).Delete(&Like{})
|
||||
if del.Error != nil {
|
||||
return del.Error
|
||||
}
|
||||
if del.RowsAffected == 0 {
|
||||
return errors.New("user has not liked this video")
|
||||
}
|
||||
|
||||
if err := tx.Model(&Video{}).Where("id = ?", like.VideoID).
|
||||
UpdateColumn("likes_count", gorm.Expr("GREATEST(likes_count - 1, 0)")).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Model(&Video{}).Where("id = ?", like.VideoID).
|
||||
UpdateColumn("popularity", gorm.Expr("GREATEST(popularity - 1, 0)")).Error
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
row, deleted, err := s.repo.ApplyUnlike(ctx, like.VideoID, like.AccountID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Fallback: direct Redis update when popularity MQ publish fails.
|
||||
if !redisEnqueued {
|
||||
UpdatePopularityCache(ctx, s.cache, like.VideoID, -1)
|
||||
if !deleted {
|
||||
return errors.New("user has not liked this video")
|
||||
}
|
||||
// 减回点赞那一分钟:热榜是窗口,不能按此刻的钟回退。
|
||||
if err := ApplyHotDelta(ctx, s.cache, like.VideoID, -1, row.CreatedAt); err != nil {
|
||||
log.Printf("unlike: 热榜更新失败(已降级)video=%d: %v", like.VideoID, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
package video
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||||
)
|
||||
|
||||
// 更新视频流行度缓存
|
||||
func UpdatePopularityCache(ctx context.Context, cache *rediscache.Client, id uint, change int64) {
|
||||
if cache == nil || id == 0 || change == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
_ = cache.Del(context.Background(), cache.Key("video:detail:id=%d", id))
|
||||
_ = cache.Del(context.Background(), cache.Key("video:entity:%d", id))
|
||||
|
||||
now := time.Now().UTC().Truncate(time.Minute)
|
||||
windowKey := cache.Key("hot:video:1m:%s", now.Format("200601021504"))
|
||||
member := strconv.FormatUint(uint64(id), 10)
|
||||
|
||||
opCtx, cancel := context.WithTimeout(ctx, 50*time.Millisecond)
|
||||
defer cancel()
|
||||
|
||||
_ = cache.ZincrBy(opCtx, windowKey, member, float64(change))
|
||||
_ = cache.Expire(opCtx, windowKey, 2*time.Hour)
|
||||
}
|
||||
@@ -4,26 +4,25 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"feedsystem_video_go/internal/apierror"
|
||||
"feedsystem_video_go/internal/middleware/rabbitmq"
|
||||
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type VideoService struct {
|
||||
repo *VideoRepository
|
||||
cache *rediscache.Client
|
||||
cacheTTL time.Duration
|
||||
popularityMQ *rabbitmq.PopularityMQ
|
||||
repo *VideoRepository
|
||||
cache *rediscache.Client
|
||||
cacheTTL time.Duration
|
||||
}
|
||||
|
||||
func NewVideoService(repo *VideoRepository, cache *rediscache.Client, popularityMQ *rabbitmq.PopularityMQ) *VideoService {
|
||||
return &VideoService{repo: repo, cache: cache, cacheTTL: 5 * time.Minute, popularityMQ: popularityMQ}
|
||||
// NewVideoService 不涉及热度写入:likes_count / popularity 只由点赞与评论的
|
||||
// 业务事务维护。
|
||||
func NewVideoService(repo *VideoRepository, cache *rediscache.Client) *VideoService {
|
||||
return &VideoService{repo: repo, cache: cache, cacheTTL: 5 * time.Minute}
|
||||
}
|
||||
|
||||
func (vs *VideoService) Publish(ctx context.Context, video *Video) error {
|
||||
@@ -199,32 +198,3 @@ func (vs *VideoService) UpdateLikesCount(ctx context.Context, id uint, likesCoun
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (vs *VideoService) UpdatePopularity(ctx context.Context, id uint, change int64) error {
|
||||
if err := vs.repo.UpdatePopularity(ctx, id, change); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if vs.popularityMQ != nil {
|
||||
if err := vs.popularityMQ.Update(ctx, id, change); err == nil {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
if vs.cache != nil {
|
||||
// 1) 详情缓存:直接失效(最简单靠谱)
|
||||
_ = vs.cache.Del(context.Background(), vs.cache.Key("video:detail:id=%d", id))
|
||||
|
||||
// 2) 热榜:写到“时间窗ZSET”,不要用 detail key
|
||||
now := time.Now().UTC().Truncate(time.Minute)
|
||||
windowKey := vs.cache.Key("hot:video:1m:%s", now.Format("200601021504"))
|
||||
member := strconv.FormatUint(uint64(id), 10)
|
||||
|
||||
opCtx, cancel := context.WithTimeout(ctx, 50*time.Millisecond)
|
||||
defer cancel()
|
||||
|
||||
_ = vs.cache.ZincrBy(opCtx, windowKey, member, float64(change))
|
||||
_ = vs.cache.Expire(opCtx, windowKey, 2*time.Hour)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
93
backend/internal/worker/comment_converge_integration_test.go
Normal file
93
backend/internal/worker/comment_converge_integration_test.go
Normal file
@@ -0,0 +1,93 @@
|
||||
//go:build integration
|
||||
|
||||
package worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"feedsystem_video_go/internal/middleware/rabbitmq"
|
||||
"feedsystem_video_go/internal/video"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// 这两个 publisher 永远失败,用来迫使 CommentService 走"直写数据库"的兜底路径。
|
||||
// 它模拟的是 P0-4 的起点:发布返回 error,但消息其实已经到了 broker。
|
||||
type failingCommentPublisher struct{}
|
||||
|
||||
func (failingCommentPublisher) Publish(context.Context, rabbitmq.CommentEvent) error {
|
||||
return errors.New("mq publish failed")
|
||||
}
|
||||
|
||||
func (failingCommentPublisher) Delete(context.Context, uint, string) error {
|
||||
return errors.New("mq publish failed")
|
||||
}
|
||||
|
||||
// P0-4 的原始缺陷是"兜底直写一次 + 消费者再写一次",结果是两条评论、双倍热度。
|
||||
// 这个用例把两条路径接起来跑:先让服务层兜底写入,再让同一个意图键的事件到达
|
||||
// worker。断言收敛到一行评论、热度恰为 1。
|
||||
//
|
||||
// 行数 = 1 证明唯一索引 (author_id, idempotency_key) 吸收了第二次插入;
|
||||
// 热度 = 1(而不是 2)证明"加热度"与"插评论"同事务、且以 created 为门控。
|
||||
// 只跑其中一侧都发现不了这个缺陷——这正是它必须写成端到端用例的原因。
|
||||
func TestP0_4_FallbackAndWorkerConvergeToOneComment(t *testing.T) {
|
||||
db := newCommentWorkerTestDB(t)
|
||||
ctx := context.Background()
|
||||
v := seedCommentVideo(t, db)
|
||||
|
||||
commentRepo := video.NewCommentRepository(db)
|
||||
videoRepo := video.NewVideoRepository(db)
|
||||
// cache 传 nil:热榜是 best-effort 派生数据,本用例只断言 DB 侧的收敛。
|
||||
svc := video.NewCommentService(commentRepo, videoRepo, nil, failingCommentPublisher{})
|
||||
|
||||
intentKey := "converge-intent-0001"
|
||||
comment := &video.Comment{
|
||||
Username: "alice",
|
||||
VideoID: v.ID,
|
||||
AuthorID: 7,
|
||||
Content: "好看",
|
||||
IdempotencyKey: &intentKey,
|
||||
}
|
||||
if err := svc.Publish(ctx, comment); err != nil {
|
||||
t.Fatalf("publish(两条事件都失败,应走兜底): %v", err)
|
||||
}
|
||||
if got := countComments(t, db, v.ID); got != 1 {
|
||||
t.Fatalf("兜底之后 comments = %d, want 1", got)
|
||||
}
|
||||
|
||||
// 消息其实已到 broker,稍后由消费者处理同一个意图键。
|
||||
w := NewCommentWorker(nil, nil, commentRepo, videoRepo, nil, rabbitmq.CommentQueue)
|
||||
evt := &rabbitmq.CommentEvent{
|
||||
EventID: intentKey,
|
||||
Action: "publish",
|
||||
Username: "alice",
|
||||
VideoID: v.ID,
|
||||
AuthorID: 7,
|
||||
Content: "好看",
|
||||
}
|
||||
if err := w.applyPublish(ctx, evt); err != nil {
|
||||
t.Fatalf("applyPublish: %v", err)
|
||||
}
|
||||
|
||||
if got := countComments(t, db, v.ID); got != 1 {
|
||||
t.Fatalf("消费者处理后 comments = %d, want 1(兜底与消费端必须收敛到同一行)", got)
|
||||
}
|
||||
var popularity int64
|
||||
if err := db.Model(&video.Video{}).Where("id = ?", v.ID).Select("popularity").Scan(&popularity).Error; err != nil {
|
||||
t.Fatalf("read popularity: %v", err)
|
||||
}
|
||||
if popularity != 1 {
|
||||
t.Fatalf("popularity = %d, want 1(重复插入不得重复加热度)", popularity)
|
||||
}
|
||||
}
|
||||
|
||||
func countComments(t *testing.T, db *gorm.DB, videoID uint) int64 {
|
||||
t.Helper()
|
||||
var got int64
|
||||
if err := db.Model(&video.Comment{}).Where("video_id = ?", videoID).Count(&got).Error; err != nil {
|
||||
t.Fatalf("count comments: %v", err)
|
||||
}
|
||||
return got
|
||||
}
|
||||
@@ -4,24 +4,28 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"feedsystem_video_go/internal/middleware/rabbitmq"
|
||||
"feedsystem_video_go/internal/video"
|
||||
"fmt"
|
||||
"log"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"feedsystem_video_go/internal/middleware/rabbitmq"
|
||||
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||||
"feedsystem_video_go/internal/video"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
)
|
||||
|
||||
type CommentWorker struct {
|
||||
ch *amqp.Channel
|
||||
comments *video.CommentRepository
|
||||
parker rabbitmq.Parker
|
||||
comments video.CommentStore
|
||||
videos *video.VideoRepository
|
||||
cache *rediscache.Client
|
||||
queue string
|
||||
}
|
||||
|
||||
func NewCommentWorker(ch *amqp.Channel, comments *video.CommentRepository, videos *video.VideoRepository, queue string) *CommentWorker {
|
||||
return &CommentWorker{ch: ch, comments: comments, videos: videos, queue: queue}
|
||||
func NewCommentWorker(ch *amqp.Channel, parker rabbitmq.Parker, comments video.CommentStore, videos *video.VideoRepository, cache *rediscache.Client, queue string) *CommentWorker {
|
||||
return &CommentWorker{ch: ch, parker: parker, comments: comments, videos: videos, cache: cache, queue: queue}
|
||||
}
|
||||
|
||||
func (w *CommentWorker) Run(ctx context.Context) error {
|
||||
@@ -31,76 +35,28 @@ func (w *CommentWorker) Run(ctx context.Context) error {
|
||||
if w.queue == "" {
|
||||
return errors.New("queue is required")
|
||||
}
|
||||
|
||||
deliveries, err := w.ch.Consume(
|
||||
w.queue,
|
||||
"",
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
nil,
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case d, ok := <-deliveries:
|
||||
if !ok {
|
||||
return errors.New("deliveries channel closed")
|
||||
}
|
||||
w.handleDelivery(ctx, d)
|
||||
}
|
||||
}
|
||||
return rabbitmq.ConsumeLoop(ctx, w.ch, w.parker, w.queue, rabbitmq.MaxAttempts, w.process)
|
||||
}
|
||||
|
||||
func (w *CommentWorker) handleDelivery(ctx context.Context, d amqp.Delivery) {
|
||||
const maxRetries = 3
|
||||
for i := 0; i <= maxRetries; i++ {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
_ = d.Nack(false, true)
|
||||
return
|
||||
default:
|
||||
}
|
||||
if err := w.process(ctx, d.Body); err != nil {
|
||||
if i >= maxRetries {
|
||||
log.Printf("comment worker: 重试 %d 次后仍失败, 丢弃: %v", maxRetries, err)
|
||||
_ = d.Ack(false)
|
||||
return
|
||||
}
|
||||
wait := time.Duration(1<<uint(i)) * time.Second
|
||||
log.Printf("comment worker: 处理失败, %v 后重试 (%d/%d): %v", wait, i+1, maxRetries, err)
|
||||
time.Sleep(wait)
|
||||
continue
|
||||
}
|
||||
_ = d.Ack(false)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (w *CommentWorker) process(ctx context.Context, body []byte) error {
|
||||
func (w *CommentWorker) process(ctx context.Context, d amqp.Delivery) error {
|
||||
var evt rabbitmq.CommentEvent
|
||||
if err := json.Unmarshal(body, &evt); err != nil {
|
||||
return nil
|
||||
if err := json.Unmarshal(d.Body, &evt); err != nil {
|
||||
return rabbitmq.Permanent(fmt.Errorf("comment worker: decode event: %w", err))
|
||||
}
|
||||
|
||||
switch evt.Action {
|
||||
case "publish":
|
||||
return w.applyPublish(ctx, &evt)
|
||||
case "delete":
|
||||
return w.applyDelete(ctx, &evt)
|
||||
default:
|
||||
return nil
|
||||
return rabbitmq.Permanent(fmt.Errorf("comment worker: unknown action %q", evt.Action))
|
||||
}
|
||||
}
|
||||
|
||||
func (w *CommentWorker) applyPublish(ctx context.Context, evt *rabbitmq.CommentEvent) error {
|
||||
if evt == nil || evt.VideoID == 0 || evt.AuthorID == 0 || strings.TrimSpace(evt.Content) == "" {
|
||||
return nil
|
||||
return rabbitmq.Permanent(fmt.Errorf("comment worker: invalid publish event video_id=%d author_id=%d", evt.VideoID, evt.AuthorID))
|
||||
}
|
||||
|
||||
ok, err := w.videos.IsExist(ctx, evt.VideoID)
|
||||
@@ -108,6 +64,7 @@ func (w *CommentWorker) applyPublish(ctx context.Context, evt *rabbitmq.CommentE
|
||||
return err
|
||||
}
|
||||
if !ok {
|
||||
// 视频已删除:处理完了,不是失败。
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -116,23 +73,48 @@ func (w *CommentWorker) applyPublish(ctx context.Context, evt *rabbitmq.CommentE
|
||||
VideoID: evt.VideoID,
|
||||
AuthorID: evt.AuthorID,
|
||||
Content: strings.TrimSpace(evt.Content),
|
||||
// 行时间来自事件:桶必须落在评论发生的那一分钟。
|
||||
// 零值时由 GORM 的 autoCreateTime 补当前时刻并回填到这个字段。
|
||||
CreatedAt: evt.OccurredAt,
|
||||
}
|
||||
if err := w.comments.CreateComment(ctx, c); err != nil {
|
||||
// event_id 即意图键:API 已直写时这里会命中唯一索引。
|
||||
if evt.EventID != "" {
|
||||
key := evt.EventID
|
||||
c.IdempotencyKey = &key
|
||||
}
|
||||
|
||||
created, err := w.comments.CreateIdempotentWithPopularity(ctx, c, 1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return w.videos.ChangePopularity(ctx, evt.VideoID, 1)
|
||||
if !created {
|
||||
log.Printf("comment worker: dedupe=hit event_id=%s video_id=%d author_id=%d",
|
||||
evt.EventID, evt.VideoID, evt.AuthorID)
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := video.ApplyHotDelta(ctx, w.cache, c.VideoID, 1, c.CreatedAt); err != nil {
|
||||
log.Printf("comment worker: hot window update failed video=%d: %v", c.VideoID, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *CommentWorker) applyDelete(ctx context.Context, evt *rabbitmq.CommentEvent) error {
|
||||
if evt == nil || evt.CommentID == 0 {
|
||||
return nil
|
||||
return rabbitmq.Permanent(errors.New("comment worker: invalid delete event: comment_id is required"))
|
||||
}
|
||||
c, err := w.comments.GetByID(ctx, evt.CommentID)
|
||||
deleted, ok, err := w.comments.DeleteWithPopularity(ctx, evt.CommentID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if c == nil {
|
||||
if !ok {
|
||||
// 重复投递的删除是空操作,不是错误;热度也不能再减一次。
|
||||
log.Printf("comment worker: comment already deleted id=%d event_id=%s", evt.CommentID, evt.EventID)
|
||||
return nil
|
||||
}
|
||||
return w.comments.DeleteComment(ctx, c)
|
||||
|
||||
if err := video.ApplyHotDelta(ctx, w.cache, deleted.VideoID, -1, deleted.CreatedAt); err != nil {
|
||||
log.Printf("comment worker: hot window update failed comment_id=%d: %v", evt.CommentID, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
168
backend/internal/worker/commentworker_integration_test.go
Normal file
168
backend/internal/worker/commentworker_integration_test.go
Normal file
@@ -0,0 +1,168 @@
|
||||
//go:build integration
|
||||
|
||||
package worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"feedsystem_video_go/internal/middleware/rabbitmq"
|
||||
"feedsystem_video_go/internal/video"
|
||||
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
)
|
||||
|
||||
// 评论消费者"只写一次评论、热度跟着事务走"这条不变式只能在真实 MySQL 上验证:
|
||||
// 判重落在唯一索引 (author_id, idempotency_key) 上,没有数据库就没有被测对象。
|
||||
//
|
||||
// MYSQL_TEST_DSN='root:123456@tcp(127.0.0.1:3306)/feedsystem_test?charset=utf8mb4&parseTime=True&loc=Local' \
|
||||
// go test -tags integration -count=1 ./internal/worker/
|
||||
|
||||
func newCommentWorkerTestDB(t *testing.T) *gorm.DB {
|
||||
t.Helper()
|
||||
dsn := os.Getenv("MYSQL_TEST_DSN")
|
||||
if dsn == "" {
|
||||
t.Skip("MYSQL_TEST_DSN 未设置:需要真实 MySQL(见本文件顶部注释)")
|
||||
}
|
||||
if strings.Contains(dsn, "clientFoundRows") {
|
||||
t.Fatalf("测试 DSN 不能带 clientFoundRows:它会让 RowsAffected 判重失效")
|
||||
}
|
||||
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
|
||||
Logger: logger.Default.LogMode(logger.Silent),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("connect mysql: %v", err)
|
||||
}
|
||||
if err := db.Migrator().DropTable(&video.Comment{}, &video.Like{}, &video.Video{}); err != nil {
|
||||
t.Fatalf("drop tables: %v", err)
|
||||
}
|
||||
if err := db.AutoMigrate(&video.Video{}, &video.Comment{}, &video.Like{}); err != nil {
|
||||
t.Fatalf("migrate: %v", err)
|
||||
}
|
||||
return db
|
||||
}
|
||||
|
||||
func seedCommentVideo(t *testing.T, db *gorm.DB) *video.Video {
|
||||
t.Helper()
|
||||
v := &video.Video{
|
||||
AuthorID: 99,
|
||||
Username: "owner",
|
||||
Title: "t",
|
||||
PlayURL: "p",
|
||||
CoverURL: "c",
|
||||
Popularity: 0,
|
||||
}
|
||||
if err := db.Create(v).Error; err != nil {
|
||||
t.Fatalf("seed video: %v", err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// 同一条评论事件被投递两次(假失败 + 兜底 + 重投的必然结果),只能落一行,
|
||||
// 数据库热度也只能加一次。
|
||||
//
|
||||
// 两个断言分别钉住两件不同的事:行数 = 1 证明唯一索引吸收了重复;热度 = 1
|
||||
// (而不是 2)证明"加热度"与"插入评论"在同一个事务里、且以 created 为门控。
|
||||
// 热度写在这里而不是 Redis,是因为 videos.popularity 是事实,热榜只是它的滑窗副本。
|
||||
func TestCommentWorker_ApplyPublish_DuplicateEventWritesOneRow(t *testing.T) {
|
||||
db := newCommentWorkerTestDB(t)
|
||||
v := seedCommentVideo(t, db)
|
||||
w := NewCommentWorker(nil, nil, video.NewCommentRepository(db), video.NewVideoRepository(db), nil, "comment.events")
|
||||
evt := &rabbitmq.CommentEvent{
|
||||
EventID: "evt-comment-1",
|
||||
Action: "publish",
|
||||
Username: "alice",
|
||||
VideoID: v.ID,
|
||||
AuthorID: 1,
|
||||
Content: "好看",
|
||||
}
|
||||
|
||||
for i := 0; i < 2; i++ {
|
||||
if err := w.applyPublish(context.Background(), evt); err != nil {
|
||||
t.Fatalf("第 %d 次 applyPublish: %v", i+1, err)
|
||||
}
|
||||
}
|
||||
|
||||
var count int64
|
||||
if err := db.Model(&video.Comment{}).Where("video_id = ?", v.ID).Count(&count).Error; err != nil {
|
||||
t.Fatalf("count comments: %v", err)
|
||||
}
|
||||
if count != 1 {
|
||||
t.Fatalf("评论行数 = %d, want 1(event_id 相同的重复投递必须被判重吸收)", count)
|
||||
}
|
||||
|
||||
var got video.Video
|
||||
if err := db.First(&got, v.ID).Error; err != nil {
|
||||
t.Fatalf("reload video: %v", err)
|
||||
}
|
||||
if got.Popularity != 1 {
|
||||
t.Fatalf("popularity = %d, want 1(重复投递不得再加一次)", got.Popularity)
|
||||
}
|
||||
}
|
||||
|
||||
// event_id 为空(老版本消息/手工构造)时不能去重:没有键就无法判断重复,
|
||||
// 插入 NULL 键是唯一正确选择——用空字符串会撞唯一索引,把所有后续评论都吃掉。
|
||||
func TestCommentWorker_ApplyPublish_EmptyEventIDStillWrites(t *testing.T) {
|
||||
db := newCommentWorkerTestDB(t)
|
||||
v := seedCommentVideo(t, db)
|
||||
w := NewCommentWorker(nil, nil, video.NewCommentRepository(db), video.NewVideoRepository(db), nil, "comment.events")
|
||||
|
||||
evt := &rabbitmq.CommentEvent{
|
||||
Action: "publish",
|
||||
Username: "alice",
|
||||
VideoID: v.ID,
|
||||
AuthorID: 1,
|
||||
Content: "第一条",
|
||||
}
|
||||
if err := w.applyPublish(context.Background(), evt); err != nil {
|
||||
t.Fatalf("applyPublish: %v", err)
|
||||
}
|
||||
|
||||
var c video.Comment
|
||||
if err := db.Where("video_id = ?", v.ID).First(&c).Error; err != nil {
|
||||
t.Fatalf("load comment: %v", err)
|
||||
}
|
||||
if c.IdempotencyKey != nil {
|
||||
t.Fatalf("IdempotencyKey = %q, want NULL", *c.IdempotencyKey)
|
||||
}
|
||||
}
|
||||
|
||||
// 删除事件重投两次:第二次是空操作,不是错误(否则会被当成故障送去停泊)。
|
||||
func TestCommentWorker_ApplyDelete_DuplicateIsNoop(t *testing.T) {
|
||||
db := newCommentWorkerTestDB(t)
|
||||
v := seedCommentVideo(t, db)
|
||||
repo := video.NewCommentRepository(db)
|
||||
w := NewCommentWorker(nil, nil, repo, video.NewVideoRepository(db), nil, "comment.events")
|
||||
|
||||
c := &video.Comment{Username: "alice", VideoID: v.ID, AuthorID: 1, Content: "x"}
|
||||
if _, err := repo.CreateIdempotentWithPopularity(context.Background(), c, 1); err != nil {
|
||||
t.Fatalf("seed comment: %v", err)
|
||||
}
|
||||
|
||||
evt := &rabbitmq.CommentEvent{EventID: "evt-del-1", Action: "delete", CommentID: c.ID}
|
||||
for i := 0; i < 2; i++ {
|
||||
if err := w.applyDelete(context.Background(), evt); err != nil {
|
||||
t.Fatalf("第 %d 次 applyDelete: %v", i+1, err)
|
||||
}
|
||||
}
|
||||
|
||||
var count int64
|
||||
if err := db.Model(&video.Comment{}).Where("id = ?", c.ID).Count(&count).Error; err != nil {
|
||||
t.Fatalf("count: %v", err)
|
||||
}
|
||||
if count != 0 {
|
||||
t.Fatalf("评论行数 = %d, want 0", count)
|
||||
}
|
||||
// P2-20:删除必须回退热度,且只回退一次(第二次删除是空操作)。
|
||||
var got video.Video
|
||||
if err := db.First(&got, v.ID).Error; err != nil {
|
||||
t.Fatalf("reload video: %v", err)
|
||||
}
|
||||
if got.Popularity != 0 {
|
||||
t.Fatalf("popularity = %d, want 0(删除要回退热度,重复删除不得再减)", got.Popularity)
|
||||
}
|
||||
}
|
||||
109
backend/internal/worker/failedeventworker.go
Normal file
109
backend/internal/worker/failedeventworker.go
Normal file
@@ -0,0 +1,109 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"feedsystem_video_go/internal/failedevent"
|
||||
"feedsystem_video_go/internal/middleware/rabbitmq"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
)
|
||||
|
||||
// failedEventSaver 是这个 worker 对存储的唯一依赖。
|
||||
type failedEventSaver interface {
|
||||
Save(ctx context.Context, e *failedevent.FailedEvent) (bool, error)
|
||||
}
|
||||
|
||||
// FailedEventWorker 消费停泊队列,把失败消息落库到 failed_events。
|
||||
type FailedEventWorker struct {
|
||||
ch *amqp.Channel
|
||||
repo failedEventSaver
|
||||
queue string
|
||||
}
|
||||
|
||||
// failedEventRetryBackoff 是落库失败后重投之前的退避,变量以便单测调小。
|
||||
var failedEventRetryBackoff = 2 * time.Second
|
||||
|
||||
// NewFailedEventWorker 构造停泊消费者。
|
||||
func NewFailedEventWorker(ch *amqp.Channel, repo failedEventSaver, queue string) *FailedEventWorker {
|
||||
return &FailedEventWorker{ch: ch, repo: repo, queue: queue}
|
||||
}
|
||||
|
||||
// Run 消费停泊队列直到 ctx 取消;刻意不走 ConsumeLoop,否则停泊失败会递归停泊自己。
|
||||
func (w *FailedEventWorker) Run(ctx context.Context) error {
|
||||
if w == nil || w.ch == nil {
|
||||
return fmt.Errorf("failedevent worker: channel is not initialized")
|
||||
}
|
||||
deliveries, err := w.ch.Consume(w.queue, "", false, false, false, false, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("consume %s: %w", w.queue, err)
|
||||
}
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil
|
||||
case d, ok := <-deliveries:
|
||||
if !ok {
|
||||
return fmt.Errorf("consume %s: delivery channel closed", w.queue)
|
||||
}
|
||||
w.persist(ctx, d)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// persist 把停泊消息落库:失败则退避后 requeue,不 Ack、也不停泊自己。
|
||||
func (w *FailedEventWorker) persist(ctx context.Context, d amqp.Delivery) {
|
||||
info := rabbitmq.ParseParkedInfo(d)
|
||||
headers, err := json.Marshal(d.Headers)
|
||||
if err != nil {
|
||||
headers = []byte("{}")
|
||||
}
|
||||
record := &failedevent.FailedEvent{
|
||||
SourceQueue: info.SourceQueue,
|
||||
EventID: nilIfEmpty(info.EventID),
|
||||
RoutingKey: d.RoutingKey,
|
||||
Attempts: info.Attempts,
|
||||
Body: d.Body,
|
||||
Headers: string(headers),
|
||||
LastError: info.LastError,
|
||||
Status: failedevent.StatusPending,
|
||||
FirstFailedAt: time.Now(),
|
||||
}
|
||||
|
||||
created, err := w.repo.Save(ctx, record)
|
||||
if err != nil {
|
||||
log.Printf("failedevent: 落库失败 queue=%s err=%v(%v 后重投)", info.SourceQueue, err, failedEventRetryBackoff)
|
||||
_ = d.Nack(false, true)
|
||||
sleepCtx(ctx, failedEventRetryBackoff)
|
||||
return
|
||||
}
|
||||
if !created {
|
||||
log.Printf("failedevent: dedupe=hit source_queue=%s event_id=%s", info.SourceQueue, info.EventID)
|
||||
}
|
||||
if err := d.Ack(false); err != nil {
|
||||
log.Printf("failedevent: ack 失败 queue=%s err=%v", info.SourceQueue, err)
|
||||
}
|
||||
}
|
||||
|
||||
func nilIfEmpty(s string) *string {
|
||||
if s == "" {
|
||||
return nil
|
||||
}
|
||||
return &s
|
||||
}
|
||||
|
||||
// sleepCtx 返回 false 表示 ctx 已取消。
|
||||
func sleepCtx(ctx context.Context, d time.Duration) bool {
|
||||
t := time.NewTimer(d)
|
||||
defer t.Stop()
|
||||
select {
|
||||
case <-t.C:
|
||||
return true
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
}
|
||||
}
|
||||
203
backend/internal/worker/failedeventworker_test.go
Normal file
203
backend/internal/worker/failedeventworker_test.go
Normal file
@@ -0,0 +1,203 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"feedsystem_video_go/internal/failedevent"
|
||||
"feedsystem_video_go/internal/middleware/rabbitmq"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
)
|
||||
|
||||
// —— 测试替身 ——
|
||||
|
||||
// fakeAck 记录 Ack/Nack 调用,让"落库失败必须 requeue"这条契约可断言。
|
||||
type fakeAck struct {
|
||||
acks int
|
||||
nacks int
|
||||
requeue bool
|
||||
}
|
||||
|
||||
func (f *fakeAck) Ack(tag uint64, multiple bool) error {
|
||||
f.acks++
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeAck) Nack(tag uint64, multiple, requeue bool) error {
|
||||
f.nacks++
|
||||
f.requeue = requeue
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeAck) Reject(tag uint64, requeue bool) error {
|
||||
f.nacks++
|
||||
f.requeue = requeue
|
||||
return nil
|
||||
}
|
||||
|
||||
type fakeSaver struct {
|
||||
got *failedevent.FailedEvent
|
||||
created bool
|
||||
err error
|
||||
calls int
|
||||
}
|
||||
|
||||
func (f *fakeSaver) Save(_ context.Context, e *failedevent.FailedEvent) (bool, error) {
|
||||
f.calls++
|
||||
f.got = e
|
||||
return f.created, f.err
|
||||
}
|
||||
|
||||
// parkedDelivery 构造一条来自 Park 的投递(header 齐备)。
|
||||
func parkedDelivery(body string) amqp.Delivery {
|
||||
return amqp.Delivery{
|
||||
Acknowledger: &fakeAck{},
|
||||
DeliveryTag: 1,
|
||||
RoutingKey: "publish",
|
||||
Body: []byte(body),
|
||||
Headers: amqp.Table{
|
||||
rabbitmq.HeaderSourceQueue: "comment.events",
|
||||
rabbitmq.HeaderAttempts: int32(4),
|
||||
rabbitmq.HeaderLastError: "db: connection refused",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// —— persist 契约 ——
|
||||
|
||||
func TestFailedEventWorker_Persist_SavesParkedRecord(t *testing.T) {
|
||||
saver := &fakeSaver{created: true}
|
||||
w := NewFailedEventWorker(nil, saver, rabbitmq.ParkedQueue)
|
||||
d := parkedDelivery(`{"event_id":"k1","action":"publish","video_id":7}`)
|
||||
|
||||
w.persist(context.Background(), d)
|
||||
|
||||
if saver.calls != 1 {
|
||||
t.Fatalf("Save 调用 %d 次, want 1", saver.calls)
|
||||
}
|
||||
got := saver.got
|
||||
if got.SourceQueue != "comment.events" {
|
||||
t.Fatalf("SourceQueue = %q", got.SourceQueue)
|
||||
}
|
||||
if got.EventID == nil || *got.EventID != "k1" {
|
||||
t.Fatalf("EventID = %v, want k1", got.EventID)
|
||||
}
|
||||
if got.Attempts != 4 {
|
||||
t.Fatalf("Attempts = %d, want 4", got.Attempts)
|
||||
}
|
||||
if got.LastError != "db: connection refused" {
|
||||
t.Fatalf("LastError = %q", got.LastError)
|
||||
}
|
||||
if got.Status != failedevent.StatusPending {
|
||||
t.Fatalf("Status = %q, want %q", got.Status, failedevent.StatusPending)
|
||||
}
|
||||
if got.FirstFailedAt.IsZero() {
|
||||
t.Fatal("FirstFailedAt 不应为零值(运维要按时间排查)")
|
||||
}
|
||||
if len(got.Body) == 0 || got.Headers == "" {
|
||||
t.Fatal("Body/Headers 必须保留,否则无法重放")
|
||||
}
|
||||
|
||||
if ack, ok := d.Acknowledger.(*fakeAck); !ok || ack.acks != 1 || ack.nacks != 0 {
|
||||
t.Fatalf("落库成功必须恰好 Ack 一次,实际 %+v", d.Acknowledger)
|
||||
}
|
||||
}
|
||||
|
||||
// TestFailedEventWorker_Persist_EmptyEventIDBecomesNil 守护"坏消息写 NULL"。
|
||||
// 空字符串会与其它空 id 的记录撞唯一键,NULL 不会(MySQL 里 NULL 不参与比较)。
|
||||
func TestFailedEventWorker_Persist_EmptyEventIDBecomesNil(t *testing.T) {
|
||||
saver := &fakeSaver{created: true}
|
||||
w := NewFailedEventWorker(nil, saver, rabbitmq.ParkedQueue)
|
||||
|
||||
w.persist(context.Background(), parkedDelivery(`not json`))
|
||||
|
||||
if saver.got == nil {
|
||||
t.Fatal("Save 必须被调用")
|
||||
}
|
||||
if saver.got.EventID != nil {
|
||||
t.Fatalf("EventID = %v, want nil", *saver.got.EventID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFailedEventWorker_Persist_SaveFailureRequeuesAndBacksOff(t *testing.T) {
|
||||
old := failedEventRetryBackoff
|
||||
failedEventRetryBackoff = time.Millisecond
|
||||
t.Cleanup(func() { failedEventRetryBackoff = old })
|
||||
|
||||
saver := &fakeSaver{err: errors.New("db down")}
|
||||
w := NewFailedEventWorker(nil, saver, rabbitmq.ParkedQueue)
|
||||
d := parkedDelivery(`{"event_id":"k2"}`)
|
||||
|
||||
start := time.Now()
|
||||
w.persist(context.Background(), d)
|
||||
elapsed := time.Since(start)
|
||||
|
||||
ack, ok := d.Acknowledger.(*fakeAck)
|
||||
if !ok {
|
||||
t.Fatal("缺 Acknowledger")
|
||||
}
|
||||
if ack.acks != 0 {
|
||||
t.Fatalf("落库失败绝不能 Ack(会丢消息),acks=%d", ack.acks)
|
||||
}
|
||||
if ack.nacks != 1 || !ack.requeue {
|
||||
t.Fatalf("落库失败必须 Nack(requeue=true),实际 nacks=%d requeue=%v", ack.nacks, ack.requeue)
|
||||
}
|
||||
if elapsed < failedEventRetryBackoff {
|
||||
t.Fatalf("重投前应有退避,实际只用了 %v", elapsed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFailedEventWorker_Persist_DuplicateIsStillAcked(t *testing.T) {
|
||||
saver := &fakeSaver{created: false}
|
||||
w := NewFailedEventWorker(nil, saver, rabbitmq.ParkedQueue)
|
||||
d := parkedDelivery(`{"event_id":"k3"}`)
|
||||
|
||||
w.persist(context.Background(), d)
|
||||
|
||||
ack, _ := d.Acknowledger.(*fakeAck)
|
||||
if ack.acks != 1 || ack.nacks != 0 {
|
||||
t.Fatalf("重复停泊是幂等成功,必须 Ack,实际 acks=%d nacks=%d", ack.acks, ack.nacks)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFailedEventWorker_Persist_CancelledContextStillNacks(t *testing.T) {
|
||||
old := failedEventRetryBackoff
|
||||
failedEventRetryBackoff = time.Hour // 只有 ctx 取消才能让它立刻返回
|
||||
t.Cleanup(func() { failedEventRetryBackoff = old })
|
||||
|
||||
saver := &fakeSaver{err: errors.New("db down")}
|
||||
w := NewFailedEventWorker(nil, saver, rabbitmq.ParkedQueue)
|
||||
d := parkedDelivery(`{"event_id":"k4"}`)
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
w.persist(ctx, d)
|
||||
close(done)
|
||||
}()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("ctx 取消后 sleepCtx 必须立刻返回,否则退出会被退避拖住")
|
||||
}
|
||||
|
||||
ack, _ := d.Acknowledger.(*fakeAck)
|
||||
if ack.nacks != 1 {
|
||||
t.Fatalf("nacks = %d, want 1(先 Nack 再退避)", ack.nacks)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNilIfEmpty(t *testing.T) {
|
||||
if got := nilIfEmpty(""); got != nil {
|
||||
t.Fatalf("nilIfEmpty(\"\") = %v, want nil", got)
|
||||
}
|
||||
got := nilIfEmpty("abc")
|
||||
if got == nil || *got != "abc" {
|
||||
t.Fatalf("nilIfEmpty(\"abc\") = %v", got)
|
||||
}
|
||||
}
|
||||
@@ -4,23 +4,28 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"feedsystem_video_go/internal/middleware/rabbitmq"
|
||||
"feedsystem_video_go/internal/video"
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"feedsystem_video_go/internal/middleware/rabbitmq"
|
||||
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||||
"feedsystem_video_go/internal/video"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
)
|
||||
|
||||
type LikeWorker struct {
|
||||
ch *amqp.Channel
|
||||
parker rabbitmq.Parker
|
||||
likes *video.LikeRepository
|
||||
videos *video.VideoRepository
|
||||
cache *rediscache.Client
|
||||
queue string
|
||||
}
|
||||
|
||||
func NewLikeWorker(ch *amqp.Channel, likes *video.LikeRepository, videos *video.VideoRepository, queue string) *LikeWorker {
|
||||
return &LikeWorker{ch: ch, likes: likes, videos: videos, queue: queue}
|
||||
func NewLikeWorker(ch *amqp.Channel, parker rabbitmq.Parker, likes *video.LikeRepository, videos *video.VideoRepository, cache *rediscache.Client, queue string) *LikeWorker {
|
||||
return &LikeWorker{ch: ch, parker: parker, likes: likes, videos: videos, cache: cache, queue: queue}
|
||||
}
|
||||
|
||||
func (w *LikeWorker) Run(ctx context.Context) error {
|
||||
@@ -30,107 +35,68 @@ func (w *LikeWorker) Run(ctx context.Context) error {
|
||||
if w.queue == "" {
|
||||
return errors.New("queue is required")
|
||||
}
|
||||
|
||||
deliveries, err := w.ch.Consume(
|
||||
w.queue, // 队列名
|
||||
"", // 消费者标签,空代表让 RabbitMQ 自动生成一个唯一的标签
|
||||
false, // autoAck = false 采用手动确认模式
|
||||
false, // exclusive = false 允许多个消费者同时消费同一个队列
|
||||
false, // noLocal = false 允许消费者接收自己发送的消息
|
||||
false, // noWait = false 阻塞等待 RabbitMQ 的响应
|
||||
nil, // args
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case d, ok := <-deliveries:
|
||||
if !ok {
|
||||
return errors.New("deliveries channel closed")
|
||||
}
|
||||
w.handleDelivery(ctx, d)
|
||||
}
|
||||
}
|
||||
// 消费循环只剩这一处:重试、停泊、Ack 的规则全在 rabbitmq.ConsumeLoop 里。
|
||||
return rabbitmq.ConsumeLoop(ctx, w.ch, w.parker, w.queue, rabbitmq.MaxAttempts, w.process)
|
||||
}
|
||||
|
||||
func (w *LikeWorker) handleDelivery(ctx context.Context, d amqp.Delivery) {
|
||||
const maxRetries = 3
|
||||
for i := 0; i <= maxRetries; i++ {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
_ = d.Nack(false, true)
|
||||
return
|
||||
default:
|
||||
}
|
||||
if err := w.process(ctx, d.Body); err != nil {
|
||||
if i >= maxRetries {
|
||||
log.Printf("like worker: 重试 %d 次后仍失败, 丢弃: %v", maxRetries, err)
|
||||
_ = d.Ack(false)
|
||||
return
|
||||
}
|
||||
wait := time.Duration(1<<uint(i)) * time.Second
|
||||
log.Printf("like worker: 处理失败, %v 后重试 (%d/%d): %v", wait, i+1, maxRetries, err)
|
||||
time.Sleep(wait)
|
||||
continue
|
||||
}
|
||||
_ = d.Ack(false)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (w *LikeWorker) process(ctx context.Context, body []byte) error {
|
||||
func (w *LikeWorker) process(ctx context.Context, d amqp.Delivery) error {
|
||||
var evt rabbitmq.LikeEvent
|
||||
if err := json.Unmarshal(body, &evt); err != nil {
|
||||
// 解析事件失败,直接丢弃
|
||||
return nil
|
||||
if err := json.Unmarshal(d.Body, &evt); err != nil {
|
||||
// 坏消息重投多少次都是坏的:标记为不可重试,立即停泊而不是烧掉 3 次重试。
|
||||
return rabbitmq.Permanent(fmt.Errorf("like worker: decode event: %w", err))
|
||||
}
|
||||
if evt.UserID == 0 || evt.VideoID == 0 {
|
||||
return nil
|
||||
return rabbitmq.Permanent(fmt.Errorf("like worker: invalid event user_id=%d video_id=%d", evt.UserID, evt.VideoID))
|
||||
}
|
||||
|
||||
switch evt.Action {
|
||||
case "like":
|
||||
return w.applyLike(ctx, evt.UserID, evt.VideoID)
|
||||
return w.applyLike(ctx, evt)
|
||||
case "unlike":
|
||||
return w.applyUnlike(ctx, evt.UserID, evt.VideoID)
|
||||
return w.applyUnlike(ctx, evt)
|
||||
default:
|
||||
return nil
|
||||
return rabbitmq.Permanent(fmt.Errorf("like worker: unknown action %q", evt.Action))
|
||||
}
|
||||
}
|
||||
|
||||
func (w *LikeWorker) applyLike(ctx context.Context, userID, videoID uint) error {
|
||||
ok, err := w.videos.IsExist(ctx, videoID)
|
||||
func (w *LikeWorker) applyLike(ctx context.Context, evt rabbitmq.LikeEvent) error {
|
||||
ok, err := w.videos.IsExist(ctx, evt.VideoID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok {
|
||||
// 视频已被删除:这条点赞没有可落的地方,但它是"处理完了",不是失败。
|
||||
return nil
|
||||
}
|
||||
|
||||
created, err := w.likes.LikeIgnoreDuplicate(ctx, &video.Like{
|
||||
VideoID: videoID,
|
||||
AccountID: userID,
|
||||
CreatedAt: time.Now(),
|
||||
// 行时间来自消息:积压的 worker 必须把增量记在事件发生的那一分钟。
|
||||
at := evt.OccurredAt
|
||||
if at.IsZero() {
|
||||
at = time.Now()
|
||||
}
|
||||
|
||||
created, err := w.likes.ApplyLike(ctx, &video.Like{
|
||||
VideoID: evt.VideoID,
|
||||
AccountID: evt.UserID,
|
||||
CreatedAt: at,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !created {
|
||||
// 重复投递:点赞已存在,计数与热榜都不能再加。
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := w.videos.ChangeLikesCount(ctx, videoID, 1); err != nil {
|
||||
return err
|
||||
// 热榜是派生数据:写失败不回滚点赞,-verify 能发现、-rebuild-hot 能补回。
|
||||
if err := video.ApplyHotDelta(ctx, w.cache, evt.VideoID, 1, at); err != nil {
|
||||
log.Printf("like worker: hot window update failed video=%d: %v", evt.VideoID, err)
|
||||
}
|
||||
return w.videos.ChangePopularity(ctx, videoID, 1)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *LikeWorker) applyUnlike(ctx context.Context, userID, videoID uint) error {
|
||||
ok, err := w.videos.IsExist(ctx, videoID)
|
||||
func (w *LikeWorker) applyUnlike(ctx context.Context, evt rabbitmq.LikeEvent) error {
|
||||
ok, err := w.videos.IsExist(ctx, evt.VideoID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -138,16 +104,18 @@ func (w *LikeWorker) applyUnlike(ctx context.Context, userID, videoID uint) erro
|
||||
return nil
|
||||
}
|
||||
|
||||
deleted, err := w.likes.DeleteByVideoAndAccount(ctx, videoID, userID)
|
||||
row, deleted, err := w.likes.ApplyUnlike(ctx, evt.VideoID, evt.UserID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !deleted {
|
||||
// 重复投递:行已经不在了,热度也不能再减。
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := w.videos.ChangeLikesCount(ctx, videoID, -1); err != nil {
|
||||
return err
|
||||
// 减回点赞那一刻的桶,不能按消费时刻减。
|
||||
if err := video.ApplyHotDelta(ctx, w.cache, evt.VideoID, -1, row.CreatedAt); err != nil {
|
||||
log.Printf("like worker: hot window update failed video=%d: %v", evt.VideoID, err)
|
||||
}
|
||||
return w.videos.ChangePopularity(ctx, videoID, -1)
|
||||
return nil
|
||||
}
|
||||
|
||||
133
backend/internal/worker/likeworker_integration_test.go
Normal file
133
backend/internal/worker/likeworker_integration_test.go
Normal file
@@ -0,0 +1,133 @@
|
||||
//go:build integration
|
||||
|
||||
package worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"feedsystem_video_go/internal/middleware/rabbitmq"
|
||||
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||||
"feedsystem_video_go/internal/video"
|
||||
|
||||
"github.com/alicebob/miniredis/v2"
|
||||
goredis "github.com/redis/go-redis/v9"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// 热榜增量必须由"事务是否真的插入"驱动,而不是由消息驱动:
|
||||
// 重投一次不能再加一次分,否则同一次点赞会在榜上加两次。
|
||||
func newLikeWorkerCache(t *testing.T) (*rediscache.Client, *miniredis.Miniredis) {
|
||||
t.Helper()
|
||||
mr := miniredis.RunT(t)
|
||||
rdb := goredis.NewClient(&goredis.Options{Addr: mr.Addr()})
|
||||
t.Cleanup(func() { _ = rdb.Close() })
|
||||
return rediscache.NewClient(rdb, "test:"), mr
|
||||
}
|
||||
|
||||
func hotScore(t *testing.T, cache *rediscache.Client, mr *miniredis.Miniredis, videoID uint, at time.Time) float64 {
|
||||
t.Helper()
|
||||
score, err := mr.ZScore(cache.Key("hot:video:1m:%s", video.HotBucket(at)), video.HotMember(videoID))
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return score
|
||||
}
|
||||
|
||||
func reloadVideo(t *testing.T, db *gorm.DB, id uint) video.Video {
|
||||
t.Helper()
|
||||
var v video.Video
|
||||
if err := db.First(&v, id).Error; err != nil {
|
||||
t.Fatalf("reload video: %v", err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func TestLikeWorker_ReplayDoesNotDoubleHot(t *testing.T) {
|
||||
db := newCommentWorkerTestDB(t)
|
||||
v := seedCommentVideo(t, db)
|
||||
cache, mr := newLikeWorkerCache(t)
|
||||
w := NewLikeWorker(nil, nil, video.NewLikeRepository(db), video.NewVideoRepository(db), cache, "like.events")
|
||||
|
||||
// 10 分钟前发生的点赞,10 分钟后才被消费:桶要按 OccurredAt 落。
|
||||
at := time.Now().UTC().Add(-10 * time.Minute).Truncate(time.Second)
|
||||
evt := &rabbitmq.LikeEvent{EventID: "evt-like-1", Action: "like", UserID: 7, VideoID: v.ID, OccurredAt: at}
|
||||
|
||||
for i := 0; i < 2; i++ {
|
||||
if err := w.applyLike(context.Background(), *evt); err != nil {
|
||||
t.Fatalf("第 %d 次 applyLike: %v", i+1, err)
|
||||
}
|
||||
}
|
||||
|
||||
got := reloadVideo(t, db, v.ID)
|
||||
if got.LikesCount != 1 || got.Popularity != 1 {
|
||||
t.Fatalf("likes_count=%d popularity=%d, want 1/1(重投不得再计数)", got.LikesCount, got.Popularity)
|
||||
}
|
||||
if score := hotScore(t, cache, mr, v.ID, at); score != 1 {
|
||||
t.Fatalf("热榜分数 = %v, want 1(重投不得再加一次分)", score)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLikeWorker_UnlikeRevertsOriginalBucket(t *testing.T) {
|
||||
db := newCommentWorkerTestDB(t)
|
||||
v := seedCommentVideo(t, db)
|
||||
cache, mr := newLikeWorkerCache(t)
|
||||
w := NewLikeWorker(nil, nil, video.NewLikeRepository(db), video.NewVideoRepository(db), cache, "like.events")
|
||||
|
||||
at := time.Now().UTC().Add(-20 * time.Minute).Truncate(time.Second)
|
||||
if err := w.applyLike(context.Background(), rabbitmq.LikeEvent{EventID: "e1", Action: "like", UserID: 7, VideoID: v.ID, OccurredAt: at}); err != nil {
|
||||
t.Fatalf("applyLike: %v", err)
|
||||
}
|
||||
|
||||
// 取消事件的重投也要是空操作,且 -1 落回点赞那一分钟。
|
||||
unlike := &rabbitmq.LikeEvent{EventID: "e2", Action: "unlike", UserID: 7, VideoID: v.ID}
|
||||
if err := w.applyUnlike(context.Background(), *unlike); err != nil {
|
||||
t.Fatalf("applyUnlike: %v", err)
|
||||
}
|
||||
if err := w.applyUnlike(context.Background(), *unlike); err != nil {
|
||||
t.Fatalf("重复 applyUnlike: %v", err)
|
||||
}
|
||||
|
||||
got := reloadVideo(t, db, v.ID)
|
||||
if got.LikesCount != 0 || got.Popularity != 0 {
|
||||
t.Fatalf("likes_count=%d popularity=%d, want 0/0", got.LikesCount, got.Popularity)
|
||||
}
|
||||
if score := hotScore(t, cache, mr, v.ID, at); score != 0 {
|
||||
t.Fatalf("原桶分数 = %v, want 0(+1 与 -1 落在同一分钟)", score)
|
||||
}
|
||||
}
|
||||
|
||||
// P2-20:删除评论时必须把热度 -1 记回评论创建的那一分钟。
|
||||
func TestCommentWorker_DeleteRevertsHot(t *testing.T) {
|
||||
db := newCommentWorkerTestDB(t)
|
||||
v := seedCommentVideo(t, db)
|
||||
cache, mr := newLikeWorkerCache(t)
|
||||
repo := video.NewCommentRepository(db)
|
||||
w := NewCommentWorker(nil, nil, repo, video.NewVideoRepository(db), cache, "comment.events")
|
||||
|
||||
createdAt := time.Now().UTC().Add(-15 * time.Minute).Truncate(time.Second)
|
||||
c := &video.Comment{Username: "alice", VideoID: v.ID, AuthorID: 1, Content: "x", CreatedAt: createdAt}
|
||||
if created, err := repo.CreateIdempotentWithPopularity(context.Background(), c, 1); err != nil || !created {
|
||||
t.Fatalf("seed comment = created:%v err:%v", created, err)
|
||||
}
|
||||
// 用真实行时间模拟"发布时已经加过一分"。
|
||||
if err := video.ApplyHotDelta(context.Background(), cache, v.ID, 1, createdAt); err != nil {
|
||||
t.Fatalf("seed hot delta: %v", err)
|
||||
}
|
||||
|
||||
evt := &rabbitmq.CommentEvent{EventID: "evt-del-1", Action: "delete", CommentID: c.ID}
|
||||
for i := 0; i < 2; i++ {
|
||||
if err := w.applyDelete(context.Background(), evt); err != nil {
|
||||
t.Fatalf("第 %d 次 applyDelete: %v", i+1, err)
|
||||
}
|
||||
}
|
||||
|
||||
got := reloadVideo(t, db, v.ID)
|
||||
if got.Popularity != 0 {
|
||||
t.Fatalf("popularity = %d, want 0(删除回退一次,重投不再减)", got.Popularity)
|
||||
}
|
||||
if score := hotScore(t, cache, mr, v.ID, createdAt); score != 0 {
|
||||
t.Fatalf("原桶分数 = %v, want 0(-1 必须落回创建那一分钟)", score)
|
||||
}
|
||||
}
|
||||
129
backend/internal/worker/notificationbus.go
Normal file
129
backend/internal/worker/notificationbus.go
Normal file
@@ -0,0 +1,129 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||||
"feedsystem_video_go/internal/notification"
|
||||
)
|
||||
|
||||
// 频道名经 cache.Key 加前缀,与环境内其他键共用命名空间。
|
||||
const notificationBusChannel = "notification:push"
|
||||
|
||||
const (
|
||||
notificationPushTimeout = 500 * time.Millisecond
|
||||
notificationBusMinBackoff = time.Second
|
||||
notificationBusMaxBackoff = 30 * time.Second
|
||||
)
|
||||
|
||||
// 跨进程线缆格式:改动它必须同时改生产端与消费端。
|
||||
type notificationPushEnvelope struct {
|
||||
UserID uint `json:"user_id"`
|
||||
Notification *notification.Notification `json:"notification"`
|
||||
}
|
||||
|
||||
// RedisNotificationPublisher 把通知发给 Redis,由各 API 实例转给本地 SSE 连接。
|
||||
type RedisNotificationPublisher struct {
|
||||
cache *rediscache.Client
|
||||
}
|
||||
|
||||
func NewRedisNotificationPublisher(cache *rediscache.Client) *RedisNotificationPublisher {
|
||||
return &RedisNotificationPublisher{cache: cache}
|
||||
}
|
||||
|
||||
// Push 尽力而为:通知已落库,失败只影响实时性。
|
||||
func (p *RedisNotificationPublisher) Push(userID uint, n *notification.Notification) {
|
||||
if p == nil || p.cache == nil || n == nil || userID == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
payload, err := json.Marshal(notificationPushEnvelope{UserID: userID, Notification: n})
|
||||
if err != nil {
|
||||
log.Printf("notification push: 序列化失败 notification=%d: %v", n.ID, err)
|
||||
return
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), notificationPushTimeout)
|
||||
defer cancel()
|
||||
if err := p.cache.Publish(ctx, p.cache.Key(notificationBusChannel), payload); err != nil {
|
||||
log.Printf("notification push: 发布失败 notification=%d user=%d(通知已落库,实时推送跳过): %v",
|
||||
n.ID, userID, err)
|
||||
}
|
||||
}
|
||||
|
||||
// StartNotificationSubscriber 订阅推送通道并转给本地 SSE;Redis 不可用时只降级实时推送。
|
||||
func StartNotificationSubscriber(ctx context.Context, cache *rediscache.Client, hub NotificationHub) {
|
||||
if cache == nil || hub == nil {
|
||||
log.Printf("Notification push disabled: redis 或 hub 未初始化")
|
||||
return
|
||||
}
|
||||
|
||||
go func() {
|
||||
backoff := notificationBusMinBackoff
|
||||
for ctx.Err() == nil {
|
||||
started := time.Now()
|
||||
err := runNotificationSubscriber(ctx, cache, hub, nil)
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
// 存活够久说明是抖动而非配置错误:重置退避,避免长期停在长退避上。
|
||||
if time.Since(started) > notificationBusMaxBackoff {
|
||||
backoff = notificationBusMinBackoff
|
||||
}
|
||||
log.Printf("notification push: 订阅中断(%v 后重连): %v", backoff, err)
|
||||
if !waitOrDone(ctx, backoff) {
|
||||
return
|
||||
}
|
||||
backoff *= 2
|
||||
if backoff > notificationBusMaxBackoff {
|
||||
backoff = notificationBusMaxBackoff
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// runNotificationSubscriber 转发到 ctx 取消或订阅断开;onSubscribed 供测试确认订阅生效。
|
||||
func runNotificationSubscriber(ctx context.Context, cache *rediscache.Client, hub NotificationHub, onSubscribed func()) error {
|
||||
if cache == nil || hub == nil {
|
||||
return errors.New("notification subscriber: redis 或 hub 未初始化")
|
||||
}
|
||||
|
||||
sub, err := cache.Subscribe(ctx, cache.Key(notificationBusChannel))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = sub.Close() }()
|
||||
|
||||
if onSubscribed != nil {
|
||||
onSubscribed()
|
||||
}
|
||||
|
||||
msgs := sub.Channel()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil
|
||||
case msg, ok := <-msgs:
|
||||
if !ok {
|
||||
return errors.New("订阅通道已关闭")
|
||||
}
|
||||
var envelope notificationPushEnvelope
|
||||
if err := json.Unmarshal([]byte(msg.Payload), &envelope); err != nil {
|
||||
// 坏消息不能打断订阅:否则一条脏数据会让后续所有通知都送不到。
|
||||
log.Printf("notification push: 丢弃无法解析的消息: %v", err)
|
||||
continue
|
||||
}
|
||||
if envelope.UserID == 0 || envelope.Notification == nil {
|
||||
log.Printf("notification push: 丢弃缺少 user_id/notification 的消息")
|
||||
continue
|
||||
}
|
||||
hub.Push(envelope.UserID, envelope.Notification)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var _ NotificationHub = (*RedisNotificationPublisher)(nil)
|
||||
145
backend/internal/worker/notificationbus_test.go
Normal file
145
backend/internal/worker/notificationbus_test.go
Normal file
@@ -0,0 +1,145 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||||
"feedsystem_video_go/internal/notification"
|
||||
|
||||
miniredis "github.com/alicebob/miniredis/v2"
|
||||
goredis "github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
// recordingHub 用带缓冲的 channel 记录推送:测试靠 channel 同步,不靠 sleep 猜时序。
|
||||
type recordingHub struct {
|
||||
pushes chan recordedPush
|
||||
}
|
||||
|
||||
type recordedPush struct {
|
||||
userID uint
|
||||
n *notification.Notification
|
||||
}
|
||||
|
||||
func newRecordingHub() *recordingHub {
|
||||
return &recordingHub{pushes: make(chan recordedPush, 8)}
|
||||
}
|
||||
|
||||
func (h *recordingHub) Push(userID uint, n *notification.Notification) {
|
||||
h.pushes <- recordedPush{userID: userID, n: n}
|
||||
}
|
||||
|
||||
func newTestRedisClient(t *testing.T) *rediscache.Client {
|
||||
t.Helper()
|
||||
mr, err := miniredis.Run()
|
||||
if err != nil {
|
||||
t.Fatalf("start miniredis: %v", err)
|
||||
}
|
||||
client := rediscache.NewClient(goredis.NewClient(&goredis.Options{Addr: mr.Addr()}), "v1:")
|
||||
t.Cleanup(func() {
|
||||
_ = client.Close()
|
||||
mr.Close()
|
||||
})
|
||||
return client
|
||||
}
|
||||
|
||||
// startSubscriber 起一个订阅器,并等到订阅真正建立(SUBSCRIBE 确认返回)再返回。
|
||||
func startSubscriber(t *testing.T, ctx context.Context, client *rediscache.Client, hub NotificationHub) <-chan error {
|
||||
t.Helper()
|
||||
subscribed := make(chan struct{})
|
||||
errCh := make(chan error, 1)
|
||||
go func() {
|
||||
errCh <- runNotificationSubscriber(ctx, client, hub, func() { close(subscribed) })
|
||||
}()
|
||||
select {
|
||||
case <-subscribed:
|
||||
return errCh
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("订阅器未在 5s 内建立订阅")
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func TestNotificationBus_PublishReachesSubscriber(t *testing.T) {
|
||||
client := newTestRedisClient(t)
|
||||
hub := newRecordingHub()
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
startSubscriber(t, ctx, client, hub)
|
||||
|
||||
want := ¬ification.Notification{ID: 7, RecipientID: 42, Type: "like", TargetID: 9}
|
||||
NewRedisNotificationPublisher(client).Push(42, want)
|
||||
|
||||
select {
|
||||
case got := <-hub.pushes:
|
||||
if got.userID != 42 {
|
||||
t.Fatalf("user_id = %d, want 42(投递给错误的 SSE 连接等于通知丢失)", got.userID)
|
||||
}
|
||||
if got.n == nil || got.n.ID != want.ID || got.n.Type != want.Type || got.n.TargetID != want.TargetID {
|
||||
t.Fatalf("notification = %+v, want %+v", got.n, want)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("通知没有穿过 Redis Pub/Sub:worker 落库后 API 侧收不到推送")
|
||||
}
|
||||
}
|
||||
|
||||
// 一条坏消息不能让订阅器退出,否则后续合法通知都送不到。
|
||||
func TestNotificationSubscriber_SkipsMalformedPayload(t *testing.T) {
|
||||
client := newTestRedisClient(t)
|
||||
hub := newRecordingHub()
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
startSubscriber(t, ctx, client, hub)
|
||||
|
||||
channel := client.Key(notificationBusChannel)
|
||||
pubCtx, pubCancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer pubCancel()
|
||||
if err := client.Publish(pubCtx, channel, []byte(`{"user_id":`)); err != nil {
|
||||
t.Fatalf("publish malformed: %v", err)
|
||||
}
|
||||
|
||||
good := ¬ification.Notification{ID: 11, RecipientID: 5, Type: "follow"}
|
||||
NewRedisNotificationPublisher(client).Push(5, good)
|
||||
|
||||
select {
|
||||
case got := <-hub.pushes:
|
||||
if got.n == nil || got.n.ID != good.ID {
|
||||
t.Fatalf("收到 %+v,坏消息没有被跳过", got.n)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("坏消息之后的合法通知没有送达:订阅循环已退出")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNotificationSubscriber_StopsOnContextCancel(t *testing.T) {
|
||||
client := newTestRedisClient(t)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
errCh := startSubscriber(t, ctx, client, newRecordingHub())
|
||||
|
||||
cancel()
|
||||
|
||||
select {
|
||||
case err := <-errCh:
|
||||
if err != nil {
|
||||
t.Fatalf("ctx 取消应视为正常退出,got err = %v", err)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("ctx 取消后订阅器没有退出:API 无法优雅停机")
|
||||
}
|
||||
}
|
||||
|
||||
// Redis 未配置时 SSE 仍要能建立连接并读历史通知,只是没有实时推送。
|
||||
func TestRedisNotificationPublisher_NilClientIsNoop(t *testing.T) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
t.Fatalf("Redis 不可用时 Push 不允许 panic: %v", r)
|
||||
}
|
||||
}()
|
||||
|
||||
NewRedisNotificationPublisher(nil).Push(1, ¬ification.Notification{ID: 1})
|
||||
(*RedisNotificationPublisher)(nil).Push(1, ¬ification.Notification{ID: 1})
|
||||
NewRedisNotificationPublisher(nil).Push(1, nil)
|
||||
}
|
||||
@@ -4,38 +4,39 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"feedsystem_video_go/internal/middleware/rabbitmq"
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"feedsystem_video_go/internal/middleware/rabbitmq"
|
||||
"feedsystem_video_go/internal/notification"
|
||||
"feedsystem_video_go/internal/video"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
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"`
|
||||
// 分派必须用队列 + body.action:重试回源会把 routing key 改写成队列名。
|
||||
var notificationActions = map[string]string{
|
||||
rabbitmq.NotificationLikeQueue: "like",
|
||||
rabbitmq.NotificationCommentQueue: "publish",
|
||||
rabbitmq.NotificationSocialQueue: "follow",
|
||||
}
|
||||
|
||||
type NotificationWorker struct {
|
||||
ch *amqp.Channel
|
||||
db *gorm.DB
|
||||
queue string
|
||||
hub NotificationHub
|
||||
ch *amqp.Channel
|
||||
parker rabbitmq.Parker
|
||||
db *gorm.DB
|
||||
queue string
|
||||
hub NotificationHub
|
||||
}
|
||||
|
||||
type NotificationHub interface {
|
||||
Push(userID uint, n *Notification)
|
||||
Push(userID uint, n *notification.Notification)
|
||||
}
|
||||
|
||||
func NewNotificationWorker(ch *amqp.Channel, db *gorm.DB, queue string, hub NotificationHub) *NotificationWorker {
|
||||
return &NotificationWorker{ch: ch, db: db, queue: queue, hub: hub}
|
||||
func NewNotificationWorker(ch *amqp.Channel, parker rabbitmq.Parker, db *gorm.DB, queue string, hub NotificationHub) *NotificationWorker {
|
||||
return &NotificationWorker{ch: ch, parker: parker, db: db, queue: queue, hub: hub}
|
||||
}
|
||||
|
||||
func (w *NotificationWorker) Run(ctx context.Context) error {
|
||||
@@ -45,118 +46,135 @@ func (w *NotificationWorker) Run(ctx context.Context) error {
|
||||
if w.queue == "" {
|
||||
return errors.New("queue is required")
|
||||
}
|
||||
if err := w.db.WithContext(ctx).AutoMigrate(&Notification{}); err != nil {
|
||||
return err
|
||||
}
|
||||
deliveries, err := w.ch.Consume(w.queue, "", false, false, false, false, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case d, ok := <-deliveries:
|
||||
if !ok {
|
||||
return errors.New("deliveries channel closed")
|
||||
}
|
||||
w.handleDelivery(ctx, d)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (w *NotificationWorker) handleDelivery(ctx context.Context, d amqp.Delivery) {
|
||||
const maxRetries = 3
|
||||
for i := 0; i <= maxRetries; i++ {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
_ = d.Nack(false, true)
|
||||
return
|
||||
default:
|
||||
}
|
||||
if err := w.process(ctx, d); err != nil {
|
||||
if i >= maxRetries {
|
||||
log.Printf("notification worker: 重试 %d 次后仍失败, 丢弃: %v", maxRetries, err)
|
||||
_ = d.Ack(false)
|
||||
return
|
||||
}
|
||||
wait := time.Duration(1<<uint(i)) * time.Second
|
||||
log.Printf("notification worker: 处理失败, %v 后重试 (%d/%d): %v", wait, i+1, maxRetries, err)
|
||||
time.Sleep(wait)
|
||||
continue
|
||||
}
|
||||
_ = d.Ack(false)
|
||||
return
|
||||
}
|
||||
// 建表由 API 进程的 db.AutoMigrate 统一负责;三个消费者并发建索引会撞 1061。
|
||||
return rabbitmq.ConsumeLoop(ctx, w.ch, w.parker, w.queue, rabbitmq.MaxAttempts, w.process)
|
||||
}
|
||||
|
||||
func (w *NotificationWorker) process(ctx context.Context, d amqp.Delivery) error {
|
||||
body := d.Body
|
||||
if len(body) == 0 {
|
||||
return nil
|
||||
if len(d.Body) == 0 {
|
||||
return rabbitmq.Permanent(errors.New("notification worker: empty body"))
|
||||
}
|
||||
routingKey := d.RoutingKey // 复用路由键充当事件类型标识
|
||||
|
||||
var notif *Notification
|
||||
|
||||
switch {
|
||||
case routingKey == "like.like":
|
||||
var evt rabbitmq.LikeEvent
|
||||
if err := json.Unmarshal(body, &evt); err != nil {
|
||||
return nil
|
||||
}
|
||||
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: "点赞了你的视频"}
|
||||
|
||||
case routingKey == "comment.publish":
|
||||
var evt rabbitmq.CommentEvent
|
||||
if err := json.Unmarshal(body, &evt); err != nil {
|
||||
return nil
|
||||
}
|
||||
if evt.AuthorID == 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.AuthorID {
|
||||
return nil
|
||||
}
|
||||
notif = &Notification{RecipientID: authorID, SenderID: evt.AuthorID, Type: "comment", TargetID: evt.VideoID, Content: "评论了你的视频"}
|
||||
|
||||
case routingKey == "social.follow":
|
||||
var evt rabbitmq.SocialEvent
|
||||
if err := json.Unmarshal(body, &evt); err != nil {
|
||||
return nil
|
||||
}
|
||||
if evt.FollowerID == 0 || evt.VloggerID == 0 {
|
||||
return nil
|
||||
}
|
||||
notif = &Notification{RecipientID: evt.VloggerID, SenderID: evt.FollowerID, Type: "follow", TargetID: evt.FollowerID, Content: "关注了你"}
|
||||
want, ok := notificationActions[w.queue]
|
||||
if !ok {
|
||||
return rabbitmq.Permanent(fmt.Errorf("notification worker: unexpected queue %q", w.queue))
|
||||
}
|
||||
|
||||
if notif == nil {
|
||||
return nil
|
||||
var envelope struct {
|
||||
Action string `json:"action"`
|
||||
}
|
||||
if err := w.db.WithContext(ctx).Create(notif).Error; err != nil {
|
||||
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
|
||||
}
|
||||
|
||||
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, ¬ification.Notification{
|
||||
RecipientID: authorID,
|
||||
SenderID: evt.UserID,
|
||||
Type: "like",
|
||||
TargetID: evt.VideoID,
|
||||
Content: "点赞了你的视频",
|
||||
}, evt.EventID)
|
||||
}
|
||||
|
||||
func (w *NotificationWorker) applyComment(ctx context.Context, body []byte) error {
|
||||
var evt rabbitmq.CommentEvent
|
||||
if err := json.Unmarshal(body, &evt); err != nil {
|
||||
return rabbitmq.Permanent(fmt.Errorf("notification worker: decode comment event: %w", err))
|
||||
}
|
||||
if evt.AuthorID == 0 || evt.VideoID == 0 {
|
||||
return rabbitmq.Permanent(fmt.Errorf("notification worker: invalid comment event author_id=%d video_id=%d", evt.AuthorID, evt.VideoID))
|
||||
}
|
||||
authorID, err := w.videoAuthorID(ctx, evt.VideoID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if authorID == 0 || authorID == evt.AuthorID {
|
||||
return nil
|
||||
}
|
||||
return w.persist(ctx, ¬ification.Notification{
|
||||
RecipientID: authorID,
|
||||
SenderID: evt.AuthorID,
|
||||
Type: "comment",
|
||||
TargetID: evt.VideoID,
|
||||
Content: "评论了你的视频",
|
||||
}, evt.EventID)
|
||||
}
|
||||
|
||||
func (w *NotificationWorker) applySocial(ctx context.Context, body []byte) error {
|
||||
var evt rabbitmq.SocialEvent
|
||||
if err := json.Unmarshal(body, &evt); err != nil {
|
||||
return rabbitmq.Permanent(fmt.Errorf("notification worker: decode social event: %w", err))
|
||||
}
|
||||
if evt.FollowerID == 0 || evt.VloggerID == 0 {
|
||||
return rabbitmq.Permanent(fmt.Errorf("notification worker: invalid social event follower_id=%d vlogger_id=%d", evt.FollowerID, evt.VloggerID))
|
||||
}
|
||||
return w.persist(ctx, ¬ification.Notification{
|
||||
RecipientID: evt.VloggerID,
|
||||
SenderID: evt.FollowerID,
|
||||
Type: "follow",
|
||||
TargetID: evt.FollowerID,
|
||||
Content: "关注了你",
|
||||
}, evt.EventID)
|
||||
}
|
||||
|
||||
func (w *NotificationWorker) videoAuthorID(ctx context.Context, videoID uint) (uint, error) {
|
||||
var authorID uint
|
||||
err := w.db.WithContext(ctx).
|
||||
Table("videos").
|
||||
Where("id = ?", videoID).
|
||||
Select("author_id").
|
||||
Scan(&authorID).Error
|
||||
return authorID, err
|
||||
}
|
||||
|
||||
func (w *NotificationWorker) persist(ctx context.Context, notif *notification.Notification, eventID string) error {
|
||||
// event_id 取不到时留空,此时该通知不参与去重。
|
||||
notif.DedupeKey = nilIfEmpty(video.NotificationDedupeKey(notif.Type, eventID, notif.RecipientID))
|
||||
|
||||
res := w.db.WithContext(ctx).
|
||||
Clauses(clause.OnConflict{DoNothing: true}).
|
||||
Create(notif)
|
||||
if res.Error != nil {
|
||||
return res.Error
|
||||
}
|
||||
if res.RowsAffected == 0 {
|
||||
// 这条意图的通知已经写过:不重复推送,也不修改既有行。
|
||||
key := ""
|
||||
if notif.DedupeKey != nil {
|
||||
key = *notif.DedupeKey
|
||||
}
|
||||
log.Printf("notification worker: dedupe=hit type=%s recipient=%d dedupe_key=%s", notif.Type, notif.RecipientID, key)
|
||||
return nil
|
||||
}
|
||||
if w.hub != nil {
|
||||
w.hub.Push(notif.RecipientID, notif)
|
||||
}
|
||||
|
||||
184
backend/internal/worker/notificationworker_integration_test.go
Normal file
184
backend/internal/worker/notificationworker_integration_test.go
Normal file
@@ -0,0 +1,184 @@
|
||||
//go:build integration
|
||||
|
||||
package worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"feedsystem_video_go/internal/middleware/rabbitmq"
|
||||
"feedsystem_video_go/internal/notification"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
)
|
||||
|
||||
// 通知去重的正确性完全落在数据库唯一索引上,因此只能在真实 MySQL 上验证:
|
||||
//
|
||||
// MYSQL_TEST_DSN='root:123456@tcp(127.0.0.1:3306)/feedsystem_test?charset=utf8mb4&parseTime=True&loc=Local' \
|
||||
// go test -tags integration -count=1 ./internal/worker/
|
||||
|
||||
type fakeHub struct {
|
||||
mu sync.Mutex
|
||||
pushes []*notification.Notification
|
||||
}
|
||||
|
||||
func (h *fakeHub) Push(userID uint, n *notification.Notification) {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
h.pushes = append(h.pushes, n)
|
||||
}
|
||||
|
||||
func (h *fakeHub) count() int {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
return len(h.pushes)
|
||||
}
|
||||
|
||||
type testVideoRow struct {
|
||||
ID uint `gorm:"primaryKey"`
|
||||
AuthorID uint `gorm:"column:author_id;not null"`
|
||||
}
|
||||
|
||||
func (testVideoRow) TableName() string { return "videos" }
|
||||
|
||||
func newWorkerTestDB(t *testing.T) *gorm.DB {
|
||||
t.Helper()
|
||||
dsn := os.Getenv("MYSQL_TEST_DSN")
|
||||
if dsn == "" {
|
||||
t.Skip("MYSQL_TEST_DSN 未设置:需要真实 MySQL(见本文件顶部注释)")
|
||||
}
|
||||
if strings.Contains(dsn, "clientFoundRows") {
|
||||
t.Fatalf("测试 DSN 不能带 clientFoundRows:它会让 RowsAffected 判重失效")
|
||||
}
|
||||
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
|
||||
Logger: logger.Default.LogMode(logger.Silent),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("connect mysql: %v", err)
|
||||
}
|
||||
if err := db.Migrator().DropTable(¬ification.Notification{}, &testVideoRow{}); err != nil {
|
||||
t.Fatalf("drop tables: %v", err)
|
||||
}
|
||||
if err := db.AutoMigrate(&testVideoRow{}, ¬ification.Notification{}); err != nil {
|
||||
t.Fatalf("migrate: %v", err)
|
||||
}
|
||||
return db
|
||||
}
|
||||
|
||||
func likeDelivery(t *testing.T, eventID string, userID, videoID uint) amqp.Delivery {
|
||||
t.Helper()
|
||||
body, err := json.Marshal(rabbitmq.LikeEvent{
|
||||
EventID: eventID,
|
||||
Action: "like",
|
||||
UserID: userID,
|
||||
VideoID: videoID,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("marshal event: %v", err)
|
||||
}
|
||||
return amqp.Delivery{Body: body, RoutingKey: rabbitmq.LikeLikeRK}
|
||||
}
|
||||
|
||||
// 同一条事件被投递两次(MQ 假失败、重试、重放都会产生这种情形),
|
||||
// 收件人只能看到一条通知、只收到一次 SSE 推送。
|
||||
func TestNotificationWorker_DuplicateDeliveryWritesOneRow(t *testing.T) {
|
||||
db := newWorkerTestDB(t)
|
||||
if err := db.Create(&testVideoRow{ID: 10, AuthorID: 2}).Error; err != nil {
|
||||
t.Fatalf("seed video: %v", err)
|
||||
}
|
||||
hub := &fakeHub{}
|
||||
w := NewNotificationWorker(nil, nil, db, rabbitmq.NotificationLikeQueue, hub)
|
||||
ctx := context.Background()
|
||||
|
||||
d := likeDelivery(t, "intent-0009", 1, 10)
|
||||
for i := 0; i < 3; i++ {
|
||||
if err := w.process(ctx, d); err != nil {
|
||||
t.Fatalf("第 %d 次处理: %v", i+1, err)
|
||||
}
|
||||
}
|
||||
|
||||
var count int64
|
||||
db.Model(¬ification.Notification{}).Count(&count)
|
||||
if count != 1 {
|
||||
t.Fatalf("notifications 行数 = %d, want 1(同一意图键必须去重)", count)
|
||||
}
|
||||
if got := hub.count(); got != 1 {
|
||||
t.Fatalf("SSE 推送次数 = %d, want 1(只有真的插入才推送)", got)
|
||||
}
|
||||
}
|
||||
|
||||
// 没有 event_id 的事件(旧版本发布的消息,或事件体里没有该字段)
|
||||
// 不参与判重:宁可多一条通知,也不要因为"键为空"把不同事件判成同一条。
|
||||
func TestNotificationWorker_MissingEventIDDoesNotDedupe(t *testing.T) {
|
||||
db := newWorkerTestDB(t)
|
||||
if err := db.Create(&testVideoRow{ID: 11, AuthorID: 2}).Error; err != nil {
|
||||
t.Fatalf("seed video: %v", err)
|
||||
}
|
||||
hub := &fakeHub{}
|
||||
w := NewNotificationWorker(nil, nil, db, rabbitmq.NotificationLikeQueue, hub)
|
||||
ctx := context.Background()
|
||||
|
||||
d := likeDelivery(t, "", 1, 11)
|
||||
for i := 0; i < 2; i++ {
|
||||
if err := w.process(ctx, d); err != nil {
|
||||
t.Fatalf("第 %d 次处理: %v", i+1, err)
|
||||
}
|
||||
}
|
||||
|
||||
var count int64
|
||||
db.Model(¬ification.Notification{}).Count(&count)
|
||||
if count != 2 {
|
||||
t.Fatalf("notifications 行数 = %d, want 2(无意图键时不判重)", count)
|
||||
}
|
||||
}
|
||||
|
||||
// 自己给自己的视频点赞不该产生通知,且不得写行。
|
||||
func TestNotificationWorker_SelfActionWritesNothing(t *testing.T) {
|
||||
db := newWorkerTestDB(t)
|
||||
if err := db.Create(&testVideoRow{ID: 12, AuthorID: 7}).Error; err != nil {
|
||||
t.Fatalf("seed video: %v", err)
|
||||
}
|
||||
w := NewNotificationWorker(nil, nil, db, rabbitmq.NotificationLikeQueue, &fakeHub{})
|
||||
ctx := context.Background()
|
||||
|
||||
if err := w.process(ctx, likeDelivery(t, "intent-0010", 7, 12)); err != nil {
|
||||
t.Fatalf("process: %v", err)
|
||||
}
|
||||
var count int64
|
||||
db.Model(¬ification.Notification{}).Count(&count)
|
||||
if count != 0 {
|
||||
t.Fatalf("notifications 行数 = %d, want 0", count)
|
||||
}
|
||||
}
|
||||
|
||||
// 重试队列回源时会把 routing key 改写成队列名(`like.like` → `notification.like`)。
|
||||
// 这个用例用改写后的 routing key 复现该场景,断言仍然正常写入:
|
||||
// 它守护的是"分派依据是队列 + body.action,不是 routing key"。
|
||||
func TestNotificationWorker_RewrittenRoutingKeyStillWorks(t *testing.T) {
|
||||
db := newWorkerTestDB(t)
|
||||
if err := db.Create(&testVideoRow{ID: 13, AuthorID: 2}).Error; err != nil {
|
||||
t.Fatalf("seed video: %v", err)
|
||||
}
|
||||
hub := &fakeHub{}
|
||||
w := NewNotificationWorker(nil, nil, db, rabbitmq.NotificationLikeQueue, hub)
|
||||
|
||||
d := likeDelivery(t, "intent-0011", 1, 13)
|
||||
d.RoutingKey = rabbitmq.NotificationLikeQueue // 第二次投递时的 routing key
|
||||
|
||||
if err := w.process(context.Background(), d); err != nil {
|
||||
t.Fatalf("process: %v", err)
|
||||
}
|
||||
|
||||
var count int64
|
||||
db.Model(¬ification.Notification{}).Count(&count)
|
||||
if count != 1 {
|
||||
t.Fatalf("notifications 行数 = %d, want 1(routing key 被改写不应影响分派)", count)
|
||||
}
|
||||
}
|
||||
66
backend/internal/worker/notificationworker_test.go
Normal file
66
backend/internal/worker/notificationworker_test.go
Normal file
@@ -0,0 +1,66 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"feedsystem_video_go/internal/middleware/rabbitmq"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
)
|
||||
|
||||
// 分派依据必须是队列 + body 里的 action。
|
||||
//
|
||||
// 重试链路回源时会把 routing key 改写成队列名(`like.like` → `notification.like`)。
|
||||
// 若按 routing key 判断事件类型,第二次投递就会变成"未知事件"并被立即停泊,
|
||||
// 重试预算白丢,而用户只会觉得"通知丢了"。
|
||||
//
|
||||
// 这些用例停在 Permanent 判断之前,不需要数据库。
|
||||
func TestNotificationWorker_RejectsWrongActionAsPermanent(t *testing.T) {
|
||||
w := NewNotificationWorker(nil, nil, nil, rabbitmq.NotificationLikeQueue, nil)
|
||||
d := amqp.Delivery{Body: []byte(`{"action":"follow"}`), RoutingKey: rabbitmq.LikeLikeRK}
|
||||
|
||||
err := w.process(context.Background(), d)
|
||||
if err == nil {
|
||||
t.Fatal("队列 notification.like 收到 action=follow 时必须报错,否则会被当成正常事件处理")
|
||||
}
|
||||
if !rabbitmq.IsPermanent(err) {
|
||||
t.Fatalf("err = %v, want permanent(坏消息重投多少次都是坏的)", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNotificationWorker_RejectsUnknownQueueAsPermanent(t *testing.T) {
|
||||
w := NewNotificationWorker(nil, nil, nil, "some.other.queue", nil)
|
||||
d := amqp.Delivery{Body: []byte(`{"action":"like"}`)}
|
||||
|
||||
err := w.process(context.Background(), d)
|
||||
if err == nil {
|
||||
t.Fatal("未登记的队列必须报错:继续处理会用错的通知类型写库")
|
||||
}
|
||||
if !rabbitmq.IsPermanent(err) {
|
||||
t.Fatalf("err = %v, want permanent", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNotificationWorker_RejectsEmptyBodyAsPermanent(t *testing.T) {
|
||||
w := NewNotificationWorker(nil, nil, nil, rabbitmq.NotificationLikeQueue, nil)
|
||||
|
||||
err := w.process(context.Background(), amqp.Delivery{})
|
||||
if err == nil {
|
||||
t.Fatal("空消息体必须报错")
|
||||
}
|
||||
if !rabbitmq.IsPermanent(err) {
|
||||
t.Fatalf("err = %v, want permanent", err)
|
||||
}
|
||||
}
|
||||
|
||||
// 空消息体与非法 action 都是"不可重试"的,但要确认判定顺序:
|
||||
// 队列未知时先报队列错误,避免把配置问题误判成消息问题。
|
||||
func TestNotificationWorker_UnknownQueueCheckedBeforeAction(t *testing.T) {
|
||||
w := NewNotificationWorker(nil, nil, nil, "some.other.queue", nil)
|
||||
|
||||
err := w.process(context.Background(), amqp.Delivery{Body: []byte(`not json`)})
|
||||
if err == nil || !rabbitmq.IsPermanent(err) {
|
||||
t.Fatalf("err = %v, want permanent", err)
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package worker
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"feedsystem_video_go/internal/middleware/rabbitmq"
|
||||
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||||
"feedsystem_video_go/internal/video"
|
||||
@@ -10,46 +11,77 @@ import (
|
||||
"log"
|
||||
"time"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
oredis "github.com/redis/go-redis/v9"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// 轮询器,轮询数据库中的 outbox 表,获取待投递的消息,投递到 MQ 中
|
||||
func StartOutboxPoller(db *gorm.DB, tmq *rabbitmq.TimelineMQ) {
|
||||
// 断连期间 Publish 会阻塞等待重连,超时让它失败并进入下一轮轮询。
|
||||
const outboxPublishTimeout = 5 * time.Second
|
||||
|
||||
const (
|
||||
// 空批次后的等待时间。
|
||||
outboxPollInterval = time.Second
|
||||
outboxBatchSize = 100
|
||||
)
|
||||
|
||||
// StartOutboxPoller 阻塞轮询 outbox 表;调用方负责起 goroutine。
|
||||
func StartOutboxPoller(ctx context.Context, db *gorm.DB, tmq *rabbitmq.TimelineMQ) {
|
||||
if db == nil || tmq == nil {
|
||||
log.Printf("Outbox poller disabled: timeline mq is not initialized")
|
||||
return
|
||||
}
|
||||
|
||||
go func() {
|
||||
for {
|
||||
var messages []video.OutboxMsg
|
||||
for ctx.Err() == nil {
|
||||
var messages []video.OutboxMsg
|
||||
|
||||
err := db.Where("status = ?", "pending").Order("create_time ASC").Limit(100).Find(&messages).Error
|
||||
|
||||
if err != nil || len(messages) == 0 {
|
||||
time.Sleep(1 * time.Second)
|
||||
continue
|
||||
err := db.Where("status = ?", "pending").Order("create_time ASC").Limit(outboxBatchSize).Find(&messages).Error
|
||||
if err != nil {
|
||||
log.Printf("outbox 轮询失败: %v", err)
|
||||
if !waitOrDone(ctx, outboxPollInterval) {
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
if len(messages) == 0 {
|
||||
if !waitOrDone(ctx, outboxPollInterval) {
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
for _, msg := range messages {
|
||||
err := tmq.PublishVideo(context.Background(), msg.VideoID, msg.CreateTime)
|
||||
for _, msg := range messages {
|
||||
// 超时派生自 poller 的 ctx:进程退出时不再为一条消息多等 5 秒。
|
||||
pubCtx, cancel := context.WithTimeout(ctx, outboxPublishTimeout)
|
||||
err := tmq.PublishVideo(pubCtx, msg.VideoID, msg.CreateTime)
|
||||
cancel()
|
||||
|
||||
if err == nil {
|
||||
if err := db.Delete(&msg).Error; err != nil {
|
||||
log.Printf("删除 outbox 消息失败: id=%d, err=%v", msg.ID, err)
|
||||
}
|
||||
} else {
|
||||
log.Printf("投递MQ失败: VideoID: %d, err: %v", msg.VideoID, err)
|
||||
if err == nil {
|
||||
if err := db.Delete(&msg).Error; err != nil {
|
||||
log.Printf("删除 outbox 消息失败: id=%d, err=%v", msg.ID, err)
|
||||
}
|
||||
} else {
|
||||
log.Printf("投递MQ失败: VideoID: %d, err: %v", msg.VideoID, err)
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
}
|
||||
|
||||
// 消费者,消费 MQ 中的消息,写入 Redis 的 Zset 中
|
||||
func StartConsumer(tmq *rabbitmq.TimelineMQ, queueName string, redisClient *rediscache.Client, rmq *rabbitmq.RabbitMQ) {
|
||||
if tmq == nil || rmq == nil || rmq.Conn == nil {
|
||||
// waitOrDone 等待 d 到点;ctx 取消则提前返回 false。
|
||||
func waitOrDone(ctx context.Context, d time.Duration) bool {
|
||||
t := time.NewTimer(d)
|
||||
defer t.Stop()
|
||||
select {
|
||||
case <-t.C:
|
||||
return true
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// StartConsumer 阻塞消费 timeline 事件;调用方负责起 goroutine。
|
||||
func StartConsumer(ctx context.Context, rmq *rabbitmq.RabbitMQ, queueName string, redisClient *rediscache.Client) {
|
||||
if rmq == nil {
|
||||
log.Printf("Timeline consumer disabled: rabbitmq is not initialized")
|
||||
return
|
||||
}
|
||||
@@ -58,66 +90,51 @@ func StartConsumer(tmq *rabbitmq.TimelineMQ, queueName string, redisClient *redi
|
||||
return
|
||||
}
|
||||
|
||||
go func() {
|
||||
for {
|
||||
// 每次重连创建独立的 Channel,不与发布者共用
|
||||
ch, err := rmq.NewChannel()
|
||||
if err != nil {
|
||||
log.Printf("Timeline consumer: 创建 Channel 失败: %v, 5秒后重试", err)
|
||||
time.Sleep(5 * time.Second)
|
||||
continue
|
||||
}
|
||||
|
||||
// 设置当前 Channel 的 QoS(Quality of Service)参数,控制消息的预取数量和大小
|
||||
// prefetch count = 10 一次最多取10个消息, prefetch size = 0 不限制预取的字节大小, global = false Qos 设置只对当前 Channel 生效
|
||||
if err := ch.Qos(10, 0, false); err != nil {
|
||||
log.Printf("Timeline consumer: QoS 设置失败: %v", err)
|
||||
}
|
||||
|
||||
msgs, err := ch.Consume(queueName, "", false, false, false, false, nil)
|
||||
if err != nil {
|
||||
log.Printf("Timeline consumer: 注册消费失败: %v, 5秒后重试", err)
|
||||
ch.Close()
|
||||
time.Sleep(5 * time.Second)
|
||||
continue
|
||||
}
|
||||
|
||||
log.Printf("Timeline consumer 已启动, queue=%s", queueName)
|
||||
|
||||
for msg := range msgs {
|
||||
var event rabbitmq.TimelineEvent
|
||||
if err := json.Unmarshal(msg.Body, &event); err != nil {
|
||||
log.Printf("Timeline consumer: 反序列化失败: %v", err)
|
||||
msg.Ack(false)
|
||||
continue
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
|
||||
timelineKey := redisClient.Key("feed:global_timeline")
|
||||
err = redisClient.ZAdd(ctx, timelineKey, oredis.Z{
|
||||
Score: float64(event.CreateTime),
|
||||
Member: fmt.Sprintf("%d", event.VideoID),
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
log.Printf("Timeline consumer: 写入Zset失败: %v", err)
|
||||
msg.Nack(false, true)
|
||||
cancel()
|
||||
continue
|
||||
}
|
||||
|
||||
if err := redisClient.ZRemRangeByRank(ctx, timelineKey, 0, -1001); err != nil {
|
||||
log.Printf("Timeline consumer: ZRem失败: %v", err)
|
||||
}
|
||||
|
||||
msg.Ack(false)
|
||||
cancel()
|
||||
}
|
||||
|
||||
// msgs channel 关闭说明 AMQP Channel 断开,关闭并重连
|
||||
ch.Close()
|
||||
log.Printf("Timeline consumer: Channel 断开, 5秒后重连...")
|
||||
time.Sleep(5 * time.Second)
|
||||
rabbitmq.RunConsumer(ctx, rmq, "TimelineConsumer", 10, func(ch *amqp.Channel) error {
|
||||
msgs, err := ch.Consume(queueName, "", false, false, false, false, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case msg, ok := <-msgs:
|
||||
if !ok {
|
||||
return errors.New("deliveries channel closed")
|
||||
}
|
||||
handleTimelineMessage(ctx, redisClient, msg)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// handleTimelineMessage 把一条 timeline 事件写入 Redis ZSet(幂等:member 为 VideoID)。
|
||||
func handleTimelineMessage(ctx context.Context, redisClient *rediscache.Client, msg amqp.Delivery) {
|
||||
var event rabbitmq.TimelineEvent
|
||||
if err := json.Unmarshal(msg.Body, &event); err != nil {
|
||||
log.Printf("Timeline consumer: 反序列化失败: %v", err)
|
||||
_ = msg.Ack(false)
|
||||
return
|
||||
}
|
||||
|
||||
opCtx, cancel := context.WithTimeout(ctx, 500*time.Millisecond)
|
||||
defer cancel()
|
||||
|
||||
timelineKey := redisClient.Key("feed:global_timeline")
|
||||
err := redisClient.ZAdd(opCtx, timelineKey, oredis.Z{
|
||||
Score: float64(event.CreateTime),
|
||||
Member: fmt.Sprintf("%d", event.VideoID),
|
||||
})
|
||||
if err != nil {
|
||||
log.Printf("Timeline consumer: 写入Zset失败: %v", err)
|
||||
_ = msg.Nack(false, true)
|
||||
return
|
||||
}
|
||||
|
||||
if err := redisClient.ZRemRangeByRank(opCtx, timelineKey, 0, -1001); err != nil {
|
||||
log.Printf("Timeline consumer: ZRem失败: %v", err)
|
||||
}
|
||||
|
||||
_ = msg.Ack(false)
|
||||
}
|
||||
|
||||
33
backend/internal/worker/outboxworker_test.go
Normal file
33
backend/internal/worker/outboxworker_test.go
Normal file
@@ -0,0 +1,33 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// 轮询间隔必须可被 ctx 打断:否则 Worker 收到 SIGTERM 后还要把最后一轮空等走完。
|
||||
func TestWaitOrDone(t *testing.T) {
|
||||
t.Run("ctx 已取消时立即返回 false", func(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
|
||||
start := time.Now()
|
||||
if waitOrDone(ctx, time.Minute) {
|
||||
t.Fatal("ctx 已取消时不应报告等待完成")
|
||||
}
|
||||
if elapsed := time.Since(start); elapsed > time.Second {
|
||||
t.Fatalf("ctx 已取消仍等待了 %v", elapsed)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("ctx 未取消时等满间隔返回 true", func(t *testing.T) {
|
||||
start := time.Now()
|
||||
if !waitOrDone(context.Background(), 20*time.Millisecond) {
|
||||
t.Fatal("ctx 未取消时应报告等待完成")
|
||||
}
|
||||
if elapsed := time.Since(start); elapsed < 20*time.Millisecond {
|
||||
t.Fatalf("提前返回:%v", elapsed)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"feedsystem_video_go/internal/middleware/rabbitmq"
|
||||
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||||
"feedsystem_video_go/internal/video"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
)
|
||||
|
||||
type PopularityWorker struct {
|
||||
ch *amqp.Channel
|
||||
cache *rediscache.Client
|
||||
queue string
|
||||
}
|
||||
|
||||
func NewPopularityWorker(ch *amqp.Channel, cache *rediscache.Client, queue string) *PopularityWorker {
|
||||
return &PopularityWorker{ch: ch, cache: cache, queue: queue}
|
||||
}
|
||||
|
||||
func (w *PopularityWorker) Run(ctx context.Context) error {
|
||||
if w == nil || w.ch == nil || w.cache == nil {
|
||||
return errors.New("popularity worker is not initialized")
|
||||
}
|
||||
if w.queue == "" {
|
||||
return errors.New("queue is required")
|
||||
}
|
||||
|
||||
deliveries, err := w.ch.Consume(
|
||||
w.queue,
|
||||
"",
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
nil,
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case d, ok := <-deliveries:
|
||||
if !ok {
|
||||
return errors.New("deliveries channel closed")
|
||||
}
|
||||
w.handleDelivery(ctx, d)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (w *PopularityWorker) handleDelivery(ctx context.Context, d amqp.Delivery) {
|
||||
const maxRetries = 3
|
||||
for i := 0; i <= maxRetries; i++ {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
_ = d.Nack(false, true)
|
||||
return
|
||||
default:
|
||||
}
|
||||
if err := w.process(ctx, d.Body); err != nil {
|
||||
if i >= maxRetries {
|
||||
log.Printf("popularity worker: 重试 %d 次后仍失败, 丢弃: %v", maxRetries, err)
|
||||
_ = d.Ack(false)
|
||||
return
|
||||
}
|
||||
wait := time.Duration(1<<uint(i)) * time.Second
|
||||
log.Printf("popularity worker: 处理失败, %v 后重试 (%d/%d): %v", wait, i+1, maxRetries, err)
|
||||
time.Sleep(wait)
|
||||
continue
|
||||
}
|
||||
_ = d.Ack(false)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (w *PopularityWorker) process(ctx context.Context, body []byte) error {
|
||||
var evt rabbitmq.PopularityEvent
|
||||
if err := json.Unmarshal(body, &evt); err != nil {
|
||||
return nil
|
||||
}
|
||||
if evt.VideoID == 0 || evt.Change == 0 {
|
||||
return nil
|
||||
}
|
||||
video.UpdatePopularityCache(ctx, w.cache, evt.VideoID, evt.Change)
|
||||
return nil
|
||||
}
|
||||
@@ -1,117 +0,0 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"feedsystem_video_go/internal/middleware/rabbitmq"
|
||||
"feedsystem_video_go/internal/social"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/go-sql-driver/mysql"
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
)
|
||||
|
||||
type SocialWorker struct {
|
||||
ch *amqp.Channel
|
||||
repo *social.SocialRepository
|
||||
queue string
|
||||
}
|
||||
|
||||
func NewSocialWorker(ch *amqp.Channel, repo *social.SocialRepository, queue string) *SocialWorker {
|
||||
return &SocialWorker{ch: ch, repo: repo, queue: queue}
|
||||
}
|
||||
|
||||
func (w *SocialWorker) Run(ctx context.Context) error {
|
||||
if w == nil || w.ch == nil || w.repo == nil {
|
||||
return errors.New("social worker is not initialized")
|
||||
}
|
||||
if w.queue == "" {
|
||||
return errors.New("queue is required")
|
||||
}
|
||||
|
||||
deliveries, err := w.ch.Consume(
|
||||
w.queue,
|
||||
"",
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
nil,
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case d, ok := <-deliveries:
|
||||
if !ok {
|
||||
return errors.New("deliveries channel closed")
|
||||
}
|
||||
w.handleDelivery(ctx, d)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (w *SocialWorker) handleDelivery(ctx context.Context, d amqp.Delivery) {
|
||||
const maxRetries = 3
|
||||
for i := 0; i <= maxRetries; i++ {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
_ = d.Nack(false, true)
|
||||
return
|
||||
default:
|
||||
}
|
||||
if err := w.process(ctx, d.Body); err != nil {
|
||||
if i >= maxRetries {
|
||||
log.Printf("social worker: 重试 %d 次后仍失败, 丢弃: %v", maxRetries, err)
|
||||
_ = d.Ack(false)
|
||||
return
|
||||
}
|
||||
wait := time.Duration(1<<uint(i)) * time.Second
|
||||
log.Printf("social worker: 处理失败, %v 后重试 (%d/%d): %v", wait, i+1, maxRetries, err)
|
||||
time.Sleep(wait)
|
||||
continue
|
||||
}
|
||||
_ = d.Ack(false)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (w *SocialWorker) process(ctx context.Context, body []byte) error {
|
||||
var evt rabbitmq.SocialEvent
|
||||
if err := json.Unmarshal(body, &evt); err != nil {
|
||||
// 解析事件失败,直接丢弃
|
||||
return nil
|
||||
}
|
||||
if evt.FollowerID == 0 || evt.VloggerID == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
switch evt.Action {
|
||||
case "follow":
|
||||
err := w.repo.Follow(ctx, &social.Social{
|
||||
FollowerID: evt.FollowerID,
|
||||
VloggerID: evt.VloggerID,
|
||||
})
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
var mysqlErr *mysql.MySQLError
|
||||
if errors.As(err, &mysqlErr) && mysqlErr.Number == 1062 {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
case "unfollow":
|
||||
return w.repo.Unfollow(ctx, &social.Social{
|
||||
FollowerID: evt.FollowerID,
|
||||
VloggerID: evt.VloggerID,
|
||||
})
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -11,6 +12,7 @@ import (
|
||||
"time"
|
||||
|
||||
"feedsystem_video_go/internal/auth"
|
||||
"feedsystem_video_go/internal/notification"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
@@ -18,15 +20,21 @@ import (
|
||||
|
||||
type SSEHub struct {
|
||||
mu sync.RWMutex
|
||||
clients map[uint][]chan *Notification
|
||||
clients map[uint][]chan *notification.Notification
|
||||
db *gorm.DB
|
||||
done <-chan struct{}
|
||||
}
|
||||
|
||||
func NewSSEHub(db *gorm.DB) *SSEHub {
|
||||
return &SSEHub{clients: make(map[uint][]chan *Notification), db: db}
|
||||
// ctx 结束时 SSEHandler 主动断开:Shutdown 不取消在途请求,而 SSE 响应永不结束。
|
||||
func NewSSEHub(ctx context.Context, db *gorm.DB) *SSEHub {
|
||||
h := &SSEHub{clients: make(map[uint][]chan *notification.Notification), db: db}
|
||||
if ctx != nil {
|
||||
h.done = ctx.Done()
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
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]
|
||||
@@ -41,15 +49,15 @@ 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()
|
||||
return ch
|
||||
}
|
||||
|
||||
func (h *SSEHub) Unsubscribe(userID uint, ch chan *Notification) {
|
||||
func (h *SSEHub) Unsubscribe(userID uint, ch chan *notification.Notification) {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
chs := h.clients[userID]
|
||||
@@ -128,6 +136,8 @@ func (h *SSEHub) SSEHandler(c *gin.Context) {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-h.done:
|
||||
return
|
||||
case n, ok := <-ch:
|
||||
if !ok {
|
||||
return
|
||||
@@ -153,7 +163,7 @@ func (h *SSEHub) ListHandler(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
var notifications []Notification
|
||||
var notifications []notification.Notification
|
||||
if err := h.db.WithContext(c.Request.Context()).
|
||||
Where("recipient_id = ?", userID).
|
||||
Order("created_at desc").
|
||||
@@ -163,7 +173,7 @@ func (h *SSEHub) ListHandler(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
if notifications == nil {
|
||||
notifications = []Notification{}
|
||||
notifications = []notification.Notification{}
|
||||
}
|
||||
c.JSON(200, gin.H{"notifications": notifications})
|
||||
}
|
||||
@@ -185,9 +195,9 @@ func (h *SSEHub) MarkReadHandler(c *gin.Context) {
|
||||
|
||||
var err error
|
||||
if req.ID != nil {
|
||||
err = h.db.WithContext(c.Request.Context()).Model(&Notification{}).Where("id = ? AND recipient_id = ?", *req.ID, userID).Update("is_read", true).Error
|
||||
err = h.db.WithContext(c.Request.Context()).Model(¬ification.Notification{}).Where("id = ? AND recipient_id = ?", *req.ID, userID).Update("is_read", true).Error
|
||||
} else {
|
||||
err = h.db.WithContext(c.Request.Context()).Model(&Notification{}).Where("recipient_id = ?", userID).Update("is_read", true).Error
|
||||
err = h.db.WithContext(c.Request.Context()).Model(¬ification.Notification{}).Where("recipient_id = ?", userID).Update("is_read", true).Error
|
||||
}
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
@@ -204,7 +214,7 @@ func (h *SSEHub) UnreadCountHandler(c *gin.Context) {
|
||||
}
|
||||
|
||||
var count int64
|
||||
if err := h.db.WithContext(c.Request.Context()).Model(&Notification{}).Where("recipient_id = ? AND is_read = ?", userID, false).Count(&count).Error; err != nil {
|
||||
if err := h.db.WithContext(c.Request.Context()).Model(¬ification.Notification{}).Where("recipient_id = ? AND is_read = ?", userID, false).Count(&count).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
# 固定项目名:compose 的项目名默认取自工作目录,
|
||||
# 从 CI 临时目录部署会变成另一套 *_mysql_data 卷,看起来像“数据丢了”。
|
||||
name: vloop
|
||||
|
||||
services:
|
||||
mysql:
|
||||
image: mysql:8.0
|
||||
@@ -72,6 +76,9 @@ services:
|
||||
rabbitmq:
|
||||
condition: service_healthy
|
||||
healthcheck:
|
||||
# 刻意使用 /healthz(进程存活,恒 200)而不是 /readyz(依赖就绪,MQ 断连时为 503):
|
||||
# broker 故障期间 API 仍然可用(写路径降级为直写 MySQL),若此处改用 /readyz,
|
||||
# 编排会把健康实例反复判为不健康、陷入重启/摘除循环,把"异步能力降级"放大成"整站不可用"。
|
||||
test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:8080/healthz || exit 1"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
@@ -117,7 +124,9 @@ services:
|
||||
image: vloop-frontend:latest
|
||||
restart: always
|
||||
ports:
|
||||
- "127.0.0.1:9001:80"
|
||||
# 对外访问:http://goanchor.top:9000(可用 APP_PORT 覆盖)。
|
||||
# 若之后在 443 加反向代理,改成 "127.0.0.1:${APP_PORT:-9000}:80" 只监听回环。
|
||||
- "${APP_PORT:-9000}:80"
|
||||
depends_on:
|
||||
- backend
|
||||
healthcheck:
|
||||
|
||||
@@ -80,6 +80,9 @@ services:
|
||||
rabbitmq:
|
||||
condition: service_healthy
|
||||
healthcheck:
|
||||
# 刻意使用 /healthz(进程存活,恒 200)而不是 /readyz(依赖就绪,MQ 断连时为 503):
|
||||
# broker 故障期间 API 仍然可用(写路径降级为直写 MySQL),若此处改用 /readyz,
|
||||
# 编排会把健康实例反复判为不健康、造成重启/摘除循环,把"异步能力降级"放大成"整站不可用"。
|
||||
test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:8080/healthz || exit 1"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
884
docs/design/写路径幂等.md
Normal file
884
docs/design/写路径幂等.md
Normal file
@@ -0,0 +1,884 @@
|
||||
# 项目保证写路径幂等:全链路实现
|
||||
|
||||
本文只讲"当前代码如何做到只生效一次",按一次真实请求的顺序展开,逐层给出关键源码与取舍理由。
|
||||
|
||||
## 1. 写路径的重复是结构性的
|
||||
|
||||
点赞、评论走"先发消息,失败再直写数据库"。关注不同:服务层先写库,事件只做通知(P1-4)。两种路径上,重复都不是异常,而是常态:
|
||||
|
||||
| 重复来源 | 触发条件 | 是否可避免 |
|
||||
|---|---|---|
|
||||
| 发布返回错误但 broker 已收下 | 网络超时、channel 抖动、发布后进程崩溃 | 不可完全避免 |
|
||||
| 队列重复投递 | 消费端处理完但 Ack 丢失、重试队列回源 | 不可完全避免 |
|
||||
| 客户端重试 | 用户连点、请求超时后重发 | 不可完全避免 |
|
||||
| 直写与消费双写 | 发布失败 → 直写;消息其实也到了 | 由设计决定 |
|
||||
|
||||
前三种是分布式系统固有属性,第四种是"降级路径"的必然代价。关注没有第四条:它不依赖消息送达,重复由 `(follower_id, vlogger_id)` 的唯一索引裁决,`Follow` / `Unfollow` 直接返回本次是否真的写入。因此幂等不能寄希望于"只写一次",只能定义成:
|
||||
|
||||
> 同一次用户意图被执行任意多次,每个副作用的结果与执行一次相同。
|
||||
|
||||
副作用有三个,必须分别守住:评论行、视频热度、通知。
|
||||
|
||||
## 2. 核心概念:意图键
|
||||
|
||||
**一次用户动作 = 一个键。** 这个键要在四个地方存活:HTTP 请求、消息体、数据库行、通知去重键。任何一处丢失,对应的那层判重就失效。
|
||||
|
||||
### 2.1 生成:`NewIntentKey`
|
||||
|
||||
```go
|
||||
// backend/internal/video/idempotency.go
|
||||
func NewIntentKey() (string, error) {
|
||||
b := make([]byte, 16)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", fmt.Errorf("generate intent key: %w", err)
|
||||
}
|
||||
return hex.EncodeToString(b), nil
|
||||
}
|
||||
```
|
||||
|
||||
16 字节随机数编码成 32 个十六进制字符。三点说明:
|
||||
|
||||
- **不引 uuid 依赖。** 项目当前没有该依赖,`crypto/rand` + `hex` 已满足"不可预测且不碰撞"。
|
||||
- **不复用 `rabbitmq.newEventID`。** 它逻辑相同,但在包内私有;跨包导出会把 `video` 拖进 `rabbitmq → config` 的依赖链,为一个 8 行函数不值。
|
||||
- **长度上限钉在 64。** 与 `comments.idempotency_key VARCHAR(64)` 一致,避免"键能生成但列存不下"。
|
||||
|
||||
### 2.2 校验:`validateIntentKey`
|
||||
|
||||
规则:长度 8–64,字符集 `[0-9a-zA-Z_-]`。
|
||||
|
||||
```go
|
||||
const (
|
||||
MaxIntentKeyLen = 64
|
||||
minIntentKeyLen = 8
|
||||
intentKeyAlphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_"
|
||||
)
|
||||
```
|
||||
|
||||
四条约束各有原因:
|
||||
|
||||
| 约束 | 原因 |
|
||||
|---|---|
|
||||
| 最小 8 字符 | 挡住 `"1"`、`"a"` 这类极易碰撞的键;短键会让两个用户的提交意外合并 |
|
||||
| 排除 `:` | 通知去重键用 `:` 分段(`mention:<键>:<收件人>`),键里带 `:` 会让边界不可解析 |
|
||||
| 非法直接报错,不截断不替换 | 静默修正会造出"客户端以为去重了、服务端其实没有",比重复更难排查 |
|
||||
| 错误必须包 `apierror.ErrValidation` | `ClassifyHTTPStatus` 只对 `ErrValidation` 返回 400,裸 error 会落 500,把参数错误显示成服务端故障 |
|
||||
|
||||
最后一条容易写漏,写漏的表现是"用户传错 `request_id` 却收到 500",看起来像后端崩溃:
|
||||
|
||||
```go
|
||||
return fmt.Errorf("%w: request_id must be %d-%d characters",
|
||||
apierror.ErrValidation, minIntentKeyLen, MaxIntentKeyLen)
|
||||
```
|
||||
|
||||
### 2.3 解析:`ResolveIntentKey`
|
||||
|
||||
```go
|
||||
func ResolveIntentKey(raw *string) (string, error) {
|
||||
if raw == nil || strings.TrimSpace(*raw) == "" {
|
||||
return NewIntentKey()
|
||||
}
|
||||
key := strings.TrimSpace(*raw)
|
||||
if err := validateIntentKey(key); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return key, nil
|
||||
}
|
||||
```
|
||||
|
||||
三条分支对应三种客户端:
|
||||
|
||||
| 输入 | 结果 | 语义 |
|
||||
|---|---|---|
|
||||
| `nil` / 空白 | 生成新键 | 旧客户端;单次请求内仍然一致,但客户端侧的重试无法被识别 |
|
||||
| 合法值 | 原样返回 | 客户端重试携带同一个值 → 命中同一次意图 |
|
||||
| 非法值 | 返回 400 | 不猜测用户意图 |
|
||||
|
||||
### 2.4 一次评论请求里,键是怎么流转的
|
||||
|
||||
键不是"传到某一层就算完",它要横穿整条请求。下面按实际调用顺序展开。
|
||||
|
||||
**第 1 跳:HTTP 层把客户端的值放进实体。**
|
||||
|
||||
```go
|
||||
// backend/internal/video/comment_handler.go
|
||||
comment := &Comment{Username: user.Username, VideoID: req.VideoID, AuthorID: authorId, Content: req.Content}
|
||||
if req.RequestID != "" {
|
||||
requestID := req.RequestID
|
||||
comment.IdempotencyKey = &requestID
|
||||
}
|
||||
```
|
||||
|
||||
这一跳只做搬运,不校验、不生成:判断与生成统一放在服务层,避免两处规则漂移。
|
||||
|
||||
**第 2 跳:服务层解析,并把它写回实体。**
|
||||
|
||||
```go
|
||||
// backend/internal/video/comment_service.go — Publish
|
||||
key, err := ResolveIntentKey(comment.IdempotencyKey)
|
||||
if err != nil {
|
||||
return err // 非法 request_id 已包 apierror.ErrValidation,落 400
|
||||
}
|
||||
comment.IdempotencyKey = &key
|
||||
span := logIntent("comment.publish", key, comment.AuthorID, comment.VideoID)
|
||||
```
|
||||
|
||||
回写是这条链路的关键动作。`comment` 这个指针之后会被兜底写入直接使用;如果键只存在局部变量里,兜底路径拿到的就是 `nil`,它会退化成"每次都是新意图",唯一的幂等保护当场消失。
|
||||
|
||||
`span` 是同一意图的日志前缀,API 与 Worker 两侧都打印它:
|
||||
|
||||
```go
|
||||
func logIntent(stage, key string, authorID, videoID uint) string {
|
||||
return fmt.Sprintf("intent_key=%s stage=%s author_id=%d video_id=%d", key, stage, authorID, videoID)
|
||||
}
|
||||
```
|
||||
|
||||
线上排查时用 `grep intent_key=<K>` 可以把一次提交在 API 与 Worker 两侧的日志串起来。
|
||||
|
||||
**第 3 跳:事件携带同一个键。**
|
||||
|
||||
```go
|
||||
if err := s.commentMQ.Publish(ctx, rabbitmq.CommentEvent{
|
||||
EventID: key,
|
||||
Action: "publish",
|
||||
Username: comment.Username,
|
||||
VideoID: comment.VideoID,
|
||||
AuthorID: comment.AuthorID,
|
||||
Content: comment.Content,
|
||||
}); err == nil {
|
||||
commentEnqueued = true
|
||||
}
|
||||
```
|
||||
|
||||
发布函数本身不生成键,只在键为空时补一个随机值兜底:
|
||||
|
||||
```go
|
||||
// backend/internal/middleware/rabbitmq/commentMQ.go
|
||||
func (c *CommentMQ) publish(ctx context.Context, action, routingKey string, evt CommentEvent) error {
|
||||
...
|
||||
if evt.EventID == "" {
|
||||
id, err := newEventID(16)
|
||||
...
|
||||
evt.EventID = id
|
||||
}
|
||||
evt.Action = action
|
||||
evt.OccurredAt = time.Now().UTC()
|
||||
return c.mgr.PublishJSON(ctx, CommentExchange, routingKey, evt)
|
||||
}
|
||||
```
|
||||
|
||||
如果发布函数"总是自己生成",事件里的键与兜底写入的键必然不同,消费端再判重也无从命中。这个错误在没有业务测试覆盖时完全看不出来。
|
||||
|
||||
**第 4 跳:兜底写入用的是同一个实体、同一个键。**
|
||||
|
||||
```go
|
||||
if !commentEnqueued {
|
||||
created, err := s.store.CreateIdempotentWithPopularity(ctx, comment, 1)
|
||||
...
|
||||
log.Printf("%s fallback write dedupe=%s", span, dedupeLabel(created))
|
||||
}
|
||||
```
|
||||
|
||||
传的是 `comment` 本身,不是重新组装的结构体——键在第 2 跳已经写进它了。
|
||||
|
||||
**第 5 跳:数据库用唯一索引裁决,用"是否真的插入"门控副作用。**
|
||||
|
||||
```go
|
||||
// backend/internal/video/comment_repo.go
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
res := tx.Clauses(clause.OnConflict{DoNothing: true}).Create(c)
|
||||
if res.Error != nil {
|
||||
return res.Error
|
||||
}
|
||||
if res.RowsAffected == 0 {
|
||||
return nil
|
||||
}
|
||||
created = true
|
||||
if delta == 0 {
|
||||
return nil
|
||||
}
|
||||
return tx.Model(&Video{}).Where("id = ?", c.VideoID).
|
||||
UpdateColumn("popularity", gorm.Expr("GREATEST(popularity + ?, 0)", delta)).Error
|
||||
})
|
||||
```
|
||||
|
||||
`created` 是可观测的结果,不是假设。消费端拿到的是同一件事:
|
||||
|
||||
```go
|
||||
// backend/internal/worker/commentworker.go
|
||||
c := &video.Comment{Username: ..., VideoID: evt.VideoID, AuthorID: evt.AuthorID, Content: ...}
|
||||
if evt.EventID != "" {
|
||||
key := evt.EventID
|
||||
c.IdempotencyKey = &key
|
||||
}
|
||||
created, err := w.comments.CreateIdempotentWithPopularity(ctx, c, 1)
|
||||
if !created {
|
||||
log.Printf("comment worker: dedupe=hit event_id=%s video_id=%d author_id=%d",
|
||||
evt.EventID, evt.VideoID, evt.AuthorID)
|
||||
}
|
||||
```
|
||||
|
||||
API 直写过 → Worker 的插入返回 `created=false`,热度不重复;反过来也一样。谁先到都成立。
|
||||
|
||||
**第 6 跳:由同一个键派生出通知去重键。**
|
||||
|
||||
```go
|
||||
mentions = append(mentions, Mention{
|
||||
RecipientID: id,
|
||||
SenderID: comment.AuthorID,
|
||||
TargetID: comment.VideoID,
|
||||
Content: comment.Username + " 在评论中提到了你",
|
||||
DedupeKey: NotificationDedupeKey("mention", intentKey, id),
|
||||
})
|
||||
```
|
||||
|
||||
派生函数只做拼接,但有一条硬约束:
|
||||
|
||||
```go
|
||||
func NotificationDedupeKey(notifType, intentKey string, recipientID uint) string {
|
||||
if intentKey == "" {
|
||||
return ""
|
||||
}
|
||||
return fmt.Sprintf("%s:%s:%d", notifType, intentKey, recipientID)
|
||||
}
|
||||
```
|
||||
|
||||
空键返回空串,最终通过 `nilIfEmpty` 写成 `NULL`,不参与唯一索引——退化为"不去重",而不是让所有无键通知撞在同一个键上。
|
||||
|
||||
**最后一跳:把键回显给客户端。**
|
||||
|
||||
```go
|
||||
resp := gin.H{"message": "comment published successfully"}
|
||||
if comment.IdempotencyKey != nil {
|
||||
resp["request_id"] = *comment.IdempotencyKey
|
||||
}
|
||||
```
|
||||
|
||||
客户端不传 `request_id` 时,服务端在第 2 跳生成了一个并在这里回显。客户端只有拿到它,下一次重试才能声明"这还是同一次意图"。
|
||||
|
||||
载体对照:
|
||||
|
||||
| 跳 | 载体 | 字段 |
|
||||
|---|---|---|
|
||||
| HTTP 入参 | 请求体 | `request_id` |
|
||||
| 服务层实体 | `*Comment` | `IdempotencyKey` |
|
||||
| 评论事件 | 消息体 | `event_id` |
|
||||
| 兜底写入 | SQL 参数 | `comments.idempotency_key` |
|
||||
| 消费端 | 消息体 → 实体 | `event_id` → `IdempotencyKey` |
|
||||
| 通知 | 派生字符串 | `notifications.dedupe_key` |
|
||||
|
||||
中间任何一跳丢了这个值,后面的判重就全部失效——而失效的表现是"偶尔重复一条",不会报错。
|
||||
|
||||
## 3. 数据库层:唯一索引 + 单事务
|
||||
|
||||
### 3.1 字段与索引形状
|
||||
|
||||
```go
|
||||
type Comment struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
Username string `gorm:"index" json:"username"`
|
||||
VideoID uint `gorm:"index" json:"video_id"`
|
||||
AuthorID uint `gorm:"index;uniqueIndex:uk_comments_author_key,priority:1" json:"author_id"`
|
||||
Content string `gorm:"type:text" json:"content"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
|
||||
|
||||
IdempotencyKey *string `gorm:"column:idempotency_key;type:varchar(64);uniqueIndex:uk_comments_author_key,priority:2" json:"-"`
|
||||
}
|
||||
```
|
||||
|
||||
四个细节:
|
||||
|
||||
**① 唯一键是 `(author_id, idempotency_key)`,不是只有键。** 只按键唯一会让两个用户偶然拿到同一个 `request_id` 时互相顶掉;带上作者维度,判重范围恰好是"同一个人的同一次意图"。
|
||||
|
||||
**② 必须是 `*string`,不能是 `string`。** MySQL 唯一索引不约束 `NULL`,多个 `NULL` 可以共存;空串则会互相冲突。若用 `string` + `''`,所有"没带 `request_id`"的评论会撞在同一个键上,第二条正常评论就被判成重复。转空串为 `NULL` 的动作由 `nilIfEmpty` 统一负责。
|
||||
|
||||
**③ `json:"-"`。** 它是去重机制的内部标识,不属于用户可见数据;出现在 API 响应里只会诱使客户端把它当业务字段使用。
|
||||
|
||||
**④ `AuthorID` 上同时保留 `index` 与 `uniqueIndex`。** 复合索引 `(author_id, idempotency_key)` 的**最左前缀**能以 `author_id` 为条件服务查询,但方向只有一个:单列索引不能顶替复合索引。`index` 标签因此是冗余索引,暂时保留以免混入无收益的 schema 抖动。
|
||||
|
||||
### 3.2 写入:一条 SQL 决出胜负
|
||||
|
||||
```go
|
||||
func (r *CommentRepository) CreateIdempotentWithPopularity(ctx context.Context, c *Comment, delta int64) (bool, error) {
|
||||
var created bool
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
res := tx.Clauses(clause.OnConflict{DoNothing: true}).Create(c)
|
||||
...
|
||||
})
|
||||
```
|
||||
|
||||
为什么不"先 SELECT 再 INSERT":
|
||||
|
||||
- 两个 goroutine 之间永远有窗口,而这个窗口正好就是本设计要覆盖的场景(MQ 假失败后兜底直写 + worker 稍后消费)。
|
||||
- 唯一索引把"查"和"写"合并成一个原子动作,窗口不存在。
|
||||
|
||||
为什么不用 1062 判重:
|
||||
|
||||
- 报错与去重是两种语义。用报错表达去重会让每条正常路径都经过一次 error 分支。
|
||||
- 1062 也可能来自别的唯一键,需要再解析错误内容才能区分。
|
||||
- `OnConflict{DoNothing}` 直接给出 `RowsAffected`,它就是"我是否真的插入了"的答案。
|
||||
|
||||
### 3.3 为什么两个写必须同事务
|
||||
|
||||
```go
|
||||
if res.RowsAffected == 0 {
|
||||
return nil
|
||||
}
|
||||
created = true
|
||||
if delta == 0 {
|
||||
return nil
|
||||
}
|
||||
return tx.Model(&Video{}).Where("id = ?", c.VideoID).
|
||||
UpdateColumn("popularity", gorm.Expr("GREATEST(popularity + ?, 0)", delta)).Error
|
||||
```
|
||||
|
||||
如果拆成两条独立语句,它们之间崩溃就会留下"评论在、热度不在"的半成品:重投时评论命中唯一索引(`created=false`),热度永远不会补上。放进同一个事务后,两种结果只有"都在"或"都不在"。
|
||||
|
||||
`GREATEST(...,0)` 防止热度被减到负数——删除路径复用同一个函数时,负值会让排行榜出现异常条目。
|
||||
|
||||
### 3.4 三个容易踩的坑
|
||||
|
||||
**① `clientFoundRows` 会让判重静默失效。** 该选项让 MySQL 在"行未变化"时也报告影响 1 行,于是 `RowsAffected == 0` 这个判断永远不成立,重复写入被当成首次写入,热度变成 +2。项目 DSN(`internal/db/db.go`)刻意不开启它,`BuildDSN` 有一条单测钉住这一条:
|
||||
|
||||
```go
|
||||
func TestBuildDSN_DoesNotEnableClientFoundRows(t *testing.T)
|
||||
```
|
||||
|
||||
**② 冲突会消耗自增 ID。** `OnConflict DoNothing` 的插入在冲突时仍会推进 `AUTO_INCREMENT`,`comments.id` 因此出现空洞。这是可接受的代价:ID 只用于标识,不承诺连续。
|
||||
|
||||
**③ `RowsAffected` 是"这次调用插入了"的唯一可信来源。** 不要用"插入后再查一次是否存在"来判断,那会重新引入窗口,也让日志无法区分 `dedupe=hit` 与 `dedupe=miss`。
|
||||
|
||||
### 3.5 删除路径
|
||||
|
||||
```go
|
||||
func (r *CommentRepository) DeleteByID(ctx context.Context, id uint) (bool, error) {
|
||||
if id == 0 {
|
||||
return false, nil
|
||||
}
|
||||
res := r.db.WithContext(ctx).Delete(&Comment{}, id)
|
||||
if res.Error != nil {
|
||||
return false, res.Error
|
||||
}
|
||||
return res.RowsAffected > 0, nil
|
||||
}
|
||||
```
|
||||
|
||||
返回 `deleted bool` 的理由与新增对称:把热度回退当成无条件动作,同一条删除事件投递两次就会把热度减两次。`deleted` 是该回退的门控点。
|
||||
|
||||
## 4. 服务层:两条路径的编排
|
||||
|
||||
### 4.1 三个最小接口
|
||||
|
||||
```go
|
||||
type CommentPublisher interface {
|
||||
Publish(ctx context.Context, evt rabbitmq.CommentEvent) error
|
||||
Delete(ctx context.Context, commentID uint, intentKey string) error
|
||||
}
|
||||
|
||||
type PopularityPublisher interface {
|
||||
Update(ctx context.Context, videoID uint, change int64, intentKey string) error
|
||||
}
|
||||
|
||||
type videoExister interface {
|
||||
IsExist(ctx context.Context, id uint) (bool, error)
|
||||
}
|
||||
```
|
||||
|
||||
它们不是为了"面向接口编程",各有具体理由:
|
||||
|
||||
| 接口 | 存在理由 |
|
||||
|---|---|
|
||||
| `CommentPublisher` / `PopularityPublisher` | P0-4 的全部分支都取决于"这条消息到底发出去了没有",而这恰恰是真实 broker 最难稳定复现的状态。只有替身才能确定性触发"发布失败"分支 |
|
||||
| `videoExister` | 4 行代码,但 `Publish` 第一句就是 `IsExist`。删掉它,服务层所有用例都会退化成集成测试 |
|
||||
|
||||
`*VideoRepository` 天然满足 `videoExister`,因此 `router.go` 的构造代码不需要改。
|
||||
|
||||
**nil 接收者陷阱:** nil 指针装进接口后 `iface != nil` 依然为 true。所以真实实现必须在 nil 接收者上返回 error,否则"MQ 未初始化"会被当成"发布成功",直接跳过兜底。
|
||||
|
||||
### 4.2 `Publish` 的完整分支
|
||||
|
||||
```go
|
||||
func (s *CommentService) Publish(ctx context.Context, comment *Comment) error {
|
||||
if comment == nil {
|
||||
return errors.New("comment is nil")
|
||||
}
|
||||
comment.Content = strings.TrimSpace(comment.Content)
|
||||
comment.Username = strings.TrimSpace(comment.Username)
|
||||
if comment.Content == "" || comment.VideoID == 0 || comment.AuthorID == 0 {
|
||||
return fmt.Errorf("%w: video_id, author_id and content are required", apierror.ErrValidation)
|
||||
}
|
||||
|
||||
key, err := ResolveIntentKey(comment.IdempotencyKey)
|
||||
...
|
||||
```
|
||||
|
||||
**校验顺序:** 先 TrimSpace 再判空。让 `" "` 落进"内容为空"分支,而不是变成一条空白评论。
|
||||
|
||||
**闸 1:只有评论事件没入队时才直写。**
|
||||
|
||||
```go
|
||||
if !commentEnqueued {
|
||||
created, err := s.store.CreateIdempotentWithPopularity(ctx, comment, 1)
|
||||
if err != nil {
|
||||
return fmt.Errorf("fallback create comment: %w", err)
|
||||
}
|
||||
log.Printf("%s fallback write dedupe=%s", span, dedupeLabel(created))
|
||||
}
|
||||
```
|
||||
|
||||
入队成功时 API 不写库。这条规则是"避免稳定双写"的关键:如果入队成功也写,正常路径上每条评论都会写两次,幂等索引只能保证行不重复,却让热度与通知的判重长期处于"永远命中"的状态,反而掩盖真实问题。
|
||||
|
||||
**闸 2:热度兜底与评论事件彼此独立。**
|
||||
|
||||
```go
|
||||
if !popularityEnqueued {
|
||||
if err := UpdatePopularityCache(ctx, s.cache, comment.VideoID, 1, key); err != nil {
|
||||
log.Printf("%s hot cache update failed (degraded): %v", span, err)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
两条事件是两次独立发布,`commentEnqueued` 与 `popularityEnqueued` 必须分开判断。热度是"近似正确"的派生数据:更新失败只降级、不回滚评论,也不把一次成功发布变成 500。
|
||||
|
||||
**发布失败不等于没送达。** 短超时、channel 抖动都可能发生在 broker 已收下之后。因此不能根据 error 决定"要不要写",只能让两条路径共用同一个键,由唯一索引吸收重复。
|
||||
|
||||
**日志三元组。** 一次请求最多留下三条与判重有关的日志:
|
||||
|
||||
| 日志 | 含义 |
|
||||
|---|---|
|
||||
| `enqueue comment failed, fallback to direct write` | 走了兜底路径 |
|
||||
| `fallback write dedupe=miss` / `dedupe=hit` | 兜底时是否真的插入 |
|
||||
| `hot cache update failed (degraded)` | 热度未写,但请求成功 |
|
||||
|
||||
`dedupeLabel` 把 `created bool` 翻成 `miss`/`hit`:
|
||||
|
||||
```go
|
||||
func dedupeLabel(created bool) string {
|
||||
if created {
|
||||
return "miss"
|
||||
}
|
||||
return "hit"
|
||||
}
|
||||
```
|
||||
|
||||
### 4.3 `Delete`
|
||||
|
||||
```go
|
||||
key, keyErr := NewIntentKey()
|
||||
if keyErr != nil {
|
||||
key = ""
|
||||
}
|
||||
if err := s.commentMQ.Delete(ctx, commentID, key); err == nil {
|
||||
return nil
|
||||
}
|
||||
return s.store.DeleteComment(ctx, comment)
|
||||
```
|
||||
|
||||
- 删除事件的 `event_id` 也用意图键。删除的幂等不靠这个键,而是靠消费端的 `DeleteByID` 返回的 `deleted bool`——同一条删除事件投递两次,第二次是空操作。
|
||||
- 键生成失败时用空串:删除路径不依赖该键,不能因为随机数失败让用户删不掉评论。
|
||||
- 权限检查在删除之前:`comment.AuthorID != accountID` 返回 `apierror.ErrUnauthorized`。这个检查对两类重复都成立——重复投递的删除在消费端是空操作,重复点击删除在 API 侧是先查后删。
|
||||
|
||||
### 4.4 `GetAll`
|
||||
|
||||
先 `IsExist` 再查列表:视频不存在时返回 400,而不是返回空列表。空列表会让前端把"视频没了"显示成"还没有评论"。
|
||||
|
||||
## 5. 通知层
|
||||
|
||||
### 5.1 `notifyMentions` 的三段式
|
||||
|
||||
```go
|
||||
func (s *CommentService) notifyMentions(ctx context.Context, comment *Comment, intentKey string) {
|
||||
matches := mentionRegex.FindAllStringSubmatch(comment.Content, -1)
|
||||
...
|
||||
ids, err := s.store.FindAccountIDs(ctx, names)
|
||||
...
|
||||
if err := s.store.CreateMentions(ctx, mentions); err != nil {
|
||||
log.Printf("intent_key=%s stage=mention.create err=%v", intentKey, err)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**第一段:解析并去重用户名。**
|
||||
|
||||
```go
|
||||
for _, m := range matches {
|
||||
name := m[1]
|
||||
if name == comment.Username {
|
||||
continue
|
||||
}
|
||||
if _, dup := seen[name]; dup {
|
||||
continue
|
||||
}
|
||||
seen[name] = struct{}{}
|
||||
names = append(names, name)
|
||||
}
|
||||
```
|
||||
|
||||
跳过自己是必须的:`@自己` 不该产生通知。注意这里按 **username** 跳过,因为此刻还没有 ID;后面查回 ID 后还要再按 ID 跳过一次(见下)。
|
||||
|
||||
**第二段:一次批量查询。**
|
||||
|
||||
```go
|
||||
ids, err := s.store.FindAccountIDs(ctx, names)
|
||||
```
|
||||
|
||||
逐个 `SELECT` 会让"一条评论里 @ 了 5 个人"变成 5 次往返,而这段代码跑在用户请求路径上。不存在的用户名不出现在结果里,调用方按 map 的不存在分支跳过。
|
||||
|
||||
**第三段:批量写入,每条带去重键。**
|
||||
|
||||
```go
|
||||
for _, name := range names {
|
||||
id, ok := ids[name]
|
||||
if !ok || id == 0 {
|
||||
continue
|
||||
}
|
||||
if id == comment.AuthorID {
|
||||
continue
|
||||
}
|
||||
mentions = append(mentions, Mention{
|
||||
RecipientID: id,
|
||||
SenderID: comment.AuthorID,
|
||||
TargetID: comment.VideoID,
|
||||
Content: comment.Username + " 在评论中提到了你",
|
||||
DedupeKey: NotificationDedupeKey("mention", intentKey, id),
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
去重键必须含收件人。同一条评论的意图键只有一个,但它可能通知多个人;只按意图键去重会让第二个人收不到通知。
|
||||
|
||||
**失败只记日志。** 通知是派生副作用:写失败不改变"评论已发布"的结论,但必须留痕,否则"用户说没收到通知"无从排查。
|
||||
|
||||
### 5.2 `CreateMentions`:同批共享时间戳
|
||||
|
||||
```go
|
||||
func (r *CommentRepository) CreateMentions(ctx context.Context, mentions []Mention) error {
|
||||
if len(mentions) == 0 {
|
||||
return nil
|
||||
}
|
||||
now := time.Now()
|
||||
rows := make([]notification.Notification, 0, len(mentions))
|
||||
for _, m := range mentions {
|
||||
rows = append(rows, notification.Notification{
|
||||
...
|
||||
CreatedAt: now,
|
||||
DedupeKey: nilIfEmpty(m.DedupeKey),
|
||||
})
|
||||
}
|
||||
return r.db.WithContext(ctx).
|
||||
Clauses(clause.OnConflict{DoNothing: true}).
|
||||
Create(&rows).Error
|
||||
}
|
||||
```
|
||||
|
||||
显式写 `CreatedAt` 而不依赖 `autoCreateTime`:`autoCreateTime` 只在字段为零值时才生效,逐行插入会拿到毫秒级不同的时间;同一批行共享一个时间戳,便于按"同一次评论"检索。
|
||||
|
||||
### 5.3 通知实体为什么独立成包
|
||||
|
||||
`backend/internal/notification/entity.go` 是两个写入方共用的唯一实体定义:
|
||||
|
||||
```go
|
||||
package notification
|
||||
|
||||
type Notification struct {
|
||||
...
|
||||
DedupeKey *string `gorm:"column:dedupe_key;type:varchar(128);uniqueIndex:uk_notifications_dedupe" json:"-"`
|
||||
}
|
||||
|
||||
func (Notification) TableName() string { return "notifications" }
|
||||
```
|
||||
|
||||
依赖方向恒为 `worker → notification` 与 `video → notification`:
|
||||
|
||||
- `video` 不能 import `worker`(`worker` 已经 import `video`,会成环);
|
||||
- 各自维护一份结构体又会让列标签悄悄漂移,而漂移不会报错,只会在 `AutoMigrate` 时试图改动生产列类型。
|
||||
|
||||
`TableName()` 默认也是 `notifications`,显式写出是为了避免有人把类型改名后表名跟着漂移——这张表有两个写入方,表名漂移的代价远大于多写一行。
|
||||
|
||||
`DedupeKey` 用 `*string` 的原因与评论的 `IdempotencyKey` 相同:`NULL` 才不参与唯一约束。
|
||||
|
||||
### 5.4 通知消费端的幂等
|
||||
|
||||
去重键在写入时生效,推送必须跟着"是否真的插入"走:只有 `RowsAffected > 0` 才 `hub.Push`。否则列表里只有一条通知,用户却收到两次 SSE。
|
||||
|
||||
## 6. 热度层:Redis 占位
|
||||
|
||||
> **本节描述的是已被替换的设计。** P0-5 之后热度不再有独立的写路径:`hot:applied:<intentKey>` 占位与 `UpdatePopularityCache` 已随 `popularityMQ` 一起删除,热榜增量改由"事务是否真的写入了"驱动(`ApplyHotDelta`),失败不回滚、可由 DB 重建。当前设计见 [`热度排行榜.md`](热度排行榜.md)。本节保留为决策记录,说明"为什么当初要占位"以及"占位与副作用同生共死"这条约束从哪来。
|
||||
|
||||
### 6.1 为什么用占位而不是计数器
|
||||
|
||||
热度写在 Redis(分钟窗口 ZSET),没有唯一索引可用。做法是先抢占位、再执行副作用:
|
||||
|
||||
```go
|
||||
marker := ""
|
||||
if intentKey != "" {
|
||||
marker = cache.Key("hot:applied:%s", intentKey)
|
||||
claimed, err := cache.SetNX(opCtx, marker, []byte("1"), hotAppliedTTL)
|
||||
if err != nil {
|
||||
return fmt.Errorf("hot cache: claim intent %q: %w", intentKey, err)
|
||||
}
|
||||
if !claimed {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`!claimed` 是正常语义,不是错误:这条意图已经加过分,直接返回成功。
|
||||
|
||||
`SetNX` 的实现有两条约定:
|
||||
|
||||
```go
|
||||
func (c *Client) SetNX(ctx context.Context, key string, value []byte, ttl time.Duration) (bool, error) {
|
||||
if c == nil || c.rdb == nil {
|
||||
return false, errors.New("redis client not initialized")
|
||||
}
|
||||
return c.rdb.SetNX(ctx, key, value, ttl).Result()
|
||||
}
|
||||
```
|
||||
|
||||
- **key 由调用方拼好**,本方法不加前缀。加前缀的时机必须与其他原语一致,否则同一个逻辑键会因调用路径不同变成两个物理键。
|
||||
- **失败必须返回 error,不能返回 `(false, nil)`**。调用方用它判断"是否已生效",把 Redis 故障静默说成"已生效"会导致该次加分被永久跳过。
|
||||
|
||||
### 6.2 占位必须与副作用同生共死
|
||||
|
||||
```go
|
||||
if err := cache.ZincrBy(opCtx, windowKey, member, float64(change)); err != nil {
|
||||
if marker != "" {
|
||||
if delErr := cache.Del(context.Background(), marker); delErr != nil {
|
||||
log.Printf("hot cache: revoke intent marker %s failed: %v", marker, delErr)
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("hot cache: zincrby video=%d change=%d: %w", id, change, err)
|
||||
}
|
||||
```
|
||||
|
||||
ZINCRBY 失败而占位留下,这条增量就被永久跳过——用户只会觉得"热度不动了",比重复加分更难发现。因此失败分支必须撤销占位。
|
||||
|
||||
撤销本身用 `context.Background()`:`opCtx` 已经超时或即将超时,用它撤销会让"撤销"这一步自己失败。
|
||||
|
||||
撤销也失败时只记日志,不改变返回值。人工可以按 `hot:applied:<K>` 清理——这是"宁可留下明确证据,也不假装成功"。
|
||||
|
||||
### 6.3 超时的边界
|
||||
|
||||
```go
|
||||
hotOpTimeout = 100 * time.Millisecond
|
||||
```
|
||||
|
||||
它约束三次计数往返:`SetNX`、`ZINCRBY`、`EXPIRE`。
|
||||
|
||||
三次 `Del`(详情缓存、实体缓存、撤销占位)都用 `context.Background()`,不受它约束。如果把删缓存也算进预算,Redis 一抖动就会让整条热度消息失败并触发重投——而删缓存失败最多让详情页多陈旧一个缓存 TTL,不值得让消息重投。
|
||||
|
||||
`EXPIRE` 失败只记日志:窗口已经写好,缺过期时间只是键长期驻留,不影响正确性。
|
||||
|
||||
### 6.4 两个 TTL
|
||||
|
||||
| 常量 | 值 | 理由 |
|
||||
|---|---|---|
|
||||
| `hotAppliedTTL` | 2 小时 | 只需覆盖"同一事件的重复投递窗口"(重试 + 停泊重放 + 客户端重试);2 小时远大于该窗口,同时把键数量限制在可估算的量级 |
|
||||
| `hotWindowTTL` | 2 小时 | 热榜只需最近若干窗口,留 2 小时是为了跨窗口查询与事后核对仍然可读 |
|
||||
|
||||
### 6.5 空键为什么不去重
|
||||
|
||||
`intentKey == ""` 时整段占位逻辑被跳过,直接加分。调用方(点赞兜底)已经保证"只有事件发不出去才走到这里",在这里再去重会把真实增量吞掉。
|
||||
|
||||
## 7. 点赞路径:一个键喂两条事件
|
||||
|
||||
```go
|
||||
// 一条意图键同时喂给"点赞事件"和"热度事件"
|
||||
intentKey, err := NewIntentKey()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
likeEnqueued := false
|
||||
popEnqueued := false
|
||||
if s.likeMQ != nil {
|
||||
if err := s.likeMQ.Like(ctx, like.AccountID, like.VideoID, intentKey); err == nil {
|
||||
likeEnqueued = true
|
||||
}
|
||||
}
|
||||
if s.popularityMQ != nil {
|
||||
if err := s.popularityMQ.Update(ctx, like.VideoID, 1, intentKey); err == nil {
|
||||
popEnqueued = true
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
点赞行本身有 `idx_like_video_account` 唯一索引 + `LikeIgnoreDuplicate`,幂等由数据库保证;热度那条轨用同一个键去抢 Redis 占位。两条消息重复投递时,各自的消费端都能识别。
|
||||
|
||||
**兜底必须拆成两个独立判断:**
|
||||
|
||||
```go
|
||||
if !likeEnqueued {
|
||||
// 直写:插 likes + likes_count + popularity
|
||||
}
|
||||
if !popEnqueued {
|
||||
// 只更新热榜缓存
|
||||
}
|
||||
```
|
||||
|
||||
不能写成"两个都成功才 return,否则进同一个兜底"。旧写法的问题是:**点赞已入队 + 热度发布失败**时会再插一次 `likes`,撞 `idx_like_video_account` 的 1062,接口返回 500,而用户其实已经点赞成功;更糟的是 `IsLiked` 之后会告诉用户"你已经点过赞了"。
|
||||
|
||||
热度归热度,点赞归点赞——两条轨各自独立降级。
|
||||
|
||||
## 8. 消费端
|
||||
|
||||
### 8.1 事件字段到实体字段
|
||||
|
||||
```go
|
||||
if evt.EventID != "" {
|
||||
key := evt.EventID
|
||||
c.IdempotencyKey = &key
|
||||
}
|
||||
created, err := w.comments.CreateIdempotentWithPopularity(ctx, c, 1)
|
||||
```
|
||||
|
||||
`event_id` 就是"这次用户意图"的键。API 侧若已经兜底直写过,这次插入会命中唯一索引,`created=false`,热度不能再加一次。
|
||||
|
||||
`evt.EventID == ""` 时不设键:插入一行 `NULL` 键的评论,与旧行为一致,不会把不同事件判成同一条。
|
||||
|
||||
### 8.2 坏消息与空操作的区别
|
||||
|
||||
```go
|
||||
ok, err := w.videos.IsExist(ctx, evt.VideoID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
```
|
||||
|
||||
视频已被删除时返回 `nil`:没有可落评论的地方,但"处理完了"不等于"处理失败"。若返回 error,消息会在重试队列里空转直到停泊。
|
||||
|
||||
同一原则适用于:
|
||||
|
||||
| 情况 | 返回 | 原因 |
|
||||
|---|---|---|
|
||||
| 视频不存在 | `nil` | 处理完了 |
|
||||
| `event_id` 为空 | 正常插入 | 旧客户端行为 |
|
||||
| 重复删除(`deleted=false`) | `nil` | 空操作 |
|
||||
| 事件解析失败 / 字段非法 / 未知 action | `rabbitmq.Permanent` | 重投也不会成功 |
|
||||
|
||||
## 9. 失败矩阵
|
||||
|
||||
每种失败下,"评论 / 热度 / 通知"三者的结果:
|
||||
|
||||
| 失败点 | 评论 | 热度 | 通知 | 用户看到 |
|
||||
|---|---|---|---|---|
|
||||
| 正常 | 1 行(worker 写) | 队列 + Redis | 1 条 | 200 |
|
||||
| 评论发布失败 | 1 行(API 直写) | 队列 + Redis | 1 条 | 200 |
|
||||
| 评论发布失败 + 消息其实已入队 | 1 行(唯一索引吸收) | 只加一次 | 1 条 | 200 |
|
||||
| 热度发布失败 | 1 行 | 只 Redis(直写缓存) | 1 条 | 200 |
|
||||
| 两条都失败 | 1 行 | 只 Redis | 1 条 | 200 |
|
||||
| Redis 加分失败 | 1 行 | 0 | 1 条 | 200(热度降级) |
|
||||
| 客户端重试(同键) | 1 行 | 一次 | 1 条 | 200 |
|
||||
| 客户端重试(新键) | 2 行 | 两次 | 2 条 | 200(这是两次意图) |
|
||||
|
||||
最后一行是有意的:用户改了内容再发,就是新意图。用内容哈希去重会误伤"用户真的想再发一条"的合法行为。
|
||||
|
||||
## 10. 接口分层与测试
|
||||
|
||||
四个接口的规模:
|
||||
|
||||
| 接口 | 方法数 | 生产代码 | 测试替身 |
|
||||
|---|---|---|---|
|
||||
| `CommentStore` | 7 | 接口声明 | ~60 行 |
|
||||
| `CommentPublisher` | 2 | 接口声明 | ~15 行 |
|
||||
| `PopularityPublisher` | 1 | 接口声明 | ~10 行 |
|
||||
| `videoExister` | 1 | 接口声明 | ~5 行 |
|
||||
|
||||
`CommentStore` 的 7 个方法正好等于 `CommentService` 实际用到的 7 个,没有预留。
|
||||
|
||||
它们换来的覆盖:
|
||||
|
||||
- `TestCommentService_Publish_BothEnqueued_SkipsLocalWrite` —— 入队成功时不直写
|
||||
- `TestCommentService_Publish_CommentPublishFails_WritesLocallyWithIntentKey` —— 兜底与事件同键
|
||||
- `TestCommentService_Publish_PopularityPublishFails_AppliesHotCacheOnce`
|
||||
- `TestCommentService_Publish_RepeatSameIntent_DoesNotError`
|
||||
- `TestCommentService_Publish_InvalidRequestID` —— 400 而非 500
|
||||
- `TestCommentService_NotifyMentions_DedupeKeyBoundToIntent`
|
||||
|
||||
这些用例全部不需要 MySQL 与 broker。
|
||||
|
||||
## 11. 数据库约束的护栏
|
||||
|
||||
集成测试用真实 MySQL 验证"约束真的存在":
|
||||
|
||||
| 用例 | 断言 |
|
||||
|---|---|
|
||||
| `TestP0_4_DuplicateInsertReportsZeroRows` | 同键插两次:第二次 `created=false`,评论 1 行,popularity 1 |
|
||||
| `TestP0_4_ConcurrentInsertSingleRow` | 8 个 goroutine 并发:只有 1 个 `created=true` |
|
||||
| `TestP0_4_LegacyNullKeysCoexist` | 3 条 `NULL` 键共存 |
|
||||
| `TestP0_4_MentionNotificationDedupe` | 同 `DedupeKey` 写两次只有 1 行 |
|
||||
| `TestCommentWorker_ApplyPublish_DuplicateEventWritesOneRow` | 事件投递两次:评论 1 行,popularity 1 |
|
||||
| `TestCommentWorker_ApplyDelete_DuplicateIsNoop` | 删除投递两次:热度只回退一次 |
|
||||
|
||||
集成测试的 DSN 必须显式检查不含 `clientFoundRows`,否则第 1 条会通过、第 5 条会失败,而失败原因看起来像业务 bug。
|
||||
|
||||
## 12. 可观测性
|
||||
|
||||
### 12.1 日志字段
|
||||
|
||||
| 字段 | 出现位置 | 用途 |
|
||||
|---|---|---|
|
||||
| `intent_key=<K>` | API 与 Worker | 串起一次意图的全链路 |
|
||||
| `stage=<name>` | API | 区分阶段:`comment.publish`、`mention.lookup`、`mention.create` |
|
||||
| `dedupe=hit/miss` | API 兜底、Worker、通知 | 判重是否命中 |
|
||||
| `author_id` / `video_id` / `event_id` | 两侧 | 定位具体对象 |
|
||||
|
||||
排查"用户说没看到评论":
|
||||
|
||||
```
|
||||
grep intent_key=<K> # 有没有走到兜底、有没有 dedupe=hit
|
||||
grep 'dedupe=hit' # 判重命中率,用来估算"假失败"的真实比例
|
||||
```
|
||||
|
||||
### 12.2 SQL 校验
|
||||
|
||||
```sql
|
||||
-- 同一意图不应有多行
|
||||
SELECT author_id, idempotency_key, COUNT(*) FROM comments
|
||||
WHERE idempotency_key IS NOT NULL
|
||||
GROUP BY author_id, idempotency_key HAVING COUNT(*) > 1;
|
||||
|
||||
-- 同一意图对同一收件人不应有多条通知
|
||||
SELECT dedupe_key, COUNT(*) FROM notifications
|
||||
WHERE dedupe_key IS NOT NULL
|
||||
GROUP BY dedupe_key HAVING COUNT(*) > 1;
|
||||
|
||||
-- 索引确实存在
|
||||
SHOW INDEX FROM comments WHERE Key_name = 'uk_comments_author_key';
|
||||
SHOW INDEX FROM notifications WHERE Key_name = 'uk_notifications_dedupe';
|
||||
```
|
||||
|
||||
两条分组查询返回空,说明判重在工作;返回非空则说明有人绕过写入口直接插库。
|
||||
|
||||
## 13. 代码地图
|
||||
|
||||
| 文件 | 职责 | 关键符号 |
|
||||
|---|---|---|
|
||||
| `backend/internal/video/idempotency.go` | 键的生成、解析、校验;通知去重键 | `NewIntentKey`、`ResolveIntentKey`、`NotificationDedupeKey` |
|
||||
| `backend/internal/video/comment_entity.go` | 唯一索引声明;请求体字段 | `Comment.IdempotencyKey`、`PublishCommentRequest.RequestID` |
|
||||
| `backend/internal/video/comment_store.go` | 服务层依赖的窄接口 | `CommentStore`、`Mention`、`nilIfEmpty` |
|
||||
| `backend/internal/video/comment_repo.go` | 单事务"插入或跳过 + 热度" | `CreateIdempotentWithPopularity`、`DeleteByID`、`CreateMentions` |
|
||||
| `backend/internal/video/comment_service.go` | 编排两条路径、生成通知 | `Publish`、`notifyMentions`、`logIntent` |
|
||||
| `backend/internal/video/comment_handler.go` | 接收并回显 `request_id` | `PublishComment` |
|
||||
| `backend/internal/video/hot_window.go` | 热度增量的唯一写入口(§6 的占位设计已被它替换,详见 [`热度排行榜.md`](热度排行榜.md)) | `ApplyHotDelta`、`HotBucket`、`HotMember` |
|
||||
| `backend/internal/video/like_service.go` | 一个键喂两条事件 | `Like`、`Unlike` |
|
||||
| `backend/internal/middleware/redis/cache.go` | `SETNX` 原语 | `SetNX` |
|
||||
| `backend/internal/middleware/rabbitmq/commentMQ.go` | 事件携带意图键 | `Publish`、`Delete` |
|
||||
| `backend/internal/worker/commentworker.go` | 消费端用同一个键写库 | `applyPublish`、`applyDelete` |
|
||||
| `backend/internal/worker/notificationworker.go` | 通知去重与推送 | `persist` |
|
||||
| `backend/internal/notification/entity.go` | `notifications` 表唯一实体 | `Notification` |
|
||||
|
||||
## 14. 这套设计不做的事
|
||||
|
||||
- **不做全局 `processed_events` 台账。** 先记台账再执行会丢写,后记会重复写,同事务记录则等价于目标表唯一索引,且管不到 Redis。
|
||||
- **不用内容哈希做唯一键。** "好看"发两次是合法行为,哈希会误伤;哈希碰撞还会把两条不同评论合成一条。
|
||||
- **不在判重命中时返回 409。** 重复是正常语义,客户端应当把它显示成成功。
|
||||
- **不清理存量重复数据。** 唯一索引只能约束新增;存量重复需要人工评估后再删,删除时必须同步回退热度。
|
||||
- **不把删除热度回退做成无条件动作。** 门控点是 `DeleteByID` 的 `deleted bool`。
|
||||
|
||||
## 15. 一句话总结
|
||||
|
||||
一次意图一个键;键写进唯一索引;判重与副作用在同一条 SQL 或同一个 `SETNX` 里完成;所有副作用都以"这次是否真的执行了"为门控。
|
||||
616
docs/design/可观测性实现.md
Normal file
616
docs/design/可观测性实现.md
Normal file
@@ -0,0 +1,616 @@
|
||||
# 可观测性升级:pprof 评估与 Prometheus + Grafana 方案
|
||||
|
||||
> 状态:方案(尚未实现)。落地后请把本文改成现状说明:删掉本行,把“目标架构”改成“架构”。
|
||||
>
|
||||
> 读者:要接指标、要排障、要改 `observability` 包的人。
|
||||
|
||||
## 0. 结论
|
||||
|
||||
1. **pprof 不需要被替换。** 它回答“此刻为什么慢、卡在哪”,Prometheus 回答“多频繁、从什么时候开始、影响了多少请求”。两者是互补关系,不是替代关系。
|
||||
2. 现有 pprof 的实现本身没有结构性缺陷:独立监听、`enabled=false` 返回 `nil`、`Close` 幂等、有测试。真正的问题是它**在生产是关闭的**:`backend/configs/config.docker.yaml` 里 `observability.pprof.enabled: false`,两份 compose 也没有发布 6060/6061。线上实际只剩容器日志、`/healthz`、`/readyz` 的瞬时 JSON 和 Docker 健康检查。
|
||||
3. 升级的核心不是“装一个 Grafana”,而是**先让进程有一个可被抓取的观测面**:一个独立 admin 监听器,同时提供 `/metrics` 与 `/debug/pprof/*`,不碰业务端口 8080。
|
||||
4. 第一批只做 6 组指标,覆盖“MQ 断了 / 写路径降级了 / 消费堆积了 / 接口变慢了 / 进程卡住了”这几类最常见故障;其余按故障场景逐批加,不追求一次埋满。
|
||||
5. 监控栈放在 compose 的 `monitoring` profile 里,不进入 CI 的默认 `up`,避免拖慢构建、避免 `--remove-orphans` 误删。
|
||||
|
||||
本文不覆盖:链路追踪(OTel/Tempo)、日志聚合(Loki)、前端 RUM。它们是第三阶段,且都需要先有本方案的第一阶段。
|
||||
|
||||
---
|
||||
|
||||
## 1. 现状评估
|
||||
|
||||
### 1.1 已经有的东西
|
||||
|
||||
| 能力 | 位置 | 现状 |
|
||||
|---|---|---|
|
||||
| pprof(API / Worker 各一个监听器) | `backend/internal/observability/pprof.go` 的 `NewPprofServer`、`NewPprofMux` | 独立端口 6060/6061;关闭时返回 `nil`;`Close` 带 3s 超时;有 3 个测试 |
|
||||
| 存活与就绪 | `backend/internal/http/router.go` 的 `/healthz`、`/readyz` | 语义分离正确;`/readyz` 返回 `mq_enabled` / `mq_connected` / `mq_generation` / `mq_reconnects` / `mq_topology` |
|
||||
| MQ 连接状态快照 | `backend/internal/middleware/rabbitmq/rabbitMQ.go` 的 `Stats()` | 字段齐全(`Connected`、`Generation`、`Reconnects`、`Topology`、`LastUpAt`、`LastDownAt`),只差导出 |
|
||||
| 访问日志 | `gin.Default()` 的 Logger | 文本行,无法按路由聚合,也没有延迟直方图 |
|
||||
| 异步失败事实 | `failed_events` 表、`middleware/rabbitmq/dlx.go` 的 `ConsumeLoop` / `handleOne` | 有行、有日志,没有速率与积压 |
|
||||
| 排行来源 | `backend/internal/feed/entity.go` 的 `RankingSource` | 只在响应 JSON 里(`hot` / `hot_db` / `latest`),没有计数 |
|
||||
| 资源池 | GORM 背后的 `*sql.DB`、`rediscache.Client` 的 `rdb` | 标准库已提供 `DBStats` / `PoolStats`,只是没导出 |
|
||||
|
||||
### 1.2 pprof 的边界
|
||||
|
||||
pprof 是**按需采样的诊断工具**,不是监控系统。它没有历史、没有聚合、没有告警,而且每次都要人主动去抓。
|
||||
|
||||
| 问题 | pprof | Prometheus |
|
||||
|---|---|---|
|
||||
| 现在 CPU 花在哪个函数 | ✅ | ❌ |
|
||||
| 哪个 goroutine 卡住了 | ✅(goroutine profile) | ❌(只能看 goroutine 总数) |
|
||||
| 过去一小时 5xx 比例 | ❌ | ✅ |
|
||||
| 这次发布后 p95 变了吗 | ❌ | ✅ |
|
||||
| MQ 断了几次、断了多久 | ❌ | ✅ |
|
||||
| 缓存命中率从 95% 掉到 60% | ❌ | ✅ |
|
||||
|
||||
结论:pprof 是手术刀,metrics 是仪表盘。**故障时先用仪表盘判断“哪一段、什么时候、多严重”,再用 pprof 判断“为什么”。**
|
||||
|
||||
### 1.3 生产环境实际是“零可观测”
|
||||
|
||||
- `backend/configs/config.docker.yaml` 的 `observability.pprof.enabled` 是 `false`;`docker-compose.yml` 与 `docker-compose.prod.yml` 都没有发布 6060/6061。容器里即使打开 pprof,绑定 `localhost` 也只有容器自身能访问。
|
||||
- Worker 的 healthcheck 是 `pgrep worker`,不是真实健康面(`docs/ISSUES-REPORT.md` P3-39)。
|
||||
- API 的 healthcheck 是 `/healthz`,只表示进程存活。
|
||||
- 所以生产能回答的问题只有:容器是否在跑、MQ 此刻是否连着(且只在有人请求 `/readyz` 时)。
|
||||
|
||||
`README.md` 里“本地配置默认开启 pprof”只对 `config.yaml` 成立;用 Compose 启动时挂载的是 `config.docker.yaml`,默认关闭(`docs/ISSUES-REPORT.md` D-18 已记录这处不一致)。
|
||||
|
||||
### 1.4 pprof 实现层面的问题
|
||||
|
||||
| 问题 | 影响 | 建议 |
|
||||
|---|---|---|
|
||||
| 只有 `ReadHeaderTimeout`,没有 `ReadTimeout` / `IdleTimeout` | 慢连接可长期占用 fd | 补 `ReadTimeout`、`IdleTimeout` |
|
||||
| `WriteTimeout` 为 0 | 没有写超时;但直接加 10s 会让 `?seconds=30` 的 CPU profile 失败 | 若加,必须同时给 `/debug/pprof/profile` 的 `seconds` 设上限 |
|
||||
| 本地配置绑定 `localhost` | 容器内是回环地址,Prometheus 抓不到 | 容器配置改 `0.0.0.0`,并且不 publish 到宿主机 |
|
||||
| 无鉴权 | `/debug/pprof/cmdline` 可能含启动参数,heap 可能含业务数据 | 只靠网络隔离;需要时加 Bearer token |
|
||||
| block / mutex 采样率为 0 | `/debug/pprof/block`、`/debug/pprof/mutex` 基本为空 | 可选:`runtime.SetBlockProfileRate` / `SetMutexProfileFraction` |
|
||||
| 没有 wall-clock profile | CPU profile 看不到等 I/O 的时间 | 可选:`fgprof`,不是第一阶段 |
|
||||
|
||||
### 1.5 代码里已经埋好的“半成品钩子”
|
||||
|
||||
这些是这次升级的杠杆点:不需要改业务结构,只要在既有汇合点加计数。
|
||||
|
||||
- `RabbitMQ.Stats()`:连接代次、重连次数、拓扑数量,直接可转 gauge/counter。
|
||||
- `dlx.go` 的 `handleOne`:`DispositionAck` / `DispositionRetry` / `DispositionPark` 三路分支,是消费结果唯一的汇合点。
|
||||
- `OutboxMsg.CreateTime`:轮询按 `create_time ASC` 取 100 条,批次首条就是“最老积压”,不需要额外查询。
|
||||
- `RankingSource`:`hot` / `hot_db` / `latest` 三个值就是三个计数器标签。
|
||||
- `ratelimit.Limit`:六个限流规则共用同一个包装函数,一处埋点覆盖全部。
|
||||
- `sql.DB.Stats()` / `redis.PoolStats()`:连接池指标不需要额外 exporter。
|
||||
- `failed_events` 表与 `<queue>.retry` 队列:DLQ 深度与重试深度的事实来源。
|
||||
|
||||
---
|
||||
|
||||
## 2. 目标架构
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
subgraph net["compose 内网"]
|
||||
API["API :8080<br/>admin :6060"]
|
||||
WK["Worker<br/>admin :6061"]
|
||||
RMQ["RabbitMQ<br/>:15692"]
|
||||
end
|
||||
P["Prometheus :9090"]
|
||||
G["Grafana :3000"]
|
||||
A["Alertmanager(可选)"]
|
||||
|
||||
API -- "/metrics" --> P
|
||||
WK -- "/metrics" --> P
|
||||
RMQ -- "/metrics" --> P
|
||||
P -- PromQL --> G
|
||||
P -- alerts --> A
|
||||
G -. "127.0.0.1 + SSH 隧道" .-> U["人"]
|
||||
```
|
||||
|
||||
### 2.1 五条原则
|
||||
|
||||
1. **指标不经过业务端口。** `/metrics` 与 pprof 放在独立的 admin 监听器上;8080 仍然只暴露业务与 `/healthz`、`/readyz`。
|
||||
2. **Pull,不引入 Pushgateway。** API 与 Worker 都是长生命周期进程,Prometheus 直接抓;没有短任务需要 push。
|
||||
3. **低基数。** `route` 用 Gin 的路由模板(`c.FullPath()`),不用原始路径、用户 ID、视频 ID、IP、错误文本。
|
||||
4. **一个指标对应一个故障问题。** 说不清“它高了要做什么”的指标不加。
|
||||
5. **监控栈与业务同项目、不同 profile。** 同一 compose 项目保证 `--remove-orphans` 不会删掉监控容器;profile 保证 CI 的 `up -d` 不会启动它们。
|
||||
|
||||
### 2.2 端口与可达性
|
||||
|
||||
| 端口 | 进程 | 暴露方式 |
|
||||
|---|---|---|
|
||||
| 8080 | API 业务 | 公开(现状) |
|
||||
| 6060 | API admin:`/metrics`、`/debug/pprof/*` | 仅 compose 内网,不 publish |
|
||||
| 6061 | Worker admin:`/metrics`、`/debug/pprof/*`、`/healthz` | 仅 compose 内网,不 publish |
|
||||
| 9090 | Prometheus | 仅 `127.0.0.1`(需要时 SSH 隧道) |
|
||||
| 3000 | Grafana | 仅 `127.0.0.1` + SSH 隧道 |
|
||||
| 15692 | RabbitMQ prometheus 插件 | 仅 compose 内网 |
|
||||
|
||||
保留 6060/6061 而不是改成 9090/9091,有两个原因:现有文档与肌肉记忆已经绑定这两个端口;Prometheus 默认占用 9090,改了会冲突。
|
||||
|
||||
### 2.3 端点
|
||||
|
||||
| 端点 | 谁提供 | 说明 |
|
||||
|---|---|---|
|
||||
| `/metrics` | admin 监听器 | `promhttp`,OpenMetrics 文本格式 |
|
||||
| `/debug/pprof/*` | admin 监听器 | 复用 `NewPprofMux` 的 5 个 handler;`Index` 本身会分发 `goroutine` / `heap` / `allocs` 等命名 profile |
|
||||
| `/healthz` | **仅 Worker 的 admin 监听器** | 进程存活;给 compose healthcheck 用 |
|
||||
| `/healthz`、`/readyz` | API 的 8080 | 保持不变 |
|
||||
|
||||
Worker 的 `/healthz` 走 admin 端口而不是新开端口,原因是:它本来就需要一个 HTTP 面,复用 admin 监听器可以顺手把 `pgrep worker` 换掉。代价是“admin 被关闭”会让容器 unhealthy——这是有意的,配置错误应当立刻可见。
|
||||
|
||||
### 2.4 配置
|
||||
|
||||
```yaml
|
||||
observability:
|
||||
admin:
|
||||
enabled: true
|
||||
# 本地跑 go run 时用回环,避免把 pprof 暴露到局域网
|
||||
api_addr: "127.0.0.1:6060"
|
||||
worker_addr: "127.0.0.1:6061"
|
||||
# 只控制 /debug/pprof/*;/metrics 始终随 admin 开启
|
||||
pprof: true
|
||||
```
|
||||
|
||||
`config.docker.yaml` 里两个地址改为 `0.0.0.0:6060` / `0.0.0.0:6061`,端口仍然不 publish。
|
||||
|
||||
迁移对照:
|
||||
|
||||
| 旧 | 新 |
|
||||
|---|---|
|
||||
| `observability.pprof.enabled` | `observability.admin.enabled` |
|
||||
| `observability.pprof.api_addr` | `observability.admin.api_addr` |
|
||||
| `observability.pprof.worker_addr` | `observability.admin.worker_addr` |
|
||||
| — | `observability.admin.pprof` |
|
||||
|
||||
这是一次**破坏性配置变更**:三份 YAML、`DefaultLocalConfig`、`loadconfig_test.go`、`README.md` 必须在同一个提交里改完。外部自定义配置如果没迁移,`admin.enabled` 会落到零值 `false`,表现为 admin 端口不监听;Worker 的 healthcheck 会因此失败,部署会立刻暴露,而不是静默丢掉观测。
|
||||
|
||||
### 2.5 依赖
|
||||
|
||||
只加一个直接依赖:`github.com/prometheus/client_golang`。它会带入 `prometheus/common`、`client_model`、`procfs` 等间接依赖。
|
||||
|
||||
不加:
|
||||
|
||||
- **OpenTelemetry SDK**:第一阶段没有 tracing 需求,依赖面和初始化复杂度都不小。
|
||||
- **Pushgateway**:没有短生命周期任务。
|
||||
- **Loki / Tempo**:日志与追踪是第三阶段;当前 `log.Printf` 是非结构化的,先换 `log/slog` 比接 Loki 更划算。
|
||||
|
||||
---
|
||||
|
||||
## 3. 指标目录
|
||||
|
||||
命名统一用 `vloop_` 前缀;Prometheus 的 `job` / `instance` 已经能区分 API 与 Worker,不再加 `service` 标签。
|
||||
|
||||
### 3.1 P0:最小可用集(6 组)
|
||||
|
||||
| 指标 | 类型 | 标签 | 埋点位置 | 回答的问题 |
|
||||
|---|---|---|---|---|
|
||||
| `vloop_http_requests_total` | Counter | `method, route, status` | `SetRouter` 注册的 `metrics.HTTPMiddleware()` | QPS、错误率、按路由定位 |
|
||||
| `vloop_http_request_duration_seconds` | Histogram | `method, route` | 同上,`c.Next()` 之后 Observe | p95 / p99、慢接口 |
|
||||
| `vloop_http_in_flight_requests` | Gauge | — | 同上,进入 +1 / 退出 -1 | 并发与卡死 |
|
||||
| `vloop_mq_enabled` | Gauge | — | API/Worker 启动时按 `rmq != nil` 设置 | 区分“没启用 MQ”与“启用了但断了” |
|
||||
| `vloop_mq_connected` | Gauge | — | `metrics.RegisterMQStats` 读 `Stats()` | broker 是否可用,**有历史** |
|
||||
| `vloop_mq_publish_total` | Counter | `domain, result` | 各 `*MQ.Publish*` 包装 | 发布失败率 |
|
||||
| `vloop_mq_consume_total` | Counter | `queue, result` | `dlx.go` 的 `handleOne`,按 `Disposition*` 分支 | ack / retry / park 速率 |
|
||||
| `vloop_outbox_pending` | Gauge | — | `worker/outboxworker.go` 每轮批次 | outbox 积压 |
|
||||
| `vloop_write_fallback_total` | Counter | `domain, reason` | `like` / `comment` / `social` service 的降级分支 | 异步能力降级比例 |
|
||||
|
||||
这 9 个指标对应 6 个问题:接口是否变慢/报错、MQ 是否可用、发布是否失败、消费是否重试/停泊、outbox 是否堆积、写路径是否降级。
|
||||
|
||||
### 3.2 P1:MQ 与异步链路
|
||||
|
||||
| 指标 | 类型 | 标签 | 埋点位置 |
|
||||
|---|---|---|---|
|
||||
| `vloop_mq_reconnects_total` | Counter | — | `Stats().Reconnects`,自定义 Collector 以 Counter 语义输出 |
|
||||
| `vloop_mq_connection_generation` | Gauge | — | `Stats().Generation` |
|
||||
| `vloop_mq_topology_count` | Gauge | — | `Stats().Topology` |
|
||||
| `vloop_mq_last_up_timestamp_seconds` | Gauge | — | `Stats().LastUpAt` |
|
||||
| `vloop_mq_last_down_timestamp_seconds` | Gauge | — | `Stats().LastDownAt` |
|
||||
| `vloop_mq_publish_duration_seconds` | Histogram | `domain` | 发布包装 |
|
||||
| `vloop_mq_consume_duration_seconds` | Histogram | `queue` | `handleOne` 的 `process` 前后 |
|
||||
| `vloop_consumer_up` | Gauge | `consumer` | `RunConsumer` 进入消费循环置 1,退出置 0 |
|
||||
| `vloop_consumer_restarts_total` | Counter | `consumer, reason` | `RunConsumer` 的 `connLost` / channel 异常分支 |
|
||||
| `vloop_outbox_oldest_age_seconds` | Gauge | — | 批次首条的 `CreateTime` 与 `now` 之差 |
|
||||
| `vloop_outbox_publish_total` | Counter | `result` | outbox 发布成功/失败 |
|
||||
|
||||
队列深度、未 ack 数、发布速率不自己算,交给 RabbitMQ 的 `rabbitmq_prometheus` 插件:`rabbitmq_queue_messages`、`rabbitmq_queue_messages_ready`、`rabbitmq_queue_messages_unacked`、`rabbitmq_queue_messages_published_total`。停泊队列 `failed.events` 的深度用 `rabbitmq_queue_messages{queue="failed.events"}`。
|
||||
|
||||
### 3.3 P1:缓存与依赖
|
||||
|
||||
| 指标 | 类型 | 标签 | 埋点位置 |
|
||||
|---|---|---|---|
|
||||
| `vloop_cache_requests_total` | Counter | `layer=l1\|l2, result=hit\|miss` | `feed/service.go` 的 `GetVideoByIDs` |
|
||||
| `vloop_cache_fallbacks_total` | Counter | `reason=redis_error\|miss` | 同上,Redis MGet 失败或超时 |
|
||||
| `vloop_cache_singleflight_total` | Counter | `result=leader\|shared` | 同上,`requestGroup.Do` 前后 |
|
||||
| `vloop_feed_ranking_source_total` | Counter | `source=hot\|hot_db\|latest` | `ListByPopularity` 返回响应处 |
|
||||
| `vloop_redis_command_duration_seconds` | Histogram | `cmd` | go-redis `Hook`,在 `rediscache.NewClient` 注册 |
|
||||
| `vloop_redis_errors_total` | Counter | `cmd` | 同一个 Hook |
|
||||
| `vloop_redis_pool_connections` | Gauge | `state=total\|idle\|stale` | `redis.PoolStats()` |
|
||||
| `vloop_redis_pool_events_total` | Counter | `event=hits\|misses\|timeouts` | 同上 |
|
||||
| `vloop_db_connections` | Gauge | `state=open\|in_use\|idle` | `sql.DB.Stats()` |
|
||||
| `vloop_db_wait_total` | Counter | — | `sql.DBStats.WaitCount` |
|
||||
| `vloop_db_wait_duration_seconds_total` | Counter | — | `sql.DBStats.WaitDuration` |
|
||||
| `vloop_db_max_open_connections` | Gauge | — | `sql.DBStats.MaxOpenConnections` |
|
||||
|
||||
`vloop_feed_ranking_source_total` 直接对应 `docs/design/热度排行榜.md` §6.8 记录的空缺:当时只能靠响应里的 `ranking_source` 判断走了哪条路,无法量化 `hot_db` 回退率。
|
||||
|
||||
### 3.4 P2:限流、SSE、业务
|
||||
|
||||
| 指标 | 类型 | 标签 | 埋点位置 |
|
||||
|---|---|---|---|
|
||||
| `vloop_ratelimit_requests_total` | Counter | `rule, result=allowed\|rejected\|fail_open` | `middleware/ratelimit` 的 `Limit` |
|
||||
| `vloop_sse_clients` | Gauge | — | `worker/ssehub.go` 的 `Subscribe` / `Unsubscribe` |
|
||||
| `vloop_auth_failures_total` | Counter | `reason=missing\|invalid\|expired\|redis_error` | `middleware/jwt` |
|
||||
| `vloop_business_events_total` | Counter | `domain, action, result` | 各 service 成功/降级分支 |
|
||||
| `vloop_build_info` | Gauge | `version, commit, go_version` | 启动时设置 |
|
||||
|
||||
`vloop_ratelimit_requests_total{result="fail_open"}` 是安全信号:`ratelimit.Limit` 在 Redis 出错时会直接放行,限流静默失效,这条指标是唯一能发现它的地方。
|
||||
|
||||
### 3.5 命名与基数规则
|
||||
|
||||
- 计数器以 `_total` 结尾;时间用 `_seconds`;字节用 `_bytes`。
|
||||
- 标签只允许:`method`、`route`、`status`、`queue`、`consumer`、`domain`、`result`、`layer`、`rule`、`source`、`cmd`、`state`、`event`、`reason`。
|
||||
- 禁止:`account_id`、`video_id`、`ip`、原始 URL、错误文本、trace ID。
|
||||
- `route` 取 `c.FullPath()`;404 或未匹配路由统一记 `"unmatched"`,绝不把请求路径拼进标签。
|
||||
- `status` 用三位状态码字符串(`"200"`、`"500"`),不用 `2xx` / `5xx` 粗分类;本项目的路由数量下基数可控。
|
||||
- 直方图桶:`0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10` 秒。
|
||||
- **SSE 不计入 `vloop_http_request_duration_seconds`**:`/notification/stream` 的连接可能存活数小时,会把 p99 拉到没有意义。`in_flight` 可以计入,但要在面板上单独解释。
|
||||
- 计数器在进程重启后归零是正常的;查询用 `rate` / `increase`,不要用 `delta` 跨重启做减法。
|
||||
|
||||
### 3.6 反模式
|
||||
|
||||
- 把 pprof 的采样结果转成指标:没有意义,pprof 数据是给 `go tool pprof` 看的。
|
||||
- 每个 handler 一条独立指标名:标签能解决的事不要复制指标名。
|
||||
- 用指标做审计或计费:计数器会丢、会重置、会被抓取间隔平均掉。
|
||||
- 在热路径拼字符串标签:`strconv` 也有成本,标签值必须来自有限集合。
|
||||
|
||||
---
|
||||
|
||||
## 4. 采集与展示
|
||||
|
||||
### 4.1 compose 新增服务
|
||||
|
||||
两份 compose 都加同样的两个服务;`docker-compose.yml` 用默认密码方便本地,`docker-compose.prod.yml` 用 `:?` 强制设置。
|
||||
|
||||
```yaml
|
||||
prometheus:
|
||||
image: prom/prometheus:v3.2.1
|
||||
profiles: ["monitoring"]
|
||||
restart: unless-stopped
|
||||
command:
|
||||
- --config.file=/etc/prometheus/prometheus.yml
|
||||
- --storage.tsdb.path=/prometheus
|
||||
- --storage.tsdb.retention.time=15d
|
||||
- --storage.tsdb.retention.size=5GB
|
||||
- --web.enable-lifecycle
|
||||
volumes:
|
||||
- ./monitoring/prometheus:/etc/prometheus:ro
|
||||
- prometheus_data:/prometheus
|
||||
ports:
|
||||
- "127.0.0.1:9090:9090"
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:9090/-/healthy || exit 1"]
|
||||
interval: 15s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
|
||||
grafana:
|
||||
image: grafana/grafana:11.6.0
|
||||
profiles: ["monitoring"]
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
GF_SECURITY_ADMIN_PASSWORD: ${GRAFANA_ADMIN_PASSWORD:?set GRAFANA_ADMIN_PASSWORD}
|
||||
GF_USERS_ALLOW_SIGN_UP: "false"
|
||||
GF_AUTH_ANONYMOUS_ENABLED: "false"
|
||||
volumes:
|
||||
- ./monitoring/grafana/provisioning:/etc/grafana/provisioning:ro
|
||||
- ./monitoring/grafana/dashboards:/var/lib/grafana/dashboards:ro
|
||||
- grafana_data:/var/lib/grafana
|
||||
ports:
|
||||
- "127.0.0.1:3000:3000"
|
||||
depends_on:
|
||||
- prometheus
|
||||
```
|
||||
|
||||
版本号只是示例,落地时固定到当时的稳定 patch tag,不要用 `latest`。`profiles` 是关键:CI 的 `docker compose -f docker-compose.prod.yml up -d --wait --remove-orphans` 不会启动它们,也不会因为“未定义”而删掉已经手动启动的容器——profile 里的服务仍然属于当前项目配置。
|
||||
|
||||
启动与更新:
|
||||
|
||||
```bash
|
||||
docker compose -f docker-compose.prod.yml --profile monitoring up -d prometheus grafana
|
||||
# 只改了 prometheus.yml 时,不必重建容器:
|
||||
docker compose -f docker-compose.prod.yml exec prometheus wget -qO- --post-data= http://127.0.0.1:9090/-/reload
|
||||
```
|
||||
|
||||
### 4.2 Prometheus 配置
|
||||
|
||||
`monitoring/prometheus/prometheus.yml`:
|
||||
|
||||
```yaml
|
||||
global:
|
||||
scrape_interval: 15s
|
||||
scrape_timeout: 10s
|
||||
evaluation_interval: 15s
|
||||
|
||||
rule_files:
|
||||
- /etc/prometheus/alerts.yml
|
||||
|
||||
scrape_configs:
|
||||
- job_name: prometheus
|
||||
static_configs:
|
||||
- targets: ["localhost:9090"]
|
||||
|
||||
- job_name: vloop-api
|
||||
static_configs:
|
||||
- targets: ["backend:6060"]
|
||||
|
||||
- job_name: vloop-worker
|
||||
static_configs:
|
||||
- targets: ["worker:6061"]
|
||||
|
||||
- job_name: rabbitmq
|
||||
static_configs:
|
||||
- targets: ["rabbitmq:15692"]
|
||||
```
|
||||
|
||||
`backend` / `worker` 是 compose 的服务名,直接作为 DNS 名使用。
|
||||
|
||||
### 4.3 RabbitMQ 插件
|
||||
|
||||
`rabbitmq:3-management` 自带 `rabbitmq_prometheus`,但默认只输出聚合指标;要让 `rabbitmq_queue_messages{queue="..."}` 可用,必须打开 per-object 指标。
|
||||
|
||||
`monitoring/rabbitmq/enabled_plugins`:
|
||||
|
||||
```
|
||||
[rabbitmq_management,rabbitmq_prometheus].
|
||||
```
|
||||
|
||||
`monitoring/rabbitmq/rabbitmq.conf`:
|
||||
|
||||
```ini
|
||||
prometheus.return_per_object_metrics = true
|
||||
```
|
||||
|
||||
把这两个文件挂到 `rabbitmq` 服务:
|
||||
|
||||
```yaml
|
||||
volumes:
|
||||
- ./monitoring/rabbitmq/enabled_plugins:/etc/rabbitmq/enabled_plugins:ro
|
||||
- ./monitoring/rabbitmq/rabbitmq.conf:/etc/rabbitmq/rabbitmq.conf:ro
|
||||
```
|
||||
|
||||
注意 `enabled_plugins` 必须同时保留 `rabbitmq_management`,否则会覆盖 `-management` 镜像自带的启用列表。修改后 `docker compose restart rabbitmq`。如果镜像里没有该插件(旧版本),退路是进容器执行 `rabbitmq-plugins enable rabbitmq_prometheus`,或改用 Management API 采集。
|
||||
|
||||
### 4.4 Grafana provisioning
|
||||
|
||||
目录:
|
||||
|
||||
```
|
||||
monitoring/grafana/
|
||||
provisioning/
|
||||
datasources/prometheus.yml
|
||||
dashboards/dashboards.yml
|
||||
dashboards/
|
||||
vloop-overview.json
|
||||
vloop-http.json
|
||||
vloop-async.json
|
||||
vloop-runtime.json
|
||||
```
|
||||
|
||||
数据源:
|
||||
|
||||
```yaml
|
||||
apiVersion: 1
|
||||
datasources:
|
||||
- name: Prometheus
|
||||
type: prometheus
|
||||
access: proxy
|
||||
url: http://prometheus:9090
|
||||
isDefault: true
|
||||
editable: false
|
||||
```
|
||||
|
||||
面板提供者:
|
||||
|
||||
```yaml
|
||||
apiVersion: 1
|
||||
providers:
|
||||
- name: vloop
|
||||
folder: VLoop
|
||||
type: file
|
||||
options:
|
||||
path: /var/lib/grafana/dashboards
|
||||
```
|
||||
|
||||
面板 JSON 入库,Grafana 只做展示,不做唯一副本;换机器、重建容器都能恢复。
|
||||
|
||||
### 4.5 面板分组
|
||||
|
||||
| 面板 | 内容 |
|
||||
|---|---|
|
||||
| Overview | QPS、5xx 比例、p95、in-flight、goroutine、RSS、MQ connected、outbox pending、缓存命中率 |
|
||||
| HTTP | 按路由的 QPS / 错误率 / 延迟热力图,Top N 慢路由 |
|
||||
| Async | publish 速率与失败、consume 按 `result` 的速率、park 速率、`failed.events` 深度、outbox 数量与最老年龄 |
|
||||
| Runtime | DB 连接与等待、Redis 池与错误、GC / goroutine、进程 CPU / 内存 |
|
||||
|
||||
### 4.6 告警
|
||||
|
||||
Prometheus 规则文件 `monitoring/prometheus/alerts.yml`:
|
||||
|
||||
| 告警 | 表达式 | `for` | 说明 |
|
||||
|---|---|---|---|
|
||||
| `APIDown` | `up{job="vloop-api"} == 0` | 2m | 抓不到目标 |
|
||||
| `ErrorRateHigh` | `sum(rate(vloop_http_requests_total{status=~"5.."}[5m])) / clamp_min(sum(rate(vloop_http_requests_total[5m])), 0.001) > 0.01` | 5m | 5xx 超过 1% |
|
||||
| `LatencyP95High` | `histogram_quantile(0.95, sum by (le) (rate(vloop_http_request_duration_seconds_bucket[5m]))) > 0.5` | 5m | p95 超过 500ms |
|
||||
| `MQDisconnected` | `vloop_mq_enabled == 1 and vloop_mq_connected == 0` | 2m | 启用了但断开 |
|
||||
| `MessagesParked` | `sum(rate(vloop_mq_consume_total{result="park"}[5m])) > 0` | 1m | 有消息进 DLQ |
|
||||
| `DLQNotEmpty` | `rabbitmq_queue_messages{queue="failed.events"} > 0` | 5m | 停泊队列非空 |
|
||||
| `OutboxBacklog` | `vloop_outbox_pending > 100` | 10m | outbox 积压 |
|
||||
| `OutboxStalled` | `vloop_outbox_oldest_age_seconds > 60` | 5m | 最老消息超过 1 分钟 |
|
||||
| `RateLimitFailOpen` | `sum(rate(vloop_ratelimit_requests_total{result="fail_open"}[5m])) > 0` | 5m | Redis 故障导致限流失效 |
|
||||
| `DBConnSaturated` | `vloop_db_connections{state="in_use"} / vloop_db_max_open_connections > 0.9` | 5m | 连接池接近上限 |
|
||||
|
||||
`MQDisconnected` 必须带 `vloop_mq_enabled == 1`,否则“故意不启用 MQ 的本地环境”会一直告警。
|
||||
|
||||
通知两条路:
|
||||
|
||||
- **Prometheus 规则 + Alertmanager**:规则可 `promtool check rules`,可版本化,适合长期维护;多一个容器。
|
||||
- **Grafana 统一告警**:不引入 Alertmanager,联系点与静默都在 Grafana 里配;规则 schema 随 Grafana 版本变化,迁移成本略高。
|
||||
|
||||
本项目建议先落地 Prometheus 规则(先能在 Grafana 看到 firing),有明确通知渠道后再加 Alertmanager;不要为了“告警”先引入一个没人看的通知链路。
|
||||
|
||||
---
|
||||
|
||||
## 5. 实施计划
|
||||
|
||||
### 阶段 0:骨架(约 0.5–1 人日)
|
||||
|
||||
1. `go get github.com/prometheus/client_golang`,`go mod tidy`。
|
||||
2. 新建 `backend/internal/metrics`:注册 Go / process / build info 默认采集器,提供 `Handler()`。
|
||||
3. `backend/internal/observability/pprof.go` 改名为 `admin.go`:`AdminOptions{Name, Enabled, Addr, Pprof, Health, Gatherer}`,mux 注册 `/metrics`,可选 pprof 与 `/healthz`;补 `ReadTimeout`、`IdleTimeout`、`MaxHeaderBytes`。
|
||||
4. 配置改成 `observability.admin`;改三份 YAML、`DefaultLocalConfig`、`loadconfig_test.go`。
|
||||
5. API 与 Worker 的 `main` 接入;启动日志打印 `admin listening on ... (metrics=true, pprof=...)`。
|
||||
6. 测试:`/metrics` 200、pprof 开关、disabled 返回 nil。
|
||||
|
||||
验收:
|
||||
|
||||
```bash
|
||||
curl -s http://127.0.0.1:6060/metrics | grep '^go_goroutines'
|
||||
curl -s http://127.0.0.1:6061/metrics | grep '^go_goroutines'
|
||||
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:6060/debug/pprof/
|
||||
go vet ./... && go test -race -count=1 ./...
|
||||
```
|
||||
|
||||
### 阶段 1:关键路径 + 监控栈(约 1–2 人日)
|
||||
|
||||
1. `metrics.HTTPMiddleware()`:`requests_total`、`duration`、`in_flight`;`route` 用 `c.FullPath()`;SSE 排除出直方图。
|
||||
2. `metrics.RegisterMQStats`:自定义 Collector 输出连接、代次、重连、拓扑、时间戳。
|
||||
3. 发布与消费埋点:`*MQ.Publish*`、`dlx.go` 的 `handleOne`;写路径降级计数。
|
||||
4. outbox 积压与最老年龄;批次首条的 `CreateTime` 直接可用。
|
||||
5. 两份 compose 加 `monitoring` profile、Prometheus 配置、Grafana 数据源与 Overview 面板。
|
||||
6. Worker healthcheck 改 `wget -qO- http://127.0.0.1:6061/healthz`。
|
||||
|
||||
验收:停掉 RabbitMQ,`vloop_mq_connected` 在 15s 内变 0,恢复后 `vloop_mq_reconnects_total` 增长;制造一条停泊消息,`result="park"` 增长;插入一条 pending outbox,`vloop_outbox_pending` 增长。
|
||||
|
||||
### 阶段 2:业务与资源(约 2 人日)
|
||||
|
||||
1. 缓存命中/回退/singleflight、ranking source。
|
||||
2. go-redis Hook、DB 连接池 Collector。
|
||||
3. 限流拒绝与 fail-open、SSE 在线数、JWT 失败原因。
|
||||
4. RabbitMQ 插件与 per-object 指标。
|
||||
5. 告警规则;需要时加 Alertmanager。
|
||||
6. HTTP / Async / Runtime 三个面板。
|
||||
7. 更新 `README.md`、`docs/feedsystem_video_go项目设计.md` 的可观测性段落。
|
||||
|
||||
验收:命中 L1/L2 时命中率变化;超过登录限流时 `result="rejected"` 增长;停 Redis 时 `fail_open` 增长;`promtool check rules` 通过。
|
||||
|
||||
### 阶段 3:可选
|
||||
|
||||
- OpenTelemetry tracing + Tempo(先给 MQ 发布/消费加 trace context)。
|
||||
- `log/slog` 结构化日志 + Loki。
|
||||
- pprof block / mutex 采样、`fgprof`。
|
||||
- Grafana 告警替代 Alertmanager,或反过来统一。
|
||||
|
||||
### 改动文件清单
|
||||
|
||||
| 文件 | 动作 |
|
||||
|---|---|
|
||||
| `backend/go.mod`、`backend/go.sum` | 加 `client_golang` |
|
||||
| `backend/internal/metrics/*.go` | 新增:采集器、HTTP 中间件、DB/Redis/MQ Collector |
|
||||
| `backend/internal/observability/admin.go` | 由 `pprof.go` 改造:mux + 超时 + `/metrics` |
|
||||
| `backend/internal/observability/admin_test.go` | 新增/改造测试 |
|
||||
| `backend/internal/config/loadconfig.go` | `AdminConfig`,替换 `PprofConfig` |
|
||||
| `backend/configs/*.yaml` | 三份配置迁移 |
|
||||
| `backend/cmd/main.go`、`backend/cmd/worker/main.go` | 接入 admin server 与 Collector |
|
||||
| `backend/internal/http/router.go` | 注册 HTTP 中间件 |
|
||||
| `backend/internal/middleware/rabbitmq/*.go` | 发布/消费/连接指标 |
|
||||
| `backend/internal/worker/outboxworker.go`、`ssehub.go` | outbox 与 SSE 指标 |
|
||||
| `backend/internal/feed/service.go` | 缓存与 ranking source 指标 |
|
||||
| `backend/internal/middleware/ratelimit/ratelimit.go` | 限流结果指标 |
|
||||
| `backend/internal/middleware/redis/redis.go` | Hook 与池指标 |
|
||||
| `docker-compose.yml`、`docker-compose.prod.yml` | prometheus/grafana、profile、rabbitmq 配置挂载、worker healthcheck |
|
||||
| `monitoring/**` | Prometheus 配置、规则、Grafana provisioning、dashboard JSON |
|
||||
| `.env.example` | `GRAFANA_ADMIN_PASSWORD` |
|
||||
| `README.md`、设计文档 | 同步 |
|
||||
|
||||
---
|
||||
|
||||
## 6. 测试策略
|
||||
|
||||
按仓库的 TDD 约定:先写失败测试,再写实现;测试放在被覆盖代码的同包。
|
||||
|
||||
| 测试 | 位置 | 断言 |
|
||||
|---|---|---|
|
||||
| `TestAdminMux_ServesMetrics` | `observability/admin_test.go` | `/metrics` 200,body 含 `go_goroutines` |
|
||||
| `TestAdminMux_PprofToggle` | 同上 | `pprof=false` 时 `/debug/pprof/` 404,`true` 时 200 |
|
||||
| `TestAdminServer_DisabledReturnsNil` | 同上 | 保持现有行为 |
|
||||
| `TestAdminMux_WorkerHealthz` | 同上 | `/healthz` 200,JSON 含 `"status":"ok"` |
|
||||
| `TestHTTPMiddleware_RecordsStatusAndRoute` | `metrics/http_test.go` | 请求后对应 `method/route/status` 的计数 +1 |
|
||||
| `TestHTTPMiddleware_UnmatchedRouteIsBounded` | 同上 | 任意 404 都落到 `route="unmatched"`,不出现原始路径 |
|
||||
| `TestHTTPMiddleware_SSEExcludedFromHistogram` | 同上 | SSE 路由的直方图样本数不变 |
|
||||
| `TestConsumeLoop_ParkIncrementsCounter` | `middleware/rabbitmq/consume_test.go` | 永久错误/耗尽重试后 `result="park"` +1 |
|
||||
| `TestObserveOutbox_FromBatch` | `worker/outboxworker_test.go` | 批次首条 `CreateTime` 转成年龄;空批为 0 |
|
||||
| `TestConfig_AdminBlock` | `config/loadconfig_test.go` | YAML 能解析出 `admin` 字段 |
|
||||
|
||||
注意两点:
|
||||
|
||||
- 指标是包级全局变量,测试之间会累计。断言用**前后差值**,不要断言绝对值;共享计数器的子测试不要 `t.Parallel()`。
|
||||
- 需要隔离时,`AdminOptions.Gatherer` 传 `prometheus.NewRegistry()`;生产传 `nil` 用默认注册表。不要为了测试在业务包里到处传 registry。
|
||||
|
||||
验证命令与仓库一致:
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
go vet ./...
|
||||
go test -race -count=1 ./...
|
||||
```
|
||||
|
||||
需要真实 broker / MySQL 的验证放到 `//go:build integration`,通过 `RABBITMQ_TEST_URL` 等环境变量配置,缺前置条件时 `t.Skip`。
|
||||
|
||||
---
|
||||
|
||||
## 7. 风险与取舍
|
||||
|
||||
| 风险 | 影响 | 处理 |
|
||||
|---|---|---|
|
||||
| 配置迁移静默关闭 admin | 指标与 pprof 同时消失 | 三份 YAML 同提交迁移;Worker healthcheck 依赖 admin `/healthz`;启动日志明确打印 |
|
||||
| 标签基数爆炸 | Prometheus 内存与查询变慢 | `route` 用模板;禁止 ID/IP/错误文本;代码评审检查新标签 |
|
||||
| SSE 污染延迟直方图 | p95/p99 失真 | 按 `Content-Type` 排除;面板单独解释 in-flight |
|
||||
| pprof 信息泄露 / DoS | 启动参数、堆内容、CPU 采样被滥用 | 只在内网;不 publish 6060/6061;需要时加 Bearer token;限制 `?seconds` |
|
||||
| Grafana 暴露公网 | 默认口令被撞 | 只绑 `127.0.0.1`,SSH 隧道访问;强口令;关闭匿名与注册 |
|
||||
| 单机 Prometheus 与业务同生共死 | 宿主机故障时监控也丢 | 本项目可接受;需要时 `remote_write` 到云端;面板 JSON 入库 |
|
||||
| CI 的 `--remove-orphans` | 误删监控容器 | 同项目 + `profiles`;profile 服务仍算已定义 |
|
||||
| 国内拉镜像慢 | 首次启动监控栈很慢 | 使用镜像加速;CI 不启动监控,不影响部署时长 |
|
||||
| 依赖体积 | 构建变慢、二进制变大 | 只加 `client_golang`;`go mod tidy`;不引入 OTel |
|
||||
| 全局注册表与测试冲突 | 重复注册 panic、计数串扰 | 生产用默认注册表;测试用差值或独立 registry;`AdminOptions.Gatherer` 可注入 |
|
||||
| 抓取间隔与告警延迟 | 短故障漏报或告警滞后 | 15s 抓取;告警 `for` 至少 1–2 分钟;不要用单点采样做判断 |
|
||||
|
||||
---
|
||||
|
||||
## 8. 待确认
|
||||
|
||||
1. 监控栈部署在同一台 ECS(本方案默认),还是用 Grafana Cloud / 外部 Prometheus?如果走外部,`/metrics` 需要 TLS 与鉴权,端口暴露策略要重做。
|
||||
2. 是否需要 MySQL / Redis / Node exporter?应用内已经能给出连接池与命令延迟;外部 exporter 补的是服务端视角(慢查询、keyspace、磁盘)。建议第二阶段再决定。
|
||||
3. 告警通知走什么渠道(邮件 / Webhook / 企业微信)?没有渠道之前,先让规则在 Grafana 可见即可。
|
||||
4. 是否现在实施阶段 0–1?这两步已经能覆盖大部分排障需求,且不改业务逻辑。
|
||||
|
||||
---
|
||||
|
||||
## 附录 A:pprof 常用命令
|
||||
|
||||
```bash
|
||||
# CPU(默认 30s)
|
||||
go tool pprof http://127.0.0.1:6060/debug/pprof/profile?seconds=30
|
||||
|
||||
# 堆
|
||||
go tool pprof http://127.0.0.1:6060/debug/pprof/heap
|
||||
|
||||
# 浏览器里看火焰图
|
||||
go tool pprof -http=:8081 http://127.0.0.1:6061/debug/pprof/profile
|
||||
|
||||
# 在容器里看 goroutine 摘要(Alpine 自带 wget)
|
||||
docker compose exec backend wget -qO- 'http://127.0.0.1:6060/debug/pprof/goroutine?debug=1' | head
|
||||
```
|
||||
|
||||
## 附录 B:与现有问题清单的对应
|
||||
|
||||
| 编号 | 本文对应 |
|
||||
|---|---|
|
||||
| `docs/ISSUES-REPORT.md` A-7(除 pprof 外无指标) | 整个方案 |
|
||||
| `docs/ISSUES-REPORT.md` P3-25(pprof 缺超时与鉴权) | §1.4、§2.3 |
|
||||
| `docs/ISSUES-REPORT.md` P3-39(worker 用 `pgrep` 探针) | §2.3、阶段 1 |
|
||||
| `docs/design/热度排行榜.md` §6.8(回退比例不可观测) | `vloop_feed_ranking_source_total` |
|
||||
| `docs/ISSUES-REPORT.md` D-18(README 与 compose 的 pprof 默认值不一致) | §1.3、阶段 2 文档更新 |
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user