degen_websockets/
websocket_messages.rs

1
2
3use serde::{Serialize,Deserialize}; 
4use serde::de::DeserializeOwned;
5use tokio_tungstenite::tungstenite::Message;
6
7use uuid;
8
9use thiserror::Error;
10
11 
12
13//move this to shared?
14
15/*
16pub trait MessageUuid { 
17   fn get_message_uuid(&self) -> String;
18}
19*/
20
21#[derive(Serialize, Deserialize,Debug ,Clone)] 
22pub enum SecureMessageCredentials{
23  //  Client {client_uuid: String}, //client uuid 
24    Player {player_uuid: String}
25} 
26
27
28pub trait MessageReliability{ 
29   fn get_reliability_type(&self, msg_uuid:String) -> MessageReliabilityType;
30}
31
32
33#[derive(Serialize, Deserialize,Debug ,Clone)] 
34pub enum MessageReliabilityType {
35    Reliable(String), //msg uuid for ack 
36    Unreliable
37}
38
39
40
41#[derive(Serialize, Deserialize,Debug ,Clone)] 
42pub enum SocketMessageDestination {
43    All,
44    Client(String), //client uuid 
45    Room(String), 
46    ResponseToMsg(String), //message uuid
47    AckToReliableMsg(String), //message uuid 
48    Server //EcosystemServer) //server type 
49}
50
51
52#[derive(Debug, Error)]
53pub enum SocketMessageError {
54    #[error("Serialization Error: {0}")]
55    SerializationError(serde_json::Error),
56    #[error("Unknown Message Type Error")]
57    ParseFromUnknownMessageError,
58    // Add more errors as needed
59}
60
61
62
63#[derive(Serialize, Deserialize,Debug ,Clone)] 
64pub struct SocketMessage {
65    pub message_uuid: String, //used so we can respond to it 
66    pub reliability_type: MessageReliabilityType,
67    pub destination: SocketMessageDestination, 
68    pub inner_contents: Option<serde_json::Value>,   //this is what is passed to the core bsns logic 
69    pub secure_credentials: Option<SecureMessageCredentials>,   //can be added by relay server to attest about a connection 
70}
71
72impl SocketMessage {
73    
74    pub fn create<T: Serialize + MessageReliability>( 
75        destination:SocketMessageDestination,
76        contents: T  
77        ) ->  Result<Self, serde_json::Error> {
78
79        let message_uuid = uuid::Uuid::new_v4().to_string();
80
81        let wrapped_message = Self{
82            message_uuid:message_uuid.clone(),
83            destination, 
84            reliability_type: contents.get_reliability_type(message_uuid.clone()),
85            inner_contents: Some(serde_json::to_value(contents)? ),
86            secure_credentials: None 
87        };
88
89        Ok(wrapped_message)
90    }
91    
92    
93    pub fn clone_with_credentials(&self, credentials: Option<SecureMessageCredentials> ) -> Self {
94        
95        let mut clone = self.clone();
96         
97        clone.secure_credentials =  credentials ;
98         
99        clone  
100         
101          
102    }
103    
104    pub fn create_reliability_ack(ack_msg_uuid:String) 
105    -> Self {
106        
107        Self{
108            message_uuid: uuid::Uuid::new_v4().to_string(),
109            reliability_type: MessageReliabilityType::Unreliable,
110            inner_contents: None   ,
111            destination: SocketMessageDestination::AckToReliableMsg( ack_msg_uuid ) ,
112            secure_credentials: None      
113        }
114        
115    }
116        
117   pub fn from_stringified  (
118       message: serde_json::Value
119    ) -> Result<Self, SocketMessageError> {
120
121        let wrapped_message: Self = serde_json::from_value(message).map_err(SocketMessageError::SerializationError)?;
122
123        Ok(wrapped_message)
124    }
125    
126    
127    pub fn from_message(msg: Message) -> Result<Self, SocketMessageError> {
128        match msg {
129            Message::Text(inner) => {
130                let value = serde_json::from_str(&inner).map_err(SocketMessageError::SerializationError)?;
131                Self::from_stringified(value)
132            },
133            Message::Binary(inner) => {
134                let string = String::from_utf8(inner).map_err(|_| SocketMessageError::ParseFromUnknownMessageError)?;
135                let value = serde_json::from_str(&string).map_err(SocketMessageError::SerializationError)?;
136                Self::from_stringified(value)
137            },
138            _ => Err(SocketMessageError::ParseFromUnknownMessageError),
139        }
140    }
141    
142    pub fn to_message(&self) -> Result<Message, SocketMessageError > {
143        
144        let inner = serde_json::to_string( self ).map_err(SocketMessageError::SerializationError)?;
145        
146        Ok(Message::Text(inner.to_string()))        
147    }
148    
149    pub fn is_reliable(&self) -> bool {
150        
151        match self.reliability_type {
152            MessageReliabilityType::Reliable( .. ) => true,
153            MessageReliabilityType::Unreliable => false
154        }
155    }
156 
157    
158    
159    
160}
161
162 /*
163impl MessageReliability for SocketMessage {
164    fn is_reliable(&self, msg_uuid : String ) -> MessageReliabilityType {  
165        self.reliability_type.clone()
166    }  
167}*/
168
169impl std::fmt::Display for SocketMessage {
170    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
171        match self.inner_contents.clone() {
172            Some(inner) =>   write!(
173            f,
174            "SocketMessage {{ message_uuid: {}, reliability_type: {:?}, destination: {:?}, inner_contents: {} }}",
175            self.message_uuid, 
176            self.reliability_type,
177            self.destination,
178            inner
179        ),
180            None =>  write!(
181            f,
182            "SocketMessage {{ message_uuid: {}, reliability_type: {:?}, destination: {:?} }}",
183            self.message_uuid, 
184            self.reliability_type,
185            self.destination 
186        )
187        }
188       
189        
190    }
191}
192
193 
194 
195
196#[derive(Serialize, Deserialize,Debug ,Clone)] 
197pub enum OutboundMessageDestination {
198    All,
199    SocketConn(String), //socket connection uuid 
200    Room(String), 
201}
202
203
204
205
206
207#[derive(Serialize,Deserialize,Clone)]
208pub struct OutboundMessage {
209
210    //pub client_socket_uuid: Option<String>, //could be a room? 
211    //pub room: Option<String>,
212    pub destination: OutboundMessageDestination,
213    pub message: SocketMessage   //could make a custom type similar to tokio tungstenite message 
214
215}
216  
217impl OutboundMessage {
218    pub fn new_to_socket_conn_uuid(
219        message:SocketMessage,
220        socket_conn_uuid: String
221    ) -> Self {
222        Self {
223            destination: OutboundMessageDestination::SocketConn( socket_conn_uuid  ),
224            message
225        }
226    }
227}
228  
229  
230  
231
232#[derive(Serialize,Deserialize,Clone)]
233pub struct InboundMessage {
234
235    pub socket_connection_uuid: String,
236    //message_uuid: String, ? no. 
237    pub message: SocketMessage   //could make a custom type similar to tokio tungstenite message 
238
239}
240 
241 impl std::fmt::Display for InboundMessage {
242     
243     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
244        write!(
245            f,
246            "InboundMessage: {{ socket_connection_uuid: {}, message: {} }}",
247            self.socket_connection_uuid,
248            self.message
249        )
250    }
251 }
252
253
254impl InboundMessage {
255
256    pub fn from_message(socket_connection_uuid:String, msg:Message) -> Result<Self,SocketMessageError> {
257
258
259        let message = SocketMessage::from_message(msg)?;  //text( msg.clone().into_text().unwrap() ) ;
260
261       Ok( Self{
262            socket_connection_uuid,
263            message 
264        } )
265    }
266
267} 
268
269