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
use crate::net::nats_tcp_stream::NatsTcpStream;
use crate::ops::{Subscribe, Message, Publish};
use futures::{StreamExt};
use crate::nats_client::{NatsClient, NatsClientOptions, NatsClientInner, NatsSid, ReconnectHandler, NatsClientState};

use std::sync::{Arc, RwLock};
use crate::error::RatsioError;

use futures::lock::Mutex;
use nom::lib::std::collections::{HashMap};
use futures::stream::Stream;

impl NatsClient {
    pub async fn new<O>(options: O) -> Result<Arc<Self>, RatsioError>
        where O: Into<NatsClientOptions> {
        let opts = options.into();
        let tcp_stream = NatsClientInner::try_connect(opts.clone(), &opts.cluster_uris.0, false).await?;
        let (sink, stream) = NatsTcpStream::new(tcp_stream).await.split();

        let version = 1;
        let client = NatsClient {
            inner: Arc::new(NatsClientInner {
                conn_sink: Arc::new(Mutex::new(sink)),
                opts,
                server_info: RwLock::new(None),
                subscriptions: Arc::new(Mutex::new(HashMap::default())),
                on_reconnect: std::sync::Mutex::new(None),
                state: RwLock::new(NatsClientState::Connecting),
                last_ping: RwLock::new(NatsClientInner::time_in_millis()),
                reconnect_version: RwLock::new(version),
                client_ref: RwLock::new(None),
            }),
            reconnect_handlers: RwLock::new(Vec::new()),
        };
        match NatsClientInner::start(client.inner.clone(), version,stream).await {
            Ok(_) => {},
            Err(err) => {
                let _ = client.close().await;
                return Err(err)
            }
        }

        let arc_client = Arc::new(client);
        let reconn_client = arc_client.clone();


        if let Ok(mut client_ref) = arc_client.inner.client_ref.write() {
            *client_ref = Some(arc_client.clone());
        }

        if let Ok(mut reconnect) = arc_client.inner.on_reconnect.lock() {
            *reconnect = Some(Box::new(move || { reconn_client.on_reconnect() }));
        }

        //heartbeat monitor
        let heartbeat_client = arc_client.clone();
        tokio::spawn(async move {
            let _ = heartbeat_client.inner.monitor_heartbeat().await;
        });
        Ok(arc_client)
    }

    pub async fn subscribe<T>(
        &self,
        subject: T,
    ) -> Result<(NatsSid, impl Stream<Item=Message> + Send + Sync), RatsioError>
        where T: ToString {
        let cmd = Subscribe {
            subject: subject.to_string(),
            ..Default::default()
        };
        self.inner.subscribe(cmd).await
    }

    pub async fn subscribe_with_group<T>(
        &self,
        subject: T,
        group: T,
    ) -> Result<(NatsSid, impl Stream<Item=Message> + Send + Sync), RatsioError>
        where T: ToString {
        let cmd = Subscribe {
            subject: subject.to_string(),
            queue_group: Some(group.to_string()),
            ..Default::default()
        };
        self.inner.subscribe(cmd).await
    }

    pub async fn un_subscribe(
        &self,
        sid: &NatsSid,
    ) -> Result<(), RatsioError> {
        self.inner.un_subscribe(sid.clone()).await
    }

    pub async fn publish<T>(
        &self,
        subject: T,
        data: &[u8],
    ) -> Result<(), RatsioError>
        where T: ToString {
        let cmd = Publish {
            subject: subject.to_string(),
            reply_to: None,
            payload: Vec::from(data),
        };
        self.inner.publish(cmd).await
    }


    pub async fn publish_with_reply_to<T>(
        &self,
        subject: T,
        reply_to: T,
        data: &[u8],
    ) -> Result<(), RatsioError>
        where T: ToString {
        let cmd = Publish {
            subject: subject.to_string(),
            reply_to: Some(reply_to.to_string()),
            payload: Vec::from(data),
        };
        self.inner.publish(cmd).await
    }


    pub async fn request<T>(
        &self,
        subject: T,
        data: &[u8],
    ) -> Result<Message, RatsioError>
        where T: ToString {
        let cmd = Publish {
            subject: subject.to_string(),
            payload: Vec::from(data),
            reply_to: None,
        };
        self.inner.request(cmd).await
    }

    pub async fn close(&self) -> Result<(), RatsioError> {
        self.inner.stop().await
    }

    pub fn add_reconnect_handler(&self, handler: ReconnectHandler) -> Result<(), RatsioError> {
        if let Ok(mut handlers) = self.reconnect_handlers.write() {
            handlers.push(handler);
        }
        Ok(())
    }

    pub (in crate::nats_client) fn on_reconnect(&self) -> () {
        if let Ok(handlers) = self.reconnect_handlers.read() {
            let handlers: &Vec<ReconnectHandler> = handlers.as_ref();
            for handler in handlers {
                handler(self)
            }
        }
    }
}