Skip to main content

open_chess_server/
config.rs

1//! Settings, all from the environment (containers on Kubernetes and
2//! Cloudflare both pass configuration that way). Every variable has a
3//! working default except `DATABASE_URL`.
4
5use std::time::Duration;
6
7use anyhow::{Context, Result, bail};
8use clap::Args;
9
10#[derive(Debug, Clone, Args)]
11#[allow(clippy::struct_excessive_bools)] // settings switches
12pub struct Config {
13    /// Postgres URL: this server's database (its own; it may share a host
14    /// site's database in its own schema). A pooled (`-pooler`) host is
15    /// fine; notifications use the direct host automatically.
16    #[arg(long, env = "DATABASE_URL", hide_env_values = true)]
17    pub database_url: String,
18
19    /// A separate URL for LISTEN, if the direct host can't be derived.
20    #[arg(long, env = "CHESS_LISTEN_DATABASE_URL", hide_env_values = true)]
21    pub listen_database_url: Option<String>,
22
23    /// A host site's schema in the same database whose chess players (and
24    /// their chess tokens) are imported once, with their ids, the first
25    /// time this version starts. Nothing is read from it afterwards; a
26    /// schema that isn't there is skipped.
27    #[arg(long, env = "CHESS_SITE_SCHEMA", default_value = "esports")]
28    pub site_schema: String,
29
30    /// This server's own schema (games, challenges, ratings, fair play).
31    #[arg(long, env = "CHESS_SCHEMA", default_value = "chess")]
32    pub schema: String,
33
34    #[arg(long, env = "CHESS_POOL_SIZE", default_value_t = 8)]
35    pub pool_size: usize,
36
37    /// Where clients reach this server, including any path prefix
38    /// (`https://chess.example.com`). Used in game URLs and
39    /// to mount the API under the prefix.
40    #[arg(long, env = "CHESS_PUBLIC_URL", default_value = "http://localhost:8090")]
41    pub public_url: String,
42
43    /// The host site (esports-lab) players can sign in with.
44    #[arg(long, env = "ESPORTS_PUBLIC_URL", default_value = "http://localhost:8080")]
45    pub site_url: String,
46
47    /// "Sign in with the host site" (esports-lab): its players sign in
48    /// here through it, and its server gets tokens for them. Needs
49    /// `ESPORTS_SECRET`. Off by default (the site is private); the
50    /// server's own accounts work either way.
51    #[arg(
52        long,
53        env = "ESPORTS_LOGIN",
54        default_value_t = false,
55        num_args = 0..=1,
56        default_missing_value = "true",
57        action = clap::ArgAction::Set,
58        value_parser = clap::builder::BoolishValueParser::new()
59    )]
60    pub esports_login: bool,
61
62    /// The secret shared with the host site: it signs sign-ins and asks
63    /// for its players' tokens with it (at least 32 characters).
64    #[arg(long, env = "ESPORTS_SECRET", hide_env_values = true)]
65    pub esports_secret: Option<String>,
66
67    /// Anyone may make an account here (a name and a password). Off: only
68    /// accounts that exist (and the host site's players, with
69    /// `ESPORTS_LOGIN`) sign in.
70    #[arg(
71        long,
72        env = "CHESS_SIGNUP",
73        default_value_t = true,
74        num_args = 0..=1,
75        default_missing_value = "true",
76        action = clap::ArgAction::Set,
77        value_parser = clap::builder::BoolishValueParser::new()
78    )]
79    pub signup: bool,
80
81    /// What players know the site as: on the OAuth page, in PGN event
82    /// names and in `GET /` (which the training app shows).
83    #[arg(long, env = "CHESS_SITE_NAME", default_value = "open-chess")]
84    pub site_name: String,
85
86    #[arg(long, env = "CHESS_BIND", default_value = "0.0.0.0:8090")]
87    pub bind: String,
88
89    /// /metrics, /healthz and /readyz.
90    #[arg(long, env = "CHESS_METRICS_BIND", default_value = "0.0.0.0:9465")]
91    pub metrics_bind: String,
92
93    /// Milliseconds given back per move for the network round trip.
94    #[arg(long, env = "CHESS_LAG_COMP_MS", default_value_t = 100)]
95    pub lag_comp_ms: i64,
96
97    /// A real-time challenge lapses after this many seconds unless the
98    /// challenger keeps a `keepAliveStream` open.
99    #[arg(long, env = "CHESS_CHALLENGE_TTL_SECS", default_value_t = 20)]
100    pub challenge_ttl_secs: u64,
101
102    /// Each side's first move must come within this many seconds or the
103    /// game is aborted.
104    #[arg(long, env = "CHESS_FIRST_MOVE_SECS", default_value_t = 30)]
105    pub first_move_secs: u64,
106
107    /// A player with no open game stream for this long is "gone".
108    #[arg(long, env = "CHESS_GONE_AFTER_SECS", default_value_t = 20)]
109    pub gone_after_secs: u64,
110
111    /// Then the opponent may claim the win after this many more seconds.
112    #[arg(long, env = "CHESS_CLAIM_WIN_SECS", default_value_t = 10)]
113    pub claim_win_secs: u64,
114
115    /// The public move stream runs this many plies behind a live game, so
116    /// it can't feed an engine helping a player.
117    #[arg(long, env = "CHESS_PUBLIC_DELAY_PLIES", default_value_t = 3)]
118    pub public_delay_plies: usize,
119
120    /// Queue human players' finished games for fair-play analysis.
121    #[arg(long, env = "CHESS_FAIRPLAY", default_value_t = true, action = clap::ArgAction::Set)]
122    pub fairplay: bool,
123
124    /// Accounts marked for engine use can't start new games.
125    #[arg(long, env = "CHESS_BLOCK_MARKED", default_value_t = true, action = clap::ArgAction::Set)]
126    pub block_marked: bool,
127
128    /// How often the clock sweeper looks for flags and lapsed challenges.
129    #[arg(long, env = "CHESS_SWEEP_MS", default_value_t = 500)]
130    pub sweep_ms: u64,
131
132    /// Reading boards from photos: base URL of a vision model behind an
133    /// OpenAI-style `/chat/completions` (Claude via
134    /// `https://api.anthropic.com/v1`, Qwen-VL via Ollama's
135    /// `http://localhost:11434/v1`, or a gateway). Empty: photo reading is
136    /// off.
137    #[arg(long, env = "CHESS_VISION_ENDPOINT", default_value = "")]
138    pub vision_endpoint: String,
139
140    /// The vision model's name as that server knows it.
141    #[arg(long, env = "CHESS_VISION_MODEL", default_value = "qwen3-vl:8b")]
142    pub vision_model: String,
143
144    /// Bearer token for the vision server, if it needs one.
145    #[arg(long, env = "CHESS_VISION_API_KEY", hide_env_values = true)]
146    pub vision_api_key: Option<String>,
147
148    /// Our own board reader (chess-vision): a `.safetensors` weights file
149    /// from `chess-vision-train`. It reads photos first, on this
150    /// server's CPU; the vision model at CHESS_VISION_ENDPOINT (if set) is
151    /// only asked about photos it isn't sure of. Empty: not used.
152    #[arg(long, env = "CHESS_VISION_LOCAL_MODEL", default_value = "")]
153    pub vision_local_model: String,
154
155    /// The board reader's answer is used without review when every square
156    /// is above its unsure threshold and the chance that all 64 are right
157    /// is at least this.
158    #[arg(long, env = "CHESS_VISION_MIN_CONFIDENCE", default_value_t = 0.5)]
159    pub vision_min_confidence: f32,
160
161    /// Keep photos that couldn't be read for sure for the Review page,
162    /// where a person confirms the position; confirmed photos become
163    /// training data (`open-chess photos export`). Players are told.
164    #[arg(long, env = "CHESS_VISION_REVIEW", default_value_t = true, action = clap::ArgAction::Set)]
165    pub vision_review: bool,
166
167    /// At most this many photos wait for review; beyond it, new ones
168    /// aren't kept.
169    #[arg(long, env = "CHESS_VISION_REVIEW_MAX", default_value_t = 5000)]
170    pub vision_review_max: i64,
171
172    /// Where exact endgame results (up to seven pieces) come from: a
173    /// Lichess-compatible tablebase server. Answers are kept in the
174    /// database, so each position is fetched once. Empty: off.
175    #[arg(long, env = "CHESS_TABLEBASE_URL", default_value = "https://tablebase.lichess.ovh")]
176    pub tablebase_url: String,
177
178    /// The built training app (web/chess plus its wasm engine), served at
179    /// `/app/`. The chess image puts it at /usr/share/open-chess/app.
180    #[arg(long, env = "CHESS_APP_DIR")]
181    pub app_dir: Option<String>,
182
183    /// The app's look for this deployment: CSS (or the path of a .css file)
184    /// served as `/app/theme.css`, after the app's own styles, so it can set
185    /// the app's colour and font variables (docs/api.md, "The Chess lab's
186    /// look").
187    #[arg(long, env = "CHESS_APP_THEME")]
188    pub app_theme: Option<String>,
189}
190
191impl Config {
192    /// The path the API lives under (`/chess`, or empty).
193    pub fn base_path(&self) -> Result<String> {
194        let u = url::Url::parse(&self.public_url).context("CHESS_PUBLIC_URL isn't a URL")?;
195        let p = u.path().trim_end_matches('/');
196        Ok(p.to_owned())
197    }
198
199    pub fn public_url(&self) -> &str {
200        self.public_url.trim_end_matches('/')
201    }
202
203    /// The secret shared with the host site, when signing in with it is on.
204    pub fn esports(&self) -> Option<&str> {
205        self.esports_secret.as_deref().filter(|s| self.esports_login && s.len() >= 32)
206    }
207
208    pub fn challenge_ttl(&self) -> Duration {
209        Duration::from_secs(self.challenge_ttl_secs.max(5))
210    }
211
212    pub fn validate(&self) -> Result<()> {
213        for s in [&self.schema, &self.site_schema] {
214            if s.is_empty() || !s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
215                bail!("schema names are letters, digits and _ (got {s:?})");
216            }
217        }
218        if self.schema == self.site_schema {
219            bail!("CHESS_SCHEMA must differ from CHESS_SITE_SCHEMA");
220        }
221        self.base_path()?;
222        Ok(())
223    }
224}
225
226/// Settings for the fair-play worker (`open-chess analyse`).
227#[derive(Debug, Clone, Args)]
228pub struct AnalyseConfig {
229    /// The UCI engine (Stockfish).
230    #[arg(long, env = "CHESS_STOCKFISH")]
231    pub stockfish: Option<String>,
232
233    /// Search depth per position.
234    #[arg(long, env = "CHESS_ANALYSIS_DEPTH", default_value_t = 14)]
235    pub depth: u32,
236
237    /// Engine threads.
238    #[arg(long, env = "CHESS_ANALYSIS_THREADS", default_value_t = 1)]
239    pub threads: u32,
240
241    /// Engine hash, MiB.
242    #[arg(long, env = "CHESS_ANALYSIS_HASH_MB", default_value_t = 64)]
243    pub hash_mb: u32,
244
245    /// Plies at the start left out of screening (opening theory).
246    #[arg(long, env = "CHESS_FAIRPLAY_SKIP_PLIES", default_value_t = 16)]
247    pub skip_plies: usize,
248
249    /// The screening model: how the fair-play signals turn into a score
250    /// and a flag (`chess_fairplay::Model`, as JSON). Either a path to a
251    /// JSON file or the JSON itself (handy as a secret). Keep a tuned
252    /// model private: its numbers tell people what screening looks for.
253    /// Unset: an untuned example model, and a warning.
254    #[arg(long, env = "CHESS_FAIRPLAY_MODEL", hide_env_values = true)]
255    pub model: Option<String>,
256
257    /// Overrides the model's flag score (0–100).
258    #[arg(long, env = "CHESS_FAIRPLAY_FLAG_SCORE")]
259    pub flag_score: Option<f64>,
260
261    /// Overrides the model's fewest screened moves before a game can be
262    /// flagged.
263    #[arg(long, env = "CHESS_FAIRPLAY_MIN_MOVES")]
264    pub min_moves: Option<usize>,
265
266    /// The training app's engine settings, for the app fingerprint (the
267    /// app's "Normal" search). Keep in step with web/chess/app.js.
268    #[arg(long, env = "CHESS_FAIRPLAY_APP_DEPTH", default_value_t = 6)]
269    pub app_depth: u8,
270
271    #[arg(long, env = "CHESS_FAIRPLAY_APP_NODES", default_value_t = 400_000)]
272    pub app_nodes: u64,
273
274    /// The NNUE weight file the app ships (web/chess/nets/default.nnue),
275    /// if it ships one, so the fingerprint uses the same evaluation.
276    #[arg(long, env = "CHESS_FAIRPLAY_APP_NET")]
277    pub app_net: Option<String>,
278
279    /// Analyse one game and exit (for testing).
280    #[arg(long)]
281    pub once: bool,
282}
283
284impl AnalyseConfig {
285    /// The screening model: `CHESS_FAIRPLAY_MODEL` (a JSON file or inline
286    /// JSON), else the untuned example, with any overrides applied.
287    /// Returns whether a model was configured, so callers can warn.
288    pub fn model(&self) -> Result<(chess_fairplay::Model, bool)> {
289        let (mut model, configured) = match self.model.as_deref().map(str::trim) {
290            None | Some("") => (chess_fairplay::Model::default(), false),
291            Some(json) if json.starts_with('{') => {
292                (serde_json::from_str(json).context("CHESS_FAIRPLAY_MODEL isn't a valid model")?, true)
293            }
294            Some(path) => {
295                let text = std::fs::read_to_string(path)
296                    .with_context(|| format!("reading the fair-play model {path}"))?;
297                (serde_json::from_str(&text).with_context(|| format!("{path} isn't a valid model"))?, true)
298            }
299        };
300        if let Some(s) = self.flag_score {
301            model.flag_score = s;
302        }
303        if let Some(n) = self.min_moves {
304            model.min_moves = n;
305        }
306        model.validate().map_err(|e| anyhow::anyhow!("fair-play model: {e}"))?;
307        Ok((model, configured))
308    }
309}