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
179
180
use crate::{
    channel::{Context, OnTo, Target},
    core::{spawn, UnimplementedError},
    format::{ApplyDecode, ApplyEncode, Format},
    kind::{Fallible, Future, Infallible, SinkStream, TransportError},
    object, Kind,
};

use anyhow::Error;
use futures::{future::ready, lock::Mutex, FutureExt, Sink, StreamExt};
use std::{net::SocketAddr, sync::Arc};
use thiserror::Error;
use url::Url;

#[object]
pub trait Peer {}

#[derive(Error, Debug, Kind)]
pub enum ConnectError {
    #[error("connection failed: {0}")]
    Connect(#[source] Error),
    #[error("construct failed: {0}")]
    Construct(#[source] Error),
    #[error("underlying transport failed: {0}")]
    Transport(#[from] TransportError),
}

#[derive(Error, Debug, Kind)]
#[error("listening failed: {cause}")]
pub struct ListenError {
    #[source]
    cause: Error,
}

impl From<TransportError> for ListenError {
    fn from(error: TransportError) -> Self {
        ListenError {
            cause: error.into(),
        }
    }
}

#[derive(Error, Debug, Kind)]
#[error("connection failed while open: {cause}")]
pub struct ConnectionError {
    #[source]
    cause: Error,
}

impl From<TransportError> for ConnectionError {
    fn from(error: TransportError) -> Self {
        ConnectionError {
            cause: error.into(),
        }
    }
}

#[object]
pub(crate) trait RawClient {
    fn connect(
        &mut self,
        address: Url,
    ) -> Fallible<SinkStream<Vec<u8>, ConnectionError, Vec<u8>>, ConnectError>;
}

#[derive(Kind)]
pub struct Client(Box<dyn RawClient>);

impl Client {
    pub fn new() -> Result<Client, UnimplementedError> {
        RawClient::new().map(Client)
    }
    pub fn connect<
        'a,
        K: Kind,
        T: Target<'a, K> + 'static,
        F: Format<Representation = Vec<u8>> + 'static,
    >(
        &mut self,
        address: Url,
    ) -> Fallible<K, ConnectError> {
        let connection = self.0.connect(address);
        Box::pin(async move {
            connection
                .await?
                .decode::<T, F>()
                .await
                .map_err(|e| ConnectError::Construct(e.into()))
        })
    }
}

#[object]
pub(crate) trait RawServer {
    fn listen(
        &mut self,
        address: SocketAddr,
        handler: Box<
            dyn FnMut(SinkStream<Vec<u8>, ConnectionError, Vec<u8>>) -> Infallible<()>
                + Sync
                + Send,
        >,
    ) -> Fallible<(), ListenError>;
}

#[derive(Kind)]
pub struct Server(Box<dyn RawServer>);

impl Server {
    pub fn new() -> Result<Server, UnimplementedError> {
        RawServer::new().map(Server)
    }
    pub fn listen<
        'a,
        K: Kind,
        T: Target<'a, K> + 'static,
        F: Format<Representation = Vec<u8>> + 'static,
    >(
        &mut self,
        address: SocketAddr,
        handler: Box<dyn FnMut() -> Future<K> + Sync + Send>,
    ) -> Fallible<(), ListenError>
    where
        T: ApplyEncode<'a>,
        <T as Sink<<T as Context<'a>>::Item>>::Error: std::error::Error + Sync + Send + 'static,
    {
        let handler = Arc::new(Mutex::new(handler));
        self.0.listen(
            address,
            Box::new(move |channel| {
                let handler = handler.clone();
                Box::pin(async move {
                    let (sender, receiver) = channel.split();
                    let (sink, stream) = (handler.lock().await.as_mut())()
                        .await
                        .on_to::<T>()
                        .await
                        .encode::<F>()
                        .split();
                    spawn(stream.map(Ok).forward(sender).then(|_| ready(())));
                    spawn(receiver.map(Ok).forward(sink).then(|_| ready(())));
                    Ok(())
                })
            }),
        )
    }
}

#[cfg(all(not(target_arch = "wasm32"), feature = "core"))]
mod native;
#[cfg(all(target_arch = "wasm32", feature = "core"))]
mod web;

impl dyn RawClient {
    fn new() -> Result<Box<dyn RawClient>, UnimplementedError> {
        #[cfg(all(target_arch = "wasm32", feature = "core"))]
        return Ok(web::Client::new());
        #[cfg(all(not(target_arch = "wasm32"), feature = "core"))]
        return Ok(native::Client::new());
        #[cfg(not(feature = "core"))]
        return Err(UnimplementedError {
            feature: "a network client".to_owned(),
        });
    }
}

impl dyn RawServer {
    fn new() -> Result<Box<dyn RawServer>, UnimplementedError> {
        #[cfg(all(target_arch = "wasm32", feature = "core"))]
        return Err(UnimplementedError {
            feature: "a network server".to_owned(),
        });
        #[cfg(all(not(target_arch = "wasm32"), feature = "core"))]
        return Ok(native::Server::new());
        #[cfg(not(feature = "core"))]
        return Err(UnimplementedError {
            feature: "a network server".to_owned(),
        });
    }
}