aboutsummaryrefslogtreecommitdiff
path: root/server/registry/src/conn_test.rs
blob: bc371a1043a4b465448ac9a2d5bb11a25fb4eccd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/*
    Hurry Curry! - a game about cooking
    Copyright (C) 2025 Hurry Curry! Contributors

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, version 3 of the License only.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

*/
use anyhow::{Context, Result, bail};
use hurrycurry_game_core::network::tokio::Network;
use hurrycurry_protocol::PacketC;
use log::info;
use std::{
    collections::BTreeMap,
    net::SocketAddr,
    time::{Duration, Instant},
};
use tokio::{
    net::TcpStream,
    sync::{RwLock, Semaphore},
    time::{sleep, timeout},
};

#[derive(Debug, Clone, Copy)]
struct ConnectTest {
    verified_at: Instant,
    version: (u32, u32),
}

static CONNECT_OK: RwLock<BTreeMap<SocketAddr, ConnectTest>> = RwLock::const_new(BTreeMap::new());
static CONNECT_SEMAPHORE: Semaphore = Semaphore::const_new(10);

pub(crate) async fn prune_connect_cache_task() {
    loop {
        sleep(Duration::from_secs(600)).await;
        CONNECT_OK
            .write()
            .await
            .retain(|_, v| v.verified_at.elapsed().as_secs() < 3600);
    }
}

pub(crate) async fn test_connect(addr: SocketAddr, uri: &str) -> Result<(u32, u32), &'static str> {
    let r = CONNECT_OK.read().await.get(&addr).copied();
    if let Some(r) = r {
        Ok(r.version)
    } else {
        // TODO locks to prevent parallel tests for same addr and dos attempts
        let _permit = CONNECT_SEMAPHORE.acquire().await;
        let res = timeout(Duration::from_secs(10), test_connect_inner(addr, uri))
            .await
            .map_err(|_| "connect timeout")?;
        info!("connect result: {res:?}");
        drop(_permit);

        let version = res.map_err(|_| "server unreachable")?;
        let mut g = CONNECT_OK.write().await;
        g.insert(
            addr,
            ConnectTest {
                verified_at: Instant::now(),
                version,
            },
        );
        Ok(version)
    }
}

async fn test_connect_inner(addr: SocketAddr, uri: &str) -> Result<(u32, u32)> {
    info!("test connect {addr} {uri:?}");
    let stream = TcpStream::connect(addr).await.context("connect")?;
    let net = Network::connect_raw(stream, uri).await.context("upgrade")?;
    let packet = net.receive().await.context("receive")?;
    match packet {
        Some(PacketC::Version { minor, major, .. }) => Ok((major, minor)),
        _ => bail!("bad initial packet"),
    }
}