deribit_websocket/message/
builder.rs

1//! Message builder utilities for WebSocket client
2
3use crate::message::{NotificationHandler, RequestBuilder, ResponseHandler};
4use crate::model::ws_types::{JsonRpcNotification, JsonRpcRequest, JsonRpcResponse};
5
6/// Main message builder for WebSocket operations
7#[derive(Debug)]
8pub struct MessageBuilder {
9    request_builder: RequestBuilder,
10    response_handler: ResponseHandler,
11    notification_handler: NotificationHandler,
12}
13
14impl Default for MessageBuilder {
15    fn default() -> Self {
16        Self::new()
17    }
18}
19
20impl MessageBuilder {
21    /// Create a new message builder
22    pub fn new() -> Self {
23        Self {
24            request_builder: RequestBuilder::new(),
25            response_handler: ResponseHandler::new(),
26            notification_handler: NotificationHandler::new(),
27        }
28    }
29
30    /// Get mutable reference to request builder
31    pub fn request_builder(&mut self) -> &mut RequestBuilder {
32        &mut self.request_builder
33    }
34
35    /// Get reference to response handler
36    pub fn response_handler(&self) -> &ResponseHandler {
37        &self.response_handler
38    }
39
40    /// Get reference to notification handler
41    pub fn notification_handler(&self) -> &NotificationHandler {
42        &self.notification_handler
43    }
44
45    /// Parse incoming message and determine type
46    pub fn parse_message(&self, data: &str) -> Result<MessageType, serde_json::Error> {
47        // Try to parse as response first (has 'id' field)
48        if let Ok(response) = self.response_handler.parse_response(data) {
49            return Ok(MessageType::Response(response));
50        }
51
52        // Try to parse as notification (no 'id' field)
53        if let Ok(notification) = self.notification_handler.parse_notification(data) {
54            return Ok(MessageType::Notification(notification));
55        }
56
57        // If neither works, return error
58        Err(serde_json::Error::io(std::io::Error::new(
59            std::io::ErrorKind::InvalidData,
60            "Unable to parse message",
61        )))
62    }
63}
64
65/// Message type enumeration
66#[derive(Debug, Clone)]
67pub enum MessageType {
68    /// JSON-RPC request message
69    Request(JsonRpcRequest),
70    /// JSON-RPC response message
71    Response(JsonRpcResponse),
72    /// JSON-RPC notification message
73    Notification(JsonRpcNotification),
74}