Fairplay Interview Prep
Module 19 · Codebase atlas

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.

P1 Arena· reference; about 1.5 hours to read once, then use as a lookup
How to use the atlas

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/

FileWhat it isWhy it is like thisLearn
ArenaApplication.javaThe entry point: @SpringBootApplication, @EnableScheduling, @ConfigurationPropertiesScanScheduling powers the 60-second percentile refresh; the scan registers the ArenaProperties record as a bean. Excluded from coverage (no logic).03
config/ArenaProperties.javaOne 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 accountsTyped, 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.javaThe 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; @EnableMethodSecurityDeny by default; reuse Spring's resource-server JWT support instead of a hand-written filter.05
config/JwtConfig.javaBuilds 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_ authoritiesPinning the algorithm and checking typ are defence in depth; the converter makes hasRole('SERVICE') work with your claim name.05
config/ClockConfig.javaA Clock bean returning Clock.systemUTC()Every time-dependent class receives it, so tests can control time.02
config/OpenApiConfig.javaThe springdoc OpenAPI bean: title, version and a bearer-jwt HTTP security scheme applied globallySwagger UI shows a lock and accepts a token; public controllers clear it with @SecurityRequirements.04

3. common/: errors and web helpers

FileWhat it isWhy it is like thisLearn
common/error/ErrorCode.javaAn 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-lowOne place maps meaning to status; the stable code is the client contract.04
common/error/ApiException.javaThe single unchecked business exception, carrying an ErrorCodeUnchecked, 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 handlersEvery error has the same RFC 9457 shape with a code; stack traces never leak.04
common/error/ProblemAuthenticationEntryPoint.javaWrites a 401 ProblemDetail when authentication fails in the security filter chainFilter-chain errors happen before MVC, so the advice can't see them.05
common/error/ProblemAccessDeniedHandler.javaThe same for 403 (FORBIDDEN) raised in the filter chainSame shape for every error.05
common/web/PageResponse.javaA 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.javaCurrentUser.id(jwt): the caller's UUID from the token's subIdentity always comes from the verified token, never from the request body or path.05

4. auth/: accounts and tokens

