Skip to main content

dxfeed_graal/
connector.rs

1//! The message connectors of an endpoint (`MessageConnector`); see [`DXEndpoint::get_connectors`].
2//!
3//! [`DXEndpoint::get_connectors`]: crate::DXEndpoint::get_connectors
4
5use std::fmt;
6use std::sync::Arc;
7
8use dxfeed_graal_sys as sys;
9
10use crate::error::{Error, JavaException, Result};
11use crate::handle::Handle;
12use crate::isolate::{self, call};
13
14/// The kind of a [`MessageConnector`]; see [`MessageConnector::get_kind`].
15///
16/// It prints as the SDK constant: `CLIENT_SOCKET`, `SERVER_SOCKET` or `OTHER`.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
18#[non_exhaustive]
19pub enum MessageConnectorKind {
20    /// A client socket connector: an address `host:port`.
21    ClientSocket,
22    /// A server socket connector: an address `:port`.
23    ServerSocket,
24    /// Any other connector, such as a file or a custom one, and a kind that a later SDK adds.
25    Other,
26}
27
28impl MessageConnectorKind {
29    fn from_sys(kind: i32) -> Self {
30        match u32::try_from(kind) {
31            Ok(sys::DXFG_V4_MESSAGE_CONNECTOR_KIND_CLIENT_SOCKET) => MessageConnectorKind::ClientSocket,
32            Ok(sys::DXFG_V4_MESSAGE_CONNECTOR_KIND_SERVER_SOCKET) => MessageConnectorKind::ServerSocket,
33            _ => MessageConnectorKind::Other,
34        }
35    }
36}
37
38impl fmt::Display for MessageConnectorKind {
39    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40        f.pad(match self {
41            MessageConnectorKind::ClientSocket => "CLIENT_SOCKET",
42            MessageConnectorKind::ServerSocket => "SERVER_SOCKET",
43            MessageConnectorKind::Other => "OTHER",
44        })
45    }
46}
47
48/// The state of a [`MessageConnector`] (`MessageConnectorState`); see [`MessageConnector::get_state`].
49///
50/// It prints as the Java constant: `CONNECTING`, `CONNECTED` or `DISCONNECTED`.
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
52#[non_exhaustive]
53pub enum MessageConnectorState {
54    /// Started and not connected yet, or reconnecting after a failure or a drop.
55    Connecting,
56    /// At least one of its connections is established; a server socket connector accepts connections.
57    Connected,
58    /// Stopped: replaced by a connect of its endpoint to another address, or its endpoint disconnected or closed.
59    Disconnected,
60}
61
62impl MessageConnectorState {
63    fn from_sys(state: i32) -> Result<Self> {
64        Ok(match u32::try_from(state) {
65            Ok(sys::DXFG_V4_MESSAGE_CONNECTOR_STATE_CONNECTING) => MessageConnectorState::Connecting,
66            Ok(sys::DXFG_V4_MESSAGE_CONNECTOR_STATE_CONNECTED) => MessageConnectorState::Connected,
67            Ok(sys::DXFG_V4_MESSAGE_CONNECTOR_STATE_DISCONNECTED) => MessageConnectorState::Disconnected,
68            _ => {
69                return Err(Error::InvalidArgument(format!(
70                    "unknown message connector state {state}"
71                )));
72            }
73        })
74    }
75}
76
77impl fmt::Display for MessageConnectorState {
78    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
79        f.pad(match self {
80            MessageConnectorState::Connecting => "CONNECTING",
81            MessageConnectorState::Connected => "CONNECTED",
82            MessageConnectorState::Disconnected => "DISCONNECTED",
83        })
84    }
85}
86
87/// The statistics of a [`MessageConnector`] at one moment; see [`MessageConnector::get_statistics`].
88///
89/// The counters cover all the connections of the connector since it was created, the closed ones included. They are
90/// kept apart from the other values of the connector: `active_connection_count` may follow
91/// [`MessageConnector::get_connection_count`] a moment later.
92#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
93#[non_exhaustive]
94pub struct MessageConnectorStatistics {
95    /// The bytes read, heartbeats included: they grow on an idle connection too.
96    pub read_bytes: i64,
97    /// The bytes written, heartbeats included.
98    pub written_bytes: i64,
99    /// The data records read: they grow only when data arrives.
100    pub read_data_records: i64,
101    /// The data records written.
102    pub written_data_records: i64,
103    /// The open connections.
104    pub active_connection_count: i64,
105    /// The connections closed since the connector was created.
106    pub closed_connection_count: i64,
107}
108
109/// The category of a [`ConnectionError`].
110///
111/// It prints as the SDK constant without its prefix: `OTHER`, `DNS`, `CONNECT_FAILED`, `READ_TIMEOUT`,
112/// `HEARTBEAT_TIMEOUT`, `CLOSED_BY_REMOTE`, `TLS` or `IO`.
113#[cfg(feature = "experimental")]
114#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
115#[non_exhaustive]
116pub enum ConnectionErrorCategory {
117    /// None of the others, such as an error of the protocol or of the authentication, and a category that a later
118    /// SDK adds.
119    Other,
120    /// The host name of the address is not resolved (`java.net.UnknownHostException`).
121    Dns,
122    /// The connect failed, was refused or timed out (`java.net.ConnectException` and others).
123    ConnectFailed,
124    /// A read of an established connection timed out (`java.net.SocketTimeoutException`).
125    ReadTimeout,
126    /// The remote side sent no data and no heartbeat within the heartbeat timeout (the address option
127    /// `[heartbeatTimeout=...]`), so QD closed the connection; the error has no exception.
128    HeartbeatTimeout,
129    /// The remote side closed the connection (`java.io.EOFException`).
130    ClosedByRemote,
131    /// The TLS handshake or a TLS record failed, such as a `tls+` address of a port without TLS or a certificate that
132    /// is not trusted (`javax.net.ssl.SSLException`).
133    Tls,
134    /// Another I/O error, such as a connection reset (`java.io.IOException`).
135    Io,
136}
137
138#[cfg(feature = "experimental")]
139impl ConnectionErrorCategory {
140    fn from_sys(category: i32) -> Self {
141        match u32::try_from(category) {
142            Ok(sys::DXFG_V4_CONNECTION_ERROR_DNS) => ConnectionErrorCategory::Dns,
143            Ok(sys::DXFG_V4_CONNECTION_ERROR_CONNECT_FAILED) => ConnectionErrorCategory::ConnectFailed,
144            Ok(sys::DXFG_V4_CONNECTION_ERROR_READ_TIMEOUT) => ConnectionErrorCategory::ReadTimeout,
145            Ok(sys::DXFG_V4_CONNECTION_ERROR_HEARTBEAT_TIMEOUT) => ConnectionErrorCategory::HeartbeatTimeout,
146            Ok(sys::DXFG_V4_CONNECTION_ERROR_CLOSED_BY_REMOTE) => ConnectionErrorCategory::ClosedByRemote,
147            Ok(sys::DXFG_V4_CONNECTION_ERROR_TLS) => ConnectionErrorCategory::Tls,
148            Ok(sys::DXFG_V4_CONNECTION_ERROR_IO) => ConnectionErrorCategory::Io,
149            _ => ConnectionErrorCategory::Other,
150        }
151    }
152}
153
154#[cfg(feature = "experimental")]
155impl fmt::Display for ConnectionErrorCategory {
156    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
157        f.pad(match self {
158            ConnectionErrorCategory::Other => "OTHER",
159            ConnectionErrorCategory::Dns => "DNS",
160            ConnectionErrorCategory::ConnectFailed => "CONNECT_FAILED",
161            ConnectionErrorCategory::ReadTimeout => "READ_TIMEOUT",
162            ConnectionErrorCategory::HeartbeatTimeout => "HEARTBEAT_TIMEOUT",
163            ConnectionErrorCategory::ClosedByRemote => "CLOSED_BY_REMOTE",
164            ConnectionErrorCategory::Tls => "TLS",
165            ConnectionErrorCategory::Io => "IO",
166        })
167    }
168}
169
170/// A connection error of a [`MessageConnector`]: a failed connect or a dropped connection; see
171/// [`MessageConnector::get_last_error`] and [`DXEndpoint::get_last_connection_error`].
172///
173/// It is a copy, which does not change when the connector records a newer error. A successful connection clears
174/// nothing, so compare [`time`](Self::time) or [`count`](Self::count) with an error seen before to tell a new error
175/// from an old one.
176///
177/// The SDK captures the errors from the log records of QD's default logging, at any `log.level` and with or without a
178/// [logging listener](crate::logging). With another `log.className` nothing is captured, and a level set on QD's
179/// loggers `com.devexperts.qd.qtp.MessageConnector`, `com.devexperts.qd.qtp.MessageAdapterConnection` or
180/// `com.devexperts.connector.codec.ssl` themselves may stop the capture.
181///
182/// [`DXEndpoint::get_last_connection_error`]: crate::DXEndpoint::get_last_connection_error
183#[cfg(feature = "experimental")]
184#[derive(Debug, Clone, PartialEq, Eq, Hash)]
185#[non_exhaustive]
186pub struct ConnectionError {
187    /// The time of the error, in milliseconds since the epoch (UTC).
188    pub time: i64,
189    /// The address the connector was configured with, the user and the password masked: the whole list of a
190    /// multi-host address, not the host that failed.
191    pub address: String,
192    /// The category of the error.
193    pub category: ConnectionErrorCategory,
194    /// Whether an established connection was dropped, as opposed to a failed connect attempt.
195    pub dropped: bool,
196    /// The class name of the Java exception, such as `java.net.ConnectException`; `None` when there is none, as for
197    /// [`HeartbeatTimeout`](ConnectionErrorCategory::HeartbeatTimeout).
198    pub exception_class_name: Option<String>,
199    /// The message of the exception, or of QD's log record when there is no exception, the user and the password
200    /// masked, at most 256 characters; `None` when there is none.
201    pub message: Option<String>,
202    /// The number of errors of the connector up to this one.
203    pub count: i64,
204}
205
206#[cfg(feature = "experimental")]
207impl ConnectionError {
208    /// Calls an SDK function that writes a new error or NULL to its out-pointer, copies the error and releases it.
209    pub(crate) fn last(
210        f: impl FnOnce(isolate::Thread, *mut *mut sys::dxfg_v4_connection_error_t) -> i32,
211    ) -> Result<Option<Self>> {
212        let mut error = std::ptr::null_mut();
213        call(|t| f(t, &mut error))?;
214        if error.is_null() {
215            return Ok(None);
216        }
217        // SAFETY: the SDK wrote an error whose strings are NUL-terminated or NULL; it is released right after copying.
218        let copy = unsafe {
219            let e = &*error;
220            let optional = |s: *const std::ffi::c_char| (!s.is_null()).then(|| isolate::string(s).into_owned());
221            ConnectionError {
222                time: e.time,
223                address: isolate::string(e.address).into_owned(),
224                category: ConnectionErrorCategory::from_sys(e.category),
225                dropped: e.dropped != 0,
226                exception_class_name: optional(e.exception_class_name),
227                message: optional(e.message),
228                count: e.count,
229            }
230        };
231        // SAFETY: the error came from the SDK to the caller and is released once.
232        crate::error_manager::report_release(
233            "ConnectionError",
234            call(|t| unsafe { sys::dxfg_v4_ConnectionError_release(t, error) }),
235        );
236        Ok(Some(copy))
237    }
238}
239
240/// A message connector of an endpoint (`MessageConnector`): one per address of the address string that the endpoint
241/// is connected to, such as two for `(host1:7300)(host2:7300)`; see [`DXEndpoint::get_connectors`].
242///
243/// It is a live view: every getter reads the connector anew, and the values are not read together as one consistent
244/// set. Reading changes nothing; the statistics are not reset.
245///
246/// A connector holds its own handle of the SDK and nothing of its endpoint, so it never keeps the endpoint open. It
247/// answers after its endpoint is closed or dropped and after a connect of the endpoint to another address replaces
248/// it: such a connector is [`Disconnected`](MessageConnectorState::Disconnected) and not active, has no connections
249/// and no current addresses, and keeps its name, kind, address and statistics. Cloning it is cheap, and a clone reads
250/// the same connector.
251///
252/// ```no_run
253/// use dxfeed_graal::DXEndpoint;
254///
255/// # fn main() -> dxfeed_graal::Result<()> {
256/// let endpoint = DXEndpoint::create()?;
257/// endpoint.connect("demo.dxfeed.com:7300")?;
258/// for connector in endpoint.get_connectors()? {
259///     let statistics = connector.get_statistics()?;
260///     println!(
261///         "{} {} {}: {} bytes, {} records read",
262///         connector.get_name()?,
263///         connector.get_address()?,
264///         connector.get_state()?,
265///         statistics.read_bytes,
266///         statistics.read_data_records
267///     );
268/// }
269/// # Ok(())
270/// # }
271/// ```
272///
273/// [`DXEndpoint::get_connectors`]: crate::DXEndpoint::get_connectors
274#[derive(Clone)]
275pub struct MessageConnector {
276    handle: Arc<Handle<sys::dxfg_v4_message_connector_t>>,
277}
278
279impl fmt::Debug for MessageConnector {
280    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
281        // No SDK call: a getter can fail, and the values change.
282        f.debug_struct("MessageConnector").finish_non_exhaustive()
283    }
284}
285
286impl MessageConnector {
287    /// Copies the connectors of a list that the SDK returned and releases the list, also when a copy fails.
288    ///
289    /// # Safety
290    ///
291    /// `list` must be NULL or a list of live connector handles that the caller owns and releases nowhere else.
292    pub(crate) unsafe fn take_list(list: *mut sys::dxfg_v4_message_connector_list) -> Result<Vec<Self>> {
293        if list.is_null() {
294            return Err(Error::Java(JavaException::null_result()));
295        }
296        // SAFETY: the caller guarantees a live list; its elements stay live until it is released below.
297        let connectors = unsafe {
298            let list = &*list;
299            match usize::try_from(list.size) {
300                Ok(size) if size > 0 && !list.elements.is_null() => std::slice::from_raw_parts(list.elements, size)
301                    .iter()
302                    .map(|&element| Self::clone_raw(element))
303                    .collect(),
304                _ => Ok(Vec::new()),
305            }
306        };
307        // SAFETY: the list came from the SDK and is released once, after its elements are cloned.
308        crate::error_manager::report_release(
309            "MessageConnector",
310            call(|t| unsafe { sys::dxfg_v4_message_connector_list_release(t, list) }),
311        );
312        connectors
313    }
314
315    /// A connector with a new handle of the connector `raw`, which stays with its owner; NULL is an error.
316    ///
317    /// # Safety
318    ///
319    /// `raw` must be NULL or a live connector handle.
320    pub(crate) unsafe fn clone_raw(raw: *mut sys::dxfg_v4_message_connector_t) -> Result<Self> {
321        if raw.is_null() {
322            return Err(Error::Java(JavaException::null_result()));
323        }
324        // SAFETY: the caller guarantees a live handle.
325        let handle = unsafe { Handle::clone_raw(raw) }?;
326        Ok(MessageConnector {
327            handle: Arc::new(handle),
328        })
329    }
330
331    fn as_ptr(&self) -> *mut sys::dxfg_v4_message_connector_t {
332        self.handle.as_ptr()
333    }
334
335    /// The name of the connector, as in QD's log and JMX, such as `ClientSocket-Distributor`. The connectors of
336    /// different endpoints may have the same name.
337    #[doc(alias = "getName")]
338    pub fn get_name(&self) -> Result<String> {
339        let c = self.as_ptr();
340        // SAFETY: the connector is live and the out-pointer is valid for writes.
341        isolate::out_string("MessageConnector", |t, name| unsafe {
342            sys::dxfg_v4_MessageConnector_getName(t, c, name)
343        })
344    }
345
346    /// The kind of the connector.
347    pub fn get_kind(&self) -> Result<MessageConnectorKind> {
348        let c = self.as_ptr();
349        let mut kind = 0;
350        // SAFETY: the connector is live and the out-pointer is valid for writes.
351        call(|t| unsafe { sys::dxfg_v4_MessageConnector_getKind(t, c, &mut kind) })?;
352        Ok(MessageConnectorKind::from_sys(kind))
353    }
354
355    /// The address the connector was configured with, such as `127.0.0.1:7300`, or `*:7400` for a server socket
356    /// connector of the address `:7400`; the user and the password are masked as in QD's log.
357    #[doc(alias = "getAddress")]
358    pub fn get_address(&self) -> Result<String> {
359        let c = self.as_ptr();
360        // SAFETY: the connector is live and the out-pointer is valid for writes.
361        isolate::out_string("MessageConnector", |t, address| unsafe {
362            sys::dxfg_v4_MessageConnector_getAddress(t, c, address)
363        })
364    }
365
366    /// The `host:port` addresses a client socket connector is connected to now, one per connection (a striped
367    /// connector has several). It is empty when the connector is not connected, and always for the other kinds.
368    #[doc(alias = "getCurrentAddresses")]
369    pub fn get_current_addresses(&self) -> Result<Vec<String>> {
370        let c = self.as_ptr();
371        // SAFETY: the connector is live and the out-pointer is valid for writes.
372        isolate::out_string_list("MessageConnector", |t, addresses| unsafe {
373            sys::dxfg_v4_MessageConnector_getCurrentAddresses(t, c, addresses)
374        })
375    }
376
377    /// The state of the connector.
378    ///
379    /// Returns [`Error::InvalidArgument`] for a state that this crate does not know.
380    #[doc(alias = "getState")]
381    pub fn get_state(&self) -> Result<MessageConnectorState> {
382        let c = self.as_ptr();
383        let mut state = 0;
384        // SAFETY: the connector is live and the out-pointer is valid for writes.
385        call(|t| unsafe { sys::dxfg_v4_MessageConnector_getState(t, c, &mut state) })?;
386        MessageConnectorState::from_sys(state)
387    }
388
389    /// Whether the connector is started, so it connects or reconnects, as opposed to stopped.
390    #[doc(alias = "isActive")]
391    pub fn is_active(&self) -> Result<bool> {
392        let c = self.as_ptr();
393        let mut active = 0;
394        // SAFETY: the connector is live and the out-pointer is valid for writes.
395        call(|t| unsafe { sys::dxfg_v4_MessageConnector_isActive(t, c, &mut active) })?;
396        Ok(active != 0)
397    }
398
399    /// The number of the open connections: those of a client socket connector (more than one for a striped
400    /// connector) or those that a server socket connector accepted.
401    #[doc(alias = "getConnectionCount")]
402    pub fn get_connection_count(&self) -> Result<i32> {
403        let c = self.as_ptr();
404        let mut count = 0;
405        // SAFETY: the connector is live and the out-pointer is valid for writes.
406        call(|t| unsafe { sys::dxfg_v4_MessageConnector_getConnectionCount(t, c, &mut count) })?;
407        Ok(count)
408    }
409
410    /// The number of the connections closed since the connector was created: it grows on each drop and on each
411    /// reconnect.
412    #[doc(alias = "getClosedConnectionCount")]
413    pub fn get_closed_connection_count(&self) -> Result<i64> {
414        let c = self.as_ptr();
415        let mut count = 0;
416        // SAFETY: the connector is live and the out-pointer is valid for writes.
417        call(|t| unsafe { sys::dxfg_v4_MessageConnector_getClosedConnectionCount(t, c, &mut count) })?;
418        Ok(count)
419    }
420
421    /// The statistics of the connector now: the bytes and the data records read and written, the open and the closed
422    /// connections. Data arrives when `read_data_records` grows between two calls; `read_bytes` grows on heartbeats
423    /// too.
424    #[doc(alias = "retrieveCompleteEndpointStats")]
425    #[doc(alias = "getStats")]
426    pub fn get_statistics(&self) -> Result<MessageConnectorStatistics> {
427        let c = self.as_ptr();
428        let mut stats = sys::dxfg_v4_message_connector_stats_t {
429            read_bytes: 0,
430            written_bytes: 0,
431            read_data_records: 0,
432            written_data_records: 0,
433            active_connection_count: 0,
434            closed_connection_count: 0,
435        };
436        // SAFETY: the connector is live and the out-pointer is valid for writes.
437        call(|t| unsafe { sys::dxfg_v4_MessageConnector_getStatistics(t, c, &mut stats) })?;
438        Ok(MessageConnectorStatistics {
439            read_bytes: stats.read_bytes,
440            written_bytes: stats.written_bytes,
441            read_data_records: stats.read_data_records,
442            written_data_records: stats.written_data_records,
443            active_connection_count: stats.active_connection_count,
444            closed_connection_count: stats.closed_connection_count,
445        })
446    }
447
448    /// The last connection error of the connector: its newest failed connect or dropped connection, or `None` when it
449    /// has had no error, which does not mean that it is connected now; see [`ConnectionError`].
450    ///
451    /// The SDK watches the connectors of the endpoints of this crate from their creation. A connector keeps its error
452    /// after it is replaced and after its endpoint is closed or dropped. Inside a
453    /// [connector listener](crate::DXEndpoint::add_message_connector_listener) the error of the change that called it
454    /// is already recorded.
455    #[cfg(feature = "experimental")]
456    pub fn get_last_error(&self) -> Result<Option<ConnectionError>> {
457        let c = self.as_ptr();
458        // SAFETY: the connector is live and the out-pointer is valid for writes.
459        ConnectionError::last(|t, error| unsafe { sys::dxfg_v4_MessageConnector_getLastError(t, c, error) })
460    }
461}
462
463#[cfg(test)]
464mod tests {
465    use super::*;
466
467    #[test]
468    fn an_unknown_kind_is_other() {
469        assert_eq!(MessageConnectorKind::from_sys(0), MessageConnectorKind::ClientSocket);
470        assert_eq!(MessageConnectorKind::from_sys(1), MessageConnectorKind::ServerSocket);
471        assert_eq!(MessageConnectorKind::from_sys(2), MessageConnectorKind::Other);
472        assert_eq!(MessageConnectorKind::from_sys(3), MessageConnectorKind::Other);
473        assert_eq!(MessageConnectorKind::from_sys(-1), MessageConnectorKind::Other);
474    }
475
476    #[cfg(feature = "experimental")]
477    #[test]
478    fn an_unknown_category_is_other() {
479        let categories: Vec<_> = (-1..=8).map(ConnectionErrorCategory::from_sys).collect();
480        assert_eq!(
481            categories,
482            [
483                ConnectionErrorCategory::Other,
484                ConnectionErrorCategory::Other,
485                ConnectionErrorCategory::Dns,
486                ConnectionErrorCategory::ConnectFailed,
487                ConnectionErrorCategory::ReadTimeout,
488                ConnectionErrorCategory::HeartbeatTimeout,
489                ConnectionErrorCategory::ClosedByRemote,
490                ConnectionErrorCategory::Tls,
491                ConnectionErrorCategory::Io,
492                ConnectionErrorCategory::Other,
493            ]
494        );
495    }
496
497    #[test]
498    fn an_unknown_state_is_invalid() {
499        assert_eq!(
500            MessageConnectorState::from_sys(0).unwrap(),
501            MessageConnectorState::Connecting
502        );
503        assert_eq!(
504            MessageConnectorState::from_sys(1).unwrap(),
505            MessageConnectorState::Connected
506        );
507        assert_eq!(
508            MessageConnectorState::from_sys(2).unwrap(),
509            MessageConnectorState::Disconnected
510        );
511        assert!(matches!(
512            MessageConnectorState::from_sys(3),
513            Err(Error::InvalidArgument(_))
514        ));
515        assert!(matches!(
516            MessageConnectorState::from_sys(-1),
517            Err(Error::InvalidArgument(_))
518        ));
519    }
520}