Skip to main content

meio_connect/server/
mod.rs

1//! Actor for launch a server.
2
3pub mod bind;
4pub mod link;
5pub mod route;
6mod routine;
7pub mod websocket;
8
9pub use bind::WaitForAddress;
10pub use route::{DirectPath, FromRequest, NoParameters, Req, WebRoute};
11pub use websocket::{WsHandler, WsProcessor, WsReq, WsRoute};
12
13use anyhow::Error;
14use async_trait::async_trait;
15use derive_more::From;
16use meio::prelude::{Actor, Address, Context, InterruptedBy, StartedBy};
17use std::net::SocketAddr;
18
19/// The link to a HTTP server instance.
20#[derive(Debug, Clone, From)]
21pub struct HttpServerLink {
22    address: Address<HttpServer>,
23}
24
25/// The actor that binds HTTP server to a port and handle incoming requests.
26pub struct HttpServer {
27    log_target: String,
28    // TODO: Use submodules' types instead
29    // (don't use plain fields from all modules)
30    addr: SocketAddr,
31    addr_state: bind::AddrState,
32    routing_table: route::RoutingTable,
33    /// Interval (seconds) of retry if binding failed.
34    retry_interval: Option<u64>,
35}
36
37impl HttpServer {
38    /// Creates a new server instance.
39    /// It will be bind to `addr` and if binding failed will retry
40    /// to bind again in `retry_interval` seconds.
41    pub fn new(addr: SocketAddr, retry_interval: Option<u64>) -> Self {
42        let log_target = format!("HttpServer::{}", addr);
43        Self {
44            log_target,
45            addr,
46            addr_state: bind::AddrState::default(),
47            routing_table: route::RoutingTable::default(),
48            retry_interval,
49        }
50    }
51}
52
53impl Actor for HttpServer {
54    type GroupBy = ();
55
56    fn log_target(&self) -> &str {
57        &self.log_target
58    }
59}
60
61#[async_trait]
62impl<T: Actor> StartedBy<T> for HttpServer {
63    async fn handle(&mut self, ctx: &mut Context<Self>) -> Result<(), Error> {
64        self.start_http_listener(ctx);
65        Ok(())
66    }
67}
68
69#[async_trait]
70impl<T: Actor> InterruptedBy<T> for HttpServer {
71    async fn handle(&mut self, ctx: &mut Context<Self>) -> Result<(), Error> {
72        ctx.shutdown();
73        Ok(())
74    }
75}
76
77#[cfg(test)]
78mod tests {
79    use serde::Deserialize;
80
81    #[derive(Default, Deserialize)]
82    struct Index {}
83
84    #[test]
85    fn qs_index() {
86        let _index: Index = serde_qs::from_str("").unwrap();
87    }
88
89    #[derive(Default, Deserialize)]
90    struct ApiQuery {
91        query: String,
92    }
93
94    #[test]
95    fn qs_query() {
96        let api_query: ApiQuery = serde_qs::from_str("query=abc").unwrap();
97        assert_eq!(api_query.query, "abc");
98    }
99}