FileWhat it isWhy it is like thisLearn
auth/AuthController.javaPOST /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.javaRegister (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.javaIssues 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.javaEntity for refresh_tokens: player (lazy), token_hash CHAR(64) unique, expires, created, revoked, replaced_byOnly the hash is stored; replaced_by records the rotation chain.07
auth/RefreshTokenRepository.javafindByTokenHash with join fetch t.player; @Modifying bulk revokeAllActiveForPlayerThe fetch join avoids a lazy load; the bulk update revokes in one statement.07
auth/AccountSeeder.javaAn ApplicationRunner that creates the moderator and the telemetry-sim and judge-agent service accounts if missing, with bcrypt passwords from configurationMachine accounts exist from first start; secrets come only from the environment.03
auth/dto/RegisterRequest.javausername 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 tokenValidation before any work.04
auth/dto/TokenResponse.javatokenType ("Bearer"), access token and expiry, refresh token and expiryExpiry instants let clients refresh proactively.05

5. player/: profiles, stats and search

FileWhat it isWhy it is like thisLearn
player/Player.javaThe 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.javaPLAYER, MODERATOR, SERVICEMatches the JWT roles claim and the CHECK constraint.05
player/PlayerRepository.javaCase-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), countEligibleForLeaderboardSorted locking prevents deadlocks; the escape clause makes LIKE safe.06
player/PlayerService.javagetMe (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.javaGET /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.javaA 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.javaEvery 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 = higherThe 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.javaProfile, role, status, rating, matches, optional email, created and status-changed times, stats, percentilesNON_NULL hides email and percentiles when absent.04
player/dto/PlayerSummaryResponse.javaThe list view: id, username, display name, country, role, status, rating, matchesNo email in lists.–
player/dto/PlayerStats.javakills, deaths, kdRatio, headshotRate, accuracy, avgReactionMs (nullable)Derived from totals on read.–
player/dto/PlayerPercentiles.javaheadshotRate, 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.javaOptional display name ≤ 40 and country [A-Z]{2}Only the fields a player may change (no mass assignment).04

6. match/: recording matches

FileWhat it isWhy it is like thisLearn
match/Match.javaEntity for matches: external_id unique, mode, map, start and end, recordedBy (lazy), createdThe unique external id is the idempotency key.04
match/MatchParticipant.javaEntity for the join table with @EmbeddedId + @MapsId for match and player, plus per-match stats and rating before and afterThe 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/hashCodeJPA requires value-based equality for composite ids.02
match/GameMode.javaFFA, BATTLE_ROYALEMatches the CHECK constraint.–
match/MatchRepository.javafindByExternalIdReplay detection.–
match/MatchParticipantRepository.javaParticipants 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 countQueryNo N+1; paging without loading entities.07
match/MatchService.javarecordMatch: 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 getPlayerMatchesThe heart of Arena's correctness: no lost updates, no deadlocks, exactly-once effects from at-least-once callers.06, 07
match/MatchController.javaPOST /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.javaexternalId ≤ 64, mode, map ≤ 40, times, 2–100 participants (@Valid cascades)Field rules here; cross-field rules in the service.04
match/dto/ParticipantRequest.javaplayerId, placement ≥ 1, non-negative counts, avg reaction ≥ 1Exactly the shape Telemetry's MatchSummary produces (a contract).01
match/dto/MatchResponse.java, ParticipantResponse.javaThe match with its participants sorted by placement, each with rating before and afterClients see the rating effect directly.–
match/dto/PlayerMatchResponse.javaOne row of a player's history: match info, placement, participant count, stats, rating changeBuilt directly by the JPQL projection.07

7. leaderboard/: ratings and Redis

FileWhat it isWhy it is like thisLearn
leaderboard/RatingCalculator.javaA pure utility: delta = round(maxDelta × (n + 1 − 2·placement) / (n − 1)), so first place gets +30, last −30, linear in between; applyDelta floors at 0No Spring, so it's tested directly. A simple placement-based system, not Elo (see module 16).02
leaderboard/LeaderboardEvents.javaRecords 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 countedRedis never sees uncommitted data; Redis problems never fail requests.08
leaderboard/LeaderboardRebuilder.javaOn ApplicationReadyEvent: if ZCARD ≠ the eligible count, stream eligible players by keyset batches of 10,000, pipelined ZADDs into leaderboard:global:rebuild, then RENAMERepairs Redis from the truth with an atomic swap. Only compares counts (module 08).08
leaderboard/LeaderboardService.javaPaged 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 gaugeKeeps the database path for the benchmark; the timers produced the server-side numbers.08, 14
leaderboard/LeaderboardController.javaPublic 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.javaThe 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

FileWhat it isWhy it is like thisLearn
moderation/AccountStatus.javaACTIVE, FLAGGED, BANNED, APPEALED, REINSTATEDThe states of the state machine.–
moderation/ModerationActionType.javaFLAG, BAN, CLEAR, NOTE, APPEAL_SUBMITTED, APPEAL_UPHELD, APPEAL_OVERTURNEDThe transitions; the last three are only reachable through the appeal endpoints.–
moderation/ActionSource.javaHUMAN, TELEMETRY, JUDGE, SYSTEMWho acted, recorded in the audit row and enforced per role.05
moderation/AccountStateMachine.javaA 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_TRANSITIONEvery status change goes through one tested contract (all 35 pairs).02, 13
moderation/ModerationAction.javaThe 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, timeThe transformer casts the JSON string to JSONB on insert; every change is a new row.06
moderation/ModerationActionRepository.javaPaged 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.javaapplyAction: 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 historyBusiness-rule authorisation lives here, independent of the Judge.05
moderation/ModerationQueueQuery.javaSQL 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 queryA read model that is awkward in JPQL and natural in SQL.06
moderation/ModerationController.javaPOST /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.javaaction, source, reason ≤ 500, up to 20 evidence strings (each ≤ 500, non-blank), confidence 0..1, optional review flagContainer-element constraints (List<@NotBlank @Size(max = 500) String>) validate every item.04
moderation/dto/ModerationActionResponse.javaThe stored action, with the actor's username and the parsed evidence listExactly what the Judge's history tool summarises.–
moderation/dto/QueueItemResponse.javaA flagged player plus a nested LatestAction recordNested records model the joined row.–

9. appeal/: the second chance

FileWhat it isWhy it is like thisLearn
appeal/Appeal.javaEntity: player, the ban action it contests (unique), status, statement, decider, note, times, @VersionOne appeal per ban (a UNIQUE column); the version stops two moderators deciding at once.07
appeal/AppealStatus.java, AppealDecision.javaPENDING / UPHELD / OVERTURNED; UPHOLD / OVERTURNThe request says the decision; the status records the outcome.–
appeal/AppealRepository.javaexistsByBanActionId; findByIdWithDetails (fetch player, left-fetch decider); paged by status, oldest firstDuplicate check plus fetch joins.07
appeal/AppealService.javaSubmit: 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; countersEvery status change, even from appeals, goes through the same state machine and audit table.06
appeal/AppealController.javaPOST /appeals (PLAYER, 201), GET /appeals?status=PENDING (MODERATOR), POST /appeals/{id}/decision (MODERATOR)The player id comes from the token.04
appeal/dto/SubmitAppealRequest.javaStatement 20–2000 charsForces a real explanation.–
appeal/dto/DecideAppealRequest.javaDecision + a note 1–1000 charsThe note becomes the audit reason.–
appeal/dto/AppealResponse.javaThe appeal with player, username, ban action, status, statement and decision fieldsNON_NULL hides decision fields while pending.–

10. Resources: configuration and schema

FileWhat it containsLearn
src/main/resources/application.ymlVirtual 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 variables03
db/migration/V1__init.sqlSix tables (players, refresh_tokens, matches, match_participants, moderation_actions, appeals), CHECK and UNIQUE constraints, foreign keys, the expression and composite indexes06
db/migration/V2__audit_log_append_only.sqlThe PL/pgSQL function and the BEFORE UPDATE OR DELETE trigger on moderation_actions06

11. Tests: what each class proves

Test classTypeWhat it proves (from its test names)
support/AbstractIntegrationTestBaseStarts 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/TestDataFactoryHelperCreates players (any status and rating), moderators and service accounts directly in the database, mints bearer tokens for them, and records matches
moderation/AccountStateMachineTestUnitAll 35 (status, action) pairs: legal ones give the right target, illegal ones throw INVALID_STATE_TRANSITION
leaderboard/RatingCalculatorTestUnitRating deltas, flooring at zero, rejection of invalid participant counts and placements
player/StatDistributionServiceTestUnitNull percentiles below 5 matches or before a distribution exists; percentile lookups at cut-point edges; reaction speed inverted
auth/TokenServiceTestUnitAccess-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/AuthIntegrationTestIntegrationRegistration 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/SecurityIntegrationTestIntegrationMissing or expired tokens give 401, wrong roles 403; the OpenAPI document lists exactly 18 operations
common/error/ErrorHandlingIntegrationTestIntegrationProblemDetail with code for unknown routes, malformed JSON and missing resources
player/PlayerIntegrationTestIntegration"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/MatchIntegrationTestIntegrationRecording 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/LeaderboardIntegrationTestIntegrationThe 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/ModerationIntegrationTestIntegrationAllowed 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/AuditLogAppendOnlyTestIntegrationRaw SQL UPDATE and DELETE on moderation_actions fail with "append-only"
appeal/AppealIntegrationTestIntegrationThe 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

FileWhat it isLearn
pom.xmlBoot 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 mappers14
mvnw, mvnw.cmd, .mvn/wrapper/The Maven Wrapper: a pinned Maven version, no installation needed14
DockerfileMulti-stage: JDK build with a cached dependency layer, JRE runtime, non-root user, MaxRAMPercentage=7514
compose.yamlPostgreSQL 17 (named volume, pg_isready), Redis 7 (redis-cli ping), Arena (waits for both healthy), Prometheus and Grafana behind the observability profile14
.env.exampleThe four secrets with placeholder values: JWT_SECRET, MODERATOR_PASSWORD, TELEMETRY_SERVICE_PASSWORD, JUDGE_SERVICE_PASSWORD05
.dockerignoreKeeps .env, .git, .idea, target and the benchmark ids out of the build context14
.gitignoreIgnores 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–
.gitattributesLine 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.ymlOn push and PR: Temurin 21, Maven cache, ./mvnw -B verify, upload the JaCoCo report always14
.github/workflows/qodana_code_quality.yml, qodana.yamlJetBrains Qodana static analysis (the qodana.starter profile, JVM community linter) on pushes to main and pull requests; needs a QODANA_TOKEN secret14
ops/prometheus.ymlScrapes arena:8080/actuator/prometheus every 5 s14
benchmark/rank-lookup.jsThe k6 script: warm-up (50 VUs, 15 s), measure (200 VUs, 60 s), a p95 sanity threshold, SOURCE=db|redis14
scripts/seed-1m-players.sqlInserts 1,000,000 players with generate_series, random ratings 500–2499 and a pre-computed bcrypt hash placeholder, then ANALYZE06
README.mdPublic overview: architecture, quick start, the 18-endpoint table, design decisions, the benchmark with method and environment, what's next01
Fairplay Arena — Implementation Specification.mdThe 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.mdLocal 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.

Saved in this browser.