trillium_smol/server/
unix.rs1#[cfg(unix)]
2use crate::SmolUdpSocket;
3use crate::{SmolRuntime, SmolTransport};
4use async_net::{
5 TcpListener, TcpStream,
6 unix::{UnixListener, UnixStream},
7};
8use std::io::Result;
9use trillium::{Info, log_error};
10use trillium_server_common::{
11 Binding::{self, *},
12 Server,
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 Runtime = SmolRuntime;
31 type Transport = Binding<SmolTransport<TcpStream>, SmolTransport<UnixStream>>;
32 type UdpTransport = SmolUdpSocket;
33
34 fn runtime() -> Self::Runtime {
35 SmolRuntime::default()
36 }
37
38 async fn accept(&mut self) -> Result<Self::Transport> {
39 match &self.0 {
40 Tcp(t) => t.accept().await.map(|(t, _)| Tcp(SmolTransport::from(t))),
41 Unix(u) => u.accept().await.map(|(u, _)| Unix(SmolTransport::from(u))),
42 }
43 }
44
45 fn from_tcp(tcp: std::net::TcpListener) -> Self {
46 Self(Tcp(tcp.try_into().unwrap()))
47 }
48
49 fn from_unix(tcp: std::os::unix::net::UnixListener) -> Self {
50 Self(Unix(tcp.try_into().unwrap()))
51 }
52
53 fn init(&self, info: &mut Info) {
54 match &self.0 {
55 Tcp(t) => {
56 if let Ok(socket_addr) = t.local_addr() {
57 info.insert_shared_state(socket_addr);
58 }
59 }
60 Unix(u) => {
61 if let Ok(socket_addr) = u.local_addr() {
62 info.insert_shared_state(socket_addr);
63 }
64 }
65 }
66 }
67
68 async fn clean_up(self) {
69 if let Unix(u) = &self.0
70 && let Ok(local) = u.local_addr()
71 && let Some(path) = local.as_pathname()
72 {
73 log::info!("deleting {:?}", path);
74 log_error!(std::fs::remove_file(path));
75 }
76 }
77}