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
use crate::{
    connection::Connection, executor::Executor, frames::Frames, id_sequence::IdSequence,
    protocol::AMQPClass, BasicProperties, Channel, ChannelState, Error, Result,
};
use log::debug;
use parking_lot::Mutex;
use std::{collections::HashMap, sync::Arc};

#[derive(Clone, Debug)]
pub(crate) struct Channels {
    inner: Arc<Mutex<Inner>>,
    frames: Frames,
}

impl Channels {
    pub(crate) fn new(frames: Frames, executor: Arc<dyn Executor>) -> Self {
        Self {
            inner: Arc::new(Mutex::new(Inner::new(executor))),
            frames,
        }
    }

    pub(crate) fn create(&self, connection: Connection) -> Result<Channel> {
        self.inner.lock().create(connection)
    }

    pub(crate) fn create_zero(&self, connection: Connection) {
        self.inner
            .lock()
            .create_channel(0, connection)
            .set_state(ChannelState::Connected);
    }

    pub(crate) fn get(&self, id: u16) -> Option<Channel> {
        self.inner.lock().channels.get(&id).cloned()
    }

    pub(crate) fn remove(&self, id: u16, error: Error) -> Result<()> {
        self.frames.clear_expected_replies(id, error);
        if self.inner.lock().channels.remove(&id).is_some() {
            Ok(())
        } else {
            Err(Error::InvalidChannel(id))
        }
    }

    pub(crate) fn receive_method(&self, id: u16, method: AMQPClass) -> Result<()> {
        if let Some(channel) = self.get(id) {
            channel.receive_method(method)
        } else {
            Err(Error::InvalidChannel(id))
        }
    }

    pub(crate) fn handle_content_header_frame(
        &self,
        id: u16,
        size: u64,
        properties: BasicProperties,
    ) -> Result<()> {
        if let Some(channel) = self.get(id) {
            channel.handle_content_header_frame(size, properties)
        } else {
            Err(Error::InvalidChannel(id))
        }
    }

    pub(crate) fn handle_body_frame(&self, id: u16, payload: Vec<u8>) -> Result<()> {
        if let Some(channel) = self.get(id) {
            channel.handle_body_frame(payload)
        } else {
            Err(Error::InvalidChannel(id))
        }
    }

    pub(crate) fn set_closing(&self) {
        for channel in self.inner.lock().channels.values() {
            channel.set_state(ChannelState::Closing);
        }
    }

    pub(crate) fn set_closed(&self, error: Error) -> Result<()> {
        self.inner
            .lock()
            .channels
            .drain()
            .map(|(id, channel)| {
                self.frames.clear_expected_replies(id, error.clone());
                channel.set_state(ChannelState::Closed);
                channel.error_publisher_confirms(error.clone());
                channel.cancel_consumers()
            })
            .fold(Ok(()), Result::and)
    }

    pub(crate) fn set_error(&self, error: Error) -> Result<()> {
        self.inner
            .lock()
            .channels
            .drain()
            .map(|(id, channel)| {
                self.frames.clear_expected_replies(id, error.clone());
                channel.set_state(ChannelState::Error);
                channel.error_publisher_confirms(error.clone());
                channel.error_consumers(error.clone())
            })
            .fold(Ok(()), Result::and)
    }

    pub(crate) fn flow(&self) -> bool {
        self.inner
            .lock()
            .channels
            .values()
            .all(|c| c.status().flow())
    }
}

#[derive(Debug)]
struct Inner {
    channels: HashMap<u16, Channel>,
    channel_id: IdSequence<u16>,
    executor: Arc<dyn Executor>,
}

impl Inner {
    fn new(executor: Arc<dyn Executor>) -> Self {
        Self {
            channels: HashMap::default(),
            channel_id: IdSequence::new(false),
            executor,
        }
    }
}

impl Inner {
    fn create_channel(&mut self, id: u16, connection: Connection) -> Channel {
        debug!("create channel with id {}", id);
        let channel = Channel::new(id, connection, self.executor.clone());
        self.channels.insert(id, channel.clone());
        channel
    }

    fn create(&mut self, connection: Connection) -> Result<Channel> {
        debug!("create channel");
        self.channel_id
            .set_max(connection.configuration().channel_max());
        let first_id = self.channel_id.next();
        let mut looped = false;
        let mut id = first_id;
        while !looped || id < first_id {
            if id == 1 {
                looped = true;
            }
            if !self.channels.contains_key(&id) {
                return Ok(self.create_channel(id, connection));
            }
            id = self.channel_id.next();
        }
        Err(Error::ChannelsLimitReached)
    }
}