Skip to main content

bunqueue_client/
connection.rs

1use std::fmt;
2use std::path::PathBuf;
3use std::sync::{Arc, Mutex};
4use std::time::Duration;
5
6use rmpv::Value;
7
8use crate::telemetry::{TelemetryCallback, TelemetryEvent, emit_all};
9use crate::transport::Socket;
10use crate::wire::{command, get, map};
11use crate::{PROTOCOL_VERSION, Result};
12
13#[derive(Clone, Debug, Default)]
14pub struct TlsOptions {
15    /// PEM bundle added to the system trust store.
16    pub ca_file: Option<PathBuf>,
17}
18
19#[derive(Clone)]
20pub struct ConnectionOptions {
21    pub host: String,
22    pub port: u16,
23    pub token: Option<String>,
24    pub tls: Option<TlsOptions>,
25    pub connect_timeout: Duration,
26    pub command_timeout: Duration,
27    pub telemetry: Option<TelemetryCallback>,
28}
29
30impl Default for ConnectionOptions {
31    fn default() -> Self {
32        Self {
33            host: "localhost".into(),
34            port: 6789,
35            token: None,
36            tls: None,
37            connect_timeout: Duration::from_secs(10),
38            command_timeout: Duration::from_secs(30),
39            telemetry: None,
40        }
41    }
42}
43
44impl fmt::Debug for ConnectionOptions {
45    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
46        formatter
47            .debug_struct("ConnectionOptions")
48            .field("host", &self.host)
49            .field("port", &self.port)
50            .field("token", &self.token.as_ref().map(|_| "<redacted>"))
51            .field("tls", &self.tls)
52            .field("connect_timeout", &self.connect_timeout)
53            .field("command_timeout", &self.command_timeout)
54            .field("telemetry", &self.telemetry.as_ref().map(|_| "<callback>"))
55            .finish()
56    }
57}
58
59pub(crate) struct Inner {
60    pub(crate) socket: Option<Socket>,
61    pub(crate) generation: i64,
62    pub(crate) request_counter: u32,
63    pub(crate) closed: bool,
64}
65
66/// A cloneable, mutex-serialized TCP connection with lazy reconnect.
67#[derive(Clone)]
68pub struct Connection {
69    pub(crate) options: ConnectionOptions,
70    pub(crate) inner: Arc<Mutex<Inner>>,
71}
72
73impl Connection {
74    pub fn new(options: ConnectionOptions) -> Self {
75        Self {
76            options,
77            inner: Arc::new(Mutex::new(Inner {
78                socket: None,
79                generation: -1,
80                request_counter: 0,
81                closed: false,
82            })),
83        }
84    }
85
86    pub fn options(&self) -> &ConnectionOptions {
87        &self.options
88    }
89
90    pub fn generation(&self) -> i64 {
91        self.inner
92            .lock()
93            .expect("connection mutex poisoned")
94            .generation
95    }
96
97    pub fn is_connected(&self) -> bool {
98        self.inner
99            .lock()
100            .expect("connection mutex poisoned")
101            .socket
102            .is_some()
103    }
104
105    pub fn ensure_connected(&self) -> Result<()> {
106        let mut events = Vec::new();
107        let result = {
108            let mut inner = self.inner.lock().expect("connection mutex poisoned");
109            self.connect_locked(&mut inner, &mut events)
110        };
111        emit_all(self.options.telemetry.as_ref(), events);
112        result
113    }
114
115    /// Sends one protocol command. Calls are safe from multiple threads.
116    pub fn call(&self, command: crate::Message) -> Result<crate::Message> {
117        self.call_timeout(command, self.options.command_timeout)
118    }
119
120    pub fn call_timeout(
121        &self,
122        command_map: crate::Message,
123        timeout: Duration,
124    ) -> Result<crate::Message> {
125        let mut events = Vec::new();
126        let result = {
127            let mut inner = self.inner.lock().expect("connection mutex poisoned");
128            self.call_locked(&mut inner, command_map, timeout, &mut events)
129        };
130        emit_all(self.options.telemetry.as_ref(), events);
131        result
132    }
133
134    pub fn hello(&self) -> Result<crate::Message> {
135        self.call(command(
136            "Hello",
137            map([
138                ("protocolVersion", Value::from(PROTOCOL_VERSION)),
139                ("capabilities", Value::Array(Vec::new())),
140            ]),
141        ))
142    }
143
144    pub fn protocol_version(&self) -> Result<i64> {
145        let response = self.hello()?;
146        Ok(get(&response, "protocolVersion")
147            .and_then(Value::as_i64)
148            .unwrap_or(0))
149    }
150
151    pub fn ping(&self) -> Result<bool> {
152        let response = self.call(command("Ping", Vec::new()))?;
153        Ok(get(&response, "data")
154            .and_then(Value::as_map)
155            .and_then(|data| {
156                data.iter()
157                    .find(|(key, _)| key.as_str() == Some("pong"))
158                    .and_then(|(_, value)| value.as_bool())
159            })
160            == Some(true))
161    }
162
163    /// Permanently closes this connection and rejects later calls.
164    pub fn close(&self) {
165        {
166            let mut inner = self.inner.lock().expect("connection mutex poisoned");
167            inner.closed = true;
168            self.teardown_locked(&mut inner);
169        }
170        emit_all(self.options.telemetry.as_ref(), [TelemetryEvent::Closed]);
171    }
172}