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