17 KiB
AGENTS.md
This file provides guidance to Codex (claude.ai/code) when working with code in this repository.
Project Overview
Short video feed system with Go 1.24 backend (Gin + GORM + MySQL + Redis + RabbitMQ) and Vue 3 + TypeScript frontend (rolldown-vite). Two backend binaries: API server and async Worker process. All domain wiring is manual constructor injection in router.go — no DI framework.
Documentation: Chinese documentation available in docs/project-construction-guide.md (detailed build roadmap) and feedsystem_video_go项目设计.md (system design).
Commands
Backend (run from backend/)
# 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/)
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)
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)
# start.sh uses env vars to control what starts: START_REDIS, START_RABBITMQ, START_BACKEND, START_WORKER, START_FRONTEND
START_BACKEND=1 START_WORKER=1 START_FRONTEND=1 ./start.sh
# Or start infra via compose, then run backend locally with the compose-local config:
docker compose up -d mysql redis rabbitmq
CONFIG_PATH=configs/config.compose-local.yaml go run ./cmd # API
CONFIG_PATH=configs/config.compose-local.yaml go run ./cmd/worker # Worker
Architecture
Dual Binary Split
backend/cmd/main.go— Gin HTTP API server (port 8080, pprof on :6060)backend/cmd/worker/main.go— RabbitMQ consumer process (pprof on :6061). Runs the Social, Like, Comment, and Popularity workers in independent goroutines; each gets its own AMQP channel from the shared connection manager and reconnects automatically. (Notification workers, the Outbox poller, and the timeline consumer currently live in the API process — seerouter.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 countGET /healthz— health check (process liveness; always 200)GET /readyz— dependency readiness: 503 while RabbitMQ is disconnected, reportingmq_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 frombackend/.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) andSoftJWTAuth()(optional) inmiddleware/jwt/. Redis-first token check, DB fallback. The signing key is injected once at startup viaauth.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-generationSession{Ch,Done}handles). Per-domain publishers and DLX live here too.
Workers
Consumers never touch *amqp.Connection. Each one runs rabbitmq.RunConsumer(ctx, mgr, name, prefetch, fn) — the single consume loop in the project. It blocks (no polling) while the connection is down, and on recovery rebuilds the channel, re-applies per-channel QoS, and re-runs Consume. Channel-level exceptions (queue deleted, 406 conflicts) trigger a topology replay rather than a reconnect. Topology is registered once (RegisterTopology) and replayed automatically on every new connection. SSEHub is an in-process pub/sub for real-time notification push to connected clients. Notification workers consume from notification.like, notification.comment, notification.social queues. Note: notification domain is handler-only — routes in router.go, worker-side logic in worker/notificationworker.go.
Frontend (Vue 3 + TypeScript on rolldown-vite)
- Language: Chinese UI (matching README and documentation)
- State: Pinia stores in
frontend/src/stores/(auth, social, toast) - API layer:
frontend/src/api/— one module per domain (account, comment, feed, like, message, social, video).client.tswrapsfetchwith automatic JWT injection and 401 → token refresh → retry - Composables:
useLikeFollow,useVideoFeed,useVideoPlayerinfrontend/src/composables/ - Vite dev proxy:
/api→http://127.0.0.1:8080(strips/apiprefix)
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). Requiresauth.Configureat startup — see Configuration.apierror/— error classification → HTTP status codesdb/— GORM MySQL connection setupobservability/— pprof server registration
Database Entities (auto-migrated via GORM)
Account, Video, Like, Comment, Social, OutboxMsg, Tag, VideoTag, Message, Notification
Chunked Upload
Redis-based session tracking for 5MB chunks with per-chunk MD5 verification, breakpoint resume, and merge on completion. See backend/internal/video/chunk_handler.go.
Configuration
Config files in backend/configs/ (YAML). Loaded by backend/internal/config/loadconfig.go. CONFIG_PATH env var selects which config file to load (default: configs/config.yaml). Additional env vars override YAML values — see ApplyEnvOverrides() for the full list (SERVER_PORT, MYSQL_*, REDIS_*, RABBITMQ_*, JWT_SECRET, JWT_ACCESS_TOKEN_TTL). Copy .env.example to .env for secrets (includes MYSQL_ROOT_PASSWORD, MYSQL_DATABASE, REDIS_PASSWORD, RABBITMQ_USER, RABBITMQ_PASS, JWT_SECRET).
JWT config is required and fail-fast: JWT_SECRET must be at least 32 bytes — both binaries call auth.Configure(auth.Options{...}) right after config load and refuse to start if it is missing or too short (there is no random-key fallback). Access token lifetime comes from jwt.access_token_ttl (YAML, default 15m, overridable via JWT_ACCESS_TOKEN_TTL). Startup logs a key fingerprint — JWT secret loaded (fingerprint=..., access_ttl=...) — which must match between API and Worker. Never write the secret into the committed YAML files.
Config variants:
config.yaml— default, connects to localhost MySQL/Redis/RabbitMQconfig.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.5container —go vet ./...thengo test -race -count=1 ./... - Frontend:
node:24-alpinecontainer —npm cithennpm run build - Deploy: validates
/opt/vloop/.env,rsyncs the workspace to/opt/vloop, thendocker 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.jsonfor manual API testing
Observability
- Health check:
GET /healthz(always 200) andGET /readyz(503 when RabbitMQ is down; seeinternal/http/router_test.gofor the invariant) - pprof: API on
localhost:6060, Worker onlocalhost: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 viaGET /static/
Key Files
backend/internal/http/router.go— all route definitions and dependency wiringbackend/internal/middleware/rabbitmq/— connection manager (reconnect + topology replay +RunConsumer), exchange declarations, DLX, per-domain MQ publishersbackend/internal/feed/service.go— three-tier caching, hot/cold feed splitbackend/internal/worker/— all async workers and SSE hubbackend/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
- 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.
- Green — write the minimal production code that makes it pass. No speculative abstractions, no extra options "while I'm here".
- Refactor — clean up implementation and test names with the suite green, re-running after each step.
- 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.gobeside the code it covers, in the same package (package http,package rabbitmq, …) so unexported state and helpers are reachable. Use an external_testpackage only when the test should consume the public API. - Name tests
TestSubject_ExpectedBehavior, e.g.TestReadyz_MQEnabledButDisconnected_IsDistinguishable. Use table-driven cases witht.Runsubtests and aname stringfield when one behavior has several inputs. - Mark every helper with
t.Helper(). Shared fixtures live in_test.gofiles, never in production packages. - Keep the intent comment. Existing suites explain why an invariant exists (see the
/readyzcase inbackend/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 (
fakeConninbackend/internal/middleware/rabbitmq/rabbitmq_test.go). Keep them tiny: no network I/O, no timing assumptions. - Redis —
miniredis. - HTTP handlers —
httptestwithgin.SetMode(gin.TestMode),gin.CreateTestContext, or a router built viaSetRouterasbackend/internal/http/router_test.godoes. - 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:
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.Sleepas synchronization. Prefer channels, context deadlines, or an injected clock. Tests must pass under-raceand in any order. - Run
go test -race -count=1 ./...before every push.-count=1is required: cached results hide flakiness, and-racecatches the concurrency bugs this codebase is full of. - Do not shorten a documented timing guard to make the suite faster.
TestReadyz_MQEnabledButDisconnected_IsDistinguishabletakes ~5s on purpose — that wait is the assertion that the startupEnsureTopologytimeout 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.