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:

Who calls it

CallerRoleWhat it does
Players (any HTTP client)PLAYERRegister, log in, view profiles/matches/leaderboard, edit profile, submit an appeal when banned.
Human moderatorsMODERATORReview the moderation queue, flag/ban/clear/note players, decide appeals.
Telemetry simulator (“Project 2”)SERVICERecords finished matches; may flag players.
Judge agent (“Project 3”)SERVICEReads stats/history, posts moderation actions with a confidence score and evidence.
The API paths, JSON fields, enum values, HTTP status codes and error codes are a contract two other services depend on. The authoritative spec is 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

ConcernChoiceWhy / where it shows up
Language / frameworkJava 21, Spring Boot 4.1.2Virtual threads are enabled (spring.threads.virtual.enabled). Boot 4 means Jackson 3 (tools.jackson.*) and renamed starters.
DatabasePostgreSQL 17Source of truth. JPA/Hibernate 7, Flyway migrations, ddl-auto: validate.
Cache / rankingRedis 7 (Lettuce)One sorted set (leaderboard:global) gives O(log N) rank lookups.
SecuritySpring Security + OAuth2 Resource Server (Nimbus)Self-issued HS256 JWT access tokens; opaque rotating refresh tokens in Postgres.
API docsspringdoc 3.xSwagger UI at /swagger-ui.html; OpenApiConfig adds a bearer scheme.
MappingMapStruct 1.6.3 + LombokOnly PlayerMapper uses MapStruct; Lombok restricted to getters/setters/ctor/logging.
MetricsMicrometer + PrometheusCustom counters/timers/gauge (see Observability).
TestsJUnit 5, MockMvc, Testcontainers 2Real Postgres + Redis containers; JaCoCo enforces ≥ 85% line coverage.
Load testk6benchmark/rank-lookup.js.
ContainerDocker, Composearena/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).

auth
register / login / refresh, JWT + refresh-token logic, seeds moderator & service accounts
player
Player entity (profile + cumulative stats), profile endpoints, search, percentile computation
match
Record matches idempotently, update ratings/stats, match history
leaderboard
Redis ZSET reads, rank lookup (Redis vs DB), event-driven sync, startup rebuild, rating formula
moderation
Actions, state machine, guardrails, audit log entity, review queue
appeal
Submit & decide ban appeals
config
Typed properties, security, JWT, clock, OpenAPI
common
Error model & global handler, paging wrapper, current-user helper

Design principles you will see repeated

5. Life of a request

Example: a moderator bans a player — POST /api/v1/moderation/players/{id}/actions.

  1. Security filter chain (SecurityConfig): not a public route, so the Authorization: Bearer <jwt> header is required. JwtConfig.jwtDecoder verifies the HS256 signature, issuer, expiry, and that the typ claim is access. jwtAuthenticationConverter turns the roles claim into ROLE_MODERATOR. Failures go to ProblemAuthenticationEntryPoint (401) or ProblemAccessDeniedHandler (403).
  2. Controller (ModerationController.applyAction): @PreAuthorize("hasAnyRole('MODERATOR','SERVICE')"), @Valid validates the ModerationActionRequest record. CurrentUser.id(jwt) extracts the caller's UUID from the JWT subject.
  3. Service (ModerationService.applyAction, one DB transaction): loads actor and target, runs guardrails (source must match role; service BANs need confidence ≥ 0.80), asks AccountStateMachine.next() for the new status, updates the player, inserts an immutable ModerationAction row, publishes RemovedFromLeaderboard if now banned, bumps a metric.
  4. 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.
  5. Response: 201 with a ModerationActionResponse. Any ApiException thrown along the way is converted by GlobalExceptionHandler to a ProblemDetail JSON.

Code, by package — root & resources

FileWhat it does
ArenaApplication.javaSpring Boot entry point. Enables @EnableScheduling (for the percentile refresh job) and @ConfigurationPropertiesScan (to bind ArenaProperties).
resources/application.ymlAll 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.sqlCreates 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.sqlCreates 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

FileWhat it does
ArenaPropertiesA 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.
SecurityConfigThe 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.
JwtConfigBuilds 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.
ClockConfigExposes Clock.systemUTC() as a bean so every service injects time.
OpenApiConfigSwagger metadata + a global bearer-jwt security scheme (public controllers opt out via @SecurityRequirements).

common

FileWhat it does
error/ErrorCodeEnum 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/ApiExceptionThe 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/ProblemAuthenticationEntryPointFilter-level 401 writer (used when Spring Security rejects a request before it reaches MVC).
error/ProblemAccessDeniedHandlerFilter-level 403 writer.
web/CurrentUserHelper: 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

FileWhat it does
AuthControllerPublic endpoints under /api/v1/auth: register (201 + Location), login, refresh.
AuthServiceregister: 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).
TokenServiceBuilds 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 / RefreshTokenRepositoryEntity for the refresh_tokens table (token_hash, expires_at, revoked_at, replaced_by). The repository has findByTokenHash and a bulk revokeAllActiveForPlayer update.
AccountSeederAn 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

