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
use crate::common::{authentication::Verifier, UnixSocketListener};
use crate::server::{Server, ServerConfig, ServerHandler, UnixSocketServerRef};
use serde::{de::DeserializeOwned, Serialize};
use std::{io, path::Path};

pub struct UnixSocketServerBuilder<T>(Server<T>);

impl<T> Server<T> {
    /// Consume [`Server`] and produce a builder for a Unix socket variant.
    pub fn into_unix_socket_builder(self) -> UnixSocketServerBuilder<T> {
        UnixSocketServerBuilder(self)
    }
}

impl Default for UnixSocketServerBuilder<()> {
    fn default() -> Self {
        Self(Server::new())
    }
}

impl<T> UnixSocketServerBuilder<T> {
    pub fn config(self, config: ServerConfig) -> Self {
        Self(self.0.config(config))
    }

    pub fn handler<U>(self, handler: U) -> UnixSocketServerBuilder<U> {
        UnixSocketServerBuilder(self.0.handler(handler))
    }

    pub fn verifier(self, verifier: Verifier) -> Self {
        Self(self.0.verifier(verifier))
    }
}

impl<T> UnixSocketServerBuilder<T>
where
    T: ServerHandler + Sync + 'static,
    T::Request: DeserializeOwned + Send + Sync + 'static,
    T::Response: Serialize + Send + 'static,
    T::LocalData: Default + Send + Sync + 'static,
{
    pub async fn start<P>(self, path: P) -> io::Result<UnixSocketServerRef>
    where
        P: AsRef<Path> + Send,
    {
        let path = path.as_ref();
        let listener = UnixSocketListener::bind(path).await?;
        let path = listener.path().to_path_buf();
        let inner = self.0.start(listener)?;
        Ok(UnixSocketServerRef { path, inner })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::client::Client;
    use crate::common::{authentication::DummyAuthHandler, Request};
    use crate::server::ServerCtx;
    use async_trait::async_trait;
    use tempfile::NamedTempFile;
    use test_log::test;

    pub struct TestServerHandler;

    #[async_trait]
    impl ServerHandler for TestServerHandler {
        type Request = String;
        type Response = String;
        type LocalData = ();

        async fn on_request(&self, ctx: ServerCtx<Self::Request, Self::Response, Self::LocalData>) {
            // Echo back what we received
            ctx.reply
                .send(ctx.request.payload.to_string())
                .await
                .unwrap();
        }
    }

    #[test(tokio::test)]
    async fn should_invoke_handler_upon_receiving_a_request() {
        // Generate a socket path and delete the file after so there is nothing there
        let path = NamedTempFile::new()
            .expect("Failed to create socket file")
            .path()
            .to_path_buf();

        let server = UnixSocketServerBuilder::default()
            .handler(TestServerHandler)
            .verifier(Verifier::none())
            .start(path)
            .await
            .expect("Failed to start Unix socket server");

        let mut client: Client<String, String> = Client::unix_socket(server.path())
            .auth_handler(DummyAuthHandler)
            .connect()
            .await
            .expect("Client failed to connect");

        let response = client
            .send(Request::new("hello".to_string()))
            .await
            .expect("Failed to send message");
        assert_eq!(response.payload, "hello");
    }
}