Compare commits
19 Commits
e3ee3eee2f
...
5f30f264f7
| Author | SHA1 | Date | |
|---|---|---|---|
| 5f30f264f7 | |||
| 9b8a116852 | |||
| ff8b058409 | |||
| 243ae3fcfb | |||
| 8204f4659d | |||
| 405d31db96 | |||
| 21d5fee922 | |||
| 99d629bbfd | |||
| fcf93f09c9 | |||
| 3ab0851656 | |||
| 0b1f26f16a | |||
| ea134d6d71 | |||
| 4b7f707860 | |||
| 90b9e7e0ac | |||
| c94c9babdd | |||
| 2928269329 | |||
| ec9c53a80c | |||
| 65ca5c5218 | |||
| 87f6e91ed1 |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -2,7 +2,6 @@
|
||||
backend/.run/
|
||||
data/
|
||||
.sisyphus/
|
||||
CLAUDE.md
|
||||
|
||||
#
|
||||
# Binaries for programs and plugins
|
||||
|
||||
241
AGENTS.md
Normal file
241
AGENTS.md
Normal file
@@ -0,0 +1,241 @@
|
||||
# AGENTS.md
|
||||
|
||||
This file provides guidance to Codex (claude.ai/code) when working with code in this repository.
|
||||
|
||||
## Project Overview
|
||||
|
||||
Short video feed system with Go 1.24 backend (Gin + GORM + MySQL + Redis + RabbitMQ) and Vue 3 + TypeScript frontend (rolldown-vite). Two backend binaries: API server and async Worker process. All domain wiring is manual constructor injection in `router.go` — no DI framework.
|
||||
|
||||
**Documentation**: Chinese documentation available in `docs/project-construction-guide.md` (detailed build roadmap) and `feedsystem_video_go项目设计.md` (system design).
|
||||
|
||||
## Commands
|
||||
|
||||
### Backend (run from `backend/`)
|
||||
|
||||
```bash
|
||||
# Run all tests with race detection
|
||||
go test -race -count=1 ./...
|
||||
|
||||
# Run a single test
|
||||
go test -run TestFunctionName ./internal/package/...
|
||||
|
||||
# Vet
|
||||
go vet ./...
|
||||
|
||||
# Run API server locally
|
||||
go run ./cmd
|
||||
|
||||
# Run worker process locally
|
||||
go run ./cmd/worker
|
||||
```
|
||||
|
||||
### Frontend (run from `frontend/`)
|
||||
|
||||
```bash
|
||||
npm ci # install dependencies (clean)
|
||||
npm run dev # dev server (Vite, proxies /api -> http://127.0.0.1:8080)
|
||||
npm run build # production build (vue-tsc -b && vite build)
|
||||
npm run preview # preview production build locally
|
||||
```
|
||||
|
||||
### Docker Compose (root)
|
||||
|
||||
```bash
|
||||
docker compose up -d # full stack: MySQL, Redis, RabbitMQ, API, Worker, Frontend
|
||||
docker compose up -d mysql redis rabbitmq # infra only, then run backend locally
|
||||
```
|
||||
|
||||
### Local Dev Script (root)
|
||||
|
||||
```bash
|
||||
# start.sh uses env vars to control what starts: START_REDIS, START_RABBITMQ, START_BACKEND, START_WORKER, START_FRONTEND
|
||||
START_BACKEND=1 START_WORKER=1 START_FRONTEND=1 ./start.sh
|
||||
|
||||
# Or start infra via compose, then run backend locally with the compose-local config:
|
||||
docker compose up -d mysql redis rabbitmq
|
||||
CONFIG_PATH=configs/config.compose-local.yaml go run ./cmd # API
|
||||
CONFIG_PATH=configs/config.compose-local.yaml go run ./cmd/worker # Worker
|
||||
```
|
||||
|
||||
## Architecture
|
||||
|
||||
### Dual Binary Split
|
||||
|
||||
- `backend/cmd/main.go` — Gin HTTP API server (port 8080, pprof on :6060)
|
||||
- `backend/cmd/worker/main.go` — RabbitMQ consumer process (pprof on :6061). Runs the Social, Like, Comment, and Popularity workers in independent goroutines; each gets its own AMQP channel from the shared connection manager and reconnects automatically. (Notification workers, the Outbox poller, and the timeline consumer currently live in the API process — see `router.go`.)
|
||||
|
||||
### Domain Layer Pattern
|
||||
|
||||
Each domain (`account`, `video`, `social`, `feed`) follows: **Entity → Repository → Service → Handler**. `message` and `notification` are simpler — `message` has entity + handler only (no separate repo/service), `notification` is handler-only (routes in `router.go`, worker-side logic in `worker/notificationworker.go`). All wiring is manual constructor injection in `backend/internal/http/router.go` (no DI framework).
|
||||
|
||||
**API Style**: All endpoints use POST (except SSE stream and health check) to simplify frontend client abstraction and unify JSON body handling.
|
||||
|
||||
### API Route Groups
|
||||
|
||||
All routes defined in `backend/internal/http/router.go`:
|
||||
- `/account/*` — registration, login, refresh, profile, avatar
|
||||
- `/video/*` — publish, upload (regular + chunked), detail, list by author
|
||||
- `/like/*` — like/unlike, check liked, list liked videos
|
||||
- `/comment/*` — publish, delete, list all
|
||||
- `/social/*` — follow/unfollow, followers/following lists, counts
|
||||
- `/feed/*` — latest, likes ranking, popularity, following feed, tag feed
|
||||
- `/message/*` — send/list direct messages
|
||||
- `/notification/*` — SSE stream, list, mark read, unread count
|
||||
- `GET /healthz` — health check (process liveness; always 200)
|
||||
- `GET /readyz` — dependency readiness: 503 while RabbitMQ is disconnected, reporting `mq_enabled` / `mq_connected` / `mq_generation` / `mq_reconnects` / `mq_topology`. Deliberately separate from `/healthz`: during a broker outage the API is still usable (writes fall back to direct DB), so MQ state must not cause orchestrators to restart healthy instances.
|
||||
- `GET /static/*` — serves uploaded files from `backend/.run/uploads`
|
||||
|
||||
### Async Write Path
|
||||
|
||||
Write operations (like, comment, follow) use **MQ-first with DB fallback** pattern: publish to RabbitMQ topic exchanges (`like.events`, `comment.events`, `social.events`); if MQ fails, fall back to direct DB transaction. The worker process consumes and writes to DB. Video publishing uses the **Outbox pattern** — API writes video + `OutboxMsg` in one DB transaction, a poller publishes to `video.timeline.events`.
|
||||
|
||||
### Caching (Feed Service)
|
||||
|
||||
Three-tier: L1 in-process `go-cache` (3s) → L2 Redis JSON (1h) → L3 MySQL with `singleflight` dedup. Feed "latest" uses a Redis ZSET hot cache (1000 entries) with MySQL fallback. Cache stampede protection via distributed Redis locks + `singleflight`.
|
||||
|
||||
### Middleware
|
||||
|
||||
- **JWT**: `JWTAuth()` (hard) and `SoftJWTAuth()` (optional) in `middleware/jwt/`. Redis-first token check, DB fallback. The signing key is injected once at startup via `auth.Configure` (see Configuration); when it is missing the middleware answers **500** (`server auth misconfigured`) instead of 401, so misconfiguration is never mistaken for an invalid token.
|
||||
- **Rate Limit**: Redis sliding window via Lua script in `middleware/ratelimit/`.
|
||||
- **Redis**: Wrapped client with key prefixing and distributed locking in `middleware/redis/`.
|
||||
- **RabbitMQ**: Connection manager in `middleware/rabbitmq/` — owns the AMQP connection lifecycle (connection-level reconnect with exponential backoff + jitter, topology replay on every new connection, per-generation `Session{Ch,Done}` handles). Per-domain publishers and DLX live here too.
|
||||
|
||||
### Workers
|
||||
|
||||
Consumers never touch `*amqp.Connection`. Each one runs `rabbitmq.RunConsumer(ctx, mgr, name, prefetch, fn)` — the single consume loop in the project. It blocks (no polling) while the connection is down, and on recovery rebuilds the channel, re-applies per-channel QoS, and re-runs `Consume`. Channel-level exceptions (queue deleted, 406 conflicts) trigger a topology replay rather than a reconnect. Topology is registered once (`RegisterTopology`) and replayed automatically on every new connection. `SSEHub` is an in-process pub/sub for real-time notification push to connected clients. Notification workers consume from `notification.like`, `notification.comment`, `notification.social` queues. Note: `notification` domain is handler-only — routes in `router.go`, worker-side logic in `worker/notificationworker.go`.
|
||||
|
||||
### Frontend (Vue 3 + TypeScript on rolldown-vite)
|
||||
|
||||
- **Language**: Chinese UI (matching README and documentation)
|
||||
- **State**: Pinia stores in `frontend/src/stores/` (auth, social, toast)
|
||||
- **API layer**: `frontend/src/api/` — one module per domain (account, comment, feed, like, message, social, video). `client.ts` wraps `fetch` with automatic JWT injection and 401 → token refresh → retry
|
||||
- **Composables**: `useLikeFollow`, `useVideoFeed`, `useVideoPlayer` in `frontend/src/composables/`
|
||||
- **Vite dev proxy**: `/api` → `http://127.0.0.1:8080` (strips `/api` prefix)
|
||||
|
||||
#### Frontend Routes (defined in `frontend/src/router/index.ts`)
|
||||
|
||||
| Path | View | Auth |
|
||||
|------|------|------|
|
||||
| `/` | HomeView (feed tabs: recommend, following, likes ranking) | no |
|
||||
| `/hot` | HotView (popularity ranking) | no |
|
||||
| `/video` | VideoView (publish) | yes |
|
||||
| `/video/:id` | VideoDetailView | no |
|
||||
| `/account` | AccountView (login) | no |
|
||||
| `/account/register` | RegisterView | no |
|
||||
| `/account/change-password` | ChangePasswordView | no |
|
||||
| `/settings` | SettingsView | yes |
|
||||
| `/u/:id` | UserProfileView | no |
|
||||
| `/messages` | MessageView (contact list) | yes |
|
||||
| `/messages/:peerId` | MessageView (conversation) | yes |
|
||||
|
||||
### Supporting Packages
|
||||
|
||||
- `auth/` — JWT token generation/parsing (HS256, access token TTL from config, default 15min; opaque random refresh token). Requires `auth.Configure` at startup — see Configuration.
|
||||
- `apierror/` — error classification → HTTP status codes
|
||||
- `db/` — GORM MySQL connection setup
|
||||
- `observability/` — pprof server registration
|
||||
|
||||
### Database Entities (auto-migrated via GORM)
|
||||
|
||||
`Account`, `Video`, `Like`, `Comment`, `Social`, `OutboxMsg`, `Tag`, `VideoTag`, `Message`, `Notification`
|
||||
|
||||
### Chunked Upload
|
||||
|
||||
Redis-based session tracking for 5MB chunks with per-chunk MD5 verification, breakpoint resume, and merge on completion. See `backend/internal/video/chunk_handler.go`.
|
||||
|
||||
## Configuration
|
||||
|
||||
Config files in `backend/configs/` (YAML). Loaded by `backend/internal/config/loadconfig.go`. `CONFIG_PATH` env var selects which config file to load (default: `configs/config.yaml`). Additional env vars override YAML values — see `ApplyEnvOverrides()` for the full list (`SERVER_PORT`, `MYSQL_*`, `REDIS_*`, `RABBITMQ_*`, `JWT_SECRET`, `JWT_ACCESS_TOKEN_TTL`). Copy `.env.example` to `.env` for secrets (includes `MYSQL_ROOT_PASSWORD`, `MYSQL_DATABASE`, `REDIS_PASSWORD`, `RABBITMQ_USER`, `RABBITMQ_PASS`, `JWT_SECRET`).
|
||||
|
||||
**JWT config is required and fail-fast**: `JWT_SECRET` must be at least 32 bytes — both binaries call `auth.Configure(auth.Options{...})` right after config load and **refuse to start** if it is missing or too short (there is no random-key fallback). Access token lifetime comes from `jwt.access_token_ttl` (YAML, default `15m`, overridable via `JWT_ACCESS_TOKEN_TTL`). Startup logs a key fingerprint — `JWT secret loaded (fingerprint=..., access_ttl=...)` — which must match between API and Worker. Never write the secret into the committed YAML files.
|
||||
|
||||
Config variants:
|
||||
- `config.yaml` — default, connects to localhost MySQL/Redis/RabbitMQ
|
||||
- `config.compose-local.yaml` — local dev with compose infra (MySQL on port 3307)
|
||||
- `config.docker.yaml` — used inside Docker containers (mounted via docker-compose)
|
||||
|
||||
`start.sh` env var toggles: `START_REDIS`, `START_RABBITMQ`, `START_BACKEND`, `START_WORKER`, `START_FRONTEND`, `STOP_DOCKER`
|
||||
|
||||
## CI
|
||||
|
||||
GitHub Actions (`.github/workflows/ci.yml`) runs on PRs and pushes to `main`/`master`:
|
||||
- Backend: Go 1.24.x — `go vet ./...` then `go test -race -count=1 ./...`
|
||||
- Frontend: Node 22 — `npm ci` then `npm run build`
|
||||
|
||||
## Testing
|
||||
|
||||
- Redis tests use `miniredis` (in-memory)
|
||||
- HTTP handler tests use `httptest` + `gin.CreateTestContext`
|
||||
- No mocking framework for DB; tests that need Redis use `miniredis`
|
||||
- Some tests require running MySQL — start infra first: `docker compose up -d mysql redis rabbitmq`
|
||||
- Postman collection at `test/postman.json` for manual API testing
|
||||
|
||||
## Observability
|
||||
|
||||
- Health check: `GET /healthz` (always 200) and `GET /readyz` (503 when RabbitMQ is down; see `internal/http/router_test.go` for the invariant)
|
||||
- pprof: API on `localhost:6060`, Worker on `localhost:6061` (enabled by default in local config)
|
||||
- Frontend dev server: `localhost:5173` (proxies `/api` → `http://127.0.0.1:8080`)
|
||||
- Uploads stored at `backend/.run/uploads`, served via `GET /static/`
|
||||
|
||||
## Key Files
|
||||
|
||||
- `backend/internal/http/router.go` — all route definitions and dependency wiring
|
||||
- `backend/internal/middleware/rabbitmq/` — connection manager (reconnect + topology replay + `RunConsumer`), exchange declarations, DLX, per-domain MQ publishers
|
||||
- `backend/internal/feed/service.go` — three-tier caching, hot/cold feed split
|
||||
- `backend/internal/worker/` — all async workers and SSE hub
|
||||
- `backend/internal/video/chunk_handler.go` — chunked upload logic
|
||||
|
||||
## Test-Driven Development (TDD)
|
||||
|
||||
TDD is the default working mode for behavior changes under `backend/`. The frontend has no test runner yet (`frontend/package.json` exposes only `dev`, `build`, `preview`), so frontend work is verified with `npm run build` plus a manual check of the affected view — do not describe it as test-driven. If a runner (e.g. Vitest) is added, extend this section in the same change.
|
||||
|
||||
### The loop: red → green → refactor
|
||||
|
||||
1. **Red** — write the smallest test that expresses the new behavior, run it, and watch it fail. Confirm it fails for the expected reason (wrong value, missing call, unexpected status) and not because of a typo, nil panic, or broken fixture.
|
||||
2. **Green** — write the minimal production code that makes it pass. No speculative abstractions, no extra options "while I'm here".
|
||||
3. **Refactor** — clean up implementation and test names with the suite green, re-running after each step.
|
||||
4. Commit the test and the implementation together. A push that adds behavior without a test is incomplete work, not a follow-up.
|
||||
|
||||
Bug fixes start from a regression test that reproduces the bug — failing before the fix, green after. State the failing assertion in the commit message or PR description so reviewers can see what was actually broken.
|
||||
|
||||
### Placement and naming
|
||||
|
||||
- One `*_test.go` beside the code it covers, in the **same package** (`package http`, `package rabbitmq`, …) so unexported state and helpers are reachable. Use an external `_test` package only when the test should consume the public API.
|
||||
- Name tests `TestSubject_ExpectedBehavior`, e.g. `TestReadyz_MQEnabledButDisconnected_IsDistinguishable`. Use table-driven cases with `t.Run` subtests and a `name string` field when one behavior has several inputs.
|
||||
- Mark every helper with `t.Helper()`. Shared fixtures live in `_test.go` files, never in production packages.
|
||||
- Keep the intent comment. Existing suites explain *why* an invariant exists (see the `/readyz` case in `backend/internal/http/router_test.go`); a test whose reason is unwritten gets deleted by the next person who finds it inconvenient. Match the surrounding file's comment language — test comments in this repo are largely Chinese.
|
||||
|
||||
### Test doubles
|
||||
|
||||
The repo deliberately has no mocking framework. Match that:
|
||||
|
||||
- **RabbitMQ / connection state machines** — hand-written fakes implementing the narrow interface (`fakeConn` in `backend/internal/middleware/rabbitmq/rabbitmq_test.go`). Keep them tiny: no network I/O, no timing assumptions.
|
||||
- **Redis** — `miniredis`.
|
||||
- **HTTP handlers** — `httptest` with `gin.SetMode(gin.TestMode)`, `gin.CreateTestContext`, or a router built via `SetRouter` as `backend/internal/http/router_test.go` does.
|
||||
- **MySQL** — there is no DB mock. Either extract a narrow interface and fake it for a unit test, or write the test against real MySQL and document that the infra must be up first.
|
||||
|
||||
Assert on observable behavior (HTTP status and body, rows written, messages published) rather than internal call counts; call-count assertions break on harmless refactors.
|
||||
|
||||
### Integration tests
|
||||
|
||||
Anything needing a real broker or MySQL lives in a `//go:build integration` file and is excluded from the default run:
|
||||
|
||||
```bash
|
||||
docker compose up -d rabbitmq
|
||||
go test -tags integration -count=1 -timeout 300s -v ./internal/middleware/rabbitmq/
|
||||
```
|
||||
|
||||
Configure endpoints through env vars (`RABBITMQ_TEST_URL`, …), never hardcoded hosts. When a prerequisite is missing — a restart command, a delete-queue command — `t.Skip` with the reason; a silent pass is not a substitute for a skip.
|
||||
|
||||
### Determinism and speed
|
||||
|
||||
- No real network in unit tests; no `time.Sleep` as synchronization. Prefer channels, context deadlines, or an injected clock. Tests must pass under `-race` and in any order.
|
||||
- Run `go test -race -count=1 ./...` before every push. `-count=1` is required: cached results hide flakiness, and `-race` catches the concurrency bugs this codebase is full of.
|
||||
- Do not shorten a documented timing guard to make the suite faster. `TestReadyz_MQEnabledButDisconnected_IsDistinguishable` takes ~5s on purpose — that wait *is* the assertion that the startup `EnsureTopology` timeout works.
|
||||
- Treat coverage as review input (`go test -cover ./...`), not a gate. Chasing a percentage produces assertion-free tests; missing behavior coverage on service and branch logic is the real risk.
|
||||
|
||||
### Existing tests are contracts
|
||||
|
||||
- Never weaken, skip, or delete an assertion to get a change through. If an invariant genuinely changes, change the test in the same commit and explain why in the message.
|
||||
- A new test that needs to reach into private fields, sleep for seconds, or start a container usually means the unit boundary is wrong — fix the design (inject the dependency) instead of adding scaffolding.
|
||||
- When a test starts failing "because the environment changed", check whether it was ever deterministic before editing it.
|
||||
7
CLAUDE.md
Normal file
7
CLAUDE.md
Normal file
@@ -0,0 +1,7 @@
|
||||
# CLAUDE.md
|
||||
|
||||
All agent guidance for this repository lives in a single source of truth: [AGENTS.md](AGENTS.md).
|
||||
|
||||
Read AGENTS.md before making any change. It covers the project overview, commands, architecture, configuration, CI, testing conventions, the TDD workflow, and the key files.
|
||||
|
||||
Do not duplicate that content here — if guidance needs to change, edit AGENTS.md instead, so Codex, Claude Code, and every other agent stay in sync.
|
||||
@@ -169,8 +169,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 重启或队列丢失后消费者会自行恢复,无需人工重启进程。
|
||||
|
||||
@@ -14,7 +14,6 @@ import (
|
||||
"log"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strconv"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
@@ -23,24 +22,6 @@ 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.*"
|
||||
)
|
||||
|
||||
// 带重试机制的基础设施连接函数
|
||||
func connectWithRetry(name string, maxRetries int, fn func() error) {
|
||||
for i := 0; i < maxRetries; i++ {
|
||||
@@ -57,38 +38,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 {
|
||||
@@ -120,6 +69,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 {
|
||||
@@ -146,36 +96,30 @@ func main() {
|
||||
log.Printf("Redis connected (popularity worker 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)
|
||||
}
|
||||
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)
|
||||
// RabbitMQ 连接管理器(P0-2)。
|
||||
// Worker 的职责就是消费,因此使用 Lazy 语义:broker 未就绪时在这里持续重试等待,
|
||||
// 而不是让进程退出;连接一旦建立,后续所有断连都由管理器自愈。
|
||||
rmqMgr := mqrabbit.NewRabbitMQLazy(&cfg.RabbitMQ)
|
||||
if rmqMgr == nil {
|
||||
log.Fatalf("RabbitMQ config invalid: cannot start worker without a queue manager")
|
||||
}
|
||||
defer rmqMgr.Close()
|
||||
|
||||
// 登记拓扑:每一代连接(含重连后的新连接)都会自动重放这些声明。
|
||||
// 这是"broker 侧拓扑丢失"也能恢复的关键,不能只在启动时声明一次。
|
||||
// 交换机名 / 队列名 / 绑定键一律取自 rabbitmq 包的导出常量——它们是跨进程的
|
||||
// 线缆契约,本地再定义一份就会漂移成"消费一个没人发布的队列"。
|
||||
rmqMgr.RegisterTopology(
|
||||
mqrabbit.Topology{Exchange: mqrabbit.SocialExchange, Queue: mqrabbit.SocialQueue, BindingKey: mqrabbit.SocialBindingKey},
|
||||
mqrabbit.Topology{Exchange: mqrabbit.LikeExchange, Queue: mqrabbit.LikeQueue, BindingKey: mqrabbit.LikeBindingKey},
|
||||
mqrabbit.Topology{Exchange: mqrabbit.CommentExchange, Queue: mqrabbit.CommentQueue, BindingKey: mqrabbit.CommentBindingKey},
|
||||
)
|
||||
if cache != nil {
|
||||
if err := mqrabbit.DeclareTopic(topoCh, popularityExchange, popularityQueue, popularityBindingKey); err != nil {
|
||||
log.Fatalf("Failed to declare popularity topology: %v", err)
|
||||
}
|
||||
rmqMgr.RegisterTopology(
|
||||
mqrabbit.Topology{Exchange: mqrabbit.PopularityExchange, Queue: mqrabbit.PopularityQueue, BindingKey: mqrabbit.PopularityBindingKey},
|
||||
)
|
||||
}
|
||||
topoCh.Close()
|
||||
|
||||
// 准备 repo
|
||||
socialRepo := social.NewSocialRepository(sqlDB)
|
||||
@@ -198,19 +142,19 @@ 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)
|
||||
// 每个 Worker 独立 Channel;连接断开由管理器统一重拨 + 重放拓扑 + 重建 Channel
|
||||
go mqrabbit.RunConsumer(ctx, rmqMgr, "SocialWorker", 50, func(ch *amqp.Channel) error {
|
||||
return worker.NewSocialWorker(ch, socialRepo, mqrabbit.SocialQueue).Run(ctx)
|
||||
})
|
||||
go runWorkerWithRetry(ctx, "LikeWorker", conn, func(ch *amqp.Channel) error {
|
||||
return worker.NewLikeWorker(ch, likeRepo, videoRepo, likeQueue).Run(ctx)
|
||||
go mqrabbit.RunConsumer(ctx, rmqMgr, "LikeWorker", 50, func(ch *amqp.Channel) error {
|
||||
return worker.NewLikeWorker(ch, likeRepo, videoRepo, mqrabbit.LikeQueue).Run(ctx)
|
||||
})
|
||||
go runWorkerWithRetry(ctx, "CommentWorker", conn, func(ch *amqp.Channel) error {
|
||||
return worker.NewCommentWorker(ch, commentRepo, videoRepo, commentQueue).Run(ctx)
|
||||
go mqrabbit.RunConsumer(ctx, rmqMgr, "CommentWorker", 50, func(ch *amqp.Channel) error {
|
||||
return worker.NewCommentWorker(ch, commentRepo, videoRepo, 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)
|
||||
go mqrabbit.RunConsumer(ctx, rmqMgr, "PopularityWorker", 50, func(ch *amqp.Channel) error {
|
||||
return worker.NewPopularityWorker(ch, cache, mqrabbit.PopularityQueue).Run(ctx)
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -13,9 +13,11 @@ import (
|
||||
"feedsystem_video_go/internal/video"
|
||||
"feedsystem_video_go/internal/worker"
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
@@ -24,9 +26,30 @@ func SetRouter(db *gorm.DB, cache *rediscache.Client, rmq *rabbitmq.RabbitMQ) *g
|
||||
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)
|
||||
@@ -194,62 +217,52 @@ func SetRouter(db *gorm.DB, cache *rediscache.Client, rmq *rabbitmq.RabbitMQ) *g
|
||||
protectedMessageGroup.POST("/send", messageHandler.Send)
|
||||
protectedMessageGroup.POST("/list", messageHandler.List)
|
||||
}
|
||||
//worker
|
||||
// worker:Outbox 轮询 + Timeline 消费者
|
||||
// 连接级重连 / 拓扑重放 / channel 重建统一由连接管理器(rabbitmq.RunConsumer)负责
|
||||
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)
|
||||
worker.StartConsumer(context.Background(), rmq, rabbitmq.TimelineQueue, cache)
|
||||
|
||||
// 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)
|
||||
notifGroup := r.Group("/notification")
|
||||
notifGroup.Use(sseHub.SSERequireAuth())
|
||||
sseHub.RegisterRoutes(r, notifGroup)
|
||||
|
||||
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)")
|
||||
// 3 个 notification 消费者:拓扑登记后由管理器随每一代连接重放。
|
||||
// 交换机名、队列名、路由键全部复用 rabbitmq 包的导出常量——它们是跨进程的
|
||||
// 线缆契约,在这里再写一遍字面量就会与 Worker 侧悄悄漂移。
|
||||
if rmq != nil {
|
||||
rmq.RegisterTopology(
|
||||
rabbitmq.Topology{Exchange: rabbitmq.LikeExchange, Queue: rabbitmq.NotificationLikeQueue, BindingKey: rabbitmq.LikeLikeRK},
|
||||
rabbitmq.Topology{Exchange: rabbitmq.CommentExchange, Queue: rabbitmq.NotificationCommentQueue, BindingKey: rabbitmq.CommentPublishRK},
|
||||
rabbitmq.Topology{Exchange: rabbitmq.SocialExchange, Queue: rabbitmq.NotificationSocialQueue, BindingKey: rabbitmq.SocialFollowRK},
|
||||
)
|
||||
for _, q := range []string{rabbitmq.NotificationLikeQueue, rabbitmq.NotificationCommentQueue, rabbitmq.NotificationSocialQueue} {
|
||||
queue := q
|
||||
go rabbitmq.RunConsumer(context.Background(), rmq, "notification-"+queue, 10,
|
||||
func(ch *amqp.Channel) error {
|
||||
return worker.NewNotificationWorker(ch, db, queue, sseHub).Run(context.Background())
|
||||
})
|
||||
}
|
||||
}()
|
||||
} else {
|
||||
log.Printf("Notification SSE disabled (MQ not available)")
|
||||
}
|
||||
|
||||
// 所有 publisher / consumer 都已登记拓扑:在【当前】连接上立即声明一遍。
|
||||
// 重连时管理器会自动重放,因此这里只需处理"首次连接早于拓扑登记"的启动顺序。
|
||||
// 用带超时的 ctx,避免连接恰在此刻断开时把 API 启动挂住。
|
||||
if rmq != nil {
|
||||
initCtx, cancel := context.WithTimeout(context.Background(), 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
|
||||
}
|
||||
|
||||
84
backend/internal/http/router_test.go
Normal file
84
backend/internal/http/router_test.go
Normal file
@@ -0,0 +1,84 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"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(nil, nil, rmq)
|
||||
}
|
||||
|
||||
// 这是 /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,21 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
)
|
||||
|
||||
// CommentMQ 通过连接管理器发布评论事件(不再持有长生命周期 channel)。
|
||||
type CommentMQ struct {
|
||||
ch *amqp.Channel
|
||||
mgr *RabbitMQ
|
||||
}
|
||||
|
||||
// 拓扑常量导出:见 likeMQ.go 中的说明。
|
||||
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,19 +36,12 @@ 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{
|
||||
return c.publish(ctx, "publish", CommentPublishRK, CommentEvent{
|
||||
Username: username,
|
||||
VideoID: videoID,
|
||||
AuthorID: authorID,
|
||||
@@ -57,13 +50,13 @@ func (c *CommentMQ) Publish(ctx context.Context, username string, videoID, autho
|
||||
}
|
||||
|
||||
func (c *CommentMQ) Delete(ctx context.Context, commentID uint) error {
|
||||
return c.publish(ctx, "delete", commentDeleteRK, CommentEvent{
|
||||
return c.publish(ctx, "delete", CommentDeleteRK, CommentEvent{
|
||||
CommentID: commentID,
|
||||
})
|
||||
}
|
||||
|
||||
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)
|
||||
@@ -73,5 +66,5 @@ func (c *CommentMQ) publish(ctx context.Context, action, routingKey string, evt
|
||||
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)
|
||||
}
|
||||
|
||||
54
backend/internal/middleware/rabbitmq/constants_test.go
Normal file
54
backend/internal/middleware/rabbitmq/constants_test.go
Normal file
@@ -0,0 +1,54 @@
|
||||
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"},
|
||||
{"SocialQueue", SocialQueue, "social.events"},
|
||||
{"SocialBindingKey", SocialBindingKey, "social.*"},
|
||||
{"SocialFollowRK", SocialFollowRK, "social.follow"},
|
||||
{"SocialUnfollowRK", SocialUnfollowRK, "social.unfollow"},
|
||||
|
||||
{"PopularityExchange", PopularityExchange, "video.popularity.events"},
|
||||
{"PopularityQueue", PopularityQueue, "video.popularity.events"},
|
||||
{"PopularityBindingKey", PopularityBindingKey, "video.popularity.*"},
|
||||
{"PopularityUpdateRK", PopularityUpdateRK, "video.popularity.update"},
|
||||
|
||||
{"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"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if c.got != c.want {
|
||||
t.Errorf("%s = %q, want %q(broker 线缆契约被改动,需配套迁移)", c.name, c.got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
122
backend/internal/middleware/rabbitmq/consumer.go
Normal file
122
backend/internal/middleware/rabbitmq/consumer.go
Normal file
@@ -0,0 +1,122 @@
|
||||
package rabbitmq
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
)
|
||||
|
||||
// RunConsumer 在连接管理器上运行一个消费循环——全项目唯一的消费循环实现。
|
||||
//
|
||||
// 行为:
|
||||
// - 连接断开的整个期间,它阻塞在 mgr.WaitReady 上:不轮询、不打日志,
|
||||
// 从而不会被"每 5 秒一行"的噪声掩盖真正的错误;
|
||||
// - 连接恢复后,自动重建 channel、重新设置 QoS、重新执行 fn(即重新 Consume);
|
||||
// - 若 channel 因"连接仍健康"的原因失效(队列被删、声明参数冲突等),
|
||||
// 先重放一次拓扑再退避重试,覆盖 P0-2 之外的第二种永久卡死模式。
|
||||
//
|
||||
// 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
|
||||
|
||||
// 消费前先确保拓扑存在。这覆盖了"连接建立早于拓扑登记"的启动顺序:
|
||||
// 例如 API 进程先建立连接,再构造各 publisher/consumer 并登记拓扑,
|
||||
// 此时当前连接上还没有声明过任何队列。重连路径由 supervise 的 declareAll 覆盖。
|
||||
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 后重新设置。
|
||||
// 切勿把它提到循环外——那样重连后会静默失去 prefetch 限制。
|
||||
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
|
||||
}
|
||||
|
||||
// 把"channel 失效"分成两类:连接级失效 vs channel 级异常。
|
||||
//
|
||||
// 不能只用 sess.Done 判断:库在 shutdown 中是【先】派发 NotifyClose、
|
||||
// 【后】关闭所有 channel 的 deliveries(connection.go:600-641),而
|
||||
// supervise 处理 NotifyClose 还需要一次 goroutine 调度。因此 deliveries
|
||||
// 关闭的瞬间,sess.Done 往往【还没有】关闭——此时若按"连接仍健康"处理,
|
||||
// 就会打出一条误导日志("连接仍健康"其实连接刚死)并白白重放一次拓扑。
|
||||
// 直接复查连接状态既准确、又不依赖调度时序(shutdown 一开始就置位了
|
||||
// closed 标志,所以此刻 conn.IsClosed() 必为 true)。
|
||||
connLost := false
|
||||
select {
|
||||
case <-sess.Done:
|
||||
connLost = true
|
||||
default:
|
||||
connLost = !mgr.Healthy()
|
||||
}
|
||||
|
||||
if connLost {
|
||||
// 连接级失效:等新一代连接。断连/恢复已由 supervise 记录,
|
||||
// 这里刻意不打日志——8 个消费者各刷一行才是真正的噪声源。
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -11,24 +11,32 @@ const (
|
||||
MaxRetryCount = 3
|
||||
)
|
||||
|
||||
// DeclareDLX 声明死信交换机和对应的死信队列
|
||||
// DeclareDLX 声明死信交换机和对应的死信队列(保留原有签名)。
|
||||
func DeclareDLX(ch *amqp.Channel, queueName string) error {
|
||||
if ch == nil {
|
||||
return nil
|
||||
}
|
||||
if err := ch.ExchangeDeclare(
|
||||
return declareDLX(ch, queueName)
|
||||
}
|
||||
|
||||
// declareDLX 是 DeclareDLX 的接口版本,供拓扑重放路径复用。
|
||||
func declareDLX(d declarer, queueName string) error {
|
||||
if d == nil {
|
||||
return nil
|
||||
}
|
||||
if err := d.ExchangeDeclare(
|
||||
DLXExchange, "topic", true, false, false, false, nil,
|
||||
); err != nil {
|
||||
return err
|
||||
}
|
||||
dlxQueue := queueName + ".dlx"
|
||||
_, err := ch.QueueDeclare(
|
||||
_, err := d.QueueDeclare(
|
||||
dlxQueue, true, false, false, false, nil, // 死信队列不设置 DLX
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := ch.QueueBind(dlxQueue, "#", DLXExchange, false, nil); err != nil {
|
||||
if err := d.QueueBind(dlxQueue, "#", DLXExchange, false, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
log.Printf("DLX ready: exchange=%s queue=%s", DLXExchange, dlxQueue)
|
||||
|
||||
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,27 +35,21 @@ 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)
|
||||
return l.publish(ctx, "like", LikeLikeRK, userID, videoID)
|
||||
}
|
||||
|
||||
func (l *LikeMQ) Unlike(ctx context.Context, userID, videoID uint) error {
|
||||
return l.publish(ctx, "unlike", likeUnlikeRK, userID, videoID)
|
||||
return l.publish(ctx, "unlike", LikeUnlikeRK, userID, videoID)
|
||||
}
|
||||
|
||||
func (l *LikeMQ) publish(ctx context.Context, action, routingKey string, userID, videoID uint) error {
|
||||
if l == nil || l.ch == nil {
|
||||
if l == nil || l.mgr == nil {
|
||||
return errors.New("like mq is not initialized")
|
||||
}
|
||||
if userID == 0 || videoID == 0 {
|
||||
@@ -70,5 +66,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)
|
||||
}
|
||||
|
||||
20
backend/internal/middleware/rabbitmq/notification.go
Normal file
20
backend/internal/middleware/rabbitmq/notification.go
Normal file
@@ -0,0 +1,20 @@
|
||||
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 需要同步
|
||||
// 点赞与取消点赞两个方向;通知只关心"发生过",取关 / 删评论不需要推送。
|
||||
//
|
||||
// 这三个队列原先以字符串字面量写在 internal/http/router.go 里,导致
|
||||
// rabbitmq 包与 http 包各存一份"线缆契约"。改为导出常量后,登记拓扑
|
||||
// 与启动消费者共用同一份定义。
|
||||
const (
|
||||
NotificationLikeQueue = "notification.like"
|
||||
NotificationCommentQueue = "notification.comment"
|
||||
NotificationSocialQueue = "notification.social"
|
||||
)
|
||||
@@ -4,20 +4,20 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
)
|
||||
|
||||
// PopularityMQ 通过连接管理器发布热度事件(不再持有长生命周期 channel)。
|
||||
type PopularityMQ struct {
|
||||
ch *amqp.Channel
|
||||
mgr *RabbitMQ
|
||||
}
|
||||
|
||||
// 拓扑常量导出:见 likeMQ.go 中的说明。
|
||||
const (
|
||||
popularityExchange = "video.popularity.events"
|
||||
popularityQueue = "video.popularity.events"
|
||||
popularityBindingKey = "video.popularity.*"
|
||||
PopularityExchange = "video.popularity.events"
|
||||
PopularityQueue = "video.popularity.events"
|
||||
PopularityBindingKey = "video.popularity.*"
|
||||
|
||||
popularityUpdateRK = "video.popularity.update"
|
||||
PopularityUpdateRK = "video.popularity.update"
|
||||
)
|
||||
|
||||
type PopularityEvent struct {
|
||||
@@ -31,19 +31,12 @@ 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
|
||||
base.RegisterTopology(Topology{Exchange: PopularityExchange, Queue: PopularityQueue, BindingKey: PopularityBindingKey})
|
||||
return &PopularityMQ{mgr: base}, nil
|
||||
}
|
||||
|
||||
func (p *PopularityMQ) Update(ctx context.Context, videoID uint, change int64) error {
|
||||
if p == nil || p.ch == nil {
|
||||
if p == nil || p.mgr == nil {
|
||||
return errors.New("popularity mq is not initialized")
|
||||
}
|
||||
if videoID == 0 || change == 0 {
|
||||
@@ -59,5 +52,5 @@ func (p *PopularityMQ) Update(ctx context.Context, videoID uint, change int64) e
|
||||
Change: change,
|
||||
OccurredAt: time.Now().UTC(),
|
||||
}
|
||||
return PublishJSON(ctx, p.ch, popularityExchange, popularityUpdateRK, event)
|
||||
return p.mgr.PublishJSON(ctx, PopularityExchange, PopularityUpdateRK, event)
|
||||
}
|
||||
|
||||
@@ -6,112 +6,615 @@ 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 !containsTopology(r.topology, t) {
|
||||
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
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
func containsTopology(list []Topology, t Topology) bool {
|
||||
for _, x := range list {
|
||||
if x == t {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return 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) {
|
||||
|
||||
450
backend/internal/middleware/rabbitmq/rabbitmq_test.go
Normal file
450
backend/internal/middleware/rabbitmq/rabbitmq_test.go
Normal file
@@ -0,0 +1,450 @@
|
||||
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
|
||||
}
|
||||
|
||||
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)
|
||||
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})
|
||||
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)
|
||||
return nil
|
||||
}
|
||||
|
||||
// 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, " ")
|
||||
// 交换机必须先于队列,队列必须先于绑定
|
||||
if !strings.HasPrefix(joined, "exchange:like.events queue:like.events bind:like.events<-like.events/like.*") {
|
||||
t.Fatalf("unexpected declare order: %v", f.calls)
|
||||
}
|
||||
|
||||
// 业务队列必须带 DLX 参数,否则 P0-3 的死信链路会静默失效
|
||||
for _, q := range []string{"like.events", "comment.events"} {
|
||||
args, ok := f.queueArgs(q)
|
||||
if !ok {
|
||||
t.Fatalf("queue %s was never declared", q)
|
||||
}
|
||||
if args == nil || args["x-dead-letter-exchange"] != DLXExchange {
|
||||
t.Fatalf("queue %s missing dead-letter exchange (P0-3 wiring regression): %v", q, args)
|
||||
}
|
||||
// 死信队列自身不能再带 DLX(否则会形成环)
|
||||
dlxArgs, ok := f.queueArgs(q + ".dlx")
|
||||
if !ok {
|
||||
t.Fatalf("dead-letter queue %s.dlx was never declared", q)
|
||||
}
|
||||
if len(dlxArgs) != 0 {
|
||||
t.Fatalf("dead-letter queue %s.dlx must not carry a DLX itself: %v", q, dlxArgs)
|
||||
}
|
||||
}
|
||||
|
||||
// 死信队列必须绑定到死信交换机
|
||||
if !strings.Contains(joined, "bind:like.events.dlx<-dlx.events/#") {
|
||||
t.Fatalf("dead-letter queue not bound to DLX 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")
|
||||
}
|
||||
}
|
||||
@@ -4,21 +4,21 @@ 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"
|
||||
SocialQueue = "social.events"
|
||||
SocialBindingKey = "social.*"
|
||||
|
||||
socialFollowRK = "social.follow"
|
||||
socialUnfollowRK = "social.unfollow"
|
||||
SocialFollowRK = "social.follow"
|
||||
SocialUnfollowRK = "social.unfollow"
|
||||
)
|
||||
|
||||
type SocialEvent struct {
|
||||
@@ -33,27 +33,20 @@ 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: SocialQueue, BindingKey: SocialBindingKey})
|
||||
return &SocialMQ{mgr: base}, nil
|
||||
}
|
||||
|
||||
func (s *SocialMQ) Follow(ctx context.Context, followerID, vloggerID uint) error {
|
||||
return s.publish(ctx, "follow", socialFollowRK, followerID, vloggerID)
|
||||
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, "unfollow", SocialUnfollowRK, 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 +63,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)
|
||||
}
|
||||
|
||||
103
backend/internal/middleware/rabbitmq/topology.go
Normal file
103
backend/internal/middleware/rabbitmq/topology.go
Normal file
@@ -0,0 +1,103 @@
|
||||
package rabbitmq
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
)
|
||||
|
||||
// Topology 描述一组"交换机 + 队列 + 绑定键",是可重复声明的幂等单元。
|
||||
//
|
||||
// 连接管理器会在每一代连接上重放已登记的拓扑,因此 broker 侧拓扑丢失
|
||||
// (数据卷重建、队列被手工删除、集群节点替换)之后也能自动恢复——
|
||||
// 这一条与"连接重连"同等重要:只重连不重放拓扑,
|
||||
// 会退化为"连接健康但队列不存在"的 404 死循环。
|
||||
type Topology struct {
|
||||
Exchange string
|
||||
Queue string
|
||||
BindingKey string
|
||||
}
|
||||
|
||||
// declarer 是 *amqp.Channel 上拓扑声明所需方法的最小集合。
|
||||
//
|
||||
// 抽出接口的唯一目的是可测性:声明顺序与 DLX 参数是"重构时最容易静默丢失"
|
||||
// 的两件事,有了它就能在没有 broker 的情况下断言它们。
|
||||
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)→ 绑定 → 死信队列。
|
||||
//
|
||||
// 注意:d 为 nil 的判断只能拦住"nil 接口"。若调用方传入类型化的 nil
|
||||
// (如 var ch *amqp.Channel = nil),此处无法识别——因此 *amqp.Channel
|
||||
// 的入口(DeclareTopic)保留了自己的 nil 检查。
|
||||
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")
|
||||
}
|
||||
|
||||
if err := d.ExchangeDeclare(
|
||||
t.Exchange,
|
||||
"topic",
|
||||
true, // durable
|
||||
false, // autoDelete
|
||||
false, // internal
|
||||
false, // noWait
|
||||
nil,
|
||||
); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
q, err := d.QueueDeclare(
|
||||
t.Queue,
|
||||
true, // durable
|
||||
false, // autoDelete
|
||||
false, // exclusive
|
||||
false, // noWait
|
||||
amqp.Table{"x-dead-letter-exchange": DLXExchange},
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := d.QueueBind(
|
||||
q.Name,
|
||||
t.BindingKey,
|
||||
t.Exchange,
|
||||
false, // noWait
|
||||
nil,
|
||||
); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// DLX 只声明一次即可;重复声明幂等。失败降级为告警(与改造前行为一致)。
|
||||
if err := declareDLX(d, t.Queue); err != nil {
|
||||
log.Printf("DLX declare failed for %s: %v", t.Queue, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeclareTopologies 按登记顺序重放拓扑。顺序有意义:交换机先于队列先于绑定。
|
||||
func DeclareTopologies(d declarer, topo []Topology) error {
|
||||
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})
|
||||
}
|
||||
@@ -100,7 +100,7 @@ func (w *NotificationWorker) process(ctx context.Context, d amqp.Delivery) error
|
||||
var notif *Notification
|
||||
|
||||
switch {
|
||||
case routingKey == "like.like":
|
||||
case routingKey == rabbitmq.LikeLikeRK:
|
||||
var evt rabbitmq.LikeEvent
|
||||
if err := json.Unmarshal(body, &evt); err != nil {
|
||||
return nil
|
||||
@@ -120,7 +120,7 @@ func (w *NotificationWorker) process(ctx context.Context, d amqp.Delivery) error
|
||||
}
|
||||
notif = &Notification{RecipientID: authorID, SenderID: evt.UserID, Type: "like", TargetID: evt.VideoID, Content: "点赞了你的视频"}
|
||||
|
||||
case routingKey == "comment.publish":
|
||||
case routingKey == rabbitmq.CommentPublishRK:
|
||||
var evt rabbitmq.CommentEvent
|
||||
if err := json.Unmarshal(body, &evt); err != nil {
|
||||
return nil
|
||||
@@ -140,7 +140,7 @@ func (w *NotificationWorker) process(ctx context.Context, d amqp.Delivery) error
|
||||
}
|
||||
notif = &Notification{RecipientID: authorID, SenderID: evt.AuthorID, Type: "comment", TargetID: evt.VideoID, Content: "评论了你的视频"}
|
||||
|
||||
case routingKey == "social.follow":
|
||||
case routingKey == rabbitmq.SocialFollowRK:
|
||||
var evt rabbitmq.SocialEvent
|
||||
if err := json.Unmarshal(body, &evt); err != nil {
|
||||
return nil
|
||||
|
||||
@@ -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,10 +11,16 @@ import (
|
||||
"log"
|
||||
"time"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
oredis "github.com/redis/go-redis/v9"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// outboxPublishTimeout 限制单条 outbox 消息的发布时间。
|
||||
// 连接管理器在断连期间会阻塞等待重连,这里加超时可以保持"失败即进入下一轮轮询"
|
||||
// 的既有语义,而不是把整个轮询器挂在一条消息上。
|
||||
const outboxPublishTimeout = 5 * time.Second
|
||||
|
||||
// 轮询器,轮询数据库中的 outbox 表,获取待投递的消息,投递到 MQ 中
|
||||
func StartOutboxPoller(db *gorm.DB, tmq *rabbitmq.TimelineMQ) {
|
||||
if db == nil || tmq == nil {
|
||||
@@ -27,13 +34,20 @@ func StartOutboxPoller(db *gorm.DB, tmq *rabbitmq.TimelineMQ) {
|
||||
|
||||
err := db.Where("status = ?", "pending").Order("create_time ASC").Limit(100).Find(&messages).Error
|
||||
|
||||
if err != nil || len(messages) == 0 {
|
||||
if err != nil {
|
||||
log.Printf("outbox 轮询失败: %v", err)
|
||||
time.Sleep(1 * time.Second)
|
||||
continue
|
||||
}
|
||||
if len(messages) == 0 {
|
||||
time.Sleep(1 * time.Second)
|
||||
continue
|
||||
}
|
||||
|
||||
for _, msg := range messages {
|
||||
err := tmq.PublishVideo(context.Background(), msg.VideoID, msg.CreateTime)
|
||||
pubCtx, cancel := context.WithTimeout(context.Background(), outboxPublishTimeout)
|
||||
err := tmq.PublishVideo(pubCtx, msg.VideoID, msg.CreateTime)
|
||||
cancel()
|
||||
|
||||
if err == nil {
|
||||
if err := db.Delete(&msg).Error; err != nil {
|
||||
@@ -47,9 +61,12 @@ func StartOutboxPoller(db *gorm.DB, tmq *rabbitmq.TimelineMQ) {
|
||||
}()
|
||||
}
|
||||
|
||||
// 消费者,消费 MQ 中的消息,写入 Redis 的 Zset 中
|
||||
func StartConsumer(tmq *rabbitmq.TimelineMQ, queueName string, redisClient *rediscache.Client, rmq *rabbitmq.RabbitMQ) {
|
||||
if tmq == nil || rmq == nil || rmq.Conn == nil {
|
||||
// StartConsumer 消费 timeline 事件并写入 Redis ZSet。
|
||||
//
|
||||
// 连接级重连、拓扑重放、channel 重建全部交给连接管理器(rabbitmq.RunConsumer),
|
||||
// 这里只关心"一条消息应该怎么被处理"。
|
||||
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 +75,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)
|
||||
go 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)
|
||||
}
|
||||
|
||||
@@ -72,6 +72,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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -63,6 +63,18 @@ func jwtSecret() []byte {
|
||||
|
||||
### P0-2 RabbitMQ 无 connection 级重连:MQ 重启后所有消费者永久卡死
|
||||
|
||||
> **状态:✅ 已修复**(2026-10-14)。完整方案、代码、实装差异与实测输出见 [`docs/solutions/P0-2-rabbitmq-reconnect.md`](solutions/P0-2-rabbitmq-reconnect.md)。
|
||||
>
|
||||
> 修复要点:`RabbitMQ` 升级为**连接管理器**(连接私有化给唯一的 `supervise` 协程、`NotifyClose` 事件驱动、指数退避 + 抖动、**连接代** `Session{Ch,Done}`);**重连后自动重放拓扑**,因此同时修掉了报告未覆盖的第二种永久卡死——"连接活着但队列没了"(broker 数据卷重建 / 队列被删 / 声明参数冲突),那种情况下永远不会触发连接重连;三处重复的重连循环收敛为唯一的 `RunConsumer`(顺带统一了此前不一致的 prefetch:50 / 无 / 10);5 个 publisher 一并改走管理器(联动 P1-13)。
|
||||
>
|
||||
> 上游核实:`amqp091-go` 的连接**在 closed 后 `Channel()` 直接短路返回 `ErrClosed`,零网络 I/O**(`connection.go:842-848`),即原实现**从未尝试过重连**,而非"重连失败"。
|
||||
>
|
||||
> 遗留验证:§9.2 的端到端"MQ 重启自愈"验收需要有 Docker 的环境(实施沙箱无法访问 Docker API),集成测试已随代码提供(`//go:build integration`)。
|
||||
>
|
||||
> 行号勘误:`runWorkerWithRetry` 修复前为 `:61-90`,唯一 Dial 为 `:152-157`(P0-1 修复插入 `auth.Configure` 后行号后移)。
|
||||
>
|
||||
> 下文为**修复前的原始分析**,保留以资回溯。
|
||||
|
||||
**位置**:`backend/cmd/worker/main.go:59-89`(`runWorkerWithRetry`)、`backend/cmd/worker/main.go:139-145`(唯一一次 Dial)
|
||||
|
||||
```go
|
||||
@@ -616,6 +628,16 @@ jobs:
|
||||
|
||||
### P1-13 🆕 API 侧 MQ Publisher 各持单一长生命周期 channel 且无重建,故障后永久降级
|
||||
|
||||
> **状态:✅ 已随 P0-2 一并修复**(2026-10-14)。方案、代码与实测见 [`docs/solutions/P0-2-rabbitmq-reconnect.md`](solutions/P0-2-rabbitmq-reconnect.md) §6.7 与 §9.5.4。
|
||||
>
|
||||
> 修复要点:5 个 publisher 不再各自在构造时取 channel 并终身持有,改为只持 `*RabbitMQ` 并在构造时 `RegisterTopology`;发布统一走 `(*RabbitMQ).PublishJSON`,管理器为**每一代连接**复用一个发布 channel,失败即丢弃、随下一代重建。
|
||||
>
|
||||
> 刻意**不做**"`ErrClosed` 时自动重发":那会在 P0-4 的双写窗口之上再叠加一次不确定性;发布失败如实返回错误,交由既有的 DB 直写降级,幂等交给事件层(`event_id`)。
|
||||
>
|
||||
> 实测:broker 重启后 A 关注 B,`notifications` 正常落库——即"API 发布 → 队列 → 消费者 → DB"整链在重启后仍然通(§9.5.4(c))。
|
||||
>
|
||||
> 下文为**修复前的原始分析**,保留以资回溯。
|
||||
|
||||
**位置**:`backend/internal/middleware/rabbitmq/likeMQ.go:32-45`(其余 4 个 publisher 同构:`commentMQ.go:35-48`、`socialMQ.go:32-45`、`popularityMQ.go:30-43`、`timelineMQ.go:29-42`);构造点 `backend/internal/http/router.go:62-66, 87-91, 106-110, 124-128, 198-202`
|
||||
|
||||
```go
|
||||
@@ -1234,7 +1256,7 @@ SSE 为进程内 pub/sub(`ssehub.go:18-26`)、feed L1 为进程内 go-cache
|
||||
|
||||
### A-7 🆕 缺乏可观测性落地(除 pprof 外无任何指标)
|
||||
**位置**:`observability/pprof.go:20-29`(仅注册 pprof);全项目 `grep` 无 metrics/otel 依赖(`backend/go.mod` 中无 prometheus/otel)
|
||||
项目只有 pprof 与 `/healthz`,**没有业务指标**(MQ 发布失败数、消费失败数、DLX 深度、outbox 积压、缓存命中率、DB 连接池、限流触发次数)。P0-3(消息丢弃)、P1-3(outbox 积压)、P2-1(限流降级)这类问题之所以只能靠读代码发现,正是因为缺少指标。**建议**:引入 `prometheus/client_golang`,暴露关键计数器/直方图,并在 compose/部署中让 pprof 与 metrics 仅对内网开放。
|
||||
项目只有 pprof、`/healthz` 与 `/readyz`(后者只报告 MQ 连接状态与重连计数),**没有业务指标**(MQ 发布失败数、消费失败数、DLX 深度、outbox 积压、缓存命中率、DB 连接池、限流触发次数)。P0-3(消息丢弃)、P1-3(outbox 积压)、P2-1(限流降级)这类问题之所以只能靠读代码发现,正是因为缺少指标。**建议**:引入 `prometheus/client_golang`,暴露关键计数器/直方图,并在 compose/部署中让 pprof 与 metrics 仅对内网开放。`RabbitMQ.Stats()` 已经备好了连接代次、重连次数与状态快照,接出指标是纯增量工作。
|
||||
|
||||
---
|
||||
|
||||
@@ -1270,7 +1292,7 @@ SSE 为进程内 pub/sub(`ssehub.go:18-26`)、feed L1 为进程内 go-cache
|
||||
|
||||
| # | 文档声称 | 代码事实(含位置) |
|
||||
|---|---|---|
|
||||
| D-1 | CLAUDE.md:Worker 进程运行"Social、Like、Comment、Popularity、Notification、Outbox 六类 worker" | Worker 二进制**只有 4 类**(`cmd/worker/main.go:190-203`);Notification×3、Outbox、Timeline consumer 全在 **API 进程**(`router.go:197-252`) |
|
||||
| D-1 | CLAUDE.md:Worker 进程运行"Social、Like、Comment、Popularity、Notification、Outbox 六类 worker" | Worker 二进制**只有 4 类**(`cmd/worker/main.go:190-203`);Notification×3、Outbox、Timeline consumer 全在 **API 进程**(`router.go:197-252`)。**✅ 已在工作区修正**(2026-10-14):CLAUDE.md 改为如实描述"Worker 跑 4 类 + Notification/Outbox/Timeline 在 API 进程";但该文件仍被 `.gitignore:5` 忽略、未纳入版本库(见 P1-11),**克隆仓库者依旧看不到修正** |
|
||||
| D-2 | CLAUDE.md:写操作(like/comment/follow)"use **MQ-first with DB fallback**" | `social/service.go:43-57` 实为 **DB-first + MQ 仅作通知**,且 `socialworker.go:95-113` 还会冗余重放写库 |
|
||||
| D-3 | CLAUDE.md:限流为 "Redis **sliding window** via Lua script" | 实为**首请求锚定固定窗口**(`redis.go:90-96`,仅 count==1 时 PEXPIRE) |
|
||||
| D-4 | README.md:CI 位于 `.github/workflows/ci.yml`(GitHub Actions) | **`.github/` 目录不存在**;实际只有 `.gitea/workflows/ci.yml`(Gitea Actions,仅 push 触发,含生产部署步骤) |
|
||||
@@ -1322,8 +1344,8 @@ SSE 为进程内 pub/sub(`ssehub.go:18-26`)、feed L1 为进程内 go-cache
|
||||
## 九、修复路线建议
|
||||
|
||||
**第一阶段(可用性与正确性)**
|
||||
1. P0-1 JWT 密钥缓存 + fail-fast(改动极小、收益极高)。
|
||||
2. P0-2 RabbitMQ connection 级重连(含 P1-13 的 publisher channel 重建)。
|
||||
1. P0-1 JWT 密钥缓存 + fail-fast(改动极小、收益极高)。—— **✅ 已完成**(2026-10-12),见 [`docs/solutions/P0-1-jwt-secret.md`](solutions/P0-1-jwt-secret.md)。
|
||||
2. P0-2 RabbitMQ connection 级重连(含 P1-13 的 publisher channel 重建)。—— **✅ 已完成**(2026-10-14),含端到端验收与配套的 `/readyz` 依赖就绪探针;见 [`docs/solutions/P0-2-rabbitmq-reconnect.md`](solutions/P0-2-rabbitmq-reconnect.md)。
|
||||
3. P0-3 重试耗尽改 Nack→DLX + 死信消费者 + 真实重试计数。
|
||||
4. P0-4 建立 `processed_events` 幂等表(覆盖 like/comment/notify,让 `event_id` 生效)。
|
||||
5. P0-5 热度双轨收敛(推荐 `PopularityWorker` 同步累加 DB 列)。
|
||||
|
||||
@@ -11,13 +11,13 @@
|
||||
| ORM 框架 | GORM | 模型定义、CRUD、启动时 AutoMigrate 自动迁移表结构。 |
|
||||
| 持久化 | MySQL | 存储 `Account / Video / Like / Comment / Social / Tag / VideoTag / Message / Notification / OutboxMsg` 等表及统计字段(如 likes_count、popularity)。 |
|
||||
| 缓存/排行榜 | Redis(可选) | Token/Refresh Token 缓存、Feed 时间线、视频实体缓存、视频详情缓存、热榜 ZSET、分片上传会话、接口限流计数。 |
|
||||
| 消息队列 | RabbitMQ(可选) | Topic 事件总线:`like.events`、`comment.events`、`social.events`、`video.popularity.events`、`video.timeline.events`;支持 DLX、异常降级直写。 |
|
||||
| 消息队列 | RabbitMQ(可选) | Topic 事件总线:`like.events`、`comment.events`、`social.events`、`video.popularity.events`、`video.timeline.events`;支持 DLX、异常降级直写。连接由 `middleware/rabbitmq` 的连接管理器持有:断连自动重连、每一代连接自动重放拓扑(见“RabbitMQ 优化部分”)。 |
|
||||
| 异步执行 | Worker(Go) | `cmd/worker`:LikeWorker/CommentWorker/SocialWorker/PopularityWorker;API 进程内启动 OutboxPoller、TimelineConsumer 与 NotificationWorker。 |
|
||||
| 文件存储 | Local Disk(可替换对象存储) | 视频与封面文件存放本地目录(生产可替换为 OSS/S3/MinIO)。 |
|
||||
| 容器化/依赖编排 | Docker / Docker Compose | 一键拉起 RabbitMQ 等依赖(可配合 `./start.sh`),便于本地联调与部署环境一致性。 |
|
||||
| 接口调试 | Postman Collection | `test/postman.json`:预置变量、批量跑接口与部分断言脚本。 |
|
||||
| 前端 | Vue 3 + Vite + Pinia | 前端工程 `frontend/`,通过 Vite 代理 `/api` 对接后端,提供沉浸式播放、发布、主页、私信等页面。 |
|
||||
| 可观测性 | pprof / healthz | `GET /healthz` 健康检查;本地 pprof 默认 API `localhost:6060`、Worker `localhost:6061`。 |
|
||||
| 可观测性 | pprof / healthz / readyz | `GET /healthz` 存活检查(恒 200);`GET /readyz` 依赖就绪检查(RabbitMQ 断连时 503,并给出 `mq_reconnects` 等计数);本地 pprof 默认 API `localhost:6060`、Worker `localhost:6061`。 |
|
||||
|
||||
## 模块设计
|
||||
|
||||
@@ -186,6 +186,23 @@
|
||||
| 时间线 | `video.timeline.events` / `video.timeline.publish` | 新视频发布时间线 | `{event_id, video_id, create_time, occurred_at}` | `TimelineConsumer` | `Publish` 事务写 `outbox_msgs`;OutboxPoller 投递 MQ;TimelineConsumer 写 Redis `feed:global_timeline`。 |
|
||||
| 死信 | `dlx.events` / `#` | 失败消息 | 原始消息 | DLX Queue | RabbitMQ 队列声明 `x-dead-letter-exchange`;Worker 按 `x-death` 统计最多重试 3 次。 |
|
||||
|
||||
**连接管理(连接级重连与拓扑重放)**
|
||||
|
||||
上表的拓扑本身**在运行期保持不变**(交换机/队列/绑定键/DLX 均未改动);变化的是"谁持有连接、断连后怎么办":
|
||||
|
||||
| 关注点 | 现状 |
|
||||
| ------ | ---- |
|
||||
| 连接归属 | 由 `middleware/rabbitmq` 的连接管理器(`RabbitMQ`)独占持有,连接字段私有化,只允许内部 `supervise` 协程创建;其他组件只能拿到 channel。 |
|
||||
| 断连感知 | `NotifyClose` 事件驱动(带缓冲 channel,避免卡住库的 `shutdown` 路径),不轮询。 |
|
||||
| 重连策略 | 指数退避 + 抖动(默认 500ms → 30s 上限);进程退出用可中断的定时器,不会被退避拖住。 |
|
||||
| 拓扑重放 | 拓扑经 `RegisterTopology` 登记一次,**每一代新连接都会完整重放**;因此 broker 数据卷重建、队列被手工删除、声明参数冲突等"连接健康但拓扑丢失"的场景也能恢复。 |
|
||||
| 消费者取 channel | `RunConsumer` 是全项目唯一的消费循环;用 `Session{Ch, Done}` 按"连接代"取 channel,断连期间阻塞等待(不轮询、不刷日志),恢复后重建 channel、重新设置 QoS 并重新 `Consume`。 |
|
||||
| 发布侧 | 5 个 publisher 不再各自终身持有 channel,统一经管理器发布;管理器为每一代连接复用一个发布 channel,失败即丢弃并在下一代重建。 |
|
||||
|
||||
**为什么 `/readyz` 不并入 `/healthz`**:broker 故障期间 API 仍是可用的——写路径会降级为直写 MySQL,读路径不依赖 MQ。若把 MQ 状态放进 `/healthz` 并返回非 200,容器编排或负载均衡可能在故障期间反复重启/摘除仍然健康的实例,把"异步能力降级"放大成"整站不可用"。
|
||||
|
||||
> 完整成因分析、备选方案与端到端验收记录(含 broker 重启后 8 个消费者全部自愈的实测日志)见 [`docs/solutions/P0-2-rabbitmq-reconnect.md`](solutions/P0-2-rabbitmq-reconnect.md)。
|
||||
|
||||
# 整体架构
|
||||
|
||||

|
||||
@@ -234,4 +251,4 @@
|
||||
| 工程交付 | Docker Compose 一键拉起 | `docker compose up -d --build` 同时拉起 MySQL、Redis、RabbitMQ、API、Worker、Frontend,并配置健康检查与 volume。 | 本地演示和部署入口统一,依赖健康状态明确。 |
|
||||
| 工程交付 | 脚本化一键启动与可拆分运行 | `./start.sh` 默认启动后端、Worker、前端、Redis、RabbitMQ;可用 `START_FRONTEND=0`、`START_WORKER=0`、`STOP_DOCKER=1` 等开关控制。 | 提升开发体验与部署灵活性,API/Worker 可独立伸缩。 |
|
||||
| 工程质量 | 自动化基础设施 | 服务启动时执行 GORM `AutoMigrate` 自动同步账号、视频、互动、标签、私信、通知、Outbox 等表结构。 | 简化部署与迭代成本,保证 Schema 与模型一致。 |
|
||||
| 可观测性 | 健康检查与 pprof | `GET /healthz` 提供 API 健康检查;本地 pprof 默认 API `localhost:6060`、Worker `localhost:6061`。 | 便于定位 CPU、内存、goroutine 等运行时问题。 |
|
||||
| 可观测性 | 健康检查与 pprof | `GET /healthz` 提供 API 存活检查(恒 200);`GET /readyz` 提供依赖就绪检查(RabbitMQ 断连时 503,并给出 `mq_generation` / `mq_reconnects` 等计数);本地 pprof 默认 API `localhost:6060`、Worker `localhost:6061`。 | 便于定位 CPU、内存、goroutine 等运行时问题;两个探针分离,使 broker 故障期间"可见但不误杀"。 |
|
||||
|
||||
@@ -161,7 +161,7 @@ POST /video/like → 401
|
||||
|
||||
**D3 值得单独强调**:报告把它列为"绝对不安全的兜底",但它实际上是比 P0-1 主症状**更值得优先处理的漏洞**。`rand.Read` 失败虽罕见(熵池耗尽),但其后果不是"不可用"而是"**可被冒充**"——攻击者用公开字符串即可签发任意 `account_id` 的合法 token。**修复中必须直接删除该分支,不做等价替换。**
|
||||
|
||||
另外核对报告提到的一处事实(D-5,`docs/ISSUES-REPORT.md:1271`):README 与 `.env.example` 承诺的默认值 `feedsystem-dev-secret-key` 在代码中**不存在**(已确认 `grep JWT_SECRET` 全仓仅命中 `jwt.go`、compose、README、docs);且该字面量实测长度 **25 字节**,本身不满足 §5 建议的 ≥32 字节下限。**文档与代码的不一致,恰好掩盖了 D2**——开发者以为"有默认值",于是从未深究。
|
||||
另外核对报告提到的一处事实(D-5,`docs/ISSUES-REPORT.md:1299`):README 与 `.env.example` 承诺的默认值 `feedsystem-dev-secret-key` 在代码中**不存在**(已确认 `grep JWT_SECRET` 全仓仅命中 `jwt.go`、compose、README、docs);且该字面量实测长度 **25 字节**,本身不满足 §5 建议的 ≥32 字节下限。**文档与代码的不一致,恰好掩盖了 D2**——开发者以为"有默认值",于是从未深究。
|
||||
|
||||
---
|
||||
|
||||
@@ -1427,7 +1427,7 @@ func GenerateToken(accountID uint, username string) (string, error) {
|
||||
|
||||
**文档**
|
||||
|
||||
- `docs/ISSUES-REPORT.md:26-54`(P0-1 原文,已标注修复状态)、`:1271`(D-5,已标注修复)
|
||||
- `docs/ISSUES-REPORT.md:26-54`(P0-1 原文,已标注修复状态)、`:1299`(D-5,已标注修复)
|
||||
- `docs/feedsystem_video_go项目设计.md`(`:45`、`:218` — 令牌有效期改为可配置的说明)
|
||||
- `README.md:30,153-156`(JWT_SECRET 必填 + JWT_ACCESS_TOKEN_TTL)
|
||||
- `CLAUDE.md:147`(配置项清单;**该文件被 `.gitignore` 忽略,未纳入版本控制**)
|
||||
|
||||
2106
docs/solutions/P0-2-rabbitmq-reconnect.md
Normal file
2106
docs/solutions/P0-2-rabbitmq-reconnect.md
Normal file
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user