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
use std::{pin::Pin, task::Poll, sync::Arc, collections::HashMap, net::SocketAddr};
use futures_util::{Future, Stream, task, FutureExt};
use tokio::{net::{TcpListener, ToSocketAddrs}, sync::{RwLock, mpsc, Mutex}, io::AsyncReadExt};
use crate::{network::{Connection, Error, Message, Event}, MPSC_BUFFER_SIZE, packet::Packet, BYTE_BUFFER_SIZE, parser::Parser};
pub struct Server {
nickname: Arc<RwLock<Vec<u8>>>,
connections: Arc<RwLock<HashMap<SocketAddr, Arc<User>>>>,
event_queue_reciever: Arc<Mutex<mpsc::Receiver<Event>>>,
event_queue_sender: mpsc::Sender<Event>,
event_queue_future: Pin<Box<dyn Future<Output = Option<Event>>>>,
}
impl Connection for Server {
fn connect<A, B>(addr: A, nickname: B) -> Pin<Box<dyn Future<Output = Result<Self, Error>> + 'static>>
where A: ToSocketAddrs + 'static, B: Into<Vec<u8>> + 'static, Self: Sized
{
Box::pin(async move {
let nickname = Arc::new(RwLock::new(nickname.into()));
let listener = TcpListener::bind(addr).await?;
let connections = Arc::new(RwLock::new(HashMap::new()));
let (event_queue_sender, event_queue_reciever) = mpsc::channel(MPSC_BUFFER_SIZE);
{
let connections = connections.clone();
let nickname = nickname.clone();
let event_queue_sender = event_queue_sender.clone();
tokio::spawn(async move {
while let Ok((stream, address)) = listener.accept().await {
let (packet_queue_sender, mut packet_queue_reciever) = mpsc::channel(MPSC_BUFFER_SIZE);
let user = Arc::new(User {
nickname: RwLock::new(None),
packet_queue_sender,
});
connections.write().await.insert(address, user.clone());
let (mut stream_read, mut stream_write) = stream.into_split();
let connections = connections.clone();
let nickname = nickname.clone();
let event_queue_sender = event_queue_sender.clone();
tokio::spawn(async move {
while let Some(packet) = packet_queue_reciever.recv().await {
packet.async_write(&mut stream_write).await.unwrap();
}
});
tokio::spawn(async move {
let mut buffer = [0; BYTE_BUFFER_SIZE];
let mut parser = Parser::new();
loop {
let read_bytes = stream_read.read(&mut buffer).await.unwrap();
parser.parse(&buffer[0..read_bytes]).unwrap();
while let Some(packet) = parser.get_packet() {
match packet {
Packet::SetNicknameRequest(ref nickname)
| Packet::ChangeNicknameRequest(ref nickname) => {
*user.nickname.write().await = Some(nickname.clone());
let packet = match packet {
Packet::SetNicknameRequest(nickname) => Packet::SetNickname(nickname),
Packet::ChangeNicknameRequest(nickname) => Packet::ChangeNickname(nickname),
_ => unreachable!(),
};
user.packet_queue_sender.send(packet).await.unwrap();
},
Packet::UserListRequest => {
user.packet_queue_sender.send(Packet::UserListResponse(generate_user_list(&nickname, &connections).await)).await.unwrap();
},
Packet::SendWord { ref sender, ref recipients, .. }
| Packet::SendInstructions { ref sender, ref recipients, .. }
| Packet::SendList { ref sender, ref recipients, .. }
| Packet::SendImage { ref sender, ref recipients, .. }
| Packet::SendObject { ref sender, ref recipients, .. } => {
for recipient in recipients {
if *recipient == *nickname.read().await {
let event = match &packet {
Packet::SendWord { word, .. } => Event::RecievedMessage { sender: sender.clone(), message: Message::Word(word.clone()) },
Packet::SendInstructions { instructions, .. } => Event::RecievedMessage { sender: sender.clone(), message: Message::Instructions(instructions.clone()) },
Packet::SendList { list, .. } => Event::RecievedMessage { sender: sender.clone(), message: Message::List(list.clone()) },
Packet::SendImage { bytes, .. } => Event::RecievedMessage { sender: sender.clone(), message: Message::Image(bytes.clone()) },
Packet::SendObject { bytes, .. } => Event::RecievedMessage { sender: sender.clone(), message: Message::Object(bytes.clone()) },
_ => unreachable!(),
};
event_queue_sender.send(event).await.unwrap();
} else {
for (_, user) in &*connections.read().await {
if user.nickname.read().await.as_ref().map_or(false, |nickname| nickname == recipient) {
let packet = match &packet {
Packet::SendWord { word, .. } => Packet::DeliverWord { sender: sender.clone(), word: word.clone() },
Packet::SendInstructions { instructions, .. } => Packet::DeliverInstructions { sender: sender.clone(), instructions: instructions.clone() },
Packet::SendList { list, .. } => Packet::DeliverList { sender: sender.clone(), list: list.clone() },
Packet::SendImage { bytes, .. } => Packet::DeliverImage { sender: sender.clone(), bytes: bytes.clone() },
Packet::SendObject { bytes, .. } => Packet::DeliverObject { sender: sender.clone(), bytes: bytes.clone() },
_ => unreachable!(),
};
user.packet_queue_sender.send(packet).await.unwrap();
}
}
}
}
},
_ => (),
}
}
}
});
}
});
}
let event_queue_reciever = Arc::new(Mutex::new(event_queue_reciever));
let event_queue_future = {
let event_queue_reciever = event_queue_reciever.clone();
Box::pin(async move {
event_queue_reciever.lock().await.recv().await
})
};
Ok(Self {
nickname,
connections,
event_queue_sender,
event_queue_reciever,
event_queue_future,
})
})
}
fn send<B>(&mut self, message: Message, recipients: Vec<B>) -> Pin<Box<dyn Future<Output = Result<(), Error>> + '_>>
where B: Into<Vec<u8>>, B: 'static
{
Box::pin(async move {
for recipient in recipients {
let recipient: Vec<u8> = recipient.into();
let nickname = self.nickname.read().await;
if recipient == *nickname {
let nickname = nickname.clone();
let event = match &message {
Message::Word(word) => Event::RecievedMessage { sender: nickname, message: Message::Word(word.clone()) },
Message::Instructions(instructions) => Event::RecievedMessage { sender: nickname, message: Message::Instructions(instructions.clone()) },
Message::List(list) => Event::RecievedMessage { sender: nickname, message: Message::List(list.clone()) },
Message::Image(bytes) => Event::RecievedMessage { sender: nickname, message: Message::Image(bytes.clone()) },
Message::Object(bytes) => Event::RecievedMessage { sender: nickname, message: Message::Object(bytes.clone()) },
};
self.event_queue_sender.send(event).await.unwrap();
} else {
for (_, user) in &*self.connections.read().await {
if user.nickname.read().await.as_ref().map_or(false, |nickname| *nickname == recipient) {
let nickname = nickname.clone();
let packet = match &message {
Message::Word(word) => Packet::DeliverWord { sender: nickname, word: word.clone() },
Message::Instructions(instructions) => Packet::DeliverInstructions { sender: nickname, instructions: instructions.clone() },
Message::List(list) => Packet::DeliverList { sender: nickname, list: list.clone() },
Message::Image(bytes) => Packet::DeliverImage { sender: nickname, bytes: bytes.clone() },
Message::Object(bytes) => Packet::DeliverObject { sender: nickname, bytes: bytes.clone() },
};
user.packet_queue_sender.send(packet).await.unwrap();
}
}
}
}
Ok(())
})
}
fn user_list(&mut self) -> Pin<Box<dyn Future<Output = Result<Vec<Vec<u8>>, Error>> + '_>> {
Box::pin(async move {
Ok(generate_user_list(&self.nickname, &self.connections).await)
})
}
fn change_nickname<B>(&mut self, _nickname: B) -> Pin<Box<dyn Future<Output = Result<(), Error>> + '_>>
where B: Into<Vec<u8>>, B: 'static
{
Box::pin(async move {
todo!();
})
}
}
impl Stream for Server {
type Item = Result<Event, Error>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Option<Self::Item>> {
match self.event_queue_future.poll_unpin(cx) {
Poll::Ready(Some(event)) => {
self.event_queue_future = {
let event_queue_reciever = self.event_queue_reciever.clone();
Box::pin(async move {
event_queue_reciever.lock().await.recv().await
})
};
Poll::Ready(Some(Ok(event)))
},
Poll::Ready(None) => Poll::Ready(None),
Poll::Pending => Poll::Pending,
}
}
}
struct User {
nickname: RwLock<Option<Vec<u8>>>,
packet_queue_sender: mpsc::Sender<Packet>,
}
async fn generate_user_list(nickname: &RwLock<Vec<u8>>, connections: &RwLock<HashMap<SocketAddr, Arc<User>>>) -> Vec<Vec<u8>> {
let mut user_list = vec![nickname.read().await.clone()];
for (_, user) in &*connections.read().await {
if let Some(nickname) = &*user.nickname.read().await {
user_list.push(nickname.clone());
}
}
user_list
}