diff --git a/README.md b/README.md index 6da684f..7de0161 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ Corvin -server +server

server  @@ -13,7 +13,7 @@
-Rust Axum game server for Corvin. Ships a bindable binary with `GET /health`, WebSocket `GET /ws` handshake (`Hello` / `Welcome` / `Ping` / `Pong` per PROTOCOL.md), reversible Postgres migrations for `users`, `sessions`, `passkeys`, and `email_otps`, Redis presence keys, Redis append-only live game event logs that replay to FEN via [chess-core](https://github.com/corvin-chess/chess-core), legal `apply_move` with PROTOCOL `MoveApplied` / `MoveRejected` (`ILLEGAL_MOVE`, `NOT_YOUR_TURN`, `GAME_GONE`, `AUTH`), server-authoritative clocks with Fischer increment and flag verification (`ClockSync` / `GameEnd` reason `flag`), lag compensation quota from server-measured RTT (`lag_comp_ms` on apply; never trusts client send time), HTTP auth under `/api/v1/auth` (WebAuthn passkeys plus email OTP), HttpOnly session cookies, CSRF-bound logout, and age-appropriate messaging defaults (`dm_enabled` / `public_chat_enabled`, minors stay off). Lobby, rated play, tournaments, WS move dispatch, and the wider HTTP API remain Planned. +Rust Axum game server for Corvin. Ships a bindable binary with `GET /health`, WebSocket `GET /ws` handshake (`Hello` / `Welcome` / `Ping` / `Pong` per PROTOCOL.md), reversible Postgres migrations for `users`, `sessions`, `passkeys`, and `email_otps`, Redis presence keys, Redis append-only live game event logs that replay to FEN via [chess-core](https://github.com/corvin-chess/chess-core), legal `apply_move` with PROTOCOL `MoveApplied` / `MoveRejected` (`ILLEGAL_MOVE`, `NOT_YOUR_TURN`, `GAME_GONE`, `AUTH`), server-authoritative clocks with Fischer increment and flag verification (`ClockSync` / `GameEnd` reason `flag`), lag compensation quota from server-measured RTT (`lag_comp_ms` on apply; never trusts client send time), draw / takeback / resign / abort helpers (`OfferState`, `OFFER_INVALID`, `ABORT_DENIED`, `GameEnd` reasons `agreement` / `resign` / `abort`), HTTP auth under `/api/v1/auth` (WebAuthn passkeys plus email OTP), HttpOnly session cookies, CSRF-bound logout, and age-appropriate messaging defaults (`dm_enabled` / `public_chat_enabled`, minors stay off). Lobby, rated play, tournaments, WS move dispatch, and the wider HTTP API remain Planned. @@ -21,7 +21,7 @@ Rust Axum game server for Corvin. Ships a bindable binary with `GET /health`, We

Overview

-Rust Axum server for Corvin. Current surface: `GET /health` returns HTTP 200 with plain body `ok` plus a trailing newline for Compose probes; `GET /ws` upgrades to the JSON play protocol v1 handshake (`Hello` with `client` `web|mobile|bot` and `locale` yields `Welcome` with ULID `session_id`, unix-ms `server_time`, and empty `features`, then a server `Ping` for RTT sampling; client `Ping`/`Pong` echo `nonce`; unsupported `v` returns `Error` `PROTO_VERSION`); reversible SQL migrations under `migrations/` create `users`, `sessions`, `passkeys`, and `email_otps`, and add `dm_enabled` / `public_chat_enabled` on `users` (ULID account ids, opaque sessions with CSRF secret material, WebAuthn credential JSON, hashed email OTP challenges); Redis helpers under `src/redis_store.rs` connect via `REDIS_URL` and maintain short-TTL presence keys `corvin:presence:{user_id}`; game helpers under `src/game/` store live append-only logs at `corvin:game:{id}:meta` (initial FEN, seat ids, clocks with Fischer `increment_ms` and `active_started_ms`, per-seat `lag_quota_*_ms`) and `corvin:game:{id}:events` (JSON Move / ServerNote entries with monotonic `seq`), reconstruct position FEN by replaying Move UCIs through [chess-core](https://github.com/corvin-chess/chess-core), apply seated legal moves via `apply_move` / `apply_move_with_rtt` (SAN + FEN + PROTOCOL reject codes; deducts effective elapsed after lag credit then adds increment; flags before increment; optional `lag_comp_ms`), and verify flag claims via `claim_flag` / `check_flag` (timeout draw when the opponent has no mating potential); lag helpers under `src/game/lag.rs` publish interim quota `clamp((initial+40×inc)/60, 200, 1000)` ms from server RTT EWMA one-way estimates (remeasure CV-305; never trust client send time); auth routes under `/api/v1/auth/email/otp/*` and `/api/v1/auth/passkey/*` mint HttpOnly `corvin_session` cookies (`SameSite=Lax`, `Secure` on https) and return a synchronizer `csrf_token` plus messaging flags (prior sessions for that user are revoked); `GET /api/v1/auth/session` resolves the cookie to `{user_id,username,csrf_token,dm_enabled,public_chat_enabled}`; `POST /api/v1/auth/logout` requires matching `X-CSRF-Token` and clears the cookie; `GET|PATCH /api/v1/account/messaging` reads or updates those flags (CSRF on PATCH; estimated age under 18 or missing `birth_year` cannot enable DMs or public chat). Planned surfaces: auth ticket on the socket, lobby and matchmaking, WS Move / Flag dispatch with live RTT into `LagTracker`, ratings, tournaments, DM delivery (CV-281 uses `assert_can_send_dm`), and the wider HTTP API. Intended dependencies: PostgreSQL for durable data, Redis for live games and presence, chess-core for legality, and optional analysis via [engine](https://github.com/corvin-chess/engine). Fair-play review hooks are planned to consume the public [fairplay](https://github.com/corvin-chess/fairplay) library; private thresholds stay out of this repository. Outbound SMTP is not wired yet; OTP delivery uses a log sink unless tests inject a capture mailer. +Rust Axum server for Corvin. Current surface: `GET /health` returns HTTP 200 with plain body `ok` plus a trailing newline for Compose probes; `GET /ws` upgrades to the JSON play protocol v1 handshake (`Hello` with `client` `web|mobile|bot` and `locale` yields `Welcome` with ULID `session_id`, unix-ms `server_time`, and empty `features`, then a server `Ping` for RTT sampling; client `Ping`/`Pong` echo `nonce`; unsupported `v` returns `Error` `PROTO_VERSION`); reversible SQL migrations under `migrations/` create `users`, `sessions`, `passkeys`, and `email_otps`, and add `dm_enabled` / `public_chat_enabled` on `users` (ULID account ids, opaque sessions with CSRF secret material, WebAuthn credential JSON, hashed email OTP challenges); Redis helpers under `src/redis_store.rs` connect via `REDIS_URL` and maintain short-TTL presence keys `corvin:presence:{user_id}`; game helpers under `src/game/` store live append-only logs at `corvin:game:{id}:meta` (initial FEN, seat ids, clocks with Fischer `increment_ms` and `active_started_ms`, per-seat `lag_quota_*_ms`, `time_class`, optional `pending_offer`, prev-clock snapshot for takeback) and `corvin:game:{id}:events` (JSON Move / Offer / OfferResponse / Resign / Abort / Takeback / ServerNote entries with monotonic `seq`), reconstruct position FEN by replaying net Move UCIs through [chess-core](https://github.com/corvin-chess/chess-core) (Takeback pops the last net ply), apply seated legal moves via `apply_move` / `apply_move_with_rtt` (SAN + FEN + PROTOCOL reject codes; deducts effective elapsed after lag credit then adds increment; flags before increment; optional `lag_comp_ms`; clears pending offers), and verify flag claims via `claim_flag` / `check_flag` (timeout draw when the opponent has no mating potential); offer helpers under `src/game/offers.rs` implement `offer_draw` / `offer_takeback` / `respond_offer` / `resign` / `abort` with PROTOCOL `OfferState` and `GameEnd` (`agreement`, `resign`, `abort`), reject codes `OFFER_INVALID` / `ABORT_DENIED`, ADR-005 first-move abort windows (bullet 15s / blitz 20s / rapid+ 60s), and counter-offer-as-accept; lag helpers under `src/game/lag.rs` publish interim quota `clamp((initial+40×inc)/60, 200, 1000)` ms from server RTT EWMA one-way estimates (remeasure CV-305; never trust client send time); auth routes under `/api/v1/auth/email/otp/*` and `/api/v1/auth/passkey/*` mint HttpOnly `corvin_session` cookies (`SameSite=Lax`, `Secure` on https) and return a synchronizer `csrf_token` plus messaging flags (prior sessions for that user are revoked); `GET /api/v1/auth/session` resolves the cookie to `{user_id,username,csrf_token,dm_enabled,public_chat_enabled}`; `POST /api/v1/auth/logout` requires matching `X-CSRF-Token` and clears the cookie; `GET|PATCH /api/v1/account/messaging` reads or updates those flags (CSRF on PATCH; estimated age under 18 or missing `birth_year` cannot enable DMs or public chat). Planned surfaces: auth ticket on the socket, lobby and matchmaking, WS Move / Offer / Flag dispatch with live RTT into `LagTracker`, ratings, tournaments, DM delivery (CV-281 uses `assert_can_send_dm`), and the wider HTTP API. Intended dependencies: PostgreSQL for durable data, Redis for live games and presence, chess-core for legality, and optional analysis via [engine](https://github.com/corvin-chess/engine). Fair-play review hooks are planned to consume the public [fairplay](https://github.com/corvin-chess/fairplay) library; private thresholds stay out of this repository. Outbound SMTP is not wired yet; OTP delivery uses a log sink unless tests inject a capture mailer. @@ -61,7 +61,7 @@ Redis presence (requires `REDIS_URL` from the same Compose stack): export REDIS_URL=redis://127.0.0.1:6379/0 ``` -Library helpers `touch_presence` / `is_online` / `clear_presence` use keys `corvin:presence:{user_id}` with a short TTL. Live game helpers `create_game` / `append_move_event` / `apply_move` / `apply_move_with_rtt` / `reconstruct_fen` / `claim_flag` / `check_flag` / `seed_lag_quotas` use `corvin:game:{id}:meta` and `corvin:game:{id}:events` (replay reconstructs FEN; `apply_move` rejects illegal and wrong-turn moves and ticks clocks with injectable server `ts`; `apply_move_with_rtt` credits lag from a fake or measured RTT; `claim_flag` verifies PROTOCOL flag claims). +Library helpers `touch_presence` / `is_online` / `clear_presence` use keys `corvin:presence:{user_id}` with a short TTL. Live game helpers `create_game` / `append_move_event` / `apply_move` / `apply_move_with_rtt` / `reconstruct_fen` / `claim_flag` / `check_flag` / `seed_lag_quotas` / `offer_draw` / `offer_takeback` / `respond_offer` / `resign` / `abort` use `corvin:game:{id}:meta` and `corvin:game:{id}:events` (replay reconstructs FEN; `apply_move` rejects illegal and wrong-turn moves and ticks clocks with injectable server `ts`; `apply_move_with_rtt` credits lag from a fake or measured RTT; `claim_flag` verifies PROTOCOL flag claims; offer helpers return `OfferState` or `GameEnd` and map rejects to `OFFER_INVALID` / `ABORT_DENIED`). WebSocket handshake (no Postgres required for the socket itself): @@ -77,7 +77,7 @@ WebSocket handshake (no Postgres required for the socket itself):

Development

-Edit `src/lib.rs` (router and `AppState`), `src/ws/` (PROTOCOL Hello/Welcome/Ping), `src/auth/` (email OTP, passkeys, sessions, mailer), `src/safety/` (age defaults and DM gate), `src/account/` (messaging prefs), `src/db.rs` (pool and migrate up/down), `src/redis_store.rs` (Redis connect and presence keys), `src/game/` (append-only game event log, FEN replay, legal `apply_move`, clocks with Fischer increment and flag, lag quota), `src/main.rs` (bind, graceful shutdown, migrate CLI), and SQL under `migrations/`. Local Postgres and Redis from [infra](https://github.com/corvin-chess/infra) supply `DATABASE_URL` / `REDIS_URL`. Secrets and fair-play private configuration never live in this repository. +Edit `src/lib.rs` (router and `AppState`), `src/ws/` (PROTOCOL Hello/Welcome/Ping), `src/auth/` (email OTP, passkeys, sessions, mailer), `src/safety/` (age defaults and DM gate), `src/account/` (messaging prefs), `src/db.rs` (pool and migrate up/down), `src/redis_store.rs` (Redis connect and presence keys), `src/game/` (append-only game event log, FEN replay, legal `apply_move`, clocks with Fischer increment and flag, lag quota, draw/takeback/resign/abort offers), `src/main.rs` (bind, graceful shutdown, migrate CLI), and SQL under `migrations/`. Local Postgres and Redis from [infra](https://github.com/corvin-chess/infra) supply `DATABASE_URL` / `REDIS_URL`. Secrets and fair-play private configuration never live in this repository. @@ -92,7 +92,7 @@ cargo test --locked node scripts/verify-readme.mjs ``` -`tests/health.rs` asserts `/health` returns 200 with body `ok\n` and unknown paths return 404. `tests/ws_hello.rs` binds a local listener and contracts `Hello`/`Welcome`/`Ping`/`Pong` plus `PROTO_VERSION` against PROTOCOL.md (no Postgres). `tests/migrations.rs` asserts paired up/down SQL and, when `DATABASE_URL` is set, applies migrate up/down against Postgres including `passkeys` / `email_otps` and messaging flags (CI runs Postgres 16). `tests/presence.rs` asserts presence key shape and, when `REDIS_URL` is set, PING plus touch/clear/TTL expiry against Redis (CI runs Redis 7). `tests/game_event_log.rs` asserts FEN replay for a known opening line always-on and, when `REDIS_URL` is set, create/append/reconstruct against Redis. `tests/move_apply.rs` asserts PROTOCOL `MoveApplied` / `MoveRejected` JSON shapes always-on and, when `REDIS_URL` is set, legal apply plus `ILLEGAL_MOVE` / `NOT_YOUR_TURN` / `AUTH` / `GAME_GONE` rejects. `tests/clocks.rs` asserts injectable clock math (deduct then Fischer increment; flag before increment), PROTOCOL `ClockSync` / `GameEnd` shapes, and when `REDIS_URL` is set, persisted tick on `apply_move`, flag-on-apply, and `claim_flag` verification. `tests/lag_quota.rs` asserts interim quota bounds, EWMA one-way math, PROTOCOL optional `lag_comp_ms`, and when `REDIS_URL` is set, fake-RTT credit/deplete plus lag preventing a false flag. `tests/auth_email_otp.rs` and `tests/auth_passkey.rs` exercise register/login e2e when `DATABASE_URL` is set (capture mailer; SoftPasskey). `tests/session_csrf.rs` asserts cookie attribute matrix always-on and, when `DATABASE_URL` is set, CSRF-bound logout plus session probe security tests. `tests/age_defaults.rs` asserts under-18 / missing birth year default DMs off, adults can toggle via `/api/v1/account/messaging`, and minors cannot enable messaging. Broader WS move/flag dispatch with live RTT wiring, and Compose integration checks land with later tasks. +`tests/health.rs` asserts `/health` returns 200 with body `ok\n` and unknown paths return 404. `tests/ws_hello.rs` binds a local listener and contracts `Hello`/`Welcome`/`Ping`/`Pong` plus `PROTO_VERSION` against PROTOCOL.md (no Postgres). `tests/migrations.rs` asserts paired up/down SQL and, when `DATABASE_URL` is set, applies migrate up/down against Postgres including `passkeys` / `email_otps` and messaging flags (CI runs Postgres 16). `tests/presence.rs` asserts presence key shape and, when `REDIS_URL` is set, PING plus touch/clear/TTL expiry against Redis (CI runs Redis 7). `tests/game_event_log.rs` asserts FEN replay for a known opening line always-on and, when `REDIS_URL` is set, create/append/reconstruct against Redis. `tests/move_apply.rs` asserts PROTOCOL `MoveApplied` / `MoveRejected` JSON shapes always-on and, when `REDIS_URL` is set, legal apply plus `ILLEGAL_MOVE` / `NOT_YOUR_TURN` / `AUTH` / `GAME_GONE` rejects. `tests/clocks.rs` asserts injectable clock math (deduct then Fischer increment; flag before increment), PROTOCOL `ClockSync` / `GameEnd` shapes, and when `REDIS_URL` is set, persisted tick on `apply_move`, flag-on-apply, and `claim_flag` verification. `tests/lag_quota.rs` asserts interim quota bounds, EWMA one-way math, PROTOCOL optional `lag_comp_ms`, and when `REDIS_URL` is set, fake-RTT credit/deplete plus lag preventing a false flag. `tests/offers.rs` asserts ADR-005 abort windows, PROTOCOL `OfferState` / `GameEnd` / `OFFER_INVALID` / `ABORT_DENIED` shapes, and when `REDIS_URL` is set, draw accept/decline/withdraw/counter-offer, resign, abort (0–1 ply window), takeback FEN+clock restore, and auth rejects. `tests/auth_email_otp.rs` and `tests/auth_passkey.rs` exercise register/login e2e when `DATABASE_URL` is set (capture mailer; SoftPasskey). `tests/session_csrf.rs` asserts cookie attribute matrix always-on and, when `DATABASE_URL` is set, CSRF-bound logout plus session probe security tests. `tests/age_defaults.rs` asserts under-18 / missing birth year default DMs off, adults can toggle via `/api/v1/account/messaging`, and minors cannot enable messaging. Broader WS move/offer/flag dispatch with live RTT wiring, and Compose integration checks land with later tasks. @@ -100,7 +100,7 @@ node scripts/verify-readme.mjs

Architecture

-Binary crate `corvin-server`: `src/lib.rs` owns the Axum router and `AppState`; `src/ws/` implements PROTOCOL connection lifecycle (`Hello`/`Welcome`/`Ping`/`Pong` on `/ws`); `src/auth/` implements PROTOCOL auth paths with `webauthn-rs` and hashed email OTPs; `src/safety/` owns age-based messaging defaults and `assert_can_send_dm`; `src/account/` serves messaging preference GET/PATCH; `src/db.rs` embeds reversible sqlx migrations and exposes `migrate_up` / `migrate_down`; `src/redis_store.rs` opens a Redis connection manager from `REDIS_URL` and owns presence key helpers; `src/game/` owns live game meta, append-only Move event lists in Redis, FEN reconstruction, legal `apply_move` (PROTOCOL `MoveApplied` / `MoveRejected`), clocks (`src/game/clock.rs`: Fischer tick, `claim_flag`, `ClockSync` / `GameEnd`), and lag compensation (`src/game/lag.rs`: EWMA RTT, quota, credit) via `corvin-chess-core`; `src/main.rs` binds `HOST`/`PORT` and serves with graceful shutdown, or runs `migrate up|down` when those args are passed. Planned modules: `src/api`, `src/match`, `src/rating`, and WS Move / Flag dispatch on `src/ws` (feeding `LagTracker` from Ping RTT). Server is authoritative for game state and clocks; clients reconcile to protocol events. See organization ADRs and [website](https://github.com/corvin-chess/website) once docs are published. +Binary crate `corvin-server`: `src/lib.rs` owns the Axum router and `AppState`; `src/ws/` implements PROTOCOL connection lifecycle (`Hello`/`Welcome`/`Ping`/`Pong` on `/ws`); `src/auth/` implements PROTOCOL auth paths with `webauthn-rs` and hashed email OTPs; `src/safety/` owns age-based messaging defaults and `assert_can_send_dm`; `src/account/` serves messaging preference GET/PATCH; `src/db.rs` embeds reversible sqlx migrations and exposes `migrate_up` / `migrate_down`; `src/redis_store.rs` opens a Redis connection manager from `REDIS_URL` and owns presence key helpers; `src/game/` owns live game meta, append-only event lists in Redis, FEN reconstruction, legal `apply_move` (PROTOCOL `MoveApplied` / `MoveRejected`), clocks (`src/game/clock.rs`: Fischer tick, `claim_flag`, `ClockSync` / `GameEnd`), lag compensation (`src/game/lag.rs`: EWMA RTT, quota, credit), and offers (`src/game/offers.rs`: draw/takeback/resign/abort state machine) via `corvin-chess-core`; `src/main.rs` binds `HOST`/`PORT` and serves with graceful shutdown, or runs `migrate up|down` when those args are passed. Planned modules: `src/api`, `src/match`, `src/rating`, and WS Move / Offer / Flag dispatch on `src/ws` (feeding `LagTracker` from Ping RTT). Server is authoritative for game state and clocks; clients reconcile to protocol events. See organization ADRs and [website](https://github.com/corvin-chess/website) once docs are published. @@ -122,6 +122,7 @@ Binary crate `corvin-server`: `src/lib.rs` owns the Axum router and `AppState`; | Move apply | Built | | Clocks | Built | | Lag compensation | Built | +| Offers | Built | | Play protocol / WS | Planned | | Matchmaking | Planned | | Implementation | Planned | diff --git a/scripts/verify-readme.mjs b/scripts/verify-readme.mjs index 98c4036..4a02105 100644 --- a/scripts/verify-readme.mjs +++ b/scripts/verify-readme.mjs @@ -23,7 +23,7 @@ const CLOSING = const PLANNED_AREAS = /^(Play protocol \/ WS|Matchmaking|Implementation)$/i const BUILT_AREAS = - /^(README|Axum scaffold|Postgres migrations|Redis presence|Auth|Session cookies \/ CSRF|Age-appropriate defaults|WS Hello\/Welcome\/Ping|Game event log|Move apply|Clocks|Lag compensation)$/i + /^(README|Axum scaffold|Postgres migrations|Redis presence|Auth|Session cookies \/ CSRF|Age-appropriate defaults|WS Hello\/Welcome\/Ping|Game event log|Move apply|Clocks|Lag compensation|Offers)$/i const fail = (msg) => { console.error(`FAIL: ${msg}`) @@ -164,6 +164,7 @@ if (!statusTableMatch) { let sawMoveApplyBuilt = false let sawClocksBuilt = false let sawLagBuilt = false + let sawOffersBuilt = false let sawImplPlanned = false for (const [, areaRaw, stateRaw] of stateCells) { const area = areaRaw.trim() @@ -213,6 +214,9 @@ if (!statusTableMatch) { if (/^Lag compensation$/i.test(area) && /^Built$/i.test(state)) { sawLagBuilt = true } + if (/^Offers$/i.test(area) && /^Built$/i.test(state)) { + sawOffersBuilt = true + } if (PLANNED_AREAS.test(area) && !/^Planned$/i.test(state)) { fail(`STATUS row "${area}" must stay Planned until code exists; got "${state}"`) } @@ -246,6 +250,9 @@ if (!statusTableMatch) { if (!sawLagBuilt) { fail('STATUS must include "| Lag compensation | Built |"') } + if (!sawOffersBuilt) { + fail('STATUS must include "| Offers | Built |"') + } if (!sawImplPlanned) fail('STATUS must include "| Implementation | Planned |"') if (!process.exitCode) ok("STATUS rows use Planned/Built correctly") } @@ -487,6 +494,28 @@ if ( ok("Lag compensation surface documented") } +const offersRs = join(repoRoot, "src", "game", "offers.rs") +const offersTest = join(repoRoot, "tests", "offers.rs") +if (!existsSync(offersRs) || !existsSync(offersTest)) { + fail("Offers sources missing (src/game/offers.rs, tests/offers.rs)") +} else { + ok("Offers sources present") +} + +if ( + !readme.includes("offer_draw") || + !readme.includes("OfferState") || + !readme.includes("ABORT_DENIED") || + !readme.includes("OFFER_INVALID") || + !readme.includes("offers") +) { + fail( + "README must document offer_draw, OfferState, OFFER_INVALID/ABORT_DENIED, and offers tests" + ) +} else { + ok("Offers surface documented") +} + if (!existsSync(join(repoRoot, "src", "lib.rs")) || !existsSync(join(repoRoot, "src", "main.rs"))) { fail("Axum scaffold source missing (src/lib.rs, src/main.rs)") } else { diff --git a/src/game/apply.rs b/src/game/apply.rs index b6a32b0..87fb0f3 100644 --- a/src/game/apply.rs +++ b/src/game/apply.rs @@ -275,6 +275,7 @@ pub async fn apply_move_with_rtt( zeroed.b_ms = 0; } write_flag_to_meta(&mut meta, color, &zeroed); + meta.pending_offer = None; meta.ended_reason = Some(format!("flag:{}", outcome.result)); save_meta(conn, game_id, &meta).await?; return Err(ApplyError::Flagged { outcome }); @@ -290,12 +291,26 @@ pub async fn apply_move_with_rtt( .ok_or_else(|| ApplyError::IllegalMove(uci.to_owned()))?; let next_fen = next.to_fen(); + // Snapshot clocks + lag quotas for one-ply takeback; clear pending offers (CV-165). + meta.prev_clock_w_ms = meta.clock_w_ms; + meta.prev_clock_b_ms = meta.clock_b_ms; + meta.prev_active = if meta.active.is_empty() { + board_active.to_owned() + } else { + meta.active.clone() + }; + meta.prev_active_started_ms = meta.active_started_ms; + meta.prev_lag_quota_w_ms = meta.lag_quota_w_ms; + meta.prev_lag_quota_b_ms = meta.lag_quota_b_ms; + meta.pending_offer = None; + // Deduct effective elapsed then add Fischer increment (ADR-005). match tick_meta_on_move_compensated(&meta, seat, ts, lag_comp) { ClockTick::Flagged { color, clocks } => { // Same `ts` as peek should not flag; treat as internal fault. let outcome = flag_outcome_for_position(&fen, color).map_err(ApplyError::Corrupt)?; write_flag_to_meta(&mut meta, color, &clocks); + meta.pending_offer = None; meta.ended_reason = Some(format!("flag:{}", outcome.result)); save_meta(conn, game_id, &meta).await?; return Err(ApplyError::Flagged { outcome }); diff --git a/src/game/clock.rs b/src/game/clock.rs index a5bfd02..e0edc33 100644 --- a/src/game/clock.rs +++ b/src/game/clock.rs @@ -407,6 +407,7 @@ pub fn write_flag_to_meta(meta: &mut super::events::GameMeta, color: &str, pair: } meta.ended = true; meta.ended_reason = Some("flag".to_owned()); + meta.pending_offer = None; } #[cfg(test)] diff --git a/src/game/events.rs b/src/game/events.rs index 502ff2a..08e2d43 100644 --- a/src/game/events.rs +++ b/src/game/events.rs @@ -5,6 +5,15 @@ use serde::{Deserialize, Serialize}; /// Standard chess starting position FEN (six fields). pub const START_FEN: &str = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"; +/// Pending draw or takeback offer (cleared on move apply or response). +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct PendingOffer { + /// `"draw"` or `"takeback"`. + pub kind: String, + /// Seat that created the offer (`"w"` / `"b"`). + pub by: String, +} + /// Durable-enough live meta for a Redis game (initial FEN + seats + clocks). #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct GameMeta { @@ -44,6 +53,26 @@ pub struct GameMeta { /// Last server-measured one-way lag estimate for Black (ms). #[serde(default)] pub lag_one_way_b_ms: u64, + /// Time class for abort first-move windows (ADR-005): bullet/blitz/rapid/classical/correspondence. + #[serde(default = "default_time_class")] + pub time_class: String, + /// Open draw/takeback offer, if any (CV-165). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub pending_offer: Option, + /// Clock snapshot before the last accepted ply (one-ply takeback restore). + #[serde(default)] + pub prev_clock_w_ms: u64, + #[serde(default)] + pub prev_clock_b_ms: u64, + #[serde(default)] + pub prev_active: String, + #[serde(default)] + pub prev_active_started_ms: u64, + /// Lag quota snapshot before the last accepted ply (restored on takeback). + #[serde(default)] + pub prev_lag_quota_w_ms: u64, + #[serde(default)] + pub prev_lag_quota_b_ms: u64, /// True after a terminal result (flag, resign, …) has been recorded. #[serde(default)] pub ended: bool, @@ -52,6 +81,10 @@ pub struct GameMeta { pub ended_reason: Option, } +fn default_time_class() -> String { + "blitz".to_owned() +} + impl Default for GameMeta { fn default() -> Self { Self { @@ -68,6 +101,14 @@ impl Default for GameMeta { lag_quota_b_ms: 0, lag_one_way_w_ms: 0, lag_one_way_b_ms: 0, + time_class: default_time_class(), + pending_offer: None, + prev_clock_w_ms: 0, + prev_clock_b_ms: 0, + prev_active: String::new(), + prev_active_started_ms: 0, + prev_lag_quota_w_ms: 0, + prev_lag_quota_b_ms: 0, ended: false, ended_reason: None, } @@ -82,20 +123,66 @@ pub struct MoveEvent { pub ts: u64, } -/// Append-only game events. Only `Move` changes the board for FEN replay. +/// Append-only game events. Only `Move` changes the board for FEN replay +/// (and `Takeback` undoes the latest net Move; see `replay_fen`). #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "typ")] pub enum GameEvent { #[serde(rename = "Move")] - Move { seq: u64, uci: String, ts: u64 }, + Move { + seq: u64, + uci: String, + ts: u64, + }, /// Non-position note (pairing, admin). Ignored by FEN replay. - ServerNote { seq: u64, text: String, ts: u64 }, + ServerNote { + seq: u64, + text: String, + ts: u64, + }, + /// Draw or takeback offered (audit; pending also mirrored on meta). + Offer { + seq: u64, + kind: String, + by: String, + ts: u64, + }, + /// Accept/decline/withdraw of a pending offer. + OfferResponse { + seq: u64, + kind: String, + by: String, + accept: bool, + ts: u64, + }, + Resign { + seq: u64, + by: String, + ts: u64, + }, + Abort { + seq: u64, + by: String, + ts: u64, + }, + /// Undo the net Move with `undone_seq` (replay pops that ply). + Takeback { + seq: u64, + undone_seq: u64, + ts: u64, + }, } impl GameEvent { pub fn seq(&self) -> u64 { match self { - Self::Move { seq, .. } | Self::ServerNote { seq, .. } => *seq, + Self::Move { seq, .. } + | Self::ServerNote { seq, .. } + | Self::Offer { seq, .. } + | Self::OfferResponse { seq, .. } + | Self::Resign { seq, .. } + | Self::Abort { seq, .. } + | Self::Takeback { seq, .. } => *seq, } } diff --git a/src/game/mod.rs b/src/game/mod.rs index a83d395..f9539ef 100644 --- a/src/game/mod.rs +++ b/src/game/mod.rs @@ -4,11 +4,13 @@ //! Legal apply + PROTOCOL MoveRejected codes: CV-162. //! Clocks + Fischer increment + flag: CV-163 / ADR-005. //! Lag compensation quota from server RTT: CV-164. +//! Draw / takeback / resign / abort: CV-165. mod apply; mod clock; mod events; mod lag; +mod offers; mod replay; mod store; @@ -21,15 +23,20 @@ pub use clock::{ is_flagged_at, is_flagged_at_compensated, remaining_at, tick_on_move, tick_on_move_compensated, ClockPair, ClockTick, FlagClaimError, FlagOutcome, }; -pub use events::{GameEvent, GameMeta, MoveEvent, START_FEN}; +pub use events::{GameEvent, GameMeta, MoveEvent, PendingOffer, START_FEN}; pub use lag::{ active_seat_credit_ms, credit_lag, effective_elapsed_ms, estimated_game_ms, initial_quota_ms, peek_credit_ms, seed_lag_quotas, LagCredit, LagTracker, ESTIMATE_INC_MOVES, QUOTA_CAP_MS, QUOTA_FLOOR_MS, }; -pub use replay::replay_fen; +pub use offers::{ + abort, abort_allowed, abort_window_ms, game_end_offer_json, offer_draw, offer_error_json, + offer_state_json, offer_takeback, resign, respond_offer, GameEndOut, OfferError, OfferOutcome, + OfferRejectCode, OfferStateOut, OFFER_DRAW, OFFER_TAKEBACK, +}; +pub use replay::{net_move_events, replay_fen}; pub use store::{ - append_move_event, create_game, delete_game, game_events_key, game_meta_key, load_events, - load_meta, reconstruct_fen, save_meta, GameLogError, GAME_KEY_PREFIX, MAX_EVENTS, MAX_FEN_LEN, - MAX_GAME_ID_LEN, MAX_PLAYER_ID_LEN, MAX_UCI_LEN, + append_game_event, append_move_event, create_game, delete_game, game_events_key, game_meta_key, + load_events, load_meta, reconstruct_fen, save_meta, GameLogError, GAME_KEY_PREFIX, MAX_EVENTS, + MAX_EVENT_BYTES, MAX_FEN_LEN, MAX_GAME_ID_LEN, MAX_META_BYTES, MAX_PLAYER_ID_LEN, MAX_UCI_LEN, }; diff --git a/src/game/offers.rs b/src/game/offers.rs new file mode 100644 index 0000000..5713f66 --- /dev/null +++ b/src/game/offers.rs @@ -0,0 +1,585 @@ +//! Draw / takeback offers, resign, and abort (CV-165 / PROTOCOL / ADR-004 / ADR-005). + +use std::fmt; + +use redis::aio::ConnectionManager; +use serde_json::{json, Value}; + +use super::events::{GameEvent, GameMeta, PendingOffer}; +use super::replay::{net_move_events, replay_fen}; +use super::store::{ + append_game_event, load_events, load_meta, save_meta, GameLogError, MAX_PLAYER_ID_LEN, +}; + +const PROTOCOL_V: u32 = 1; + +/// Offer kinds accepted by PROTOCOL `OfferResponse.offer`. +pub const OFFER_DRAW: &str = "draw"; +pub const OFFER_TAKEBACK: &str = "takeback"; + +/// ADR-005 first-move abort windows by time class (ms). +pub fn abort_window_ms(time_class: &str) -> u64 { + match time_class.trim().to_ascii_lowercase().as_str() { + "bullet" => 15_000, + "blitz" => 20_000, + "rapid" | "classical" | "correspondence" => 60_000, + // Unknown class: treat as blitz so abort stays bounded. + _ => 20_000, + } +} + +/// Whether abort is still allowed given net ply count and first-move timestamp. +pub fn abort_allowed( + net_plies: usize, + first_move_ts: Option, + now_ms: u64, + time_class: &str, +) -> bool { + match net_plies { + 0 => true, + 1 => match first_move_ts { + // Missing ts with a ply on the board is corrupt; deny rather than open an unbounded window. + None => false, + Some(start) => now_ms.saturating_sub(start) <= abort_window_ms(time_class), + }, + _ => false, + } +} + +/// PROTOCOL error codes for offer/abort rejects (and AUTH / GAME_GONE). +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub enum OfferRejectCode { + OfferInvalid, + AbortDenied, + Auth, + GameGone, +} + +impl OfferRejectCode { + pub fn as_str(self) -> &'static str { + match self { + Self::OfferInvalid => "OFFER_INVALID", + Self::AbortDenied => "ABORT_DENIED", + Self::Auth => "AUTH", + Self::GameGone => "GAME_GONE", + } + } +} + +/// Errors from offer / resign / abort mutations. +#[derive(Debug)] +pub enum OfferError { + OfferInvalid(String), + AbortDenied(String), + Auth, + GameGone, + Corrupt(String), + TooManyEvents, + Redis(redis::RedisError), +} + +impl OfferError { + pub fn reject_code(&self) -> OfferRejectCode { + match self { + Self::OfferInvalid(_) => OfferRejectCode::OfferInvalid, + Self::AbortDenied(_) => OfferRejectCode::AbortDenied, + Self::Auth => OfferRejectCode::Auth, + Self::GameGone => OfferRejectCode::GameGone, + Self::Corrupt(_) | Self::TooManyEvents | Self::Redis(_) => { + OfferRejectCode::OfferInvalid + } + } + } +} + +impl fmt::Display for OfferError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::OfferInvalid(msg) => write!(f, "{msg}"), + Self::AbortDenied(msg) => write!(f, "{msg}"), + Self::Auth => write!(f, "not a player in this game"), + Self::GameGone => write!(f, "game not found"), + Self::Corrupt(detail) => write!(f, "corrupt game state: {detail}"), + Self::TooManyEvents => write!(f, "game event log exceeds max length"), + Self::Redis(err) => write!(f, "{err}"), + } + } +} + +impl std::error::Error for OfferError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Redis(err) => Some(err), + _ => None, + } + } +} + +impl From for OfferError { + fn from(value: GameLogError) -> Self { + match value { + GameLogError::GameGone | GameLogError::InvalidGameId => Self::GameGone, + GameLogError::TooManyEvents => Self::TooManyEvents, + GameLogError::Redis(err) => Self::Redis(err), + GameLogError::CorruptEvent(detail) | GameLogError::IllegalMove(detail) => { + Self::Corrupt(detail) + } + GameLogError::InvalidFen(err) => Self::Corrupt(err.to_string()), + GameLogError::InvalidUci(err) => Self::Corrupt(err.to_string()), + GameLogError::GameExists => Self::Corrupt("unexpected game exists".into()), + } + } +} + +/// Successful non-terminal offer mutation (PROTOCOL `OfferState`). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct OfferStateOut { + pub offer: &'static str, + pub by: &'static str, + pub status: &'static str, + pub seq: u64, +} + +/// Terminal game result from resign / abort / draw agreement. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct GameEndOut { + pub result: &'static str, + pub winner: Option<&'static str>, + pub reason: &'static str, + pub seq: u64, +} + +/// Result of an offer / resign / abort call. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum OfferOutcome { + State(OfferStateOut), + End(GameEndOut), +} + +/// PROTOCOL `OfferState` JSON. +pub fn offer_state_json( + game_id: &str, + offer: &str, + by: &str, + status: &str, + seq: u64, + ts: u64, +) -> Value { + json!({ + "typ": "OfferState", + "v": PROTOCOL_V, + "game_id": game_id, + "offer": offer, + "by": by, + "status": status, + "seq": seq, + "ts": ts + }) +} + +/// PROTOCOL `GameEnd` JSON for resign / abort / agreement (no `flagged`). +pub fn game_end_offer_json(game_id: &str, end: &GameEndOut, ts: u64) -> Value { + let mut body = json!({ + "typ": "GameEnd", + "v": PROTOCOL_V, + "game_id": game_id, + "result": end.result, + "reason": end.reason, + "seq": end.seq, + "ts": ts + }); + match end.winner { + Some(w) => body["winner"] = json!(w), + None => body["winner"] = Value::Null, + } + body +} + +/// PROTOCOL `Error` for offer/abort rejects. +pub fn offer_error_json(id: Option<&str>, code: OfferRejectCode, message: &str) -> Value { + let mut body = json!({ + "typ": "Error", + "v": PROTOCOL_V, + "code": code.as_str(), + "message": message + }); + if let Some(id) = id { + body["id"] = json!(id); + } + body +} + +fn seat_color(meta: &GameMeta, player_id: &str) -> Result<&'static str, OfferError> { + if player_id.is_empty() || player_id.len() > MAX_PLAYER_ID_LEN { + return Err(OfferError::Auth); + } + if meta.white_id.is_empty() || meta.black_id.is_empty() { + return Err(OfferError::Auth); + } + if player_id == meta.white_id { + Ok("w") + } else if player_id == meta.black_id { + Ok("b") + } else { + Err(OfferError::Auth) + } +} + +fn require_live(meta: &GameMeta) -> Result<(), OfferError> { + if meta.ended { + return Err(OfferError::GameGone); + } + Ok(()) +} + +fn opponent(color: &str) -> &'static str { + if color == "w" { + "b" + } else { + "w" + } +} + +fn parse_kind(kind: &str) -> Result<&'static str, OfferError> { + match kind { + OFFER_DRAW => Ok(OFFER_DRAW), + OFFER_TAKEBACK => Ok(OFFER_TAKEBACK), + _ => Err(OfferError::OfferInvalid("unknown offer kind".into())), + } +} + +/// Offer a draw. Counter-offering an opponent draw accepts it. +pub async fn offer_draw( + conn: &mut ConnectionManager, + game_id: &str, + player_id: &str, + ts: u64, +) -> Result { + offer_kind(conn, game_id, player_id, OFFER_DRAW, ts).await +} + +/// Offer a takeback of the last net ply. Counter-offer accepts. +pub async fn offer_takeback( + conn: &mut ConnectionManager, + game_id: &str, + player_id: &str, + ts: u64, +) -> Result { + offer_kind(conn, game_id, player_id, OFFER_TAKEBACK, ts).await +} + +async fn offer_kind( + conn: &mut ConnectionManager, + game_id: &str, + player_id: &str, + kind: &'static str, + ts: u64, +) -> Result { + let mut meta = load_meta(conn, game_id).await?; + require_live(&meta)?; + let by = seat_color(&meta, player_id)?; + let events = load_events(conn, game_id).await?; + + if kind == OFFER_TAKEBACK && net_move_events(&events).is_empty() { + return Err(OfferError::OfferInvalid("no move to take back".into())); + } + + if let Some(pending) = meta.pending_offer.clone() { + if pending.kind == kind && pending.by != by { + // Opponent already offered the same kind → treat as accept. + return respond_offer_inner(conn, game_id, &mut meta, &events, by, kind, true, ts) + .await; + } + if pending.kind == kind && pending.by == by { + return Err(OfferError::OfferInvalid( + "offer already pending from this seat".into(), + )); + } + if pending.kind != kind { + return Err(OfferError::OfferInvalid( + "different offer already pending".into(), + )); + } + } + + // Append audit event before meta so a failed RPUSH cannot leave pending without a log entry. + let seq = append_game_event( + conn, + game_id, + GameEvent::Offer { + seq: 0, + kind: kind.to_owned(), + by: by.to_owned(), + ts, + }, + ) + .await?; + meta.pending_offer = Some(PendingOffer { + kind: kind.to_owned(), + by: by.to_owned(), + }); + save_meta(conn, game_id, &meta).await?; + + Ok(OfferOutcome::State(OfferStateOut { + offer: kind, + by, + status: "offered", + seq, + })) +} + +/// Accept, decline, or withdraw a pending offer (`accept:false` = decline or withdraw). +pub async fn respond_offer( + conn: &mut ConnectionManager, + game_id: &str, + player_id: &str, + offer: &str, + accept: bool, + ts: u64, +) -> Result { + let kind = parse_kind(offer)?; + let mut meta = load_meta(conn, game_id).await?; + require_live(&meta)?; + let by = seat_color(&meta, player_id)?; + let events = load_events(conn, game_id).await?; + respond_offer_inner(conn, game_id, &mut meta, &events, by, kind, accept, ts).await +} + +#[allow(clippy::too_many_arguments)] // PROTOCOL fields + Redis handles; keep flat for call sites. +async fn respond_offer_inner( + conn: &mut ConnectionManager, + game_id: &str, + meta: &mut GameMeta, + events: &[GameEvent], + by: &'static str, + kind: &'static str, + accept: bool, + ts: u64, +) -> Result { + let pending = meta + .pending_offer + .clone() + .ok_or_else(|| OfferError::OfferInvalid("no pending offer".into()))?; + if pending.kind != kind { + return Err(OfferError::OfferInvalid( + "pending offer kind mismatch".into(), + )); + } + + if accept { + // Only the opponent of the offerer may accept. + if pending.by == by { + return Err(OfferError::OfferInvalid("cannot accept own offer".into())); + } + match kind { + OFFER_DRAW => { + let seq = append_game_event( + conn, + game_id, + GameEvent::OfferResponse { + seq: 0, + kind: kind.to_owned(), + by: by.to_owned(), + accept: true, + ts, + }, + ) + .await?; + meta.pending_offer = None; + meta.ended = true; + meta.ended_reason = Some("agreement".into()); + meta.active_started_ms = 0; + save_meta(conn, game_id, meta).await?; + Ok(OfferOutcome::End(GameEndOut { + result: "1/2-1/2", + winner: None, + reason: "agreement", + seq, + })) + } + OFFER_TAKEBACK => { + let offerer = if pending.by == "w" { "w" } else { "b" }; + apply_takeback(conn, game_id, meta, events, offerer, ts).await + } + _ => Err(OfferError::OfferInvalid("unknown offer kind".into())), + } + } else { + // Decline (opponent) or withdraw (offerer). + let status = if pending.by == by { + "withdrawn" + } else { + "declined" + }; + let offerer = if pending.by == "w" { "w" } else { "b" }; + let seq = append_game_event( + conn, + game_id, + GameEvent::OfferResponse { + seq: 0, + kind: kind.to_owned(), + by: by.to_owned(), + accept: false, + ts, + }, + ) + .await?; + meta.pending_offer = None; + save_meta(conn, game_id, meta).await?; + Ok(OfferOutcome::State(OfferStateOut { + offer: kind, + by: offerer, + status, + seq, + })) + } +} + +async fn apply_takeback( + conn: &mut ConnectionManager, + game_id: &str, + meta: &mut GameMeta, + events: &[GameEvent], + offerer: &'static str, + ts: u64, +) -> Result { + let net = net_move_events(events); + let last = net + .last() + .ok_or_else(|| OfferError::OfferInvalid("no move to take back".into()))?; + let GameEvent::Move { + seq: undone_seq, .. + } = last + else { + return Err(OfferError::Corrupt("net move stack corrupt".into())); + }; + + // Append first so a failed RPUSH cannot leave meta clocks undone while the ply remains. + let _ = append_game_event( + conn, + game_id, + GameEvent::OfferResponse { + seq: 0, + kind: OFFER_TAKEBACK.to_owned(), + by: offerer.to_owned(), + accept: true, + ts, + }, + ) + .await?; + let seq = append_game_event( + conn, + game_id, + GameEvent::Takeback { + seq: 0, + undone_seq: *undone_seq, + ts, + }, + ) + .await?; + + // Restore clocks + lag quotas from the snapshot taken before the undone ply. + meta.clock_w_ms = meta.prev_clock_w_ms; + meta.clock_b_ms = meta.prev_clock_b_ms; + meta.lag_quota_w_ms = meta.prev_lag_quota_w_ms; + meta.lag_quota_b_ms = meta.prev_lag_quota_b_ms; + meta.pending_offer = None; + + let fen = replay_fen(&meta.initial_fen, &load_events(conn, game_id).await?)?; + let active = fen.split_whitespace().nth(1).unwrap_or("w"); + meta.active = active.to_owned(); + // Fresh think clock for the side that must move again after the undo. + meta.active_started_ms = ts; + + save_meta(conn, game_id, meta).await?; + + Ok(OfferOutcome::State(OfferStateOut { + offer: OFFER_TAKEBACK, + by: offerer, + status: "accepted", + seq, + })) +} + +/// Resign: opponent wins. Allowed any time while the game is live. +pub async fn resign( + conn: &mut ConnectionManager, + game_id: &str, + player_id: &str, + ts: u64, +) -> Result { + let mut meta = load_meta(conn, game_id).await?; + require_live(&meta)?; + let by = seat_color(&meta, player_id)?; + let winner = opponent(by); + let result = if winner == "w" { "1-0" } else { "0-1" }; + + let seq = append_game_event( + conn, + game_id, + GameEvent::Resign { + seq: 0, + by: by.to_owned(), + ts, + }, + ) + .await?; + meta.pending_offer = None; + meta.ended = true; + meta.ended_reason = Some("resign".into()); + meta.active_started_ms = 0; + save_meta(conn, game_id, &meta).await?; + + Ok(OfferOutcome::End(GameEndOut { + result, + winner: Some(winner), + reason: "resign", + seq, + })) +} + +/// Abort under ADR-005 first-move rules (0 plies, or 1 ply within class window). +pub async fn abort( + conn: &mut ConnectionManager, + game_id: &str, + player_id: &str, + ts: u64, +) -> Result { + let mut meta = load_meta(conn, game_id).await?; + require_live(&meta)?; + let by = seat_color(&meta, player_id)?; + let events = load_events(conn, game_id).await?; + let net = net_move_events(&events); + let first_ts = net.first().and_then(|e| match e { + GameEvent::Move { ts, .. } => Some(*ts), + _ => None, + }); + + if !abort_allowed(net.len(), first_ts, ts, &meta.time_class) { + return Err(OfferError::AbortDenied( + "abort not allowed after first-move window".into(), + )); + } + + let seq = append_game_event( + conn, + game_id, + GameEvent::Abort { + seq: 0, + by: by.to_owned(), + ts, + }, + ) + .await?; + meta.pending_offer = None; + meta.ended = true; + meta.ended_reason = Some("abort".into()); + meta.active_started_ms = 0; + save_meta(conn, game_id, &meta).await?; + + Ok(OfferOutcome::End(GameEndOut { + result: "*", + winner: None, + reason: "abort", + seq, + })) +} diff --git a/src/game/replay.rs b/src/game/replay.rs index 51a66fd..7939693 100644 --- a/src/game/replay.rs +++ b/src/game/replay.rs @@ -5,13 +5,28 @@ use corvin_chess_core::{Move, Position}; use super::events::GameEvent; use super::store::GameLogError; +/// Net Move events after applying Takeback pops (audit/non-move events ignored). +pub fn net_move_events(events: &[GameEvent]) -> Vec<&GameEvent> { + let mut stack: Vec<&GameEvent> = Vec::new(); + for event in events { + match event { + GameEvent::Move { .. } => stack.push(event), + GameEvent::Takeback { .. } => { + let _ = stack.pop(); + } + _ => {} + } + } + stack +} + /// Replay `events` from `initial_fen` and return the resulting FEN. /// -/// Only `GameEvent::Move` updates the board. Non-move events are skipped so -/// clock/offer notes can sit in the same log without changing position. +/// Only net `GameEvent::Move` plies update the board. `Takeback` pops the last +/// net Move. Other event types are skipped so offers/resigns can share the log. pub fn replay_fen(initial_fen: &str, events: &[GameEvent]) -> Result { let mut pos = Position::from_fen(initial_fen).map_err(GameLogError::InvalidFen)?; - for event in events { + for event in net_move_events(events) { let GameEvent::Move { uci, .. } = event else { continue; }; diff --git a/src/game/store.rs b/src/game/store.rs index 388ae73..c7ee4f5 100644 --- a/src/game/store.rs +++ b/src/game/store.rs @@ -27,6 +27,12 @@ pub const MAX_UCI_LEN: usize = 8; /// Hard cap on live event list length for a single reconstruct (DoS bound). pub const MAX_EVENTS: usize = 1024; +/// Meta JSON DoS bound (offers + prev clocks grow the payload; CV-165). +pub const MAX_META_BYTES: usize = 2048; + +/// Single event JSON DoS bound. +pub const MAX_EVENT_BYTES: usize = 512; + /// Errors from game log create / append / replay. #[derive(Debug)] pub enum GameLogError { @@ -158,8 +164,8 @@ pub async fn load_meta( let (meta_key, _) = require_keys(game_id)?; let raw: Option = conn.get(meta_key).await?; let raw = raw.ok_or(GameLogError::GameGone)?; - // Clock fields grew the payload; keep a hard DoS bound. - if raw.len() > 1024 { + // Clock/offer fields grew the payload; keep a hard DoS bound. + if raw.len() > MAX_META_BYTES { return Err(GameLogError::CorruptEvent("meta payload too large".into())); } let meta: GameMeta = @@ -195,29 +201,24 @@ pub async fn save_meta( } let payload = serde_json::to_string(meta).map_err(|err| GameLogError::CorruptEvent(err.to_string()))?; - if payload.len() > 1024 { + if payload.len() > MAX_META_BYTES { return Err(GameLogError::CorruptEvent("meta payload too large".into())); } let _: () = conn.set(meta_key, payload).await?; Ok(()) } -/// Append a Move event; returns the new monotonic `seq` (1-based list length). +/// Append any game event; assigns monotonic `seq` (1-based list length) and returns it. /// +/// Pass `seq: 0` on the event; the stored value is overwritten with the list length. /// Assumes single-writer ownership per game (live match node). Concurrent -/// appenders can race LLEN/RPUSH; CV-162+ can tighten with a Lua script. -pub async fn append_move_event( +/// appenders can race LLEN/RPUSH; CV-171 can tighten with a Lua script. +pub async fn append_game_event( conn: &mut ConnectionManager, game_id: &str, - uci: &str, - ts: u64, + mut event: GameEvent, ) -> Result { let (meta_key, events_key) = require_keys(game_id)?; - if uci.is_empty() || uci.len() > MAX_UCI_LEN { - return Err(GameLogError::InvalidUci(UciError::Invalid)); - } - // Shape-check UCI before storage; callers that need legality use `apply_move`. - let _ = corvin_chess_core::Move::from_uci(uci).map_err(GameLogError::InvalidUci)?; let exists: bool = conn.exists(meta_key).await?; if !exists { return Err(GameLogError::GameGone); @@ -227,13 +228,43 @@ pub async fn append_move_event( return Err(GameLogError::TooManyEvents); } let seq = prev + 1; - let event = GameEvent::move_uci(seq, uci, ts); + set_event_seq(&mut event, seq); let payload = serde_json::to_string(&event).map_err(|err| GameLogError::CorruptEvent(err.to_string()))?; + if payload.len() > MAX_EVENT_BYTES { + return Err(GameLogError::CorruptEvent("event payload too large".into())); + } let new_len: u64 = conn.rpush(events_key, payload).await?; Ok(new_len) } +fn set_event_seq(event: &mut GameEvent, seq: u64) { + match event { + GameEvent::Move { seq: s, .. } + | GameEvent::ServerNote { seq: s, .. } + | GameEvent::Offer { seq: s, .. } + | GameEvent::OfferResponse { seq: s, .. } + | GameEvent::Resign { seq: s, .. } + | GameEvent::Abort { seq: s, .. } + | GameEvent::Takeback { seq: s, .. } => *s = seq, + } +} + +/// Append a Move event; returns the new monotonic `seq` (1-based list length). +pub async fn append_move_event( + conn: &mut ConnectionManager, + game_id: &str, + uci: &str, + ts: u64, +) -> Result { + if uci.is_empty() || uci.len() > MAX_UCI_LEN { + return Err(GameLogError::InvalidUci(UciError::Invalid)); + } + // Shape-check UCI before storage; callers that need legality use `apply_move`. + let _ = corvin_chess_core::Move::from_uci(uci).map_err(GameLogError::InvalidUci)?; + append_game_event(conn, game_id, GameEvent::move_uci(0, uci, ts)).await +} + /// Load all events in order (empty vec when none). Requires meta to exist. pub async fn load_events( conn: &mut ConnectionManager, @@ -251,7 +282,7 @@ pub async fn load_events( let raw: Vec = conn.lrange(events_key, 0, -1).await?; let mut out = Vec::with_capacity(raw.len()); for (idx, line) in raw.iter().enumerate() { - if line.len() > 512 { + if line.len() > MAX_EVENT_BYTES { return Err(GameLogError::CorruptEvent(format!( "index {idx}: event payload too large" ))); diff --git a/tests/offers.rs b/tests/offers.rs new file mode 100644 index 0000000..c2ec6f2 --- /dev/null +++ b/tests/offers.rs @@ -0,0 +1,477 @@ +//! CV-165: Draw / resign / abort / takeback offer state machine (PROTOCOL). + +use std::env; + +use corvin_server::game::{ + abort, abort_allowed, abort_window_ms, apply_move, create_game, delete_game, + game_end_offer_json, load_meta, offer_draw, offer_error_json, offer_state_json, offer_takeback, + reconstruct_fen, resign, respond_offer, GameEndOut, GameMeta, OfferError, OfferOutcome, + OfferRejectCode, OFFER_DRAW, OFFER_TAKEBACK, START_FEN, +}; +use corvin_server::redis_store::connect; + +const WHITE: &str = "player-white-ulid-cv165-00001"; +const BLACK: &str = "player-black-ulid-cv165-00001"; + +fn redis_url() -> Option { + env::var("REDIS_URL") + .ok() + .map(|value| value.trim().to_owned()) + .filter(|value| !value.is_empty()) +} + +fn seated_meta(time_class: &str, clock_ms: u64) -> GameMeta { + GameMeta { + initial_fen: START_FEN.to_owned(), + created_ms: 1_000, + white_id: WHITE.to_owned(), + black_id: BLACK.to_owned(), + clock_w_ms: clock_ms, + clock_b_ms: clock_ms, + increment_ms: 0, + active: "w".to_owned(), + active_started_ms: 1_000, + time_class: time_class.to_owned(), + ..GameMeta::default() + } +} + +#[test] +fn abort_windows_match_adr_005() { + assert_eq!(abort_window_ms("bullet"), 15_000); + assert_eq!(abort_window_ms("blitz"), 20_000); + assert_eq!(abort_window_ms("rapid"), 60_000); + assert_eq!(abort_window_ms("classical"), 60_000); + assert_eq!(abort_window_ms("correspondence"), 60_000); + assert_eq!(abort_window_ms("unknown"), 20_000); +} + +#[test] +fn abort_allowed_zero_or_one_ply_within_window() { + assert!(abort_allowed(0, None, 50_000, "blitz")); + assert!(abort_allowed(1, Some(10_000), 25_000, "blitz")); // 15s < 20s + assert!(!abort_allowed(1, Some(10_000), 35_000, "blitz")); // 25s > 20s + assert!(!abort_allowed(1, None, 11_000, "blitz")); // missing ts with a ply → deny + assert!(!abort_allowed(2, Some(10_000), 11_000, "blitz")); + assert!(abort_allowed(1, Some(10_000), 69_000, "rapid")); // 59s < 60s +} + +#[test] +fn offer_state_and_game_end_json_match_protocol() { + let state = offer_state_json("g1", OFFER_DRAW, "w", "offered", 3, 9); + assert_eq!(state["typ"], "OfferState"); + assert_eq!(state["v"], 1); + assert_eq!(state["offer"], "draw"); + assert_eq!(state["by"], "w"); + assert_eq!(state["status"], "offered"); + assert_eq!(state["seq"], 3); + + let end = game_end_offer_json( + "g1", + &GameEndOut { + result: "1/2-1/2", + winner: None, + reason: "agreement", + seq: 4, + }, + 10, + ); + assert_eq!(end["typ"], "GameEnd"); + assert_eq!(end["result"], "1/2-1/2"); + assert_eq!(end["reason"], "agreement"); + assert!(end["winner"].is_null()); + assert!(end.get("flagged").is_none()); + + let resign_end = game_end_offer_json( + "g1", + &GameEndOut { + result: "0-1", + winner: Some("b"), + reason: "resign", + seq: 2, + }, + 11, + ); + assert_eq!(resign_end["winner"], "b"); + assert_eq!(resign_end["reason"], "resign"); + + let err = offer_error_json(Some("req-1"), OfferRejectCode::AbortDenied, "too late"); + assert_eq!(err["typ"], "Error"); + assert_eq!(err["code"], "ABORT_DENIED"); + assert_eq!(err["id"], "req-1"); +} + +#[test] +fn offer_error_maps_reject_codes() { + assert_eq!( + OfferError::OfferInvalid("x".into()).reject_code(), + OfferRejectCode::OfferInvalid + ); + assert_eq!( + OfferError::AbortDenied("x".into()).reject_code(), + OfferRejectCode::AbortDenied + ); + assert_eq!(OfferError::Auth.reject_code(), OfferRejectCode::Auth); + assert_eq!( + OfferError::GameGone.reject_code(), + OfferRejectCode::GameGone + ); +} + +#[tokio::test] +async fn redis_draw_offer_accept_ends_agreement() { + let Some(url) = redis_url() else { + eprintln!("skip redis_draw_offer_accept_ends_agreement: REDIS_URL unset"); + return; + }; + let mut conn = connect(&url) + .await + .unwrap_or_else(|err| panic!("connect REDIS_URL failed: {err}")); + let game_id = "01CV165DRAW0000000000000001"; + let _ = delete_game(&mut conn, game_id).await; + create_game(&mut conn, game_id, &seated_meta("blitz", 60_000)) + .await + .expect("create"); + + let offered = offer_draw(&mut conn, game_id, WHITE, 2_000) + .await + .expect("offer draw"); + match offered { + OfferOutcome::State(s) => { + assert_eq!(s.offer, OFFER_DRAW); + assert_eq!(s.by, "w"); + assert_eq!(s.status, "offered"); + } + other => panic!("expected OfferState, got {other:?}"), + } + + let meta = load_meta(&mut conn, game_id).await.expect("meta"); + assert_eq!(meta.pending_offer.as_ref().unwrap().kind, OFFER_DRAW); + + let ended = respond_offer(&mut conn, game_id, BLACK, OFFER_DRAW, true, 3_000) + .await + .expect("accept draw"); + match ended { + OfferOutcome::End(e) => { + assert_eq!(e.result, "1/2-1/2"); + assert_eq!(e.reason, "agreement"); + assert!(e.winner.is_none()); + } + other => panic!("expected GameEnd, got {other:?}"), + } + + let meta = load_meta(&mut conn, game_id).await.expect("meta"); + assert!(meta.ended); + assert_eq!(meta.ended_reason.as_deref(), Some("agreement")); + assert!(meta.pending_offer.is_none()); + + let _ = delete_game(&mut conn, game_id).await; +} + +#[tokio::test] +async fn redis_draw_counter_offer_accepts() { + let Some(url) = redis_url() else { + eprintln!("skip redis_draw_counter_offer_accepts: REDIS_URL unset"); + return; + }; + let mut conn = connect(&url) + .await + .unwrap_or_else(|err| panic!("connect REDIS_URL failed: {err}")); + let game_id = "01CV165DRAW0000000000000002"; + let _ = delete_game(&mut conn, game_id).await; + create_game(&mut conn, game_id, &seated_meta("blitz", 60_000)) + .await + .expect("create"); + + offer_draw(&mut conn, game_id, WHITE, 2_000) + .await + .expect("offer"); + let ended = offer_draw(&mut conn, game_id, BLACK, 3_000) + .await + .expect("counter"); + match ended { + OfferOutcome::End(e) => assert_eq!(e.reason, "agreement"), + other => panic!("expected GameEnd, got {other:?}"), + } + let _ = delete_game(&mut conn, game_id).await; +} + +#[tokio::test] +async fn redis_draw_decline_and_withdraw() { + let Some(url) = redis_url() else { + eprintln!("skip redis_draw_decline_and_withdraw: REDIS_URL unset"); + return; + }; + let mut conn = connect(&url) + .await + .unwrap_or_else(|err| panic!("connect REDIS_URL failed: {err}")); + let game_id = "01CV165DRAW0000000000000003"; + let _ = delete_game(&mut conn, game_id).await; + create_game(&mut conn, game_id, &seated_meta("blitz", 60_000)) + .await + .expect("create"); + + offer_draw(&mut conn, game_id, WHITE, 2_000) + .await + .expect("offer"); + let declined = respond_offer(&mut conn, game_id, BLACK, OFFER_DRAW, false, 3_000) + .await + .expect("decline"); + match declined { + OfferOutcome::State(s) => assert_eq!(s.status, "declined"), + other => panic!("expected declined, got {other:?}"), + } + assert!(load_meta(&mut conn, game_id) + .await + .unwrap() + .pending_offer + .is_none()); + + offer_draw(&mut conn, game_id, BLACK, 4_000) + .await + .expect("re-offer"); + let withdrawn = respond_offer(&mut conn, game_id, BLACK, OFFER_DRAW, false, 5_000) + .await + .expect("withdraw"); + match withdrawn { + OfferOutcome::State(s) => assert_eq!(s.status, "withdrawn"), + other => panic!("expected withdrawn, got {other:?}"), + } + + let _ = delete_game(&mut conn, game_id).await; +} + +#[tokio::test] +async fn redis_move_clears_pending_draw() { + let Some(url) = redis_url() else { + eprintln!("skip redis_move_clears_pending_draw: REDIS_URL unset"); + return; + }; + let mut conn = connect(&url) + .await + .unwrap_or_else(|err| panic!("connect REDIS_URL failed: {err}")); + let game_id = "01CV165DRAW0000000000000004"; + let _ = delete_game(&mut conn, game_id).await; + create_game(&mut conn, game_id, &seated_meta("blitz", 60_000)) + .await + .expect("create"); + + offer_draw(&mut conn, game_id, BLACK, 2_000) + .await + .expect("offer"); + apply_move(&mut conn, game_id, WHITE, "e2e4", 3_000) + .await + .expect("move"); + assert!(load_meta(&mut conn, game_id) + .await + .unwrap() + .pending_offer + .is_none()); + + let _ = delete_game(&mut conn, game_id).await; +} + +#[tokio::test] +async fn redis_resign_awards_opponent() { + let Some(url) = redis_url() else { + eprintln!("skip redis_resign_awards_opponent: REDIS_URL unset"); + return; + }; + let mut conn = connect(&url) + .await + .unwrap_or_else(|err| panic!("connect REDIS_URL failed: {err}")); + let game_id = "01CV165RESIGN00000000000001"; + let _ = delete_game(&mut conn, game_id).await; + create_game(&mut conn, game_id, &seated_meta("blitz", 60_000)) + .await + .expect("create"); + + let ended = resign(&mut conn, game_id, WHITE, 2_000) + .await + .expect("resign"); + match ended { + OfferOutcome::End(e) => { + assert_eq!(e.result, "0-1"); + assert_eq!(e.winner, Some("b")); + assert_eq!(e.reason, "resign"); + } + other => panic!("expected GameEnd, got {other:?}"), + } + assert!(load_meta(&mut conn, game_id).await.unwrap().ended); + + let again = resign(&mut conn, game_id, BLACK, 3_000).await; + assert!(matches!(again, Err(OfferError::GameGone))); + + let _ = delete_game(&mut conn, game_id).await; +} + +#[tokio::test] +async fn redis_abort_zero_ply_ok_two_plies_denied() { + let Some(url) = redis_url() else { + eprintln!("skip redis_abort_zero_ply_ok_two_plies_denied: REDIS_URL unset"); + return; + }; + let mut conn = connect(&url) + .await + .unwrap_or_else(|err| panic!("connect REDIS_URL failed: {err}")); + let game_id = "01CV165ABORT000000000000001"; + let _ = delete_game(&mut conn, game_id).await; + create_game(&mut conn, game_id, &seated_meta("blitz", 60_000)) + .await + .expect("create"); + + let ended = abort(&mut conn, game_id, BLACK, 2_000) + .await + .expect("abort at 0 plies"); + match ended { + OfferOutcome::End(e) => { + assert_eq!(e.result, "*"); + assert_eq!(e.reason, "abort"); + assert!(e.winner.is_none()); + } + other => panic!("expected abort GameEnd, got {other:?}"), + } + let _ = delete_game(&mut conn, game_id).await; + + let game_id2 = "01CV165ABORT000000000000002"; + let _ = delete_game(&mut conn, game_id2).await; + create_game(&mut conn, game_id2, &seated_meta("blitz", 60_000)) + .await + .expect("create"); + apply_move(&mut conn, game_id2, WHITE, "e2e4", 2_000) + .await + .expect("e4"); + apply_move(&mut conn, game_id2, BLACK, "e7e5", 3_000) + .await + .expect("e5"); + let denied = abort(&mut conn, game_id2, WHITE, 4_000).await; + assert!(matches!(denied, Err(OfferError::AbortDenied(_)))); + assert_eq!( + denied.unwrap_err().reject_code(), + OfferRejectCode::AbortDenied + ); + + let _ = delete_game(&mut conn, game_id2).await; +} + +#[tokio::test] +async fn redis_abort_one_ply_outside_window_denied() { + let Some(url) = redis_url() else { + eprintln!("skip redis_abort_one_ply_outside_window_denied: REDIS_URL unset"); + return; + }; + let mut conn = connect(&url) + .await + .unwrap_or_else(|err| panic!("connect REDIS_URL failed: {err}")); + let game_id = "01CV165ABORT000000000000003"; + let _ = delete_game(&mut conn, game_id).await; + create_game(&mut conn, game_id, &seated_meta("bullet", 60_000)) + .await + .expect("create"); + apply_move(&mut conn, game_id, WHITE, "e2e4", 10_000) + .await + .expect("e4"); + // Bullet window 15s; claim at +16s. + let denied = abort(&mut conn, game_id, BLACK, 26_000).await; + assert!(matches!(denied, Err(OfferError::AbortDenied(_)))); + + let ok = abort(&mut conn, game_id, BLACK, 20_000).await; + // Fresh game needed — previous denied left game live; retry within window. + // 20_000 - 10_000 = 10s < 15s → allowed. + match ok { + Ok(OfferOutcome::End(e)) => assert_eq!(e.reason, "abort"), + other => panic!("expected abort within window, got {other:?}"), + } + + let _ = delete_game(&mut conn, game_id).await; +} + +#[tokio::test] +async fn redis_takeback_accept_restores_fen_and_clocks() { + let Some(url) = redis_url() else { + eprintln!("skip redis_takeback_accept_restores_fen_and_clocks: REDIS_URL unset"); + return; + }; + let mut conn = connect(&url) + .await + .unwrap_or_else(|err| panic!("connect REDIS_URL failed: {err}")); + let game_id = "01CV165TAKEBACK000000000001"; + let _ = delete_game(&mut conn, game_id).await; + create_game(&mut conn, game_id, &seated_meta("blitz", 60_000)) + .await + .expect("create"); + + apply_move(&mut conn, game_id, WHITE, "e2e4", 5_000) + .await + .expect("e4"); + let after = load_meta(&mut conn, game_id).await.expect("meta"); + assert!(after.clock_w_ms < 60_000); + assert_eq!(after.prev_clock_w_ms, 60_000); + + let no_tb = offer_takeback(&mut conn, game_id, WHITE, 6_000) + .await + .expect("offer takeback"); + match no_tb { + OfferOutcome::State(s) => assert_eq!(s.status, "offered"), + other => panic!("expected offered, got {other:?}"), + } + + let accepted = respond_offer(&mut conn, game_id, BLACK, OFFER_TAKEBACK, true, 7_000) + .await + .expect("accept takeback"); + match accepted { + OfferOutcome::State(s) => { + assert_eq!(s.offer, OFFER_TAKEBACK); + assert_eq!(s.status, "accepted"); + } + other => panic!("expected accepted OfferState, got {other:?}"), + } + + let fen = reconstruct_fen(&mut conn, game_id).await.expect("fen"); + assert_eq!(fen, START_FEN); + let meta = load_meta(&mut conn, game_id).await.expect("meta"); + assert_eq!(meta.clock_w_ms, 60_000); + assert_eq!(meta.clock_b_ms, 60_000); + assert_eq!(meta.active, "w"); + assert!(!meta.ended); + assert!(meta.pending_offer.is_none()); + + // Takeback with zero plies is invalid. + let empty = offer_takeback(&mut conn, game_id, WHITE, 8_000).await; + assert!(matches!(empty, Err(OfferError::OfferInvalid(_)))); + + let _ = delete_game(&mut conn, game_id).await; +} + +#[tokio::test] +async fn redis_offer_rejects_auth_and_invalid() { + let Some(url) = redis_url() else { + eprintln!("skip redis_offer_rejects_auth_and_invalid: REDIS_URL unset"); + return; + }; + let mut conn = connect(&url) + .await + .unwrap_or_else(|err| panic!("connect REDIS_URL failed: {err}")); + let game_id = "01CV165AUTH0000000000000001"; + let _ = delete_game(&mut conn, game_id).await; + create_game(&mut conn, game_id, &seated_meta("blitz", 60_000)) + .await + .expect("create"); + + let auth = offer_draw(&mut conn, game_id, "not-a-player", 1_000).await; + assert!(matches!(auth, Err(OfferError::Auth))); + + let none = respond_offer(&mut conn, game_id, WHITE, OFFER_DRAW, true, 2_000).await; + assert!(matches!(none, Err(OfferError::OfferInvalid(_)))); + + offer_draw(&mut conn, game_id, WHITE, 3_000) + .await + .expect("offer"); + let dup = offer_draw(&mut conn, game_id, WHITE, 4_000).await; + assert!(matches!(dup, Err(OfferError::OfferInvalid(_)))); + + let own = respond_offer(&mut conn, game_id, WHITE, OFFER_DRAW, true, 5_000).await; + assert!(matches!(own, Err(OfferError::OfferInvalid(_)))); + + let _ = delete_game(&mut conn, game_id).await; +}