native_db_32bit/watch/
mod.rs

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
mod batch;
mod event;
mod filter;
pub mod query;
mod request;
mod sender;

pub(crate) use batch::*;
pub use event::*;
pub(crate) use filter::*;
pub(crate) use request::*;
pub(crate) use sender::*;

use std::sync::{Arc, RwLock, TryLockError};
use thiserror::Error;

#[derive(Error, Debug)]
pub enum WatchEventError {
    #[error("TryLockErrorPoisoned")]
    // TryLockErrorPoisoned(Batch<'a>), // TODO: remove 'a lifetime from Batch Error
    TryLockErrorPoisoned,
    #[error("TryLockErrorWouldBlock")]
    // TryLockErrorWouldBlock(Batch<'a>), // TODO: remove 'a lifetime from Batch Error
    TryLockErrorWouldBlock,
    #[cfg(not(feature = "tokio"))]
    #[error("SendError")]
    SendError(#[from] std::sync::mpsc::SendError<Event>),
    #[cfg(feature = "tokio")]
    #[error("SendError")]
    SendError(#[from] tokio::sync::mpsc::error::SendError<Event>),
}

#[cfg(not(feature = "tokio"))]
pub type MpscSender<T> = std::sync::mpsc::Sender<T>;
#[cfg(not(feature = "tokio"))]
pub type MpscReceiver<T> = std::sync::mpsc::Receiver<T>;

#[cfg(feature = "tokio")]
pub type MpscSender<T> = tokio::sync::mpsc::UnboundedSender<T>;
#[cfg(feature = "tokio")]
pub type MpscReceiver<T> = tokio::sync::mpsc::UnboundedReceiver<T>;

pub(crate) fn push_batch(
    senders: Arc<RwLock<Watchers>>,
    batch: Batch,
) -> Result<(), WatchEventError> {
    let watchers = senders.try_read().map_err(|err| match err {
        TryLockError::Poisoned(_) => WatchEventError::TryLockErrorPoisoned,
        TryLockError::WouldBlock => WatchEventError::TryLockErrorWouldBlock,
    })?;

    for (watcher_request, event) in batch {
        for sender in watchers.find_senders(&watcher_request) {
            let sender = sender.lock().unwrap();
            sender.send(event.clone())?;
        }
    }

    Ok(())
}