Skip to main content

longbridge_wscli/
client.rs

1use std::{
2    collections::HashMap,
3    fmt::Debug,
4    str::FromStr,
5    sync::{Arc, LazyLock},
6    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
7};
8
9use futures_util::{
10    SinkExt, StreamExt, TryFutureExt,
11    stream::{SplitSink, SplitStream},
12};
13use leaky_bucket::RateLimiter;
14use longbridge_proto::control::{AuthRequest, AuthResponse, ReconnectRequest, ReconnectResponse};
15use num_enum::IntoPrimitive;
16use prost::Message as _;
17use tokio::{
18    net::TcpStream,
19    sync::{mpsc, oneshot},
20};
21use tokio_tungstenite::{
22    Connector, MaybeTlsStream, WebSocketStream,
23    tungstenite::{Message, client::IntoClientRequest, http::Uri},
24};
25use url::Url;
26
27use crate::{
28    WsClientError, WsClientResult, WsCloseReason, WsEvent, WsResponseErrorDetail, codec::Packet,
29};
30
31/// TLS connector shared by every WebSocket connection.
32///
33/// Without an explicit connector, `connect_async` builds a fresh
34/// `rustls::ClientConfig` per connection, and since we trust the OS
35/// certificate store as well as the bundled roots that means re-reading the
36/// platform trust store on every connect and reconnect. `rustls-native-certs`
37/// does not cache, and a measured read costs ~90ms, which a reconnect loop
38/// would pay over and over. Build the config once instead.
39///
40/// The root set is identical to what `tokio-tungstenite` assembles itself:
41/// the OS trust store plus the bundled webpki roots, unioned. A trust store
42/// that yields nothing is not fatal, exactly as upstream treats it, because
43/// the webpki roots are always added.
44static TLS_CONNECTOR: LazyLock<Connector> = LazyLock::new(|| {
45    let mut root_store = rustls::RootCertStore::empty();
46
47    let native = rustls_native_certs::load_native_certs();
48    if !native.errors.is_empty() {
49        tracing::warn!(errors = ?native.errors, "native root CA certificate loading errors");
50    }
51    let total = native.certs.len();
52    let (added, ignored) = root_store.add_parsable_certificates(native.certs);
53    tracing::debug!(added, total, ignored, "loaded native root certificates");
54
55    root_store.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
56
57    Connector::Rustls(Arc::new(
58        rustls::ClientConfig::builder()
59            .with_root_certificates(root_store)
60            .with_no_client_auth(),
61    ))
62});
63
64const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
65const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
66const HEARTBEAT_TIMEOUT: Duration = Duration::from_secs(120);
67const AUTH_TIMEOUT: Duration = Duration::from_secs(5);
68const RECONNECT_TIMEOUT: Duration = Duration::from_secs(5);
69
70const COMMAND_CODE_AUTH: u8 = 2;
71const COMMAND_CODE_RECONNECT: u8 = 3;
72
73/// Longbridge websocket protocol version
74#[derive(Debug, IntoPrimitive, Copy, Clone, Eq, PartialEq, Hash)]
75#[repr(i32)]
76pub enum ProtocolVersion {
77    /// Version 1
78    Version1 = 1,
79}
80
81/// Longbridge websocket codec type
82#[derive(Debug, IntoPrimitive, Copy, Clone, Eq, PartialEq, Hash)]
83#[repr(i32)]
84pub enum CodecType {
85    /// Protobuf
86    Protobuf = 1,
87}
88
89/// Longbridge websocket platform type
90#[derive(Debug, IntoPrimitive, Copy, Clone, Eq, PartialEq, Hash)]
91#[repr(i32)]
92pub enum Platform {
93    /// OpenAPI
94    OpenAPI = 9,
95}
96
97enum Command {
98    Request {
99        command_code: u8,
100        timeout_millis: u16,
101        body: Vec<u8>,
102        reply_tx: oneshot::Sender<WsClientResult<Vec<u8>>>,
103    },
104}
105
106/// Rate limiter config
107#[derive(Debug, Copy, Clone)]
108pub struct RateLimit {
109    /// The time duration between which we add refill number to the bucket
110    pub interval: Duration,
111    /// The initial number of tokens
112    pub initial: usize,
113    /// The max number of tokens to use
114    pub max: usize,
115    /// The number of tokens to add at each interval interval
116    pub refill: usize,
117}
118
119impl From<RateLimit> for RateLimiter {
120    fn from(config: RateLimit) -> Self {
121        RateLimiter::builder()
122            .interval(config.interval)
123            .refill(config.refill)
124            .max(config.max)
125            .initial(config.initial)
126            .build()
127    }
128}
129
130struct Context<'a> {
131    request_id: u32,
132    inflight_requests: HashMap<u32, oneshot::Sender<WsClientResult<Vec<u8>>>>,
133    sink: SplitSink<WebSocketStream<MaybeTlsStream<TcpStream>>, Message>,
134    stream: SplitStream<WebSocketStream<MaybeTlsStream<TcpStream>>>,
135    command_rx: &'a mut mpsc::UnboundedReceiver<Command>,
136    event_sender: &'a mut mpsc::UnboundedSender<WsEvent>,
137}
138
139impl<'a> Context<'a> {
140    fn new(
141        conn: WebSocketStream<MaybeTlsStream<TcpStream>>,
142        command_rx: &'a mut mpsc::UnboundedReceiver<Command>,
143        event_sender: &'a mut mpsc::UnboundedSender<WsEvent>,
144    ) -> Self {
145        let (sink, stream) = conn.split();
146        Context {
147            request_id: 0,
148            inflight_requests: Default::default(),
149            sink,
150            stream,
151            command_rx,
152            event_sender,
153        }
154    }
155
156    #[inline]
157    fn get_request_id(&mut self) -> u32 {
158        self.request_id += 1;
159        self.request_id
160    }
161
162    fn send_event(&mut self, event: WsEvent) {
163        let _ = self.event_sender.send(event);
164    }
165
166    async fn process_loop(&mut self) -> WsClientResult<()> {
167        let mut ping_time = Instant::now();
168        let mut checkout_timeout = tokio::time::interval(Duration::from_secs(1));
169
170        loop {
171            tokio::select! {
172                item = self.stream.next() => {
173                    match item.transpose()? {
174                        Some(msg) => {
175                            if msg.is_ping() {
176                                tracing::debug!("ping");
177                                ping_time = Instant::now();
178                            }
179                            self.handle_message(msg).await?;
180                        },
181                        None => return Err(WsClientError::ConnectionClosed { reason: None }),
182                    }
183                }
184                item = self.command_rx.recv() => {
185                    match item {
186                        Some(command) => self.handle_command(command).await?,
187                        None => return Ok(()),
188                    }
189                }
190                _ = checkout_timeout.tick() => {
191                    if (Instant::now() - ping_time) > HEARTBEAT_TIMEOUT {
192                        tracing::info!("heartbeat timeout");
193                        return Err(WsClientError::ConnectionClosed { reason: None });
194                    }
195                }
196            }
197        }
198    }
199
200    async fn handle_command(&mut self, command: Command) -> WsClientResult<()> {
201        match command {
202            Command::Request {
203                command_code,
204                timeout_millis: timeout,
205                body,
206                reply_tx,
207            } => {
208                let request_id = self.get_request_id();
209                let msg = Message::Binary(
210                    Packet::Request {
211                        command_code,
212                        request_id,
213                        timeout_millis: timeout,
214                        body,
215                        signature: None,
216                    }
217                    .encode()
218                    .into(),
219                );
220                self.inflight_requests.insert(request_id, reply_tx);
221                self.sink.send(msg).await?;
222                Ok(())
223            }
224        }
225    }
226
227    async fn handle_message(&mut self, msg: Message) -> WsClientResult<()> {
228        match msg {
229            Message::Ping(data) => {
230                self.sink.send(Message::Pong(data)).await?;
231            }
232            Message::Binary(data) => match Packet::decode(&data)? {
233                Packet::Response {
234                    request_id,
235                    status,
236                    body,
237                    ..
238                } => {
239                    if let Some(sender) = self.inflight_requests.remove(&request_id) {
240                        if status == 0 {
241                            let _ = sender.send(Ok(body));
242                        } else {
243                            let detail = longbridge_proto::Error::decode(&*body).ok().map(
244                                |longbridge_proto::Error { code, msg }| WsResponseErrorDetail {
245                                    code,
246                                    msg,
247                                },
248                            );
249                            let _ =
250                                sender.send(Err(WsClientError::ResponseError { status, detail }));
251                        }
252                    }
253                }
254                Packet::Push {
255                    command_code, body, ..
256                } => {
257                    let _ = self.event_sender.send(WsEvent::Push { command_code, body });
258                }
259                _ => return Err(WsClientError::UnexpectedResponse),
260            },
261            Message::Close(Some(close_frame)) => {
262                return Err(WsClientError::ConnectionClosed {
263                    reason: Some(WsCloseReason {
264                        code: close_frame.code,
265                        message: close_frame.reason.to_string(),
266                    }),
267                });
268            }
269            _ => return Err(WsClientError::UnexpectedResponse),
270        }
271
272        Ok(())
273    }
274}
275
276/// The session for the Websocket connection
277#[derive(Debug)]
278pub struct WsSession {
279    /// Session id
280    pub session_id: String,
281    /// The expiration time of the session id.
282    pub deadline: SystemTime,
283}
284
285impl WsSession {
286    /// Returns `true` if the session id is expired, otherwise returns `false
287    #[inline]
288    pub fn is_expired(&self) -> bool {
289        self.deadline < SystemTime::now()
290    }
291}
292
293/// Longbridge Websocket client
294pub struct WsClient {
295    command_tx: mpsc::UnboundedSender<Command>,
296    rate_limit: Arc<HashMap<u8, RateLimiter>>,
297}
298
299impl WsClient {
300    /// Connect to `url` and returns a `WsClient` object
301    pub async fn open(
302        request: impl IntoClientRequest,
303        version: ProtocolVersion,
304        codec: CodecType,
305        platform: Platform,
306        event_sender: mpsc::UnboundedSender<WsEvent>,
307        rate_limit: Vec<(u8, RateLimit)>,
308    ) -> WsClientResult<Self> {
309        let (command_tx, command_rx) = mpsc::unbounded_channel();
310        let conn = do_connect(request, version, codec, platform).await?;
311        tokio::spawn(client_loop(conn, command_rx, event_sender));
312        Ok(Self {
313            command_tx,
314            rate_limit: Arc::new(
315                rate_limit
316                    .into_iter()
317                    .map(|(cmd, rate_limit)| (cmd, rate_limit.into()))
318                    .collect(),
319            ),
320        })
321    }
322
323    /// Set the rate limit
324    pub fn set_rate_limit(&mut self, rate_limit: Vec<(u8, RateLimit)>) {
325        self.rate_limit = Arc::new(
326            rate_limit
327                .into_iter()
328                .map(|(cmd, rate_limit)| (cmd, rate_limit.into()))
329                .collect(),
330        );
331    }
332
333    /// Send an authentication request to get a [`WsSession`]
334    ///
335    /// Reference: <https://open.longbridge.com/en/docs/socket-token-api>
336    /// Reference: <https://open.longbridge.com/en/docs/socket/control-command#auth>
337    pub async fn request_auth(
338        &self,
339        otp: impl Into<String>,
340        metadata: HashMap<String, String>,
341    ) -> WsClientResult<WsSession> {
342        let resp: AuthResponse = self
343            .request(
344                COMMAND_CODE_AUTH,
345                Some(AUTH_TIMEOUT),
346                AuthRequest {
347                    token: otp.into(),
348                    metadata,
349                },
350            )
351            .await?;
352        let expires_mills = resp.expires.saturating_sub(
353            SystemTime::now()
354                .duration_since(UNIX_EPOCH)
355                .unwrap()
356                .as_millis() as i64,
357        ) as u64;
358        let deadline = SystemTime::now() + Duration::from_millis(expires_mills);
359        Ok(WsSession {
360            session_id: resp.session_id,
361            deadline,
362        })
363    }
364
365    /// Send a reconnect request to get a [`WsSession`]
366    ///
367    /// Reference: <https://open.longbridge.com/en/docs/socket/control-command#reconnect>
368    pub async fn request_reconnect(
369        &self,
370        session_id: impl Into<String>,
371        metadata: HashMap<String, String>,
372    ) -> WsClientResult<WsSession> {
373        let resp: ReconnectResponse = self
374            .request(
375                COMMAND_CODE_RECONNECT,
376                Some(RECONNECT_TIMEOUT),
377                ReconnectRequest {
378                    session_id: session_id.into(),
379                    metadata,
380                },
381            )
382            .await?;
383        Ok(WsSession {
384            session_id: resp.session_id,
385            deadline: SystemTime::now() + Duration::from_millis(resp.expires as u64),
386        })
387    }
388
389    /// Send a raw request
390    pub async fn request_raw(
391        &self,
392        command_code: u8,
393        timeout: Option<Duration>,
394        body: Vec<u8>,
395    ) -> WsClientResult<Vec<u8>> {
396        if let Some(rate_limit) = self.rate_limit.get(&command_code) {
397            rate_limit.acquire_one().await;
398        }
399
400        let (reply_tx, reply_rx) = oneshot::channel();
401        self.command_tx
402            .send(Command::Request {
403                command_code,
404                timeout_millis: timeout.unwrap_or(REQUEST_TIMEOUT).as_millis().min(60000) as u16,
405                body,
406                reply_tx,
407            })
408            .map_err(|_| WsClientError::ClientClosed)?;
409        let resp = tokio::time::timeout(
410            REQUEST_TIMEOUT,
411            reply_rx.map_err(|_| WsClientError::ClientClosed),
412        )
413        .map_err(|_| WsClientError::RequestTimeout)
414        .await???;
415        Ok(resp)
416    }
417
418    /// Send a request `T` to get a response `R`
419    pub async fn request<T, R>(
420        &self,
421        command_code: u8,
422        timeout: Option<Duration>,
423        req: T,
424    ) -> WsClientResult<R>
425    where
426        T: prost::Message + Debug,
427        R: prost::Message + Default + Debug,
428    {
429        tracing::info!(message = ?req, "ws request");
430        let resp = self
431            .request_raw(command_code, timeout, req.encode_to_vec())
432            .await?;
433        let resp = R::decode(&*resp)?;
434        tracing::info!(message = ?resp, "ws response");
435        Ok(resp)
436    }
437}
438
439async fn do_connect(
440    request: impl IntoClientRequest,
441    version: ProtocolVersion,
442    codec: CodecType,
443    platform: Platform,
444) -> WsClientResult<WebSocketStream<MaybeTlsStream<TcpStream>>> {
445    let mut request = request.into_client_request()?;
446    let mut url_obj = Url::parse(&request.uri().to_string())?;
447    url_obj.query_pairs_mut().extend_pairs(&[
448        ("version", i32::from(version).to_string()),
449        ("codec", i32::from(codec).to_string()),
450        ("platform", i32::from(platform).to_string()),
451    ]);
452    *request.uri_mut() = Uri::from_str(url_obj.as_ref()).expect("valid url");
453
454    let conn = match tokio::time::timeout(
455        CONNECT_TIMEOUT,
456        tokio_tungstenite::connect_async_tls_with_config(
457            request,
458            None,
459            false,
460            Some(TLS_CONNECTOR.clone()),
461        )
462        .map_err(WsClientError::from),
463    )
464    .map_err(|_| WsClientError::ConnectTimeout)
465    .await
466    .and_then(std::convert::identity)
467    {
468        Ok((conn, _)) => conn,
469        Err(err) => return Err(err),
470    };
471
472    Ok(conn)
473}
474
475async fn client_loop(
476    conn: WebSocketStream<MaybeTlsStream<TcpStream>>,
477    mut command_tx: mpsc::UnboundedReceiver<Command>,
478    mut event_sender: mpsc::UnboundedSender<WsEvent>,
479) {
480    let mut ctx = Context::new(conn, &mut command_tx, &mut event_sender);
481
482    let res = ctx.process_loop().await;
483    match res {
484        Ok(()) => return,
485        Err(err) => {
486            ctx.send_event(WsEvent::Error(err));
487        }
488    };
489
490    for sender in ctx.inflight_requests.into_values() {
491        let _ = sender.send(Err(WsClientError::Cancelled));
492    }
493}