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
use cfg_if::cfg_if;

cfg_if! {
    if #[cfg(target_arch = "wasm32")] {
        mod wasm;
        pub use wasm::WebSocketInterface;
    } else {
        mod native;
        pub use native::WebSocketInterface;
    }
}

pub mod settings;
pub mod result;
pub mod error;
pub mod message;
pub mod event;
pub mod state;

pub use result::Result;
pub use error::Error;
pub use settings::Settings;
pub use message::*;

pub use message::Message;

use std::sync::Arc;
use async_std::channel::{Receiver,Sender,unbounded,bounded};
use workflow_core::channel::oneshot;
use workflow_core::trigger::Listener;

struct Inner {
    client : Arc<WebSocketInterface>,
    sender_tx : Sender<DispatchMessage>,
    receiver_rx : Receiver<Message>,
}

impl Inner {
    pub fn new(
        client: Arc<WebSocketInterface>,
        sender_tx: Sender<DispatchMessage>,
        receiver_rx: Receiver<Message>,
    ) -> Self {
        Self {
            client,
            sender_tx,
            receiver_rx,
        }
    }
}

#[derive(Clone)] 
pub struct WebSocket {
    inner: Arc<Inner>,
}

impl WebSocket {
    pub fn new(url : &str, settings : Settings) -> Result<WebSocket> {

        let (receiver_tx, receiver_rx) = 
            if settings.receiver_channel_bounds == 0 {
                unbounded::<Message>()
            } else {
                bounded(settings.receiver_channel_bounds)
            };
        let (sender_tx, sender_tx_rx) = { 
            if settings.sender_channel_bounds == 0 {
                let tx_rx = unbounded::<DispatchMessage>();
                let tx = tx_rx.0.clone();
                (tx, tx_rx)
            } else {
                let tx_rx = bounded::<DispatchMessage>(settings.sender_channel_bounds);
                let tx = tx_rx.0.clone();
                (tx, tx_rx)
            }
        };

        let client = Arc::new(WebSocketInterface::new(
            url,
            receiver_tx,
            sender_tx_rx
        )?);

        let websocket = WebSocket { 
            inner : Arc::new(Inner::new(
                client, sender_tx, receiver_rx
            )) 
        };

        Ok(websocket)
    }

    /// Get current websocket connection URL
    pub fn url(&self) -> String {
        self.inner.client.url()
    }

    /// Changes WebSocket connection URL.
    /// Following this call, you must invoke
    /// `WebSocket::reconnect().await` manually
    pub fn set_url(&self, url : &str) {
        self.inner.client.set_url(url);
    }


    ///
    /// Returns reference to the transmission channel.
    /// You can clone the channel and use it directly.
    /// The channel sends DispatchMessage struct that
    /// has two values:
    /// 
    ///     - DispatchMessage::Post(Message)
    ///     - DispatchMessage::WithAck(Message, Sender<Result<Arc<(),Arc<Error>>>)
    /// 
    /// To use WithAck message, you need to create an instance
    /// of `oneshot` channel and supply the sender, while retain
    /// and await on receiver.recv() to get acknowledgement that
    /// the message has been successfully handed off to the underlying
    /// websocket.
    /// 
    pub fn sender_tx<'ws>(&'ws self) -> &'ws Sender<DispatchMessage> {
        &self.inner.sender_tx
    }

    /// Returns the reference to the receiver channel
    pub fn receiver_rx<'ws>(&'ws self) -> &'ws Receiver<Message> {
        &self.inner.receiver_rx
    }

    /// Returns true if websocket is connected, false otherwise
    pub fn is_open(&self) -> bool {
        self.inner.client.is_open()
    }

    /// Connects the websocket to the destination URL.
    /// Optionally accepts `block_until_connected` argument
    /// that will block the async execution until the websocket
    /// is connected.
    /// 
    /// Once invoked, connection task will run in the background
    /// and will attempt to repeatedly reconnect if the websocket
    /// connection is closed.
    /// 
    /// To suspend reconnection, you have to call `disconnect()`
    /// method explicitly.
    /// 
    pub async fn connect(&self, block_until_connected : bool) -> Result<Option<Listener>> {
        Ok(self.inner.client.connect(block_until_connected).await?)
    }

    /// Disconnects the websocket from the destination server.
    pub async fn disconnect(&self) -> Result<()> {
        Ok(self.inner.client.disconnect().await?)
    }

    /// Trigger WebSocket to reconnect.  This method
    /// closes the underlying WebSocket connection
    /// causing the WebSocket implementation to 
    /// re-initiate connection.
    pub async fn reconnect(&self) -> Result<()> {
        Ok(self.inner.client.close().await?)
    }

    /// Sends a message to the destination server. This function
    /// will queue the message on the relay channel and return
    /// successfully if the message has been queued.
    /// This function enforces async yield in order to prevent
    /// potential blockage of the executor if it is being executed
    /// in tight loops.
    pub async fn post(&self, message: Message) -> Result<&Self> {
        if !self.inner.client.is_open() {
            return Err(Error::NotConnected);
        }
        
        let result = Ok(self.inner.sender_tx.send(DispatchMessage::Post(message)).await?);
        workflow_core::task::yield_now().await;
        result.map(|_| self)
    }

    /// Sends a message to the destination server. This function
    /// will block until until the message was relayed to the
    /// underlying websocket implementation.
    pub async fn send(&self, message: Message) -> std::result::Result<&Self,Arc<Error>> {
        if !self.inner.client.is_open() {
            return Err(Arc::new(Error::NotConnected));
        }
        
        let (sender, receiver) = oneshot(); 
        self.inner.sender_tx.send(DispatchMessage::WithAck(message, sender)).await
            .map_err(|err|Arc::new(err.into()))?;
    
        receiver.recv().await.map_err(|_|Arc::new(Error::DispatchChannelAck))?
            .map(|_|self)
    }

    /// Receives message from the websocket. Blocks until a message is
    /// received from the underlying websocket connection.
    pub async fn recv(&self) -> Result<Message> {
        Ok(self.inner.receiver_rx.recv().await?)
    }

    /// Helper function that will relay a Ctl enum to the receiver
    /// in the form of `Message::Ctl(Ctl::*)`
    /// This should be called only with Ctl::Custom(u32) as other
    /// control messages are issues by the underlying websocket implementation
    pub fn inject_ctl(&self, ctl : Ctl) -> Result<()> {
        Ok(self.inner.client.inject_ctl(ctl)?)
    }
}