~starkingdoms/starkingdoms

ref: 71ce7ed846f05352b63458d4a63a97cca36169dd starkingdoms/server/src/main.rs -rw-r--r-- 7.4 KiB
71ce7ed8 — c0repwn3r spritesheets 2 years ago
                                                                                
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
use std::convert::Infallible;
use std::net::SocketAddr;
use std::sync::Arc;
use hyper::{Body, header, Request, Response, Server, server::conn::AddrStream, StatusCode, upgrade};
use hyper::service::{make_service_fn, service_fn};
use tokio_tungstenite::WebSocketStream;
use tungstenite::{handshake};
use futures::stream::StreamExt;
use lazy_static::lazy_static;
use log::{error, info, Level};
use serde::{Deserialize, Serialize};
use tokio::sync::RwLock;
use starkingdoms_protocol::{PROTOCOL_VERSION};
use crate::manager::{ClientHandler, ClientManager, PhysicsEngine};
use crate::handler::handle_client;
use crate::timer::timer_main;

pub mod handler;
pub mod manager;
pub mod timer;
#[macro_use]
pub mod macros;

async fn handle_request(mut request: Request<Body>, remote_addr: SocketAddr, mgr: ClientManager) -> Result<Response<Body>, Infallible> {
    match (request.uri().path(), request.headers().contains_key(header::UPGRADE)) {
        //if the request is ws_echo and the request headers contains an Upgrade key
        ("/ws", true) => {
            info!("received connection from {}", remote_addr);
            //assume request is a handshake, so create the handshake response
            let response =
                match handshake::server::create_response_with_body(&request, Body::empty) {
                    Ok(response) => {
                        //in case the handshake response creation succeeds,
                        //spawn a task to handle the websocket connection
                        tokio::spawn(async move {
                            //using the hyper feature of upgrading a connection
                            match upgrade::on(&mut request).await {
                                //if successfully upgraded
                                Ok(upgraded) => {
                                    info!("[{}] connection upgraded", remote_addr);
                                    //create a websocket stream from the upgraded object
                                    let ws_stream = WebSocketStream::from_raw_socket(
                                        //pass the upgraded object
                                        //as the base layer stream of the Websocket
                                        upgraded,
                                        tokio_tungstenite::tungstenite::protocol::Role::Server,
                                        None,
                                    ).await;

                                    //we can split the stream into a sink and a stream
                                    let (ws_write, ws_read) = ws_stream.split();

                                    let (tx, rx) = tokio::sync::mpsc::channel(128);

                                    let client = ClientHandler {
                                        tx,
                                    };

                                    // Acquire the write lock in a small scope, so it's dropped as quickly as possible
                                    {
                                        mgr.handlers.write().await.insert(remote_addr, client);
                                    }

                                    info!("[{}] passing to client handler", remote_addr);

                                    //forward the stream to the sink to achieve echo
                                    match handle_client(mgr.clone(), remote_addr, rx, ws_write, ws_read).await {
                                        Ok(_) => {},
                                        Err(e) => error!("error on WS connection {}: {}", remote_addr, e),
                                    };

                                    // clean up values left over
                                    {
                                        mgr.handlers.write().await.remove(&remote_addr);
                                        mgr.usernames.write().await.remove(&remote_addr);
                                    }
                                },
                                Err(e) => {
                                    error!("error upgrading connection from {} to WS: {}", remote_addr, e);
                                }
                            }
                        });
                        //return the response to the handshake request
                        response
                    },
                    Err(e) => {
                        //probably the handshake request is not up to spec for websocket
                        error!("error creating websocket response to {}: {}", remote_addr, e);
                        let mut res = Response::new(Body::from(format!("Failed to create websocket: {}", e)));
                        *res.status_mut() = StatusCode::BAD_REQUEST;
                        return Ok(res);
                    }
                };

            Ok::<_, Infallible>(response)
        },
        ("/ws", false) => {
            Ok(Response::builder().status(400).body(Body::from("Connection-Upgrade header missing")).unwrap())
        },
        ("/ping", false) => {
            Ok(Response::builder().status(200).header("Access-Control-Allow-Origin", "*").body(Body::from(
                serde_json::to_string(&ServerPingResponse {
                    version: ServerPingResponseVersion {
                        name: env!("STK_VERSION_NAME").to_string(), // Set by build.rs
                        number: env!("STK_VERSION").to_string(), // Set by build.rs
                        protocol: PROTOCOL_VERSION,
                    },
                    players: CMGR.usernames.read().await.len() as u32,
                    description: env!("STK_SLP_DESCRIPTION").to_string(),
                }).unwrap()
            )).unwrap())
        },
        (_url, false) => {
            // typical HTTP file request
            // TODO
            Ok(Response::new(Body::empty()))
        },
        (_, true) => {
            // http upgrade on non-/ws endpoint
            Ok(Response::builder().status(400).body(Body::from("Incorrect WebSocket endpoint")).unwrap())
        }
    }
}

lazy_static! {
    static ref CMGR: ClientManager = ClientManager {
        handlers: Arc::new(RwLock::new(Default::default())),
        usernames: Arc::new(RwLock::new(Default::default())),
        players: Arc::new(RwLock::new(Default::default())),
    };
}

#[tokio::main]
async fn main() {
    simple_logger::init_with_level(Level::Debug).expect("Unable to start logging service");

    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));

    info!("Listening on {} for HTTP/WebSocket connections", addr);

    let make_svc = make_service_fn(|conn: &AddrStream| {
        let remote_addr = conn.remote_addr();

        async move {
            Ok::<_, Infallible>(service_fn({
                move |request: Request<Body>| {
                    handle_request(request, remote_addr, CMGR.clone())
                }
            }))
        }
    });


    let mgr_timer = CMGR.clone();
    let _timer_thread = tokio::spawn(async move {
        timer_main(mgr_timer).await;
    });

    let server = Server::bind(&addr).serve(make_svc);

    if let Err(e) = server.await {
        error!("error in server thread: {}", e);
    }
}

#[derive(Serialize, Deserialize)]
pub struct ServerPingResponse {
    pub version: ServerPingResponseVersion,
    pub players: u32,
    pub description: String
}

#[derive(Serialize, Deserialize)]
pub struct ServerPingResponseVersion {
    pub name: String,
    pub number: String,
    pub protocol: u32
}