1use 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
20pub const DEFAULT_HOST: &str = "127.0.0.1";
22
23pub const DEFAULT_PORT: u16 = 1337;
25
26pub const DEFAULT_MAX_PAYLOAD: usize = 128 * 1024 * 1024;
28
29#[derive(Debug, Clone)]
31pub struct ConnectionConfig {
32 pub host: String,
34 pub port: u16,
36 pub tls: bool,
38 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 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 pub fn with_tls(mut self) -> Self {
65 self.tls = true;
66 self
67 }
68
69 pub fn with_max_payload(mut self, max_payload: usize) -> Self {
71 self.max_payload = max_payload;
72 self
73 }
74}
75
76#[derive(Debug, Clone)]
78pub struct ConnectionAddress {
79 pub http: String,
81 pub websocket: String,
83}
84
85#[derive(Debug, Clone)]
87pub struct Connection {
88 pub max_payload: usize,
90 pub address: ConnectionAddress,
92}
93
94impl Connection {
95 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
110pub fn create_connection_object(config: Option<ConnectionConfig>) -> Connection {
112 Connection::from_config(&config.unwrap_or_default())
113}
114
115#[derive(Debug, Clone, Copy, PartialEq, Eq)]
117pub enum InteractionType {
118 LongRunning,
120 OneTime,
122}
123
124#[derive(Debug)]
126enum WsMessage {
127 Request {
129 payload: String,
130 response_tx: oneshot::Sender<Result<String>>,
131 },
132 Send { payload: String },
134 Close,
136}
137
138struct WebSocketState {
140 tx: mpsc::Sender<WsMessage>,
142 is_open: std::sync::atomic::AtomicBool,
144}
145
146pub struct InteractionContext {
150 pub connection: Connection,
152 pub interaction_type: InteractionType,
154 request_id: AtomicU64,
156 ws_state: Arc<WebSocketState>,
158 _task_handle: tokio::task::JoinHandle<()>,
160}
161
162impl InteractionContext {
163 pub fn is_socket_open(&self) -> bool {
165 self.ws_state.is_open.load(Ordering::SeqCst)
166 }
167
168 fn next_request_id(&self) -> u64 {
170 self.request_id.fetch_add(1, Ordering::SeqCst)
171 }
172
173 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 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 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
234pub 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
244pub type ErrorHandler = Box<dyn Fn(OgmiosError) + Send + Sync>;
246
247pub type CloseHandler = Box<dyn Fn() + Send + Sync>;
249
250pub struct InteractionContextOptions {
252 pub connection: ConnectionConfig,
254 pub interaction_type: InteractionType,
256 pub error_handler: Option<ErrorHandler>,
258 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
273pub 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 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 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
330async 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 let pending: Arc<Mutex<Vec<oneshot::Sender<Result<String>>>>> =
342 Arc::new(Mutex::new(Vec::new()));
343 let pending_clone = pending.clone();
344
345 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 }
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 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
419pub 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}