Arena, file by file
Every file in Project 1 (Project 1/arena): all 81 main source files, both migrations, all 15 test classes, and every build, delivery and documentation file. For each one: what it is, why it is shaped that way, and where the technology is explained. Use it as a map when you open the code, and as a checklist: an interviewer can point at any file, and you should be able to say one confident sentence about it.
Read it with the code open next to it. For each file, say the "what" out loud, then the "why". The Learn column links to the module that teaches the underlying idea. Paths are relative to src/main/java/dev/fairplay/arena/ unless shown otherwise. The project's own beginner tour is project1_explained.html.
1. The shape of the repository
arena/ one Spring Boot service, package-by-feature
├── pom.xml mvnw .mvn/ Maven build (Boot 4.1.2 parent), wrapper
├── Dockerfile compose.yaml .env.example .dockerignore
├── .github/workflows/ci.yml qodana_code_quality.yml qodana.yaml
├── ops/prometheus.yml benchmark/rank-lookup.js scripts/seed-1m-players.sql
├── README.md (local only: CLAUDE.md, handoff.md, todo.md, the spec, Code Explanation/)
└── src/
├── main/java/dev/fairplay/arena/
│ ├── ArenaApplication.java
│ ├── config/ 5 files security, JWT, clock, OpenAPI, typed properties
│ ├── common/ 7 files error model (ProblemDetail), paging, current user
│ ├── auth/ 10 files register, login, refresh rotation, seeding accounts
│ ├── player/ 12 files profiles, stats, percentiles, search
│ ├── match/ 13 files match recording (locking, idempotency), history
│ ├── leaderboard/ 9 files rating maths, Redis sync, rebuild, rank lookup
│ ├── moderation/ 12 files state machine, actions, queue, audit history
│ └── appeal/ 9 files submit and decide appeals
├── main/resources/ application.yml, db/migration/V1__init.sql, V2__audit_log_append_only.sql
└── test/java/dev/fairplay/arena/ 15 classes (2 support, 3 pure unit, 10 integration)
Each feature package follows the same layering: controller → service → repository, with request and response records in a dto/ subpackage. Two classes are deliberately pure (no Spring at all): AccountStateMachine and RatingCalculator. Section 17 explains why the design looks like this.
2. Application root and config/
| File | What it is | Why it is like this | Learn |
|---|---|---|---|
ArenaApplication.java | The entry point: @SpringBootApplication, @EnableScheduling, @ConfigurationPropertiesScan | Scheduling powers the 60-second percentile refresh; the scan registers the ArenaProperties record as a bean. Excluded from coverage (no logic). | 03 |
config/ArenaProperties.java | One validated record tree for every arena.* setting: JWT (secret ≥ 32 chars, issuer, TTLs), rating (initial 1000, max delta 30), leaderboard (key, rebuild flag, batch 10,000), stats (min matches 5, refresh 60 s), moderation (service-ban floor as BigDecimal 0.80), seeded accounts | Typed, validated at startup; a missing or short secret stops the app with the property's name. Nested records keep related settings together. | 03 |
config/SecurityConfig.java | The SecurityFilterChain: CSRF off, stateless sessions, public allow-list (auth POSTs, leaderboard GETs, health, Prometheus, Swagger), everything else authenticated; JWT resource server; ProblemDetail entry point and access-denied handler; BCryptPasswordEncoder bean; @EnableMethodSecurity | Deny by default; reuse Spring's resource-server JWT support instead of a hand-written filter. | 05 |
config/JwtConfig.java | Builds the HMAC SecretKey, a NimbusJwtEncoder, a NimbusJwtDecoder pinned to HS256 with issuer, expiry and a custom typ=access validator, and a converter that maps the roles claim to ROLE_ authorities | Pinning the algorithm and checking typ are defence in depth; the converter makes hasRole('SERVICE') work with your claim name. | 05 |
config/ClockConfig.java | A Clock bean returning Clock.systemUTC() | Every time-dependent class receives it, so tests can control time. | 02 |
config/OpenApiConfig.java | The springdoc OpenAPI bean: title, version and a bearer-jwt HTTP security scheme applied globally | Swagger UI shows a lock and accepts a token; public controllers clear it with @SecurityRequirements. | 04 |
3. common/: errors and web helpers
| File | What it is | Why it is like this | Learn |
|---|---|---|---|
common/error/ErrorCode.java | An enum of every business error code with its HTTP status and title (VALIDATION_FAILED 400, INVALID_CREDENTIALS 401, ACCOUNT_SUSPENDED 403, PLAYER_NOT_RANKED 404, INVALID_STATE_TRANSITION 409, CONFIDENCE_TOO_LOW 422, ...) and a typeUri() such as https://fairplay.dev/errors/confidence-too-low | One place maps meaning to status; the stable code is the client contract. | 04 |
common/error/ApiException.java | The single unchecked business exception, carrying an ErrorCode | Unchecked, so @Transactional rolls back and the advice converts it uniformly. | 02 |
common/error/GlobalExceptionHandler.java | @RestControllerAdvice extending ResponseEntityExceptionHandler: maps ApiException, access denied, constraint violations, optimistic-lock failures (409), data-integrity violations (username or email race → 409 by constraint name, otherwise 500), bad JSON, type mismatches, missing params, 404, 405 and a catch-all 500. buildProblem is shared with the security handlers | Every error has the same RFC 9457 shape with a code; stack traces never leak. | 04 |
common/error/ProblemAuthenticationEntryPoint.java | Writes a 401 ProblemDetail when authentication fails in the security filter chain | Filter-chain errors happen before MVC, so the advice can't see them. | 05 |
common/error/ProblemAccessDeniedHandler.java | The same for 403 (FORBIDDEN) raised in the filter chain | Same shape for every error. | 05 |
common/web/PageResponse.java | A generic record PageResponse<T>(content, page, size, totalElements, totalPages) with from(Page) | A stable JSON contract instead of serialising Spring's PageImpl. | 04 |
common/web/CurrentUser.java | CurrentUser.id(jwt): the caller's UUID from the token's sub | Identity always comes from the verified token, never from the request body or path. | 05 |
4. auth/: accounts and tokens
| File | What it is | Why it is like this | Learn |
|---|---|---|---|
auth/AuthController.java | POST /auth/register (201 + Location: /api/v1/players/{id}), /auth/login, /auth/refresh; each marked @SecurityRequirements (public) | Thin: validate the body, call the service. | 04 |
auth/AuthService.java | Register (case-insensitive uniqueness checks, bcrypt, initial rating, publishes RatingChanged so the player joins the leaderboard after commit), login (one generic error for unknown user or wrong password), refresh (expired first, then reuse → revoke all in REQUIRES_NEW, else rotate) | All token rules in one place; a TransactionTemplate with REQUIRES_NEW keeps the revocation when the request fails. Known gap: the token row isn't locked, so two concurrent refreshes can both succeed (module 16, section 2.1). | 05, 07 |
auth/TokenService.java | Issues the access JWT (iss, sub, iat, exp, username, roles, typ=access, HS256); generates refresh tokens (32 SecureRandom bytes, Base64url without padding = 43 chars); SHA-256 hex hashing (64 chars) | Pure token mechanics separated from business flow; the injected clock makes expiry testable. | 05 |
auth/RefreshToken.java | Entity for refresh_tokens: player (lazy), token_hash CHAR(64) unique, expires, created, revoked, replaced_by | Only the hash is stored; replaced_by records the rotation chain. | 07 |
auth/RefreshTokenRepository.java | findByTokenHash with join fetch t.player; @Modifying bulk revokeAllActiveForPlayer | The fetch join avoids a lazy load; the bulk update revokes in one statement. | 07 |
auth/AccountSeeder.java | An ApplicationRunner that creates the moderator and the telemetry-sim and judge-agent service accounts if missing, with bcrypt passwords from configuration | Machine accounts exist from first start; secrets come only from the environment. | 03 |
auth/dto/RegisterRequest.java | username 3–20 chars [a-zA-Z0-9_], email (@Email, ≤ 254), password 8–72, optional display name ≤ 40, country [A-Z]{2} | The 72 cap matches a real limit: bcrypt only uses the first 72 bytes of a password, so longer input would be truncated or rejected by the hasher. | 05 |
auth/dto/LoginRequest.java, RefreshRequest.java | @NotBlank username and password; @NotBlank refresh token | Validation before any work. | 04 |
auth/dto/TokenResponse.java | tokenType ("Bearer"), access token and expiry, refresh token and expiry | Expiry instants let clients refresh proactively. | 05 |
5. player/: profiles, stats and search
| File | What it is | Why it is like this | Learn |
|---|---|---|---|
player/Player.java | The main entity (players): identity, role, status, rating, lifetime totals, timestamps, @Version; isEligibleForMatchAndRanking() (PLAYER and not BANNED/APPEALED) | Running totals are a deliberate denormalisation; the version enables optimistic locking; eligibility lives on the entity, so every caller uses one rule. | 06, 07 |
player/Role.java | PLAYER, MODERATOR, SERVICE | Matches the JWT roles claim and the CHECK constraint. | 05 |
player/PlayerRepository.java | Case-insensitive lookups via lower() (matching the expression indexes), findAllByIdInForUpdate (PESSIMISTIC_WRITE, order by p.id), a paged searchPlayers (prefix with escape '!', optional status, ordered by rating then id), countEligibleForLeaderboard | Sorted locking prevents deadlocks; the escape clause makes LIKE safe. | 06 |
player/PlayerService.java | getMe (with email), getById (without email), updateMe (403 ACCOUNT_SUSPENDED when BANNED or APPEALED; changes only display name and country), search (lower-cases the prefix and escapes !, % and _), toDetail, and the static computeStats (K/D, headshot rate, accuracy rounded to 4 dp HALF_UP; average reaction) | Escaping stops a user's % acting as a wildcard. Note: average reaction is sum_reaction_ms / matches_played, an average of per-match averages (see module 16). | 04 |
player/PlayerController.java | GET /players/me, PATCH /players/me (PLAYER), GET /players/{id}, GET /players?q=&status= (MODERATOR or SERVICE) | "me" endpoints take the id from the token, which makes broken access control impossible. | 05 |
player/PlayerMapper.java | A MapStruct interface (componentModel = "spring"): entity to summary and to detail (with email, stats and percentiles as extra sources) | Compile-time generated mapping; PlayerMapperImpl is excluded from coverage. | 04 |
player/StatDistributionService.java | Every 60 s (and at startup), runs percentile_cont for headshot rate, accuracy and reaction time over eligible players with ≥ 5 matches; keeps 101 cut points per metric in an AtomicReference; a binary search gives a player's percentile; reaction is inverted (100 − p) so faster = higher | The expensive aggregate runs once per minute instead of per request; returns Optional because an empty table yields NULL (the startup-crash bug). | 06, 02 |
player/dto/PlayerDetailResponse.java | Profile, role, status, rating, matches, optional email, created and status-changed times, stats, percentiles | NON_NULL hides email and percentiles when absent. | 04 |
player/dto/PlayerSummaryResponse.java | The list view: id, username, display name, country, role, status, rating, matches | No email in lists. | – |
player/dto/PlayerStats.java | kills, deaths, kdRatio, headshotRate, accuracy, avgReactionMs (nullable) | Derived from totals on read. | – |
player/dto/PlayerPercentiles.java | headshotRate, accuracy and reactionSpeed percentiles (0–100) | Null until the player has 5 matches and a distribution exists. The Judge's get_stat_percentiles tool reads these. | 11 |
player/dto/UpdateProfileRequest.java | Optional display name ≤ 40 and country [A-Z]{2} | Only the fields a player may change (no mass assignment). | 04 |
6. match/: recording matches
| File | What it is | Why it is like this | Learn |
|---|---|---|---|
match/Match.java | Entity for matches: external_id unique, mode, map, start and end, recordedBy (lazy), created | The unique external id is the idempotency key. | 04 |
match/MatchParticipant.java | Entity for the join table with @EmbeddedId + @MapsId for match and player, plus per-match stats and rating before and after | The many-to-many carries data, so it's a real entity, keyed like the SQL table. | 07 |
match/MatchParticipantId.java | @Embeddable composite key (matchId, playerId) with hand-written equals/hashCode | JPA requires value-based equality for composite ids. | 02 |
match/GameMode.java | FFA, BATTLE_ROYALE | Matches the CHECK constraint. | – |
match/MatchRepository.java | findByExternalId | Replay detection. | – |
match/MatchParticipantRepository.java | Participants of a match with join fetch ordered by placement; a player's history as a JPQL constructor projection into PlayerMatchResponse (with a participant-count subquery) and a cheap custom countQuery | No N+1; paging without loading entities. | 07 |
match/MatchService.java | recordMatch: a TransactionTemplate around validate → replay check → sort ids → lock rows → 404/422 checks → insert match (flush) → per-participant rating delta and totals on managed entities → insert participants → publish RatingChanged → a counter; catches a unique-violation race after rollback and returns the winner (200). Also getMatch and getPlayerMatches | The heart of Arena's correctness: no lost updates, no deadlocks, exactly-once effects from at-least-once callers. | 06, 07 |
match/MatchController.java | POST /matches (SERVICE; 201 + Location, or 200 on replay), GET /matches/{id}, GET /players/{id}/matches (paged) | The status code tells the client which case happened. | 04 |
match/dto/RecordMatchRequest.java | externalId ≤ 64, mode, map ≤ 40, times, 2–100 participants (@Valid cascades) | Field rules here; cross-field rules in the service. | 04 |
match/dto/ParticipantRequest.java | playerId, placement ≥ 1, non-negative counts, avg reaction ≥ 1 | Exactly the shape Telemetry's MatchSummary produces (a contract). | 01 |
match/dto/MatchResponse.java, ParticipantResponse.java | The match with its participants sorted by placement, each with rating before and after | Clients see the rating effect directly. | – |
match/dto/PlayerMatchResponse.java | One row of a player's history: match info, placement, participant count, stats, rating change | Built directly by the JPQL projection. | 07 |
7. leaderboard/: ratings and Redis
| File | What it is | Why it is like this | Learn |
|---|---|---|---|
leaderboard/RatingCalculator.java | A pure utility: delta = round(maxDelta × (n + 1 − 2·placement) / (n − 1)), so first place gets +30, last −30, linear in between; applyDelta floors at 0 | No Spring, so it's tested directly. A simple placement-based system, not Elo (see module 16). | 02 |
leaderboard/LeaderboardEvents.java | Records RatingChanged(playerId, rating) and RemovedFromLeaderboard(playerId) | Domain events decouple writers (match, auth, moderation, appeal) from Redis. | 03 |
leaderboard/LeaderboardSync.java | @TransactionalEventListener(AFTER_COMMIT) handlers: ZADD on rating change, ZREM on removal; failures caught, logged and counted | Redis never sees uncommitted data; Redis problems never fail requests. | 08 |
leaderboard/LeaderboardRebuilder.java | On ApplicationReadyEvent: if ZCARD ≠ the eligible count, stream eligible players by keyset batches of 10,000, pipelined ZADDs into leaderboard:global:rebuild, then RENAME | Repairs Redis from the truth with an atomic swap. Only compares counts (module 08). | 08 |
leaderboard/LeaderboardService.java | Paged board (ZREVRANGE WITH SCORES, then one findAllById for names); rank by source=redis (ZREVRANK + ZSCORE + ZCARD) or source=db (COUNT(*) + 1 with the COLLATE "C" tie-break); timers tagged by source; a size gauge | Keeps the database path for the benchmark; the timers produced the server-side numbers. | 08, 14 |
leaderboard/LeaderboardController.java | Public GET /leaderboard?offset&limit (default 50, max 100) and GET /leaderboard/players/{id}?source= | Public reads; the source switch exists for benchmarking. | 04 |
leaderboard/dto/LeaderboardPage.java, LeaderboardEntry.java, PlayerRankResponse.java | The page (total, offset, limit, entries); an entry (rank, id, username, display name, rating); a rank answer (rating, 1-based rank, total ranked, source) | The response states which source answered. | – |
8. moderation/: rules, actions, audit
| File | What it is | Why it is like this | Learn |
|---|---|---|---|
moderation/AccountStatus.java | ACTIVE, FLAGGED, BANNED, APPEALED, REINSTATED | The states of the state machine. | – |
moderation/ModerationActionType.java | FLAG, BAN, CLEAR, NOTE, APPEAL_SUBMITTED, APPEAL_UPHELD, APPEAL_OVERTURNED | The transitions; the last three are only reachable through the appeal endpoints. | – |
moderation/ActionSource.java | HUMAN, TELEMETRY, JUDGE, SYSTEM | Who acted, recorded in the audit row and enforced per role. | 05 |
moderation/AccountStateMachine.java | A pure class: an EnumMap of allowed source states per action and a target state; next(current, action) returns the new status (NOTE keeps it) or throws INVALID_STATE_TRANSITION | Every status change goes through one tested contract (all 35 pairs). | 02, 13 |
moderation/ModerationAction.java | The append-only audit entity: target, action, from and to status, actor, source, reason, evidence as JSONB (@ColumnTransformer(write = "?::jsonb")), confidence NUMERIC(4,3), review flag, time | The transformer casts the JSON string to JSONB on insert; every change is a new row. | 06 |
moderation/ModerationActionRepository.java | Paged history with join fetch m.actor (newest first) and a count query; the latest BAN for a player (used by appeals) | No N+1 when listing actor names. | 07 |
moderation/ModerationService.java | applyAction: only FLAG/BAN/CLEAR/NOTE here; guardrails (MODERATOR ⇒ HUMAN; SERVICE ⇒ TELEMETRY or JUDGE, and BAN needs confidence ≥ 0.80); target must be a PLAYER; state machine; write the audit row; on a new ban publish RemovedFromLeaderboard; a counter tagged by action and source. Also queue and history | Business-rule authorisation lives here, independent of the Judge. | 05 |
moderation/ModerationQueueQuery.java | SQL via JdbcClient: flagged players, each with their latest action through JOIN LATERAL ... LIMIT 1, optionally only those needing human review, oldest first, plus a count query | A read model that is awkward in JPQL and natural in SQL. | 06 |
moderation/ModerationController.java | POST /moderation/players/{id}/actions (MODERATOR, SERVICE; 201), GET /moderation/queue (MODERATOR), GET /moderation/players/{id}/history (MODERATOR, SERVICE) | The Judge uses the first and third. | 04 |
moderation/dto/ModerationActionRequest.java | action, source, reason ≤ 500, up to 20 evidence strings (each ≤ 500, non-blank), confidence 0..1, optional review flag | Container-element constraints (List<@NotBlank @Size(max = 500) String>) validate every item. | 04 |
moderation/dto/ModerationActionResponse.java | The stored action, with the actor's username and the parsed evidence list | Exactly what the Judge's history tool summarises. | – |
moderation/dto/QueueItemResponse.java | A flagged player plus a nested LatestAction record | Nested records model the joined row. | – |
9. appeal/: the second chance
| File | What it is | Why it is like this | Learn |
|---|---|---|---|
appeal/Appeal.java | Entity: player, the ban action it contests (unique), status, statement, decider, note, times, @Version | One appeal per ban (a UNIQUE column); the version stops two moderators deciding at once. | 07 |
appeal/AppealStatus.java, AppealDecision.java | PENDING / UPHELD / OVERTURNED; UPHOLD / OVERTURN | The request says the decision; the status records the outcome. | – |
appeal/AppealRepository.java | existsByBanActionId; findByIdWithDetails (fetch player, left-fetch decider); paged by status, oldest first | Duplicate check plus fetch joins. | 07 |
appeal/AppealService.java | Submit: only BANNED; find the latest BAN; reject a duplicate; state machine BANNED → APPEALED; audit row by the player (source HUMAN). Decide: only PENDING; UPHOLD → back to BANNED, OVERTURN → REINSTATED and RatingChanged (back on the leaderboard); audit row by the moderator; counters | Every status change, even from appeals, goes through the same state machine and audit table. | 06 |
appeal/AppealController.java | POST /appeals (PLAYER, 201), GET /appeals?status=PENDING (MODERATOR), POST /appeals/{id}/decision (MODERATOR) | The player id comes from the token. | 04 |
appeal/dto/SubmitAppealRequest.java | Statement 20–2000 chars | Forces a real explanation. | – |
appeal/dto/DecideAppealRequest.java | Decision + a note 1–1000 chars | The note becomes the audit reason. | – |
appeal/dto/AppealResponse.java | The appeal with player, username, ban action, status, statement and decision fields | NON_NULL hides decision fields while pending. | – |
10. Resources: configuration and schema
| File | What it contains | Learn |
|---|---|---|
src/main/resources/application.yml | Virtual threads on; datasource from DB_URL, DB_USER, DB_PASSWORD with local defaults; Hikari pool 20; open-in-view: false; ddl-auto: validate; UTC JDBC time zone; Redis host and port; ProblemDetail on; no stack traces; ECS JSON logs; Actuator exposure (health, info, metrics, prometheus) with probes; percentile histograms for HTTP and rank lookups; springdoc paths; every arena.* setting with secrets only from environment variables | 03 |
db/migration/V1__init.sql | Six tables (players, refresh_tokens, matches, match_participants, moderation_actions, appeals), CHECK and UNIQUE constraints, foreign keys, the expression and composite indexes | 06 |
db/migration/V2__audit_log_append_only.sql | The PL/pgSQL function and the BEFORE UPDATE OR DELETE trigger on moderation_actions | 06 |
11. Tests: what each class proves
| Test class | Type | What it proves (from its test names) |
|---|---|---|
support/AbstractIntegrationTest | Base | Starts PostgreSQL 17 and Redis 7 once per JVM with @ServiceConnection; MockMvc; test properties (secret, account usernames and passwords, rebuild off); truncates all tables and flushes Redis before each test |
support/TestDataFactory | Helper | Creates players (any status and rating), moderators and service accounts directly in the database, mints bearer tokens for them, and records matches |
moderation/AccountStateMachineTest | Unit | All 35 (status, action) pairs: legal ones give the right target, illegal ones throw INVALID_STATE_TRANSITION |
leaderboard/RatingCalculatorTest | Unit | Rating deltas, flooring at zero, rejection of invalid participant counts and placements |
player/StatDistributionServiceTest | Unit | Null percentiles below 5 matches or before a distribution exists; percentile lookups at cut-point edges; reaction speed inverted |
auth/TokenServiceTest | Unit | Access-token claims, header and expiry from the fixed clock (the clock-bug fix); 43-character Base64url refresh tokens and 64-character SHA-256 hex hashes |
auth/AuthIntegrationTest | Integration | Registration joins the leaderboard; duplicate username or email rejected case-insensitively; validation errors for a bad email; login, rotation and reuse detection; an expired token is plain invalid and doesn't trigger mass revocation |
auth/SecurityIntegrationTest | Integration | Missing or expired tokens give 401, wrong roles 403; the OpenAPI document lists exactly 18 operations |
common/error/ErrorHandlingIntegrationTest | Integration | ProblemDetail with code for unknown routes, malformed JSON and missing resources |
player/PlayerIntegrationTest | Integration | "me" includes email while other players' profiles don't; PATCH works; a banned player can't PATCH; percentiles appear after five matches; moderators search by prefix and status |
match/MatchIntegrationTest | Integration | Recording updates ratings, totals and Redis and is idempotent (201 then 200); match rules and eligibility validated; concurrent requests with the same externalId create one match and replay the other |
leaderboard/LeaderboardIntegrationTest | Integration | The top page reflects a ban and an overturn; Redis rank equals database rank for 200 players with forced rating ties, and again after a rebuild |
moderation/ModerationIntegrationTest | Integration | Allowed transitions applied, invalid ones rejected, guardrails enforced (source per role, confidence floor); two parallel bans (started together with CountDownLatches) give exactly one success and one conflict, the loser failing with an optimistic-lock or state-machine error |
moderation/AuditLogAppendOnlyTest | Integration | Raw SQL UPDATE and DELETE on moderation_actions fail with "append-only" |
appeal/AppealIntegrationTest | Integration | The appeal lifecycle: one appeal per ban, decided only once |
Maven counts 71 tests (each parameterised case counts separately), at 89.6% line coverage in the last full run. A small test-clock fix landed after that run.
12. Build, delivery and documentation files
| File | What it is | Learn |
|---|---|---|
pom.xml | Boot 4.1.2 parent; starters (webmvc, security, OAuth2 resource server, data-jpa, data-redis, flyway, validation, actuator); springdoc 3.2.0; MapStruct 1.6.3; runtime PostgreSQL driver and Prometheus registry; optional Lombok; test starters and Testcontainers; compiler with ordered annotation processors; JaCoCo 0.8.13 with the 85% line gate, excluding the application class and generated mappers | 14 |
mvnw, mvnw.cmd, .mvn/wrapper/ | The Maven Wrapper: a pinned Maven version, no installation needed | 14 |
Dockerfile | Multi-stage: JDK build with a cached dependency layer, JRE runtime, non-root user, MaxRAMPercentage=75 | 14 |
compose.yaml | PostgreSQL 17 (named volume, pg_isready), Redis 7 (redis-cli ping), Arena (waits for both healthy), Prometheus and Grafana behind the observability profile | 14 |
.env.example | The four secrets with placeholder values: JWT_SECRET, MODERATOR_PASSWORD, TELEMETRY_SERVICE_PASSWORD, JUDGE_SERVICE_PASSWORD | 05 |
.dockerignore | Keeps .env, .git, .idea, target and the benchmark ids out of the build context | 14 |
.gitignore | Ignores build output, IDE files, .env, HELP.md and benchmark/player-ids.json. The local notes are excluded through .git/info/exclude instead, so the pushed .gitignore doesn't reveal them | – |
.gitattributes | Line endings by file type: LF for mvnw, CRLF for *.cmd, so each wrapper script runs on its own OS whichever machine checked it out | – |
.github/workflows/ci.yml | On push and PR: Temurin 21, Maven cache, ./mvnw -B verify, upload the JaCoCo report always | 14 |
.github/workflows/qodana_code_quality.yml, qodana.yaml | JetBrains Qodana static analysis (the qodana.starter profile, JVM community linter) on pushes to main and pull requests; needs a QODANA_TOKEN secret | 14 |
ops/prometheus.yml | Scrapes arena:8080/actuator/prometheus every 5 s | 14 |
benchmark/rank-lookup.js | The k6 script: warm-up (50 VUs, 15 s), measure (200 VUs, 60 s), a p95 sanity threshold, SOURCE=db|redis | 14 |
scripts/seed-1m-players.sql | Inserts 1,000,000 players with generate_series, random ratings 500–2499 and a pre-computed bcrypt hash placeholder, then ANALYZE | 06 |
README.md | Public overview: architecture, quick start, the 18-endpoint table, design decisions, the benchmark with method and environment, what's next | 01 |
Fairplay Arena — Implementation Specification.md | The 1,441-line design document the code was built from: overview and goals, rules, stack and Boot 4 pitfalls, structure, configuration, schema, state machine, security, the 18 endpoints, errors, leaderboard, observability, testing, Docker and CI, benchmark, build order (local only) | 17 |
CLAUDE.md, handoff.md, todo.md | Local working notes for the AI coding assistant and for you: conventions, current state, decisions, what's left (git-excluded) | 16 |
Code Explanation/ | Your two existing HTML walkthroughs of this project (local only) | Start |
13. Code-level probe questions
Questions an interviewer asks with your code on the screen. Each one tests whether you know a specific file.
Why does RegisterRequest limit passwords to 72 characters? Deep
bcrypt only uses the first 72 bytes of its input. Depending on the library version, longer input is either silently truncated (so two passwords differing only after byte 72 would match) or rejected with an exception at hashing time. Capping input at 72 makes the limitation an explicit validation rule with a clean 400, instead of a surprise. (Multi-byte UTF-8 characters can still exceed 72 bytes within 72 characters, so a stricter version would check byte length.)
What does PlayerService.search do to the query string, and why? Intermediate
It lower-cases the prefix and escapes !, % and _ with !, and the JPQL uses like concat(:prefix, '%') escape '!'. Without escaping, a user typing % or _ would inject LIKE wildcards: not SQL injection (it's still a bind parameter), but a way to change the query's meaning and force expensive scans.
How does a player get back onto the leaderboard after a successful appeal? Intermediate
AppealService.decideAppeal with OVERTURN moves APPEALED → REINSTATED through the state machine, writes an APPEAL_OVERTURNED audit row, and publishes RatingChanged with the player's rating. After commit, LeaderboardSync ZADDs them back. LeaderboardIntegrationTest checks the ban and the overturn both show up on the top page.
Two moderators ban the same player at the same instant. What happens? Deep
Exactly one succeeds. Both transactions read ACTIVE and try to update the same row: the second either fails the optimistic version check (ObjectOptimisticLockingFailureException, mapped to 409 CONCURRENT_MODIFICATION) or, if it reads after the first commits, sees BANNED and the state machine rejects BAN from BANNED (409 INVALID_STATE_TRANSITION). ModerationIntegrationTest.parallelBansGiveExactlyOneSuccessAndOneConflict starts both threads together with latches and accepts either failure type.
How is evidence stored, and why the @ColumnTransformer? Deep
Evidence is a JSON array serialised by Jackson into a String field mapped to a jsonb column. PostgreSQL won't implicitly cast a text bind parameter to jsonb, so @ColumnTransformer(write = "?::jsonb") makes Hibernate write ?::jsonb in the INSERT. Reads come back as text and are parsed with a TypeReference<List<String>>.
Why is getById different from getMe? Basic
Both return the same PlayerDetailResponse, but getMe passes includeEmail = true and getById passes false, so a player's email is only visible to themselves. @JsonInclude(NON_NULL) drops the null field entirely. PlayerIntegrationTest checks it.
What's the rating formula, and what's wrong with it as a real rating system? Intermediate
delta = round(30 × (n + 1 − 2·placement) / (n − 1)): first place +30, last −30, linear between, floored at 0. It ignores opponents' strength, so beating ten beginners earns the same as beating ten pros, and ratings don't converge to skill the way Elo or Glicko/TrueSkill do. It was a deliberate simplification (the spec's choice) because the project is about consistency and moderation, not ranking theory. Module 16 discusses it.
Where does @SecurityRequirements come in? Basic
OpenApiConfig applies the bearer-JWT requirement to every operation. Public endpoints (auth, leaderboard) clear it with an empty @SecurityRequirements, so Swagger UI only shows a lock on secured routes. It affects documentation only; real access rules are in SecurityConfig.
Which test would fail if someone removed the trigger migration? Basic
AuditLogAppendOnlyTest.databaseRejectsUpdateAndDeleteOnModerationActions: it saves an action and then expects raw SQL UPDATE and DELETE to fail with "moderation_actions is append-only".
Why does the refresh token come out as exactly 43 characters? Curveball
32 random bytes is 256 bits. Base64 encodes every 3 bytes as 4 characters: 32 bytes is 10 full groups (40 characters) plus 2 leftover bytes (3 more characters), so 43, without the = padding (withoutPadding()). The URL-safe alphabet avoids + and /. The SHA-256 hash is 32 bytes, so 64 hex characters, hence CHAR(64). TokenServiceTest asserts both lengths.