Skip to main content

open_chess_server/
app.rs

1//! The shared context, and the HTTP server's routes.
2
3use std::collections::HashMap;
4use std::sync::{Arc, Mutex};
5
6use axum::Router;
7use axum::extract::{FromRequestParts, Request, State};
8use axum::http::{HeaderValue, Method, StatusCode, header, request::Parts};
9use axum::middleware::{self, Next};
10use axum::response::{IntoResponse, Response};
11use axum::routing::{get, post};
12
13use crate::auth::{Auth, Identity, bearer};
14use crate::config::Config;
15use crate::db::Db;
16use crate::error::ApiError;
17use crate::http;
18use crate::metrics::Metrics;
19
20#[derive(Clone)]
21pub struct Ctx {
22    pub db: Db,
23    pub cfg: Arc<Config>,
24    pub auth: Auth,
25    pub metrics: Metrics,
26    /// Our board reader, when CHESS_VISION_LOCAL_MODEL names one.
27    pub reader: Option<Arc<chess_vision::Reader>>,
28    slots: Arc<Mutex<HashMap<(i64, &'static str), usize>>>,
29}
30
31/// Open streams a player may hold on one replica, by kind.
32const STREAM_LIMITS: &[(&str, usize)] = &[("event", 8), ("game", 40), ("challenge", 20)];
33
34/// One open stream of a player's; frees its slot when dropped.
35pub struct Slot {
36    slots: Arc<Mutex<HashMap<(i64, &'static str), usize>>>,
37    key: (i64, &'static str),
38}
39
40impl Drop for Slot {
41    fn drop(&mut self) {
42        if let Ok(mut m) = self.slots.lock()
43            && let Some(n) = m.get_mut(&self.key)
44        {
45            *n = n.saturating_sub(1);
46            if *n == 0 {
47                m.remove(&self.key);
48            }
49        }
50    }
51}
52
53impl Ctx {
54    pub fn new(db: Db, cfg: Config) -> Ctx {
55        Ctx {
56            auth: Auth::new(db.clone()),
57            db,
58            cfg: Arc::new(cfg),
59            metrics: Metrics::new(),
60            reader: None,
61            slots: Arc::default(),
62        }
63    }
64
65    /// Load the board reader CHESS_VISION_LOCAL_MODEL names, if any.
66    pub fn with_reader(mut self) -> anyhow::Result<Ctx> {
67        if let Some(r) = crate::vision::load_reader(&self.cfg)? {
68            let card = r.card();
69            tracing::info!(
70                model = card.name,
71                version = card.version,
72                licence = card.licence,
73                internal_only = card.internal_only,
74                size = r.config().image_size,
75                "board reader loaded"
76            );
77            self.reader = Some(Arc::new(r));
78        }
79        Ok(self)
80    }
81
82    /// Take a stream slot for `player`, or refuse with 429 (as Lichess does
83    /// when one account opens too many streams).
84    pub fn slot(&self, player: i64, kind: &'static str) -> Result<Slot, ApiError> {
85        let limit = STREAM_LIMITS.iter().find(|(k, _)| *k == kind).map_or(10, |(_, n)| *n);
86        let mut m = self.slots.lock().map_err(|_| ApiError::too_many("try again"))?;
87        let n = m.entry((player, kind)).or_insert(0);
88        if *n >= limit {
89            return Err(ApiError::too_many(format!("Too many open {kind} streams for this account")));
90        }
91        *n += 1;
92        Ok(Slot { slots: Arc::clone(&self.slots), key: (player, kind) })
93    }
94
95    /// Milliseconds each side has for a first move.
96    pub fn first_move_ms(&self) -> i64 {
97        i64::try_from(self.cfg.first_move_secs * 1000).unwrap_or(i64::MAX)
98    }
99}
100
101/// A caller with a valid bearer token.
102pub struct Who(pub Identity);
103
104impl FromRequestParts<Ctx> for Who {
105    type Rejection = ApiError;
106
107    async fn from_request_parts(parts: &mut Parts, ctx: &Ctx) -> Result<Who, ApiError> {
108        let t = bearer(&parts.headers).ok_or_else(ApiError::unauthorized)?;
109        match ctx.auth.token(t).await? {
110            Some(id) => Ok(Who(id)),
111            None => Err(ApiError::unauthorized()),
112        }
113    }
114}
115
116impl Who {
117    /// The token must carry one of `scopes`.
118    pub fn need(&self, scopes: &[&str]) -> Result<&Identity, ApiError> {
119        if self.0.has_any(scopes) { Ok(&self.0) } else { Err(ApiError::missing_scope(scopes)) }
120    }
121}
122
123/// Lichess answers API calls from any origin (tokens, not cookies, carry
124/// the identity), so browsers' preflights get a yes.
125async fn cors(req: Request, next: Next) -> Response {
126    let preflight = req.method() == Method::OPTIONS;
127    let mut resp = if preflight { StatusCode::NO_CONTENT.into_response() } else { next.run(req).await };
128    let h = resp.headers_mut();
129    h.insert(header::ACCESS_CONTROL_ALLOW_ORIGIN, HeaderValue::from_static("*"));
130    if preflight {
131        h.insert(
132            header::ACCESS_CONTROL_ALLOW_METHODS,
133            HeaderValue::from_static("GET, POST, DELETE, OPTIONS"),
134        );
135        h.insert(
136            header::ACCESS_CONTROL_ALLOW_HEADERS,
137            HeaderValue::from_static("Authorization, Content-Type"),
138        );
139        h.insert(header::ACCESS_CONTROL_MAX_AGE, HeaderValue::from_static("86400"));
140    }
141    resp
142}
143
144pub fn router(ctx: &Ctx) -> anyhow::Result<Router> {
145    use http::{account, app_files, challenges, fairplay, feed, games, lab, oauth, streams, web};
146    let api = Router::new()
147        // OAuth (PKCE) and tokens
148        .route("/oauth", get(oauth::authorize).post(oauth::decide))
149        .route("/login", get(web::login_page).post(web::login))
150        .route("/signup", get(web::signup_page).post(web::signup))
151        .route("/logout", post(web::logout))
152        .route("/account", get(web::account))
153        .route("/account/tokens", post(web::new_token))
154        .route("/account/tokens/revoke", post(web::revoke_token))
155        .route("/auth/esports", get(web::esports_start))
156        .route("/auth/esports/back", get(web::esports_back))
157        .route("/api/esports/token", post(web::esports_token))
158        .route("/api/esports/revoke", post(web::esports_revoke))
159        .route("/api/esports/players", get(web::esports_players))
160        .route("/api/esports/link", post(web::esports_link))
161        .route("/api/feed", get(feed::feed))
162        .route("/api/token", post(oauth::token).delete(oauth::revoke))
163        .route("/api/token/test", post(oauth::test))
164        // account and users
165        .route("/api/account", get(account::me))
166        .route("/api/account/email", get(account::email))
167        .route("/api/account/playing", get(account::playing))
168        .route("/api/user/{username}", get(account::user))
169        .route("/api/player/autocomplete", get(account::autocomplete))
170        .route("/api/bot/account/upgrade", post(account::upgrade))
171        .route("/api/bot/online", get(account::bots_online))
172        // streams
173        .route("/api/stream/event", get(streams::events))
174        .route("/api/board/game/stream/{id}", get(streams::board_game))
175        .route("/api/bot/game/stream/{id}", get(streams::bot_game))
176        .route("/api/stream/game/{id}", get(streams::moves))
177        // challenges
178        .route("/api/challenge", get(challenges::list))
179        .route("/api/challenge/ai", post(challenges::ai))
180        .route("/api/challenge/{id}", post(challenges::create))
181        .route("/api/challenge/{id}/show", get(challenges::show))
182        .route("/api/challenge/{id}/accept", post(challenges::accept))
183        .route("/api/challenge/{id}/decline", post(challenges::decline))
184        .route("/api/challenge/{id}/cancel", post(challenges::cancel))
185        // playing: Board API (people) and Bot API (bot accounts)
186        .merge(play_routes("board"))
187        .merge(play_routes("bot"))
188        // games
189        .route("/game/export/{id}", get(games::export))
190        .route("/api/games/export/{id}", get(games::export))
191        // fair play (our own, for reviewers)
192        .route("/api/fairplay/queue", get(fairplay::queue))
193        .route("/api/fairplay/games/{id}", get(fairplay::game))
194        .route("/api/fairplay/players/{username}", get(fairplay::player))
195        .route("/api/fairplay/reviews", post(fairplay::review))
196        // our additions for the training app
197        .route("/api/board/game/{id}/assist", post(lab::assist))
198        .route("/api/esl/position", get(lab::position).post(lab::position_hint))
199        .route("/api/esl/position/moves", get(lab::position_moves))
200        .route("/api/esl/tablebase", get(lab::tablebase))
201        // Photos are sent as base64: allow up to 10 MB.
202        .route(
203            "/api/esl/recognise",
204            post(lab::recognise).layer(axum::extract::DefaultBodyLimit::max(10 * 1024 * 1024)),
205        )
206        .route("/api/esl/photos/{id}/confirm", post(lab::confirm_photo))
207        .route("/api/esl/photo-terms", get(lab::photo_terms).post(lab::set_photo_terms))
208        .route("/api/esl/photos", get(lab::photos))
209        .route("/api/esl/photos/{id}/image", get(lab::photo_image))
210        .route("/api/esl/photos/{id}/label", post(lab::label_photo))
211        // the training app (static files)
212        .route("/app", get(app_files::bare))
213        .route("/app/", get(app_files::index))
214        .route("/app/theme.css", get(app_files::theme))
215        .route("/app/{*path}", get(app_files::file))
216        .route("/docs", get(http::docs))
217        .route("/docs/", get(http::docs))
218        .route("/docs/{guide}", get(http::docs))
219        .route("/favicon.svg", get(http::favicon))
220        .route("/favicon.ico", get(http::favicon))
221        .route("/", get(http::index))
222        .layer(middleware::from_fn(cors))
223        .with_state(ctx.clone());
224    let base = ctx.cfg.base_path()?;
225    Ok(if base.is_empty() { api } else { Router::new().nest(&base, api) })
226}
227
228/// The same actions under /api/board and /api/bot (the handler tells them
229/// apart by the matched path).
230fn play_routes(api: &str) -> Router<Ctx> {
231    use http::play;
232    let p = |tail: &str| format!("/api/{api}/game/{{id}}/{tail}");
233    Router::new()
234        .route(&p("move/{uci}"), post(play::make_move))
235        .route(&p("resign"), post(play::resign))
236        .route(&p("abort"), post(play::abort))
237        .route(&p("draw/{accept}"), post(play::draw))
238        .route(&p("takeback/{accept}"), post(play::takeback))
239        .route(&p("claim-victory"), post(play::claim_victory))
240        .route(&p("claim-draw"), post(play::claim_draw))
241        .route(&p("chat"), post(play::chat_post).get(play::chat_get))
242}
243
244/// /metrics, /healthz and /readyz, on their own port.
245pub fn ops_router(ctx: Ctx) -> Router {
246    Router::new()
247        .route("/metrics", get(|State(c): State<Ctx>| async move { c.metrics.render() }))
248        .route("/healthz", get(|| async { "ok" }))
249        .route(
250            "/readyz",
251            get(|State(c): State<Ctx>| async move {
252                match c.db.conn().await {
253                    Ok(conn) if conn.simple_query("SELECT 1").await.is_ok() => (StatusCode::OK, "ready"),
254                    _ => (StatusCode::SERVICE_UNAVAILABLE, "database unavailable"),
255                }
256            }),
257        )
258        .with_state(ctx)
259}