rsub 0.1.0

A high-performance message broker with QUIC transport and pub/sub messaging patterns
Documentation
use std::{collections::HashMap, sync::Arc};

use anyhow::{anyhow, Result};
use quinn::{Connection, RecvStream};
use tokio::sync::Mutex;

use crate::common::frame::FrameReader;

#[derive(Debug)]
pub struct ClientConnection {
    pub connection: Connection,
    // the recv stream is the stream that is used to receive data from the client.
    pub recv_stream: Option<FrameReader>,
    // binary streams are streams that are used to send binary data. string is the topic name.
    pub binary_streams: HashMap<String, Arc<Mutex<RecvStream>>>,
}

impl ClientConnection {
    pub async fn new(connection: Connection) -> Result<Self> {
        let binary_streams: HashMap<String, Arc<Mutex<RecvStream>>> = HashMap::new();

        Ok(Self {
            connection,
            binary_streams,
            recv_stream: None,
        })
    }

    pub async fn get_recv_stream(&mut self) -> Result<Option<FrameReader>> {
        let (_, recv_stream) = self
            .connection
            .accept_bi()
            .await
            .map_err(|e| anyhow!("Failed to open bi stream: {}", e))?;
        let recv_stream = FrameReader::new(Arc::new(Mutex::new(recv_stream)));

        self.recv_stream = Some(recv_stream);
        Ok(self.recv_stream.clone())
    }
}