Skip to main content

asimov_protocol/
peer_connection.rs

1// This is free and unencumbered software released into the public domain.
2
3#![allow(dead_code)]
4
5use crate::{Message, MessageRecv, MessageSend, PeerHello, PingError, RecvError, SendError};
6use iroh::endpoint::{Connection, RecvStream, SendStream};
7use tokio::time::{Duration, Instant};
8
9#[derive(Debug)]
10pub struct PeerConnection {
11    pub(crate) inner: Connection,
12    pub(crate) send: SendStream,
13    pub(crate) recv: RecvStream,
14    pub(crate) hello: PeerHello,
15}
16
17impl PeerConnection {
18    pub fn hello(&self) -> &PeerHello {
19        return &self.hello;
20    }
21
22    pub async fn ping(&mut self) -> Result<Duration, PingError> {
23        // Begin measuring elapsed time:
24        let start = Instant::now();
25
26        // Send the ping request:
27        let _ = self.send(Message::Ping).await?;
28
29        // Read the ping response:
30        let response = self.recv().await?;
31        assert_eq!(response, Message::Ping);
32
33        // Measure the duration of this interaction:
34        let duration = start.elapsed();
35
36        Ok(duration)
37    }
38
39    // pub fn close(self) -> Result<PeerConnection<Closed>, Infallible> {
40    //     let Ready { inner, .. } = self.0;
41    //     inner.close(0u32.into(), &[]);
42    //     Ok(PeerConnection(Closed { inner }))
43    // }
44}
45
46impl MessageSend for PeerConnection {
47    async fn write_all(&mut self, buffer: &[u8]) -> Result<(), SendError> {
48        Ok(self.send.write_all(buffer).await?)
49    }
50}
51
52impl MessageRecv for PeerConnection {
53    async fn read_exact(&mut self, buffer: &mut [u8]) -> Result<(), RecvError> {
54        Ok(self.recv.read_exact(buffer).await?)
55    }
56}