peer.rs

  1use crate::proto::{self, AnyTypedEnvelope, EnvelopedMessage, MessageStream, RequestMessage};
  2use anyhow::{anyhow, Context, Result};
  3use async_lock::{Mutex, RwLock};
  4use async_tungstenite::tungstenite::{Error as WebSocketError, Message as WebSocketMessage};
  5use futures::{FutureExt, StreamExt};
  6use postage::{
  7    mpsc,
  8    prelude::{Sink as _, Stream as _},
  9};
 10use std::{
 11    collections::HashMap,
 12    fmt,
 13    future::Future,
 14    marker::PhantomData,
 15    sync::{
 16        atomic::{self, AtomicU32},
 17        Arc,
 18    },
 19};
 20
 21#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
 22pub struct ConnectionId(pub u32);
 23
 24impl fmt::Display for ConnectionId {
 25    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 26        self.0.fmt(f)
 27    }
 28}
 29
 30#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
 31pub struct PeerId(pub u32);
 32
 33impl fmt::Display for PeerId {
 34    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 35        self.0.fmt(f)
 36    }
 37}
 38
 39pub struct Receipt<T> {
 40    pub sender_id: ConnectionId,
 41    pub message_id: u32,
 42    payload_type: PhantomData<T>,
 43}
 44
 45impl<T> Clone for Receipt<T> {
 46    fn clone(&self) -> Self {
 47        Self {
 48            sender_id: self.sender_id,
 49            message_id: self.message_id,
 50            payload_type: PhantomData,
 51        }
 52    }
 53}
 54
 55impl<T> Copy for Receipt<T> {}
 56
 57pub struct TypedEnvelope<T> {
 58    pub sender_id: ConnectionId,
 59    pub original_sender_id: Option<PeerId>,
 60    pub message_id: u32,
 61    pub payload: T,
 62}
 63
 64impl<T> TypedEnvelope<T> {
 65    pub fn original_sender_id(&self) -> Result<PeerId> {
 66        self.original_sender_id
 67            .ok_or_else(|| anyhow!("missing original_sender_id"))
 68    }
 69}
 70
 71impl<T: RequestMessage> TypedEnvelope<T> {
 72    pub fn receipt(&self) -> Receipt<T> {
 73        Receipt {
 74            sender_id: self.sender_id,
 75            message_id: self.message_id,
 76            payload_type: PhantomData,
 77        }
 78    }
 79}
 80
 81pub struct Peer {
 82    connections: RwLock<HashMap<ConnectionId, Connection>>,
 83    next_connection_id: AtomicU32,
 84}
 85
 86#[derive(Clone)]
 87struct Connection {
 88    outgoing_tx: mpsc::Sender<proto::Envelope>,
 89    next_message_id: Arc<AtomicU32>,
 90    response_channels: Arc<Mutex<HashMap<u32, mpsc::Sender<proto::Envelope>>>>,
 91}
 92
 93impl Peer {
 94    pub fn new() -> Arc<Self> {
 95        Arc::new(Self {
 96            connections: Default::default(),
 97            next_connection_id: Default::default(),
 98        })
 99    }
100
101    pub async fn add_connection<Conn>(
102        self: &Arc<Self>,
103        conn: Conn,
104    ) -> (
105        ConnectionId,
106        impl Future<Output = anyhow::Result<()>> + Send,
107        mpsc::Receiver<Box<dyn AnyTypedEnvelope>>,
108    )
109    where
110        Conn: futures::Sink<WebSocketMessage, Error = WebSocketError>
111            + futures::Stream<Item = Result<WebSocketMessage, WebSocketError>>
112            + Send
113            + Unpin,
114    {
115        let (tx, rx) = conn.split();
116        let connection_id = ConnectionId(
117            self.next_connection_id
118                .fetch_add(1, atomic::Ordering::SeqCst),
119        );
120        let (mut incoming_tx, incoming_rx) = mpsc::channel(64);
121        let (outgoing_tx, mut outgoing_rx) = mpsc::channel(64);
122        let connection = Connection {
123            outgoing_tx,
124            next_message_id: Default::default(),
125            response_channels: Default::default(),
126        };
127        let mut writer = MessageStream::new(tx);
128        let mut reader = MessageStream::new(rx);
129
130        let response_channels = connection.response_channels.clone();
131        let handle_io = async move {
132            loop {
133                let read_message = reader.read_message().fuse();
134                futures::pin_mut!(read_message);
135                loop {
136                    futures::select_biased! {
137                        incoming = read_message => match incoming {
138                            Ok(incoming) => {
139                                if let Some(responding_to) = incoming.responding_to {
140                                    let channel = response_channels.lock().await.remove(&responding_to);
141                                    if let Some(mut tx) = channel {
142                                        tx.send(incoming).await.ok();
143                                    } else {
144                                        log::warn!("received RPC response to unknown request {}", responding_to);
145                                    }
146                                } else {
147                                    if let Some(envelope) = proto::build_typed_envelope(connection_id, incoming) {
148                                        if incoming_tx.send(envelope).await.is_err() {
149                                            response_channels.lock().await.clear();
150                                            return Ok(())
151                                        }
152                                    } else {
153                                        log::error!("unable to construct a typed envelope");
154                                    }
155                                }
156
157                                break;
158                            }
159                            Err(error) => {
160                                response_channels.lock().await.clear();
161                                Err(error).context("received invalid RPC message")?;
162                            }
163                        },
164                        outgoing = outgoing_rx.recv().fuse() => match outgoing {
165                            Some(outgoing) => {
166                                if let Err(result) = writer.write_message(&outgoing).await {
167                                    response_channels.lock().await.clear();
168                                    Err(result).context("failed to write RPC message")?;
169                                }
170                            }
171                            None => {
172                                response_channels.lock().await.clear();
173                                return Ok(())
174                            }
175                        }
176                    }
177                }
178            }
179        };
180
181        self.connections
182            .write()
183            .await
184            .insert(connection_id, connection);
185
186        (connection_id, handle_io, incoming_rx)
187    }
188
189    pub async fn disconnect(&self, connection_id: ConnectionId) {
190        self.connections.write().await.remove(&connection_id);
191    }
192
193    pub async fn reset(&self) {
194        self.connections.write().await.clear();
195    }
196
197    pub fn request<T: RequestMessage>(
198        self: &Arc<Self>,
199        receiver_id: ConnectionId,
200        request: T,
201    ) -> impl Future<Output = Result<T::Response>> {
202        self.request_internal(None, receiver_id, request)
203    }
204
205    pub fn forward_request<T: RequestMessage>(
206        self: &Arc<Self>,
207        sender_id: ConnectionId,
208        receiver_id: ConnectionId,
209        request: T,
210    ) -> impl Future<Output = Result<T::Response>> {
211        self.request_internal(Some(sender_id), receiver_id, request)
212    }
213
214    pub fn request_internal<T: RequestMessage>(
215        self: &Arc<Self>,
216        original_sender_id: Option<ConnectionId>,
217        receiver_id: ConnectionId,
218        request: T,
219    ) -> impl Future<Output = Result<T::Response>> {
220        let this = self.clone();
221        let (tx, mut rx) = mpsc::channel(1);
222        async move {
223            let mut connection = this.connection(receiver_id).await?;
224            let message_id = connection
225                .next_message_id
226                .fetch_add(1, atomic::Ordering::SeqCst);
227            connection
228                .response_channels
229                .lock()
230                .await
231                .insert(message_id, tx);
232            connection
233                .outgoing_tx
234                .send(request.into_envelope(message_id, None, original_sender_id.map(|id| id.0)))
235                .await
236                .map_err(|_| anyhow!("connection was closed"))?;
237            let response = rx
238                .recv()
239                .await
240                .ok_or_else(|| anyhow!("connection was closed"))?;
241            if let Some(proto::envelope::Payload::Error(error)) = &response.payload {
242                Err(anyhow!("request failed").context(error.message.clone()))
243            } else {
244                T::Response::from_envelope(response)
245                    .ok_or_else(|| anyhow!("received response of the wrong type"))
246            }
247        }
248    }
249
250    pub fn send<T: EnvelopedMessage>(
251        self: &Arc<Self>,
252        receiver_id: ConnectionId,
253        message: T,
254    ) -> impl Future<Output = Result<()>> {
255        let this = self.clone();
256        async move {
257            let mut connection = this.connection(receiver_id).await?;
258            let message_id = connection
259                .next_message_id
260                .fetch_add(1, atomic::Ordering::SeqCst);
261            connection
262                .outgoing_tx
263                .send(message.into_envelope(message_id, None, None))
264                .await?;
265            Ok(())
266        }
267    }
268
269    pub fn forward_send<T: EnvelopedMessage>(
270        self: &Arc<Self>,
271        sender_id: ConnectionId,
272        receiver_id: ConnectionId,
273        message: T,
274    ) -> impl Future<Output = Result<()>> {
275        let this = self.clone();
276        async move {
277            let mut connection = this.connection(receiver_id).await?;
278            let message_id = connection
279                .next_message_id
280                .fetch_add(1, atomic::Ordering::SeqCst);
281            connection
282                .outgoing_tx
283                .send(message.into_envelope(message_id, None, Some(sender_id.0)))
284                .await?;
285            Ok(())
286        }
287    }
288
289    pub fn respond<T: RequestMessage>(
290        self: &Arc<Self>,
291        receipt: Receipt<T>,
292        response: T::Response,
293    ) -> impl Future<Output = Result<()>> {
294        let this = self.clone();
295        async move {
296            let mut connection = this.connection(receipt.sender_id).await?;
297            let message_id = connection
298                .next_message_id
299                .fetch_add(1, atomic::Ordering::SeqCst);
300            connection
301                .outgoing_tx
302                .send(response.into_envelope(message_id, Some(receipt.message_id), None))
303                .await?;
304            Ok(())
305        }
306    }
307
308    pub fn respond_with_error<T: RequestMessage>(
309        self: &Arc<Self>,
310        receipt: Receipt<T>,
311        response: proto::Error,
312    ) -> impl Future<Output = Result<()>> {
313        let this = self.clone();
314        async move {
315            let mut connection = this.connection(receipt.sender_id).await?;
316            let message_id = connection
317                .next_message_id
318                .fetch_add(1, atomic::Ordering::SeqCst);
319            connection
320                .outgoing_tx
321                .send(response.into_envelope(message_id, Some(receipt.message_id), None))
322                .await?;
323            Ok(())
324        }
325    }
326
327    fn connection(
328        self: &Arc<Self>,
329        connection_id: ConnectionId,
330    ) -> impl Future<Output = Result<Connection>> {
331        let this = self.clone();
332        async move {
333            let connections = this.connections.read().await;
334            let connection = connections
335                .get(&connection_id)
336                .ok_or_else(|| anyhow!("no such connection: {}", connection_id))?;
337            Ok(connection.clone())
338        }
339    }
340}
341
342#[cfg(test)]
343mod tests {
344    use super::*;
345    use crate::{test, TypedEnvelope};
346
347    #[test]
348    fn test_request_response() {
349        smol::block_on(async move {
350            // create 2 clients connected to 1 server
351            let server = Peer::new();
352            let client1 = Peer::new();
353            let client2 = Peer::new();
354
355            let (client1_to_server_conn, server_to_client_1_conn) = test::Channel::bidirectional();
356            let (client1_conn_id, io_task1, _) =
357                client1.add_connection(client1_to_server_conn).await;
358            let (_, io_task2, incoming1) = server.add_connection(server_to_client_1_conn).await;
359
360            let (client2_to_server_conn, server_to_client_2_conn) = test::Channel::bidirectional();
361            let (client2_conn_id, io_task3, _) =
362                client2.add_connection(client2_to_server_conn).await;
363            let (_, io_task4, incoming2) = server.add_connection(server_to_client_2_conn).await;
364
365            smol::spawn(io_task1).detach();
366            smol::spawn(io_task2).detach();
367            smol::spawn(io_task3).detach();
368            smol::spawn(io_task4).detach();
369            smol::spawn(handle_messages(incoming1, server.clone())).detach();
370            smol::spawn(handle_messages(incoming2, server.clone())).detach();
371
372            assert_eq!(
373                client1
374                    .request(client1_conn_id, proto::Ping { id: 1 },)
375                    .await
376                    .unwrap(),
377                proto::Pong { id: 1 }
378            );
379
380            assert_eq!(
381                client2
382                    .request(client2_conn_id, proto::Ping { id: 2 },)
383                    .await
384                    .unwrap(),
385                proto::Pong { id: 2 }
386            );
387
388            assert_eq!(
389                client1
390                    .request(
391                        client1_conn_id,
392                        proto::OpenBuffer {
393                            worktree_id: 1,
394                            path: "path/one".to_string(),
395                        },
396                    )
397                    .await
398                    .unwrap(),
399                proto::OpenBufferResponse {
400                    buffer: Some(proto::Buffer {
401                        id: 101,
402                        content: "path/one content".to_string(),
403                        history: vec![],
404                        selections: vec![],
405                    }),
406                }
407            );
408
409            assert_eq!(
410                client2
411                    .request(
412                        client2_conn_id,
413                        proto::OpenBuffer {
414                            worktree_id: 2,
415                            path: "path/two".to_string(),
416                        },
417                    )
418                    .await
419                    .unwrap(),
420                proto::OpenBufferResponse {
421                    buffer: Some(proto::Buffer {
422                        id: 102,
423                        content: "path/two content".to_string(),
424                        history: vec![],
425                        selections: vec![],
426                    }),
427                }
428            );
429
430            client1.disconnect(client1_conn_id).await;
431            client2.disconnect(client1_conn_id).await;
432
433            async fn handle_messages(
434                mut messages: mpsc::Receiver<Box<dyn AnyTypedEnvelope>>,
435                peer: Arc<Peer>,
436            ) -> Result<()> {
437                while let Some(envelope) = messages.next().await {
438                    let envelope = envelope.into_any();
439                    if let Some(envelope) = envelope.downcast_ref::<TypedEnvelope<proto::Ping>>() {
440                        let receipt = envelope.receipt();
441                        peer.respond(
442                            receipt,
443                            proto::Pong {
444                                id: envelope.payload.id,
445                            },
446                        )
447                        .await?
448                    } else if let Some(envelope) =
449                        envelope.downcast_ref::<TypedEnvelope<proto::OpenBuffer>>()
450                    {
451                        let message = &envelope.payload;
452                        let receipt = envelope.receipt();
453                        let response = match message.path.as_str() {
454                            "path/one" => {
455                                assert_eq!(message.worktree_id, 1);
456                                proto::OpenBufferResponse {
457                                    buffer: Some(proto::Buffer {
458                                        id: 101,
459                                        content: "path/one content".to_string(),
460                                        history: vec![],
461                                        selections: vec![],
462                                    }),
463                                }
464                            }
465                            "path/two" => {
466                                assert_eq!(message.worktree_id, 2);
467                                proto::OpenBufferResponse {
468                                    buffer: Some(proto::Buffer {
469                                        id: 102,
470                                        content: "path/two content".to_string(),
471                                        history: vec![],
472                                        selections: vec![],
473                                    }),
474                                }
475                            }
476                            _ => {
477                                panic!("unexpected path {}", message.path);
478                            }
479                        };
480
481                        peer.respond(receipt, response).await?
482                    } else {
483                        panic!("unknown message type");
484                    }
485                }
486
487                Ok(())
488            }
489        });
490    }
491
492    #[test]
493    fn test_disconnect() {
494        smol::block_on(async move {
495            let (client_conn, mut server_conn) = test::Channel::bidirectional();
496
497            let client = Peer::new();
498            let (connection_id, io_handler, mut incoming) =
499                client.add_connection(client_conn).await;
500
501            let (mut io_ended_tx, mut io_ended_rx) = postage::barrier::channel();
502            smol::spawn(async move {
503                io_handler.await.ok();
504                io_ended_tx.send(()).await.unwrap();
505            })
506            .detach();
507
508            let (mut messages_ended_tx, mut messages_ended_rx) = postage::barrier::channel();
509            smol::spawn(async move {
510                incoming.next().await;
511                messages_ended_tx.send(()).await.unwrap();
512            })
513            .detach();
514
515            client.disconnect(connection_id).await;
516
517            io_ended_rx.recv().await;
518            messages_ended_rx.recv().await;
519            assert!(
520                futures::SinkExt::send(&mut server_conn, WebSocketMessage::Binary(vec![]))
521                    .await
522                    .is_err()
523            );
524        });
525    }
526
527    #[test]
528    fn test_io_error() {
529        smol::block_on(async move {
530            let (client_conn, server_conn) = test::Channel::bidirectional();
531            drop(server_conn);
532
533            let client = Peer::new();
534            let (connection_id, io_handler, mut incoming) =
535                client.add_connection(client_conn).await;
536            smol::spawn(io_handler).detach();
537            smol::spawn(async move { incoming.next().await }).detach();
538
539            let err = client
540                .request(connection_id, proto::Ping { id: 42 })
541                .await
542                .unwrap_err();
543            assert_eq!(err.to_string(), "connection was closed");
544        });
545    }
546}