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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348use std::collections::*;
use std::iter::FromIterator;
use std::time::Duration;
use actix::prelude::*;
use actix_ogn::OGNMessage;
use chrono::prelude::*;
use log::{debug, error, warn};
use crate::geo::BoundingBox;
use crate::ogn;
use crate::redis::{self, RedisExecutor};
use crate::ws_client::{SendTextFast, SendTextSlow, WSClient};
/// `Gateway` manages connected websocket clients and distributes
/// `OGNRecord` messages to them.
pub struct Gateway {
redis: Addr<RedisExecutor>,
ws_clients: HashSet<Addr<WSClient>>,
id_subscriptions: HashMap<String, Vec<Addr<WSClient>>>,
bbox_subscriptions: HashMap<Addr<WSClient>, BoundingBox>,
ignore_list: HashSet<String>,
redis_buffer: Vec<(String, redis::OGNPosition)>,
record_count: Option<u64>,
}
impl Gateway {
pub fn new(redis: Addr<RedisExecutor>) -> Gateway {
Gateway {
redis,
ws_clients: HashSet::new(),
id_subscriptions: HashMap::new(),
bbox_subscriptions: HashMap::new(),
ignore_list: HashSet::new(),
redis_buffer: Vec::new(),
record_count: None,
}
}
fn update_record_count(&self, ctx: &mut Context<Self>) {
let fut = self
.redis
.send(redis::CountOGNPositions)
.into_actor(self)
.map(|result, act, _ctx| match result {
Err(error) => warn!("Could not count OGN position records in redis: {}", error),
Ok(result) => {
if act.record_count.is_none() || result.is_ok() {
act.record_count = result.ok();
}
}
});
ctx.spawn(fut);
}
fn flush_records(&mut self, ctx: &mut Context<Self>) {
let buffer = self.redis_buffer.split_off(0);
let count = buffer.len();
if count > 0 {
let fut = self
.redis
.send(redis::AddOGNPositions { positions: buffer })
.into_actor(self)
.map(move |result, act, _ctx| {
match result {
Ok(Ok(_)) => {
debug!("Flushed {} OGN position records to redis", &count);
if act.record_count.is_some() {
act.record_count = Some(act.record_count.unwrap() + count as u64);
}
}
Ok(Err(error)) => error!(
"Could not flush new OGN position records to redis: {}",
error
),
Err(error) => error!(
"Could not flush new OGN position records to redis: {}",
error
),
};
});
ctx.spawn(fut);
}
}
fn drop_outdated_records(&self, ctx: &mut Context<Self>) {
let fut = self
.redis
.send(redis::DropOldOGNPositions)
.into_actor(self)
.map(|result, act, _ctx| match result {
Err(error) => warn!(
"Could not drop outdated OGN position records from redis: {}",
error
),
Ok(result) => {
if let Some(current_count) = act.record_count {
if let Ok(result) = result {
act.record_count = Some(current_count + result);
}
}
}
});
ctx.spawn(fut);
}
fn update_ignore_list(&self, ctx: &mut Context<Self>) {
let fut =
self.redis
.send(redis::ReadOGNIgnore)
.into_actor(self)
.map(|result, act, _ctx| match result {
Err(error) => {
warn!("Could not read OGN ignore list from redis: {}", error);
}
Ok(Ok(result)) => {
act.ignore_list = HashSet::from_iter(result);
debug!(
"Updated OGN ignore list from redis: {} records",
act.ignore_list.len()
);
}
_ => {}
});
ctx.spawn(fut);
}
}
impl Actor for Gateway {
type Context = Context<Self>;
fn started(&mut self, ctx: &mut Self::Context) {
self.update_record_count(ctx);
ctx.run_interval(Duration::from_secs(30 * 60), |act, ctx| {
act.update_record_count(ctx);
});
ctx.run_interval(Duration::from_secs(5), |act, ctx| {
act.flush_records(ctx);
});
ctx.run_later(Duration::from_secs(30), |act, ctx| {
act.drop_outdated_records(ctx);
ctx.run_interval(Duration::from_secs(30 * 60), |act, ctx| {
act.drop_outdated_records(ctx);
});
});
ctx.run_later(Duration::from_secs(10), |act, ctx| {
act.update_ignore_list(ctx);
ctx.run_interval(Duration::from_secs(10 * 60), |act, ctx| {
act.update_ignore_list(ctx);
});
});
}
}
pub struct RequestStatus;
impl Message for RequestStatus {
type Result = StatusResponse;
}
pub struct StatusResponse {
pub users: usize,
pub record_count: Option<u64>,
}
impl Handler<RequestStatus> for Gateway {
type Result = MessageResult<RequestStatus>;
fn handle(&mut self, _msg: RequestStatus, _ctx: &mut Context<Self>) -> Self::Result {
MessageResult(StatusResponse {
users: self.ws_clients.len(),
record_count: self.record_count,
})
}
}
/// New websocket client has connected.
#[derive(Message)]
#[rtype(result = "()")]
pub struct Connect {
pub addr: Addr<WSClient>,
}
impl Handler<Connect> for Gateway {
type Result = ();
fn handle(&mut self, msg: Connect, _: &mut Context<Self>) {
self.ws_clients.insert(msg.addr);
debug!("Client connected ({} clients)", self.ws_clients.len());
}
}
/// Websocket client has disconnected.
#[derive(Message)]
#[rtype(result = "()")]
pub struct Disconnect {
pub addr: Addr<WSClient>,
}
impl Handler<Disconnect> for Gateway {
type Result = ();
fn handle(&mut self, msg: Disconnect, _: &mut Context<Self>) {
self.bbox_subscriptions.remove(&msg.addr);
self.id_subscriptions.values_mut().for_each(|subscribers| {
if let Some(pos) = subscribers.iter().position(|x| *x == msg.addr) {
subscribers.remove(pos);
}
});
self.ws_clients.remove(&msg.addr);
debug!("Client disconnected ({} clients)", self.ws_clients.len());
}
}
#[derive(Message)]
#[rtype(result = "()")]
pub struct SubscribeToId {
pub id: String,
pub addr: Addr<WSClient>,
}
impl Handler<SubscribeToId> for Gateway {
type Result = ();
fn handle(&mut self, msg: SubscribeToId, _ctx: &mut Context<Self>) {
self.id_subscriptions
.entry(msg.id)
.or_insert_with(Vec::new)
.push(msg.addr);
}
}
#[derive(Message)]
#[rtype(result = "()")]
pub struct UnsubscribeFromId {
pub id: String,
pub addr: Addr<WSClient>,
}
impl Handler<UnsubscribeFromId> for Gateway {
type Result = ();
fn handle(&mut self, msg: UnsubscribeFromId, _ctx: &mut Context<Self>) {
if let Some(subscribers) = self.id_subscriptions.get_mut(&msg.id) {
if let Some(pos) = subscribers.iter_mut().position(|x| *x == msg.addr) {
subscribers.remove(pos);
}
}
}
}
#[derive(Message)]
#[rtype(result = "()")]
pub struct SetBoundingBox {
pub addr: Addr<WSClient>,
pub bbox: BoundingBox,
}
impl Handler<SetBoundingBox> for Gateway {
type Result = ();
fn handle(&mut self, msg: SetBoundingBox, _ctx: &mut Context<Self>) {
self.bbox_subscriptions.insert(msg.addr, msg.bbox);
}
}
impl Handler<OGNMessage> for Gateway {
type Result = ();
fn handle(&mut self, message: OGNMessage, _: &mut Context<Self>) {
if let Some(position) = ogn::aprs::parse(&message.raw) {
if self.ignore_list.contains(position.id) {
return;
}
let now = Utc::now();
let time = ogn::time_to_datetime(now, position.time);
let age = time - now;
// throw away records older than 15min or more than 5min into the future
if age.num_minutes() > 15 || age.num_minutes() < -5 {
return;
}
// find subscribers
let id_subscribers = self.id_subscriptions.get(position.id);
let bbox_subscribers: Vec<&Addr<WSClient>> = self
.bbox_subscriptions
.iter()
.filter(|(_, bbox)| bbox.contains(position.longitude, position.latitude))
.map(|(addr, _)| addr)
.filter(|addr| id_subscribers.map_or(true, |list| !list.contains(addr)))
.collect();
// send record to subscribers
if !bbox_subscribers.is_empty() || id_subscribers.map_or(false, |list| !list.is_empty())
{
let ws_message = format!(
"{}|{}|{:.6}|{:.6}|{}|{}",
position.id,
time.timestamp(),
position.longitude,
position.latitude,
position.course,
position.altitude as i32,
);
for subscriber in bbox_subscribers {
subscriber.do_send(SendTextSlow(ws_message.clone()));
}
if let Some(id_subscribers) = id_subscribers {
for subscriber in id_subscribers {
subscriber.do_send(SendTextFast(ws_message.clone()));
}
}
}
// save record in the database
self.redis_buffer.push((
position.id.to_owned(),
redis::OGNPosition {
time,
longitude: position.longitude as f32,
latitude: position.latitude as f32,
altitude: position.altitude as i16,
},
));
}
}
}