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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
/*!
  mpsc with requests

  # Examples

  ```
  use mrsc;
  use std::thread;

  let server: mrsc::Server<u32, String> = mrsc::Server::new();
  let channel = server.pop();

  thread::spawn(move || {
      let req = server.recv().unwrap();
      let reply = {
          let msg = req.get();
          assert_eq!(msg, &123);
          "world".to_string()
      };
      req.reply(reply).unwrap();
  });

  let response = channel.req(123).unwrap();
  let reply = response.recv().unwrap();
  assert_eq!(reply, "world".to_string());
*/

use std::sync::mpsc;
use std::time::Duration;

type Sender<T, R> = mpsc::Sender<Request<T, R>>;
type InternalReceiver<T, R> = mpsc::Receiver<Request<T, R>>;
type Receiver<R> = mpsc::Receiver<R>;

pub type SendError<R, T> = mpsc::SendError<Request<R, T>>;
pub type RecvError = mpsc::RecvError;
pub type TryRecvError = mpsc::TryRecvError;
pub type RecvTimeoutError = mpsc::RecvTimeoutError;

/// The server that receives requests and creates channels
#[derive(Debug)]
pub struct Server<T, R> {
    tx: Sender<T, R>,
    rx: InternalReceiver<T, R>,
}

impl<T, R> Server<T, R> {
    /// Create a new server.
    ///
    /// # Examples
    ///
    /// ```
    /// use mrsc;
    ///
    /// let server: mrsc::Server<u32, String> = mrsc::Server::new();
    pub fn new() -> Server<T, R> {
        let (tx, rx) = mpsc::channel();
        Server {
            tx,
            rx,
        }
    }

    /// Request a new channel for a worker thread.
    ///
    /// A channel can safely be cloned without calling pop() for every worker.
    ///
    /// # Examples
    ///
    /// ```
    /// use mrsc;
    ///
    /// let server: mrsc::Server<u32, String> = mrsc::Server::new();
    /// let channel = server.pop();
    pub fn pop(&self) -> Channel<T, R> {
        Channel {
            tx: self.tx.clone(),
        }
    }

    /// Receive a request from a worker thread.
    ///
    /// # Examples
    ///
    /// ```
    /// use mrsc;
    ///
    /// let server: mrsc::Server<u32, String> = mrsc::Server::new();
    ///
    /// let channel = server.pop();
    /// // send request
    /// let response = channel.req(123).unwrap();
    ///
    /// // receive request
    /// let req = server.recv().unwrap();
    pub fn recv(&self) -> Result<Request<T, R>, RecvError> {
        self.rx.recv()
    }

    pub fn try_recv(&self) -> Result<Request<T, R>, TryRecvError> {
        self.rx.try_recv()
    }

    pub fn recv_timeout(&self, timeout: Duration) -> Result<Request<T, R>, RecvTimeoutError> {
        self.rx.recv_timeout(timeout)
    }
}

/// A channel to the server that can be used to send requests
#[derive(Debug, Clone)]
pub struct Channel<T, R> {
    tx: Sender<T, R>,
}

impl<T, R> Channel<T, R> {
    /// Sends a new request to the server.
    ///
    /// # Examples
    ///
    /// ```
    /// use mrsc;
    ///
    /// let server: mrsc::Server<u32, String> = mrsc::Server::new();
    ///
    /// let channel = server.pop();
    /// channel.req(123).unwrap();
    pub fn req(&self, payload: T) -> Result<Response<R>, SendError<T, R>> {
        let (tx, rx) = mpsc::channel();
        self.tx.send(Request {
            tx,
            payload
        })?;

        Ok(Response {
            rx: rx
        })
    }
}

/// The request as seen by the server thread
#[derive(Debug)]
pub struct Request<T, R> {
    tx: mpsc::Sender<R>,
    payload: T,
}

impl<T, R> Request<T, R> {
    /// Returns a reference to the request payload.
    pub fn get(&self) -> &T {
        &self.payload
    }

    /// Returns the payload and an EmptyRequest, consumes the Request.
    pub fn take(self) -> (EmptyRequest<R>, T) {
        (EmptyRequest {
            tx: self.tx,
        }, self.payload)
    }

    /// Reply to the request with a response. This consumes the request.
    ///
    /// # Examples
    ///
    /// ```
    /// use mrsc;
    ///
    /// let server: mrsc::Server<u32, String> = mrsc::Server::new();
    ///
    /// let channel = server.pop();
    /// // send request
    /// let response = channel.req(123).unwrap();
    ///
    /// // answer request
    /// let req = server.recv().unwrap();
    /// req.reply("hello world".to_string()).unwrap();
    pub fn reply(self, response: R) -> Result<(), mpsc::SendError<R>> {
        self.tx.send(response)
    }
}

