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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
#[macro_use]
extern crate log;
use futures_util::StreamExt;
use std::future::Future;
use std::io;
use tokio::net::ToSocketAddrs;
use tokio::net::{TcpListener, TcpStream};
use tokio::sync::mpsc;
use tokio::sync::mpsc::Sender;
use tokio_tungstenite::WebSocketStream;
use tungstenite::Message;

pub struct WsEndpoint<T, F> {
    processor: fn(T) -> F,
    sync: bool,
}

impl<F: 'static + Future<Output = Option<String>> + Send> WsEndpoint<String, F> {
    pub fn new_async_text_endpoint(processor: fn(String) -> F) -> WsEndpoint<String, F> {
        WsEndpoint {
            processor,
            sync: false,
        }
    }

    pub fn new_sync_text_endpoint(processor: fn(String) -> F) -> WsEndpoint<String, F> {
        WsEndpoint {
            processor,
            sync: true,
        }
    }

    pub async fn start<A: ToSocketAddrs>(self, addr: A) -> io::Result<()> {
        let mut listener = TcpListener::bind(addr).await?;

        loop {
            info!("Accepting new clients...");
            let incoming = listener.accept().await;
            match incoming {
                Ok((socket, _)) => {
                    tokio::spawn(serve_text_client(socket, self.processor, self.sync));
                }
                Err(e) => {
                    error!("Error accepting client connection: {}", e);
                }
            }
        }
    }
}

impl<F: 'static + Future<Output = Option<Vec<u8>>> + Send> WsEndpoint<Vec<u8>, F> {
    pub fn new_async_binary_endpoint(processor: fn(Vec<u8>) -> F) -> WsEndpoint<Vec<u8>, F> {
        WsEndpoint {
            processor,
            sync: false,
        }
    }

    pub fn new_sync_binary_endpoint(processor: fn(Vec<u8>) -> F) -> WsEndpoint<Vec<u8>, F> {
        WsEndpoint {
            processor,
            sync: true,
        }
    }

    pub async fn start<A: ToSocketAddrs>(self, addr: A) -> io::Result<()> {
        let mut listener = TcpListener::bind(addr).await?;

        loop {
            info!("Accepting new clients...");
            let incoming = listener.accept().await;
            match incoming {
                Ok((socket, _)) => {
                    tokio::spawn(serve_binary_client(socket, self.processor, self.sync));
                }
                Err(e) => {
                    error!("Error accepting client connection: {}", e);
                }
            }
        }
    }
}

async fn serve_text_client<F: 'static + Future<Output = Option<String>> + Send>(
    socket: TcpStream,
    processor: fn(String) -> F,
    sync: bool,
) {
    match tokio_tungstenite::accept_async(socket).await {
        Ok(ws_stream) => {
            process_text_stream(ws_stream, processor, sync).await;
        }
        Err(e) => error!("Error during the websocket handshake occurred: {}", e),
    }
}

async fn serve_binary_client<F: 'static + Future<Output = Option<Vec<u8>>> + Send>(
    socket: TcpStream,
    processor: fn(Vec<u8>) -> F,
    sync: bool,
) {
    match tokio_tungstenite::accept_async(socket).await {
        Ok(ws_stream) => {
            process_binary_stream(ws_stream, processor, sync).await;
        }
        Err(e) => error!("Error during the websocket handshake occurred: {}", e),
    }
}

async fn process_text_stream<F: 'static + Future<Output = Option<String>> + Send>(
    ws_stream: WebSocketStream<TcpStream>,
    processor: fn(String) -> F,
    sync: bool,
) {
    let (write, mut read) = ws_stream.split();

    let (response_tx, response_rx): (Sender<Option<String>>, _) = mpsc::channel(100);

    tokio::spawn(
        response_rx
            .filter_map(|e| async { e.map(|r| Ok(Message::from(r))) })
            .forward(write),
    );

    while let Some(input) = read.next().await {
        match input {
            Ok(input) => {
                if input.is_text() {
                    process_text_request(input, response_tx.clone(), processor, sync).await;
                }
            }
            Err(e) => error!("Error receiving WS message: {}", e),
        }
    }
}

async fn process_binary_stream<F: 'static + Future<Output = Option<Vec<u8>>> + Send>(
    ws_stream: WebSocketStream<TcpStream>,
    processor: fn(Vec<u8>) -> F,
    sync: bool,
) {
    let (write, mut read) = ws_stream.split();

    let (response_tx, response_rx): (Sender<Option<Vec<u8>>>, _) = mpsc::channel(100);

    tokio::spawn(
        response_rx
            .filter_map(|e| async { e.map(|r| Ok(Message::from(r))) })
            .forward(write),
    );

    while let Some(input) = read.next().await {
        match input {
            Ok(input) => {
                dbg!(&input);
                if input.is_binary() {
                    process_binary_request(input, response_tx.clone(), processor, sync).await;
                }
            }
            Err(e) => error!("Error receiving WS message: {}", e),
        }
    }
}

async fn process_text_request<F: 'static + Future<Output = Option<String>> + Send>(
    msg: Message,
    response_tx: Sender<Option<String>>,
    processor: fn(String) -> F,
    sync: bool,
) {
    match msg.into_text() {
        Ok(request) => {
            if sync {
                do_process(request, processor, response_tx).await;
            } else {
                tokio::spawn(do_process(request, processor, response_tx));
            }
        }
        Err(e) => {
            error!("Error converting message to text: {}", e);
            return;
        }
    }
}

async fn process_binary_request<F: 'static + Future<Output = Option<Vec<u8>>> + Send>(
    msg: Message,
    response_tx: Sender<Option<Vec<u8>>>,
    processor: fn(Vec<u8>) -> F,
    sync: bool,
) {
    let request = msg.into_data();
    if sync {
        do_process(request, processor, response_tx).await;
    } else {
        tokio::spawn(do_process(request, processor, response_tx));
    }
}

async fn do_process<T: 'static, F: 'static + Future<Output = Option<T>> + Send>(
    msg: T,
    process: fn(T) -> F,
    response_tx: Sender<Option<T>>,
) {
    let mut response_tx = response_tx;
    let response = process(msg).await;
    if let Err(e) = response_tx.send(response).await {
        error!("Error sending response to WS: {}", e);
    }
}