This file provides guidance to Codex (claude.ai/code) when working with code in this repository.
## Project Overview
Short video feed system with Go 1.24 backend (Gin + GORM + MySQL + Redis + RabbitMQ) and Vue 3 + TypeScript frontend (rolldown-vite). Two backend binaries: API server and async Worker process. All domain wiring is manual constructor injection in `router.go` — no DI framework.
**Documentation**: Chinese documentation available in `docs/project-construction-guide.md` (detailed build roadmap) and `feedsystem_video_go项目设计.md` (system design).
## Commands
### Backend (run from `backend/`)
```bash
# Run all tests with race detection
go test -race -count=1 ./...
# Run a single test
go test -run TestFunctionName ./internal/package/...
# Vet
go vet ./...
# Run API server locally
go run ./cmd
# Run worker process locally
go run ./cmd/worker
```
### Frontend (run from `frontend/`)
```bash
npm ci # install dependencies (clean)
npm run dev # dev server (Vite, proxies /api -> http://127.0.0.1:8080)
npm run build # production build (vue-tsc -b && vite build)
npm run preview # preview production build locally
```
### Docker Compose (root)
```bash
docker compose up -d # full stack: MySQL, Redis, RabbitMQ, API, Worker, Frontend
docker compose up -d mysql redis rabbitmq # infra only, then run backend locally
```
### Local Dev Script (root)
```bash
# start.sh uses env vars to control what starts: START_REDIS, START_RABBITMQ, START_BACKEND, START_WORKER, START_FRONTEND
# Or start infra via compose, then run backend locally with the compose-local config:
docker compose up -d mysql redis rabbitmq
CONFIG_PATH=configs/config.compose-local.yaml go run ./cmd # API
CONFIG_PATH=configs/config.compose-local.yaml go run ./cmd/worker # Worker
```
## Architecture
### Dual Binary Split
-`backend/cmd/main.go` — Gin HTTP API server (port 8080, pprof on :6060)
-`backend/cmd/worker/main.go` — RabbitMQ consumer process (pprof on :6061). Runs the Social, Like, Comment, and Popularity workers in independent goroutines; each gets its own AMQP channel from the shared connection manager and reconnects automatically. (Notification workers, the Outbox poller, and the timeline consumer currently live in the API process — see `router.go`.)
### Domain Layer Pattern
Each domain (`account`, `video`, `social`, `feed`) follows: **Entity → Repository → Service → Handler**. `message` and `notification` are simpler — `message` has entity + handler only (no separate repo/service), `notification` is handler-only (routes in `router.go`, worker-side logic in `worker/notificationworker.go`). All wiring is manual constructor injection in `backend/internal/http/router.go` (no DI framework).
**API Style**: All endpoints use POST (except SSE stream and health check) to simplify frontend client abstraction and unify JSON body handling.
### API Route Groups
All routes defined in `backend/internal/http/router.go`:
-`/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.
-`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`.
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`
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.
TDD is the default working mode for behavior changes under `backend/`. The frontend has no test runner yet (`frontend/package.json` exposes only `dev`, `build`, `preview`), so frontend work is verified with `npm run build` plus a manual check of the affected view — do not describe it as test-driven. If a runner (e.g. Vitest) is added, extend this section in the same change.
### The loop: red → green → refactor
1.**Red** — write the smallest test that expresses the new behavior, run it, and watch it fail. Confirm it fails for the expected reason (wrong value, missing call, unexpected status) and not because of a typo, nil panic, or broken fixture.
2.**Green** — write the minimal production code that makes it pass. No speculative abstractions, no extra options "while I'm here".
3.**Refactor** — clean up implementation and test names with the suite green, re-running after each step.
4. Commit the test and the implementation together. A push that adds behavior without a test is incomplete work, not a follow-up.
Bug fixes start from a regression test that reproduces the bug — failing before the fix, green after. State the failing assertion in the commit message or PR description so reviewers can see what was actually broken.
### Placement and naming
- One `*_test.go` beside the code it covers, in the **same package** (`package http`, `package rabbitmq`, …) so unexported state and helpers are reachable. Use an external `_test` package only when the test should consume the public API.
- Name tests `TestSubject_ExpectedBehavior`, e.g. `TestReadyz_MQEnabledButDisconnected_IsDistinguishable`. Use table-driven cases with `t.Run` subtests and a `name string` field when one behavior has several inputs.
- Mark every helper with `t.Helper()`. Shared fixtures live in `_test.go` files, never in production packages.
- Keep the intent comment. Existing suites explain *why* an invariant exists (see the `/readyz` case in `backend/internal/http/router_test.go`); a test whose reason is unwritten gets deleted by the next person who finds it inconvenient. Match the surrounding file's comment language — test comments in this repo are largely Chinese.
### Test doubles
The repo deliberately has no mocking framework. Match that:
- **RabbitMQ / connection state machines** — hand-written fakes implementing the narrow interface (`fakeConn` in `backend/internal/middleware/rabbitmq/rabbitmq_test.go`). Keep them tiny: no network I/O, no timing assumptions.
- **Redis** — `miniredis`.
- **HTTP handlers** — `httptest` with `gin.SetMode(gin.TestMode)`, `gin.CreateTestContext`, or a router built via `SetRouter` as `backend/internal/http/router_test.go` does.
- **MySQL** — there is no DB mock. Either extract a narrow interface and fake it for a unit test, or write the test against real MySQL and document that the infra must be up first.
Assert on observable behavior (HTTP status and body, rows written, messages published) rather than internal call counts; call-count assertions break on harmless refactors.
### Integration tests
Anything needing a real broker or MySQL lives in a `//go:build integration` file and is excluded from the default run:
```bash
docker compose up -d rabbitmq
go test -tags integration -count=1 -timeout 300s -v ./internal/middleware/rabbitmq/
```
Configure endpoints through env vars (`RABBITMQ_TEST_URL`, …), never hardcoded hosts. When a prerequisite is missing — a restart command, a delete-queue command — `t.Skip` with the reason; a silent pass is not a substitute for a skip.
### Determinism and speed
- No real network in unit tests; no `time.Sleep` as synchronization. Prefer channels, context deadlines, or an injected clock. Tests must pass under `-race` and in any order.
- Run `go test -race -count=1 ./...` before every push. `-count=1` is required: cached results hide flakiness, and `-race` catches the concurrency bugs this codebase is full of.
- Do not shorten a documented timing guard to make the suite faster. `TestReadyz_MQEnabledButDisconnected_IsDistinguishable` takes ~5s on purpose — that wait *is* the assertion that the startup `EnsureTopology` timeout works.
- Treat coverage as review input (`go test -cover ./...`), not a gate. Chasing a percentage produces assertion-free tests; missing behavior coverage on service and branch logic is the real risk.
### Existing tests are contracts
- Never weaken, skip, or delete an assertion to get a change through. If an invariant genuinely changes, change the test in the same commit and explain why in the message.
- A new test that needs to reach into private fields, sleep for seconds, or start a container usually means the unit boundary is wrong — fix the design (inject the dependency) instead of adding scaffolding.
- When a test starts failing "because the environment changed", check whether it was ever deterministic before editing it.
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 ./... 全绿`.