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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
use std::{
boxed::Box,
future::Future,
pin::Pin,
sync::Arc,
task::{Context as FutContext, Poll},
time::Duration,
};
use futures::{future::BoxFuture, stream::Stream};
use tokio::sync::mpsc::{
unbounded_channel,
UnboundedReceiver as Receiver,
UnboundedSender as Sender,
};
#[cfg(all(feature = "tokio_compat", not(feature = "tokio")))]
use tokio::time::{delay_for as sleep, Delay as Sleep};
#[cfg(feature = "tokio")]
use tokio::time::{sleep, Sleep};
use crate::{
client::bridge::gateway::ShardMessenger,
collector::{CollectorError, LazyArc},
model::{
event::{Event, EventType, RelatedIdsForEventType},
id::{ChannelId, GuildId, MessageId, UserId},
},
Error,
Result,
};
#[derive(Clone, Debug)]
pub struct EventFilter {
filtered: u32,
collected: u32,
options: FilterOptions,
sender: Sender<Arc<Event>>,
}
impl EventFilter {
fn new(options: FilterOptions) -> Result<(Self, Receiver<Arc<Event>>)> {
Self::validate_options(&options)?;
let (sender, receiver) = unbounded_channel();
let filter = Self {
filtered: 0,
collected: 0,
sender,
options,
};
Ok((filter, receiver))
}
fn validate_options(options: &FilterOptions) -> Result<()> {
if options.event_types.is_empty() {
return Err(Error::Collector(CollectorError::NoEventTypes));
}
let related = options.event_types.iter().map(EventType::related_ids).fold(
RelatedIdsForEventType::default(),
|mut acc, e| {
acc.user_id |= e.user_id;
acc.guild_id |= e.guild_id;
acc.channel_id |= e.channel_id;
acc.message_id |= e.message_id;
acc
},
);
if (options.user_id.is_empty() || related.user_id)
&& (options.guild_id.is_empty() || related.guild_id)
&& (options.channel_id.is_empty() || related.channel_id)
&& (options.message_id.is_empty() || related.message_id)
{
Ok(())
} else {
Err(Error::Collector(CollectorError::InvalidEventIdFilters))
}
}
pub(crate) fn send_event(&mut self, event: &mut LazyArc<'_, Event>) -> bool {
if !self.is_matching_event_type(&event) {
return !self.sender.is_closed();
}
if self.is_passing_constraints(event) {
self.collected += 1;
if let Err(_) = self.sender.send(event.as_arc()) {
return false;
}
}
self.filtered += 1;
self.is_within_limits() && !self.sender.is_closed()
}
fn is_matching_event_type(&self, event: &Event) -> bool {
self.options.event_types.contains(&event.event_type())
}
fn is_passing_constraints(&mut self, event: &mut LazyArc<'_, Event>) -> bool {
fn empty_or_any<T, F>(slice: &[T], f: F) -> bool
where
F: Fn(&T) -> bool,
{
slice.is_empty() || slice.iter().any(f)
}
empty_or_any(&self.options.guild_id, |id| event.guild_id().contains(id))
&& empty_or_any(&self.options.user_id, |id| event.user_id().contains(id))
&& empty_or_any(&self.options.channel_id, |id| event.channel_id().contains(id))
&& empty_or_any(&self.options.message_id, |id| event.message_id().contains(id))
&& self.options.filter.as_mut().map_or(true, |f| f.0(&event.as_arc()))
}
fn is_within_limits(&self) -> bool {
self.options.filter_limit.as_ref().map_or(true, |limit| self.filtered < *limit)
&& self.options.collect_limit.as_ref().map_or(true, |limit| self.collected < *limit)
}
}
#[derive(Clone)]
struct FilterFn(Arc<dyn Fn(&Arc<Event>) -> bool + 'static + Send + Sync>);
impl std::fmt::Debug for FilterFn {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("Arc<dyn Fn(&Arc<Event>) -> bool + 'static + Send + Sync>")
}
}
#[derive(Clone, Debug, Default)]
struct FilterOptions {
event_types: Vec<EventType>,
filter_limit: Option<u32>,
collect_limit: Option<u32>,
filter: Option<FilterFn>,
channel_id: Vec<ChannelId>,
guild_id: Vec<GuildId>,
user_id: Vec<UserId>,
message_id: Vec<MessageId>,
}
pub struct EventCollectorBuilder<'a> {
filter: Option<FilterOptions>,
shard: Option<ShardMessenger>,
timeout: Option<Pin<Box<Sleep>>>,
fut: Option<BoxFuture<'a, Result<EventCollector>>>,
}
impl<'a> EventCollectorBuilder<'a> {
pub fn new(shard_messenger: impl AsRef<ShardMessenger>) -> Self {
Self {
filter: Some(FilterOptions::default()),
shard: Some(shard_messenger.as_ref().clone()),
timeout: None,
fut: None,
}
}
#[allow(clippy::unwrap_used)]
pub fn filter_limit(mut self, limit: u32) -> Self {
self.filter.as_mut().unwrap().filter_limit = Some(limit);
self
}
#[allow(clippy::unwrap_used)]
pub fn collect_limit(mut self, limit: u32) -> Self {
self.filter.as_mut().unwrap().collect_limit = Some(limit);
self
}
#[allow(clippy::unwrap_used)]
pub fn filter<F: Fn(&Arc<Event>) -> bool + 'static + Send + Sync>(
mut self,
function: F,
) -> Self {
self.filter.as_mut().unwrap().filter = Some(FilterFn(Arc::new(function)));
self
}
#[allow(clippy::unwrap_used)]
pub fn add_event_type(mut self, event_type: EventType) -> Self {
self.filter.as_mut().unwrap().event_types.push(event_type);
self
}
#[allow(clippy::unwrap_used)]
pub fn add_user_id(mut self, user_id: impl Into<UserId>) -> Self {
self.filter.as_mut().unwrap().user_id.push(user_id.into());
self
}
#[allow(clippy::unwrap_used)]
pub fn add_channel_id(mut self, channel_id: impl Into<ChannelId>) -> Self {
self.filter.as_mut().unwrap().channel_id.push(channel_id.into());
self
}
#[allow(clippy::unwrap_used)]
pub fn add_guild_id(mut self, guild_id: impl Into<GuildId>) -> Self {
self.filter.as_mut().unwrap().guild_id.push(guild_id.into());
self
}
#[allow(clippy::unwrap_used)]
pub fn add_message_id(mut self, message_id: impl Into<MessageId>) -> Self {
self.filter.as_mut().unwrap().message_id.push(message_id.into());
self
}
pub fn timeout(mut self, duration: Duration) -> Self {
self.timeout = Some(Box::pin(sleep(duration)));
self
}
}
impl<'a> Future for EventCollectorBuilder<'a> {
type Output = Result<EventCollector>;
#[allow(clippy::unwrap_used)]
fn poll(mut self: Pin<&mut Self>, ctx: &mut FutContext<'_>) -> Poll<Self::Output> {
if self.fut.is_none() {
let shard_messenger = self.shard.take().unwrap();
let (filter, receiver) = match EventFilter::new(self.filter.take().unwrap()) {
Ok(ret) => ret,
Err(err) => return Poll::Ready(Err(err)),
};
let timeout = self.timeout.take();
self.fut = Some(Box::pin(async move {
shard_messenger.set_event_filter(filter);
Ok(EventCollector {
receiver: Box::pin(receiver),
timeout,
})
}))
}
self.fut.as_mut().unwrap().as_mut().poll(ctx)
}
}
pub struct EventCollector {
receiver: Pin<Box<Receiver<Arc<Event>>>>,
timeout: Option<Pin<Box<Sleep>>>,
}
impl EventCollector {
pub fn stop(mut self) {
self.receiver.close();
}
}
impl Stream for EventCollector {
type Item = Arc<Event>;
fn poll_next(mut self: Pin<&mut Self>, ctx: &mut FutContext<'_>) -> Poll<Option<Self::Item>> {
if let Some(ref mut timeout) = self.timeout {
match timeout.as_mut().poll(ctx) {
Poll::Ready(_) => {
return Poll::Ready(None);
},
Poll::Pending => (),
}
}
self.receiver.as_mut().poll_recv(ctx)
}
}
impl Drop for EventCollector {
fn drop(&mut self) {
self.receiver.close();
}
}
#[cfg(test)]
mod test {
use futures::channel::mpsc::unbounded;
use super::*;
use crate::client::bridge::gateway::ShardMessenger;
#[tokio::test]
async fn test_no_event_types() {
let (sender, _) = unbounded();
let msg = ShardMessenger::new(sender);
assert!(matches!(
EventCollectorBuilder::new(&msg).await,
Err(Error::Collector(CollectorError::NoEventTypes))
));
assert!(matches!(
EventCollectorBuilder::new(&msg).add_channel_id(ChannelId::default()).await,
Err(Error::Collector(CollectorError::NoEventTypes))
));
}
#[tokio::test]
async fn test_build_with_single_id_filter() {
let (sender, _) = unbounded();
let msg = ShardMessenger::new(sender);
assert!(matches!(
EventCollectorBuilder::new(&msg)
.add_event_type(EventType::GuildCreate)
.add_user_id(UserId::default())
.await,
Err(Error::Collector(CollectorError::InvalidEventIdFilters))
));
assert!(matches!(
EventCollectorBuilder::new(&msg)
.add_event_type(EventType::GuildCreate)
.add_event_type(EventType::GuildRoleCreate)
.add_user_id(UserId::default())
.await,
Err(Error::Collector(CollectorError::InvalidEventIdFilters))
));
assert!(matches!(
EventCollectorBuilder::new(&msg)
.add_event_type(EventType::GuildBanAdd)
.add_user_id(UserId::default())
.await,
Ok(_)
));
assert!(matches!(
EventCollectorBuilder::new(&msg)
.add_event_type(EventType::GuildBanAdd)
.add_event_type(EventType::GuildCreate)
.add_user_id(UserId::default())
.await,
Ok(_)
));
}
#[tokio::test]
async fn test_build_with_multiple_id_filters() {
let (sender, _) = unbounded();
let msg = ShardMessenger::new(sender);
assert!(matches!(
EventCollectorBuilder::new(&msg)
.add_event_type(EventType::UserUpdate)
.add_user_id(UserId::default())
.add_guild_id(GuildId::default())
.await,
Err(Error::Collector(CollectorError::InvalidEventIdFilters))
));
assert!(matches!(
EventCollectorBuilder::new(&msg)
.add_event_type(EventType::UserUpdate)
.add_user_id(UserId::default())
.await,
Ok(_)
));
}
#[tokio::test]
async fn test_build_with_multiple_event_types() {
let (sender, _) = unbounded();
let msg = ShardMessenger::new(sender);
assert!(matches!(
EventCollectorBuilder::new(&msg)
.add_event_type(EventType::GuildCreate)
.add_event_type(EventType::GuildMemberAdd)
.add_user_id(UserId::default())
.await,
Ok(_)
));
assert!(matches!(
EventCollectorBuilder::new(&msg)
.add_event_type(EventType::GuildCreate)
.add_event_type(EventType::UserUpdate)
.add_channel_id(ChannelId::default())
.await,
Err(Error::Collector(CollectorError::InvalidEventIdFilters))
));
}
}