aboutsummaryrefslogtreecommitdiff
path: root/server/registry/src/main.rs
blob: 670ac3a60498b885b4e24878c57f114c02fc012d (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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
/*
    Hurry Curry! - a game about cooking
    Copyright 2024 metamuffin

    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/>.

*/
pub mod conn_test;
pub mod list;
pub mod register;

use hurrycurry_protocol::registry::Entry;
use list::{generate_html_list, generate_json_list, r_list};
use log::{error, info};
use register::r_register;
use rocket::{get, routes, Config};
use std::{
    cmp::Reverse,
    collections::HashMap,
    env::var,
    net::{IpAddr, Ipv4Addr},
    str::FromStr,
    sync::Arc,
    time::{Duration, Instant},
};
use tokio::{sync::RwLock, time::interval};

const MAX_ADDR_CACHE: usize = 4096;
const MAX_SERVERS: usize = 128;

fn main() {
    env_logger::init_from_env("LOG");
    let registry = Arc::new(RwLock::new(Registry::default()));
    tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        .build()
        .unwrap()
        .block_on(async move {
            tokio::task::spawn(Registry::update_loop(registry.clone()));
            rocket::build()
                .configure(Config {
                    address: var("BIND_ADDR")
                        .map(|a| IpAddr::from_str(&a).unwrap())
                        .unwrap_or(IpAddr::V4(Ipv4Addr::LOCALHOST)),
                    port: var("PORT").map(|p| p.parse().unwrap()).unwrap_or(27033),
                    ..Default::default()
                })
                .manage(registry)
                .mount("/", routes![r_index, r_list, r_register])
                .ignite()
                .await
                .unwrap()
                .launch()
                .await
                .unwrap()
        });
}

#[derive(Default)]
struct Registry {
    json_response: Arc<str>,
    html_response: Arc<str>,
    servers: HashMap<u128, InternalEntry>,
}

impl Registry {
    pub async fn update_loop(r: Arc<RwLock<Self>>) {
        let mut interval = interval(Duration::from_secs(
            var("UPDATE_INTERVAL")
                .map(|e| e.parse::<u64>().unwrap())
                .unwrap_or(60),
        ));
        loop {
            interval.tick().await;
            if let Err(e) = r.write().await.update() {
                error!("update failed: {e}")
            }
        }
    }
    pub fn update(&mut self) -> anyhow::Result<()> {
        info!("updating list");
        self.remove_dead();

        let mut list = self
            .servers
            .values()
            .map(|e| Entry {
                name: e.name.clone(),
                address: e.address.keys().cloned().collect(),
                last_game: e.last_game,
                players_online: e.players_online,
                version: e.version,
            })
            .collect::<Vec<_>>();

        list.sort_by_key(|e| Reverse(e.players_online));

        self.json_response = generate_json_list(&list)?;
        self.html_response = generate_html_list(&list)?;

        info!("done. {} servers registered", self.servers.len());
        Ok(())
    }
    pub fn remove_dead(&mut self) {
        self.servers.retain(|_, e| {
            e.address
                .retain(|_, updated| updated.elapsed() < Duration::from_secs(120));
            e.address.len() > 0
        });
    }
}

#[derive(Debug)]
struct InternalEntry {
    name: String,
    address: HashMap<String, Instant>,
    players_online: usize,
    last_game: i64,
    version: (u32, u32),
}

impl Default for InternalEntry {
    fn default() -> Self {
        Self {
            address: HashMap::new(),
            last_game: 0,
            name: String::new(),
            players_online: 0,
            version: (0, 0),
        }
    }
}

#[get("/")]
fn r_index() -> &'static str {
    "Hurry Curry! Server Registry Service"
}