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