FileWhat it does
PlayerThe 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.
RoleEnum PLAYER, MODERATOR, SERVICE.
PlayerControllerGET /players/me, PATCH /players/me (PLAYER only), GET /players/{id}, GET /players (MODERATOR/SERVICE search by username prefix + status).
PlayerServiceProfile 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.
StatDistributionServiceAnti-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.
PlayerRepositoryCase-insensitive lookups, findAllByIdInForUpdate (pessimistic FOR UPDATE, ORDER BY id), prefix search, and countEligibleForLeaderboard.
PlayerMapperMapStruct interface producing PlayerSummaryResponse and PlayerDetailResponse.
dto/PlayerDetailResponse, PlayerSummaryResponse, PlayerStats, PlayerPercentiles, UpdateProfileRequest.

match

FileWhat it does
MatchControllerPOST /matches (SERVICE only; 201 when created, 200 when it is a replay), GET /matches/{id}, GET /players/{id}/matches (paged).
MatchServiceThe 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, MatchParticipantIdEntities for matches and match_participants (composite key (match_id, player_id) via the @Embeddable id).
GameModeEnum FFA, BATTLE_ROYALE.
MatchRepository / MatchParticipantRepositoryfindByExternalId; 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

FileWhat it does
LeaderboardControllerPublic: GET /leaderboard?offset&limit and GET /leaderboard/players/{id}?source=redis|db.
LeaderboardServicePage: 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.
LeaderboardEventsTwo 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.
LeaderboardRebuilderOn 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.
RatingCalculatorPure 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

FileWhat it does
ModerationControllerPOST /moderation/players/{id}/actions, GET /moderation/queue (MODERATOR), GET /moderation/players/{id}/history.
ModerationServiceapplyAction (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.
AccountStateMachinePure, dependency-free class listing which actions are legal from which statuses (see state machine). Throws INVALID_STATE_TRANSITION (409).
ModerationActionEntity 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.
ModerationQueueQueryHand-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.
ModerationActionRepositoryPaged history (fetch-joins the actor) and "latest BAN for a player" (used by appeals).
AccountStatus, ModerationActionType, ActionSourceEnums: 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

FileWhat it does
AppealControllerPOST /appeals (PLAYER), GET /appeals?status= (MODERATOR, default PENDING), POST /appeals/{id}/decision (MODERATOR).
AppealServicesubmitAppeal: 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, AppealDecisionEntity (ban_action_id is UNIQUE — one appeal per ban at the DB level too), status PENDING/UPHELD/OVERTURNED, request-side decision UPHOLD/OVERTURN.
AppealRepositoryexistsByBanActionId, 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)
TableHighlights
playersCHECK 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_tokenstoken_hash CHAR(64) UNIQUE (SHA-256 hex); revoked_at, replaced_by record rotation chain.
matchesexternal_id UNIQUE (idempotency key supplied by the caller); CHECK (ended_at > started_at).
match_participantsPK (match_id, player_id); CHECKs: headshots ≤ kills, shots_hit ≤ shots_fired, avg_reaction_ms > 0; stores rating_before/after.
moderation_actionsJSONB 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.)
appealsban_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.

ActionAllowed fromResulting status
FLAGACTIVE, REINSTATEDFLAGGED
BANACTIVE, FLAGGED, REINSTATEDBANNED
CLEARFLAGGEDACTIVE
NOTEanyunchanged (audit-only)
APPEAL_SUBMITTEDBANNEDAPPEALED
APPEAL_UPHELDAPPEALEDBANNED
APPEAL_OVERTURNEDAPPEALEDREINSTATED
ACTIVE—FLAG→FLAGGED—BAN→BANNED—appeal→APPEALED—overturn→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

POST /auth/register→BCrypt hash, Player(ACTIVE, 1000)→RatingChanged → Redis ZADD
POST /auth/login→access JWT (15 min) + refresh token (7 d, stored as SHA-256)
POST /auth/refresh→revoke old, issue new pair
Replay of an old refresh token→revoke ALL tokens (REQUIRES_NEW tx)→401 REFRESH_TOKEN_REUSED

B. Recording a match

  1. SERVICE account POSTs a result with a unique externalId and a participant list.
  2. Same externalId seen before? → return the stored match with 200 (safe retry). A concurrent race on the same id is also resolved to 200 for the loser.
  3. Lock all participant rows in sorted-UUID order (deadlock-free), check they exist and are eligible.
  4. For each participant: delta = RatingCalculator.delta(N, placement, maxDelta), update rating & cumulative stats, persist the participant row.
  5. Transaction commits → LeaderboardSync pushes each new rating to Redis.

C. Anti-cheat moderation loop

  1. Judge/telemetry service reads GET /players/{id} (stats + percentiles) and history.
  2. If unsure it posts FLAG or NOTE with requiresHumanReview=true. A BAN from a service must carry confidence ≥ 0.80.
  3. Moderators work GET /moderation/queue?humanReviewOnly=true, then CLEAR or BAN.
  4. Every step is permanently recorded in moderation_actions (who, source, from→to, reason, evidence, confidence).

