1. What is this project?
Fairplay Arena is a stateless REST backend (Java 21 / Spring Boot 4.1) that acts as the source of truth for an anti-cheat platform for a competitive shooter game. It has no UI. It stores:
- Player accounts (with cumulative combat stats: kills, deaths, headshots, accuracy, reaction time).
- Match results posted by game/telemetry services; each match changes player ratings.
- A global leaderboard in a Redis sorted set (fast rank lookups), backed by PostgreSQL.
- Moderation actions (
FLAG,BAN,CLEAR,NOTE) written to an append-only audit log that the database itself protects. - Ban appeals that players submit and moderators decide.
Who calls it
| Caller | Role | What it does |
|---|---|---|
| Players (any HTTP client) | PLAYER | Register, log in, view profiles/matches/leaderboard, edit profile, submit an appeal when banned. |
| Human moderators | MODERATOR | Review the moderation queue, flag/ban/clear/note players, decide appeals. |
| Telemetry simulator (“Project 2”) | SERVICE | Records finished matches; may flag players. |
| Judge agent (“Project 3”) | SERVICE | Reads stats/history, posts moderation actions with a confidence score and evidence. |
Fairplay Arena — Implementation Specification.md in the repo root — read it before changing behaviour.2. Repository map
Project 1/
├── CLAUDE.md Guidance for Claude Code (commands, architecture summary)
├── Fairplay Arena — Implementation Specification.md The authoritative spec (~1100 lines)
├── Code Explanation/code guide.html ← this file
├── arena/ ★ THE REAL PROJECT (Maven, Spring Boot)
│ ├── pom.xml Dependencies, MapStruct/Lombok processors, JaCoCo 85% gate
│ ├── Dockerfile Multi-stage build (temurin 21 JDK → JRE), non-root user
│ ├── .dockerignore Keeps .env, target/ and .git out of the build context
│ ├── compose.yaml Postgres 17 + Redis 7 + Arena (+ Prometheus/Grafana profile)
│ ├── .env.example JWT secret + 3 account passwords
│ ├── mvnw / mvnw.cmd / .mvn/ Maven wrapper
│ ├── .github/workflows/ci.yml CI: ./mvnw verify, uploads JaCoCo report
│ ├── benchmark/rank-lookup.js k6 load test (DB vs Redis rank lookup)
│ ├── scripts/seed-1m-players.sql Seeds 1,000,000 players for the benchmark
│ ├── ops/prometheus.yml Prometheus scrape config
│ ├── src/main/java/dev/fairplay/arena/ Application code (see §Code, by package)
│ ├── src/main/resources/ application.yml + Flyway migrations
│ ├── src/test/java/... Integration + unit tests
│ └── target/ Build output (generated; ignore)
└── (root: index.html, package.json, vite.config.ts, src/App.tsx, public/ ...)
An empty Google AI Studio React/Vite scaffold, unrelated to Arena
3. Tech stack
| Concern | Choice | Why / where it shows up |
|---|---|---|
| Language / framework | Java 21, Spring Boot 4.1.2 | Virtual threads are enabled (spring.threads.virtual.enabled). Boot 4 means Jackson 3 (tools.jackson.*) and renamed starters. |
| Database | PostgreSQL 17 | Source of truth. JPA/Hibernate 7, Flyway migrations, ddl-auto: validate. |
| Cache / ranking | Redis 7 (Lettuce) | One sorted set (leaderboard:global) gives O(log N) rank lookups. |
| Security | Spring Security + OAuth2 Resource Server (Nimbus) | Self-issued HS256 JWT access tokens; opaque rotating refresh tokens in Postgres. |
| API docs | springdoc 3.x | Swagger UI at /swagger-ui.html; OpenApiConfig adds a bearer scheme. |
| Mapping | MapStruct 1.6.3 + Lombok | Only PlayerMapper uses MapStruct; Lombok restricted to getters/setters/ctor/logging. |
| Metrics | Micrometer + Prometheus | Custom counters/timers/gauge (see Observability). |
| Tests | JUnit 5, MockMvc, Testcontainers 2 | Real Postgres + Redis containers; JaCoCo enforces ≥ 85% line coverage. |
| Load test | k6 | benchmark/rank-lookup.js. |
| Container | Docker, Compose | arena/Dockerfile (temurin 21 JDK build → JRE runtime) and arena/compose.yaml. |
4. Architecture at a glance
Players / Moderators / Telemetry sim / Judge agent
│ HTTP + Bearer JWT
▼
┌──────────────────────────────────────────────────────┐
│ Spring Security filter chain (SecurityConfig) │ stateless, JWT → roles
├──────────────────────────────────────────────────────┤
│ Controllers (@PreAuthorize role checks, @Valid) │ thin HTTP layer
├──────────────────────────────────────────────────────┤
│ Services (@Transactional, business rules) │ state machine, guardrails,
│ │ rating math, idempotency
├───────────────┬────────────────────────┬─────────────┤
│ Repositories │ ApplicationEvents │ JdbcClient │
│ (Spring Data) │ RatingChanged / │ raw SQL │
│ │ RemovedFromLeaderboard│ (queue, │
│ │ │ │ percentiles│
│ │ ▼ AFTER_COMMIT│ rank, ...) │
│ │ LeaderboardSync │ │
└──────┬────────┴──────────┬─────────────┴──────┬──────┘
▼ ▼ │
PostgreSQL 17 Redis 7 (ZSET) │
(truth + audit log) (rank/leaderboard) ◄─────┘ LeaderboardRebuilder on startup
Package-by-feature layout
Under arena/src/main/java/dev/fairplay/arena/ every business area has its own package with the same internal shape: Controller → Service → Repository (+ Entity, enums, dto/ records).
register / login / refresh, JWT + refresh-token logic, seeds moderator & service accounts
Player entity (profile + cumulative stats), profile endpoints, search, percentile computation
Record matches idempotently, update ratings/stats, match history
Redis ZSET reads, rank lookup (Redis vs DB), event-driven sync, startup rebuild, rating formula
Actions, state machine, guardrails, audit log entity, review queue
Submit & decide ban appeals
Typed properties, security, JWT, clock, OpenAPI
Error model & global handler, paging wrapper, current-user helper
Design principles you will see repeated
- Constructor injection only; services have
private finalcollaborators. - All DTOs are Java
records. Entities are never returned from controllers. - Time comes from an injected
Clock(Instant.now(clock)), neverInstant.now(), so tests can control time. - IDs are UUIDs generated in Java; timestamps are UTC
Instants. - Every non-2xx is an RFC 9457
ProblemDetailwith a stable machine-readablecode. - Postgres is the truth; Redis is a derived index that is updated only after commit and can always be rebuilt.
5. Life of a request
Example: a moderator bans a player — POST /api/v1/moderation/players/{id}/actions.
- Security filter chain (
SecurityConfig): not a public route, so theAuthorization: Bearer <jwt>header is required.JwtConfig.jwtDecoderverifies the HS256 signature, issuer, expiry, and that thetypclaim isaccess.jwtAuthenticationConverterturns therolesclaim intoROLE_MODERATOR. Failures go toProblemAuthenticationEntryPoint(401) orProblemAccessDeniedHandler(403). - Controller (
ModerationController.applyAction):@PreAuthorize("hasAnyRole('MODERATOR','SERVICE')"),@Validvalidates theModerationActionRequestrecord.CurrentUser.id(jwt)extracts the caller's UUID from the JWT subject. - Service (
ModerationService.applyAction, one DB transaction): loads actor and target, runs guardrails (source must match role; serviceBANs need confidence ≥ 0.80), asksAccountStateMachine.next()for the new status, updates the player, inserts an immutableModerationActionrow, publishesRemovedFromLeaderboardif now banned, bumps a metric. - Commit → Spring fires
LeaderboardSync(AFTER_COMMIT) which removes the player from the Redis ZSET. If the transaction had rolled back, Redis would never be touched. - Response:
201with aModerationActionResponse. AnyApiExceptionthrown along the way is converted byGlobalExceptionHandlerto aProblemDetailJSON.
Code, by package — root & resources
| File | What it does |
|---|---|
ArenaApplication.java | Spring Boot entry point. Enables @EnableScheduling (for the percentile refresh job) and @ConfigurationPropertiesScan (to bind ArenaProperties). |
resources/application.yml | All runtime configuration: datasource (Hikari pool 20), JPA (open-in-view: false, ddl-auto: validate), Redis, ECS-structured JSON logging, actuator exposure, springdoc paths, and the whole arena.* block (JWT, rating, leaderboard, stats, moderation, accounts). Secrets come from env vars. |
resources/db/migration/V1__init.sql | Creates the 6 tables: players, refresh_tokens, matches, match_participants, moderation_actions, appeals, with CHECK constraints, case-insensitive unique indexes and query indexes. See Database schema. |
resources/db/migration/V2__audit_log_append_only.sql | Creates a PL/pgSQL trigger function that RAISE EXCEPTIONs on any UPDATE/DELETE against moderation_actions. This is the database-level guarantee of the audit log. |
config
| File | What it does |
|---|---|
ArenaProperties | A validated @ConfigurationProperties("arena") record tree mirroring the arena: block of application.yml: Jwt (secret ≥ 32 chars, issuer, TTLs), Rating (initial, maxDelta), Leaderboard (Redis key, rebuild flags), Stats, Moderation (min service-ban confidence), Accounts (moderator + service credentials). The app refuses to start if invalid. |
SecurityConfig | The single SecurityFilterChain: CSRF off, stateless sessions, public routes (POST /api/v1/auth/**, GET /api/v1/leaderboard/**, health/prometheus/swagger), everything else authenticated; JWT resource-server; custom 401/403 handlers. Also defines the BCryptPasswordEncoder bean. @EnableMethodSecurity turns on @PreAuthorize in controllers. |
JwtConfig | Builds the HMAC key from arena.jwt.secret; provides JwtEncoder (signing), JwtDecoder (verifying, with issuer check and a custom validator that rejects any token whose typ is not access), and a JwtAuthenticationConverter mapping the roles claim to ROLE_* authorities. |
ClockConfig | Exposes Clock.systemUTC() as a bean so every service injects time. |
OpenApiConfig | Swagger metadata + a global bearer-jwt security scheme (public controllers opt out via @SecurityRequirements). |
common
| File | What it does |
|---|---|
error/ErrorCode | Enum of every stable error code, each carrying its HTTP status + title (e.g. USERNAME_TAKEN 409, CONFIDENCE_TOO_LOW 422, REFRESH_TOKEN_REUSED 401). Also builds the type URI https://fairplay.dev/errors/<kebab-code>. |
error/ApiException | The one unchecked exception services throw: new ApiException(ErrorCode.X, "detail"). |
error/GlobalExceptionHandler | @RestControllerAdvice converting everything to application/problem+json: ApiException, validation errors (with a per-field errors array), malformed JSON, type mismatches, missing params, 404/405, optimistic-lock failures (→ CONCURRENT_MODIFICATION), unique-constraint violations (→ USERNAME_TAKEN/EMAIL_TAKEN), and a catch-all 500 that never leaks stack traces. |
error/ProblemAuthenticationEntryPoint | Filter-level 401 writer (used when Spring Security rejects a request before it reaches MVC). |
error/ProblemAccessDeniedHandler | Filter-level 403 writer. |
web/CurrentUser | Helper: CurrentUser.id(jwt) → the caller's UUID (JWT sub). |
web/PageResponse<T> | Uniform paged JSON: content, page, size, totalElements, totalPages; from(Page) converts a Spring Data page. |
auth
| File | What it does |
|---|---|
AuthController | Public endpoints under /api/v1/auth: register (201 + Location), login, refresh. |
AuthService | register: checks username/email uniqueness (case-insensitive), BCrypt-hashes the password, creates a PLAYER with ACTIVE status and the initial rating (1000), publishes RatingChanged so the new player lands on the Redis leaderboard. login: verifies credentials (same error for unknown user and wrong password), issues an access JWT + refresh token. refresh: looks up the SHA-256 hash of the presented token; unknown or expired → 401 INVALID_REFRESH_TOKEN (checked first, per spec §8); already revoked → reuse detected: revokes all of that player's active refresh tokens in a separate REQUIRES_NEW transaction (so it survives the exception rollback) and returns 401 REFRESH_TOKEN_REUSED; otherwise rotates (revoke old, link replaced_by, create new). |
TokenService | Builds access JWTs (claims: iss, sub=playerId, iat, exp, username, roles, typ=access, HS256), generates 32-byte SecureRandom refresh tokens (base64url), and hashes them with SHA-256 for storage. Raw refresh tokens are never persisted. |
RefreshToken / RefreshTokenRepository | Entity for the refresh_tokens table (token_hash, expires_at, revoked_at, replaced_by). The repository has findByTokenHash and a bulk revokeAllActiveForPlayer update. |
AccountSeeder | An ApplicationRunner that, on every startup, creates the moderator (mod-admin) and service accounts (telemetry-sim, judge-agent) from arena.accounts.* if they do not yet exist (email <username>@fairplay.local, rating 0). |
dto/ | RegisterRequest, LoginRequest, RefreshRequest, TokenResponse (tokenType, accessToken, accessTokenExpiresAt, refreshToken, refreshTokenExpiresAt). |
player
| File | What it does |
|---|---|
Player | The central JPA entity (table players). Holds identity, role, moderation status, rating, and cumulative counters (matchesPlayed, totalKills/Deaths/Headshots/ShotsFired/ShotsHit, sumReactionMs) from which all stats are derived. Has an @Version column for optimistic locking. isEligibleForMatchAndRanking() = role PLAYER and status not BANNED/APPEALED. |
Role | Enum PLAYER, MODERATOR, SERVICE. |
PlayerController | GET /players/me, PATCH /players/me (PLAYER only), GET /players/{id}, GET /players (MODERATOR/SERVICE search by username prefix + status). |
PlayerService | Profile read/update (banned or appealing accounts get ACCOUNT_SUSPENDED), search (escapes % _ ! for safe LIKE), and computeStats() which derives kdRatio, headshotRate, accuracy, avgReactionMs from the raw counters (rounded to 4 dp). toDetail() attaches percentiles for real players and hides the email unless it is the caller's own profile. |
StatDistributionService | Anti-cheat building block: periodically (arena.stats.refresh-interval, default 60 s, plus once at startup) runs Postgres percentile_cont over all eligible players to compute 101 cut points for headshot rate, accuracy and reaction time, cached in an AtomicReference. percentilesFor() binary-searches a player's value into a 0–100 percentile (reaction is inverted so higher = faster). Returns null until the player has ≥ 5 matches. If no player is eligible yet (for example an empty database at first startup) percentile_cont returns NULL and the distribution stays unset; the query helper returns an Optional because JdbcClient rejects a null extractor result. An unusually high percentile is a signal for the Judge agent. |
PlayerRepository | Case-insensitive lookups, findAllByIdInForUpdate (pessimistic FOR UPDATE, ORDER BY id), prefix search, and countEligibleForLeaderboard. |
PlayerMapper | MapStruct interface producing PlayerSummaryResponse and PlayerDetailResponse. |
dto/ | PlayerDetailResponse, PlayerSummaryResponse, PlayerStats, PlayerPercentiles, UpdateProfileRequest. |
match
| File | What it does |
|---|---|
MatchController | POST /matches (SERVICE only; 201 when created, 200 when it is a replay), GET /matches/{id}, GET /players/{id}/matches (paged). |
MatchService | The most intricate service. recordMatch drives its transaction with a TransactionTemplate so that if two concurrent requests race on the same externalId, the loser's unique-constraint violation is caught after rollback and answered with the winner's match (200) instead of a 500. Inside the transaction it validates the payload (endedAt > startedAt, no duplicate players, placements form exactly 1..N, headshots ≤ kills, shotsHit ≤ shotsFired) → idempotency check by externalId (returns the existing match, created=false) → sorts participant IDs and locks the players with SELECT ... FOR UPDATE ORDER BY id (consistent lock order prevents deadlocks between concurrent matches) → rejects unknown or ineligible (banned/appealing) players → saves the match → for each participant computes the rating delta, applies it, accumulates stats, stores a MatchParticipant row with ratingBefore/After, and publishes RatingChanged. |
Match, MatchParticipant, MatchParticipantId | Entities for matches and match_participants (composite key (match_id, player_id) via the @Embeddable id). |
GameMode | Enum FFA, BATTLE_ROYALE. |
MatchRepository / MatchParticipantRepository | findByExternalId; fetch-joined participants ordered by placement; a constructor-expression JPQL query that projects a player's match history straight into PlayerMatchResponse (including participant count). |
dto/ | RecordMatchRequest (2–100 participants), ParticipantRequest, MatchResponse, ParticipantResponse, PlayerMatchResponse. |
leaderboard
| File | What it does |
|---|---|
LeaderboardController | Public: GET /leaderboard?offset&limit and GET /leaderboard/players/{id}?source=redis|db. |
LeaderboardService | Page: ZREVRANGE WITHSCORES on Redis, then one batched Postgres lookup for usernames. Rank: two interchangeable implementations — Redis (ZREVRANK, O(log N)) and DB (COUNT(*)+1 of players with a higher rating, ties broken by id::text COLLATE "C" to match Redis's lexicographic member ordering). The DB path exists so the benchmark can compare them. Each is timed with a Micrometer Timer; a gauge reports leaderboard size. |
LeaderboardEvents | Two event records: RatingChanged(playerId, rating) and RemovedFromLeaderboard(playerId). |
LeaderboardSync | @TransactionalEventListener(AFTER_COMMIT) handlers: ZADD on rating change, ZREM on removal. Failures are logged and counted (arena.leaderboard.sync.failures) but never break the user's request. |
LeaderboardRebuilder | On ApplicationReadyEvent (if rebuild-on-startup), compares Redis ZCARD with the DB's eligible-player count; if they differ it streams eligible players in keyset-paginated batches (id > lastId, batch 10 000) into a temp ZSET using Redis pipelining, then atomically RENAMEs it over the live key — readers never see a half-built board. |
RatingCalculator | Pure static math: delta = round(maxDelta × (N + 1 − 2·placement) / (N − 1)). First place gets +maxDelta, last gets −maxDelta, symmetric between. applyDelta floors the rating at 0. |
dto/ | LeaderboardPage, LeaderboardEntry, PlayerRankResponse. |
Who is on the leaderboard? Players with role PLAYER and status ACTIVE, FLAGGED or REINSTATED. Banning removes you; an overturned appeal puts you back.
moderation
| File | What it does |
|---|---|
ModerationController | POST /moderation/players/{id}/actions, GET /moderation/queue (MODERATOR), GET /moderation/players/{id}/history. |
ModerationService | applyAction (only FLAG, BAN, CLEAR, NOTE via this endpoint): guardrails (moderators must use source HUMAN; service accounts must use TELEMETRY or JUDGE; a service BAN needs confidence ≥ 0.80 or it is rejected with CONFIDENCE_REQUIRED / CONFIDENCE_TOO_LOW) → target must be a PLAYER → state machine decides the new status → writes an audit row (evidence list serialised to JSONB) → publishes leaderboard removal on a new ban → metric + log. |
AccountStateMachine | Pure, dependency-free class listing which actions are legal from which statuses (see state machine). Throws INVALID_STATE_TRANSITION (409). |
ModerationAction | Entity for the append-only moderation_actions table: player, action, from_status/to_status, actor, source, reason, evidence (JSONB string), confidence, requires_human_review, created_at. |
ModerationQueueQuery | Hand-written SQL (JdbcClient) for the review queue: currently-FLAGGED players joined (JOIN LATERAL) to their latest action, optionally only those with requires_human_review, oldest first. |
ModerationActionRepository | Paged history (fetch-joins the actor) and "latest BAN for a player" (used by appeals). |
AccountStatus, ModerationActionType, ActionSource | Enums: statuses ACTIVE, FLAGGED, BANNED, APPEALED, REINSTATED; actions FLAG, BAN, CLEAR, NOTE, APPEAL_SUBMITTED, APPEAL_UPHELD, APPEAL_OVERTURNED; sources HUMAN, TELEMETRY, JUDGE, SYSTEM. |
dto/ | ModerationActionRequest (action, source, reason, up to 20 evidence strings, confidence 0–1, requiresHumanReview), ModerationActionResponse, QueueItemResponse. |
appeal
| File | What it does |
|---|---|
AppealController | POST /appeals (PLAYER), GET /appeals?status= (MODERATOR, default PENDING), POST /appeals/{id}/decision (MODERATOR). |
AppealService | submitAppeal: caller must be BANNED; finds their latest BAN action; one appeal per ban (APPEAL_ALREADY_EXISTS); creates the Appeal, moves the player to APPEALED and writes an APPEAL_SUBMITTED audit row. decideAppeal: appeal must be PENDING; UPHOLD → back to BANNED; OVERTURN → REINSTATED and a RatingChanged event puts the player back on the leaderboard. Both go through AccountStateMachine and write audit rows. |
Appeal, AppealStatus, AppealDecision | Entity (ban_action_id is UNIQUE — one appeal per ban at the DB level too), status PENDING/UPHELD/OVERTURNED, request-side decision UPHOLD/OVERTURN. |
AppealRepository | existsByBanActionId, fetch-joined lookups, status-filtered paging oldest-first. |
dto/ | SubmitAppealRequest (statement ≤ 2000 chars), DecideAppealRequest, AppealResponse. |
Database schema (Flyway V1 + V2)
players ──┬──< refresh_tokens (player_id)
├──< match_participants (player_id) >── matches (recorded_by → players)
├──< moderation_actions (player_id; actor_id → players) ← append-only trigger
└──< appeals (player_id; decided_by → players; ban_action_id UNIQUE → moderation_actions)
| Table | Highlights |
|---|---|
| players | CHECK constraints on role and status; rating ≥ 0; unique lower(username) and lower(email) indexes; ix_players_rating (rating DESC, id) for ordering; version for optimistic locking. Stores raw cumulative counters, not derived ratios. |
| refresh_tokens | token_hash CHAR(64) UNIQUE (SHA-256 hex); revoked_at, replaced_by record rotation chain. |
| matches | external_id UNIQUE (idempotency key supplied by the caller); CHECK (ended_at > started_at). |
| match_participants | PK (match_id, player_id); CHECKs: headshots ≤ kills, shots_hit ≤ shots_fired, avg_reaction_ms > 0; stores rating_before/after. |
| moderation_actions | JSONB evidence, NUMERIC(4,3) confidence in [0,1]; V2 trigger forbids UPDATE and DELETE, so even a buggy deploy cannot rewrite history. (Tests that truncate use TRUNCATE, which row triggers do not fire on.) |
| appeals | ban_action_id UNIQUE; statement ≤ 2000, decision note ≤ 1000. |
Account state machine
AccountStateMachine.next(currentStatus, action) is the only place that decides whether a status change is legal.
| Action | Allowed from | Resulting status |
|---|---|---|
FLAG | ACTIVE, REINSTATED | FLAGGED |
BAN | ACTIVE, FLAGGED, REINSTATED | BANNED |
CLEAR | FLAGGED | ACTIVE |
NOTE | any | unchanged (audit-only) |
APPEAL_SUBMITTED | BANNED | APPEALED |
APPEAL_UPHELD | APPEALED | BANNED |
APPEAL_OVERTURNED | APPEALED | REINSTATED |
FLAGGED —CLEAR→ ACTIVE; APPEALED —uphold→ BANNED; REINSTATED can be FLAGged or BANned again. The three appeal actions can only be produced by the appeals endpoints, never directly by /moderation/.../actions.
35 = 7 actions × 5 statuses — the unit test AccountStateMachineTest exhaustively verifies every pair.
Key flows
A. Authentication & token rotation
B. Recording a match
- SERVICE account POSTs a result with a unique
externalIdand a participant list. - Same
externalIdseen before? → return the stored match with200(safe retry). A concurrent race on the same id is also resolved to200for the loser. - Lock all participant rows in sorted-UUID order (deadlock-free), check they exist and are eligible.
- For each participant:
delta = RatingCalculator.delta(N, placement, maxDelta), update rating & cumulative stats, persist the participant row. - Transaction commits →
LeaderboardSyncpushes each new rating to Redis.
C. Anti-cheat moderation loop
- Judge/telemetry service reads
GET /players/{id}(stats + percentiles) and history. - If unsure it posts
FLAGorNOTEwithrequiresHumanReview=true. ABANfrom a service must carry confidence ≥ 0.80. - Moderators work
GET /moderation/queue?humanReviewOnly=true, thenCLEARorBAN. - Every step is permanently recorded in
moderation_actions(who, source, from→to, reason, evidence, confidence).
D. Appeal
E. Leaderboard consistency
- Write path: Postgres commit first → Redis updated by an after-commit listener. If Redis is down, the request still succeeds; a failure metric increments.
- Repair path: on startup
LeaderboardRebuilderdetects count drift and rebuilds into a temp key thenRENAMEs atomically. (It compares counts only — it does not detect wrong scores with the same cardinality.) - Tie-breaking: equal ratings are ordered by
idtext (byte order) in both Redis and the DB query, so both sources return identical ranks.
All 18 endpoints (base path /api/v1)
| # | Method & path | Who | Handled by | Success |
|---|---|---|---|---|
| 1 | POST /auth/register | public | AuthController → AuthService.register | 201 |
| 2 | POST /auth/login | public | AuthService.login | 200 |
| 3 | POST /auth/refresh | public | AuthService.refresh | 200 |
| 4 | GET /players/me | any authenticated | PlayerController → PlayerService.getMe | 200 |
| 5 | PATCH /players/me | PLAYER (not banned/appealing) | PlayerService.updateMe | 200 |
| 6 | GET /players/{id} | any authenticated | PlayerService.getById | 200 |
| 7 | GET /players | MODERATOR SERVICE | PlayerService.search | 200 |
| 8 | POST /matches | SERVICE | MatchController → MatchService.recordMatch | 201 / 200 replay |
| 9 | GET /matches/{id} | any authenticated | MatchService.getMatch | 200 |
| 10 | GET /players/{id}/matches | any authenticated | MatchService.getPlayerMatches | 200 |
| 11 | GET /leaderboard | public | LeaderboardController → LeaderboardService.getLeaderboard | 200 |
| 12 | GET /leaderboard/players/{id}?source=redis|db | public | LeaderboardService.getPlayerRank | 200 |
| 13 | POST /moderation/players/{id}/actions | MODERATOR SERVICE | ModerationController → ModerationService.applyAction | 201 |
| 14 | GET /moderation/queue | MODERATOR | ModerationService.getQueue → ModerationQueueQuery | 200 |
| 15 | GET /moderation/players/{id}/history | MODERATOR SERVICE | ModerationService.getHistory | 200 |
| 16 | POST /appeals | PLAYER (status BANNED) | AppealController → AppealService.submitAppeal | 201 |
| 17 | GET /appeals | MODERATOR | AppealService.listAppeals | 200 |
| 18 | POST /appeals/{id}/decision | MODERATOR | AppealService.decideAppeal | 200 |
Paged endpoints use page (0-based) and size (1–100, default 20); the leaderboard uses offset/limit (default 50, max 100).
Error handling
Every failure is application/problem+json:
{
"type": "https://fairplay.dev/errors/confidence-too-low",
"title": "Confidence too low",
"status": 422,
"detail": "Service BAN confidence must be at least 0.80",
"instance": "/api/v1/moderation/players/7c1e.../actions",
"code": "CONFIDENCE_TOO_LOW"
}
Validation failures add an errors: [{field, message}] array. Clients should switch on code, not on detail. Families: 400 validation/malformed; 401 auth & token problems; 403 role or suspended account; 404 not found / not ranked; 409 conflicts (duplicate, illegal transition, concurrent edit, appeal states); 422 semantic rule violations (wrong source, confidence, ineligible player, non-player target); 500 generic (never a stack trace).
Observability
- Logs: structured ECS JSON to the console (
logging.structured.format.console: ecs). - Endpoints:
/actuator/health(with liveness/readiness probes),/actuator/metrics,/actuator/prometheus. - Custom metrics:
arena.matches.recorded,arena.moderation.actions{action,source},arena.appeals.decided{decision},arena.leaderboard.rank.lookup{source=redis|db}(timer with histogram),arena.leaderboard.size(gauge),arena.leaderboard.sync.failures. - Dashboards:
docker compose --profile observability upadds Prometheus (scrapesarena:8080every 5 s perops/prometheus.yml) and Grafana on :3000.
Tests (arena/src/test/java/dev/fairplay/arena)
| File | Kind | Covers |
|---|---|---|
support/AbstractIntegrationTest | base class | Starts Postgres 17 + Redis 7 via Testcontainers (shared static containers), sets test secrets, enables MockMvc, and TRUNCATEs all tables + FLUSHALLs Redis before each test. Add new tables to its TRUNCATE list. Its arena.accounts.services[n] test properties must include username as well as password, because a list set by a higher-priority source replaces the whole application.yml list. |
support/TestDataFactory | helper | Builds test fixtures: player(...), moderator(), service(...) accounts, bearer(player) (a ready-made Authorization header value) and match(...). |
auth/AuthIntegrationTest, SecurityIntegrationTest | integration | Register joins the leaderboard; duplicate username/email rejected case-insensitively; login rotates refresh tokens and detects reuse; an expired refresh token is INVALID_REFRESH_TOKEN (not reuse) and does not revoke other sessions; missing/expired tokens and role enforcement; the OpenAPI spec documents exactly 18 operations. |
auth/TokenServiceTest | unit | Access-token claims/header/expiry (driven by the injected clock); refresh token is 43-char base64url with a SHA-256 hex hash. |
player/PlayerIntegrationTest, StatDistributionServiceTest | integration / unit | /me shows email but other players' profiles omit it; banned players cannot PATCH; percentiles appear after 5 matches; moderator prefix/status search. Unit test: null percentiles when under the minimum or distribution not ready, cut-point edges, inverted reaction speed. |
match/MatchIntegrationTest | integration | Recording updates ratings, totals and Redis and is idempotent; validation rules and player eligibility; two concurrent requests with the same externalId produce exactly one match and one replay. |
leaderboard/LeaderboardIntegrationTest, RatingCalculatorTest | integration / unit | Top page reflects ban and overturn; Redis rank equals DB rank for 200 players with forced rating ties, also after a rebuild. Unit test: exact deltas from the spec, floor at 0, invalid inputs rejected. |
moderation/ModerationIntegrationTest, AccountStateMachineTest, AuditLogAppendOnlyTest | integration / unit | Allowed/invalid transitions and guardrails, plus a race test (parallel bans produce exactly one success and one conflict); all 35 transition pairs; DB trigger blocks UPDATE/DELETE. |
appeal/AppealIntegrationTest | integration | Full lifecycle: one appeal per ban, decide only once. |
common/error/ErrorHandlingIntegrationTest | integration | ProblemDetail with a code for unknown route, malformed JSON and missing resources. |
The JaCoCo check goal in ./mvnw verify fails the build below 85% line coverage (measured: 89.6%, 71 tests, all passing) (excluding ArenaApplication and generated *MapperImpl). Docker must be running for the integration tests.
Build, CI & ops files
| File | Purpose |
|---|---|
arena/pom.xml | Spring Boot parent 4.1.2; starters (webmvc, data-jpa, data-redis, flyway, security, oauth2-resource-server, validation, actuator); springdoc 3.2.0; MapStruct; Lombok; Prometheus registry; Testcontainers. The compiler plugin's annotationProcessorPaths order (lombok → lombok-mapstruct-binding → mapstruct-processor) matters. JaCoCo prepare/report/check. |
arena/Dockerfile, arena/.dockerignore | Build stage: eclipse-temurin:21-jdk + ./mvnw package -DskipTests; runtime stage: eclipse-temurin:21-jre, non-root arena user (uid 1001), -XX:MaxRAMPercentage=75. .dockerignore keeps .env out of the build context. |
arena/compose.yaml | Services: postgres, redis (both with health checks), arena (build: ., env_file: .env, depends on healthy DB/Redis), and profile-gated prometheus + grafana. |
arena/.env.example | JWT_SECRET, MODERATOR_PASSWORD, TELEMETRY_SERVICE_PASSWORD, JUDGE_SERVICE_PASSWORD. Copy to .env. |
arena/.github/workflows/ci.yml | On push/PR: Temurin 21, ./mvnw -B verify, uploads the JaCoCo report artifact. (GitHub only reads this if arena/ is the repository root.) |
arena/benchmark/rank-lookup.js | k6 script: 15 s warm-up at 50 VUs then 60 s at 200 VUs, random IDs from player-ids.json, ?source=db|redis. Results (3 runs each, 1M players, 200 VUs) are in the README: Redis p95 63.5 ms vs DB p95 18 s. |
arena/scripts/seed-1m-players.sql | Inserts 1 000 000 players with ratings 500–2499; you must substitute a real bcrypt hash for <BCRYPT_HASH>. |
arena/ops/prometheus.yml | Prometheus scrape job for /actuator/prometheus. |
arena/README.md, HELP.md | Project README (architecture, endpoint table, design decisions, benchmark method); HELP.md is Spring Initializr boilerplate. |
Running, verification & benchmark
Commands (run from arena/)
./mvnw verify # build + 71 tests + JaCoCo gate (needs Docker for Testcontainers)
./mvnw test -Dtest=AccountStateMachineTest # one test class
./mvnw test -Dtest=MatchIntegrationTest#methodName # one test method
cp .env.example .env # then edit the secrets
docker compose up --build # Arena + Postgres + Redis (http://localhost:8080)
docker compose --profile observability up --build # + Prometheus :9090, Grafana :3000
docker compose down -v # stop and delete the database volume
Useful URLs: /swagger-ui.html, /actuator/health, /actuator/prometheus. Moderator login for local testing: mod-admin with the MODERATOR_PASSWORD from your .env.
Verification status (last run, 2026-11-17)
| Check | Result |
|---|---|
./mvnw verify | BUILD SUCCESS — 71 tests, 0 failures |
| Line coverage (JaCoCo) | 89.6% (1,047 of 1,169 lines); the build gate is 85% |
docker compose up --build | Image builds; /actuator/health returns UP |
| Swagger / OpenAPI | Exactly 18 operations; 13 secured (18 minus 3 auth and 2 leaderboard public routes) |
| Smoke test | Register → login as moderator → FLAG → Redis and DB rank lookups agree |
grep com.fasterxml.jackson.databind src | No matches (Jackson 3 only) |
Bugs found by running the full suite (now fixed)
- Startup crash on an empty database:
StatDistributionServicereturnednullfrom aJdbcClientresult extractor when no players existed, which Spring rejects. It now returns anOptional, so the percentile cache simply stays empty until there is data. - No integration test could load its context: test properties set only
arena.accounts.services[n].password, so Boot replaced the wholeapplication.ymllist andusernamebecame null.AbstractIntegrationTestnow sets usernames too. - Refresh-token order now follows spec §8 (expired →
INVALID_REFRESH_TOKENbefore the reuse check). - Concurrent duplicate
externalIdreturns the winner's match (200) instead of a 500; seeMatchService.recordMatch.
Benchmark: rank lookup, PostgreSQL vs Redis
1,000,000 seeded players (about 500 tied per rating), k6 with 200 virtual users for 60 s after a 15 s warm-up. Three runs per source; the last run is reported. k6 and Arena shared one Docker Desktop VM (12 vCPU, 8 GB) on a Ryzen 5 3600 with 15.9 GB RAM.
| Source | p50 | p95 | p99 | Throughput | Failed |
|---|---|---|---|---|---|
db (COUNT(*)+1) | 15.62 s | 18.01 s | 29.39 s | 12.6 req/s | 2 of 1,127 |
redis (ZREVRANK) | 33.07 ms | 63.53 ms | 90.21 ms | 5,764 req/s | 0 of 432,474 |
Redis was about 280× faster at p95. The server-side Prometheus timer reports a mean of 1.54 s for db and 2.9 ms for redis. It is much lower than the k6 figure for db because the timer starts after the transaction has its connection, so it excludes the wait for one of the 20 Hikari connections that 200 virtual users compete for. The Redis rebuild of 1,000,001 members took 22.6 s at startup.
To repeat it without installing k6 or htpasswd, run them from Docker (grafana/k6, httpd:2.4-alpine) on the compose network; see arena/README.md for the full method.
Configuration & environment variables
| Variable | Default | Used for |
|---|---|---|
JWT_SECRET | required (≥ 32 chars) | HS256 signing key |
MODERATOR_PASSWORD | required | Password for seeded mod-admin |
TELEMETRY_SERVICE_PASSWORD | required | Password for seeded telemetry-sim |
JUDGE_SERVICE_PASSWORD | required | Password for seeded judge-agent |
DB_URL / DB_USER / DB_PASSWORD | jdbc:postgresql://localhost:5432/arena / arena / arena | Datasource |
REDIS_HOST / REDIS_PORT | localhost / 6379 | Redis |
Tunables in application.yml under arena.*: access-token TTL 15 m, refresh TTL 7 d, initial rating 1000, max rating delta 30, leaderboard key leaderboard:global, rebuild batch 10 000, min 5 matches for percentiles, percentile refresh 60 s, service-ban min confidence 0.80.
The root React stub (not part of Arena)
The repo root contains index.html, package.json, vite.config.ts, tsconfig.json, metadata.json, .env.example (GEMINI_API_KEY, APP_URL), public/assets/aistudio/ and src/{App.tsx,main.tsx,index.css}. This is an unmodified Google AI Studio React + Vite + Tailwind template; App renders an empty <div>. It never talks to Arena (the spec lists a frontend as a non-goal). Scripts: npm run dev (port 3000), npm run build, npm run lint (tsc --noEmit). Safe to ignore unless you decide to build a UI.
Gotchas & open items
- Port clash: Grafana is mapped to host port 3000, the same port the root Vite dev server uses.
- Prometheus endpoint is unauthenticated (intentional for local scraping; restrict in production).
- Redis sync is best-effort: after-commit listener, in-memory. A crash between commit and ZADD leaves Redis stale until the next restart rebuild (which only compares counts). The README's "what I'd do next" proposes a transactional outbox.
- The DB rank path is very slow under load (p95 18 s at 200 VUs with a 20-connection pool, by design a benchmark baseline). The server-side timer excludes connection-pool wait, so it understates user-visible latency.
- Authorization vs validation order:
@Validrequest bodies are validated before@PreAuthorize, so a caller without the role but with an invalid body gets 400, not 403. - Not implemented by design: rate limiting, Kafka, social login, email verification, password reset, admin UI.
- Adding a table? Add a Flyway migration and add it to the
TRUNCATEinAbstractIntegrationTest. Entities must match the schema exactly becauseddl-autoisvalidate. - Boot 4 imports differ from Boot 3: Jackson 3 (
tools.jackson.*),@MockitoBean,org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc, Testcontainers 2 package names. If an import fails, the class likely moved — do not downgrade Boot. - Tagged counters appear lazily:
arena_moderation_actionsandarena_appeals_decidedshow up on/actuator/prometheusonly after their first use (Micrometer creates tagged meters on first increment). - Not a git repository / CI location:
arena/.github/workflows/ci.ymlonly runs ifarena/is the repo root; otherwise move it to the root and addworking-directory: arena. The README's CI badge URL is still a placeholder. - Leftovers to decide on: the unrelated root React/Vite stub and
arena/HELP.md(seetodo.md). - Local files:
arena/.env(git-ignored, placeholder secrets) is needed bydocker compose;benchmark/player-ids.jsonis a generated, git-ignored artifact. - Non-obvious choices (for example the
TransactionTemplateinMatchService, theOptionalinStatDistributionService, and clearing the bearer requirement on public endpoints) have a short comment explaining why.
Written from a read-through of the source and updated after the full build, compose and benchmark runs on 2026-11-17. If code and this guide disagree, the code wins — and the implementation spec wins over both for the API contract.