Skip to main content

ma_core/iroh/
channel.rs

1//! Write-only persistent connection handle to a remote ma endpoint.
2//!
3//! A `Channel` wraps an iroh `Connection` + `SendStream` for sending
4//! one-way messages. Created via [`crate::iroh::IrohEndpoint::open`].
5
6use iroh::endpoint::{Connection, SendStream};
7use tokio::io::AsyncWriteExt;
8
9use crate::error::{Error, Result};
10
11/// A persistent write-only handle to a remote endpoint on a specific protocol.
12///
13/// The channel stays open until explicitly closed or the connection drops.
14#[derive(Debug)]
15pub struct Channel {
16    connection: Connection,
17    send: SendStream,
18}
19
20impl Channel {
21    /// Create a channel from an existing connection and send stream.
22    pub(crate) fn new(connection: Connection, send: SendStream) -> Self {
23        Self { connection, send }
24    }
25
26    /// Send a payload over the channel.
27    pub async fn send(&mut self, payload: &[u8]) -> Result<()> {
28        self.send
29            .write_all(payload)
30            .await
31            .map_err(|e| Error::Transport(format!("channel write failed: {e}")))?;
32        self.send
33            .flush()
34            .await
35            .map_err(|e| Error::Transport(format!("channel flush failed: {e}")))?;
36        Ok(())
37    }
38
39    /// Close the channel gracefully.
40    pub fn close(mut self) {
41        let _ = self.send.finish();
42        self.connection.close(0u32.into(), b"done");
43    }
44
45    /// Access the underlying iroh connection.
46    pub fn connection(&self) -> &Connection {
47        &self.connection
48    }
49}
50
51impl Drop for Channel {
52    fn drop(&mut self) {
53        let _ = self.send.finish();
54    }
55}