D. Appeal

Banned player POST /appeals→status APPEALED→Moderator POST /appeals/{id}/decision→UPHOLD: BANNEDorOVERTURN: REINSTATED + back on leaderboard

E. Leaderboard consistency

All 18 endpoints (base path /api/v1)

#Method & pathWhoHandled bySuccess
1POST /auth/registerpublicAuthController → AuthService.register201
2POST /auth/loginpublicAuthService.login200
3POST /auth/refreshpublicAuthService.refresh200
4GET /players/meany authenticatedPlayerController → PlayerService.getMe200
5PATCH /players/mePLAYER (not banned/appealing)PlayerService.updateMe200
6GET /players/{id}any authenticatedPlayerService.getById200
7GET /playersMODERATOR SERVICEPlayerService.search200
8POST /matchesSERVICEMatchController → MatchService.recordMatch201 / 200 replay
9GET /matches/{id}any authenticatedMatchService.getMatch200
10GET /players/{id}/matchesany authenticatedMatchService.getPlayerMatches200
11GET /leaderboardpublicLeaderboardController → LeaderboardService.getLeaderboard200
12GET /leaderboard/players/{id}?source=redis|dbpublicLeaderboardService.getPlayerRank200
13POST /moderation/players/{id}/actionsMODERATOR SERVICEModerationController → ModerationService.applyAction201
14GET /moderation/queueMODERATORModerationService.getQueue → ModerationQueueQuery200
15GET /moderation/players/{id}/historyMODERATOR SERVICEModerationService.getHistory200
16POST /appealsPLAYER (status BANNED)AppealController → AppealService.submitAppeal201
17GET /appealsMODERATORAppealService.listAppeals200
18POST /appeals/{id}/decisionMODERATORAppealService.decideAppeal200

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

Tests (arena/src/test/java/dev/fairplay/arena)

FileKindCovers
support/AbstractIntegrationTestbase classStarts 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/TestDataFactoryhelperBuilds test fixtures: player(...), moderator(), service(...) accounts, bearer(player) (a ready-made Authorization header value) and match(...).
auth/AuthIntegrationTest, SecurityIntegrationTestintegrationRegister 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/TokenServiceTestunitAccess-token claims/header/expiry (driven by the injected clock); refresh token is 43-char base64url with a SHA-256 hex hash.
player/PlayerIntegrationTest, StatDistributionServiceTestintegration / 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/MatchIntegrationTestintegrationRecording 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, RatingCalculatorTestintegration / unitTop 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, AuditLogAppendOnlyTestintegration / unitAllowed/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/AppealIntegrationTestintegrationFull lifecycle: one appeal per ban, decide only once.
common/error/ErrorHandlingIntegrationTestintegrationProblemDetail 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

FilePurpose
arena/pom.xmlSpring 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/.dockerignoreBuild 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.yamlServices: postgres, redis (both with health checks), arena (build: ., env_file: .env, depends on healthy DB/Redis), and profile-gated prometheus + grafana.
arena/.env.exampleJWT_SECRET, MODERATOR_PASSWORD, TELEMETRY_SERVICE_PASSWORD, JUDGE_SERVICE_PASSWORD. Copy to .env.
arena/.github/workflows/ci.ymlOn 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.jsk6 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.sqlInserts 1 000 000 players with ratings 500–2499; you must substitute a real bcrypt hash for <BCRYPT_HASH>.
arena/ops/prometheus.ymlPrometheus scrape job for /actuator/prometheus.
arena/README.md, HELP.mdProject 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)

CheckResult
./mvnw verifyBUILD SUCCESS — 71 tests, 0 failures
Line coverage (JaCoCo)89.6% (1,047 of 1,169 lines); the build gate is 85%
docker compose up --buildImage builds; /actuator/health returns UP
Swagger / OpenAPIExactly 18 operations; 13 secured (18 minus 3 auth and 2 leaderboard public routes)
Smoke testRegister → login as moderator → FLAG → Redis and DB rank lookups agree
grep com.fasterxml.jackson.databind srcNo matches (Jackson 3 only)

Bugs found by running the full suite (now fixed)

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.

Sourcep50p95p99ThroughputFailed
db (COUNT(*)+1)15.62 s18.01 s29.39 s12.6 req/s2 of 1,127
redis (ZREVRANK)33.07 ms63.53 ms90.21 ms5,764 req/s0 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

VariableDefaultUsed for
JWT_SECRETrequired (≥ 32 chars)HS256 signing key
MODERATOR_PASSWORDrequiredPassword for seeded mod-admin
TELEMETRY_SERVICE_PASSWORDrequiredPassword for seeded telemetry-sim
JUDGE_SERVICE_PASSWORDrequiredPassword for seeded judge-agent
DB_URL / DB_USER / DB_PASSWORDjdbc:postgresql://localhost:5432/arena / arena / arenaDatasource
REDIS_HOST / REDIS_PORTlocalhost / 6379Redis

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

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.