Skip to main content

open_chess_server/
lib.rs

1//! The open-chess server, as a library (the `open-chess` binary is a
2//! thin wrapper; integration tests drive the same pieces).
3
4pub mod ai;
5pub mod analyse;
6pub mod app;
7pub mod auth;
8pub mod challenges;
9pub mod cli;
10pub mod config;
11pub mod db;
12pub mod error;
13pub mod http;
14pub mod metrics;
15pub mod model;
16pub mod passkeys;
17pub mod play;
18pub mod vision;
19
20use std::time::Duration;
21
22use tokio::sync::watch;
23use tracing::warn;
24
25/// Resolves once shutdown has begun (the watch guard isn't held, so the
26/// future stays `Send`).
27pub async fn stopped(stop: &mut watch::Receiver<bool>) {
28    let _ = stop.wait_for(|v| *v).await.map(drop);
29}
30
31/// What every serving replica runs besides HTTP: the LISTEN connection
32/// that brings other replicas' changes in, and the clock/challenge
33/// sweeper (rows are claimed with SKIP LOCKED, so replicas don't collide).
34pub fn spawn_background(ctx: &app::Ctx, stop: &watch::Receiver<bool>) {
35    tokio::spawn(ctx.db.clone().listen((*ctx.cfg).clone(), stop.clone()));
36    tokio::spawn(ai::run(ctx.clone(), stop.clone()));
37    let sweeper = ctx.clone();
38    let mut stop_sweep = stop.clone();
39    tokio::spawn(async move {
40        let mut t = tokio::time::interval(Duration::from_millis(sweeper.cfg.sweep_ms.max(100)));
41        t.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
42        loop {
43            tokio::select! {
44                _ = t.tick() => {
45                    if let Err(e) = play::sweep(&sweeper).await {
46                        warn!("sweeper: {e:#}");
47                    }
48                }
49                () = stopped(&mut stop_sweep) => break,
50            }
51        }
52    });
53}