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