Skip to main content

ogmios_client/
connection.rs

1//! Connection management for Ogmios.
2//!
3//! This module provides types and functions for establishing and managing
4//! WebSocket connections to an Ogmios server.
5
6use crate::error::{OgmiosError, Result};
7use crate::schema::{JsonRpcRequest, JsonRpcResponse};
8use futures_util::{SinkExt, StreamExt};
9use serde::{de::DeserializeOwned, Serialize};
10use std::sync::atomic::{AtomicU64, Ordering};
11use std::sync::Arc;
12use tokio::sync::{mpsc, oneshot, Mutex};
13use tokio_tungstenite::{
14    connect_async,
15    tungstenite::{handshake::client::Request, protocol::Message},
16    MaybeTlsStream, WebSocketStream,
17};
18use tracing::{debug, error, trace};
19
20/// Default Ogmios host.
21pub const DEFAULT_HOST: &str = "127.0.0.1";
22
23/// Default Ogmios port.
24pub const DEFAULT_PORT: u16 = 1337;
25
26/// Default maximum payload size (128 MB).
27pub const DEFAULT_MAX_PAYLOAD: usize = 128 * 1024 * 1024;
28
29/// Connection configuration.
30#[derive(Debug, Clone)]
31pub struct ConnectionConfig {
32    /// Ogmios server host.
33    pub host: String,
34    /// Ogmios server port.
35    pub port: u16,
36    /// Use TLS (wss://).
37    pub tls: bool,
38    /// Maximum payload size in bytes.
39    pub max_payload: usize,
40}
41
42impl Default for ConnectionConfig {
43    fn default() -> Self {
44        Self {
45            host: DEFAULT_HOST.to_string(),
46            port: DEFAULT_PORT,
47            tls: false,
48            max_payload: DEFAULT_MAX_PAYLOAD,
49        }
50    }
51}
52
53impl ConnectionConfig {
54    /// Create a new connection configuration.
55    pub fn new(host: impl Into<String>, port: u16) -> Self {
56        Self {
57            host: host.into(),
58            port,
59            ..Default::default()
60        }
61    }
62
63    /// Enable TLS.
64    pub fn with_tls(mut self) -> Self {
65        self.tls = true;
66        self
67    }
68
69    /// Set maximum payload size.
70    pub fn with_max_payload(mut self, max_payload: usize) -> Self {
71        self.max_payload = max_payload;
72        self
73    }
74}
75
76/// Connection addresses.
77#[derive(Debug, Clone)]
78pub struct ConnectionAddress {
79    /// HTTP address for health checks.
80    pub http: String,
81    /// WebSocket address for protocol communication.
82    pub websocket: String,
83}
84
85/// A connection object representing an Ogmios server connection.
86#[derive(Debug, Clone)]
87pub struct Connection {
88    /// Maximum payload size.
89    pub max_payload: usize,
90    /// Connection addresses.
91    pub address: ConnectionAddress,
92}
93
94impl Connection {
95    /// Create a connection object from configuration.
96    pub fn from_config(config: &ConnectionConfig) -> Self {
97        let scheme = if config.tls { "https" } else { "http" };
98        let ws_scheme = if config.tls { "wss" } else { "ws" };
99
100        Self {
101            max_payload: config.max_payload,
102            address: ConnectionAddress {
103                http: format!("{}://{}:{}", scheme, config.host, config.port),
104                websocket: format!("{}://{}:{}", ws_scheme, config.host, config.port),
105            },
106        }
107    }
108}
109
110/// Create a connection object from optional configuration.
111pub fn create_connection_object(config: Option<ConnectionConfig>) -> Connection {
112    Connection::from_config(&config.unwrap_or_default())
113}
114
115/// Interaction type for client connections.
116#[derive(Debug, Clone, Copy, PartialEq, Eq)]
117pub enum InteractionType {
118    /// Long-running connection (persists across multiple requests).
119    LongRunning,
120    /// One-time connection (closes after request).
121    OneTime,
122}
123
124/// Internal message for WebSocket communication.
125#[derive(Debug)]
126enum WsMessage {
127    /// Send a request and wait for a response.
128    Request {
129        payload: String,
130        response_tx: oneshot::Sender<Result<String>>,
131    },
132    /// Send a message without waiting for response.
133    Send { payload: String },
134    /// Close the connection.
135    Close,
136}
137
138/// Shared WebSocket state.
139struct WebSocketState {
140    /// Sender for WebSocket messages.
141    tx: mpsc::Sender<WsMessage>,
142    /// Connection status.
143    is_open: std::sync::atomic::AtomicBool,
144}
145
146/// Interaction context for Ogmios clients.
147///
148/// This is the main context object that clients use to communicate with Ogmios.
149pub struct InteractionContext {
150    /// Connection configuration.
151    pub connection: Connection,
152    /// Interaction type.
153    pub interaction_type: InteractionType,
154    /// Request ID counter.
155    request_id: AtomicU64,
156    /// WebSocket state.
157    ws_state: Arc<WebSocketState>,
158    /// Background task handle.
159    _task_handle: tokio::task::JoinHandle<()>,
160}
161
162impl InteractionContext {
163    /// Check if the socket is open.
164    pub fn is_socket_open(&self) -> bool {
165        self.ws_state.is_open.load(Ordering::SeqCst)
166    }
167
168    /// Get the next request ID.
169    fn next_request_id(&self) -> u64 {
170        self.request_id.fetch_add(1, Ordering::SeqCst)
171    }
172
173    /// Send a JSON-RPC request and wait for the response.
174    pub async fn request<P, R>(&self, method: &str, params: Option<P>) -> Result<R>
175    where
176        P: Serialize,
177        R: DeserializeOwned,
178    {
179        ensure_socket_is_open(self)?;
180
181        let id = self.next_request_id();
182        let request = JsonRpcRequest::with_id(method, params, serde_json::Value::Number(id.into()));
183
184        let payload = serde_json::to_string(&request)?;
185        trace!("Sending request: {}", payload);
186
187        let (response_tx, response_rx) = oneshot::channel();
188        self.ws_state
189            .tx
190            .send(WsMessage::Request {
191                payload,
192                response_tx,
193            })
194            .await
195            .map_err(|e| OgmiosError::ChannelSend(e.to_string()))?;
196
197        let response_str = response_rx.await.map_err(|_| OgmiosError::ChannelRecv)??;
198        trace!("Received response: {}", response_str);
199
200        let response: JsonRpcResponse<R> = serde_json::from_str(&response_str)?;
201
202        response
203            .into_result()
204            .map_err(|e| OgmiosError::InvalidResponse {
205                message: e.to_string(),
206            })
207    }
208
209    /// Send a JSON-RPC notification (no response expected).
210    pub async fn notify<P: Serialize>(&self, method: &str, params: Option<P>) -> Result<()> {
211        ensure_socket_is_open(self)?;
212
213        let request = JsonRpcRequest::new(method, params);
214        let payload = serde_json::to_string(&request)?;
215        trace!("Sending notification: {}", payload);
216
217        self.ws_state
218            .tx
219            .send(WsMessage::Send { payload })
220            .await
221            .map_err(|e| OgmiosError::ChannelSend(e.to_string()))?;
222
223        Ok(())
224    }
225
226    /// Close the connection.
227    pub async fn shutdown(&self) -> Result<()> {
228        let _ = self.ws_state.tx.send(WsMessage::Close).await;
229        self.ws_state.is_open.store(false, Ordering::SeqCst);
230        Ok(())
231    }
232}
233
234/// Ensure the WebSocket is open.
235pub fn ensure_socket_is_open(context: &InteractionContext) -> Result<()> {
236    if !context.is_socket_open() {
237        return Err(OgmiosError::SocketNotOpen {
238            state: "closed".to_string(),
239        });
240    }
241    Ok(())
242}
243
244/// Error handler callback type.
245pub type ErrorHandler = Box<dyn Fn(OgmiosError) + Send + Sync>;
246
247/// Close handler callback type.
248pub type CloseHandler = Box<dyn Fn() + Send + Sync>;
249
250/// Options for creating an interaction context.
251pub struct InteractionContextOptions {
252    /// Connection configuration.
253    pub connection: ConnectionConfig,
254    /// Interaction type.
255    pub interaction_type: InteractionType,
256    /// Error handler.
257    pub error_handler: Option<ErrorHandler>,
258    /// Close handler.
259    pub close_handler: Option<CloseHandler>,
260}
261
262impl Default for InteractionContextOptions {
263    fn default() -> Self {
264        Self {
265            connection: ConnectionConfig::default(),
266            interaction_type: InteractionType::LongRunning,
267            error_handler: None,
268            close_handler: None,
269        }
270    }
271}
272
273/// Create an interaction context.
274///
275/// This establishes a WebSocket connection to the Ogmios server and returns
276/// a context that can be used to make requests.
277pub async fn create_interaction_context(
278    options: InteractionContextOptions,
279) -> Result<InteractionContext> {
280    let connection = Connection::from_config(&options.connection);
281    let ws_url = &connection.address.websocket;
282
283    debug!("Connecting to Ogmios at {}", ws_url);
284
285    // Build WebSocket request
286    let request = Request::builder()
287        .uri(ws_url)
288        .header(
289            "Host",
290            format!("{}:{}", options.connection.host, options.connection.port),
291        )
292        .header("Connection", "Upgrade")
293        .header("Upgrade", "websocket")
294        .header("Sec-WebSocket-Version", "13")
295        .header(
296            "Sec-WebSocket-Key",
297            tokio_tungstenite::tungstenite::handshake::client::generate_key(),
298        )
299        .body(())
300        .map_err(|e| OgmiosError::HttpHandshake(e.to_string()))?;
301
302    let (ws_stream, _) = connect_async(request)
303        .await
304        .map_err(|e| OgmiosError::WebSocket(e.to_string()))?;
305    debug!("WebSocket connection established");
306
307    let (tx, rx) = mpsc::channel::<WsMessage>(100);
308    let is_open = std::sync::atomic::AtomicBool::new(true);
309
310    let ws_state = Arc::new(WebSocketState { tx, is_open });
311
312    let ws_state_clone = ws_state.clone();
313    let error_handler = options.error_handler;
314    let close_handler = options.close_handler;
315
316    // Spawn background task to handle WebSocket messages
317    let task_handle = tokio::spawn(async move {
318        handle_websocket(ws_stream, rx, ws_state_clone, error_handler, close_handler).await;
319    });
320
321    Ok(InteractionContext {
322        connection,
323        interaction_type: options.interaction_type,
324        request_id: AtomicU64::new(1),
325        ws_state,
326        _task_handle: task_handle,
327    })
328}
329
330/// Handle WebSocket message loop.
331async fn handle_websocket(
332    ws_stream: WebSocketStream<MaybeTlsStream<tokio::net::TcpStream>>,
333    mut rx: mpsc::Receiver<WsMessage>,
334    ws_state: Arc<WebSocketState>,
335    error_handler: Option<ErrorHandler>,
336    close_handler: Option<CloseHandler>,
337) {
338    let (mut write, mut read) = ws_stream.split();
339
340    // Pending requests waiting for responses
341    let pending: Arc<Mutex<Vec<oneshot::Sender<Result<String>>>>> =
342        Arc::new(Mutex::new(Vec::new()));
343    let pending_clone = pending.clone();
344
345    // Spawn read task
346    let read_task = tokio::spawn(async move {
347        while let Some(msg_result) = read.next().await {
348            match msg_result {
349                Ok(Message::Text(text)) => {
350                    let mut pending = pending_clone.lock().await;
351                    if let Some(tx) = pending.pop() {
352                        let _ = tx.send(Ok(text));
353                    }
354                }
355                Ok(Message::Close(_)) => {
356                    debug!("WebSocket closed by server");
357                    break;
358                }
359                Ok(Message::Ping(data)) => {
360                    trace!("Received ping: {:?}", data);
361                    // Pong is handled automatically by tungstenite
362                }
363                Ok(_) => {}
364                Err(e) => {
365                    error!("WebSocket read error: {}", e);
366                    let err_msg = e.to_string();
367                    let mut pending = pending_clone.lock().await;
368                    while let Some(tx) = pending.pop() {
369                        let _ = tx.send(Err(OgmiosError::WebSocket(err_msg.clone())));
370                    }
371                    break;
372                }
373            }
374        }
375    });
376
377    // Handle outgoing messages
378    while let Some(msg) = rx.recv().await {
379        match msg {
380            WsMessage::Request {
381                payload,
382                response_tx,
383            } => {
384                {
385                    let mut pending = pending.lock().await;
386                    pending.push(response_tx);
387                }
388                if let Err(e) = write.send(Message::Text(payload)).await {
389                    error!("Failed to send WebSocket message: {}", e);
390                    let mut pending = pending.lock().await;
391                    if let Some(tx) = pending.pop() {
392                        let _ = tx.send(Err(OgmiosError::WebSocket(e.to_string())));
393                    }
394                }
395            }
396            WsMessage::Send { payload } => {
397                if let Err(e) = write.send(Message::Text(payload)).await {
398                    error!("Failed to send WebSocket message: {}", e);
399                    if let Some(ref handler) = error_handler {
400                        handler(OgmiosError::WebSocket(e.to_string()));
401                    }
402                }
403            }
404            WsMessage::Close => {
405                let _ = write.send(Message::Close(None)).await;
406                break;
407            }
408        }
409    }
410
411    ws_state.is_open.store(false, Ordering::SeqCst);
412    read_task.abort();
413
414    if let Some(handler) = close_handler {
415        handler();
416    }
417}
418
419/// Send a request and get a response using an interaction context.
420///
421/// This is a helper function that wraps the request/response cycle.
422pub async fn send<P, R>(context: &InteractionContext, method: &str, params: Option<P>) -> Result<R>
423where
424    P: Serialize,
425    R: DeserializeOwned,
426{
427    context.request(method, params).await
428}
429
430#[cfg(test)]
431mod tests {
432    use super::*;
433
434    #[test]
435    fn test_connection_config_default() {
436        let config = ConnectionConfig::default();
437        assert_eq!(config.host, DEFAULT_HOST);
438        assert_eq!(config.port, DEFAULT_PORT);
439        assert!(!config.tls);
440        assert_eq!(config.max_payload, DEFAULT_MAX_PAYLOAD);
441    }
442
443    #[test]
444    fn test_connection_from_config() {
445        let config = ConnectionConfig::new("localhost", 1338).with_tls();
446        let connection = Connection::from_config(&config);
447
448        assert_eq!(connection.address.http, "https://localhost:1338");
449        assert_eq!(connection.address.websocket, "wss://localhost:1338");
450    }
451
452    #[test]
453    fn test_create_connection_object() {
454        let connection = create_connection_object(None);
455        assert_eq!(connection.address.http, "http://127.0.0.1:1337");
456        assert_eq!(connection.address.websocket, "ws://127.0.0.1:1337");
457    }
458}