Compare commits
21 Commits
111fea0f0c
...
af77a979ff
| Author | SHA1 | Date | |
|---|---|---|---|
| af77a979ff | |||
| 52213c1d83 | |||
| f658b7e76e | |||
| c73c8861db | |||
| 73b1989bbf | |||
| 7454bf457e | |||
| 7d9cb061a2 | |||
| 5d05c147ed | |||
| 06e001a151 | |||
| fe3ad4a558 | |||
| 6e302be567 | |||
| 81259e5aff | |||
| 239a98e1fa | |||
| ffd33f981c | |||
| 814b94a0f1 | |||
| 97a6258ccc | |||
| 101f46f927 | |||
| b2d2e3d473 | |||
| 9bf3ffc9d8 | |||
| b3d381b0a0 | |||
| fc93ccfcf5 |
343
AGENTS.md
343
AGENTS.md
@@ -1,288 +1,95 @@
|
||||
# AGENTS.md
|
||||
|
||||
This file provides guidance to Codex (claude.ai/code) when working with code in this repository.
|
||||
本文件只写约束。项目是什么见 `README.md`,设计与决策见 `docs/design/`、`docs/solutions/`。
|
||||
|
||||
## 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.
|
||||
- 新增消费者必须实现幂等的 `process`,失败处置只走 `rabbitmq.ConsumeLoop`(Ack / 重投 / 停泊)。不要自己写重试循环,也不要新增 `ch.Consume` 调用点。
|
||||
- `JWT_SECRET` 等密钥只从环境变量或 `.env` 读取,不得写入提交的 YAML。
|
||||
|
||||
**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/`)
|
||||
### 后端(在 `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 test -race -count=1 ./... # 推送前必跑
|
||||
go test -run TestName ./internal/package/...
|
||||
go vet ./...
|
||||
|
||||
# Run API server locally
|
||||
go run ./cmd
|
||||
|
||||
# Run worker process locally
|
||||
go run ./cmd/worker
|
||||
go run ./cmd # API
|
||||
go run ./cmd/worker # Worker
|
||||
```
|
||||
|
||||
### Frontend (run from `frontend/`)
|
||||
### 前端(在 `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
|
||||
npm ci
|
||||
npm run dev # localhost:5173,/api 代理到 127.0.0.1:8080
|
||||
npm run build # 前端唯一的验证手段
|
||||
```
|
||||
|
||||
### 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
|
||||
CONFIG_PATH=configs/config.compose-local.yaml go run ./cmd
|
||||
START_BACKEND=1 START_WORKER=1 START_FRONTEND=1 ./start.sh
|
||||
```
|
||||
|
||||
## 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, and Comment workers in independent goroutines; each gets its own AMQP channel from the shared connection manager and reconnects automatically. Interaction counts are written by the business transaction (`ApplyLike`/`ApplyUnlike`/`CreateIdempotentWithPopularity`/`DeleteWithPopularity`); the hot ranking is a derived 60-minute sliding window (`video.ApplyHotDelta`, best-effort after commit, rebuildable with `cmd/reconcile -rebuild-hot`). (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`.
|
||||
|
||||
Inside that callback every business worker calls `rabbitmq.ConsumeLoop(ctx, ch, parker, queue, rabbitmq.MaxAttempts, process)`. It is the only place that decides Ack / retry / park: a `nil` error acks, `rabbitmq.Permanent(err)` parks immediately, and any other error goes back through the queue's own `<queue>.retry` delay queue until `MaxAttempts` is spent. Parking publishes to `dlx.events` with routing key `parked.<source queue>`, and `FailedEventWorker` persists those messages into the `failed_events` table. Retry counts come from the broker's `x-death` header, never from process memory. A worker dispatches on the message body (`action`) rather than `d.RoutingKey`: the retry hop rewrites the routing key to the queue name.
|
||||
|
||||
### 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
|
||||
- `notification/` — entity for the `notifications` table. Shared by `worker` and `video` so the column tags have exactly one definition; handlers stay in `worker/ssehub.go` and `router.go`.
|
||||
- `observability/` — pprof server registration
|
||||
|
||||
### Database Entities (auto-migrated via GORM)
|
||||
|
||||
`Account`, `Video`, `Like`, `Comment`, `Social`, `OutboxMsg`, `Tag`, `VideoTag`, `Message`, `Notification`, `FailedEvent`
|
||||
|
||||
### 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/CD
|
||||
|
||||
Gitea Actions (`.gitea/workflows/ci.yml`) runs on pushes to `main`/`master` and deploys to production in the same job. The runner label is `aliyun` — a **host-mode** runner on the Aliyun ECS, so steps execute directly on the host (`/opt/vloop`, Docker, rsync) rather than in a disposable container.
|
||||
|
||||
- Backend: `golang:1.24.5` container — `go vet ./...` then `go test -race -count=1 ./...`
|
||||
- Frontend: `node:24-alpine` container — `npm ci` then `npm run build`
|
||||
- Deploy: validates `/opt/vloop/.env`, `rsync`s the workspace to `/opt/vloop`, then `docker compose -f docker-compose.prod.yml up -d --build --wait`
|
||||
|
||||
Host prerequisites: Git ≥ 2.34.1, **Node.js 22** (JavaScript actions such as `actions/checkout@v4` look up `node` on PATH), Docker + Compose v2, `rsync`. Public entrypoint: `http://goanchor.top:9000` (`APP_PORT` overridable). There is no PR gate — a push to `main` deploys immediately.
|
||||
|
||||
## 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.
|
||||
|
||||
The MySQL fixtures each `DropTable` + `AutoMigrate` the shared schema, so run more than one such package at a time with `-p 1`. Without it the packages run in parallel and drop each other's tables (`Error 1050 Table already exists`, `Error 1146 doesn't exist`).
|
||||
|
||||
### 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.
|
||||
|
||||
## Documentation
|
||||
|
||||
Design docs live in `docs/design/` and are written in Chinese. They describe what the code does and why. They are not a spec the code must satisfy: when a doc and the code disagree, the doc is wrong until proven otherwise — fix the doc first, and change code only if the code is actually broken.
|
||||
|
||||
**Never locate code by line number.** Line numbers drift on every edit, so `service.go:496` is wrong within a week. Cite the file plus a stable symbol instead:
|
||||
|
||||
- good: `backend/internal/feed/service.go` 的 `listByHotWindowRedis`
|
||||
- good: `backend/internal/feed/service.go` 的 `hotSnapshotTTL`
|
||||
- good: test name `TestListByPopularity_StaleAsOfIsReplaced`
|
||||
- good: an exact string, e.g. the log line `feed: expire hot snapshot %s failed, dropping it`
|
||||
- bad: `backend/internal/feed/service.go:496-532`
|
||||
|
||||
Inside a code excerpt, the header comment names the file only — the block already shows which function it is. When a paragraph already names the symbol, do not add a path for it.
|
||||
|
||||
Keep each doc current in the same change that touches the behavior it describes. Prefer a table or a short excerpt over prose that repeats the code.
|
||||
|
||||
## Code Comments
|
||||
|
||||
Comments carry the *why* the code cannot say: an invariant, a non-obvious tradeoff, a failure mode, a deliberate omission. Everything else is noise, and noise is what makes real comments invisible.
|
||||
|
||||
- Do not restate the code. No `// 遍历 videos`, no comment that repeats the function name, no changelog (`// 新增于 X`), no attribution.
|
||||
- One short paragraph is the budget, usually one or two lines. If a comment needs five lines to justify a two-line block, rename or restructure the code instead.
|
||||
- Keep the ones that encode a reason: `// RENAMENX 把临时键的 1 分钟 TTL 带给了 dest` earns its line; `// 返回响应` does not.
|
||||
- Write in the file's language — Chinese in `backend/`, matching the surrounding file.
|
||||
- The same limit applies to test intent comments: one sentence saying why the invariant exists, not a recount of the bug.
|
||||
|
||||
## Commit Messages
|
||||
|
||||
Commit messages are Chinese, `type(scope): subject`, and written to the structural rules of ASD-STE100 — target roughly 80 %, which means the text reads simply. This is not a certified STE document; it is a readability standard with two hard parts: short sentences, and terms kept exactly as the code spells them.
|
||||
|
||||
- **One idea per sentence.** Split on `——`, `;` and `:` into separate sentences instead of chaining clauses. Aim for ≤ 30 characters; a sentence with three comma-joined clauses is a rewrite.
|
||||
- **Verb first, active voice.** `只做声明` → `只声明`. No verb-less lines like `DLX 交换机 X + 唯一队列 Y parked.# 绑定`; write `包含 … 和 …` / `以 … 绑定到 …`.
|
||||
- **One paragraph per topic**, opened by its claim (`每个队列必须有独立的重试入口。…`). Use `因此` / `所以` to start the conclusion sentence instead of glueing it on.
|
||||
- **Identifiers stay verbatim**: exchange, queue and routing-key names, type and function names, test names. Never translate, reflow or abbreviate them.
|
||||
- **A term is a fixed phrase, not a word.** A phrase that already appears in code comments or test names is project vocabulary: keep it exactly, and do not borrow one of its words to mean something else. Everything that is not a term uses plain words — do not coin new metaphors, since a metaphor that cannot be `grep`ed is one the next reader has to decode.
|
||||
- When the change is verified by a command, close with a `验证:…` line naming it, e.g. `验证:go test -race -count=1 ./... 全绿`.
|
||||
|
||||
## TDD
|
||||
|
||||
`backend/` 下改行为默认 TDD。前端没有测试运行器,只跑 `npm run build` 再人工点页面,不要称其为 TDD。
|
||||
|
||||
1. **红**——写最小测试,跑,看它失败。确认失败原因是预期的那一个(值不对、没调用、状态码错),不是拼写或 fixture 坏了。
|
||||
2. **绿**——写最小实现,不加「顺手」的抽象和选项。
|
||||
3. **重构**——在绿的前提下清实现和测试名,每步重跑。
|
||||
|
||||
测试与实现同一次提交。改 bug 先写复现测试,把失败断言写进提交信息或 PR 说明。
|
||||
|
||||
## 测试
|
||||
|
||||
- 测试与被测代码同包同目录(`package http`、`package rabbitmq`),一个 `*_test.go` 放在旁边。只有要用公开 API 时才用 `_test` 包。
|
||||
- 命名 `TestSubject_ExpectedBehavior`。一个行为多种输入用表驱动 + `t.Run` + `name string` 字段。
|
||||
- 辅助函数标 `t.Helper()`;共享 fixture 只放 `_test.go`,不进生产包。
|
||||
- 保留意图注释:一句话说明这个不变量为什么存在,不复述 bug。测试注释用中文。
|
||||
- 没有 mock 框架。RabbitMQ 用窄接口手写 fake(如 `fakeConn`),Redis 用 `miniredis`,handler 用 `httptest` + `gin.CreateTestContext`,MySQL 没有 mock——抽窄接口做单测,或对着真库写并注明要先起 infra。
|
||||
- 断言可观察行为(状态码、响应体、落库行、发出的消息),不断言内部调用次数。
|
||||
- 集成测试放 `//go:build integration` 文件,端点走环境变量。缺前置条件就 `t.Skip` 并写原因,静默通过与跳过不等价。
|
||||
- 多个 MySQL fixture 包同时跑要加 `-p 1`,否则互相 `DropTable`。
|
||||
- 单测不碰真实网络,不拿 `time.Sleep` 当同步。测试要过 `-race`,且与执行顺序无关。
|
||||
- 不要为了让套件变快而改小文档化的时间守卫——`TestReadyz_MQEnabledButDisconnected_IsDistinguishable` 那 5 秒就是断言本身。
|
||||
- 覆盖率当评审输入,不当门禁。
|
||||
- 既有测试是契约:不为过审削弱、跳过或删除断言。不变量真变了,就在同一提交里改测试并说明原因。
|
||||
- 新测试需要摸私有字段、睡几秒或起容器,通常是边界画错了——注入依赖,别加脚手架。
|
||||
|
||||
## 文档
|
||||
|
||||
- 设计文档在 `docs/design/`,中文,写代码做什么、为什么。文档不是代码的规格:两者冲突时先改文档,除非代码确实坏了。
|
||||
- 永远不要用行号定位代码。写路径 + 标识符(函数、类型、常量、配置键、测试名、日志原文),不写 `service.go:496`;行号每次改动都会漂移,标识符不会。
|
||||
- 一个概念一个术语。同一篇文档不换同义词,术语在首次出现处定义。
|
||||
- 不写没验证过的内容。未验证的标 `TBD`,并写清怎么确认(问谁、跑哪条命令)。猜测不是事实。
|
||||
- 清单类内容取自源码,再校对:API 列表、配置键、错误码表来自 `go doc`、`router.go` 的路由注册、YAML schema 或常量;手写的部分逐条对照源码。
|
||||
- 不重复 README 的入门内容,给链接。每个事实只写一处。
|
||||
- 文档内引用代码片段时,头部只写文件名,不重复段落已提到的路径。
|
||||
- 行为变了,同一次改动里把对应文档改掉。表格或短片段优于复述代码的散文。
|
||||
|
||||
## 注释
|
||||
|
||||
注释只写代码说不出来的 why:不变量、非显然的取舍、失败模式、刻意省略。
|
||||
|
||||
- 不复述代码,不写变更日志,不写署名。
|
||||
- 一两行就够。需要五行为两行代码辩护,就去重构代码。
|
||||
- 留下承载理由的(`// RENAMENX 把临时键的 1 分钟 TTL 带给了 dest`),删掉复述的(`// 返回响应`)。
|
||||
- 用文件的语言:`backend/` 下用中文。
|
||||
|
||||
## 提交信息
|
||||
|
||||
中文,`type(scope): subject`,按 ASD-STE100 的结构写,约 80% 即可:短句,术语照代码拼写。
|
||||
|
||||
- 一次提交只做一件事。不把无关改动攒进一次提交,不 `git add .` 或 `git commit -a`。拆到单独可回滚、单独可验证的最小单元。
|
||||
- 提交前看 `git status` 与 `git diff --staged`。暂存区里只该有本次要的改动,多出来的拆到下一次。
|
||||
- 一句话一个意思。把 `——`、`;`、`:` 拆成独立句子。目标 ≤ 30 字。
|
||||
- 动词开头,主动语态。`只做声明` → `只声明`。
|
||||
- 一段讲一件事,首句给结论,用 `因此` / `所以` 起结论句。
|
||||
- 标识符原样保留:交换机、队列、路由键、类型名、函数名、测试名。不翻译、不改写、不缩写。
|
||||
- 术语是固定短语:代码注释或测试名里已有的说法就是项目词汇,原样沿用;非术语用平实词,不要造无法 grep 的隐喻。
|
||||
- 有验证命令时,结尾写一行 `验证:…`,如 `验证:go test -race -count=1 ./... 全绿`。
|
||||
|
||||
@@ -1,7 +1,3 @@
|
||||
# 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.
|
||||
所有 Agent 规范都在 [AGENTS.md](AGENTS.md)。改规范请改 AGENTS.md,不要在本文件重复。
|
||||
|
||||
20
README.md
20
README.md
@@ -31,6 +31,24 @@ docker compose up -d --build
|
||||
> 本地开发可直接沿用 `.env.example` 中的公开默认值;生产环境必须自行生成:`openssl rand -hex 32`。
|
||||
> 另外 `docker-compose.prod.yml` 把该变量声明为必填,未设置时 `docker compose up` 会在部署阶段直接报错。
|
||||
|
||||
## 进程分工与扩展约束
|
||||
|
||||
| 进程 | 职责 | 能否多副本 |
|
||||
|------|------|-----------|
|
||||
| API(`go run ./cmd`) | HTTP 接口、SSE 连接、事务内写 `outbox` 行、订阅 Redis 推送并转给本实例的 SSE | 可以。唯一残留的进程内状态是 feed 的 L1 缓存(5 秒 TTL),多实例下同一 key 短时间内可能各读到一份旧值 |
|
||||
| Worker(`go run ./cmd/worker`) | 全部 MQ 消费者(social / like / comment / notification ×3 / parked)、Outbox poller、timeline consumer | **暂只支持单副本**:Outbox poller 多副本会重复投递(下游 `ZADD` 幂等,不会产生脏数据,只是浪费投递) |
|
||||
|
||||
API 进程不再启动任何消费者或轮询器。实时通知的链路是:
|
||||
|
||||
```
|
||||
Worker 落库 notifications → Redis Pub/Sub(v1:notification:push)
|
||||
→ 每个 API 实例的订阅器 → 该实例上的 SSE 连接
|
||||
```
|
||||
|
||||
所以 **Redis 是通知实时性的必要条件**:Redis 不可用时通知仍会落库,只是不会即时出现在页面上,刷新后可见。SSE 的权威数据始终是 `notifications` 表,Pub/Sub 只是"在线时尽快看到"。
|
||||
|
||||
前端目前尚未接入 `EventSource`(见 [`docs/ISSUES-REPORT.md`](docs/ISSUES-REPORT.md) 的 P1-9),这条链路只到浏览器之前。
|
||||
|
||||
## 脚本启动
|
||||
|
||||
```bash
|
||||
@@ -41,7 +59,7 @@ docker compose up -d --build
|
||||
|
||||
```bash
|
||||
START_FRONTEND=0 ./start.sh # API + Worker
|
||||
START_WORKER=0 ./start.sh # API + 前端
|
||||
START_WORKER=0 ./start.sh # 只起 API + 前端(通知与 timeline 不再被消费,仅适合调 HTTP 接口)
|
||||
STOP_DOCKER=1 ./start.sh # 退出时停止脚本拉起的 compose 服务
|
||||
CONFIG_PATH=configs/config.yaml ./start.sh
|
||||
```
|
||||
|
||||
@@ -2,6 +2,7 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"feedsystem_video_go/internal/auth"
|
||||
"feedsystem_video_go/internal/config"
|
||||
"feedsystem_video_go/internal/db"
|
||||
@@ -10,8 +11,11 @@ import (
|
||||
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||||
"feedsystem_video_go/internal/observability"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strconv"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/joho/godotenv"
|
||||
@@ -100,10 +104,46 @@ func main() {
|
||||
defer pprofServer.Close()
|
||||
}
|
||||
|
||||
// 进程生命周期:SIGINT/SIGTERM 后先停止接收新请求,再等在途请求结束。
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
|
||||
// 设置路由
|
||||
r := apphttp.SetRouter(sqlDB, cache, rmq)
|
||||
log.Printf("Server is running on port %d", cfg.Server.Port)
|
||||
if err := r.Run(":" + strconv.Itoa(cfg.Server.Port)); err != nil {
|
||||
log.Fatalf("Failed to run server: %v", err)
|
||||
r := apphttp.SetRouter(ctx, sqlDB, cache, rmq)
|
||||
srv := &http.Server{
|
||||
Addr: ":" + strconv.Itoa(cfg.Server.Port),
|
||||
Handler: r,
|
||||
ReadHeaderTimeout: 10 * time.Second,
|
||||
}
|
||||
|
||||
// ListenAndServe 在 goroutine 里跑,主协程负责等待信号或启动失败。
|
||||
serverErr := make(chan error, 1)
|
||||
go func() {
|
||||
log.Printf("Server is running on port %d", cfg.Server.Port)
|
||||
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
serverErr <- err
|
||||
}
|
||||
}()
|
||||
|
||||
select {
|
||||
case err := <-serverErr:
|
||||
log.Printf("Failed to run server: %v", err)
|
||||
stop()
|
||||
_ = srv.Close()
|
||||
return
|
||||
case <-ctx.Done():
|
||||
}
|
||||
|
||||
// 恢复默认信号处理:第二次 Ctrl-C 立刻强杀,而不是卡在 Shutdown 里。
|
||||
stop()
|
||||
|
||||
log.Printf("API shutting down...")
|
||||
// SSE 连接已随 ctx 断开,这里等的是普通在途请求;超时则 Close 兜底。
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
if err := srv.Shutdown(shutdownCtx); err != nil {
|
||||
log.Printf("API graceful shutdown failed (forcing close): %v", err)
|
||||
_ = srv.Close()
|
||||
}
|
||||
log.Printf("API stopped")
|
||||
}
|
||||
|
||||
@@ -9,12 +9,12 @@ import (
|
||||
mqrabbit "feedsystem_video_go/internal/middleware/rabbitmq"
|
||||
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||||
"feedsystem_video_go/internal/observability"
|
||||
"feedsystem_video_go/internal/social"
|
||||
"feedsystem_video_go/internal/video"
|
||||
"feedsystem_video_go/internal/worker"
|
||||
"log"
|
||||
"os"
|
||||
"os/signal"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
@@ -23,6 +23,9 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// 消费者正常毫秒级退出;超时说明 handler 卡在 I/O 上,不再无限等待。
|
||||
const workerShutdownTimeout = 10 * time.Second
|
||||
|
||||
// 带重试机制的基础设施连接函数
|
||||
func connectWithRetry(name string, maxRetries int, fn func() error) {
|
||||
for i := 0; i < maxRetries; i++ {
|
||||
@@ -106,13 +109,11 @@ func main() {
|
||||
|
||||
// 登记拓扑:每一代连接都会重放。名字一律取自 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},
|
||||
)
|
||||
|
||||
// 准备 repo
|
||||
socialRepo := social.NewSocialRepository(sqlDB)
|
||||
videoRepo := video.NewVideoRepository(sqlDB)
|
||||
likeRepo := video.NewLikeRepository(sqlDB)
|
||||
commentRepo := video.NewCommentRepository(sqlDB)
|
||||
@@ -133,24 +134,79 @@ func main() {
|
||||
defer pprofServer.Close()
|
||||
}
|
||||
|
||||
// 这两类事件最终由本进程消费,拓扑因此在这里声明。
|
||||
rmqMgr.RegisterTopology(
|
||||
mqrabbit.Topology{Exchange: mqrabbit.LikeExchange, Queue: mqrabbit.NotificationLikeQueue, BindingKey: mqrabbit.LikeLikeRK},
|
||||
mqrabbit.Topology{Exchange: mqrabbit.CommentExchange, Queue: mqrabbit.NotificationCommentQueue, BindingKey: mqrabbit.CommentPublishRK},
|
||||
mqrabbit.Topology{Exchange: mqrabbit.SocialExchange, Queue: mqrabbit.NotificationSocialQueue, BindingKey: mqrabbit.SocialFollowRK},
|
||||
)
|
||||
|
||||
// Outbox 投递只有 Worker 一个执行者,不随 API 实例数复制。
|
||||
timelineMQ, err := mqrabbit.NewTimelineMQ(rmqMgr)
|
||||
if err != nil {
|
||||
log.Printf("timelineMQ init failed (timeline consumer disabled): %v", err)
|
||||
timelineMQ = nil
|
||||
}
|
||||
|
||||
// Worker 不持有 SSE 连接:通知经 Redis 广播给每个 API 实例。
|
||||
notificationHub := worker.NewRedisNotificationPublisher(cache)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
run := func(fn func()) {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
fn()
|
||||
}()
|
||||
}
|
||||
|
||||
// 停泊消费者排在最前面:它是最后一道防线,越早可用,停泊后无人接收的窗口越小。
|
||||
// prefetch=1 是刻意背压,落库慢时不要一次抓 10 条进内存。
|
||||
go mqrabbit.RunConsumer(ctx, rmqMgr, "FailedEventWorker", 1, func(ch *amqp.Channel) error {
|
||||
return worker.NewFailedEventWorker(ch, failedEventRepo, mqrabbit.ParkedQueue).Run(ctx)
|
||||
run(func() {
|
||||
mqrabbit.RunConsumer(ctx, rmqMgr, "FailedEventWorker", 1, func(ch *amqp.Channel) error {
|
||||
return worker.NewFailedEventWorker(ch, failedEventRepo, mqrabbit.ParkedQueue).Run(ctx)
|
||||
})
|
||||
})
|
||||
go mqrabbit.RunConsumer(ctx, rmqMgr, "SocialWorker", 50, func(ch *amqp.Channel) error {
|
||||
return worker.NewSocialWorker(ch, rmqMgr, socialRepo, mqrabbit.SocialQueue).Run(ctx)
|
||||
run(func() {
|
||||
mqrabbit.RunConsumer(ctx, rmqMgr, "LikeWorker", 50, func(ch *amqp.Channel) error {
|
||||
return worker.NewLikeWorker(ch, rmqMgr, likeRepo, videoRepo, cache, mqrabbit.LikeQueue).Run(ctx)
|
||||
})
|
||||
})
|
||||
go mqrabbit.RunConsumer(ctx, rmqMgr, "LikeWorker", 50, func(ch *amqp.Channel) error {
|
||||
return worker.NewLikeWorker(ch, rmqMgr, likeRepo, videoRepo, cache, mqrabbit.LikeQueue).Run(ctx)
|
||||
})
|
||||
go mqrabbit.RunConsumer(ctx, rmqMgr, "CommentWorker", 50, func(ch *amqp.Channel) error {
|
||||
return worker.NewCommentWorker(ch, rmqMgr, commentRepo, videoRepo, cache, mqrabbit.CommentQueue).Run(ctx)
|
||||
run(func() {
|
||||
mqrabbit.RunConsumer(ctx, rmqMgr, "CommentWorker", 50, func(ch *amqp.Channel) error {
|
||||
return worker.NewCommentWorker(ch, rmqMgr, commentRepo, videoRepo, cache, mqrabbit.CommentQueue).Run(ctx)
|
||||
})
|
||||
})
|
||||
|
||||
// 等待退出信号
|
||||
// 通知消费者:三个队列各自一个 channel,一个队列阻塞不会拖住另外两个。
|
||||
for _, queue := range []string{
|
||||
mqrabbit.NotificationLikeQueue,
|
||||
mqrabbit.NotificationCommentQueue,
|
||||
mqrabbit.NotificationSocialQueue,
|
||||
} {
|
||||
run(func() {
|
||||
mqrabbit.RunConsumer(ctx, rmqMgr, "notification-"+queue, 10, func(ch *amqp.Channel) error {
|
||||
return worker.NewNotificationWorker(ch, rmqMgr, sqlDB, queue, notificationHub).Run(ctx)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
run(func() { worker.StartOutboxPoller(ctx, sqlDB, timelineMQ) })
|
||||
run(func() { worker.StartConsumer(ctx, rmqMgr, mqrabbit.TimelineQueue, cache) })
|
||||
|
||||
// 等消费者真正返回,而不是用固定 sleep 猜。
|
||||
<-ctx.Done()
|
||||
log.Printf("Worker shutting down...")
|
||||
time.Sleep(2 * time.Second) // 等待正在处理的消息完成
|
||||
log.Printf("Worker stopped")
|
||||
|
||||
stopped := make(chan struct{})
|
||||
go func() {
|
||||
wg.Wait()
|
||||
close(stopped)
|
||||
}()
|
||||
select {
|
||||
case <-stopped:
|
||||
log.Printf("Worker stopped")
|
||||
case <-time.After(workerShutdownTimeout):
|
||||
log.Printf("Worker stopped (timeout waiting for consumers)")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,11 +17,11 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func SetRouter(db *gorm.DB, cache *rediscache.Client, rmq *rabbitmq.RabbitMQ) *gin.Engine {
|
||||
// SetRouter 只装配 HTTP 入口;ctx 是进程生命周期,订阅器与 SSE 连接随它退出。
|
||||
func SetRouter(ctx context.Context, db *gorm.DB, cache *rediscache.Client, rmq *rabbitmq.RabbitMQ) *gin.Engine {
|
||||
r := gin.Default()
|
||||
if err := r.SetTrustedProxies(nil); err != nil {
|
||||
log.Printf("SetTrustedProxies failed: %v", err)
|
||||
@@ -212,47 +212,18 @@ func SetRouter(db *gorm.DB, cache *rediscache.Client, rmq *rabbitmq.RabbitMQ) *g
|
||||
protectedMessageGroup.POST("/send", messageHandler.Send)
|
||||
protectedMessageGroup.POST("/list", messageHandler.List)
|
||||
}
|
||||
// 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(context.Background(), rmq, rabbitmq.TimelineQueue, cache)
|
||||
|
||||
// SSE notification
|
||||
sseHub := worker.NewSSEHub(db)
|
||||
// 通知由 Worker 落库并发布到 Redis,本进程只把它推给本地连接。
|
||||
sseHub := worker.NewSSEHub(ctx, db)
|
||||
notifGroup := r.Group("/notification")
|
||||
notifGroup.Use(sseHub.SSERequireAuth())
|
||||
sseHub.RegisterRoutes(r, notifGroup)
|
||||
|
||||
// 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, rmq, db, queue, sseHub).Run(context.Background())
|
||||
})
|
||||
}
|
||||
} else {
|
||||
log.Printf("Notification SSE disabled (MQ not available)")
|
||||
}
|
||||
worker.StartNotificationSubscriber(ctx, cache, sseHub)
|
||||
|
||||
// 所有 publisher / consumer 都已登记拓扑:在【当前】连接上立即声明一遍。
|
||||
// 重连时管理器会自动重放,因此这里只需处理"首次连接早于拓扑登记"的启动顺序。
|
||||
// 用带超时的 ctx,避免连接恰在此刻断开时把 API 启动挂住。
|
||||
if rmq != nil {
|
||||
initCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
initCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
if err := rmq.EnsureTopology(initCtx); err != nil {
|
||||
log.Printf("rabbitmq topology init failed (will be redeclared on reconnect): %v", err)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
@@ -27,7 +28,28 @@ func doGet(t *testing.T, r *gin.Engine, path string) (int, map[string]any) {
|
||||
func newRouterForTest(t *testing.T, rmq *mqrabbit.RabbitMQ) *gin.Engine {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
return SetRouter(nil, nil, rmq)
|
||||
return SetRouter(context.Background(), nil, nil, rmq)
|
||||
}
|
||||
|
||||
// 消费者搬到 Worker 之后,SSE 与列表/已读接口仍必须留在 API。
|
||||
func TestRouter_NotificationRoutesRegistered(t *testing.T) {
|
||||
r := newRouterForTest(t, nil)
|
||||
|
||||
want := []string{
|
||||
"GET /notification/stream",
|
||||
"POST /notification/list",
|
||||
"POST /notification/markRead",
|
||||
"POST /notification/unreadCount",
|
||||
}
|
||||
registered := make(map[string]bool, len(want))
|
||||
for _, route := range r.Routes() {
|
||||
registered[route.Method+" "+route.Path] = true
|
||||
}
|
||||
for _, route := range want {
|
||||
if !registered[route] {
|
||||
t.Errorf("route %q is not registered", route)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 这是 /readyz 存在的全部意义所在,也是最容易被后人"顺手合并"掉的不变式:
|
||||
|
||||
@@ -27,10 +27,7 @@ func TestTopologyConstants_WireNamesAreStable(t *testing.T) {
|
||||
{"CommentDeleteRK", CommentDeleteRK, "comment.delete"},
|
||||
|
||||
{"SocialExchange", SocialExchange, "social.events"},
|
||||
{"SocialQueue", SocialQueue, "social.events"},
|
||||
{"SocialBindingKey", SocialBindingKey, "social.*"},
|
||||
{"SocialFollowRK", SocialFollowRK, "social.follow"},
|
||||
{"SocialUnfollowRK", SocialUnfollowRK, "social.unfollow"},
|
||||
|
||||
{"TimelineExchange", TimelineExchange, "video.timeline.events"},
|
||||
{"TimelineQueue", TimelineQueue, "video.timeline.update.queue"},
|
||||
|
||||
@@ -9,6 +9,7 @@ package rabbitmq
|
||||
//
|
||||
// 与主队列的区别:主队列用通配键(like.* 等)收全部动作,因为 DB 需要同步
|
||||
// 点赞与取消点赞两个方向;通知只关心"发生过",取关 / 删评论不需要推送。
|
||||
// 关注没有 DB 同步队列:写库在 API 内完成,social.events 只承载通知。
|
||||
//
|
||||
// 这三个队列原先以字符串字面量写在 internal/http/router.go 里,导致
|
||||
// rabbitmq 包与 http 包各存一份"线缆契约"。改为导出常量后,登记拓扑
|
||||
|
||||
@@ -13,12 +13,9 @@ type SocialMQ struct {
|
||||
|
||||
// 拓扑常量导出:见 likeMQ.go 中的说明。
|
||||
const (
|
||||
SocialExchange = "social.events"
|
||||
SocialQueue = "social.events"
|
||||
SocialBindingKey = "social.*"
|
||||
SocialExchange = "social.events"
|
||||
|
||||
SocialFollowRK = "social.follow"
|
||||
SocialUnfollowRK = "social.unfollow"
|
||||
SocialFollowRK = "social.follow"
|
||||
)
|
||||
|
||||
type SocialEvent struct {
|
||||
@@ -29,11 +26,12 @@ type SocialEvent struct {
|
||||
OccurredAt time.Time `json:"occurred_at"`
|
||||
}
|
||||
|
||||
// NewSocialMQ 只登记关注通知的落点:服务层已先写库,事件不再承担写库职责。
|
||||
func NewSocialMQ(base *RabbitMQ) (*SocialMQ, error) {
|
||||
if base == nil {
|
||||
return nil, errors.New("rabbitmq base is nil")
|
||||
}
|
||||
base.RegisterTopology(Topology{Exchange: SocialExchange, Queue: SocialQueue, BindingKey: SocialBindingKey})
|
||||
base.RegisterTopology(Topology{Exchange: SocialExchange, Queue: NotificationSocialQueue, BindingKey: SocialFollowRK})
|
||||
return &SocialMQ{mgr: base}, nil
|
||||
}
|
||||
|
||||
@@ -41,10 +39,6 @@ func (s *SocialMQ) Follow(ctx context.Context, followerID, vloggerID uint) error
|
||||
return s.publish(ctx, "follow", SocialFollowRK, followerID, vloggerID)
|
||||
}
|
||||
|
||||
func (s *SocialMQ) UnFollow(ctx context.Context, followerID, vloggerID uint) error {
|
||||
return s.publish(ctx, "unfollow", SocialUnfollowRK, followerID, vloggerID)
|
||||
}
|
||||
|
||||
func (s *SocialMQ) publish(ctx context.Context, action, routingKey string, followerID, vloggerID uint) error {
|
||||
if s == nil || s.mgr == nil {
|
||||
return errors.New("social mq is not initialized")
|
||||
|
||||
@@ -103,6 +103,27 @@ func (c *Client) Unlock(ctx context.Context, key string, token string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// 频道名由调用方用 Key 加前缀,多环境共享同一 Redis 时不串台。
|
||||
func (c *Client) Publish(ctx context.Context, channel string, payload []byte) error {
|
||||
if c == nil || c.rdb == nil {
|
||||
return errors.New("redis client not initialized")
|
||||
}
|
||||
return c.rdb.Publish(ctx, channel, payload).Err()
|
||||
}
|
||||
|
||||
// Subscribe 返回前等 broker 确认订阅生效,避免丢第一批消息;PubSub 由调用方 Close。
|
||||
func (c *Client) Subscribe(ctx context.Context, channel string) (*redis.PubSub, error) {
|
||||
if c == nil || c.rdb == nil {
|
||||
return nil, errors.New("redis client not initialized")
|
||||
}
|
||||
ps := c.rdb.Subscribe(ctx, channel)
|
||||
if _, err := ps.Receive(ctx); err != nil {
|
||||
_ = ps.Close()
|
||||
return nil, err
|
||||
}
|
||||
return ps, nil
|
||||
}
|
||||
|
||||
func (c *Client) IncrementWithExpire(ctx context.Context, key string, expire time.Duration) (int64, error) {
|
||||
if c == nil || c.rdb == nil {
|
||||
return 0, nil
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package social
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"feedsystem_video_go/internal/account"
|
||||
"feedsystem_video_go/internal/apierror"
|
||||
"feedsystem_video_go/internal/middleware/jwt"
|
||||
@@ -9,6 +10,14 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// classifySocialError 只补一条本地语义:自关注是客户端错误,不是数据库故障。
|
||||
func classifySocialError(err error) int {
|
||||
if errors.Is(err, ErrCannotFollowSelf) {
|
||||
return http.StatusBadRequest
|
||||
}
|
||||
return apierror.ClassifyHTTPStatus(err)
|
||||
}
|
||||
|
||||
type SocialHandler struct {
|
||||
service *SocialService
|
||||
}
|
||||
@@ -36,11 +45,12 @@ func (h *SocialHandler) Follow(c *gin.Context) {
|
||||
FollowerID: FollowerID,
|
||||
VloggerID: req.VloggerID,
|
||||
}
|
||||
if err := h.service.Follow(c.Request.Context(), social); err != nil {
|
||||
c.JSON(apierror.ClassifyHTTPStatus(err), gin.H{"error": err.Error()})
|
||||
created, err := h.service.Follow(c.Request.Context(), social)
|
||||
if err != nil {
|
||||
c.JSON(classifySocialError(err), gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"message": "followed"})
|
||||
c.JSON(http.StatusOK, gin.H{"message": "followed", "created": created})
|
||||
}
|
||||
|
||||
func (h *SocialHandler) Unfollow(c *gin.Context) {
|
||||
@@ -62,11 +72,12 @@ func (h *SocialHandler) Unfollow(c *gin.Context) {
|
||||
FollowerID: FollowerID,
|
||||
VloggerID: req.VloggerID,
|
||||
}
|
||||
if err := h.service.Unfollow(c.Request.Context(), social); err != nil {
|
||||
c.JSON(apierror.ClassifyHTTPStatus(err), gin.H{"error": err.Error()})
|
||||
deleted, err := h.service.Unfollow(c.Request.Context(), social)
|
||||
if err != nil {
|
||||
c.JSON(classifySocialError(err), gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"message": "unfollowed"})
|
||||
c.JSON(http.StatusOK, gin.H{"message": "unfollowed", "deleted": deleted})
|
||||
}
|
||||
|
||||
func (h *SocialHandler) GetAllFollowers(c *gin.Context) {
|
||||
|
||||
85
backend/internal/social/handler_test.go
Normal file
85
backend/internal/social/handler_test.go
Normal file
@@ -0,0 +1,85 @@
|
||||
package social
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func newTestHandler(t *testing.T) (*SocialHandler, *fakeStore) {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
store := newFakeStore()
|
||||
notifier := &fakeNotifier{}
|
||||
return NewSocialHandler(newTestService(store, fakeAccounts{}, notifier)), store
|
||||
}
|
||||
|
||||
func postSocial(t *testing.T, h *SocialHandler, accountID uint, action, body string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/social/"+action, strings.NewReader(body))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
c.Set("accountID", accountID)
|
||||
if action == "follow" {
|
||||
h.Follow(c)
|
||||
} else {
|
||||
h.Unfollow(c)
|
||||
}
|
||||
return w
|
||||
}
|
||||
|
||||
func TestSocialHandler_Follow_SelfReturnsBadRequest(t *testing.T) {
|
||||
h, _ := newTestHandler(t)
|
||||
|
||||
w := postSocial(t, h, 1, "follow", `{"vlogger_id":1}`)
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("自关注状态码 = %d,想要 %d", w.Code, http.StatusBadRequest)
|
||||
}
|
||||
if !strings.Contains(w.Body.String(), "can not follow self") {
|
||||
t.Fatalf("响应体 = %s,想要包含 can not follow self", w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSocialHandler_Follow_DuplicateReturnsOK(t *testing.T) {
|
||||
h, store := newTestHandler(t)
|
||||
store.rows[[2]uint{1, 2}] = true
|
||||
|
||||
w := postSocial(t, h, 1, "follow", `{"vlogger_id":2}`)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("重复关注状态码 = %d,想要 %d", w.Code, http.StatusOK)
|
||||
}
|
||||
var resp struct {
|
||||
Message string `json:"message"`
|
||||
Created bool `json:"created"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("解析响应体失败: %v", err)
|
||||
}
|
||||
if resp.Message != "followed" || resp.Created {
|
||||
t.Fatalf("重复关注响应 = %+v,想要 message=followed created=false", resp)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSocialHandler_Unfollow_DuplicateReturnsOK(t *testing.T) {
|
||||
h, _ := newTestHandler(t)
|
||||
|
||||
w := postSocial(t, h, 1, "unfollow", `{"vlogger_id":2}`)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("重复取关状态码 = %d,想要 %d", w.Code, http.StatusOK)
|
||||
}
|
||||
var resp struct {
|
||||
Message string `json:"message"`
|
||||
Deleted bool `json:"deleted"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("解析响应体失败: %v", err)
|
||||
}
|
||||
if resp.Message != "unfollowed" || resp.Deleted {
|
||||
t.Fatalf("重复取关响应 = %+v,想要 message=unfollowed deleted=false", resp)
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"feedsystem_video_go/internal/account"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
type SocialRepository struct {
|
||||
@@ -15,14 +16,27 @@ func NewSocialRepository(db *gorm.DB) *SocialRepository {
|
||||
return &SocialRepository{db: db}
|
||||
}
|
||||
|
||||
func (r *SocialRepository) Follow(ctx context.Context, social *Social) error {
|
||||
return r.db.WithContext(ctx).Create(social).Error
|
||||
// Follow 返回本次是否真的插入关系:重复关注是幂等成功,不是错误。
|
||||
// 判重交给唯一索引 idx_social_follower_vlogger,OnConflict 把冲突变成一次不报错的 SQL。
|
||||
func (r *SocialRepository) Follow(ctx context.Context, social *Social) (bool, error) {
|
||||
res := r.db.WithContext(ctx).
|
||||
Clauses(clause.OnConflict{DoNothing: true}).
|
||||
Create(social)
|
||||
if res.Error != nil {
|
||||
return false, res.Error
|
||||
}
|
||||
return res.RowsAffected > 0, nil
|
||||
}
|
||||
|
||||
func (r *SocialRepository) Unfollow(ctx context.Context, social *Social) error {
|
||||
return r.db.WithContext(ctx).
|
||||
// Unfollow 用影响行数回答"这次是否真的删掉":第二次取关是空操作。
|
||||
func (r *SocialRepository) Unfollow(ctx context.Context, social *Social) (bool, error) {
|
||||
res := r.db.WithContext(ctx).
|
||||
Where("follower_id = ? AND vlogger_id = ?", social.FollowerID, social.VloggerID).
|
||||
Delete(&Social{}).Error
|
||||
Delete(&Social{})
|
||||
if res.Error != nil {
|
||||
return false, res.Error
|
||||
}
|
||||
return res.RowsAffected > 0, nil
|
||||
}
|
||||
|
||||
func (r *SocialRepository) GetAllFollowers(ctx context.Context, VloggerID uint) ([]*account.Account, error) {
|
||||
|
||||
87
backend/internal/social/repo_integration_test.go
Normal file
87
backend/internal/social/repo_integration_test.go
Normal file
@@ -0,0 +1,87 @@
|
||||
//go:build integration
|
||||
|
||||
package social
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
)
|
||||
|
||||
// 判重由唯一索引 idx_social_follower_vlogger 裁决,"这次有没有真的写入"只能对着
|
||||
// 真实 MySQL 验证:没有数据库就没有被测对象。
|
||||
//
|
||||
// MYSQL_TEST_DSN='root:123456@tcp(127.0.0.1:3306)/feedsystem_test?charset=utf8mb4&parseTime=True&loc=Local' \
|
||||
// go test -tags integration -count=1 ./internal/social/
|
||||
|
||||
func newSocialTestDB(t *testing.T) *gorm.DB {
|
||||
t.Helper()
|
||||
dsn := os.Getenv("MYSQL_TEST_DSN")
|
||||
if dsn == "" {
|
||||
t.Skip("MYSQL_TEST_DSN 未设置:需要真实 MySQL(见本文件顶部注释)")
|
||||
}
|
||||
if strings.Contains(dsn, "clientFoundRows") {
|
||||
t.Fatalf("测试 DSN 不能带 clientFoundRows:它会让 RowsAffected 判重失效")
|
||||
}
|
||||
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
|
||||
Logger: logger.Default.LogMode(logger.Silent),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("connect mysql: %v", err)
|
||||
}
|
||||
if err := db.Migrator().DropTable(&Social{}); err != nil {
|
||||
t.Fatalf("drop table: %v", err)
|
||||
}
|
||||
if err := db.AutoMigrate(&Social{}); err != nil {
|
||||
t.Fatalf("migrate: %v", err)
|
||||
}
|
||||
return db
|
||||
}
|
||||
|
||||
func TestSocialRepository_Follow_DuplicateReportsNotCreated(t *testing.T) {
|
||||
db := newSocialTestDB(t)
|
||||
repo := NewSocialRepository(db)
|
||||
ctx := context.Background()
|
||||
|
||||
created, err := repo.Follow(ctx, &Social{FollowerID: 1, VloggerID: 2})
|
||||
if err != nil || !created {
|
||||
t.Fatalf("首次关注 = (%v, %v),想要 (true, nil)", created, err)
|
||||
}
|
||||
|
||||
created, err = repo.Follow(ctx, &Social{FollowerID: 1, VloggerID: 2})
|
||||
if err != nil || created {
|
||||
t.Fatalf("重复关注 = (%v, %v),想要 (false, nil)", created, err)
|
||||
}
|
||||
|
||||
var count int64
|
||||
if err := db.Model(&Social{}).Count(&count).Error; err != nil {
|
||||
t.Fatalf("count: %v", err)
|
||||
}
|
||||
if count != 1 {
|
||||
t.Fatalf("socials 行数 = %d,想要 1", count)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSocialRepository_Unfollow_SecondCallReportsNotDeleted(t *testing.T) {
|
||||
db := newSocialTestDB(t)
|
||||
repo := NewSocialRepository(db)
|
||||
ctx := context.Background()
|
||||
if _, err := repo.Follow(ctx, &Social{FollowerID: 3, VloggerID: 4}); err != nil {
|
||||
t.Fatalf("准备关注失败: %v", err)
|
||||
}
|
||||
|
||||
deleted, err := repo.Unfollow(ctx, &Social{FollowerID: 3, VloggerID: 4})
|
||||
if err != nil || !deleted {
|
||||
t.Fatalf("首次取关 = (%v, %v),想要 (true, nil)", deleted, err)
|
||||
}
|
||||
|
||||
deleted, err = repo.Unfollow(ctx, &Social{FollowerID: 3, VloggerID: 4})
|
||||
if err != nil || deleted {
|
||||
t.Fatalf("重复取关 = (%v, %v),想要 (false, nil)", deleted, err)
|
||||
}
|
||||
}
|
||||
@@ -4,91 +4,92 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"feedsystem_video_go/internal/account"
|
||||
"feedsystem_video_go/internal/middleware/rabbitmq"
|
||||
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||||
"log"
|
||||
)
|
||||
|
||||
// ErrCannotFollowSelf 是客户端错误:自关注不写库,也不发消息。
|
||||
var ErrCannotFollowSelf = errors.New("can not follow self")
|
||||
|
||||
// socialStore 只声明 SocialService 用到的方法,测试里用 fake 驱动。
|
||||
type socialStore interface {
|
||||
Follow(ctx context.Context, social *Social) (bool, error)
|
||||
Unfollow(ctx context.Context, social *Social) (bool, error)
|
||||
IsFollowed(ctx context.Context, social *Social) (bool, error)
|
||||
GetAllFollowers(ctx context.Context, vloggerID uint) ([]*account.Account, error)
|
||||
GetAllVloggers(ctx context.Context, followerID uint) ([]*account.Account, error)
|
||||
CountFollowers(ctx context.Context, vloggerID uint) (int64, error)
|
||||
CountVloggers(ctx context.Context, followerID uint) (int64, error)
|
||||
}
|
||||
|
||||
type accountFinder interface {
|
||||
FindByID(ctx context.Context, id uint) (*account.Account, error)
|
||||
}
|
||||
|
||||
// followNotifier 只暴露关注通知。真实实现 *rabbitmq.SocialMQ 在 nil 接收者上返回 error,
|
||||
// 所以 MQ 未启用时这里只会多一条日志。
|
||||
type followNotifier interface {
|
||||
Follow(ctx context.Context, followerID, vloggerID uint) error
|
||||
}
|
||||
|
||||
type SocialService struct {
|
||||
repo *SocialRepository
|
||||
accountrepo *account.AccountRepository
|
||||
socialMQ *rabbitmq.SocialMQ
|
||||
repo socialStore
|
||||
accountrepo accountFinder
|
||||
socialMQ followNotifier
|
||||
cache *rediscache.Client
|
||||
}
|
||||
|
||||
func NewSocialService(repo *SocialRepository, accountrepo *account.AccountRepository, socialMQ *rabbitmq.SocialMQ, cache *rediscache.Client) *SocialService {
|
||||
func NewSocialService(repo socialStore, accountrepo accountFinder, socialMQ followNotifier, cache *rediscache.Client) *SocialService {
|
||||
return &SocialService{repo: repo, accountrepo: accountrepo, socialMQ: socialMQ, cache: cache}
|
||||
}
|
||||
|
||||
func (s *SocialService) Follow(ctx context.Context, social *Social) error {
|
||||
_, err := s.accountrepo.FindByID(ctx, social.FollowerID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = s.accountrepo.FindByID(ctx, social.VloggerID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Follow 返回本次是否真的插入关系:重复关注返回 (false, nil)。
|
||||
func (s *SocialService) Follow(ctx context.Context, social *Social) (bool, error) {
|
||||
if social.FollowerID == social.VloggerID {
|
||||
return errors.New("can not follow self")
|
||||
return false, ErrCannotFollowSelf
|
||||
}
|
||||
isFollowed, err := s.repo.IsFollowed(ctx, social)
|
||||
if _, err := s.accountrepo.FindByID(ctx, social.FollowerID); err != nil {
|
||||
return false, err
|
||||
}
|
||||
if _, err := s.accountrepo.FindByID(ctx, social.VloggerID); err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
created, err := s.repo.Follow(ctx, social)
|
||||
if err != nil {
|
||||
return err
|
||||
return false, err
|
||||
}
|
||||
if isFollowed {
|
||||
return errors.New("already followed")
|
||||
if !created {
|
||||
// 关系已在,缓存和通知都已经是“已关注”状态。
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// 先写 DB,确保数据持久化
|
||||
if err := s.repo.Follow(ctx, social); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// DB 成功后,失效该用户的关注列表缓存
|
||||
s.invalidateFollowingFeedCache(context.Background(), social.FollowerID)
|
||||
|
||||
// 最后发 MQ(用于通知),失败只记日志不影响业务
|
||||
if s.socialMQ != nil {
|
||||
if err := s.socialMQ.Follow(ctx, social.FollowerID, social.VloggerID); err != nil {
|
||||
log.Printf("social MQ Follow 发布失败: %v", err)
|
||||
}
|
||||
if err := s.socialMQ.Follow(ctx, social.FollowerID, social.VloggerID); err != nil {
|
||||
log.Printf("social MQ Follow 发布失败: %v", err)
|
||||
}
|
||||
return nil
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (s *SocialService) Unfollow(ctx context.Context, social *Social) error {
|
||||
_, err := s.accountrepo.FindByID(ctx, social.FollowerID)
|
||||
if err != nil {
|
||||
return err
|
||||
// Unfollow 返回本次是否真的删掉关系:重复取关返回 (false, nil)。
|
||||
func (s *SocialService) Unfollow(ctx context.Context, social *Social) (bool, error) {
|
||||
if _, err := s.accountrepo.FindByID(ctx, social.FollowerID); err != nil {
|
||||
return false, err
|
||||
}
|
||||
_, err = s.accountrepo.FindByID(ctx, social.VloggerID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
isFollowed, err := s.repo.IsFollowed(ctx, social)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !isFollowed {
|
||||
return errors.New("not followed")
|
||||
if _, err := s.accountrepo.FindByID(ctx, social.VloggerID); err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
// 先写 DB
|
||||
if err := s.repo.Unfollow(ctx, social); err != nil {
|
||||
return err
|
||||
deleted, err := s.repo.Unfollow(ctx, social)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if !deleted {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// 失效缓存
|
||||
s.invalidateFollowingFeedCache(context.Background(), social.FollowerID)
|
||||
|
||||
// 最后发 MQ
|
||||
if s.socialMQ != nil {
|
||||
if err := s.socialMQ.UnFollow(ctx, social.FollowerID, social.VloggerID); err != nil {
|
||||
log.Printf("social MQ UnFollow 发布失败: %v", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// 失效关注列表缓存,确保下次查询时能获取到最新的关注列表
|
||||
|
||||
193
backend/internal/social/service_test.go
Normal file
193
backend/internal/social/service_test.go
Normal file
@@ -0,0 +1,193 @@
|
||||
package social
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"feedsystem_video_go/internal/account"
|
||||
)
|
||||
|
||||
// fakeStore 用内存行模拟 socials 表:返回值就是"这张表这次有没有变"。
|
||||
type fakeStore struct {
|
||||
rows map[[2]uint]bool
|
||||
err error
|
||||
}
|
||||
|
||||
func newFakeStore() *fakeStore {
|
||||
return &fakeStore{rows: map[[2]uint]bool{}}
|
||||
}
|
||||
|
||||
func (f *fakeStore) Follow(ctx context.Context, social *Social) (bool, error) {
|
||||
if f.err != nil {
|
||||
return false, f.err
|
||||
}
|
||||
key := [2]uint{social.FollowerID, social.VloggerID}
|
||||
if f.rows[key] {
|
||||
return false, nil
|
||||
}
|
||||
f.rows[key] = true
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) Unfollow(ctx context.Context, social *Social) (bool, error) {
|
||||
if f.err != nil {
|
||||
return false, f.err
|
||||
}
|
||||
key := [2]uint{social.FollowerID, social.VloggerID}
|
||||
if !f.rows[key] {
|
||||
return false, nil
|
||||
}
|
||||
delete(f.rows, key)
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) IsFollowed(ctx context.Context, social *Social) (bool, error) {
|
||||
return f.rows[[2]uint{social.FollowerID, social.VloggerID}], nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) GetAllFollowers(ctx context.Context, vloggerID uint) ([]*account.Account, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) GetAllVloggers(ctx context.Context, followerID uint) ([]*account.Account, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) CountFollowers(ctx context.Context, vloggerID uint) (int64, error) {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) CountVloggers(ctx context.Context, followerID uint) (int64, error) {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
type fakeAccounts struct {
|
||||
err error
|
||||
}
|
||||
|
||||
func (f fakeAccounts) FindByID(ctx context.Context, id uint) (*account.Account, error) {
|
||||
if f.err != nil {
|
||||
return nil, f.err
|
||||
}
|
||||
return &account.Account{ID: id}, nil
|
||||
}
|
||||
|
||||
// fakeNotifier 记录真正发出去的通知事件,而不是调用次数。
|
||||
type fakeNotifier struct {
|
||||
published [][2]uint
|
||||
err error
|
||||
}
|
||||
|
||||
func (f *fakeNotifier) Follow(ctx context.Context, followerID, vloggerID uint) error {
|
||||
f.published = append(f.published, [2]uint{followerID, vloggerID})
|
||||
return f.err
|
||||
}
|
||||
|
||||
func newTestService(store socialStore, accounts accountFinder, notifier followNotifier) *SocialService {
|
||||
return NewSocialService(store, accounts, notifier, nil)
|
||||
}
|
||||
|
||||
func TestSocialService_Follow_SecondCallIsNoop(t *testing.T) {
|
||||
store := newFakeStore()
|
||||
notifier := &fakeNotifier{}
|
||||
svc := newTestService(store, fakeAccounts{}, notifier)
|
||||
rel := &Social{ID: 1, FollowerID: 7, VloggerID: 9}
|
||||
|
||||
created, err := svc.Follow(context.Background(), rel)
|
||||
if err != nil || !created {
|
||||
t.Fatalf("首次关注 = (%v, %v),想要 (true, nil)", created, err)
|
||||
}
|
||||
|
||||
created, err = svc.Follow(context.Background(), &Social{FollowerID: 7, VloggerID: 9})
|
||||
if err != nil || created {
|
||||
t.Fatalf("重复关注 = (%v, %v),想要 (false, nil)", created, err)
|
||||
}
|
||||
if len(store.rows) != 1 {
|
||||
t.Fatalf("socials 行数 = %d,想要 1", len(store.rows))
|
||||
}
|
||||
// 重复点击不该产生第二条通知。
|
||||
if len(notifier.published) != 1 {
|
||||
t.Fatalf("通知事件数 = %d,想要 1", len(notifier.published))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSocialService_Follow_SelfIsRejected(t *testing.T) {
|
||||
store := newFakeStore()
|
||||
notifier := &fakeNotifier{}
|
||||
svc := newTestService(store, fakeAccounts{}, notifier)
|
||||
|
||||
created, err := svc.Follow(context.Background(), &Social{FollowerID: 3, VloggerID: 3})
|
||||
if created || !errors.Is(err, ErrCannotFollowSelf) {
|
||||
t.Fatalf("自关注 = (%v, %v),想要 (false, ErrCannotFollowSelf)", created, err)
|
||||
}
|
||||
if len(store.rows) != 0 {
|
||||
t.Fatalf("自关注写入了 %d 行,想要 0", len(store.rows))
|
||||
}
|
||||
if len(notifier.published) != 0 {
|
||||
t.Fatalf("自关注发出了 %d 条通知,想要 0", len(notifier.published))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSocialService_Follow_RepoErrorPropagates(t *testing.T) {
|
||||
repoErr := errors.New("db is down")
|
||||
store := newFakeStore()
|
||||
store.err = repoErr
|
||||
notifier := &fakeNotifier{}
|
||||
svc := newTestService(store, fakeAccounts{}, notifier)
|
||||
|
||||
created, err := svc.Follow(context.Background(), &Social{FollowerID: 1, VloggerID: 2})
|
||||
if created || !errors.Is(err, repoErr) {
|
||||
t.Fatalf("仓储报错 = (%v, %v),想要 (false, db is down)", created, err)
|
||||
}
|
||||
if len(notifier.published) != 0 {
|
||||
t.Fatalf("仓储报错仍发出了 %d 条通知,想要 0", len(notifier.published))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSocialService_Follow_NotifyFailureKeepsSuccess(t *testing.T) {
|
||||
store := newFakeStore()
|
||||
notifier := &fakeNotifier{err: errors.New("mq is down")}
|
||||
svc := newTestService(store, fakeAccounts{}, notifier)
|
||||
|
||||
created, err := svc.Follow(context.Background(), &Social{FollowerID: 1, VloggerID: 2})
|
||||
if !created || err != nil {
|
||||
t.Fatalf("通知失败时 Follow = (%v, %v),想要 (true, nil)", created, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSocialService_Follow_AccountLookupErrorPropagates(t *testing.T) {
|
||||
lookupErr := errors.New("account not found")
|
||||
store := newFakeStore()
|
||||
svc := newTestService(store, fakeAccounts{err: lookupErr}, &fakeNotifier{})
|
||||
|
||||
created, err := svc.Follow(context.Background(), &Social{FollowerID: 1, VloggerID: 2})
|
||||
if created || !errors.Is(err, lookupErr) {
|
||||
t.Fatalf("账号校验失败 = (%v, %v),想要 (false, account not found)", created, err)
|
||||
}
|
||||
if len(store.rows) != 0 {
|
||||
t.Fatalf("账号校验失败仍写入了 %d 行,想要 0", len(store.rows))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSocialService_Unfollow_SecondCallIsNoop(t *testing.T) {
|
||||
store := newFakeStore()
|
||||
notifier := &fakeNotifier{}
|
||||
svc := newTestService(store, fakeAccounts{}, notifier)
|
||||
if _, err := svc.Follow(context.Background(), &Social{FollowerID: 7, VloggerID: 9}); err != nil {
|
||||
t.Fatalf("准备关注失败: %v", err)
|
||||
}
|
||||
|
||||
deleted, err := svc.Unfollow(context.Background(), &Social{FollowerID: 7, VloggerID: 9})
|
||||
if err != nil || !deleted {
|
||||
t.Fatalf("首次取关 = (%v, %v),想要 (true, nil)", deleted, err)
|
||||
}
|
||||
|
||||
deleted, err = svc.Unfollow(context.Background(), &Social{FollowerID: 7, VloggerID: 9})
|
||||
if err != nil || deleted {
|
||||
t.Fatalf("重复取关 = (%v, %v),想要 (false, nil)", deleted, err)
|
||||
}
|
||||
if len(store.rows) != 0 {
|
||||
t.Fatalf("取关后还有 %d 行,想要 0", len(store.rows))
|
||||
}
|
||||
}
|
||||
129
backend/internal/worker/notificationbus.go
Normal file
129
backend/internal/worker/notificationbus.go
Normal file
@@ -0,0 +1,129 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||||
"feedsystem_video_go/internal/notification"
|
||||
)
|
||||
|
||||
// 频道名经 cache.Key 加前缀,与环境内其他键共用命名空间。
|
||||
const notificationBusChannel = "notification:push"
|
||||
|
||||
const (
|
||||
notificationPushTimeout = 500 * time.Millisecond
|
||||
notificationBusMinBackoff = time.Second
|
||||
notificationBusMaxBackoff = 30 * time.Second
|
||||
)
|
||||
|
||||
// 跨进程线缆格式:改动它必须同时改生产端与消费端。
|
||||
type notificationPushEnvelope struct {
|
||||
UserID uint `json:"user_id"`
|
||||
Notification *notification.Notification `json:"notification"`
|
||||
}
|
||||
|
||||
// RedisNotificationPublisher 把通知发给 Redis,由各 API 实例转给本地 SSE 连接。
|
||||
type RedisNotificationPublisher struct {
|
||||
cache *rediscache.Client
|
||||
}
|
||||
|
||||
func NewRedisNotificationPublisher(cache *rediscache.Client) *RedisNotificationPublisher {
|
||||
return &RedisNotificationPublisher{cache: cache}
|
||||
}
|
||||
|
||||
// Push 尽力而为:通知已落库,失败只影响实时性。
|
||||
func (p *RedisNotificationPublisher) Push(userID uint, n *notification.Notification) {
|
||||
if p == nil || p.cache == nil || n == nil || userID == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
payload, err := json.Marshal(notificationPushEnvelope{UserID: userID, Notification: n})
|
||||
if err != nil {
|
||||
log.Printf("notification push: 序列化失败 notification=%d: %v", n.ID, err)
|
||||
return
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), notificationPushTimeout)
|
||||
defer cancel()
|
||||
if err := p.cache.Publish(ctx, p.cache.Key(notificationBusChannel), payload); err != nil {
|
||||
log.Printf("notification push: 发布失败 notification=%d user=%d(通知已落库,实时推送跳过): %v",
|
||||
n.ID, userID, err)
|
||||
}
|
||||
}
|
||||
|
||||
// StartNotificationSubscriber 订阅推送通道并转给本地 SSE;Redis 不可用时只降级实时推送。
|
||||
func StartNotificationSubscriber(ctx context.Context, cache *rediscache.Client, hub NotificationHub) {
|
||||
if cache == nil || hub == nil {
|
||||
log.Printf("Notification push disabled: redis 或 hub 未初始化")
|
||||
return
|
||||
}
|
||||
|
||||
go func() {
|
||||
backoff := notificationBusMinBackoff
|
||||
for ctx.Err() == nil {
|
||||
started := time.Now()
|
||||
err := runNotificationSubscriber(ctx, cache, hub, nil)
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
// 存活够久说明是抖动而非配置错误:重置退避,避免长期停在长退避上。
|
||||
if time.Since(started) > notificationBusMaxBackoff {
|
||||
backoff = notificationBusMinBackoff
|
||||
}
|
||||
log.Printf("notification push: 订阅中断(%v 后重连): %v", backoff, err)
|
||||
if !waitOrDone(ctx, backoff) {
|
||||
return
|
||||
}
|
||||
backoff *= 2
|
||||
if backoff > notificationBusMaxBackoff {
|
||||
backoff = notificationBusMaxBackoff
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// runNotificationSubscriber 转发到 ctx 取消或订阅断开;onSubscribed 供测试确认订阅生效。
|
||||
func runNotificationSubscriber(ctx context.Context, cache *rediscache.Client, hub NotificationHub, onSubscribed func()) error {
|
||||
if cache == nil || hub == nil {
|
||||
return errors.New("notification subscriber: redis 或 hub 未初始化")
|
||||
}
|
||||
|
||||
sub, err := cache.Subscribe(ctx, cache.Key(notificationBusChannel))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = sub.Close() }()
|
||||
|
||||
if onSubscribed != nil {
|
||||
onSubscribed()
|
||||
}
|
||||
|
||||
msgs := sub.Channel()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil
|
||||
case msg, ok := <-msgs:
|
||||
if !ok {
|
||||
return errors.New("订阅通道已关闭")
|
||||
}
|
||||
var envelope notificationPushEnvelope
|
||||
if err := json.Unmarshal([]byte(msg.Payload), &envelope); err != nil {
|
||||
// 坏消息不能打断订阅:否则一条脏数据会让后续所有通知都送不到。
|
||||
log.Printf("notification push: 丢弃无法解析的消息: %v", err)
|
||||
continue
|
||||
}
|
||||
if envelope.UserID == 0 || envelope.Notification == nil {
|
||||
log.Printf("notification push: 丢弃缺少 user_id/notification 的消息")
|
||||
continue
|
||||
}
|
||||
hub.Push(envelope.UserID, envelope.Notification)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var _ NotificationHub = (*RedisNotificationPublisher)(nil)
|
||||
145
backend/internal/worker/notificationbus_test.go
Normal file
145
backend/internal/worker/notificationbus_test.go
Normal file
@@ -0,0 +1,145 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||||
"feedsystem_video_go/internal/notification"
|
||||
|
||||
miniredis "github.com/alicebob/miniredis/v2"
|
||||
goredis "github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
// recordingHub 用带缓冲的 channel 记录推送:测试靠 channel 同步,不靠 sleep 猜时序。
|
||||
type recordingHub struct {
|
||||
pushes chan recordedPush
|
||||
}
|
||||
|
||||
type recordedPush struct {
|
||||
userID uint
|
||||
n *notification.Notification
|
||||
}
|
||||
|
||||
func newRecordingHub() *recordingHub {
|
||||
return &recordingHub{pushes: make(chan recordedPush, 8)}
|
||||
}
|
||||
|
||||
func (h *recordingHub) Push(userID uint, n *notification.Notification) {
|
||||
h.pushes <- recordedPush{userID: userID, n: n}
|
||||
}
|
||||
|
||||
func newTestRedisClient(t *testing.T) *rediscache.Client {
|
||||
t.Helper()
|
||||
mr, err := miniredis.Run()
|
||||
if err != nil {
|
||||
t.Fatalf("start miniredis: %v", err)
|
||||
}
|
||||
client := rediscache.NewClient(goredis.NewClient(&goredis.Options{Addr: mr.Addr()}), "v1:")
|
||||
t.Cleanup(func() {
|
||||
_ = client.Close()
|
||||
mr.Close()
|
||||
})
|
||||
return client
|
||||
}
|
||||
|
||||
// startSubscriber 起一个订阅器,并等到订阅真正建立(SUBSCRIBE 确认返回)再返回。
|
||||
func startSubscriber(t *testing.T, ctx context.Context, client *rediscache.Client, hub NotificationHub) <-chan error {
|
||||
t.Helper()
|
||||
subscribed := make(chan struct{})
|
||||
errCh := make(chan error, 1)
|
||||
go func() {
|
||||
errCh <- runNotificationSubscriber(ctx, client, hub, func() { close(subscribed) })
|
||||
}()
|
||||
select {
|
||||
case <-subscribed:
|
||||
return errCh
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("订阅器未在 5s 内建立订阅")
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func TestNotificationBus_PublishReachesSubscriber(t *testing.T) {
|
||||
client := newTestRedisClient(t)
|
||||
hub := newRecordingHub()
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
startSubscriber(t, ctx, client, hub)
|
||||
|
||||
want := ¬ification.Notification{ID: 7, RecipientID: 42, Type: "like", TargetID: 9}
|
||||
NewRedisNotificationPublisher(client).Push(42, want)
|
||||
|
||||
select {
|
||||
case got := <-hub.pushes:
|
||||
if got.userID != 42 {
|
||||
t.Fatalf("user_id = %d, want 42(投递给错误的 SSE 连接等于通知丢失)", got.userID)
|
||||
}
|
||||
if got.n == nil || got.n.ID != want.ID || got.n.Type != want.Type || got.n.TargetID != want.TargetID {
|
||||
t.Fatalf("notification = %+v, want %+v", got.n, want)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("通知没有穿过 Redis Pub/Sub:worker 落库后 API 侧收不到推送")
|
||||
}
|
||||
}
|
||||
|
||||
// 一条坏消息不能让订阅器退出,否则后续合法通知都送不到。
|
||||
func TestNotificationSubscriber_SkipsMalformedPayload(t *testing.T) {
|
||||
client := newTestRedisClient(t)
|
||||
hub := newRecordingHub()
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
startSubscriber(t, ctx, client, hub)
|
||||
|
||||
channel := client.Key(notificationBusChannel)
|
||||
pubCtx, pubCancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer pubCancel()
|
||||
if err := client.Publish(pubCtx, channel, []byte(`{"user_id":`)); err != nil {
|
||||
t.Fatalf("publish malformed: %v", err)
|
||||
}
|
||||
|
||||
good := ¬ification.Notification{ID: 11, RecipientID: 5, Type: "follow"}
|
||||
NewRedisNotificationPublisher(client).Push(5, good)
|
||||
|
||||
select {
|
||||
case got := <-hub.pushes:
|
||||
if got.n == nil || got.n.ID != good.ID {
|
||||
t.Fatalf("收到 %+v,坏消息没有被跳过", got.n)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("坏消息之后的合法通知没有送达:订阅循环已退出")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNotificationSubscriber_StopsOnContextCancel(t *testing.T) {
|
||||
client := newTestRedisClient(t)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
errCh := startSubscriber(t, ctx, client, newRecordingHub())
|
||||
|
||||
cancel()
|
||||
|
||||
select {
|
||||
case err := <-errCh:
|
||||
if err != nil {
|
||||
t.Fatalf("ctx 取消应视为正常退出,got err = %v", err)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("ctx 取消后订阅器没有退出:API 无法优雅停机")
|
||||
}
|
||||
}
|
||||
|
||||
// Redis 未配置时 SSE 仍要能建立连接并读历史通知,只是没有实时推送。
|
||||
func TestRedisNotificationPublisher_NilClientIsNoop(t *testing.T) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
t.Fatalf("Redis 不可用时 Push 不允许 panic: %v", r)
|
||||
}
|
||||
}()
|
||||
|
||||
NewRedisNotificationPublisher(nil).Push(1, ¬ification.Notification{ID: 1})
|
||||
(*RedisNotificationPublisher)(nil).Push(1, ¬ification.Notification{ID: 1})
|
||||
NewRedisNotificationPublisher(nil).Push(1, nil)
|
||||
}
|
||||
@@ -16,55 +16,70 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// outboxPublishTimeout 限制单条 outbox 消息的发布时间。
|
||||
// 连接管理器在断连期间会阻塞等待重连,这里加超时可以保持"失败即进入下一轮轮询"
|
||||
// 的既有语义,而不是把整个轮询器挂在一条消息上。
|
||||
// 断连期间 Publish 会阻塞等待重连,超时让它失败并进入下一轮轮询。
|
||||
const outboxPublishTimeout = 5 * time.Second
|
||||
|
||||
// 轮询器,轮询数据库中的 outbox 表,获取待投递的消息,投递到 MQ 中
|
||||
func StartOutboxPoller(db *gorm.DB, tmq *rabbitmq.TimelineMQ) {
|
||||
const (
|
||||
// 空批次后的等待时间。
|
||||
outboxPollInterval = time.Second
|
||||
outboxBatchSize = 100
|
||||
)
|
||||
|
||||
// StartOutboxPoller 阻塞轮询 outbox 表;调用方负责起 goroutine。
|
||||
func StartOutboxPoller(ctx context.Context, db *gorm.DB, tmq *rabbitmq.TimelineMQ) {
|
||||
if db == nil || tmq == nil {
|
||||
log.Printf("Outbox poller disabled: timeline mq is not initialized")
|
||||
return
|
||||
}
|
||||
|
||||
go func() {
|
||||
for {
|
||||
var messages []video.OutboxMsg
|
||||
for ctx.Err() == nil {
|
||||
var messages []video.OutboxMsg
|
||||
|
||||
err := db.Where("status = ?", "pending").Order("create_time ASC").Limit(100).Find(&messages).Error
|
||||
|
||||
if err != nil {
|
||||
log.Printf("outbox 轮询失败: %v", err)
|
||||
time.Sleep(1 * time.Second)
|
||||
continue
|
||||
err := db.Where("status = ?", "pending").Order("create_time ASC").Limit(outboxBatchSize).Find(&messages).Error
|
||||
if err != nil {
|
||||
log.Printf("outbox 轮询失败: %v", err)
|
||||
if !waitOrDone(ctx, outboxPollInterval) {
|
||||
return
|
||||
}
|
||||
if len(messages) == 0 {
|
||||
time.Sleep(1 * time.Second)
|
||||
continue
|
||||
continue
|
||||
}
|
||||
if len(messages) == 0 {
|
||||
if !waitOrDone(ctx, outboxPollInterval) {
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
for _, msg := range messages {
|
||||
pubCtx, cancel := context.WithTimeout(context.Background(), outboxPublishTimeout)
|
||||
err := tmq.PublishVideo(pubCtx, msg.VideoID, msg.CreateTime)
|
||||
cancel()
|
||||
for _, msg := range messages {
|
||||
// 超时派生自 poller 的 ctx:进程退出时不再为一条消息多等 5 秒。
|
||||
pubCtx, cancel := context.WithTimeout(ctx, outboxPublishTimeout)
|
||||
err := tmq.PublishVideo(pubCtx, msg.VideoID, msg.CreateTime)
|
||||
cancel()
|
||||
|
||||
if err == nil {
|
||||
if err := db.Delete(&msg).Error; err != nil {
|
||||
log.Printf("删除 outbox 消息失败: id=%d, err=%v", msg.ID, err)
|
||||
}
|
||||
} else {
|
||||
log.Printf("投递MQ失败: VideoID: %d, err: %v", msg.VideoID, err)
|
||||
if err == nil {
|
||||
if err := db.Delete(&msg).Error; err != nil {
|
||||
log.Printf("删除 outbox 消息失败: id=%d, err=%v", msg.ID, err)
|
||||
}
|
||||
} else {
|
||||
log.Printf("投递MQ失败: VideoID: %d, err: %v", msg.VideoID, err)
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
}
|
||||
|
||||
// StartConsumer 消费 timeline 事件并写入 Redis ZSet。
|
||||
//
|
||||
// 连接级重连、拓扑重放、channel 重建全部交给连接管理器(rabbitmq.RunConsumer),
|
||||
// 这里只关心"一条消息应该怎么被处理"。
|
||||
// waitOrDone 等待 d 到点;ctx 取消则提前返回 false。
|
||||
func waitOrDone(ctx context.Context, d time.Duration) bool {
|
||||
t := time.NewTimer(d)
|
||||
defer t.Stop()
|
||||
select {
|
||||
case <-t.C:
|
||||
return true
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// StartConsumer 阻塞消费 timeline 事件;调用方负责起 goroutine。
|
||||
func StartConsumer(ctx context.Context, rmq *rabbitmq.RabbitMQ, queueName string, redisClient *rediscache.Client) {
|
||||
if rmq == nil {
|
||||
log.Printf("Timeline consumer disabled: rabbitmq is not initialized")
|
||||
@@ -75,7 +90,7 @@ func StartConsumer(ctx context.Context, rmq *rabbitmq.RabbitMQ, queueName string
|
||||
return
|
||||
}
|
||||
|
||||
go rabbitmq.RunConsumer(ctx, rmq, "TimelineConsumer", 10, func(ch *amqp.Channel) error {
|
||||
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
|
||||
|
||||
33
backend/internal/worker/outboxworker_test.go
Normal file
33
backend/internal/worker/outboxworker_test.go
Normal file
@@ -0,0 +1,33 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// 轮询间隔必须可被 ctx 打断:否则 Worker 收到 SIGTERM 后还要把最后一轮空等走完。
|
||||
func TestWaitOrDone(t *testing.T) {
|
||||
t.Run("ctx 已取消时立即返回 false", func(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
|
||||
start := time.Now()
|
||||
if waitOrDone(ctx, time.Minute) {
|
||||
t.Fatal("ctx 已取消时不应报告等待完成")
|
||||
}
|
||||
if elapsed := time.Since(start); elapsed > time.Second {
|
||||
t.Fatalf("ctx 已取消仍等待了 %v", elapsed)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("ctx 未取消时等满间隔返回 true", func(t *testing.T) {
|
||||
start := time.Now()
|
||||
if !waitOrDone(context.Background(), 20*time.Millisecond) {
|
||||
t.Fatal("ctx 未取消时应报告等待完成")
|
||||
}
|
||||
if elapsed := time.Since(start); elapsed < 20*time.Millisecond {
|
||||
t.Fatalf("提前返回:%v", elapsed)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"feedsystem_video_go/internal/middleware/rabbitmq"
|
||||
"feedsystem_video_go/internal/social"
|
||||
|
||||
"github.com/go-sql-driver/mysql"
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
)
|
||||
|
||||
type SocialWorker struct {
|
||||
ch *amqp.Channel
|
||||
parker rabbitmq.Parker
|
||||
repo *social.SocialRepository
|
||||
queue string
|
||||
}
|
||||
|
||||
func NewSocialWorker(ch *amqp.Channel, parker rabbitmq.Parker, repo *social.SocialRepository, queue string) *SocialWorker {
|
||||
return &SocialWorker{ch: ch, parker: parker, repo: repo, queue: queue}
|
||||
}
|
||||
|
||||
func (w *SocialWorker) Run(ctx context.Context) error {
|
||||
if w == nil || w.ch == nil || w.repo == nil {
|
||||
return errors.New("social worker is not initialized")
|
||||
}
|
||||
if w.queue == "" {
|
||||
return errors.New("queue is required")
|
||||
}
|
||||
return rabbitmq.ConsumeLoop(ctx, w.ch, w.parker, w.queue, rabbitmq.MaxAttempts, w.process)
|
||||
}
|
||||
|
||||
func (w *SocialWorker) process(ctx context.Context, d amqp.Delivery) error {
|
||||
var evt rabbitmq.SocialEvent
|
||||
if err := json.Unmarshal(d.Body, &evt); err != nil {
|
||||
return rabbitmq.Permanent(fmt.Errorf("social worker: decode event: %w", err))
|
||||
}
|
||||
if evt.FollowerID == 0 || evt.VloggerID == 0 {
|
||||
return rabbitmq.Permanent(fmt.Errorf("social worker: invalid event follower_id=%d vlogger_id=%d", evt.FollowerID, evt.VloggerID))
|
||||
}
|
||||
|
||||
switch evt.Action {
|
||||
case "follow":
|
||||
err := w.repo.Follow(ctx, &social.Social{
|
||||
FollowerID: evt.FollowerID,
|
||||
VloggerID: evt.VloggerID,
|
||||
})
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
// 重复投递:关注关系已在,唯一索引挡下第二条。这是成功语义。
|
||||
var mysqlErr *mysql.MySQLError
|
||||
if errors.As(err, &mysqlErr) && mysqlErr.Number == 1062 {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
case "unfollow":
|
||||
return w.repo.Unfollow(ctx, &social.Social{
|
||||
FollowerID: evt.FollowerID,
|
||||
VloggerID: evt.VloggerID,
|
||||
})
|
||||
default:
|
||||
return rabbitmq.Permanent(fmt.Errorf("social worker: unknown action %q", evt.Action))
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -21,10 +22,16 @@ type SSEHub struct {
|
||||
mu sync.RWMutex
|
||||
clients map[uint][]chan *notification.Notification
|
||||
db *gorm.DB
|
||||
done <-chan struct{}
|
||||
}
|
||||
|
||||
func NewSSEHub(db *gorm.DB) *SSEHub {
|
||||
return &SSEHub{clients: make(map[uint][]chan *notification.Notification), db: db}
|
||||
// ctx 结束时 SSEHandler 主动断开:Shutdown 不取消在途请求,而 SSE 响应永不结束。
|
||||
func NewSSEHub(ctx context.Context, db *gorm.DB) *SSEHub {
|
||||
h := &SSEHub{clients: make(map[uint][]chan *notification.Notification), db: db}
|
||||
if ctx != nil {
|
||||
h.done = ctx.Done()
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
func (h *SSEHub) Push(userID uint, n *notification.Notification) {
|
||||
@@ -129,6 +136,8 @@ func (h *SSEHub) SSEHandler(c *gin.Context) {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-h.done:
|
||||
return
|
||||
case n, ok := <-ch:
|
||||
if !ok {
|
||||
return
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -4,7 +4,7 @@
|
||||
|
||||
## 1. 写路径的重复是结构性的
|
||||
|
||||
点赞、评论、关注都走"先发消息,失败再直写数据库"。这条路径上,重复不是异常,而是常态:
|
||||
点赞、评论走"先发消息,失败再直写数据库"。关注不同:服务层先写库,事件只做通知(P1-4)。两种路径上,重复都不是异常,而是常态:
|
||||
|
||||
| 重复来源 | 触发条件 | 是否可避免 |
|
||||
|---|---|---|
|
||||
@@ -13,7 +13,7 @@
|
||||
| 客户端重试 | 用户连点、请求超时后重发 | 不可完全避免 |
|
||||
| 直写与消费双写 | 发布失败 → 直写;消息其实也到了 | 由设计决定 |
|
||||
|
||||
前三种是分布式系统固有属性,第四种是"降级路径"的必然代价。因此幂等不能寄希望于"只写一次",只能定义成:
|
||||
前三种是分布式系统固有属性,第四种是"降级路径"的必然代价。关注没有第四条:它不依赖消息送达,重复由 `(follower_id, vlogger_id)` 的唯一索引裁决,`Follow` / `Unfollow` 直接返回本次是否真的写入。因此幂等不能寄希望于"只写一次",只能定义成:
|
||||
|
||||
> 同一次用户意图被执行任意多次,每个副作用的结果与执行一次相同。
|
||||
|
||||
@@ -602,7 +602,7 @@ func (Notification) TableName() string { return "notifications" }
|
||||
|
||||
## 6. 热度层:Redis 占位
|
||||
|
||||
> **本节描述的是已被替换的设计。** P0-5 之后热度不再有独立的写路径:`hot:applied:<intentKey>` 占位与 `UpdatePopularityCache` 已随 `popularityMQ` 一起删除,热榜增量改由"事务是否真的写入了"驱动(`ApplyHotDelta`),失败不回滚、可由 DB 重建。当前设计见 [`hot-ranking.md`](hot-ranking.md)。本节保留为决策记录,说明"为什么当初要占位"以及"占位与副作用同生共死"这条约束从哪来。
|
||||
> **本节描述的是已被替换的设计。** P0-5 之后热度不再有独立的写路径:`hot:applied:<intentKey>` 占位与 `UpdatePopularityCache` 已随 `popularityMQ` 一起删除,热榜增量改由"事务是否真的写入了"驱动(`ApplyHotDelta`),失败不回滚、可由 DB 重建。当前设计见 [`热度排行榜.md`](热度排行榜.md)。本节保留为决策记录,说明"为什么当初要占位"以及"占位与副作用同生共死"这条约束从哪来。
|
||||
|
||||
### 6.1 为什么用占位而不是计数器
|
||||
|
||||
@@ -863,7 +863,7 @@ SHOW INDEX FROM notifications WHERE Key_name = 'uk_notifications_dedupe';
|
||||
| `backend/internal/video/comment_repo.go` | 单事务"插入或跳过 + 热度" | `CreateIdempotentWithPopularity`、`DeleteByID`、`CreateMentions` |
|
||||
| `backend/internal/video/comment_service.go` | 编排两条路径、生成通知 | `Publish`、`notifyMentions`、`logIntent` |
|
||||
| `backend/internal/video/comment_handler.go` | 接收并回显 `request_id` | `PublishComment` |
|
||||
| `backend/internal/video/hot_window.go` | 热度增量的唯一写入口(§6 的占位设计已被它替换,详见 [`hot-ranking.md`](hot-ranking.md)) | `ApplyHotDelta`、`HotBucket`、`HotMember` |
|
||||
| `backend/internal/video/hot_window.go` | 热度增量的唯一写入口(§6 的占位设计已被它替换,详见 [`热度排行榜.md`](热度排行榜.md)) | `ApplyHotDelta`、`HotBucket`、`HotMember` |
|
||||
| `backend/internal/video/like_service.go` | 一个键喂两条事件 | `Like`、`Unlike` |
|
||||
| `backend/internal/middleware/redis/cache.go` | `SETNX` 原语 | `SetNX` |
|
||||
| `backend/internal/middleware/rabbitmq/commentMQ.go` | 事件携带意图键 | `Publish`、`Delete` |
|
||||
616
docs/design/可观测性实现.md
Normal file
616
docs/design/可观测性实现.md
Normal file
@@ -0,0 +1,616 @@
|
||||
# 可观测性升级:pprof 评估与 Prometheus + Grafana 方案
|
||||
|
||||
> 状态:方案(尚未实现)。落地后请把本文改成现状说明:删掉本行,把“目标架构”改成“架构”。
|
||||
>
|
||||
> 读者:要接指标、要排障、要改 `observability` 包的人。
|
||||
|
||||
## 0. 结论
|
||||
|
||||
1. **pprof 不需要被替换。** 它回答“此刻为什么慢、卡在哪”,Prometheus 回答“多频繁、从什么时候开始、影响了多少请求”。两者是互补关系,不是替代关系。
|
||||
2. 现有 pprof 的实现本身没有结构性缺陷:独立监听、`enabled=false` 返回 `nil`、`Close` 幂等、有测试。真正的问题是它**在生产是关闭的**:`backend/configs/config.docker.yaml` 里 `observability.pprof.enabled: false`,两份 compose 也没有发布 6060/6061。线上实际只剩容器日志、`/healthz`、`/readyz` 的瞬时 JSON 和 Docker 健康检查。
|
||||
3. 升级的核心不是“装一个 Grafana”,而是**先让进程有一个可被抓取的观测面**:一个独立 admin 监听器,同时提供 `/metrics` 与 `/debug/pprof/*`,不碰业务端口 8080。
|
||||
4. 第一批只做 6 组指标,覆盖“MQ 断了 / 写路径降级了 / 消费堆积了 / 接口变慢了 / 进程卡住了”这几类最常见故障;其余按故障场景逐批加,不追求一次埋满。
|
||||
5. 监控栈放在 compose 的 `monitoring` profile 里,不进入 CI 的默认 `up`,避免拖慢构建、避免 `--remove-orphans` 误删。
|
||||
|
||||
本文不覆盖:链路追踪(OTel/Tempo)、日志聚合(Loki)、前端 RUM。它们是第三阶段,且都需要先有本方案的第一阶段。
|
||||
|
||||
---
|
||||
|
||||
## 1. 现状评估
|
||||
|
||||
### 1.1 已经有的东西
|
||||
|
||||
| 能力 | 位置 | 现状 |
|
||||
|---|---|---|
|
||||
| pprof(API / Worker 各一个监听器) | `backend/internal/observability/pprof.go` 的 `NewPprofServer`、`NewPprofMux` | 独立端口 6060/6061;关闭时返回 `nil`;`Close` 带 3s 超时;有 3 个测试 |
|
||||
| 存活与就绪 | `backend/internal/http/router.go` 的 `/healthz`、`/readyz` | 语义分离正确;`/readyz` 返回 `mq_enabled` / `mq_connected` / `mq_generation` / `mq_reconnects` / `mq_topology` |
|
||||
| MQ 连接状态快照 | `backend/internal/middleware/rabbitmq/rabbitMQ.go` 的 `Stats()` | 字段齐全(`Connected`、`Generation`、`Reconnects`、`Topology`、`LastUpAt`、`LastDownAt`),只差导出 |
|
||||
| 访问日志 | `gin.Default()` 的 Logger | 文本行,无法按路由聚合,也没有延迟直方图 |
|
||||
| 异步失败事实 | `failed_events` 表、`middleware/rabbitmq/dlx.go` 的 `ConsumeLoop` / `handleOne` | 有行、有日志,没有速率与积压 |
|
||||
| 排行来源 | `backend/internal/feed/entity.go` 的 `RankingSource` | 只在响应 JSON 里(`hot` / `hot_db` / `latest`),没有计数 |
|
||||
| 资源池 | GORM 背后的 `*sql.DB`、`rediscache.Client` 的 `rdb` | 标准库已提供 `DBStats` / `PoolStats`,只是没导出 |
|
||||
|
||||
### 1.2 pprof 的边界
|
||||
|
||||
pprof 是**按需采样的诊断工具**,不是监控系统。它没有历史、没有聚合、没有告警,而且每次都要人主动去抓。
|
||||
|
||||
| 问题 | pprof | Prometheus |
|
||||
|---|---|---|
|
||||
| 现在 CPU 花在哪个函数 | ✅ | ❌ |
|
||||
| 哪个 goroutine 卡住了 | ✅(goroutine profile) | ❌(只能看 goroutine 总数) |
|
||||
| 过去一小时 5xx 比例 | ❌ | ✅ |
|
||||
| 这次发布后 p95 变了吗 | ❌ | ✅ |
|
||||
| MQ 断了几次、断了多久 | ❌ | ✅ |
|
||||
| 缓存命中率从 95% 掉到 60% | ❌ | ✅ |
|
||||
|
||||
结论:pprof 是手术刀,metrics 是仪表盘。**故障时先用仪表盘判断“哪一段、什么时候、多严重”,再用 pprof 判断“为什么”。**
|
||||
|
||||
### 1.3 生产环境实际是“零可观测”
|
||||
|
||||
- `backend/configs/config.docker.yaml` 的 `observability.pprof.enabled` 是 `false`;`docker-compose.yml` 与 `docker-compose.prod.yml` 都没有发布 6060/6061。容器里即使打开 pprof,绑定 `localhost` 也只有容器自身能访问。
|
||||
- Worker 的 healthcheck 是 `pgrep worker`,不是真实健康面(`docs/ISSUES-REPORT.md` P3-39)。
|
||||
- API 的 healthcheck 是 `/healthz`,只表示进程存活。
|
||||
- 所以生产能回答的问题只有:容器是否在跑、MQ 此刻是否连着(且只在有人请求 `/readyz` 时)。
|
||||
|
||||
`README.md` 里“本地配置默认开启 pprof”只对 `config.yaml` 成立;用 Compose 启动时挂载的是 `config.docker.yaml`,默认关闭(`docs/ISSUES-REPORT.md` D-18 已记录这处不一致)。
|
||||
|
||||
### 1.4 pprof 实现层面的问题
|
||||
|
||||
| 问题 | 影响 | 建议 |
|
||||
|---|---|---|
|
||||
| 只有 `ReadHeaderTimeout`,没有 `ReadTimeout` / `IdleTimeout` | 慢连接可长期占用 fd | 补 `ReadTimeout`、`IdleTimeout` |
|
||||
| `WriteTimeout` 为 0 | 没有写超时;但直接加 10s 会让 `?seconds=30` 的 CPU profile 失败 | 若加,必须同时给 `/debug/pprof/profile` 的 `seconds` 设上限 |
|
||||
| 本地配置绑定 `localhost` | 容器内是回环地址,Prometheus 抓不到 | 容器配置改 `0.0.0.0`,并且不 publish 到宿主机 |
|
||||
| 无鉴权 | `/debug/pprof/cmdline` 可能含启动参数,heap 可能含业务数据 | 只靠网络隔离;需要时加 Bearer token |
|
||||
| block / mutex 采样率为 0 | `/debug/pprof/block`、`/debug/pprof/mutex` 基本为空 | 可选:`runtime.SetBlockProfileRate` / `SetMutexProfileFraction` |
|
||||
| 没有 wall-clock profile | CPU profile 看不到等 I/O 的时间 | 可选:`fgprof`,不是第一阶段 |
|
||||
|
||||
### 1.5 代码里已经埋好的“半成品钩子”
|
||||
|
||||
这些是这次升级的杠杆点:不需要改业务结构,只要在既有汇合点加计数。
|
||||
|
||||
- `RabbitMQ.Stats()`:连接代次、重连次数、拓扑数量,直接可转 gauge/counter。
|
||||
- `dlx.go` 的 `handleOne`:`DispositionAck` / `DispositionRetry` / `DispositionPark` 三路分支,是消费结果唯一的汇合点。
|
||||
- `OutboxMsg.CreateTime`:轮询按 `create_time ASC` 取 100 条,批次首条就是“最老积压”,不需要额外查询。
|
||||
- `RankingSource`:`hot` / `hot_db` / `latest` 三个值就是三个计数器标签。
|
||||
- `ratelimit.Limit`:六个限流规则共用同一个包装函数,一处埋点覆盖全部。
|
||||
- `sql.DB.Stats()` / `redis.PoolStats()`:连接池指标不需要额外 exporter。
|
||||
- `failed_events` 表与 `<queue>.retry` 队列:DLQ 深度与重试深度的事实来源。
|
||||
|
||||
---
|
||||
|
||||
## 2. 目标架构
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
subgraph net["compose 内网"]
|
||||
API["API :8080<br/>admin :6060"]
|
||||
WK["Worker<br/>admin :6061"]
|
||||
RMQ["RabbitMQ<br/>:15692"]
|
||||
end
|
||||
P["Prometheus :9090"]
|
||||
G["Grafana :3000"]
|
||||
A["Alertmanager(可选)"]
|
||||
|
||||
API -- "/metrics" --> P
|
||||
WK -- "/metrics" --> P
|
||||
RMQ -- "/metrics" --> P
|
||||
P -- PromQL --> G
|
||||
P -- alerts --> A
|
||||
G -. "127.0.0.1 + SSH 隧道" .-> U["人"]
|
||||
```
|
||||
|
||||
### 2.1 五条原则
|
||||
|
||||
1. **指标不经过业务端口。** `/metrics` 与 pprof 放在独立的 admin 监听器上;8080 仍然只暴露业务与 `/healthz`、`/readyz`。
|
||||
2. **Pull,不引入 Pushgateway。** API 与 Worker 都是长生命周期进程,Prometheus 直接抓;没有短任务需要 push。
|
||||
3. **低基数。** `route` 用 Gin 的路由模板(`c.FullPath()`),不用原始路径、用户 ID、视频 ID、IP、错误文本。
|
||||
4. **一个指标对应一个故障问题。** 说不清“它高了要做什么”的指标不加。
|
||||
5. **监控栈与业务同项目、不同 profile。** 同一 compose 项目保证 `--remove-orphans` 不会删掉监控容器;profile 保证 CI 的 `up -d` 不会启动它们。
|
||||
|
||||
### 2.2 端口与可达性
|
||||
|
||||
| 端口 | 进程 | 暴露方式 |
|
||||
|---|---|---|
|
||||
| 8080 | API 业务 | 公开(现状) |
|
||||
| 6060 | API admin:`/metrics`、`/debug/pprof/*` | 仅 compose 内网,不 publish |
|
||||
| 6061 | Worker admin:`/metrics`、`/debug/pprof/*`、`/healthz` | 仅 compose 内网,不 publish |
|
||||
| 9090 | Prometheus | 仅 `127.0.0.1`(需要时 SSH 隧道) |
|
||||
| 3000 | Grafana | 仅 `127.0.0.1` + SSH 隧道 |
|
||||
| 15692 | RabbitMQ prometheus 插件 | 仅 compose 内网 |
|
||||
|
||||
保留 6060/6061 而不是改成 9090/9091,有两个原因:现有文档与肌肉记忆已经绑定这两个端口;Prometheus 默认占用 9090,改了会冲突。
|
||||
|
||||
### 2.3 端点
|
||||
|
||||
| 端点 | 谁提供 | 说明 |
|
||||
|---|---|---|
|
||||
| `/metrics` | admin 监听器 | `promhttp`,OpenMetrics 文本格式 |
|
||||
| `/debug/pprof/*` | admin 监听器 | 复用 `NewPprofMux` 的 5 个 handler;`Index` 本身会分发 `goroutine` / `heap` / `allocs` 等命名 profile |
|
||||
| `/healthz` | **仅 Worker 的 admin 监听器** | 进程存活;给 compose healthcheck 用 |
|
||||
| `/healthz`、`/readyz` | API 的 8080 | 保持不变 |
|
||||
|
||||
Worker 的 `/healthz` 走 admin 端口而不是新开端口,原因是:它本来就需要一个 HTTP 面,复用 admin 监听器可以顺手把 `pgrep worker` 换掉。代价是“admin 被关闭”会让容器 unhealthy——这是有意的,配置错误应当立刻可见。
|
||||
|
||||
### 2.4 配置
|
||||
|
||||
```yaml
|
||||
observability:
|
||||
admin:
|
||||
enabled: true
|
||||
# 本地跑 go run 时用回环,避免把 pprof 暴露到局域网
|
||||
api_addr: "127.0.0.1:6060"
|
||||
worker_addr: "127.0.0.1:6061"
|
||||
# 只控制 /debug/pprof/*;/metrics 始终随 admin 开启
|
||||
pprof: true
|
||||
```
|
||||
|
||||
`config.docker.yaml` 里两个地址改为 `0.0.0.0:6060` / `0.0.0.0:6061`,端口仍然不 publish。
|
||||
|
||||
迁移对照:
|
||||
|
||||
| 旧 | 新 |
|
||||
|---|---|
|
||||
| `observability.pprof.enabled` | `observability.admin.enabled` |
|
||||
| `observability.pprof.api_addr` | `observability.admin.api_addr` |
|
||||
| `observability.pprof.worker_addr` | `observability.admin.worker_addr` |
|
||||
| — | `observability.admin.pprof` |
|
||||
|
||||
这是一次**破坏性配置变更**:三份 YAML、`DefaultLocalConfig`、`loadconfig_test.go`、`README.md` 必须在同一个提交里改完。外部自定义配置如果没迁移,`admin.enabled` 会落到零值 `false`,表现为 admin 端口不监听;Worker 的 healthcheck 会因此失败,部署会立刻暴露,而不是静默丢掉观测。
|
||||
|
||||
### 2.5 依赖
|
||||
|
||||
只加一个直接依赖:`github.com/prometheus/client_golang`。它会带入 `prometheus/common`、`client_model`、`procfs` 等间接依赖。
|
||||
|
||||
不加:
|
||||
|
||||
- **OpenTelemetry SDK**:第一阶段没有 tracing 需求,依赖面和初始化复杂度都不小。
|
||||
- **Pushgateway**:没有短生命周期任务。
|
||||
- **Loki / Tempo**:日志与追踪是第三阶段;当前 `log.Printf` 是非结构化的,先换 `log/slog` 比接 Loki 更划算。
|
||||
|
||||
---
|
||||
|
||||
## 3. 指标目录
|
||||
|
||||
命名统一用 `vloop_` 前缀;Prometheus 的 `job` / `instance` 已经能区分 API 与 Worker,不再加 `service` 标签。
|
||||
|
||||
### 3.1 P0:最小可用集(6 组)
|
||||
|
||||
| 指标 | 类型 | 标签 | 埋点位置 | 回答的问题 |
|
||||
|---|---|---|---|---|
|
||||
| `vloop_http_requests_total` | Counter | `method, route, status` | `SetRouter` 注册的 `metrics.HTTPMiddleware()` | QPS、错误率、按路由定位 |
|
||||
| `vloop_http_request_duration_seconds` | Histogram | `method, route` | 同上,`c.Next()` 之后 Observe | p95 / p99、慢接口 |
|
||||
| `vloop_http_in_flight_requests` | Gauge | — | 同上,进入 +1 / 退出 -1 | 并发与卡死 |
|
||||
| `vloop_mq_enabled` | Gauge | — | API/Worker 启动时按 `rmq != nil` 设置 | 区分“没启用 MQ”与“启用了但断了” |
|
||||
| `vloop_mq_connected` | Gauge | — | `metrics.RegisterMQStats` 读 `Stats()` | broker 是否可用,**有历史** |
|
||||
| `vloop_mq_publish_total` | Counter | `domain, result` | 各 `*MQ.Publish*` 包装 | 发布失败率 |
|
||||
| `vloop_mq_consume_total` | Counter | `queue, result` | `dlx.go` 的 `handleOne`,按 `Disposition*` 分支 | ack / retry / park 速率 |
|
||||
| `vloop_outbox_pending` | Gauge | — | `worker/outboxworker.go` 每轮批次 | outbox 积压 |
|
||||
| `vloop_write_fallback_total` | Counter | `domain, reason` | `like` / `comment` / `social` service 的降级分支 | 异步能力降级比例 |
|
||||
|
||||
这 9 个指标对应 6 个问题:接口是否变慢/报错、MQ 是否可用、发布是否失败、消费是否重试/停泊、outbox 是否堆积、写路径是否降级。
|
||||
|
||||
### 3.2 P1:MQ 与异步链路
|
||||
|
||||
| 指标 | 类型 | 标签 | 埋点位置 |
|
||||
|---|---|---|---|
|
||||
| `vloop_mq_reconnects_total` | Counter | — | `Stats().Reconnects`,自定义 Collector 以 Counter 语义输出 |
|
||||
| `vloop_mq_connection_generation` | Gauge | — | `Stats().Generation` |
|
||||
| `vloop_mq_topology_count` | Gauge | — | `Stats().Topology` |
|
||||
| `vloop_mq_last_up_timestamp_seconds` | Gauge | — | `Stats().LastUpAt` |
|
||||
| `vloop_mq_last_down_timestamp_seconds` | Gauge | — | `Stats().LastDownAt` |
|
||||
| `vloop_mq_publish_duration_seconds` | Histogram | `domain` | 发布包装 |
|
||||
| `vloop_mq_consume_duration_seconds` | Histogram | `queue` | `handleOne` 的 `process` 前后 |
|
||||
| `vloop_consumer_up` | Gauge | `consumer` | `RunConsumer` 进入消费循环置 1,退出置 0 |
|
||||
| `vloop_consumer_restarts_total` | Counter | `consumer, reason` | `RunConsumer` 的 `connLost` / channel 异常分支 |
|
||||
| `vloop_outbox_oldest_age_seconds` | Gauge | — | 批次首条的 `CreateTime` 与 `now` 之差 |
|
||||
| `vloop_outbox_publish_total` | Counter | `result` | outbox 发布成功/失败 |
|
||||
|
||||
队列深度、未 ack 数、发布速率不自己算,交给 RabbitMQ 的 `rabbitmq_prometheus` 插件:`rabbitmq_queue_messages`、`rabbitmq_queue_messages_ready`、`rabbitmq_queue_messages_unacked`、`rabbitmq_queue_messages_published_total`。停泊队列 `failed.events` 的深度用 `rabbitmq_queue_messages{queue="failed.events"}`。
|
||||
|
||||
### 3.3 P1:缓存与依赖
|
||||
|
||||
| 指标 | 类型 | 标签 | 埋点位置 |
|
||||
|---|---|---|---|
|
||||
| `vloop_cache_requests_total` | Counter | `layer=l1\|l2, result=hit\|miss` | `feed/service.go` 的 `GetVideoByIDs` |
|
||||
| `vloop_cache_fallbacks_total` | Counter | `reason=redis_error\|miss` | 同上,Redis MGet 失败或超时 |
|
||||
| `vloop_cache_singleflight_total` | Counter | `result=leader\|shared` | 同上,`requestGroup.Do` 前后 |
|
||||
| `vloop_feed_ranking_source_total` | Counter | `source=hot\|hot_db\|latest` | `ListByPopularity` 返回响应处 |
|
||||
| `vloop_redis_command_duration_seconds` | Histogram | `cmd` | go-redis `Hook`,在 `rediscache.NewClient` 注册 |
|
||||
| `vloop_redis_errors_total` | Counter | `cmd` | 同一个 Hook |
|
||||
| `vloop_redis_pool_connections` | Gauge | `state=total\|idle\|stale` | `redis.PoolStats()` |
|
||||
| `vloop_redis_pool_events_total` | Counter | `event=hits\|misses\|timeouts` | 同上 |
|
||||
| `vloop_db_connections` | Gauge | `state=open\|in_use\|idle` | `sql.DB.Stats()` |
|
||||
| `vloop_db_wait_total` | Counter | — | `sql.DBStats.WaitCount` |
|
||||
| `vloop_db_wait_duration_seconds_total` | Counter | — | `sql.DBStats.WaitDuration` |
|
||||
| `vloop_db_max_open_connections` | Gauge | — | `sql.DBStats.MaxOpenConnections` |
|
||||
|
||||
`vloop_feed_ranking_source_total` 直接对应 `docs/design/热度排行榜.md` §6.8 记录的空缺:当时只能靠响应里的 `ranking_source` 判断走了哪条路,无法量化 `hot_db` 回退率。
|
||||
|
||||
### 3.4 P2:限流、SSE、业务
|
||||
|
||||
| 指标 | 类型 | 标签 | 埋点位置 |
|
||||
|---|---|---|---|
|
||||
| `vloop_ratelimit_requests_total` | Counter | `rule, result=allowed\|rejected\|fail_open` | `middleware/ratelimit` 的 `Limit` |
|
||||
| `vloop_sse_clients` | Gauge | — | `worker/ssehub.go` 的 `Subscribe` / `Unsubscribe` |
|
||||
| `vloop_auth_failures_total` | Counter | `reason=missing\|invalid\|expired\|redis_error` | `middleware/jwt` |
|
||||
| `vloop_business_events_total` | Counter | `domain, action, result` | 各 service 成功/降级分支 |
|
||||
| `vloop_build_info` | Gauge | `version, commit, go_version` | 启动时设置 |
|
||||
|
||||
`vloop_ratelimit_requests_total{result="fail_open"}` 是安全信号:`ratelimit.Limit` 在 Redis 出错时会直接放行,限流静默失效,这条指标是唯一能发现它的地方。
|
||||
|
||||
### 3.5 命名与基数规则
|
||||
|
||||
- 计数器以 `_total` 结尾;时间用 `_seconds`;字节用 `_bytes`。
|
||||
- 标签只允许:`method`、`route`、`status`、`queue`、`consumer`、`domain`、`result`、`layer`、`rule`、`source`、`cmd`、`state`、`event`、`reason`。
|
||||
- 禁止:`account_id`、`video_id`、`ip`、原始 URL、错误文本、trace ID。
|
||||
- `route` 取 `c.FullPath()`;404 或未匹配路由统一记 `"unmatched"`,绝不把请求路径拼进标签。
|
||||
- `status` 用三位状态码字符串(`"200"`、`"500"`),不用 `2xx` / `5xx` 粗分类;本项目的路由数量下基数可控。
|
||||
- 直方图桶:`0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10` 秒。
|
||||
- **SSE 不计入 `vloop_http_request_duration_seconds`**:`/notification/stream` 的连接可能存活数小时,会把 p99 拉到没有意义。`in_flight` 可以计入,但要在面板上单独解释。
|
||||
- 计数器在进程重启后归零是正常的;查询用 `rate` / `increase`,不要用 `delta` 跨重启做减法。
|
||||
|
||||
### 3.6 反模式
|
||||
|
||||
- 把 pprof 的采样结果转成指标:没有意义,pprof 数据是给 `go tool pprof` 看的。
|
||||
- 每个 handler 一条独立指标名:标签能解决的事不要复制指标名。
|
||||
- 用指标做审计或计费:计数器会丢、会重置、会被抓取间隔平均掉。
|
||||
- 在热路径拼字符串标签:`strconv` 也有成本,标签值必须来自有限集合。
|
||||
|
||||
---
|
||||
|
||||
## 4. 采集与展示
|
||||
|
||||
### 4.1 compose 新增服务
|
||||
|
||||
两份 compose 都加同样的两个服务;`docker-compose.yml` 用默认密码方便本地,`docker-compose.prod.yml` 用 `:?` 强制设置。
|
||||
|
||||
```yaml
|
||||
prometheus:
|
||||
image: prom/prometheus:v3.2.1
|
||||
profiles: ["monitoring"]
|
||||
restart: unless-stopped
|
||||
command:
|
||||
- --config.file=/etc/prometheus/prometheus.yml
|
||||
- --storage.tsdb.path=/prometheus
|
||||
- --storage.tsdb.retention.time=15d
|
||||
- --storage.tsdb.retention.size=5GB
|
||||
- --web.enable-lifecycle
|
||||
volumes:
|
||||
- ./monitoring/prometheus:/etc/prometheus:ro
|
||||
- prometheus_data:/prometheus
|
||||
ports:
|
||||
- "127.0.0.1:9090:9090"
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:9090/-/healthy || exit 1"]
|
||||
interval: 15s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
|
||||
grafana:
|
||||
image: grafana/grafana:11.6.0
|
||||
profiles: ["monitoring"]
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
GF_SECURITY_ADMIN_PASSWORD: ${GRAFANA_ADMIN_PASSWORD:?set GRAFANA_ADMIN_PASSWORD}
|
||||
GF_USERS_ALLOW_SIGN_UP: "false"
|
||||
GF_AUTH_ANONYMOUS_ENABLED: "false"
|
||||
volumes:
|
||||
- ./monitoring/grafana/provisioning:/etc/grafana/provisioning:ro
|
||||
- ./monitoring/grafana/dashboards:/var/lib/grafana/dashboards:ro
|
||||
- grafana_data:/var/lib/grafana
|
||||
ports:
|
||||
- "127.0.0.1:3000:3000"
|
||||
depends_on:
|
||||
- prometheus
|
||||
```
|
||||
|
||||
版本号只是示例,落地时固定到当时的稳定 patch tag,不要用 `latest`。`profiles` 是关键:CI 的 `docker compose -f docker-compose.prod.yml up -d --wait --remove-orphans` 不会启动它们,也不会因为“未定义”而删掉已经手动启动的容器——profile 里的服务仍然属于当前项目配置。
|
||||
|
||||
启动与更新:
|
||||
|
||||
```bash
|
||||
docker compose -f docker-compose.prod.yml --profile monitoring up -d prometheus grafana
|
||||
# 只改了 prometheus.yml 时,不必重建容器:
|
||||
docker compose -f docker-compose.prod.yml exec prometheus wget -qO- --post-data= http://127.0.0.1:9090/-/reload
|
||||
```
|
||||
|
||||
### 4.2 Prometheus 配置
|
||||
|
||||
`monitoring/prometheus/prometheus.yml`:
|
||||
|
||||
```yaml
|
||||
global:
|
||||
scrape_interval: 15s
|
||||
scrape_timeout: 10s
|
||||
evaluation_interval: 15s
|
||||
|
||||
rule_files:
|
||||
- /etc/prometheus/alerts.yml
|
||||
|
||||
scrape_configs:
|
||||
- job_name: prometheus
|
||||
static_configs:
|
||||
- targets: ["localhost:9090"]
|
||||
|
||||
- job_name: vloop-api
|
||||
static_configs:
|
||||
- targets: ["backend:6060"]
|
||||
|
||||
- job_name: vloop-worker
|
||||
static_configs:
|
||||
- targets: ["worker:6061"]
|
||||
|
||||
- job_name: rabbitmq
|
||||
static_configs:
|
||||
- targets: ["rabbitmq:15692"]
|
||||
```
|
||||
|
||||
`backend` / `worker` 是 compose 的服务名,直接作为 DNS 名使用。
|
||||
|
||||
### 4.3 RabbitMQ 插件
|
||||
|
||||
`rabbitmq:3-management` 自带 `rabbitmq_prometheus`,但默认只输出聚合指标;要让 `rabbitmq_queue_messages{queue="..."}` 可用,必须打开 per-object 指标。
|
||||
|
||||
`monitoring/rabbitmq/enabled_plugins`:
|
||||
|
||||
```
|
||||
[rabbitmq_management,rabbitmq_prometheus].
|
||||
```
|
||||
|
||||
`monitoring/rabbitmq/rabbitmq.conf`:
|
||||
|
||||
```ini
|
||||
prometheus.return_per_object_metrics = true
|
||||
```
|
||||
|
||||
把这两个文件挂到 `rabbitmq` 服务:
|
||||
|
||||
```yaml
|
||||
volumes:
|
||||
- ./monitoring/rabbitmq/enabled_plugins:/etc/rabbitmq/enabled_plugins:ro
|
||||
- ./monitoring/rabbitmq/rabbitmq.conf:/etc/rabbitmq/rabbitmq.conf:ro
|
||||
```
|
||||
|
||||
注意 `enabled_plugins` 必须同时保留 `rabbitmq_management`,否则会覆盖 `-management` 镜像自带的启用列表。修改后 `docker compose restart rabbitmq`。如果镜像里没有该插件(旧版本),退路是进容器执行 `rabbitmq-plugins enable rabbitmq_prometheus`,或改用 Management API 采集。
|
||||
|
||||
### 4.4 Grafana provisioning
|
||||
|
||||
目录:
|
||||
|
||||
```
|
||||
monitoring/grafana/
|
||||
provisioning/
|
||||
datasources/prometheus.yml
|
||||
dashboards/dashboards.yml
|
||||
dashboards/
|
||||
vloop-overview.json
|
||||
vloop-http.json
|
||||
vloop-async.json
|
||||
vloop-runtime.json
|
||||
```
|
||||
|
||||
数据源:
|
||||
|
||||
```yaml
|
||||
apiVersion: 1
|
||||
datasources:
|
||||
- name: Prometheus
|
||||
type: prometheus
|
||||
access: proxy
|
||||
url: http://prometheus:9090
|
||||
isDefault: true
|
||||
editable: false
|
||||
```
|
||||
|
||||
面板提供者:
|
||||
|
||||
```yaml
|
||||
apiVersion: 1
|
||||
providers:
|
||||
- name: vloop
|
||||
folder: VLoop
|
||||
type: file
|
||||
options:
|
||||
path: /var/lib/grafana/dashboards
|
||||
```
|
||||
|
||||
面板 JSON 入库,Grafana 只做展示,不做唯一副本;换机器、重建容器都能恢复。
|
||||
|
||||
### 4.5 面板分组
|
||||
|
||||
| 面板 | 内容 |
|
||||
|---|---|
|
||||
| Overview | QPS、5xx 比例、p95、in-flight、goroutine、RSS、MQ connected、outbox pending、缓存命中率 |
|
||||
| HTTP | 按路由的 QPS / 错误率 / 延迟热力图,Top N 慢路由 |
|
||||
| Async | publish 速率与失败、consume 按 `result` 的速率、park 速率、`failed.events` 深度、outbox 数量与最老年龄 |
|
||||
| Runtime | DB 连接与等待、Redis 池与错误、GC / goroutine、进程 CPU / 内存 |
|
||||
|
||||
### 4.6 告警
|
||||
|
||||
Prometheus 规则文件 `monitoring/prometheus/alerts.yml`:
|
||||
|
||||
| 告警 | 表达式 | `for` | 说明 |
|
||||
|---|---|---|---|
|
||||
| `APIDown` | `up{job="vloop-api"} == 0` | 2m | 抓不到目标 |
|
||||
| `ErrorRateHigh` | `sum(rate(vloop_http_requests_total{status=~"5.."}[5m])) / clamp_min(sum(rate(vloop_http_requests_total[5m])), 0.001) > 0.01` | 5m | 5xx 超过 1% |
|
||||
| `LatencyP95High` | `histogram_quantile(0.95, sum by (le) (rate(vloop_http_request_duration_seconds_bucket[5m]))) > 0.5` | 5m | p95 超过 500ms |
|
||||
| `MQDisconnected` | `vloop_mq_enabled == 1 and vloop_mq_connected == 0` | 2m | 启用了但断开 |
|
||||
| `MessagesParked` | `sum(rate(vloop_mq_consume_total{result="park"}[5m])) > 0` | 1m | 有消息进 DLQ |
|
||||
| `DLQNotEmpty` | `rabbitmq_queue_messages{queue="failed.events"} > 0` | 5m | 停泊队列非空 |
|
||||
| `OutboxBacklog` | `vloop_outbox_pending > 100` | 10m | outbox 积压 |
|
||||
| `OutboxStalled` | `vloop_outbox_oldest_age_seconds > 60` | 5m | 最老消息超过 1 分钟 |
|
||||
| `RateLimitFailOpen` | `sum(rate(vloop_ratelimit_requests_total{result="fail_open"}[5m])) > 0` | 5m | Redis 故障导致限流失效 |
|
||||
| `DBConnSaturated` | `vloop_db_connections{state="in_use"} / vloop_db_max_open_connections > 0.9` | 5m | 连接池接近上限 |
|
||||
|
||||
`MQDisconnected` 必须带 `vloop_mq_enabled == 1`,否则“故意不启用 MQ 的本地环境”会一直告警。
|
||||
|
||||
通知两条路:
|
||||
|
||||
- **Prometheus 规则 + Alertmanager**:规则可 `promtool check rules`,可版本化,适合长期维护;多一个容器。
|
||||
- **Grafana 统一告警**:不引入 Alertmanager,联系点与静默都在 Grafana 里配;规则 schema 随 Grafana 版本变化,迁移成本略高。
|
||||
|
||||
本项目建议先落地 Prometheus 规则(先能在 Grafana 看到 firing),有明确通知渠道后再加 Alertmanager;不要为了“告警”先引入一个没人看的通知链路。
|
||||
|
||||
---
|
||||
|
||||
## 5. 实施计划
|
||||
|
||||
### 阶段 0:骨架(约 0.5–1 人日)
|
||||
|
||||
1. `go get github.com/prometheus/client_golang`,`go mod tidy`。
|
||||
2. 新建 `backend/internal/metrics`:注册 Go / process / build info 默认采集器,提供 `Handler()`。
|
||||
3. `backend/internal/observability/pprof.go` 改名为 `admin.go`:`AdminOptions{Name, Enabled, Addr, Pprof, Health, Gatherer}`,mux 注册 `/metrics`,可选 pprof 与 `/healthz`;补 `ReadTimeout`、`IdleTimeout`、`MaxHeaderBytes`。
|
||||
4. 配置改成 `observability.admin`;改三份 YAML、`DefaultLocalConfig`、`loadconfig_test.go`。
|
||||
5. API 与 Worker 的 `main` 接入;启动日志打印 `admin listening on ... (metrics=true, pprof=...)`。
|
||||
6. 测试:`/metrics` 200、pprof 开关、disabled 返回 nil。
|
||||
|
||||
验收:
|
||||
|
||||
```bash
|
||||
curl -s http://127.0.0.1:6060/metrics | grep '^go_goroutines'
|
||||
curl -s http://127.0.0.1:6061/metrics | grep '^go_goroutines'
|
||||
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:6060/debug/pprof/
|
||||
go vet ./... && go test -race -count=1 ./...
|
||||
```
|
||||
|
||||
### 阶段 1:关键路径 + 监控栈(约 1–2 人日)
|
||||
|
||||
1. `metrics.HTTPMiddleware()`:`requests_total`、`duration`、`in_flight`;`route` 用 `c.FullPath()`;SSE 排除出直方图。
|
||||
2. `metrics.RegisterMQStats`:自定义 Collector 输出连接、代次、重连、拓扑、时间戳。
|
||||
3. 发布与消费埋点:`*MQ.Publish*`、`dlx.go` 的 `handleOne`;写路径降级计数。
|
||||
4. outbox 积压与最老年龄;批次首条的 `CreateTime` 直接可用。
|
||||
5. 两份 compose 加 `monitoring` profile、Prometheus 配置、Grafana 数据源与 Overview 面板。
|
||||
6. Worker healthcheck 改 `wget -qO- http://127.0.0.1:6061/healthz`。
|
||||
|
||||
验收:停掉 RabbitMQ,`vloop_mq_connected` 在 15s 内变 0,恢复后 `vloop_mq_reconnects_total` 增长;制造一条停泊消息,`result="park"` 增长;插入一条 pending outbox,`vloop_outbox_pending` 增长。
|
||||
|
||||
### 阶段 2:业务与资源(约 2 人日)
|
||||
|
||||
1. 缓存命中/回退/singleflight、ranking source。
|
||||
2. go-redis Hook、DB 连接池 Collector。
|
||||
3. 限流拒绝与 fail-open、SSE 在线数、JWT 失败原因。
|
||||
4. RabbitMQ 插件与 per-object 指标。
|
||||
5. 告警规则;需要时加 Alertmanager。
|
||||
6. HTTP / Async / Runtime 三个面板。
|
||||
7. 更新 `README.md`、`docs/feedsystem_video_go项目设计.md` 的可观测性段落。
|
||||
|
||||
验收:命中 L1/L2 时命中率变化;超过登录限流时 `result="rejected"` 增长;停 Redis 时 `fail_open` 增长;`promtool check rules` 通过。
|
||||
|
||||
### 阶段 3:可选
|
||||
|
||||
- OpenTelemetry tracing + Tempo(先给 MQ 发布/消费加 trace context)。
|
||||
- `log/slog` 结构化日志 + Loki。
|
||||
- pprof block / mutex 采样、`fgprof`。
|
||||
- Grafana 告警替代 Alertmanager,或反过来统一。
|
||||
|
||||
### 改动文件清单
|
||||
|
||||
| 文件 | 动作 |
|
||||
|---|---|
|
||||
| `backend/go.mod`、`backend/go.sum` | 加 `client_golang` |
|
||||
| `backend/internal/metrics/*.go` | 新增:采集器、HTTP 中间件、DB/Redis/MQ Collector |
|
||||
| `backend/internal/observability/admin.go` | 由 `pprof.go` 改造:mux + 超时 + `/metrics` |
|
||||
| `backend/internal/observability/admin_test.go` | 新增/改造测试 |
|
||||
| `backend/internal/config/loadconfig.go` | `AdminConfig`,替换 `PprofConfig` |
|
||||
| `backend/configs/*.yaml` | 三份配置迁移 |
|
||||
| `backend/cmd/main.go`、`backend/cmd/worker/main.go` | 接入 admin server 与 Collector |
|
||||
| `backend/internal/http/router.go` | 注册 HTTP 中间件 |
|
||||
| `backend/internal/middleware/rabbitmq/*.go` | 发布/消费/连接指标 |
|
||||
| `backend/internal/worker/outboxworker.go`、`ssehub.go` | outbox 与 SSE 指标 |
|
||||
| `backend/internal/feed/service.go` | 缓存与 ranking source 指标 |
|
||||
| `backend/internal/middleware/ratelimit/ratelimit.go` | 限流结果指标 |
|
||||
| `backend/internal/middleware/redis/redis.go` | Hook 与池指标 |
|
||||
| `docker-compose.yml`、`docker-compose.prod.yml` | prometheus/grafana、profile、rabbitmq 配置挂载、worker healthcheck |
|
||||
| `monitoring/**` | Prometheus 配置、规则、Grafana provisioning、dashboard JSON |
|
||||
| `.env.example` | `GRAFANA_ADMIN_PASSWORD` |
|
||||
| `README.md`、设计文档 | 同步 |
|
||||
|
||||
---
|
||||
|
||||
## 6. 测试策略
|
||||
|
||||
按仓库的 TDD 约定:先写失败测试,再写实现;测试放在被覆盖代码的同包。
|
||||
|
||||
| 测试 | 位置 | 断言 |
|
||||
|---|---|---|
|
||||
| `TestAdminMux_ServesMetrics` | `observability/admin_test.go` | `/metrics` 200,body 含 `go_goroutines` |
|
||||
| `TestAdminMux_PprofToggle` | 同上 | `pprof=false` 时 `/debug/pprof/` 404,`true` 时 200 |
|
||||
| `TestAdminServer_DisabledReturnsNil` | 同上 | 保持现有行为 |
|
||||
| `TestAdminMux_WorkerHealthz` | 同上 | `/healthz` 200,JSON 含 `"status":"ok"` |
|
||||
| `TestHTTPMiddleware_RecordsStatusAndRoute` | `metrics/http_test.go` | 请求后对应 `method/route/status` 的计数 +1 |
|
||||
| `TestHTTPMiddleware_UnmatchedRouteIsBounded` | 同上 | 任意 404 都落到 `route="unmatched"`,不出现原始路径 |
|
||||
| `TestHTTPMiddleware_SSEExcludedFromHistogram` | 同上 | SSE 路由的直方图样本数不变 |
|
||||
| `TestConsumeLoop_ParkIncrementsCounter` | `middleware/rabbitmq/consume_test.go` | 永久错误/耗尽重试后 `result="park"` +1 |
|
||||
| `TestObserveOutbox_FromBatch` | `worker/outboxworker_test.go` | 批次首条 `CreateTime` 转成年龄;空批为 0 |
|
||||
| `TestConfig_AdminBlock` | `config/loadconfig_test.go` | YAML 能解析出 `admin` 字段 |
|
||||
|
||||
注意两点:
|
||||
|
||||
- 指标是包级全局变量,测试之间会累计。断言用**前后差值**,不要断言绝对值;共享计数器的子测试不要 `t.Parallel()`。
|
||||
- 需要隔离时,`AdminOptions.Gatherer` 传 `prometheus.NewRegistry()`;生产传 `nil` 用默认注册表。不要为了测试在业务包里到处传 registry。
|
||||
|
||||
验证命令与仓库一致:
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
go vet ./...
|
||||
go test -race -count=1 ./...
|
||||
```
|
||||
|
||||
需要真实 broker / MySQL 的验证放到 `//go:build integration`,通过 `RABBITMQ_TEST_URL` 等环境变量配置,缺前置条件时 `t.Skip`。
|
||||
|
||||
---
|
||||
|
||||
## 7. 风险与取舍
|
||||
|
||||
| 风险 | 影响 | 处理 |
|
||||
|---|---|---|
|
||||
| 配置迁移静默关闭 admin | 指标与 pprof 同时消失 | 三份 YAML 同提交迁移;Worker healthcheck 依赖 admin `/healthz`;启动日志明确打印 |
|
||||
| 标签基数爆炸 | Prometheus 内存与查询变慢 | `route` 用模板;禁止 ID/IP/错误文本;代码评审检查新标签 |
|
||||
| SSE 污染延迟直方图 | p95/p99 失真 | 按 `Content-Type` 排除;面板单独解释 in-flight |
|
||||
| pprof 信息泄露 / DoS | 启动参数、堆内容、CPU 采样被滥用 | 只在内网;不 publish 6060/6061;需要时加 Bearer token;限制 `?seconds` |
|
||||
| Grafana 暴露公网 | 默认口令被撞 | 只绑 `127.0.0.1`,SSH 隧道访问;强口令;关闭匿名与注册 |
|
||||
| 单机 Prometheus 与业务同生共死 | 宿主机故障时监控也丢 | 本项目可接受;需要时 `remote_write` 到云端;面板 JSON 入库 |
|
||||
| CI 的 `--remove-orphans` | 误删监控容器 | 同项目 + `profiles`;profile 服务仍算已定义 |
|
||||
| 国内拉镜像慢 | 首次启动监控栈很慢 | 使用镜像加速;CI 不启动监控,不影响部署时长 |
|
||||
| 依赖体积 | 构建变慢、二进制变大 | 只加 `client_golang`;`go mod tidy`;不引入 OTel |
|
||||
| 全局注册表与测试冲突 | 重复注册 panic、计数串扰 | 生产用默认注册表;测试用差值或独立 registry;`AdminOptions.Gatherer` 可注入 |
|
||||
| 抓取间隔与告警延迟 | 短故障漏报或告警滞后 | 15s 抓取;告警 `for` 至少 1–2 分钟;不要用单点采样做判断 |
|
||||
|
||||
---
|
||||
|
||||
## 8. 待确认
|
||||
|
||||
1. 监控栈部署在同一台 ECS(本方案默认),还是用 Grafana Cloud / 外部 Prometheus?如果走外部,`/metrics` 需要 TLS 与鉴权,端口暴露策略要重做。
|
||||
2. 是否需要 MySQL / Redis / Node exporter?应用内已经能给出连接池与命令延迟;外部 exporter 补的是服务端视角(慢查询、keyspace、磁盘)。建议第二阶段再决定。
|
||||
3. 告警通知走什么渠道(邮件 / Webhook / 企业微信)?没有渠道之前,先让规则在 Grafana 可见即可。
|
||||
4. 是否现在实施阶段 0–1?这两步已经能覆盖大部分排障需求,且不改业务逻辑。
|
||||
|
||||
---
|
||||
|
||||
## 附录 A:pprof 常用命令
|
||||
|
||||
```bash
|
||||
# CPU(默认 30s)
|
||||
go tool pprof http://127.0.0.1:6060/debug/pprof/profile?seconds=30
|
||||
|
||||
# 堆
|
||||
go tool pprof http://127.0.0.1:6060/debug/pprof/heap
|
||||
|
||||
# 浏览器里看火焰图
|
||||
go tool pprof -http=:8081 http://127.0.0.1:6061/debug/pprof/profile
|
||||
|
||||
# 在容器里看 goroutine 摘要(Alpine 自带 wget)
|
||||
docker compose exec backend wget -qO- 'http://127.0.0.1:6060/debug/pprof/goroutine?debug=1' | head
|
||||
```
|
||||
|
||||
## 附录 B:与现有问题清单的对应
|
||||
|
||||
| 编号 | 本文对应 |
|
||||
|---|---|
|
||||
| `docs/ISSUES-REPORT.md` A-7(除 pprof 外无指标) | 整个方案 |
|
||||
| `docs/ISSUES-REPORT.md` P3-25(pprof 缺超时与鉴权) | §1.4、§2.3 |
|
||||
| `docs/ISSUES-REPORT.md` P3-39(worker 用 `pgrep` 探针) | §2.3、阶段 1 |
|
||||
| `docs/design/热度排行榜.md` §6.8(回退比例不可观测) | `vloop_feed_ranking_source_total` |
|
||||
| `docs/ISSUES-REPORT.md` D-18(README 与 compose 的 pprof 默认值不一致) | §1.3、阶段 2 文档更新 |
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
本文说明异步写路径(点赞、评论、关注、热度、通知)在消息**处理失败**时的完整实现:消息怎么被重投、重试次数记在哪里、什么时候停止重试、停泊到哪、谁把停泊消息落库、出问题时看什么。
|
||||
|
||||
读者只需要知道本项目的写路径结构:API 把事件发到 RabbitMQ,Worker 进程(以及 API 进程里的通知消费者)把事件写成数据库行与 Redis 计数。
|
||||
读者只需要知道本项目的写路径结构:API 把事件发到 RabbitMQ,Worker 进程把事件写成数据库行与 Redis 计数。
|
||||
|
||||
---
|
||||
|
||||
@@ -86,7 +86,7 @@ func RetryExchange(queue string) string { return RetryExchangePrefix + queue }
|
||||
func RetryQueueName(queue string) string { return queue + RetryQueueSuffix } // <Q>.retry
|
||||
```
|
||||
|
||||
项目里的 8 个业务队列都会得到自己的一组:`social.events`、`like.events`、`comment.events`、`video.popularity.events`、`notification.like`、`notification.comment`、`notification.social`、`video.timeline.update.queue`。
|
||||
项目里的 7 个业务队列都会得到自己的一组:`like.events`、`comment.events`、`video.popularity.events`、`notification.like`、`notification.comment`、`notification.social`、`video.timeline.update.queue`。
|
||||
|
||||
---
|
||||
|
||||
@@ -562,7 +562,7 @@ go mqrabbit.RunConsumer(ctx, rmqMgr, "LikeWorker", 50, func(ch *amqp.Channel) er
|
||||
|
||||
`*RabbitMQ` 实现了 `Parker` 接口,测试里可以换成假实现验证"停泊失败必须 requeue"。
|
||||
|
||||
通知消费者跑在 API 进程(`router.go`),三个队列各一个 goroutine,prefetch = 10,同样传 `rmq` 作 parker。它们产生的停泊消息落到同一个 durable 队列,由 Worker 进程落库——API 进程不需要知道 `failed_events` 的存在。
|
||||
通知消费者同样跑在 Worker 进程(`cmd/worker/main.go`),三个队列各一个 goroutine,prefetch = 10,同样传 `rmq` 作 parker。它们产生的停泊消息落到同一个 durable 队列,由 `FailedEventWorker` 落库(P1-1 之前这三个消费者在 API 进程,现已整体迁出)。
|
||||
|
||||
建表入口只有一个:API 进程启动时的 `db.AutoMigrate`(`db.go` 的 `AutoMigrate`)里包含 `&failedevent.FailedEvent{}`。Worker 侧刻意不 `AutoMigrate`,否则多个消费者并发 `CREATE INDEX` 会撞 1061。
|
||||
|
||||
@@ -667,6 +667,6 @@ rabbitmqctl list_queues name messages | grep '\.retry'
|
||||
|
||||
## 相关文档
|
||||
|
||||
- 写路径如何吸收重复投递:`docs/design/write-path-idempotency.md`
|
||||
- 热度榜如何由事务结果驱动、坏了怎么重建:`docs/design/hot-ranking.md`
|
||||
- 写路径如何吸收重复投递:`docs/design/写路径幂等.md`
|
||||
- 热度榜如何由事务结果驱动、坏了怎么重建:`docs/design/热度排行榜.md`
|
||||
- 落地细节、迁移与验证:`docs/solutions/P0-3-P0-4-retry-and-idempotency.md`
|
||||
@@ -582,7 +582,7 @@ flowchart LR
|
||||
|
||||
### 7.3 消息失败:重投、停泊与 `occurred_at`
|
||||
|
||||
热榜复用消息失败处理的整套机制(见 `docs/design/message-failure-handling.md`),这里只列与本模块相关的部分:
|
||||
热榜复用消息失败处理的整套机制(见 `docs/design/消息处理失败与死信队列.md`),这里只列与本模块相关的部分:
|
||||
|
||||
| 情况 | 对热榜的影响 |
|
||||
|---|---|
|
||||
@@ -801,6 +801,6 @@ WHERE v.likes_count <> COALESCE(l.c, 0)
|
||||
|
||||
## 相关文档
|
||||
|
||||
- 写路径如何吸收重复投递、意图键怎么设计:`docs/design/write-path-idempotency.md`
|
||||
- 消息处理失败、重试与停泊:`docs/design/message-failure-handling.md`
|
||||
- 写路径如何吸收重复投递、意图键怎么设计:`docs/design/写路径幂等.md`
|
||||
- 消息处理失败、重试与停泊:`docs/design/消息处理失败与死信队列.md`
|
||||
- 项目整体构建路线:`docs/project-construction-guide.md`
|
||||
@@ -11,8 +11,8 @@
|
||||
| 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`;队列均声明 `x-dead-letter-exchange=dlx.events`(死信重试链路尚未接线,见 P0-3);发布失败异常降级直写。连接由 `middleware/rabbitmq` 的连接管理器持有:断连自动重连、每一代连接自动重放拓扑(见“RabbitMQ 优化部分”)。 |
|
||||
| 异步执行 | Worker(Go) | `cmd/worker`:LikeWorker/CommentWorker/SocialWorker/PopularityWorker;API 进程内启动 OutboxPoller、TimelineConsumer 与 NotificationWorker。 |
|
||||
| 消息队列 | RabbitMQ(可选) | Topic 事件总线:`like.events`、`comment.events`、`social.events`、`video.popularity.events`、`video.timeline.events`;队列均声明 `x-dead-letter-exchange=dlx.events`(死信重试链路尚未接线,见 P0-3);like/comment 发布失败降级直写,关注是 DB-first,事件只做通知。连接由 `middleware/rabbitmq` 的连接管理器持有:断连自动重连、每一代连接自动重放拓扑(见“RabbitMQ 优化部分”)。 |
|
||||
| 异步执行 | Worker(Go) | `cmd/worker`:全部 MQ 消费者(Like/Comment/Social/Notification×3/Parked)以及 OutboxPoller、TimelineConsumer。API 进程只做 HTTP 与 SSE,不启动任何消费者(P1-1)。 |
|
||||
| 文件存储 | Local Disk(可替换对象存储) | 视频与封面文件存放本地目录(生产可替换为 OSS/S3/MinIO)。 |
|
||||
| 容器化/依赖编排 | Docker / Docker Compose | 一键拉起 RabbitMQ 等依赖(可配合 `./start.sh`),便于本地联调与部署环境一致性。 |
|
||||
| 接口调试 | Postman Collection | `test/postman.json`:预置变量、批量跑接口与部分断言脚本。 |
|
||||
@@ -106,8 +106,8 @@
|
||||
|
||||
| 层级 | 方法/路由 | 输入 -> 输出 | 存储(MySQL/MQ) | 核心说明 |
|
||||
| ----------------- | ------------------------------------------------ | ---------------------------------- | -------------------- | -------------------------------------------- |
|
||||
| Handler | POST `/social/follow` | `{vlogger_id}` -> `{}` | MQ ✅(可选) / MySQL ✅ | JWT 保护;关注事件可异步写入。 |
|
||||
| Handler | POST `/social/unfollow` | `{vlogger_id}` -> `{}` | MQ ✅(可选) / MySQL ✅ | 取关事件可异步写入。 |
|
||||
| Handler | POST `/social/follow` | `{vlogger_id}` -> `{message,created}` | MySQL ✅(DB-first) | JWT 保护;`created` 说明本次是否真的插入。事件只做通知:`social.follow` → `notification.social`。 |
|
||||
| Handler | POST `/social/unfollow` | `{vlogger_id}` -> `{message,deleted}` | MySQL ✅(DB-first) | `deleted` 说明本次是否真的删除。取关不发事件。 |
|
||||
| Handler | POST `/social/getAllFollowers` | `{vlogger_id?}` -> `{followers[]}` | MySQL ✅ | vlogger_id 可空:默认当前登录账号。 |
|
||||
| Handler | POST `/social/getAllVloggers` | `{follower_id?}` -> `{vloggers[]}` | MySQL ✅ | follower_id 可空:默认当前登录账号。 |
|
||||
| Handler | POST `/social/getCounts` | `{}` -> `{follower_count,vlogger_count}` | MySQL ✅ | 当前登录用户的粉丝数与关注数。 |
|
||||
@@ -151,7 +151,7 @@
|
||||
| Handler | POST `/notification/markRead` | `{id?}` -> `{message}` | MySQL ✅ | 传 `id` 标记单条,省略 `id` 标记当前用户全部通知。 |
|
||||
| Handler | POST `/notification/unreadCount` | `{}` -> `{count}` | MySQL ✅ | 当前用户未读通知计数。 |
|
||||
| Worker | `NotificationWorker` | MQ 事件 -> `notifications` + SSE Push | MQ ✅ / MySQL ✅ / SSE ✅ | 消费点赞、评论、关注事件,生成通知并推送在线连接。 |
|
||||
| Service(建议命名) | `SSEHub/List/MarkRead/UnreadCount/Push` | - | - | `SSEHub` 在 API 进程内维护每个用户的连接通道。 |
|
||||
| Service(建议命名) | `SSEHub/List/MarkRead/UnreadCount/Push` | - | - | `SSEHub` 维护本进程内每个用户的连接通道;通知由 Worker 经 Redis Pub/Sub 送达各 API 实例,再推给本地连接(P1-1)。 |
|
||||
|
||||
### 各个模块的关系
|
||||
|
||||
@@ -181,7 +181,7 @@
|
||||
| -------- | ----------------------------------------------------- | ------------- | --------------------------------------------------- | ------------------ | ------------------------------------------------------------ |
|
||||
| 点赞 | `like.events` / `like.like` `like.unlike` | 点赞/取消点赞 | `{event_id, action, user_id, video_id, occurred_at}` | `LikeWorker` / `NotificationWorker` | 发布失败:对失败目标降级直写(MySQL 或 Redis);点赞成功给视频作者生成通知。 |
|
||||
| 评论 | `comment.events` / `comment.publish` `comment.delete` | 发布/删除评论 | `{author_id, username, video_id, comment_id?, content?, ts}` | `CommentWorker` / `NotificationWorker` | 发布失败:降级直写 MySQL;热度增量事件失败则直接更新 Redis;评论成功给视频作者生成通知。 |
|
||||
| 关注 | `social.events` / `social.follow` `social.unfollow` | 关注/取关 | `{event_id, action, follower_id, vlogger_id, occurred_at}` | `SocialWorker` / `NotificationWorker` | 发布失败:降级直写 MySQL;关注成功给被关注者生成通知。 |
|
||||
| 关注 | `social.events` / `social.follow` | 关注 | `{event_id, action, follower_id, vlogger_id, occurred_at}` | `NotificationWorker` | 写库在 API 的 `SocialService` 内完成;事件只做通知。取关不发事件。 |
|
||||
| 热度增量 | `video.popularity.events` / `video.popularity.update` | 热度更新 | `{event_id, video_id, change, occurred_at}` | `PopularityWorker` | `UpdatePopularity` 发布失败:直接更新 Redis 热榜;并触发详情缓存失效(如需要)。 |
|
||||
| 时间线 | `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` / `#` | 失败消息 | 原始消息 | 暂未接线 | 队列已声明 `x-dead-letter-exchange=dlx.events` 并派生 `<queue>.dlx`;但当前消费者只用 `Ack` / `Nack(requeue=true)`,**死信链路尚未接线**(重试与 `x-death` 统计见 P0-3)。 |
|
||||
@@ -259,8 +259,8 @@ r.mu.Unlock()
|
||||
|
||||
| 消费者 | 所在进程 | 队列 | prefetch |
|
||||
| --- | --- | --- | --- |
|
||||
| `SocialWorker` / `LikeWorker` / `CommentWorker` / `PopularityWorker` | Worker | `social.events` / `like.events` / `comment.events` / `video.popularity.events` | 50 |
|
||||
| `notification-like` / `notification-comment` / `notification-social` | API | `notification.like` / `notification.comment` / `notification.social` | 10 |
|
||||
| `LikeWorker` / `CommentWorker` | Worker | `like.events` / `comment.events` | 50 |
|
||||
| `notification-like` / `notification-comment` / `notification-social` | Worker | `notification.like` / `notification.comment` / `notification.social` | 10 |
|
||||
| `TimelineConsumer` | API | `video.timeline.update.queue` | 10 |
|
||||
|
||||
```mermaid
|
||||
@@ -344,7 +344,7 @@ sequenceDiagram
|
||||
| `mq_connected` | `conn != nil && !conn.IsClosed()` | 核心状态;断开时 `/readyz` 返回 503 |
|
||||
| `mq_generation` | 成功连接的序号(`install` 时 +1) | 单调递增,可确认"确实重连过" |
|
||||
| `mq_reconnects` | 重连次数 | 频繁断连的量化指标 |
|
||||
| `mq_topology` | 已登记拓扑条数 | API 进程应为 8、Worker 进程应为 4;变小说明有拓扑漏登记 |
|
||||
| `mq_topology` | 已登记拓扑条数 | API 进程应为 3(like/comment/social 三个 publisher)、Worker 进程应为 6(like/comment 两个消费队列 + 三个通知队列 + timeline);变小说明有拓扑漏登记 |
|
||||
|
||||
# 整体架构
|
||||
|
||||
@@ -388,7 +388,7 @@ sequenceDiagram
|
||||
| 安全鉴权 | 软硬鉴权兼容模式 | 提供 `JWTAuth`(强制拦截)与 `SoftJWTAuth`(可不带 token;带了必须合法,否则 401)。 | 既支持匿名浏览 Feed,又支持登录态个性化(如点赞/关注状态),体验与安全兼顾。 |
|
||||
| 安全稳定 | Redis 限流 | 使用 `INCR + PEXPIRE` 原子脚本实现窗口限流,覆盖登录、注册、点赞、评论、关注写接口。 | 降低暴力登录、刷赞、刷评论、频繁关注对系统的冲击。 |
|
||||
| 系统稳定性 | 多级存储降级设计 | Redis 为可选依赖:连接失败自动降级走 MySQL;Redis 恢复后通过请求自愈回填缓存。 | 提升环境适应性与容灾能力,基础设施异常时核心业务仍可用。 |
|
||||
| 异步架构 | RabbitMQ 事件驱动解耦 | 使用 RabbitMQ topic exchanges:`like.events`、`comment.events`、`social.events`、`video.popularity.events`;后端接口仅负责发布事件,`cmd/worker` 内的 Like/Comment/Social/Popularity Worker 异步消费并更新 MySQL/Redis。 | 削峰填谷、降低接口响应时延;写扩散与热度计算解耦,提升吞吐与可维护性,便于后续扩展更多消费者(统计、风控等)。 |
|
||||
| 异步架构 | RabbitMQ 事件驱动解耦 | 使用 RabbitMQ topic exchanges:`like.events`、`comment.events`、`social.events`、`video.popularity.events`;点赞/评论接口发布事件,`cmd/worker` 内的 Like/Comment Worker 异步消费并更新 MySQL/Redis;关注由服务层同步写库,`social.events` 只承载通知。 | 削峰填谷、降低接口响应时延;写扩散与热度计算解耦,提升吞吐与可维护性,便于后续扩展更多消费者(统计、风控等)。 |
|
||||
| 异步架构 | Outbox 保证发布时间线 | `Publish` 事务内写 `videos` 与 `outbox_msgs`;OutboxPoller 持续投递 MQ,成功后删除消息。 | 避免视频记录已写入但时间线事件丢失的问题,提升最终一致性。 |
|
||||
| 异步架构 | MQ 异常降级直写 | 点赞/评论:尝试同时发布“写 MySQL 的队列”+“写 Redis 热度队列”;任一发布失败则对失败目标降级为直写(MySQL 或 Redis)。`UpdatePopularity` 发布失败则直接更新 Redis。 | MQ 不可用时仍能保证核心数据正确落库/可见,避免“请求成功但数据不落地”的一致性风险。 |
|
||||
| 系统稳定性 | MQ 连接自愈与统一消费循环 | 连接由 `middleware/rabbitmq` 的连接管理器独占:`supervise` 单协程拨号、`NotifyClose` 事件驱动断连、指数退避+抖动重连;每一代连接完整重放拓扑,并以 `Session{Ch, Done}` 代令牌交给消费者。8 个消费者共用 `RunConsumer` 一个循环,断连期间阻塞等待、恢复后重建 channel 并重设 QoS。 | broker 重启、网络抖动、队列被误删都能自愈,无需重启进程;旧实现会在连接关闭后陷入"每 5 秒一行日志"的永久死转。 |
|
||||
|
||||
@@ -2743,7 +2743,7 @@ COMMIT;
|
||||
|
||||
1. 更新 `docs/ISSUES-REPORT.md` 的 P0-3 / P0-4 条目与第九节修复路线;
|
||||
2. 两份原方案文首加"已被取代"提示(**不删除**:它们保留了完整的问题推导过程,是本文档 §2.3/§7 的来源);
|
||||
3. 在 `AGENTS.md` 的 "Async Write Path" 段落补一句:**"消费端失败不再丢弃:`rabbitmq.ConsumeLoop` 负责重投与停泊;新增消费者必须实现幂等 `process`"**——这是新增消费者时最容易违反的约定,写进 AGENTS.md 才算真正落地;
|
||||
3. 在 `AGENTS.md` 的「红线」段补一句:**"消费端失败不再丢弃:`rabbitmq.ConsumeLoop` 负责重投与停泊;新增消费者必须实现幂等 `process`"**——这是新增消费者时最容易违反的约定,写进 AGENTS.md 才算真正落地;
|
||||
4. 登记 §10.2 的 N12 边界,避免 P0-5 误判。
|
||||
|
||||
---
|
||||
|
||||
@@ -1439,7 +1439,7 @@ docker compose logs -f backend worker | grep -iE 'DLX ready|拓扑|started'
|
||||
| `backend/internal/middleware/rabbitmq/rabbitmq_test.go` | 改写 `TestDeclareTopologies_OrderAndDeadLetterExchange`(断言新参数/新绑定/不再有 `.dlx`);新增计数与判定用例 |
|
||||
| `backend/internal/middleware/rabbitmq/constants_test.go` | 把 `failed.events` 加入线缆名称签名表(新增固定名称必须与常量同批更新,否则下一个改名人会静默绕过契约) |
|
||||
| `backend/internal/middleware/rabbitmq/integration_test.go` | 新增 §9.2 的集成用例(沿用 `-tags integration` + `RABBITMQ_TEST_URL`) |
|
||||
| `AGENTS.md` / `docs/ISSUES-REPORT.md` | 落地后更新(异步链路与 DLX 描述、"修复路线建议"第 3 条)。注意仓库的 agent 说明已收敛到 `AGENTS.md`,`CLAUDE.md` 只是一行指针,不再承载架构描述 |
|
||||
| `docs/ISSUES-REPORT.md` | 落地后更新(异步链路与 DLX 描述、"修复路线建议"第 3 条) |
|
||||
|
||||
### 9.2 验证
|
||||
|
||||
|
||||
@@ -407,7 +407,7 @@ type Mention struct {
|
||||
|
||||
// CommentStore 是评论写路径的最小存储契约。
|
||||
//
|
||||
// 抽成接口的两个理由(AGENTS.md「测试替身」一节):
|
||||
// 抽成接口的两个理由(AGENTS.md「测试」一节):
|
||||
// 1. "发布失败走本地直写"是本次修复的核心分支,必须能在没有 MySQL 的单测里断言;
|
||||
// 2. CommentWorker 只需要其中 3 个方法,接口能把它的依赖面收窄。
|
||||
type CommentStore interface {
|
||||
@@ -1420,7 +1420,6 @@ SELECT dedupe_key, COUNT(*) FROM notifications
|
||||
| `frontend/src/api/comment.ts` | 新增 `newRequestId`;`publish` 增 `requestId` 参数 |
|
||||
| `frontend/src/components/CommentDrawer.vue` | `publishComment` 用 `pendingIntent` 复用键(§6.12) |
|
||||
| `frontend/src/views/VideoDetailView.vue` | 同上(两处代码相同,抽到 composable 更好,但不在本方案范围内) |
|
||||
| `AGENTS.md` | 更新"Async Write Path"一节:写路径的幂等约定(意图键 + 唯一索引 + 占位),以及"新增异步副作用必须自带去重键"的规则 |
|
||||
| `docs/ISSUES-REPORT.md` | 标注 P0-4 已修复;按 §2.6 勘误 `:191` 的两处表述;P2-16 标注"① 已顺带修复" |
|
||||
|
||||
### 9.2 验证
|
||||
@@ -1624,5 +1623,4 @@ if deleted && evt.VideoID != 0 {
|
||||
| `backend/internal/worker/commentworker_test.go` | 新增 | `applyPublish`/`applyDelete` 幂等 |
|
||||
| `backend/internal/worker/notificationworker_test.go` | 新增 | 通知去重键 |
|
||||
| `backend/internal/video/comment_repo_integration_test.go` | 新增 | `-tags integration`:唯一索引、并发、NULL 兼容 |
|
||||
| `AGENTS.md` | 改 | 写路径幂等约定 |
|
||||
| `docs/ISSUES-REPORT.md` | 改 | P0-4 结案 + §2.6 勘误 + P2-16 ① 状态 |
|
||||
|
||||
@@ -333,7 +333,6 @@ R1–R2 决定"DB 能不能当权威",R3–R4 决定"热榜能不能当派生
|
||||
| `backend/internal/video/hot_window_admin.go` | 新增 | 热榜核对与重建 |
|
||||
| `backend/cmd/reconcile/main.go` | 新增 | 运维入口,漂移时 `exit 1` |
|
||||
| `backend/internal/video/video_service.go` | 修改 | 修正 §2.5 的错误注释(N9) |
|
||||
| `AGENTS.md` | 修改 | Worker 段落删掉 Popularity worker |
|
||||
|
||||
### 6.4 仓储层:点赞与取消点赞进一个事务
|
||||
|
||||
@@ -1721,7 +1720,7 @@ go test -tags integration -p 1 -count=1 -timeout 300s ./internal/video/ ./intern
|
||||
cd ../frontend && npm run build
|
||||
```
|
||||
|
||||
`go test -race` 必须带 `-count=1`:缓存会掩盖 datarace 与顺序依赖(`AGENTS.md` 的"Determinism and speed"一节)。
|
||||
`go test -race` 必须带 `-count=1`:缓存会掩盖 datarace 与顺序依赖(`AGENTS.md` 的"测试"一节)。
|
||||
|
||||
### 9.3 风险
|
||||
|
||||
@@ -1823,7 +1822,6 @@ P1-7(报告里的「视频/评论删除链路残缺」)包含三件事:删
|
||||
| `backend/internal/middleware/rabbitmq/likeMQ.go` | `NewLikeMQ` 的注释 | 不再指向 `PopularityMQ.Update` |
|
||||
| `frontend/src/views/HotView.vue` | `loadHot` | 比对响应的 `as_of`/`snapshot_rebuilt`/`ranking_source`,任一与上一页不同就重置分页(§6.10) |
|
||||
| `frontend/src/api/types.ts` | `ListByPopularityResponse` | 加 `ranking_source`/`snapshot_rebuilt`;`next_latest_*` 标注废弃 |
|
||||
| `AGENTS.md` | "Workers" 段落 | 删掉 Popularity worker,改述为"计数由业务事务维护,热榜是派生滑窗" |
|
||||
|
||||
### 11.3 删除
|
||||
|
||||
|
||||
317
docs/solutions/P1-1-async-workers-out-of-api.md
Normal file
317
docs/solutions/P1-1-async-workers-out-of-api.md
Normal file
@@ -0,0 +1,317 @@
|
||||
# P1-1 解决方案:把通知 worker / Outbox / timeline consumer 迁出 API 进程
|
||||
|
||||
> **对应问题**:`docs/ISSUES-REPORT.md` → 二、P1 严重问题 → **P1-1 通知 worker / Outbox / timeline consumer 寄生 API 进程**
|
||||
> **问题定性**:进程职责划分错误(进程边界与伸缩单元不一致)。不是"某个 worker 有 bug",而是"异步链路被绑在 HTTP 进程上",因此任何单点修复都会在扩容时重新暴露。
|
||||
> **关联条目**:A-5(单点与扩展性约束未声明)、D-1(AGENTS.md 的 Worker 分工描述已过时)、P3-12(Worker 无 WaitGroup 靠 `time.Sleep`)、P3-13(API 无信号处理)。本方案一并关闭这四项中与进程边界相关的部分;**P1-3 的 Outbox 语义(退避、批次饥饿、无限 requeue、Timeline 消费端绕开 `ConsumeLoop`)不在本次范围**。
|
||||
> **本文档状态**:方案已实施。
|
||||
|
||||
---
|
||||
|
||||
## 1. 结论摘要
|
||||
|
||||
`backend/internal/http/router.go` 在装配路由的同时,顺手启动了五条**常驻后台链路**:
|
||||
|
||||
| 链路 | 启动位置 | 生命周期 |
|
||||
|------|----------|----------|
|
||||
| 3 × Notification 消费者(`notification.like` / `.comment` / `.social`) | `router.go` 的 `SetRouter` | `context.Background()`,永不停 |
|
||||
| Outbox poller | `router.go` 的 `SetRouter`(经 `worker.StartOutboxPoller`) | 同上,且 `time.Sleep` 不可中断 |
|
||||
| Timeline 消费者(`video.timeline.update.queue`) | `router.go` 的 `SetRouter`(经 `worker.StartConsumer`) | 同上 |
|
||||
|
||||
而 `backend/cmd/main.go` 用的是 `r.Run(...)`:没有 `signal.NotifyContext`,没有 `http.Server.Shutdown`,进程只能被强杀。`backend/cmd/worker/main.go` 则只跑 Social / Like / Comment / FailedEvent 四类消费者。
|
||||
|
||||
由此产生三个结构性后果:
|
||||
|
||||
1. **伸缩单元错位**。`docker-compose.yml` 与 AGENTS.md 都宣称"API/Worker 可独立伸缩",但通知与时间线链路的实际伸缩单元是"API 进程数"。`docker compose up --scale backend=3` 会得到 3 个 Outbox poller(重复投递同一行)、3 个 timeline consumer(同一事件被写 3 次 ZSet)、3 个通知消费者。
|
||||
2. **实时推送在扩容后静默失效**。`SSEHub` 的 `clients map[uint][]chan *Notification` 是进程内状态:用户连在实例 A,而通知消费者跑在实例 B 时,`Push` 在 B 上找不到任何订阅者,事件被 `default` 分支静默丢弃。**不报错、不告警,用户只是收不到通知**。
|
||||
3. **无法优雅退出**。API 无信号处理,进程退出时五条链路的 goroutine 在任意时刻被中断;Outbox 刚发布成功、尚未 `Delete` 的那条消息会在下次启动时重发(ZSet 幂等所以结果正确,但"退出"这件事本身没有被表达过)。
|
||||
|
||||
修复的核心动作只有一句话:**把异步链路从 `SetRouter` 里搬到 `cmd/worker`,把跨进程的实时推送交给 Redis Pub/Sub,并给两个进程都补上可等待的退出路径。**
|
||||
|
||||
---
|
||||
|
||||
## 2. 需求(本次要满足的验收条件)
|
||||
|
||||
| 编号 | 需求 | 验收方式 |
|
||||
|------|------|----------|
|
||||
| R1 | `SetRouter` 不再启动任何消费者或轮询器;API 进程只做 HTTP、SSE 订阅与 DB/MQ 写 | 代码审查 + `go vet`;`router.go` 不再引用 `RunConsumer` / `StartOutboxPoller` / `StartConsumer` |
|
||||
| R2 | Notification 消费者、Outbox poller、Timeline consumer 全部由 `cmd/worker` 启动,并共用同一个 `signal.NotifyContext` 的 ctx | `cmd/worker/main.go` 中可见 8 个消费者(原有 4 + 通知 3 + timeline 1)与 1 个 Outbox poller 的启动 |
|
||||
| R3 | 通知实时推送跨进程:worker 侧 `NotificationHub` 实现把通知发布到 Redis,API 侧订阅后投递到本进程 SSE | 单测用 miniredis 走通"发布 → 订阅 → hub.Push";代码中 worker 二进制不再构造 `SSEHub` |
|
||||
| R4 | API 收到 SIGINT/SIGTERM 后停止接收新请求、等待在途请求结束(含 SSE 长连接主动断开)、随后退出 | `http.Server.Shutdown` + `SSEHandler` 的 shutdown 分支;进程退出码为 0 |
|
||||
| R5 | Worker 收到信号后等待全部消费者退出,不再用 `time.Sleep` 猜测 | `sync.WaitGroup` + 有限等待;超时才打印告警退出 |
|
||||
| R6 | Outbox poller 的轮询间隔可被 ctx 打断,且单条发布使用派生自 ctx 的超时 | 单测直接验证等待函数在 ctx 取消后立即返回 |
|
||||
| R7 | Redis 不可用时降级行为明确:通知仍落库,SSE 实时推送失效并打日志,不影响点赞/评论/关注主链路 | 代码审查:`Push` 失败只 log;订阅器带退避重连 |
|
||||
| R8 | 现有测试不削弱;新增测试覆盖 R3 / R6 / R1 的路由回归 | `go test -race -count=1 ./...` |
|
||||
|
||||
**非目标(明确不做)**:
|
||||
|
||||
- P1-3:Outbox 的 `status` 状态机、退避、批次饥饿、Timeline 消费端改走 `rabbitmq.ConsumeLoop`。迁移只做"搬家 + 可中断",不改投递语义。
|
||||
- P1-2:`PublishJSON` 的 publisher confirm。
|
||||
- 把 SSE 换成本进程之外的长连接层(如独立的 WebSocket/SSE 网关)。Redis Pub/Sub 已足以让"任意 API 实例都能推送",且不引入新组件。
|
||||
- Outbox 的 leader 选举。理由见 §5.4。
|
||||
|
||||
---
|
||||
|
||||
## 3. 方案
|
||||
|
||||
### 3.1 进程职责重划
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
B["浏览器"]
|
||||
subgraph API["API 进程 cmd"]
|
||||
A1["gin 路由<br/>JWT · 限流 · feed 缓存"]
|
||||
A2["StartNotificationSubscriber"]
|
||||
A3["SSEHub<br/>本进程连接表"]
|
||||
end
|
||||
subgraph WORKER["Worker 进程 cmd/worker"]
|
||||
W1["Social / Like / Comment / FailedEvent 消费者"]
|
||||
W2["Notification × 3 消费者"]
|
||||
W3["RedisNotificationPublisher"]
|
||||
W4["Timeline consumer"]
|
||||
W5["Outbox poller"]
|
||||
end
|
||||
BUS(["Redis Pub/Sub<br/>v1:notification:push"])
|
||||
ZSET[("Redis ZSet<br/>feed:global_timeline")]
|
||||
MQ[("RabbitMQ<br/>video.timeline.events")]
|
||||
DB[("MySQL<br/>业务表与 notifications")]
|
||||
|
||||
B -->|"HTTP / SSE"| A1
|
||||
A1 --> A3
|
||||
A3 -.->|"SSE 推送"| B
|
||||
A2 --> A3
|
||||
W1 -->|"业务事务"| DB
|
||||
W2 -->|"OnConflict DoNothing"| DB
|
||||
W2 --> W3
|
||||
W3 -->|"PUBLISH"| BUS
|
||||
BUS -->|"SUBSCRIBE"| A2
|
||||
W4 -->|"ZADD"| ZSET
|
||||
W5 -->|"PublishVideo"| MQ
|
||||
```
|
||||
|
||||
- **API**:所有 HTTP 入口、SSE 连接、Redis 订阅。不再消费任何队列。
|
||||
- **Worker**:所有队列消费者 + Outbox 轮询。不再持有 SSE 连接,但保留 `NotificationHub` 抽象——它的实现换成"发布到 Redis"。
|
||||
|
||||
这样"通知从产生到送达"的路径变成:MQ → Worker 落库 → Redis Pub/Sub → 任一 API 实例的 SSE:
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
autonumber
|
||||
participant U as 浏览器
|
||||
participant API as API 进程
|
||||
participant R as Redis
|
||||
participant W as Worker 进程
|
||||
participant DB as MySQL
|
||||
participant MQ as RabbitMQ
|
||||
|
||||
MQ->>W: like.events / comment.events / social.events
|
||||
W->>DB: INSERT notifications(OnConflict DoNothing 去重)
|
||||
W->>R: PUBLISH v1:notification:push<br/>{user_id, notification}
|
||||
R-->>API: 订阅到的消息
|
||||
API->>API: SSEHub.Push(userID, n)
|
||||
API-->>U: SSE data: {...}
|
||||
U->>API: 刷新或断线重连
|
||||
API->>DB: SELECT notifications(权威副本)
|
||||
```
|
||||
|
||||
**落库是可靠的,推送是尽力而为的**,与修复前的语义(DB 为准、SSE 只是加速)完全一致,只是把"尽力而为"的范围从一个进程扩大到整个集群。
|
||||
|
||||
### 3.2 Redis Pub/Sub 桥(R3)
|
||||
|
||||
新增 `backend/internal/worker/notificationbus.go`,沿用 `NotificationHub` 接口,不改 `NotificationWorker`:
|
||||
|
||||
```go
|
||||
// NotificationHub 的 Redis 实现:worker 进程内没有 SSE 连接,本地广播无意义。
|
||||
type RedisNotificationPublisher struct{ cache *rediscache.Client }
|
||||
|
||||
func (p *RedisNotificationPublisher) Push(userID uint, n *notification.Notification)
|
||||
```
|
||||
|
||||
- 线缆格式 `{"user_id":…,"notification":{…}}`,频道名走 `cache.Key("notification:push")`,与其它键共享 `v1:` 前缀,避免同一 Redis 上多环境串台。
|
||||
- 发布用 500ms 超时的独立 ctx:推送是"锦上添花",不允许它把消费循环拖住。失败只 `log`,通知已在 `notifications` 表里,客户端下次拉列表/重连即可看到。
|
||||
- 频道名、payload 结构只在这个文件里定义一次——它们是跨进程线缆契约,与 `rabbitmq` 包里的 exchange/queue 常量同级。
|
||||
|
||||
API 侧 `StartNotificationSubscriber(ctx, cache, hub)`:
|
||||
|
||||
- 订阅 → `Receive` 确认订阅生效(避免"订阅尚未建立就返回"导致丢第一批消息)→ 逐条反序列化 → `hub.Push`。
|
||||
- 坏 JSON、`user_id == 0`、`notification == nil` 一律跳过并记日志,不退出循环。
|
||||
- 订阅断开(Redis 重启、连接被踢)后按 1s→2s→…→30s 退避重连;`ctx` 取消即返回。订阅失败不影响 HTTP 服务启动。本次连接存活超过 30 秒时把退避重置回 1 秒——否则一次网络抖动就会让后续重连长期停在长退避上。
|
||||
- `cache == nil`(Redis 未配置或启动时 ping 失败)时直接返回:SSE 仍可建立连接、仍可拉历史通知,只是收不到实时推送,日志说明原因。
|
||||
|
||||
`rediscache.Client` 补两个原语,保持"Redis 细节不外泄"的既有风格:
|
||||
|
||||
```go
|
||||
func (c *Client) Publish(ctx context.Context, channel string, payload []byte) error
|
||||
func (c *Client) Subscribe(ctx context.Context, channel string) (*redis.PubSub, error)
|
||||
```
|
||||
|
||||
### 3.3 可中断的 Outbox 轮询(R6)
|
||||
|
||||
`StartOutboxPoller` 增加 `ctx context.Context` 参数,行为只改三处:
|
||||
|
||||
1. `for ctx.Err() == nil` 取代 `for`(无限循环)。
|
||||
2. `time.Sleep(1 * time.Second)` 换成 `waitOrDone(ctx, outboxPollInterval) bool`:用 `time.NewTimer` + `select`,ctx 取消立即返回 false。
|
||||
3. 单条发布的超时从 `context.Background()` 改为派生自 poller 的 ctx:`context.WithTimeout(ctx, outboxPublishTimeout)`。**这样进程退出时不会为了等一条 publish 再挂 5 秒。**
|
||||
|
||||
`waitOrDone` 抽成包内函数是为了让"休眠是否可中断"能被单元测试直接验证——这是本次唯一能在没有 MySQL 的环境里测到的 poller 行为。
|
||||
|
||||
### 3.4 退出路径(R4 / R5)
|
||||
|
||||
**API**:
|
||||
|
||||
```go
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
|
||||
r := apphttp.SetRouter(ctx, sqlDB, cache, rmq)
|
||||
srv := &http.Server{Addr: ":" + port, Handler: r, ReadHeaderTimeout: 10 * time.Second}
|
||||
|
||||
go func() {
|
||||
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
log.Printf("HTTP server error: %v", err)
|
||||
stop() // 让主协程走同一条退出路径
|
||||
}
|
||||
}()
|
||||
|
||||
<-ctx.Done()
|
||||
stop() // 恢复默认信号处理:第二次 Ctrl-C 立刻强杀,不卡在 Shutdown
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
if err := srv.Shutdown(shutdownCtx); err != nil {
|
||||
log.Printf("API graceful shutdown failed: %v", err)
|
||||
_ = srv.Close()
|
||||
}
|
||||
```
|
||||
|
||||
两个细节值得写进注释:
|
||||
|
||||
- `ReadHeaderTimeout` 是必要的:`http.Server` 零值没有读超时,慢速请求头会永久占住一个连接。它同时是 `Shutdown` 之外唯一与安全相关的超时。
|
||||
- **SSE 会拖住 `Shutdown`**。`Shutdown` 只关闭空闲连接,正在写 `text/event-stream` 的 handler 不会被取消(请求 ctx 也不随 Shutdown 取消)。因此 `SSEHub` 增加一个 `done <-chan struct{}`(来自构造它的 ctx),`SSEHandler` 的 `select` 多一条 `case <-h.done: return`;否则每次部署都要等满 10 秒并把正常退出记成错误。
|
||||
|
||||
**Worker**:把 8 个 `go RunConsumer(...)` 纳入 `sync.WaitGroup`,`<-ctx.Done()` 之后 `wg.Wait()`,再给 10 秒上界:
|
||||
|
||||
```go
|
||||
<-ctx.Done()
|
||||
log.Printf("Worker shutting down...")
|
||||
done := make(chan struct{})
|
||||
go func() { wg.Wait(); close(done) }()
|
||||
select {
|
||||
case <-done: log.Printf("Worker stopped")
|
||||
case <-time.After(10 * time.Second): log.Printf("Worker stopped (timeout waiting for consumers)")
|
||||
}
|
||||
```
|
||||
|
||||
`RunConsumer` 在 ctx 取消后会从 `Sessions`/`sleepCtx`/`WaitReady` 的阻塞点返回,因此正常路径是毫秒级;10 秒只是防止某个 handler 卡在 DB/MQ I/O 上时无限等待——这比原来的 `time.Sleep(2s)`(既可能不够、又必然多等)更准确。
|
||||
|
||||
### 3.5 拓扑登记搬家
|
||||
|
||||
| 拓扑 | 修复前声明方 | 修复后声明方 |
|
||||
|------|--------------|--------------|
|
||||
| `notification.like` / `.comment` / `.social` | API(`router.go`) | Worker(`cmd/worker/main.go`) |
|
||||
| `video.timeline.update.queue` | API(`NewTimelineMQ` 在 `router.go` 调用) | Worker(`NewTimelineMQ(rmqMgr)`) |
|
||||
|
||||
API 不再需要 timeline 与 notification 拓扑:它只写 `outbox_msgs` 行,由 Worker 发布。API 只保留自身 publisher 用到的 exchange 声明。
|
||||
|
||||
> 迁移顺序的注意事项:滚动发布期间,旧 API 实例仍声明 notification 队列并消费,新 Worker 也声明同一组队列。两者参数完全一致(同一组导出常量),因此不会 406;重复消费由 `ConsumeLoop` 的 ack 语义兜底,通知写入有 `uk_notifications_dedupe` 唯一键,重复投递退化为 no-op。
|
||||
|
||||
### 3.6 关于 Outbox 多副本(§5.4 的结论摘要)
|
||||
|
||||
迁移后 Outbox poller 只有一个部署单元(worker),不再随 API 实例数放大。**本次不加分布式锁**,原因:
|
||||
|
||||
1. Timeline 事件天然幂等:`ZADD` 的 member 是 VideoID、score 是 `CreateTime` 毫秒,重复投递结果相同;`Delete` 竞争只有一方 RowsAffected=1。
|
||||
2. 真正的多副本安全来自"按行认领",那需要 `status`/`attempts`/`next_attempt_at` 列与租约,属于 P1-3。用一把 Redis 锁把轮询器裹起来只是把问题藏起来:锁过期仍会双投,且 Redis 一挂就把 Outbox 整体停摆(而当前 Outbox 不依赖 Redis)。
|
||||
|
||||
因此本次的承诺是:**Worker 单副本时正确;多副本时功能正确但会重复投递(幂等),并在文档中写明。**
|
||||
|
||||
---
|
||||
|
||||
## 4. 改动清单
|
||||
|
||||
| 文件 | 改动 |
|
||||
|------|------|
|
||||
| `backend/internal/middleware/redis/redis.go` | 新增 `Publish`、`Subscribe`(含订阅确认) |
|
||||
| `backend/internal/worker/notificationbus.go` | **新增**:`RedisNotificationPublisher`、`StartNotificationSubscriber`、线缆格式与频道名 |
|
||||
| `backend/internal/worker/notificationbus_test.go` | **新增**:miniredis 端到端往返、坏消息跳过、ctx 退出 |
|
||||
| `backend/internal/worker/outboxworker.go` | `StartOutboxPoller` 加 ctx;可中断等待;发布超时派生自 ctx |
|
||||
| `backend/internal/worker/outboxworker_test.go` | **新增**:`waitOrDone` 的取消/超时行为 |
|
||||
| `backend/internal/worker/ssehub.go` | `NewSSEHub(ctx, db)`;`SSEHandler` 增加 shutdown 退出分支 |
|
||||
| `backend/internal/http/router.go` | `SetRouter` 加 ctx;删除 Outbox/Timeline/Notification 消费者与通知拓扑;启动 Redis 订阅;SSE hub 接 ctx |
|
||||
| `backend/internal/http/router_test.go` | 适配新签名;新增"通知路由仍注册"回归 |
|
||||
| `backend/cmd/main.go` | `signal.NotifyContext` + `http.Server` + `Shutdown`;`SetRouter(ctx, ...)` |
|
||||
| `backend/cmd/worker/main.go` | 启动 Notification × 3、Timeline、Outbox;登记对应拓扑;`WaitGroup` 等待退出 |
|
||||
| `docs/ISSUES-REPORT.md` | P1-1 置 ✅,改写为"问题 + 解决 + 索引";路线图第三阶段第 8 条打勾;同步 A-5 / D-1 / P3-12 / P3-13 的状态 |
|
||||
| `README.md` | 部署约束:Worker 是通知/时间线的必需进程;多实例时 SSE 依赖 Redis Pub/Sub |
|
||||
| `docs/design/消息处理失败与死信队列.md`、`docs/feedsystem_video_go项目设计.md` | 同步"通知消费者在 Worker"、SSE 推送链路与 `mq_topology` 期望值(API 3 / Worker 7) |
|
||||
|
||||
---
|
||||
|
||||
## 5. 关键取舍
|
||||
|
||||
### 5.1 为什么不把 SSE 也搬进 Worker
|
||||
|
||||
用户的长连接必须落在能处理 HTTP 的地方,而 Worker 不监听业务端口。把 SSE 做成独立服务会引入第三个二进制与一套路由/鉴权复制;Redis Pub/Sub 的代价只是"推送多一跳 Redis",对通知这种低频、非强一致的消息足够。
|
||||
|
||||
### 5.2 为什么订阅放在 API,而不是让前端轮询
|
||||
|
||||
轮询会把"实时"变成"准实时",并放大 `GET /notification/list` 的 QPS;而 SSE 连接数本来就只与在线用户数相关。保持 SSE、只把投递改为跨进程,是改动面最小的正确解。
|
||||
|
||||
### 5.3 为什么 worker 侧仍保留 `NotificationHub` 抽象
|
||||
|
||||
`NotificationWorker` 只依赖 `Push(userID, *Notification)` 这一个方法。保留接口意味着:本地单测可以塞 fake hub(现有 4 个测试已在用),生产可以换 Redis 实现,未来若引入推送网关也只换实现。接口是这层唯一需要稳定的东西。
|
||||
|
||||
### 5.4 为什么 Outbox 不加锁(重复投递为何可接受)
|
||||
|
||||
见 §3.6。补充一条:Redis 锁会让 Outbox 从"只依赖 MySQL + MQ"变成"依赖 MySQL + MQ + Redis",在 Redis 故障时时间线写入会整体停摆——这是用可用性换一个本就可被幂等吸收的问题。
|
||||
|
||||
### 5.5 API 的 `SetRouter` 为什么接收 ctx 而不是在内部 `context.Background()`
|
||||
|
||||
订阅器的生命周期必须与进程一致,而 `SetRouter` 是唯一知道"路由何时装配完成"的地方。把 ctx 显式传进来,测试可以传 `context.Background()`,生产传 `signal.NotifyContext` 的 ctx,没有隐藏的全局状态。
|
||||
|
||||
---
|
||||
|
||||
## 6. 验证
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
go vet ./...
|
||||
go test -race -count=1 ./...
|
||||
```
|
||||
|
||||
> 本地 Windows 环境没有可用的 C 工具链(`CGO_ENABLED=0`、无 gcc),`-race` 跑不了,实际验证用的是 `go test -count=1 ./...`;`-race` 由 CI 的 `golang:1.24.5` 容器执行。
|
||||
|
||||
新增/更新的测试:
|
||||
|
||||
| 测试 | 断言 |
|
||||
|------|------|
|
||||
| `TestNotificationBus_PublishReachesSubscriber` | `RedisNotificationPublisher.Push` → miniredis → 订阅器 → fake hub 收到同一 `user_id` 与通知 ID(通道同步,不用 sleep) |
|
||||
| `TestNotificationSubscriber_SkipsMalformedPayload` | 先发坏 JSON 再发好 JSON,只有好的一条到达——证明坏消息被跳过且循环未退出 |
|
||||
| `TestNotificationSubscriber_StopsOnContextCancel` | 订阅建立后取消 ctx,`runNotificationSubscriber` 在超时内返回 `nil`(`ctx.Err()` 视为正常退出) |
|
||||
| `TestWaitOrDone` | ctx 已取消 → 立即返回 `false`(未等满间隔);ctx 正常 → 等满间隔后返回 `true` |
|
||||
| `TestRedisNotificationPublisher_NilClientIsNoop` | Redis 缺失时 `Push` 不 panic 也不阻塞——通知消费不能因为推送不可用而失败 |
|
||||
| `TestRouter_NotificationRoutesRegistered` | `SetRouter` 之后 `/notification/stream`、`/list`、`/markRead`、`/unreadCount` 仍存在(防止"搬家"顺手把 SSE 路由删掉) |
|
||||
| 既有 `TestReadyz_*` | 行为不变:`/healthz` 恒 200、`/readyz` 在 MQ 断开时 503 |
|
||||
|
||||
手工验收(需要 Docker):
|
||||
|
||||
1. `docker compose up -d`,两个进程都起来后发一条点赞 → 浏览器 SSE 收到 `data: {...}`。
|
||||
2. `docker compose up -d --scale backend=2`:两个 API 实例各建一条 SSE,点赞后**两条**都能收到(修复前只有与 worker 同进程的那条能收到)。
|
||||
3. `docker compose stop worker` → 点赞与评论仍成功(写路径降级为直写 DB),通知在 Worker 恢复后被消费。
|
||||
4. 对 API 发 SIGTERM:日志出现 `API shutting down` → `API stopped`,退出码 0,SSE 连接被服务端关闭而不是等满 10 秒。
|
||||
5. 对 Worker 发 SIGTERM:日志出现 `Worker shutting down` → `Worker stopped`,不再有固定 2 秒的空等。
|
||||
|
||||
---
|
||||
|
||||
## 7. 回滚
|
||||
|
||||
改动集中在进程装配层,回滚不需要数据迁移:
|
||||
|
||||
- 把 `cmd/worker/main.go` 中新增的 5 条启动语句删掉、`router.go` 中恢复 `StartOutboxPoller` / `StartConsumer` / notification 消费者即可回到旧行为(旧代码可从 git 历史取回)。
|
||||
- 旧版本 API 不会订阅 Redis,因此**回滚期间**若 Worker 已是新版本,通知只落库、不实时推送——可接受;旧版本 Worker 与新 API 的组合则会丢失实时推送(API 订阅到一个没人发布的频道)。两种混跑都不会损坏数据。
|
||||
- 无 schema 变更,无新增依赖,无配置项新增。
|
||||
|
||||
---
|
||||
|
||||
## 8. 仍存在的边界
|
||||
|
||||
- **Redis Pub/Sub 是至多一次**:订阅者掉线期间的通知不会补发。这是刻意接受的设计——通知的权威副本在 `notifications` 表,SSE 只负责"在线时尽快看到"。
|
||||
- **Worker 仍是单点**:Worker 挂掉时通知落库与 timeline 写入都会停(消息在队列里堆积),恢复后追赶。与修复前相比,API 不再因为 Worker 的角色而承担这部分风险,这是净收益。
|
||||
- **P1-3 未修**:Outbox 仍无退避与 attempts,Timeline 消费端仍绕开 `ConsumeLoop`(坏 JSON 直接 Ack、Redis 故障 `Nack(false,true)` 热循环)。迁移只是把这些问题搬到了正确的进程里,语义未变。
|
||||
737
docs/solutions/P1-2-publisher-confirm.md
Normal file
737
docs/solutions/P1-2-publisher-confirm.md
Normal file
@@ -0,0 +1,737 @@
|
||||
# P1-2 解决方案:发布确认(publisher confirm)与不可路由退回
|
||||
|
||||
> **对应问题**:`docs/ISSUES-REPORT.md` → 二、P1 严重问题 → **P1-2 MQ 发布无确认机制,消息可静默丢失**
|
||||
> **问题定性**:发布层缺少"送达证明"。`PublishJSON` 的返回值当前只表示"本地写帧成功",而所有调用方都把它读成"broker 已收下"——**语义契约与实现不一致**。因此这不是"某个 publisher 写错了",而是发布原语的缺陷:修在 `PublishJSON` 内部,四个 publisher 与全部调用方同时受益。
|
||||
> **关联条目**:P1-13 已把发布统一到连接管理器(本方案不推翻"每代复用一个发布 channel");P0-3 的 `Park` 已自带 confirm + `mandatory` + `NotifyReturn`(本方案对齐它的语义,但不改动它);P0-4 的意图键是本方案"超时后仍降级直写"的前提;P1-3(Outbox 退避/批次饥饿)与 P1-4(社交 DB-first)不在本次范围。
|
||||
> **本文档状态**:设计稿,尚未实现。实现完成并验证后回填 §9 的验证记录。
|
||||
|
||||
---
|
||||
|
||||
## 1. 结论摘要
|
||||
|
||||
`backend/internal/middleware/rabbitmq/rabbitMQ.go` 的 `PublishJSON` 以 `mandatory=false`、未开 confirm、未注册 `NotifyReturn` 的方式发布:
|
||||
|
||||
```go
|
||||
if err := ch.PublishWithContext(ctx, exchange, routingKey, false, false, pub); err != nil {
|
||||
r.invalidatePublisherChannel(ch)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
```
|
||||
|
||||
这段代码有两个分离的问题,缺一不可:
|
||||
|
||||
1. **投出去就不管了**:`PublishWithContext` 返回 nil 只说明"帧写进了 TCP 连接"。broker 之后才决定收不收(nack)、路由得到路由不到。
|
||||
2. **不路由也收不到通知**:`mandatory=false` 时 broker 对路由不到的消息**静默丢弃并照常 ack**;即使改成 `mandatory=true`,没有 `NotifyReturn` 监听者时 amqp091-go 会把 `basic.return` 直接丢掉。
|
||||
|
||||
于是 `binding key` 拼错、队列未声明、拓扑被删这类错误变成**静默黑洞**:`PublishJSON` 返回 nil → `like_service.go` 认为已入队、跳过 `ApplyLike` → 用户点赞成功但数据库里没有。P0-3/P0-4 建立的全部降级保护(失败即直写)建立在"失败能被告知"这个前提上,而这个前提当前不成立。
|
||||
|
||||
修复后的语义只有一句:**`PublishJSON` 返回 nil,当且仅当 broker 已确认收下这条消息,并且没有把它退回。**
|
||||
|
||||
```go
|
||||
// 修复后(示意,完整版见 §5.3)
|
||||
dc, err := ch.PublishConfirmed(pubCtx, exchange, routingKey, true /*mandatory*/, pub)
|
||||
acked, err := dc.WaitContext(pubCtx) // 等 broker 的 basic.ack
|
||||
if !acked { return ErrPublishUnconfirmed } // nack,或 channel 中途关闭
|
||||
select {
|
||||
case ret := <-returns: // ack 后复查 basic.return
|
||||
return fmt.Errorf("%w: code=%d %s", ErrPublishUnroutable, ret.ReplyCode, ret.ReplyText)
|
||||
default:
|
||||
}
|
||||
return nil
|
||||
```
|
||||
|
||||
三个配套决定:
|
||||
|
||||
| 决定 | 理由 | 详见 |
|
||||
|------|------|------|
|
||||
| 用 `PublishWithDeferredConfirmWithContext` 逐条等确认,不用共享 `NotifyPublish` | 后者是多 goroutine 共享的一条流,ack 无法归属到某一次发布(同 §5.5 的论证) | §5.5 |
|
||||
| 发布与等确认**串行**(`pubMu`) | `basic.return` 不带 delivery tag;只有在途消息唯一时,退回才能无歧义归属 | §5.5 |
|
||||
| `publishTimeout` 覆盖"等锁 + 等重连 + 发布 + 等确认" | 否则 broker 断连时 `WaitReady` 会随请求 ctx 无限等待,写接口挂死 | §5.6 |
|
||||
|
||||
---
|
||||
|
||||
## 2. 问题定位
|
||||
|
||||
### 2.1 缺陷现场
|
||||
|
||||
`PublishJSON`(`backend/internal/middleware/rabbitmq/rabbitMQ.go`)当前实现:
|
||||
|
||||
```go
|
||||
// PublishJSON 经连接管理器发布一条 JSON 消息。
|
||||
//
|
||||
// 失败时丢弃缓存的发布 channel(下一代会重建)并如实返回错误,由服务层
|
||||
// 按既有 "MQ 失败则直写 DB" 路径降级。
|
||||
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")
|
||||
}
|
||||
|
||||
pub, err := buildPublishing(payload)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
```
|
||||
|
||||
三处缺失,各自独立地破坏"送达":
|
||||
|
||||
| 缺失 | 后果 |
|
||||
|------|------|
|
||||
| `Confirm(false)` 从未调用 → channel 不在 confirm 模式 | broker 收下/拒收都不会告诉客户端;`PublishWithContext` 返回 nil 与"消息已持久化"无关 |
|
||||
| `mandatory=false` | 路由不到任何队列时,broker 丢弃消息并**仍然 ack**——这是协议默认行为,不是配置错误 |
|
||||
| 未注册 `NotifyReturn` | 即使后续有人把 `mandatory` 改成 true,amqp091-go 在无监听者时丢弃 `basic.return`(`channel.go` 的 `dispatch` 分支) |
|
||||
|
||||
上游文档把这个缺陷写得很直白(`amqp091-go@v1.10.0/channel.go` 的 `Publish` 注释):
|
||||
|
||||
> The way to ensure that all publishings reach the server is to add a listener to `Channel.NotifyPublish` and put the channel in confirm mode with `Channel.Confirm`.
|
||||
>
|
||||
> This can return an error when the channel, connection or socket is closed. **The error or lack of an error does not indicate whether the server has received this publishing.**
|
||||
|
||||
也就是说,当前 `PublishJSON` 的返回值连"写帧成功"都只能保证到 socket 层——`return nil` 与"消息已到达 broker"之间没有因果关系。
|
||||
|
||||
### 2.2 谁依赖这个返回值
|
||||
|
||||
| 调用方 | 代码位置 | 拿到 error 时做什么 | 拿到 nil 时做什么 |
|
||||
|--------|----------|--------------------|------------------|
|
||||
| 点赞 / 取消点赞 | `like_service.go` 的 `Like` / `Unlike` | 打日志后 `ApplyLike` / `ApplyUnlike` 直写 + 热度增量 | 直接返回成功,**不写库**,等 worker 消费 |
|
||||
| 评论 / 删评论 | `comment_service.go` 的 `Publish` / `Delete` | `CreateIdempotentWithPopularity` / `DeleteWithPopularity` 直写 + 热度 | 直接返回成功,**不写库** |
|
||||
| 关注 / 取关 | `social/service.go` 的 `Follow` / `UnFollow` | DB 已先写(DB-first),发布失败只记日志 | 通知事件入队 |
|
||||
| 视频发布 | `worker/outboxworker.go` 的 `StartOutboxPoller` | 保留 pending 行,下一轮重投 | `db.Delete(&msg)` 删除 outbox 行 |
|
||||
|
||||
四处的共同假设是:**nil ⇒ broker 已收下**。这个假设在 MQ 健康的 99.9% 时间里碰巧成立,所以缺陷长期不可见;一旦 binding 拼错或队列被删,四个调用方会整齐地一起做出错误决定,且没有任何一行日志。
|
||||
|
||||
### 2.3 对照:`Park` 为什么没有这个问题
|
||||
|
||||
同一个文件里的 `Park`(P0-3)已经把三件事做全了:
|
||||
|
||||
```go
|
||||
ch.Confirm(false)
|
||||
confirms := ch.NotifyPublish(make(chan amqp.Confirmation, 1))
|
||||
returns := ch.NotifyReturn(make(chan amqp.Return, 1))
|
||||
...
|
||||
ch.PublishWithContext(parkCtx, DLXExchange, ParkedKeyPrefix+sourceQueue, true /*mandatory*/, false, pub)
|
||||
select {
|
||||
case c, ok := <-confirms: // 等确认
|
||||
if !ok || !c.Ack { return errors.New("park: broker rejected the message (nack)") }
|
||||
select { // 确认后复查 return
|
||||
case ret := <-returns: return fmt.Errorf("park: unroutable code=%d %s", ret.ReplyCode, ret.ReplyText)
|
||||
default:
|
||||
}
|
||||
return nil
|
||||
...
|
||||
```
|
||||
|
||||
`Park` 能这么做,是因为它**每条消息一个独立 channel、同一时刻只有一条在途**——确认与退回天然归属于这条消息。业务发布路径要复用的是"必须等到确认并复查退回",不能照搬"每次新建 channel",因为 P1-13 已经确定"管理器为每一代连接复用一个发布 channel,失败即丢弃、随下一代重建"。§5.5 说明这两个约束如何在共享 channel 下共存。
|
||||
|
||||
### 2.4 缺陷拆分
|
||||
|
||||
| 编号 | 缺陷 | 位置 | 修复动作 |
|
||||
|------|------|------|----------|
|
||||
| D1 | 发布 channel 未开 confirm,拿不到 ack/nack | `publisherChannel` | 新建时 `Confirm(false)`,且早于第一次发布 |
|
||||
| D2 | `mandatory=false`,不可路由被静默丢弃 | `PublishJSON` | 改 `true` |
|
||||
| D3 | 无 `NotifyReturn`,退回事件无人接收 | `publisherChannel` | 建 channel 时注册,buffer 1,发布后非阻塞复查 |
|
||||
| D4 | 无超时,断连时随请求 ctx 无限等待 | `PublishJSON` | 内部 `context.WithTimeout(…, publishTimeout)`,覆盖整段调用 |
|
||||
| D5 | 错误不可分类,调用方无法区分"不可路由/未确认/超时" | `PublishJSON` | 三个 sentinel error + `errors.Is`;错误文本带 exchange/routing key |
|
||||
| D6 | 失败无计数,`/readyz` 看不出"发布一直在失败" | `Stats` / `/readyz` | 可选增强 O1(§5.8),不计入本次必做范围 |
|
||||
|
||||
---
|
||||
|
||||
## 3. 需求
|
||||
|
||||
| 编号 | 需求 | 验收方式 |
|
||||
|------|------|----------|
|
||||
| R1 | `PublishJSON` 返回 nil ⇔ broker 已 ack 且消息未被退回 | 单测:ack 无退回 → nil;nack → error;ack 后退回 → error |
|
||||
| R2 | 路由不到任何队列必须报错(当前静默丢) | 集成测试:绑定 `p1_2.test.*`,用 `p1_2.none` 发布 → `errors.Is(err, ErrPublishUnroutable)` |
|
||||
| R3 | 任何一次发布都在有限时间内返回,绝不无限阻塞 | 单测:无 confirm 时 `publishTimeout` 内返回 `ErrPublishTimeout`;`-race` 下无 goroutine 泄漏 |
|
||||
| R4 | 错误可分类且可诊断 | `errors.Is` 三个 sentinel;错误文本含 `exchange/routingKey` 与 `ReplyCode` |
|
||||
| R5 | 四个 publisher 与全部调用方**零改动** | 编译 + 既有服务层测试不改断言即通过 |
|
||||
| R6 | 不推翻 P1-13:每代连接复用一个发布 channel;不自动重发 | 代码审查:`publisherChannel` 仍按 `pubCh` 复用;无 `for` 重发循环 |
|
||||
| R7 | 无 broker 可单测(确认/退回/超时三条分支) | 手写 `fakePublisher`,不引入 mocking 框架、不碰网络 |
|
||||
| R8 | 既有测试不削弱 | `go test -race -count=1 ./...` 全绿;集成用例仍绿 |
|
||||
|
||||
**非目标(明确不做)**:
|
||||
|
||||
- **不做重发**。超时只报错,由服务层降级直写。理由沿用 P1-2 上游注释:重发会在 P0-4 的双写窗口上再叠一层不确定性,幂等应由事件层的 `event_id` 解决。
|
||||
- **不做 Outbox 化**。点赞/评论的两阶段写(先 MQ 后 DB)不改;`PublishJSON` 只负责"说真话"。
|
||||
- **不改消费侧**。confirm 只影响发布;重试队列、`x-death`、`Park` 的语义不动。
|
||||
- **不做批量确认 / pipelining**。串行 + 单条确认的吞吐已远高于本项目的写速率(§4.2 给了量级)。
|
||||
- **不引入新依赖**。`amqp091-go` v1.10.0 已有 `DeferredConfirmation`。
|
||||
- **不解决"已送达但客户端超时"造成的重复投递**。这是 AMQP 至少一次语义的固有区间,由 P0-4 的意图键与唯一索引吸收(§10.3)。
|
||||
|
||||
### 3.1 待确认的取舍
|
||||
|
||||
以下三项不影响正确性,只影响改动边界;本方案先按下表的默认值设计,实现前可再定。
|
||||
|
||||
| # | 取舍 | 本方案默认 | 备选与代价 |
|
||||
|---|------|-----------|-----------|
|
||||
| 1 | `publishTimeout` 固定值还是可配置 | 固定 `3s`(`var`,便于单测压缩) | 增 `rabbitmq.publish_timeout` YAML 键 + env override:要改 `config` 结构、三份 config 样例与配置测试;运维可在不重启二进制的情况下调参,但本项目尚无此先例 |
|
||||
| 2 | 是否本次一并做 O1 指标 | 不做,列入后续 | 一并做:约 10 行(`Stats` +1 字段、`/readyz` +1 键),代价是 `Stats` 的零值比较类测试要复核 |
|
||||
| 3 | 是否把 `Park` 也切到 deferred confirm | 不动 | 统一 `awaitConfirm`,去掉一份重复逻辑;代价是改动已上线的 P0-3 路径,需重跑停泊相关集成用例 |
|
||||
|
||||
---
|
||||
|
||||
## 4. 方案选型
|
||||
|
||||
### 4.1 候选方案
|
||||
|
||||
| 方案 | 做法 | 优点 | 缺点 | 结论 |
|
||||
|------|------|------|------|------|
|
||||
| **A. 只开 `mandatory` + `NotifyReturn`** | 不开 confirm,仅把退回当失败 | 改动最小,零延迟 | ack/nack 仍不可见:broker 拒收(如持久化失败、磁盘满、channel 级 406)依旧静默;退回与 ack 的先后关系也无从判定 | ❌ 只修了 D2/D3,D1 仍在 |
|
||||
| **B. confirm + deferred 确认 + `mandatory` + `NotifyReturn` + 超时(共享 channel,发布串行)** | 本方案 | 覆盖 D1–D5;复用每代 channel(不推翻 P1-13);错误可分类;可单测 | 每条发布多一个 RTT;发布被串行化(但在途本就受 `ch.m.Lock` 串行) | ✅ **采用** |
|
||||
| **C. 每条消息独立 channel(照搬 `Park`)** | `Session` → `Confirm` → publish → wait → `Close` | 无归属问题,无需锁 | 与 P1-13 的"每代复用一个发布 channel"直接冲突;每次发布付一次 `channel.open` 往返;断连时更容易在 `Close` 上再挂一次 | ❌ 推翻既有设计,收益不抵成本 |
|
||||
| **D. 换 `go-rabbitmq` 等库** | 用第三方封装 | 内建重连 + confirm | 8 个消费者与 5 个发布点全部改抽象;其队列声明无法表达现有 `<queue>.dlx` + `x-death` 布局 | ❌ P0-2 已评估并否决 |
|
||||
| **E. 只加超时与日志** | 不改送达语义 | 改动最小 | 静默丢失照旧,只是多一条"我发出去了"的日志 | ❌ 不解决问题 |
|
||||
|
||||
### 4.2 为什么 B 里的"串行"不是性能退化
|
||||
|
||||
`amqp091-go` 的 `Channel.Publish` 内部就持有 `ch.m.Lock()`(P0-2 文档已核对过 `channel.go`),所以同一个 channel 上的发布**本来就是串行的**;真正被新增的串行段只有"等确认"这一段。而"等确认"是多路复用 confirm 的必要代价:不开 confirm 就没有送达证明。
|
||||
|
||||
量级估算:本机 broker 的 confirm RTT 约 0.3–2 ms,单实例发布上限约 500–3000 条/秒。项目的写限流是点赞 30 次/分/账号、评论 10 次/分/账号、关注 20 次/分/账号(`router.go` 的 `like_write` / `comment_write` / `social_write`),单实例远达不到瓶颈。若未来真需要并行,正确做法是**按 routing key 哈希分片到 N 个发布 channel**,每个分片各自串行——那是另一个方案,不在本次范围。
|
||||
|
||||
---
|
||||
|
||||
## 5. 详细设计
|
||||
|
||||
### 5.1 数据结构
|
||||
|
||||
```go
|
||||
const defaultHeartbeat = 10 * time.Second
|
||||
|
||||
// publishTimeout 是"等锁 + 等重连 + 发布 + 等确认"的总预算。
|
||||
// 用 var 而不是 const:单测要把超时分支压到毫秒级,否则每条用例都要真等 3 秒。
|
||||
var publishTimeout = 3 * time.Second
|
||||
|
||||
var (
|
||||
// 不可路由:broker 用 basic.return 退回了消息(没有匹配的 binding)。
|
||||
ErrPublishUnroutable = errors.New("rabbitmq: message was returned as unroutable")
|
||||
// 未确认:broker nack,或 channel 在确认到达前关闭。
|
||||
ErrPublishUnconfirmed = errors.New("rabbitmq: publisher confirm was not received")
|
||||
// 超时:预算内没等到确认;消息是否已送达未知。
|
||||
ErrPublishTimeout = errors.New("rabbitmq: publisher confirm timed out")
|
||||
)
|
||||
```
|
||||
|
||||
```go
|
||||
type RabbitMQ struct {
|
||||
url string
|
||||
opts ReconnectOptions
|
||||
mu sync.Mutex
|
||||
conn connection
|
||||
gen chan struct{}
|
||||
ready chan struct{}
|
||||
closed bool
|
||||
|
||||
// 发布路径:pubMu 串行化"发布 + 等确认",见 §5.5。
|
||||
// pubRet 与 pubCh 同生共死,随连接代一起重建。
|
||||
pubMu sync.Mutex
|
||||
pubCh publishChannel
|
||||
pubRet chan amqp.Return
|
||||
|
||||
topology []Topology
|
||||
closeOne sync.Once
|
||||
generation uint64
|
||||
reconnects uint64
|
||||
lastUpAt time.Time
|
||||
lastDownAt time.Time
|
||||
}
|
||||
```
|
||||
|
||||
`publishChannel` 是发布路径用到的最小 channel 子集:
|
||||
|
||||
```go
|
||||
// publishChannel 是发布路径用到的最小 channel 子集。
|
||||
//
|
||||
// 抽接口的唯一目的是可测性:确认、退回、超时三条分支一旦写错,症状就是
|
||||
// 静默丢消息,而它们又必须连上 broker 才能触发。抽出来以后状态机可以在
|
||||
// 单测里确定性地跑(与 connection 接口同一个理由)。
|
||||
type publishChannel interface {
|
||||
Confirm(noWait bool) error
|
||||
NotifyReturn(c chan amqp.Return) chan amqp.Return
|
||||
PublishConfirmed(ctx context.Context, exchange, routingKey string, mandatory bool, msg amqp.Publishing) (confirmation, error)
|
||||
Close() error
|
||||
}
|
||||
|
||||
// confirmation 是单条消息的确认凭据(amqp.DeferredConfirmation 满足它)。
|
||||
type confirmation interface {
|
||||
WaitContext(ctx context.Context) (bool, error)
|
||||
}
|
||||
|
||||
type amqpPublisher struct{ ch *amqp.Channel }
|
||||
|
||||
func (p *amqpPublisher) Confirm(noWait bool) error { return p.ch.Confirm(noWait) }
|
||||
|
||||
func (p *amqpPublisher) NotifyReturn(c chan amqp.Return) chan amqp.Return { return p.ch.NotifyReturn(c) }
|
||||
|
||||
func (p *amqpPublisher) Close() error { return p.ch.Close() }
|
||||
|
||||
func (p *amqpPublisher) PublishConfirmed(ctx context.Context, exchange, routingKey string, mandatory bool, msg amqp.Publishing) (confirmation, error) {
|
||||
dc, err := p.ch.PublishWithDeferredConfirmWithContext(ctx, exchange, routingKey, mandatory, false, msg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// 未开 confirm 时该函数返回 (nil, nil):把它当成功正是本方案要消灭的静默丢失。
|
||||
if dc == nil {
|
||||
return nil, errors.New("rabbitmq: publisher confirm is not enabled on this channel")
|
||||
}
|
||||
return dc, nil
|
||||
}
|
||||
```
|
||||
|
||||
> `PublishWithDeferredConfirmWithContext` 的第一个参数 ctx **不被使用**(库只把它当占位),真正生效的是 `dc.WaitContext(ctx)`。因此超时必须由 `WaitContext` 提供,不能指望 publish 调用本身。
|
||||
|
||||
### 5.2 建立发布 channel:confirm 必须早于第一次发布
|
||||
|
||||
```go
|
||||
// publisherChannel 返回本代可复用的发布 channel,并保证它已开启 confirm、
|
||||
// 已注册退回监听。
|
||||
//
|
||||
// 两个动作都必须在【第一次发布之前】完成:先发后挂监听,中间那条消息的
|
||||
// basic.return 会被库直接丢弃——正是 D3 的成因。
|
||||
func (r *RabbitMQ) publisherChannel(ctx context.Context) (publishChannel, chan amqp.Return, error) {
|
||||
r.mu.Lock()
|
||||
ch, ret, conn := r.pubCh, r.pubRet, r.conn
|
||||
r.mu.Unlock()
|
||||
|
||||
if ch != nil && conn != nil && !conn.IsClosed() {
|
||||
return ch, ret, nil
|
||||
}
|
||||
|
||||
sess, err := r.Session(ctx)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if sess.Ch == nil {
|
||||
return nil, nil, errors.New("rabbitmq: session has no channel")
|
||||
}
|
||||
|
||||
pub := &amqpPublisher{ch: sess.Ch}
|
||||
if err := pub.Confirm(false); err != nil {
|
||||
_ = sess.Ch.Close()
|
||||
return nil, nil, fmt.Errorf("enable publisher confirm: %w", err)
|
||||
}
|
||||
ret = pub.NotifyReturn(make(chan amqp.Return, 1))
|
||||
|
||||
r.mu.Lock()
|
||||
if r.pubCh != nil {
|
||||
// 并发下已有人装上发布 channel:复用它,关掉我们刚取的这个。
|
||||
// 此时 pubRet 也一定是那一份——两者在同一个临界区里成对写入。
|
||||
existing, existingRet := r.pubCh, r.pubRet
|
||||
r.mu.Unlock()
|
||||
_ = sess.Ch.Close()
|
||||
return existing, existingRet, nil
|
||||
}
|
||||
r.pubCh, r.pubRet = pub, ret
|
||||
r.mu.Unlock()
|
||||
return pub, ret, nil
|
||||
}
|
||||
```
|
||||
|
||||
`markDown` 与 `install` 同步清理配对状态:
|
||||
|
||||
```go
|
||||
func (r *RabbitMQ) install(conn connection) {
|
||||
...
|
||||
r.pubCh = nil
|
||||
r.pubRet = nil
|
||||
...
|
||||
}
|
||||
|
||||
func (r *RabbitMQ) markDown() {
|
||||
r.mu.Lock()
|
||||
...
|
||||
pub := r.pubCh
|
||||
r.pubCh = nil
|
||||
r.pubRet = nil
|
||||
...
|
||||
r.mu.Unlock()
|
||||
if pub != nil {
|
||||
_ = pub.Close()
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> 这里不改"谁来关 channel"的所有权:`markDown` 关掉本代 channel,`invalidatePublisherChannel` 关掉"当前这个"。两者都先置 nil 再关,避免重复关闭。
|
||||
|
||||
### 5.3 `PublishJSON` 主流程
|
||||
|
||||
```go
|
||||
// PublishJSON 经连接管理器发布一条 JSON 消息。
|
||||
//
|
||||
// 返回 nil 的含义是"broker 已确认收下,且没有退回"。返回错误时由服务层
|
||||
// 按既有 "MQ 失败则直写 DB" 路径降级。
|
||||
//
|
||||
// 刻意【不】自动重发:那会在 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")
|
||||
}
|
||||
|
||||
pub, err := buildPublishing(payload)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 预算从函数入口开始算:等锁、等重连、等确认共用这一份。
|
||||
// 否则 broker 断连时 WaitReady 会跟着请求 ctx 一起无限等待。
|
||||
pubCtx, cancel := context.WithTimeout(ctx, publishTimeout)
|
||||
defer cancel()
|
||||
|
||||
// 串行是 mandatory 可用的前提,见 §5.5。
|
||||
r.pubMu.Lock()
|
||||
defer r.pubMu.Unlock()
|
||||
|
||||
ch, returns, err := r.publisherChannel(pubCtx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("publish %s/%s: %w", exchange, routingKey, err)
|
||||
}
|
||||
|
||||
drainReturns(returns) // 清掉上一轮可能的残留,避免错误归属
|
||||
dc, err := ch.PublishConfirmed(pubCtx, exchange, routingKey, true /*mandatory*/, pub)
|
||||
if err != nil {
|
||||
r.invalidatePublisherChannel(ch)
|
||||
return fmt.Errorf("publish %s/%s: %w", exchange, routingKey, err)
|
||||
}
|
||||
|
||||
acked, err := dc.WaitContext(pubCtx)
|
||||
if err != nil {
|
||||
r.invalidatePublisherChannel(ch)
|
||||
return fmt.Errorf("publish %s/%s: %w: %w", exchange, routingKey, ErrPublishTimeout, err)
|
||||
}
|
||||
if !acked {
|
||||
r.invalidatePublisherChannel(ch)
|
||||
return fmt.Errorf("publish %s/%s: %w", exchange, routingKey, ErrPublishUnconfirmed)
|
||||
}
|
||||
|
||||
// 无法路由时 broker 先发 basic.return、后发 basic.ack;amqp091-go 也在
|
||||
// 同一个分发协程里先投返回再解析确认(channel.go 的 dispatch),所以
|
||||
// ack 到达时 return 必已在缓冲里,这里非阻塞读一次即可。
|
||||
select {
|
||||
case ret, ok := <-returns:
|
||||
if !ok {
|
||||
// 监听通道随 channel 关闭:确认已到但无法确认是否被退回,按最坏情况处理。
|
||||
r.invalidatePublisherChannel(ch)
|
||||
return fmt.Errorf("publish %s/%s: %w", exchange, routingKey, ErrPublishUnconfirmed)
|
||||
}
|
||||
return fmt.Errorf("publish %s/%s: %w (code=%d text=%q)",
|
||||
exchange, routingKey, ErrPublishUnroutable, ret.ReplyCode, ret.ReplyText)
|
||||
default:
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// drainReturns 清空退回缓冲。不变量是"同一时刻至多一条在途",
|
||||
// 因此残留只可能来自上一次发布,清掉不会误伤。
|
||||
func drainReturns(returns <-chan amqp.Return) {
|
||||
for {
|
||||
select {
|
||||
case _, ok := <-returns:
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`invalidatePublisherChannel` 的类型跟着接口走:
|
||||
|
||||
```go
|
||||
func (r *RabbitMQ) invalidatePublisherChannel(ch publishChannel) {
|
||||
r.mu.Lock()
|
||||
if r.pubCh == ch {
|
||||
r.pubCh = nil
|
||||
r.pubRet = nil
|
||||
}
|
||||
r.mu.Unlock()
|
||||
_ = ch.Close()
|
||||
}
|
||||
```
|
||||
|
||||
### 5.4 错误分类与失效规则
|
||||
|
||||
| 情形 | 检测点 | 返回 | 丢弃 channel | 调用方看到 |
|
||||
|------|--------|------|--------------|------------|
|
||||
| broker 已收下 | `WaitContext` → `true`,`returns` 为空 | nil | 否 | 成功,不写库 |
|
||||
| 不可路由(无 binding) | `WaitContext` → `true`,`returns` 有一条 | `ErrPublishUnroutable`(含 `ReplyCode` 312/313) | **否**(channel 健康) | 降级直写;日志里能直接看到是哪个 routing key |
|
||||
| broker nack / channel 中途关闭 | `WaitContext` → `false, nil` | `ErrPublishUnconfirmed` | 是 | 降级直写 |
|
||||
| 确认超时 | `WaitContext` → err | `ErrPublishTimeout`,同时 `%w` 包住 `context.DeadlineExceeded` | 是 | 降级直写;日志标记"是否送达未知" |
|
||||
| 写帧失败 / 建 channel 失败 | `PublishConfirmed` 或 `publisherChannel` 返回 err | 保留底层错误 | 是 | 降级直写 |
|
||||
| `Confirm` / `NotifyReturn` 注册失败 | `publisherChannel` | `enable publisher confirm: …` | 是(关掉刚建的) | 降级直写 |
|
||||
|
||||
**为什么不可路由不丢 channel**:channel 本身是健康的,只是拓扑错了。每次重建只会把同一个错误重复付出建 channel 的成本。
|
||||
|
||||
**为什么超时要丢**:迟到的 ack/return 会落在旧 channel 的缓冲里;旧 channel 被关闭后,新 channel 拿到全新的 `returns`,归属不会串味。
|
||||
|
||||
**为什么 nack 要丢**:nack 可能伴随 channel 级异常(如 `406 PRECONDITION_FAILED`),继续复用同一个 channel 只会连续失败。
|
||||
|
||||
### 5.5 为什么必须串行:`basic.return` 没有投递标签
|
||||
|
||||
这是整个方案唯一不直观的地方,需要写清楚:
|
||||
|
||||
- `basic.ack` 带 `delivery-tag`,所以**确认**天然可以并发归属——`PublishWithDeferredConfirmWithContext` 每条消息返回自己的 `DeferredConfirmation`,这正是选它而不用共享 `NotifyPublish` 的原因。
|
||||
- `basic.return` **不带 `delivery-tag`**(AMQP 0-9-1 的 return 只有 reply-code/text、exchange、routing-key)。它是一段"这条被退回了"的匿名通知。
|
||||
- `NotifyReturn` 的语义是"把每条 return 投递给**所有**监听者"(`channel.go` 对 listeners 逐个阻塞发送)。共享 channel 上若有 N 条消息在途,收到一条 return 时无法知道是 N 条里的哪一条。
|
||||
|
||||
可选的做法只有三个:
|
||||
|
||||
1. **串行 + 在途唯一**(本方案):return 出现时,在途的只可能是这条消息,归属无歧义。
|
||||
2. 并发 + 把任意 return 视为"全部在途失败":会误伤真正送达的消息,制造假失败 → 假降级 → 重复写。不可接受。
|
||||
3. 每条消息独立 channel:能归属,但与 P1-13 的"每代复用一个发布 channel"冲突(方案 C)。
|
||||
|
||||
因此 `pubMu` 不是"为了简单",而是 mandatory 语义在共享 channel 上成立的**必要条件**。注释里要写这一句,否则下一个重构者会顺手把锁删掉,把"偶尔丢消息"重新装回去。
|
||||
|
||||
### 5.6 超时预算
|
||||
|
||||
`publishTimeout = 3s` 的依据:
|
||||
|
||||
| 约束 | 数值 | 说明 |
|
||||
|------|------|------|
|
||||
| 健康 broker 的 confirm RTT | 0.3–2 ms | 3s 是 1500 倍余量,正常路径不会被误判 |
|
||||
| Outbox 单条发布预算 | 5s(`outboxPublishTimeout`) | 内层 3s 必须小于外层,才能在外层超时前拿到分类错误 |
|
||||
| 重连退避 | `MinBackoff=500ms`,`Jitter=0.2`,`DialTimeout=5s` | broker 重启属于"连接被拒、毫秒级失败",1–2 次重连通常能回到预算内;网络黑洞时单次拨号可达 5s,会按超时失败直写——这正是期望行为 |
|
||||
| `Park` 的预算 | 5s(`parkTimeout`) | 停泊是最后一道防线,可以比业务发布更耐心 |
|
||||
|
||||
行为变化:broker 长时间不可用时,发布**最长 3s 失败**,而不是随请求 ctx 无限等待。这是修复而不是退化——API 在 broker 故障期间仍要能写库(AGENTS.md 的 `/readyz` 设计正是这个立场)。
|
||||
|
||||
### 5.7 与 `Park` 的关系
|
||||
|
||||
不重构 `Park`。`Park` 已经满足"确认 + mandatory + 复查退回",且它的"每条消息一个独立 channel"在停泊场景(低频、必须成功)是更合适的选择。两者的**送达判定**相同,实现路径不同:
|
||||
|
||||
| | 业务发布 | 停泊 |
|
||||
|---|---|---|
|
||||
| channel | 每代复用(P1-13) | 每次新建 |
|
||||
| 确认 | `DeferredConfirmation`(可并发归属) | `NotifyPublish`(因为只有一条在途) |
|
||||
| 并发 | `pubMu` 串行 | 天然唯一 |
|
||||
| 预算 | 3s | 5s |
|
||||
|
||||
**可选的统一(不在本次)**:把 `Park` 也改成 `PublishWithDeferredConfirmWithContext`,抽 `awaitConfirm(ctx, dc, returns)` 供两处调用。收益是去掉一份重复逻辑;风险是 P0-3 是已上线路径,改动需要重跑停泊相关的集成用例。本方案选择"先让业务发布对齐停泊的语义",把合并留给下一次触碰 `Park` 的改动。
|
||||
|
||||
### 5.8 观测(可选增强 O1)
|
||||
|
||||
`/readyz` 现在能回答"连上了没有",但回答不了"发布是否一直在失败"。建议(可拆分、不阻塞主改动):
|
||||
|
||||
```go
|
||||
type Stats struct {
|
||||
...
|
||||
PublishFailures uint64 // 自进程启动以来的发布失败次数(含超时与不可路由)
|
||||
}
|
||||
```
|
||||
|
||||
- `PublishJSON` 在返回错误前 `atomic.AddUint64(&r.publishFailures, 1)`;
|
||||
- `/readyz` 增字段 `mq_publish_failures`;
|
||||
- 只加计数、不加告警阈值:阈值属于部署侧,进程不该猜。
|
||||
|
||||
这一项解决 P1-2 原文里"数据永久丢失且无日志"的"不可发现"部分;即使不做,服务层的 `log.Printf` 也会带上 exchange/routing key(§5.4 的错误文本)。
|
||||
|
||||
---
|
||||
|
||||
## 6. 改动清单
|
||||
|
||||
| 文件 | 符号 | 改动 |
|
||||
|------|------|------|
|
||||
| `backend/internal/middleware/rabbitmq/rabbitMQ.go` | `publishTimeout`、三个 `ErrPublish*` | 新增 |
|
||||
| 同上 | `RabbitMQ.pubCh` | 类型 `*amqp.Channel` → `publishChannel` |
|
||||
| 同上 | `RabbitMQ.pubRet`、`RabbitMQ.pubMu` | 新增 |
|
||||
| 同上 | `publishChannel`、`confirmation`、`amqpPublisher` | 新增(适配 `amqp.Channel`) |
|
||||
| 同上 | `publisherChannel` | 返回 `(publishChannel, chan amqp.Return, error)`;新建分支里 `Confirm` + `NotifyReturn` |
|
||||
| 同上 | `PublishJSON` | 超时 + `pubMu` + deferred 确认 + 复查 return + 分类错误 |
|
||||
| 同上 | `invalidatePublisherChannel` | 参数改 `publishChannel`;同时清 `pubRet` |
|
||||
| 同上 | `install` / `markDown` | 同步清 `pubRet`;`markDown` 关 `pubCh` |
|
||||
| 同上 | `drainReturns` | 新增 |
|
||||
| 同上 | `Stats` / `/readyz` | 仅 O1 时改;主改动不动 |
|
||||
| `backend/internal/http/router.go` | `SetRouter` 的 `/readyz` | 仅 O1 时增字段 |
|
||||
|
||||
**不改**:四个 publisher(`likeMQ.go` / `commentMQ.go` / `socialMQ.go` / `timelineMQ.go`)、四个调用方(`like_service.go` / `comment_service.go` / `social/service.go` / `outboxworker.go`)、`dlx.go` 的 `Park` 与消费循环、拓扑声明、配置结构。
|
||||
|
||||
---
|
||||
|
||||
## 7. 测试计划(TDD)
|
||||
|
||||
### 7.1 红:先复现静默丢失
|
||||
|
||||
在包内写一个**不改生产代码就能跑**的集成用例(`//go:build integration`),它当前必须失败:
|
||||
|
||||
```go
|
||||
// TestIntegration_PublishJSON_UnroutableRoutingKeyReturnsError
|
||||
// 绑 p1_2.test.* 的队列存在,但用 p1_2.none 发布:没有任何 binding 匹配。
|
||||
// 修复前 broker 丢弃消息并 ack,PublishJSON 返回 nil —— 正是静默黑洞。
|
||||
func TestIntegration_PublishJSON_UnroutableRoutingKeyReturnsError(t *testing.T) {
|
||||
mgr, topo := p12TestManager(t) // 与 integrationTestManager 同构,随机后缀
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
err := mgr.PublishJSON(ctx, topo.Exchange, "p1_2.none", map[string]string{"k": "v"})
|
||||
if !errors.Is(err, ErrPublishUnroutable) {
|
||||
t.Fatalf("unroutable publish must fail, got %v", err)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
红阶段还应补一条**"已送达仍可消费"**的正向用例(`p1_2.test.ok` → 断言收到 body),确保修复没有把正常路径一起判失败。
|
||||
|
||||
### 7.2 绿:单测(无 broker)
|
||||
|
||||
全部用包内手写 `fakePublisher`(与 `fakeConn` 同风格:无网络、无 sleep、无第三方 mock):
|
||||
|
||||
```go
|
||||
type fakePublisher struct {
|
||||
confirmCalls int
|
||||
publishCalls int
|
||||
order []string // "confirm" / "publish",用于断言顺序
|
||||
returns chan amqp.Return
|
||||
dc *fakeConfirmation
|
||||
nilDC bool // 模拟"忘了开 confirm":PublishConfirmed 返回 (nil, nil)
|
||||
publishErr error
|
||||
|
||||
mu sync.Mutex
|
||||
inFlight int
|
||||
maxInFlight int
|
||||
}
|
||||
|
||||
type fakeConfirmation struct {
|
||||
ack bool
|
||||
block bool // true 时一直不返回,直到 ctx 到期
|
||||
}
|
||||
```
|
||||
|
||||
| 测试 | 场景 | 断言 |
|
||||
|------|------|------|
|
||||
| `TestPublishJSON_ConfirmedMessageReturnsNil` | ack、无退回 | nil;`publishCalls==1`;`maxInFlight==1` |
|
||||
| `TestPublishJSON_UnroutableAfterAckReturnsError` | ack + 缓冲里有一条 return | `errors.Is(err, ErrPublishUnroutable)`;错误文本含 routing key 与 `ReplyCode` |
|
||||
| `TestPublishJSON_NackedMessageReturnsError` | `WaitContext` → `false, nil` | `errors.Is(err, ErrPublishUnconfirmed)`;`pubCh` 被置空 |
|
||||
| `TestPublishJSON_ConfirmTimeoutReturnsError` | 把 `publishTimeout` 压到 20ms,`block=true` | `errors.Is(err, ErrPublishTimeout)` 且 `errors.Is(err, context.DeadlineExceeded)`;`pubCh` 被置空 |
|
||||
| `TestPublishJSON_ConfirmIsEnabledBeforeFirstPublish` | 新 channel | `order == ["confirm", "publish"]`;`NotifyReturn` 在 publish 前已注册 |
|
||||
| `TestPublishJSON_SerializesPublishAndConfirm` | 8 个 goroutine 同时发布 | `maxInFlight == 1`(fake 里进出各改一次计数) |
|
||||
| `TestPublishJSON_PublishWriteFailureDropsChannel` | `publishErr != nil` | 返回底层错误;`pubCh` 被置空 |
|
||||
| `TestPublishJSON_NilDeferredConfirmationIsError` | fake 让 `PublishConfirmed` 返回 `(nil, nil)` | 报错,**不得**当成功(防"忘了开 confirm"回归) |
|
||||
| `TestPublishJSON_ReusesChannelWithinGeneration` | 连发 3 条 | `confirmCalls == 1`(不是每条都开 confirm) |
|
||||
| `TestPublishJSON_NilManager_DoesNotPanic` | 既有用例 | 保持通过 |
|
||||
|
||||
测试里改 `r.pubCh` / `r.pubRet` 直接注入 fake:同包、与 `fakeConn` 先例一致,不需要新增导出 API。
|
||||
|
||||
### 7.3 集成测试(需要 broker)
|
||||
|
||||
| 用例 | 目的 |
|
||||
|------|------|
|
||||
| `TestIntegration_PublishJSON_UnroutableRoutingKeyReturnsError` | R2;红阶段用例转绿 |
|
||||
| `TestIntegration_PublishJSON_ConfirmedMessageIsConsumable` | R1 正向:确认后消息真的在队列里 |
|
||||
| `TestIntegration_PublishJSON_AfterQueueDeletedReturnsError` | 删除队列(binding 消失)后发布 → 错误,不再静默丢;对应 `TestIntegration_TopologyIsRedeclaredAfterQueueDeleted` 的中间态 |
|
||||
| `TestIntegration_PublishJSON_ReconnectKeepsWorking` | 复用既有重启命令(`RABBITMQ_TEST_RESTART_CMD`),恢复后发布成功 |
|
||||
|
||||
既有集成用例的兼容性已核对:
|
||||
|
||||
- `integration_test.go` 的 `publishAndExpect` / `canConsume` 用 `p0-2.test.msg` 发到绑定 `p0-2.test.*` 的队列,**能匹配**,行为不变。
|
||||
- `canConsume` 在队列被删除后会拿到 `ErrPublishUnroutable` 而不是等 5s——这正是修复的预期效果,用例的轮询循环仍然成立(失败 → 重放拓扑 → 重试)。
|
||||
- `p03_e2e_integration_test.go` 的绑定是 `#`,不受影响。
|
||||
|
||||
### 7.4 验证命令
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
go vet ./...
|
||||
go test -race -count=1 ./...
|
||||
docker compose up -d rabbitmq
|
||||
go test -tags integration -count=1 -timeout 300s ./internal/middleware/rabbitmq/
|
||||
```
|
||||
|
||||
`-race` 是硬要求:`pubMu` / `pubCh` / `pubRet` 与 `markDown` 的交互是本改动最可能藏竞态的地方。
|
||||
|
||||
---
|
||||
|
||||
## 8. 上线与回滚
|
||||
|
||||
- **无配置变更、无 DDL、无新依赖**,API 与 Worker 可独立滚动发布;新旧版本混跑期间行为差异只在"发布是否等确认",协议层完全兼容。
|
||||
- **回滚**:回退代码即可,broker 侧无残留状态(confirm 是 channel 级模式,channel 关闭即失效)。
|
||||
- **上线后人工验证**(staging):
|
||||
1. 故意把 `like.like` 的 binding 改成 `like.xxx`,点赞 → 日志出现 `publish like.events/like.like: … unroutable …`,数据库里有点赞行;
|
||||
2. 恢复 binding,点赞 → 日志只有"入队",数据库行由 worker 写入;
|
||||
3. `docker compose stop rabbitmq` 后点赞 → 3s 内返回成功(走了直写),`/readyz` 立即 503;
|
||||
4. `docker compose start rabbitmq`,等待 ready,确认发布恢复。
|
||||
|
||||
---
|
||||
|
||||
## 9. 验收记录(实现后回填)
|
||||
|
||||
| 项 | 结论 | 证据 |
|
||||
|----|------|------|
|
||||
| 单测 | 待填 | `go test -race -count=1 ./internal/middleware/rabbitmq/` |
|
||||
| 全量 | 待填 | `go test -race -count=1 ./...` |
|
||||
| 集成 | 待填 | `go test -tags integration ./internal/middleware/rabbitmq/` |
|
||||
| 人工验证 | 待填 | §8 的四步 |
|
||||
|
||||
---
|
||||
|
||||
## 10. 语义影响与风险
|
||||
|
||||
### 10.1 用户可见的延迟
|
||||
|
||||
点赞/评论/关注现在多等一个 broker confirm(约 1 ms 量级)。这是"返回成功即已入队"的必要代价;真正重要的是**失败不再被吞掉**。若某天需要把延迟压回 0,正确做法是把这三条写路径改成 Outbox(本地事务 + 异步发布),而不是回到 fire-and-forget。
|
||||
|
||||
### 10.2 broker 故障期间的 DB 压力
|
||||
|
||||
断连时发布改为 3s 内失败 → 降级直写。此前是无限等待:请求一直挂在 `WaitReady` 上,直到客户端放弃、请求 ctx 被取消,而降级写入此时已经带着被取消的 ctx。因此**"broker 故障 → 直写 DB"这条降级路径实际上从未真正跑通过**。上线后第一次 broker 故障会把直写流量真实地压到 MySQL 上,需要确认 MySQL 连接池与热点行的承受能力(点赞行是典型热点)。这是修正语义的必然结果,不是回归。
|
||||
|
||||
### 10.3 "是否送达未知"造成重复
|
||||
|
||||
超时(`ErrPublishTimeout`)无法区分"消息没进 broker"与"进了但确认丢了"。降级直写后,worker 可能稍后也消费到同一条事件:
|
||||
|
||||
- 点赞:`ApplyLike` 命中唯一索引 → `created=false` → 不再加热度(P0-3 已定义空操作);
|
||||
- 评论:`CreateIdempotentWithPopularity` 按 `(author, intent_key)` 去重 → 不重复插入;
|
||||
- 视频:outbox 行保留 pending,下一轮重发;timeline 写 ZSET 幂等;
|
||||
- 关注:DB-first,发布失败只影响通知,重复通知由通知表幂等吸收。
|
||||
|
||||
**已知瑕疵**:若 worker 先写入、API 的降级写入后到,`ApplyLike` 返回 `created=false`,用户会看到"已点赞过"而不是成功。这发生在超时窗口内(罕见),且是"至少一次 + 无法判定"的固有代价。更彻底的做法是把点赞降级路径的 `created=false` 视为幂等成功——属于 P0-4 范畴的独立小改动,本方案不顺手改。
|
||||
|
||||
### 10.4 Outbox 批次吞吐
|
||||
|
||||
`StartOutboxPoller` 顺序处理 100 行;每条现在会等确认。broker 正常时新增 100 × RTT(约 0.1s),可忽略。broker 异常时每条最长 3s → 一批可能拖到 300s,poller 停摆。P1-3(退避 / 批次饥饿 / 单批预算)本来就要处理这个循环,本方案只把"失败能被看到"这一前提补上。若 P1-3 未落地而需要立刻缓解,可在 poller 里"遇错即跳出本轮"(一个 `break`),但那属于 P1-3 的范围。
|
||||
|
||||
### 10.5 风险表
|
||||
|
||||
| 风险 | 概率 | 影响 | 缓解 |
|
||||
|------|------|------|------|
|
||||
| `pubMu` 被后续重构删掉 | 中 | 退回无法归属,假失败/漏失败 | §5.5 的理由写进代码注释;单测断言 `maxInFlight==1` |
|
||||
| `publishTimeout` 误伤慢 broker | 低 | 短时直写 | 3s 是 confirm RTT 的千倍;O1 的失败计数可观测 |
|
||||
| `Confirm(false)` 失败后 channel 泄漏 | 低 | 连接数缓慢增长 | 失败分支显式 `Close`;`install`/`markDown` 兜底 |
|
||||
| 集成测试依赖真实 broker | 确定 | CI 默认不跑 | 与既有 P0-2/P0-3 集成用例同一约定(`//go:build integration`) |
|
||||
| 旧版本(fire-and-forget)与新版本混跑 | 确定 | 旧实例仍会静默丢 | 滚动发布窗口内可接受;发布完成后旧行为消失 |
|
||||
|
||||
---
|
||||
|
||||
## 11. 文档同步
|
||||
|
||||
| 文档 | 改动 |
|
||||
|------|------|
|
||||
| `docs/design/消息处理失败与死信队列.md` | 在 §8"停泊是一次可靠发布"之后增一节"业务发布同样需要确认",说明 `PublishJSON` 的 nil 语义、串行的原因、以及为什么不可路由不丢 channel |
|
||||
| `docs/feedsystem_video_go项目设计.md` | 更新"不重发:`PublishJSON` 如实返回错误、由服务层降级直写"一段,补一句"nil 表示 broker 已 ack 且未退回" |
|
||||
| `docs/ISSUES-REPORT.md` | **实现完成并验证后**再把 P1-2 从"部分修复"改为已修复,附本文件链接;设计阶段不改状态 |
|
||||
|
||||
---
|
||||
|
||||
## 12. 后续(明确不在本次)
|
||||
|
||||
1. **P1-3**:outbox 的 attempts / 退避 / 单批预算 / 遇错跳出。
|
||||
2. **O1**:`Stats.PublishFailures` + `/readyz` 字段。
|
||||
3. **`Park` 与业务发布共用确认助手**:把 `Park` 切到 deferred confirm,抽 `awaitConfirm`。
|
||||
4. **发布分片**:按 routing key 哈希到 N 个发布 channel,各自串行(仅当吞吐成为问题时)。
|
||||
5. **点赞降级的幂等语义**:`created=false` 视为成功,消除 §10.3 的已知瑕疵。
|
||||
326
docs/solutions/P1-4-social-db-first.md
Normal file
326
docs/solutions/P1-4-social-db-first.md
Normal file
@@ -0,0 +1,326 @@
|
||||
# P1-4 解决方案:关注只写一次库,事件只发通知
|
||||
|
||||
> **对应问题**:`ISSUES-REPORT.md` 的 P1-4「关注流实为 DB-first,且 worker 冗余重放写库」。
|
||||
> **关联**:D-2(文档与代码不一致)、P2-13(取关的通知补偿)、P2-15(5xx 回显错误串)。
|
||||
> **状态**:已实施(2026-11-11)。§3 的三项 RabbitMQ 结构改动已按批准执行。验证:`go vet ./...` 通过,`go test -count=1 ./...` 全绿;本机没有 C 编译器,`-race` 由 CI(`golang:1.24.5`)执行。
|
||||
|
||||
## 1. 问题
|
||||
|
||||
### 1.1 现象
|
||||
|
||||
关注和取关在“已经做过一次”时会返回 500:
|
||||
|
||||
| 操作 | 发生了什么 | 客户端看到的 |
|
||||
|---|---|---|
|
||||
| 已关注后再点关注 | `Follow` 先查 `IsFollowed`,命中后返回 `errors.New("already followed")` | 500,`{"error":"already followed"}` |
|
||||
| 两个标签页同时点关注 | 两次先查都没命中,第二个 `INSERT` 撞唯一索引 | 500,`{"error":"Error 1062 (23000): Duplicate entry ..."}` |
|
||||
| 已取关后再点取关 | `Unfollow` 先查 `IsFollowed`,没查到就返回 `errors.New("not followed")` | 500,`{"error":"not followed"}` |
|
||||
| 每次关注成功 | `SocialWorker` 收到事件后再 `INSERT` 同一行,1062 被吞 | 无感,但多写一次库 |
|
||||
| 每次取关成功 | `SocialWorker` 收到事件后再 `DELETE` 一次 | 无感,但多删一次库 |
|
||||
|
||||
后果:用户看到“关注失败”,但数据库里其实已经关注成功;前端可能弹错误提示或回滚按钮;MySQL 错误原文(表名、索引名)直接返回给客户端;worker 每次都在做一次无效写。
|
||||
|
||||
### 1.2 代码位置
|
||||
|
||||
`backend/internal/social/service.go` 的 `SocialService.Follow`:
|
||||
|
||||
```go
|
||||
isFollowed, err := s.repo.IsFollowed(ctx, social)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if isFollowed {
|
||||
return errors.New("already followed")
|
||||
}
|
||||
|
||||
// 先写 DB,确保数据持久化
|
||||
if err := s.repo.Follow(ctx, social); err != nil {
|
||||
return err
|
||||
}
|
||||
```
|
||||
|
||||
同一个文件的 `SocialService.Unfollow`:
|
||||
|
||||
```go
|
||||
if !isFollowed {
|
||||
return errors.New("not followed")
|
||||
}
|
||||
```
|
||||
|
||||
`backend/internal/social/repo.go` 的 `SocialRepository.Follow` 直接 `Create`,`Unfollow` 不看影响行数:
|
||||
|
||||
```go
|
||||
func (r *SocialRepository) Follow(ctx context.Context, social *Social) error {
|
||||
return r.db.WithContext(ctx).Create(social).Error
|
||||
}
|
||||
|
||||
func (r *SocialRepository) Unfollow(ctx context.Context, social *Social) error {
|
||||
return r.db.WithContext(ctx).
|
||||
Where("follower_id = ? AND vlogger_id = ?", social.FollowerID, social.VloggerID).
|
||||
Delete(&Social{}).Error
|
||||
}
|
||||
```
|
||||
|
||||
`backend/internal/worker/socialworker.go` 的 `SocialWorker.process`:
|
||||
|
||||
```go
|
||||
case "follow":
|
||||
err := w.repo.Follow(ctx, &social.Social{
|
||||
FollowerID: evt.FollowerID,
|
||||
VloggerID: evt.VloggerID,
|
||||
})
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
// 重复投递:关注关系已在,唯一索引挡下第二条。这是成功语义。
|
||||
var mysqlErr *mysql.MySQLError
|
||||
if errors.As(err, &mysqlErr) && mysqlErr.Number == 1062 {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
```
|
||||
|
||||
### 1.3 性质
|
||||
|
||||
这是实现问题,不是文档问题。
|
||||
|
||||
- `socials` 上已经有唯一索引 `idx_social_follower_vlogger`,重复关注本来能由数据库挡下;但服务层在写之前先查了一次,把“重复”提前变成了 `error`,于是 500。
|
||||
- 取关同理:“没关注过”与“关注过又删了”都返回 `not followed`,而真正该判断的是这次 `DELETE` 有没有删掉行。
|
||||
- `SocialWorker` 与 API 各写一次 `socials`,两边对“重复”的处理相反:API 当错误,worker 当成功。
|
||||
|
||||
文档里“关注走 MQ-first、发布失败降级直写”的描述已经和代码不符(D-2),但那只是让人误判方向,不是故障根因。
|
||||
|
||||
## 2. 结论
|
||||
|
||||
1. **重复不是错误。** 关注、取关是否真的发生,交给唯一索引和影响行数回答;重复请求返回 200,响应体用 `created` / `deleted` 说明这次有没有真的改数据。
|
||||
2. **`socials` 只留一个写入点。** 服务层写完库就够了,`SocialWorker` 删除。
|
||||
3. **缓存失效和通知跟着“真的变了”走。** 只有这次真的插入或删除,才失效 following 缓存、才发通知。
|
||||
4. **关注自己返回 400。** 它是客户端错误,不该落成 500。
|
||||
5. **事件只做通知。** 只保留 `social.follow` → `notification.social`;取关不发事件。
|
||||
|
||||
## 3. 结构改动(已批准)
|
||||
|
||||
这三项会改动 RabbitMQ 拓扑,已于 2026-11-11 批准,随本次改动一起执行。
|
||||
|
||||
| 结构 | 是否改 | 具体改动 | 不改的后果 |
|
||||
|---|---|---|---|
|
||||
| MySQL 表 | 不改 | 无迁移。判重继续用现有唯一索引 `idx_social_follower_vlogger` | 只能靠预查判重,并发重复仍会 500 |
|
||||
| Redis 键 | 不改 | 键名与 pattern 不动,仍是 `feed:listByFollowing:*:accountID=%d:*`。只是调用时机从“每次请求”改为“真的插入/删除” | 无 |
|
||||
| 队列 `social.events` | 删 | 删除 `SocialQueue`、`SocialBindingKey` 与这条绑定 | 没有消费者,关注事件会一直留在队列里 |
|
||||
| 路由键 `social.unfollow` | 删 | 删除 `SocialUnfollowRK` 与 `SocialMQ.UnFollow` | 没人订阅,发出去就丢 |
|
||||
| `SocialMQ` 登记目标 | 改 | 从 `social.events` + `social.*` 改为 `notification.social` + `social.follow` | 生产者没有可登记的队列,交换机会没人声明,发布直接失败 |
|
||||
|
||||
为什么生产者要登记 `notification.social`:`RegisterTopology` 要求 exchange、queue、binding key 三者齐全,缺一个就跳过并打 `rabbitmq: 忽略非法拓扑`。队列和绑定必须有人先声明,消息才发得出去。API 和 worker 都会声明同一份拓扑,队列参数只由队列名推导,重复声明是幂等的。
|
||||
|
||||
不变的部分:交换机名 `social.events`、路由键 `social.follow`、消息体 `SocialEvent`、`notification.social` 的队列名与绑定、`NotificationWorker` 的消费与去重逻辑。
|
||||
|
||||
备选方案与取舍:
|
||||
|
||||
- **保留 worker 和队列**:现状,问题不解决。
|
||||
- **只删 worker、留队列**:队列没人消费,事件无限堆积。
|
||||
- **删队列,但给 `RegisterTopology` 加“只声明交换机”的能力**:改的是共享拓扑工具,影响所有业务方,收益只是省一个队列登记。
|
||||
- **推荐**:按上表删除队列与取关路由键,生产者改登记 `notification.social`。
|
||||
|
||||
已确认:
|
||||
|
||||
1. 删除 `social.events` 队列与 `social.unfollow` 路由键,生产者改登记 `notification.social`。
|
||||
2. 仓库内只有 `SocialWorker` 一个消费者;若仓库外另有订阅 `social.events` 的消费者,发布前需要通知对方(部署侧确认)。
|
||||
3. 发布后手工删除线上残留的 `social.events`、`social.events.retry`、`retry.events.social.events`。
|
||||
|
||||
## 4. 需求与边界
|
||||
|
||||
| # | 需求 |
|
||||
|---|---|
|
||||
| R1 | 重复关注返回 200,`created` 为 `false`;响应体不再出现 `Duplicate entry` 或 `already followed` |
|
||||
| R2 | 重复取关返回 200,`deleted` 为 `false`,不再出现 `not followed` |
|
||||
| R3 | 关注自己返回 400,且不写库、不发消息 |
|
||||
| R4 | 只有这次真的插入或删除,才失效 following 缓存、才发通知 |
|
||||
| R5 | 首次关注仍给被关注者生成一条通知;发通知失败不影响已成功的关注 |
|
||||
| R6 | 唯一索引之外的数据库错误仍向上返回,不被当成“重复”吞掉 |
|
||||
| R7 | `socials` 只有服务层一个写入点,worker 不再写库 |
|
||||
|
||||
本次不做:
|
||||
|
||||
- 取关、删评论的通知补偿(P2-13)。
|
||||
- 5xx 响应去掉错误原文(P2-15)。
|
||||
- 删除 `IsFollowed` 死代码(报告第八节,第四阶段统一清)。
|
||||
- 去掉两次 `FindByID`。`VloggerID` 不存在必须仍是 404。
|
||||
- 加事务。单条 `INSERT` / `DELETE` 本身原子,加事务只会把两段拆开的操作重新绑在一起。
|
||||
|
||||
## 5. 方案
|
||||
|
||||
### 5.1 仓储层:让数据库回答“有没有变”
|
||||
|
||||
```go
|
||||
// Follow 返回本次是否真的插入:重复关注是幂等成功,不是错误。
|
||||
func (r *SocialRepository) Follow(ctx context.Context, social *Social) (bool, error) {
|
||||
res := r.db.WithContext(ctx).
|
||||
Clauses(clause.OnConflict{DoNothing: true}).
|
||||
Create(social)
|
||||
if res.Error != nil {
|
||||
return false, res.Error
|
||||
}
|
||||
return res.RowsAffected > 0, nil
|
||||
}
|
||||
|
||||
// Unfollow 用影响行数回答“这次是否真的删掉”:第二次取关是空操作。
|
||||
func (r *SocialRepository) Unfollow(ctx context.Context, social *Social) (bool, error) {
|
||||
res := r.db.WithContext(ctx).
|
||||
Where("follower_id = ? AND vlogger_id = ?", social.FollowerID, social.VloggerID).
|
||||
Delete(&Social{})
|
||||
if res.Error != nil {
|
||||
return false, res.Error
|
||||
}
|
||||
return res.RowsAffected > 0, nil
|
||||
}
|
||||
```
|
||||
|
||||
GORM 的 MySQL 方言把 `OnConflict{DoNothing}` 编译成 `ON DUPLICATE KEY UPDATE id=id`,不是 `INSERT IGNORE`:唯一键冲突时影响行数为 0,其他错误照常返回。前提是 DSN 不开 `clientFoundRows`,`internal/db/db.go` 的注释和单测已经钉住这一点。
|
||||
|
||||
### 5.2 服务层:唯一写入点,按结果决定副作用
|
||||
|
||||
```go
|
||||
func (s *SocialService) Follow(ctx context.Context, social *Social) (bool, error) {
|
||||
if social.FollowerID == social.VloggerID {
|
||||
return false, ErrCannotFollowSelf
|
||||
}
|
||||
if _, err := s.accountrepo.FindByID(ctx, social.FollowerID); err != nil {
|
||||
return false, err
|
||||
}
|
||||
if _, err := s.accountrepo.FindByID(ctx, social.VloggerID); err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
created, err := s.repo.Follow(ctx, social)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if !created {
|
||||
// 关系已在,缓存和通知都已经是“已关注”状态。
|
||||
return false, nil
|
||||
}
|
||||
|
||||
s.invalidateFollowingFeedCache(context.Background(), social.FollowerID)
|
||||
if err := s.socialMQ.Follow(ctx, social.FollowerID, social.VloggerID); err != nil {
|
||||
log.Printf("social MQ Follow 发布失败: %v", err)
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
```
|
||||
|
||||
`Unfollow` 结构相同,返回 `(deleted bool, err error)`,去掉发通知那一段。两点说明:
|
||||
|
||||
- 自关注检查放到最前,不依赖数据库。
|
||||
- 缓存失效仍用 `context.Background()`:请求可能已被客户端取消,但行已经写进去了。
|
||||
|
||||
为了能写单测,`SocialService` 的依赖收窄成三个接口(`socialStore`、`accountFinder`、`followNotifier`),`router.go` 的调用点不用改。`*rabbitmq.SocialMQ` 在 nil 接收者上返回 error,所以 MQ 没启用时只会多一条日志,不会把已经写成功的关注变成失败。
|
||||
|
||||
### 5.3 handler:自关注映射成 400
|
||||
|
||||
```go
|
||||
func classifySocialError(err error) int {
|
||||
if errors.Is(err, ErrCannotFollowSelf) {
|
||||
return http.StatusBadRequest
|
||||
}
|
||||
return apierror.ClassifyHTTPStatus(err)
|
||||
}
|
||||
```
|
||||
|
||||
其余错误仍走 `ClassifyHTTPStatus`。`SocialHandler.Follow` 与 `Unfollow` 把布尔值写进响应:
|
||||
|
||||
```go
|
||||
created, err := h.service.Follow(c.Request.Context(), social)
|
||||
if err != nil {
|
||||
c.JSON(classifySocialError(err), gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"message": "followed", "created": created})
|
||||
```
|
||||
|
||||
`Unfollow` 对应 `deleted` 与 `"unfollowed"`。
|
||||
|
||||
### 5.4 事件:只发关注通知
|
||||
|
||||
```go
|
||||
const (
|
||||
SocialExchange = "social.events"
|
||||
SocialFollowRK = "social.follow"
|
||||
)
|
||||
|
||||
func NewSocialMQ(base *RabbitMQ) (*SocialMQ, error) {
|
||||
if base == nil {
|
||||
return nil, errors.New("rabbitmq base is nil")
|
||||
}
|
||||
base.RegisterTopology(Topology{
|
||||
Exchange: SocialExchange,
|
||||
Queue: NotificationSocialQueue,
|
||||
BindingKey: SocialFollowRK,
|
||||
})
|
||||
return &SocialMQ{mgr: base}, nil
|
||||
}
|
||||
```
|
||||
|
||||
### 5.5 删除 `SocialWorker`
|
||||
|
||||
删 `backend/internal/worker/socialworker.go`,同时去掉 `cmd/worker` 里的三处:第一批 `RegisterTopology` 中的 social 拓扑、`socialRepo` 与 `internal/social` import、`RunConsumer(..., "SocialWorker", 50, ...)`。
|
||||
|
||||
## 6. 副作用与取舍
|
||||
|
||||
- **重复点击不再刷新缓存。** 行没变,列表就没变;但如果上一次失效本身失败了,要等下一次真实变更或缓存过期才恢复。
|
||||
- **取关后旧通知仍在。** 关注通知不会撤回,这是 P2-13 的缺口。
|
||||
- **通知可能丢。** 关注已经落库但发布失败时只记日志,没有 outbox 和重试。
|
||||
- **其他数据库错误仍是 500 且带原文。** 例如连接中断、字段超长,脱敏属于 P2-15。
|
||||
- **`ON DUPLICATE KEY UPDATE` 对任何唯一键冲突都不报错。** `socials` 目前只有 `idx_social_follower_vlogger` 一个唯一索引,成立;以后加第二个唯一索引要重新评估。
|
||||
- **自增 ID 会有空洞。** 冲突的 `INSERT` 仍会推进 `AUTO_INCREMENT`,与评论路径一致。
|
||||
- **为什么不返回 409。** 重复是正常语义,不是冲突;前端会把 409 当失败弹提示。
|
||||
- **为什么不用 1062 判重。** 项目已有更直接的写法(`OnConflict` + 影响行数),`docs/design/写路径幂等.md` 也写明不用 1062。两种写法并存会让两条写路径风格分裂。
|
||||
- **响应体只新增字段。** `message` 保留,`created` / `deleted` 是增量,前端不解析也不受影响。
|
||||
|
||||
## 7. 测试
|
||||
|
||||
单测用 fake 驱动,不需要 MySQL 和 broker:
|
||||
|
||||
| 测试 | 断言 |
|
||||
|---|---|
|
||||
| `TestSocialService_Follow_SecondCallIsNoop` | 首次 `(true, nil)`、通知 1 条;重复 `(false, nil)`、通知仍是 1 条 |
|
||||
| `TestSocialService_Follow_SelfIsRejected` | `(false, ErrCannotFollowSelf)`,写库 0 次 |
|
||||
| `TestSocialService_Follow_RepoErrorPropagates` | 仓储报错 → 原样返回,通知 0 次 |
|
||||
| `TestSocialService_Follow_NotifyFailureKeepsSuccess` | 发通知失败 → `(true, nil)` |
|
||||
| `TestSocialService_Follow_AccountLookupErrorPropagates` | 账号查询失败 → 原样返回,写库 0 次 |
|
||||
| `TestSocialService_Unfollow_SecondCallIsNoop` | `(false, nil)` |
|
||||
| `TestSocialHandler_Follow_SelfReturnsBadRequest` | 状态码 400,响应体含 `can not follow self` |
|
||||
| `TestSocialHandler_Follow_DuplicateReturnsOK` | 状态码 200,响应体 `created` 为 `false` |
|
||||
| `TestSocialHandler_Unfollow_DuplicateReturnsOK` | 状态码 200,响应体 `deleted` 为 `false` |
|
||||
|
||||
`TestSocialService_*` 用 fake 的 `socialStore`、`accountFinder`、`followNotifier`;handler 测试用 `gin.CreateTestContext` 加 `c.Set("accountID", uint(1))`。
|
||||
|
||||
仓储的判重行为对着真 MySQL 验证,放 `//go:build integration`,沿用 `commentworker_integration_test.go` 的做法(`MYSQL_TEST_DSN` 缺失就 `t.Skip`,DSN 带 `clientFoundRows` 直接失败):
|
||||
|
||||
| 测试 | 断言 |
|
||||
|---|---|
|
||||
| `TestSocialRepository_Follow_DuplicateReportsNotCreated` | 插两次:`true` → `false`,都无 error,表里 1 行 |
|
||||
| `TestSocialRepository_Unfollow_SecondCallReportsNotDeleted` | 删两次:`true` → `false`,都无 error |
|
||||
|
||||
手工验收:连点两次关注、两次取关各返回两个 200;关注自己返回 400;被关注者只有一条通知;`rabbitmqctl list_queues` 里没有 `social.events`。
|
||||
|
||||
**验证记录(2026-11-11)**:`go vet ./...` 通过;`go test -count=1 ./...` 全绿,`internal/social` 与 `internal/middleware/rabbitmq` 均 ok。集成测试对 MySQL 8.0 通过(`MYSQL_TEST_DSN` 指向 `feedsystem_test`),确认重复插入返回 `created=false`、第二次删除返回 `deleted=false`。本机 `CGO_ENABLED=0` 且没有 C 编译器,未跑 `-race`,由 CI(`golang:1.24.5`)执行 `go test -race -count=1 ./...`。
|
||||
|
||||
## 8. 改动清单
|
||||
|
||||
| 文件 | 改动 |
|
||||
|---|---|
|
||||
| `backend/internal/social/repo.go` | `Follow`、`Unfollow` 返回 `(bool, error)` |
|
||||
| `backend/internal/social/service.go` | 删掉两处先查;新增 `ErrCannotFollowSelf` 与三个窄接口;`Follow` / `Unfollow` 返回 `(bool, error)`,按结果决定失效缓存和发通知;`Unfollow` 不再发事件 |
|
||||
| `backend/internal/social/handler.go` | 新增 `classifySocialError`;响应体加 `created` / `deleted` |
|
||||
| `backend/internal/social/service_test.go` | 新增 §7 的单测 |
|
||||
| `backend/internal/social/handler_test.go` | 新增自关注 400、重复关注 200 |
|
||||
| `backend/internal/social/repo_integration_test.go` | 新增集成测试 |
|
||||
| `backend/internal/worker/socialworker.go` | 删除 |
|
||||
| `backend/cmd/worker/main.go` | 删 SocialWorker 启动、`socialRepo`、social 拓扑与 import |
|
||||
| `backend/internal/middleware/rabbitmq/socialMQ.go` | 删 `SocialQueue`、`SocialBindingKey`、`SocialUnfollowRK`、`UnFollow`;登记改 `notification.social` |
|
||||
| `backend/internal/middleware/rabbitmq/constants_test.go` | 删三个常量的断言 |
|
||||
| `backend/internal/middleware/rabbitmq/notification.go` | 注释补一句“关注没有 DB 同步队列” |
|
||||
| `docs/design/写路径幂等.md` | §1 把关注从 MQ-first 里拆出来,写明判重键与 `created` / `deleted` |
|
||||
| `docs/design/消息处理失败与死信队列.md` | 业务队列 8 个改 7 个 |
|
||||
| `docs/feedsystem_video_go项目设计.md` | 事件表、接口表、消费者表、`mq_topology` 期望值(Worker 7 → 6) |
|
||||
| `docs/ISSUES-REPORT.md` | P1-4 标 ✅ 并补“解决”段与索引;D-2 更新 |
|
||||
Reference in New Issue
Block a user