/// A request without payload
#[derive(Debug)]
pub struct EmptyRequest<R> {
    tx: mpsc::Sender<R>,
}

impl<R> EmptyRequest<R> {
    /// Reply to the request with a response. This consumes the request.
    ///
    /// # Examples
    ///
    /// ```
    /// use mrsc;
    ///
    /// let server: mrsc::Server<u32, String> = mrsc::Server::new();
    ///
    /// let channel = server.pop();
    /// // send request
    /// let response = channel.req(123).unwrap();
    ///
    /// // answer request
    /// let req = server.recv().unwrap();
    /// let (req, payload) = req.take();
    /// req.reply("hello world".to_string()).unwrap();
    pub fn reply(self, response: R) -> Result<(), mpsc::SendError<R>> {
        self.tx.send(response)
    }
}

/// The response returned to an request
#[derive(Debug)]
pub struct Response<R> {
    rx: Receiver<R>,
}

impl<R> Response<R> {
    /// Receives the response from the server. Blocks until the request has been answered.
    /// Since there is only one response to each request this consumes the Response.
    /// This operation is blocking.
    ///
    /// # Examples
    ///
    /// ```
    /// use mrsc;
    ///
    /// let server: mrsc::Server<u32, String> = mrsc::Server::new();
    ///
    /// let channel = server.pop();
    /// // send request
    /// let response = channel.req(123).unwrap();
    ///
    /// // answer request
    /// server.recv().unwrap().reply("hello world".to_string()).unwrap();
    ///
    /// // receive result
    /// response.recv().unwrap();
    pub fn recv(self) -> Result<R, RecvError> {
        self.rx.recv()
    }

    pub fn try_recv(&self) -> Result<R, TryRecvError> {
        self.rx.try_recv()
    }

    pub fn recv_timeout(&self, timeout: Duration) -> Result<R, RecvTimeoutError> {
        self.rx.recv_timeout(timeout)
    }
}


#[cfg(test)]
mod tests {
    use super::Server;
    use std::thread;
    use std::time::Duration;

    #[test]
    fn readme() {
        let server: Server<u32, String> = Server::new();
        let channel = server.pop();

        thread::spawn(move || {
            let req = server.recv().unwrap();
            let reply = {
                let msg = req.get();
                println!("request: {:?}", msg);

                "hello world".to_string()
            };
            req.reply(reply).unwrap();
        });

        let response = channel.req(123).unwrap();
        let reply = response.recv().unwrap();
        println!("response: {:?}", reply);
    }

    #[test]
    fn single_requester() {
        let server: Server<u32, String> = Server::new();
        let channel = server.pop();

        thread::spawn(move || {
            for i in &[1, 2, 3] {
                let req = server.recv().unwrap();
                assert_eq!(req.get(), i);
                req.reply(format!("success: {}", i)).unwrap();
            }
        });

        let response = channel.req(1).unwrap();
        let reply = response.recv().unwrap();
        assert_eq!(reply, "success: 1".to_string());

        let response = channel.req(2).unwrap();
        let reply = response.recv().unwrap();
        assert_eq!(reply, "success: 2".to_string());

        let response = channel.req(3).unwrap();
        let reply = response.recv().unwrap();
        assert_eq!(reply, "success: 3".to_string());
    }

    #[test]
    fn take() {
        let server: Server<u32, String> = Server::new();
        let channel = server.pop();

        thread::spawn(move || {
            for i in &[1] {
                let req = server.recv().unwrap();
                let (req, payload) = req.take();
                assert_eq!(&payload, i);
                req.reply(format!("success: {}", i)).unwrap();
            }
        });

        let response = channel.req(1).unwrap();
        let reply = response.recv().unwrap();
        assert_eq!(reply, "success: 1".to_string());
    }

    #[test]
    fn try_recv() {
        let server: Server<u32, u32> = Server::new();
        let channel = server.pop();

        assert!(server.try_recv().is_err());
        let response = channel.req(1).unwrap();
        assert!(response.try_recv().is_err());

        let req = server.try_recv().unwrap();
        let (req, value) = req.take();
        req.reply(value + 2).unwrap();

        let result = response.recv().unwrap();
        assert_eq!(result, 3);
    }

    #[test]
    fn recv_timeout() {
        let server: Server<u32, u32> = Server::new();
        let channel = server.pop();

        let duration = Duration::from_secs(1);

        assert!(server.recv_timeout(duration.clone()).is_err());
        let response = channel.req(1).unwrap();
        assert!(response.recv_timeout(duration.clone()).is_err());

        let req = server.recv_timeout(duration.clone()).unwrap();
        let (req, value) = req.take();
        req.reply(value + 2).unwrap();

        let result = response.recv().unwrap();
        assert_eq!(result, 3);
    }
}