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
|
use std::{
any::Any,
collections::{HashMap, HashSet},
mem,
sync::{Arc, Mutex, MutexGuard},
};
use web_push::{PartialVapidSignatureBuilder, SubscriptionInfo, WebPushError};
use crate::{error::failed::Failed, push::Publish};
#[derive(Clone)]
pub struct Client(Arc<Mutex<ClientInner>>);
#[derive(Default)]
struct ClientInner {
sent: Vec<Publication>,
planned_failures: HashMap<SubscriptionInfo, WebPushError>,
}
impl Client {
pub fn new() -> Self {
Self(Arc::default())
}
fn inner(&self) -> MutexGuard<'_, ClientInner> {
self.0.lock().unwrap()
}
// Clears the list of sent messages (for all clones of this Client) when called, because we
// can't clone `Publications`s, so we either need to move them or try to reconstruct them.
pub fn sent(&self) -> Vec<Publication> {
let sent = &mut self.inner().sent;
mem::take(sent)
}
pub fn fail_next(&self, subscription_info: &SubscriptionInfo, err: WebPushError) {
let planned_failures = &mut self.inner().planned_failures;
planned_failures.insert(subscription_info.clone(), err);
}
}
#[async_trait::async_trait]
impl Publish for Client {
async fn publish<'s, M>(
&self,
message: M,
_: &PartialVapidSignatureBuilder,
subscriptions: impl IntoIterator<Item = &'s SubscriptionInfo> + Send,
) -> Result<Vec<(&'s SubscriptionInfo, WebPushError)>, Failed>
where
M: Send + 'static,
{
let mut inner = self.inner();
let message: Box<dyn Any + Send> = Box::new(message);
let mut recipients = HashSet::new();
let mut failures = Vec::new();
for subscription in subscriptions {
recipients.insert(subscription.clone());
if let Some(err) = inner.planned_failures.remove(subscription) {
failures.push((subscription, err));
}
}
let publication = Publication {
message,
recipients,
};
inner.sent.push(publication);
Ok(failures)
}
}
#[derive(Debug)]
pub struct Publication {
pub message: Box<dyn Any + Send>,
pub recipients: HashSet<SubscriptionInfo>,
}
impl Publication {
pub fn message_eq<M>(&self, candidate: &M) -> bool
where
M: PartialEq + 'static,
{
match self.message.downcast_ref::<M>() {
None => false,
Some(message) => message == candidate,
}
}
}
|