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
use std::sync::Arc;

use async_trait::async_trait;
use bonsaidb_core::{
    arc_bytes::serde::Bytes,
    networking::{CreateSubscriber, Publish, PublishToAll, SubscribeTo, UnsubscribeFrom},
    pubsub::{AsyncPubSub, AsyncSubscriber, Receiver},
};

use crate::Client;

#[async_trait]
impl AsyncPubSub for super::RemoteDatabase {
    type Subscriber = RemoteSubscriber;

    async fn create_subscriber(&self) -> Result<Self::Subscriber, bonsaidb_core::Error> {
        let subscriber_id = self
            .client
            .send_api_request_async(&CreateSubscriber {
                database: self.name.to_string(),
            })
            .await?;

        let (sender, receiver) = flume::unbounded();
        self.client.register_subscriber(subscriber_id, sender);
        Ok(RemoteSubscriber {
            client: self.client.clone(),
            database: self.name.clone(),
            id: subscriber_id,
            receiver: Receiver::new(receiver),
            #[cfg(not(target_arch = "wasm32"))]
            tokio: tokio::runtime::Handle::try_current().ok().map(Arc::new),
        })
    }

    async fn publish_bytes(
        &self,
        topic: Vec<u8>,
        payload: Vec<u8>,
    ) -> Result<(), bonsaidb_core::Error> {
        self.client
            .send_api_request_async(&Publish {
                database: self.name.to_string(),
                topic: Bytes::from(topic),
                payload: Bytes::from(payload),
            })
            .await?;
        Ok(())
    }

    async fn publish_bytes_to_all(
        &self,
        topics: impl IntoIterator<Item = Vec<u8>> + Send + 'async_trait,
        payload: Vec<u8>,
    ) -> Result<(), bonsaidb_core::Error> {
        let topics = topics.into_iter().map(Bytes::from).collect();
        self.client
            .send_api_request_async(&PublishToAll {
                database: self.name.to_string(),
                topics,
                payload: Bytes::from(payload),
            })
            .await?;
        Ok(())
    }
}

/// A `PubSub` subscriber from a remote server.
#[derive(Debug)]
pub struct RemoteSubscriber {
    pub(crate) client: Client,
    pub(crate) database: Arc<String>,
    pub(crate) id: u64,
    pub(crate) receiver: Receiver,
    #[cfg(not(target_arch = "wasm32"))]
    pub(crate) tokio: Option<Arc<tokio::runtime::Handle>>,
}

#[async_trait]
impl AsyncSubscriber for RemoteSubscriber {
    async fn subscribe_to_bytes(&self, topic: Vec<u8>) -> Result<(), bonsaidb_core::Error> {
        self.client
            .send_api_request_async(&SubscribeTo {
                database: self.database.to_string(),
                subscriber_id: self.id,
                topic: Bytes::from(topic),
            })
            .await?;
        Ok(())
    }

    async fn unsubscribe_from_bytes(&self, topic: &[u8]) -> Result<(), bonsaidb_core::Error> {
        self.client
            .send_api_request_async(&UnsubscribeFrom {
                database: self.database.to_string(),
                subscriber_id: self.id,
                topic: Bytes::from(topic),
            })
            .await?;
        Ok(())
    }

    fn receiver(&self) -> &Receiver {
        &self.receiver
    }
}

#[cfg(target_arch = "wasm32")]
impl Drop for RemoteSubscriber {
    fn drop(&mut self) {
        let client = self.client.clone();
        let database = self.database.to_string();
        let subscriber_id = self.id;
        let drop_future = async move {
            client
                .unregister_subscriber_async(database, subscriber_id)
                .await;
        };
        wasm_bindgen_futures::spawn_local(drop_future);
    }
}

#[cfg(not(target_arch = "wasm32"))]
impl Drop for RemoteSubscriber {
    fn drop(&mut self) {
        if let Some(tokio) = &self.tokio {
            let client = self.client.clone();
            let database = self.database.to_string();
            let subscriber_id = self.id;
            tokio.spawn(async move {
                client
                    .unregister_subscriber_async(database, subscriber_id)
                    .await;
            });
        } else {
            self.client
                .unregister_subscriber(self.database.to_string(), self.id);
        }
    }
}