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
//! Contains the [`Subscription`] struct that is returned by `subscribe` functions from an [`EvidentPublisher`].
//!
//! [req:subs]
use std::{
collections::{HashMap, HashSet},
hash::Hash,
sync::{
mpsc::{Receiver, SyncSender},
Arc,
},
};
use crate::{
event::{entry::EventEntry, filter::Filter, Event, Id, Msg},
publisher::{CaptureControl, EvidentPublisher},
};
/// Subscription that is returned when subscribing to events captured by an [`EvidentPublisher`].
///
///[req:subs]
pub struct Subscription<'p, K, M, T, F>
where
K: Id + CaptureControl,
M: Msg,
T: EventEntry<K, M>,
F: Filter<K, M>,
{
/// The ID of the channel used to send events from the [`EvidentPublisher`] to the [`Subscription`].
pub(crate) channel_id: crate::uuid::Uuid,
/// The channel [`Receiver`] used to receive captured events from the [`EvidentPublisher`].
pub(crate) receiver: Receiver<Arc<Event<K, M, T>>>,
/// Flag set to `true` if this [`Subscription`] is subscribed to receive all captured events.
pub(crate) sub_to_all: bool,
/// Optional set of event-IDs this [`Subscription`] is subscribed to.
///
/// **Note:** Only relevant for subscriptions to specific event-IDs.
pub(crate) subscriptions: Option<HashSet<K>>,
/// A reference to the [`EvidentPublisher`] the [`Subscription`] was created from.
pub(crate) publisher: &'p EvidentPublisher<K, M, T, F>,
}
impl<'p, K, M, T, F> Subscription<'p, K, M, T, F>
where
K: Id + CaptureControl,
M: Msg,
T: EventEntry<K, M>,
F: Filter<K, M>,
{
/// Get the [`Receiver`] of the subscription channel.
pub fn get_receiver(&self) -> &Receiver<Arc<Event<K, M, T>>> {
&self.receiver
}
/// Unsubscribes this subscription.
pub fn unsubscribe(self) {
drop(self)
}
/// Unsubscribes from the given event-ID.
///
/// **Note:** Only possible for subscriptions to specific IDs.
///
/// # Arguments
///
/// * `id` ... Event-ID the subscription should be unsubscribed from
///
/// # Possible Errors
///
/// * [`SubscriptionError::IdNotSubscribed`] ... If athe given ID was not subscribed,
/// * [`SubscriptionError::UnsubscribeWouldDeleteSubscription`] ... If the [`Subscription`] would not be subscribed to any ID afterwards
/// * [`SubscriptionError::AllEventsSubscriptionNotModifiable`] ... If the [`Subscription`] was created to receive all events
pub fn unsubscribe_id(&mut self, id: K) -> Result<(), SubscriptionError<K>> {
self.unsubscribe_many(vec![id])
}
/// Unsubscribes from the given list of event-IDs.
///
/// **Note:** Only possible for subscriptions to specific IDs.
///
/// # Arguments
///
/// * `ids` ... List of event-IDs the subscription should be unsubscribed from
///
/// # Possible Errors
///
/// * [`SubscriptionError::IdNotSubscribed`] ... If any of the given IDs was not subscribed,
/// * [`SubscriptionError::UnsubscribeWouldDeleteSubscription`] ... If the [`Subscription`] would not be subscribed to any ID afterwards
/// * [`SubscriptionError::AllEventsSubscriptionNotModifiable`] ... If the [`Subscription`] was created to receive all events
pub fn unsubscribe_many(&mut self, ids: Vec<K>) -> Result<(), SubscriptionError<K>> {
if self.sub_to_all || self.subscriptions.is_none() {
return Err(SubscriptionError::AllEventsSubscriptionNotModifiable);
}
let subs = self.subscriptions.as_mut().unwrap();
if ids.len() >= subs.len() {
return Err(SubscriptionError::UnsubscribeWouldDeleteSubscription);
}
for id in &ids {
if !subs.contains(id) {
return Err(SubscriptionError::IdNotSubscribed(id.clone()));
}
}
match self.publisher.subscriptions.write() {
Ok(mut publisher_subs) => {
for id in ids {
if let Some(id_sub) = publisher_subs.get_mut(&id) {
let _ = id_sub.remove(&self.channel_id);
}
subs.remove(&id);
}
Ok(())
}
Err(_) => Err(SubscriptionError::CouldNotAccessPublisher),
}
}
/// Subscribes to the given event-ID.
///
/// **Note:** Only possible for subscriptions to specific IDs.
///
/// # Arguments
///
/// * `id` ... Event-ID that should be added to the subscribed IDs by the [`Subscription`]
///
/// # Possible Errors
///
/// * [`SubscriptionError::IdAlreadySubscribed`] ... If the given ID is already subscribed,
/// * [`SubscriptionError::CouldNotAccessPublisher`] ... If the [`Subscription`] has no connection to the [`EvidentPublisher`]
/// * [`SubscriptionError::NoSubscriptionChannelAvailable`] ... If the [`EvidentPublisher`] has no stored channel to this [`Subscription`]
/// * [`SubscriptionError::AllEventsSubscriptionNotModifiable`] ... If the [`Subscription`] was created to receive all events
///
/// [req:subs.specific.one]
pub fn subscribe_id(&mut self, id: K) -> Result<(), SubscriptionError<K>> {
self.subscribe_many(vec![id])
}
/// Subscribes to the given list of event-IDs.
///
/// **Note:** Only possible for subscriptions to specific IDs.
///
/// # Arguments
///
/// * `ids` ... List of event-IDs that should be added to the subscribed IDs by the [`Subscription`]
///
/// # Possible Errors
///
/// * [`SubscriptionError::IdAlreadySubscribed`] ... If one of the given IDs is already subscribed,
/// * [`SubscriptionError::CouldNotAccessPublisher`] ... If the [`Subscription`] has no connection to the [`EvidentPublisher`]
/// * [`SubscriptionError::NoSubscriptionChannelAvailable`] ... If the [`EvidentPublisher`] has no stored channel to this [`Subscription`]
/// * [`SubscriptionError::AllEventsSubscriptionNotModifiable`] ... If the [`Subscription`] was created to receive all events
///
/// [req:subs.specific.mult]
pub fn subscribe_many(&mut self, ids: Vec<K>) -> Result<(), SubscriptionError<K>> {
if self.sub_to_all || self.subscriptions.is_none() {
return Err(SubscriptionError::AllEventsSubscriptionNotModifiable);
}
let subs = self.subscriptions.as_mut().unwrap();
for id in &ids {
if subs.contains(id) {
return Err(SubscriptionError::IdAlreadySubscribed(id.clone()));
}
}
// Needed to clone the *sender* of the subscription channel, which is stored in the publisher.
let any_sub_id = match subs.iter().next() {
Some(id) => id,
None => {
return Err(SubscriptionError::NoSubscriptionChannelAvailable);
}
};
let sender = match self.publisher.subscriptions.read() {
Ok(publisher_subs) => match publisher_subs.get(any_sub_id) {
Some(id_subs) => match id_subs.get(&self.channel_id) {
Some(sub_sender) => sub_sender.clone(),
None => {
return Err(SubscriptionError::NoSubscriptionChannelAvailable);
}
},
None => {
return Err(SubscriptionError::NoSubscriptionChannelAvailable);
}
},
Err(_) => {
return Err(SubscriptionError::CouldNotAccessPublisher);
}
};
match self.publisher.subscriptions.write() {
Ok(mut publisher_subs) => {
for id in ids {
publisher_subs
.entry(id.clone())
.and_modify(|id_subs| {
id_subs.insert(self.channel_id, sender.clone());
})
.or_insert_with(|| {
let mut map = HashMap::new();
map.insert(self.channel_id, sender.clone());
map
});
subs.insert(id);
}
Ok(())
}
Err(_) => Err(SubscriptionError::CouldNotAccessPublisher),
}
}
}
impl<'p, K, M, T, F> Drop for Subscription<'p, K, M, T, F>
where
K: Id + CaptureControl,
M: Msg,
T: EventEntry<K, M>,
F: Filter<K, M>,
{
fn drop(&mut self) {
// Note: We do not want to block the current thread for *unsubscribing*, since publisher also maintains dead channels.
if self.sub_to_all {
if let Ok(mut locked_any_event) = self.publisher.any_event.try_write() {
let _ = locked_any_event.remove(&self.channel_id);
}
} else if let Some(self_subs) = &self.subscriptions {
if let Ok(mut publisher_subs) = self.publisher.subscriptions.try_write() {
for k in self_subs {
if let Some(id_sub) = publisher_subs.get_mut(k) {
let _ = id_sub.remove(&self.channel_id);
}
}
}
}
}
}
impl<'p, K, M, T, F> PartialEq for Subscription<'p, K, M, T, F>
where
K: Id + CaptureControl,
M: Msg,
T: EventEntry<K, M>,
F: Filter<K, M>,
{
fn eq(&self, other: &Self) -> bool {
self.channel_id == other.channel_id
}
}
impl<'p, K, M, T, F> Eq for Subscription<'p, K, M, T, F>
where
K: Id + CaptureControl,
M: Msg,
T: EventEntry<K, M>,
F: Filter<K, M>,
{
}
impl<'p, K, M, T, F> Hash for Subscription<'p, K, M, T, F>
where
K: Id + CaptureControl,
M: Msg,
T: EventEntry<K, M>,
F: Filter<K, M>,
{
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.channel_id.hash(state);
}
}
/// Possible errors for (un)subscribe functions.
#[derive(Debug, Clone)]
pub enum SubscriptionError<K: Id> {
/// This [`Subscription`] was created to listen to all events, which cannot be modified afterwards.
AllEventsSubscriptionNotModifiable,
/// Event-ID is not subscribed.
/// Therefore, the ID cannot be unsubscribed.
///
/// The problematic ID may be accessed at tuple position 0.
IdNotSubscribed(K),
/// Event-ID is already subscribed.
/// Therefore, the ID cannot be re-subscribed.
///
/// The problematic ID may be accessed at tuple position 0.
IdAlreadySubscribed(K),
/// Unsubscribing would remove all subscriptions to specific event-IDs.
/// This would remove all conntections between the [`Subscription`] and the [`EvidentPublisher`], making it impossible to modify the subscription at a later point.
UnsubscribeWouldDeleteSubscription,
/// Could not lock access to the [`EvidentPublisher`].
CouldNotAccessPublisher,
/// No *sender-part* of the subscription-channel between this [`Subscription`] and the [`EvidentPublisher`] is available in the [`EvidentPublisher`].
NoSubscriptionChannelAvailable,
}
/// *Sender-part* of the subscription-channel between a [`Subscription`] and an [`EvidentPublisher`].
///
/// [req:subs]
#[derive(Clone)]
pub(crate) struct SubscriptionSender<K, M, T>
where
K: Id,
M: Msg,
T: EventEntry<K, M>,
{
/// ID to identify the *sender-part* in the [`EvidentPublisher`].
pub(crate) channel_id: crate::uuid::Uuid,
/// [`SyncSender`] of the [`sync_channel`](std::sync::mpsc::sync_channel) between [`Subscription`] and [`EvidentPublisher`].
pub(crate) sender: SyncSender<Arc<Event<K, M, T>>>,
}
impl<K, M, T> PartialEq for SubscriptionSender<K, M, T>
where
K: Id,
M: Msg,
T: EventEntry<K, M>,
{
fn eq(&self, other: &Self) -> bool {
self.channel_id == other.channel_id
}
}
impl<K, M, T> Eq for SubscriptionSender<K, M, T>
where
K: Id,
M: Msg,
T: EventEntry<K, M>,
{
}
impl<K, M, T> Hash for SubscriptionSender<K, M, T>
where
K: Id,
M: Msg,
T: EventEntry<K, M>,
{
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.channel_id.hash(state);
}
}