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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
/*
 * Created on Sat Nov 28 2020
 *
 * Copyright (c) storycraft. Licensed under the MIT Licence.
 */

use std::{collections::HashMap, io::{self, Read, Write}, sync::mpsc::Receiver, sync::mpsc::SendError, sync::mpsc::{Sender, channel}};

use crate::command::{self, Command, processor::CommandProcessor};

#[derive(Debug)]
pub enum Error {

    Command(command::Error),
    Channel,
    Socket(io::Error)

}

impl From<command::Error> for Error {

    fn from(err: command::Error) -> Self {
        Error::Command(err)
    }

}

impl From<io::Error> for Error {

    fn from(err: io::Error) -> Self {
        Error::Socket(err)
    }

}

impl<A> From<SendError<A>> for Error {

    fn from(_: SendError<A>) -> Self {
        Error::Channel
    }

}

/// ConnectionChannel holds Sender and Receiver crossed with another ConnectionChannel pair.
/// Usually considered as user side and server side pair.
pub struct ConnectionChannel {

    id: u32,

    sender: Sender<Command>,
    receiver: Receiver<Command>,

}

impl ConnectionChannel {

    pub fn new_pair(id: u32) -> (ConnectionChannel, ConnectionChannel) {
        let user = channel::<Command>();
        let socket = channel::<Command>();

        (
            ConnectionChannel {
                id,
                sender: user.0,
                receiver: socket.1,
            },
            ConnectionChannel {
                id,
                sender: socket.0,
                receiver: user.1
            }
        )
    }

    pub fn id(&self) -> u32 {
        self.id
    }

    pub fn sender(&self) -> &Sender<Command> {
        &self.sender
    }

    pub fn receiver(&self) -> &Receiver<Command> {
        &self.receiver
    }

}

/// ChannelConnection wrap command stream and process it.
/// The response command will only send to sender channel.
/// If response command doesn't have sender, It will treat as broadcast command and will be sent to every channel attached.
pub struct ChannelConnection<A: Read + Write> {

    processor: CommandProcessor<A>,

    next_channel_id: u32,
    channel_map: HashMap<u32, ConnectionChannel>,

    command_channel: HashMap<i32, u32>

}

impl<A: Read + Write> ChannelConnection<A> {

    pub fn new(processor: CommandProcessor<A>) -> Self {
        Self {
            processor,
            next_channel_id: 0,
            channel_map: HashMap::new(),
            command_channel: HashMap::new()
        }
    }

    pub fn processor(&self) -> &CommandProcessor<A> {
        &self.processor
    }

    pub fn channel_map(&self) -> &HashMap<u32, ConnectionChannel> {
        &self.channel_map
    }

    /// Attach channel between instance.
    /// The returned ConnectionChannel struct is user side Channel.
    pub fn create_channel(&mut self) -> ConnectionChannel {
        let (user_channel, socket_channel) = ConnectionChannel::new_pair(self.next_channel_id);
        self.next_channel_id += 1;

        self.channel_map.insert(user_channel.id(), socket_channel);

        user_channel
    }

    pub fn detach_channel(&mut self, channel: ConnectionChannel) -> (ConnectionChannel, Option<ConnectionChannel>) {
        let id = channel.id();
        (channel, self.channel_map.remove(&id))
    }

    pub fn process(&mut self) -> Result<(), Error> {
        let mut command_list = Vec::<Command>::new();
        for channel in self.channel_map.values() {
            for command in channel.receiver().try_iter() {
                self.command_channel.insert(command.header.id, channel.id());

                command_list.push(command);
            }
        }
        self.processor.write_all_command(command_list)?;

        let command = self.processor.read_command()?;

        match command {

            Some(command) => {
                match self.command_channel.remove(&command.header.id) {

                    Some(channel_id) => {
                        match self.channel_map.get(&channel_id) {
    
                            Some(channel) => {
                                channel.sender.send(command)?;
                            }
    
                            None => {}
                        }
                    }
    
                    None => {
                        for channel in self.channel_map.values() {
                            channel.sender().send(command.clone())?;
                        }
                    }
                }
            }

            None => {}
        }

        Ok(())
    }

}

pub type ResponseHandler = fn(Command, Command);

/// Handle command responses from ConnectionChannel
pub struct ChannelHandler {

    pub channel: ConnectionChannel,
    command_map: HashMap<i32, (Command, ResponseHandler)>

}

impl ChannelHandler {

    pub fn new(channel: ConnectionChannel) -> Self {
        Self {
            channel,
            command_map: HashMap::new()
        }
    }

    pub fn send_command(&mut self, command: Command, response_handler: ResponseHandler) -> Result<(), SendError<Command>> {
        self.command_map.insert(command.header.id, (command.clone(), response_handler));

        self.channel.sender().send(command)
    }

    pub fn handle(&mut self) {
        let iter = self.channel.receiver().try_iter();

        for response in iter {
            let id = response.header.id;

            match self.command_map.remove(&id) {

                Some(request_set) => {
                    let response_handler = request_set.1;

                    response_handler(response, request_set.0);
                }

                None => {}
            };
        }
    }
}