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
use std::collections::HashMap;
use std::sync::mpsc::{channel, Sender};
use std::sync::{Mutex, RwLock};
use actix::clock::Duration;
use actix::Addr;
use crate::communication::{
ProxyRequest, ProxyResponse, WebsocketCommand, WebsocketSignal, WrappedMessage,
};
use crate::proxy_error::{ProxyError, ProxyResult};
use crate::server::websocket_handler::WebsocketHandler;
pub struct ClientManager {
clients: RwLock<HashMap<String, Addr<WebsocketHandler>>>,
requests: RwLock<HashMap<usize, Mutex<Sender<ProxyResponse>>>>,
}
impl ClientManager {
pub fn new() -> Self {
Self {
clients: Default::default(),
requests: Default::default(),
}
}
/// Sends a request to a client and returns its response
///
/// # Errors
///
/// - when the client is not registered
/// - when the response is not coming fast enough (within 1 minute)
///
pub fn send_request(
&self,
client_id: &String,
request: ProxyRequest,
) -> ProxyResult<ProxyResponse> {
if !self.clients.read().unwrap().contains_key(client_id) {
return Err(ProxyError::message(format!(
"Client {} is not registered",
client_id
)));
}
let client = self.clients.read().unwrap().get(client_id).unwrap().clone();
let (send, recv) = channel::<ProxyResponse>();
let message = WrappedMessage::new(request);
self.requests
.write()
.unwrap()
.insert(message.id.clone(), Mutex::new(send));
client.do_send(message);
let response = match recv.recv_timeout(Duration::from_secs(60)) {
Ok(response) => response,
Err(_) => ProxyResponse {
response: json!({
"success": false,
"message": [{
"error": "Client request timed out"
}]
}),
content_type: String::from("application/json"),
},
};
Ok(response)
}
/// Checks if a given client id is available or already taken
///
/// # Example
///
/// ```
/// use new_home_proxy::server::client_manager::ClientManager;
///
/// let manager = ClientManager::new();
/// assert_eq!(manager.is_client_registered(&String::from("bob")), false);
/// ```
///
pub fn is_client_registered(&self, client_id: &String) -> bool {
self.clients.read().unwrap().contains_key(client_id)
}
/// Registers a client and its address
///
/// # Example
///
/// ```
/// use new_home_proxy::server::client_manager::ClientManager;
/// use new_home_proxy::server::websocket_handler::WebsocketHandler;
/// use actix::Addr;
/// use actix::dev::channel::channel;
///
/// let manager = ClientManager::new();
///
/// let (sender, _) = channel::<WebsocketHandler>(1);
/// assert_eq!(
/// manager.register_client(String::from("Some client"), Addr::new(sender)).is_ok(),
/// true
/// );
///
/// let (sender, _) = channel::<WebsocketHandler>(1);
/// assert_eq!(
/// manager.register_client(String::from("Some client"), Addr::new(sender)).is_ok(),
/// false
/// );
/// ```
///
/// # Errors
///
/// - when the client_id is already taken
///
pub fn register_client(
&self,
client_id: String,
handler: Addr<WebsocketHandler>,
) -> ProxyResult<()> {
if self.clients.read().unwrap().contains_key(&client_id) {
return Err(ProxyError::message(format!(
"Client {} is already registered",
&client_id
)));
}
self.clients.write().unwrap().insert(client_id, handler);
Ok(())
}
/// Unregisters a client and its address
///
/// # Errors
///
/// - when the client id is not registered
///
pub fn unregister_client(&self, client_id: &String) -> ProxyResult<()> {
if !self.clients.read().unwrap().contains_key(client_id) {
return Err(ProxyError::message(format!(
"The client {} is not registered",
client_id
)));
}
self.clients.write().unwrap().remove(client_id);
Ok(())
}
/// Sends a ping `WebsocketCommand` to all registered clients
pub fn ping_all_clients(&self) {
for (_, address) in self.clients.read().unwrap().iter() {
address.do_send(WebsocketCommand(WebsocketSignal::CheckPing))
}
}
/// Sends the response for the given message id to the registered request channel.
/// Removes the sender if the message was send successfully
///
/// # Errors
///
/// - when there is no sender registered for the given message_id
/// - when the message could not be send
///
pub(crate) fn response(&self, message_id: usize, response: ProxyResponse) -> ProxyResult<()> {
{
let requests = self.requests.read().unwrap();
let sender = match requests.get(&message_id) {
Some(sender) => sender,
_ => {
return Err(ProxyError::message(format!(
"Sender for message_id {} is not registered",
&message_id
)));
}
};
sender.lock().unwrap().send(response)?;
}
{
self.requests.write().unwrap().remove(&message_id);
}
Ok(())
}
}