trillium_smol/server/
unix.rs

1use crate::SmolTransport;
2use async_global_executor::{block_on, spawn};
3use async_net::{
4    unix::{UnixListener, UnixStream},
5    TcpListener, TcpStream,
6};
7use futures_lite::prelude::*;
8use std::{env, io::Result, pin::Pin};
9use trillium::{log_error, Info};
10use trillium_server_common::{
11    Binding::{self, *},
12    Server, Stopper,
13};
14
15#[derive(Debug, Clone)]
16pub struct SmolServer(Binding<TcpListener, UnixListener>);
17impl From<TcpListener> for SmolServer {
18    fn from(value: TcpListener) -> Self {
19        Self(Tcp(value))
20    }
21}
22impl From<UnixListener> for SmolServer {
23    fn from(value: UnixListener) -> Self {
24        Self(Unix(value))
25    }
26}
27
28#[cfg(unix)]
29impl Server for SmolServer {
30    type Transport = Binding<SmolTransport<TcpStream>, SmolTransport<UnixStream>>;
31    const DESCRIPTION: &'static str = concat!(
32        " (",
33        env!("CARGO_PKG_NAME"),
34        " v",
35        env!("CARGO_PKG_VERSION"),
36        ")"
37    );
38
39    fn handle_signals(stop: Stopper) -> Pin<Box<dyn Future<Output = ()> + Send + 'static>> {
40        Box::pin(async move {
41            use async_signal::{Signal, Signals};
42            let mut signals = Signals::new([Signal::Int, Signal::Term, Signal::Quit]).unwrap();
43            while let Some(signal) = signals.next().await {
44                if stop.is_stopped() {
45                    eprintln!("\nSecond signal ({signal:?}), shutting down harshly");
46                    signal_hook::low_level::emulate_default_handler(signal.unwrap() as i32)
47                        .unwrap();
48                } else {
49                    println!("\nShutting down gracefully.\nControl-C again to force.");
50                    stop.stop();
51                }
52            }
53        })
54    }
55
56    fn accept(&mut self) -> Pin<Box<dyn Future<Output = Result<Self::Transport>> + Send + '_>> {
57        Box::pin(async move {
58            match &self.0 {
59                Tcp(t) => t.accept().await.map(|(t, _)| Tcp(SmolTransport::from(t))),
60                Unix(u) => u.accept().await.map(|(u, _)| Unix(SmolTransport::from(u))),
61            }
62        })
63    }
64
65    fn listener_from_tcp(tcp: std::net::TcpListener) -> Self {
66        Self(Tcp(tcp.try_into().unwrap()))
67    }
68
69    fn listener_from_unix(tcp: std::os::unix::net::UnixListener) -> Self {
70        Self(Unix(tcp.try_into().unwrap()))
71    }
72
73    fn info(&self) -> Info {
74        match &self.0 {
75            Tcp(t) => t.local_addr().unwrap().into(),
76            Unix(u) => u.local_addr().unwrap().into(),
77        }
78    }
79
80    fn spawn(fut: impl Future<Output = ()> + Send + 'static) {
81        spawn(fut).detach();
82    }
83
84    fn block_on(fut: impl Future<Output = ()> + 'static) {
85        block_on(fut)
86    }
87
88    fn clean_up(self) -> Pin<Box<dyn Future<Output = ()> + Send + 'static>> {
89        Box::pin(async move {
90            if let Unix(u) = &self.0 {
91                if let Ok(local) = u.local_addr() {
92                    if let Some(path) = local.as_pathname() {
93                        log::info!("deleting {:?}", &path);
94                        log_error!(std::fs::remove_file(path));
95                    }
96                }
97            }
98        })
99    }
100}