cripsy_binary_api/transport/
websocket.rs1use std::time::Duration;
8
9use futures_util::{SinkExt, StreamExt};
10use serde_json::{json, Value};
11use tokio_tungstenite::tungstenite::client::IntoClientRequest;
12use tokio_tungstenite::tungstenite::http::HeaderValue;
13use tokio_tungstenite::tungstenite::Message;
14
15use crate::broker::config::TransportConfig;
16
17use super::error::TransportError;
18use super::retry::with_retry;
19
20pub type WsStream =
22 tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>;
23
24#[derive(Debug, Clone, PartialEq)]
26pub struct WsFrame {
27 pub name: String,
28 pub msg: Value,
29 pub request_id: Option<String>,
30}
31
32pub struct WsClient {
34 inner: WsStream,
35 url: String,
36}
37
38impl WsClient {
39 pub async fn connect(
41 url: &str,
42 headers: &[(&str, &str)],
43 cfg: &TransportConfig,
44 ) -> Result<Self, TransportError> {
45 let mut request = url
46 .into_client_request()
47 .map_err(|e| TransportError::Url(e.to_string()))?;
48 if let Some(ua) = &cfg.user_agent {
49 request.headers_mut().insert(
50 "User-Agent",
51 HeaderValue::from_str(ua).map_err(|e| TransportError::Url(e.to_string()))?,
52 );
53 }
54 for (nombre, valor) in headers {
55 let clave = tokio_tungstenite::tungstenite::http::HeaderName::try_from(*nombre)
56 .map_err(|e| TransportError::Url(e.to_string()))?;
57 let valor_hdr =
58 HeaderValue::from_str(valor).map_err(|e| TransportError::Url(e.to_string()))?;
59 request.headers_mut().insert(clave, valor_hdr);
60 }
61 let conectar = tokio::time::timeout(
62 Duration::from_secs(cfg.connect_timeout_secs),
63 tokio_tungstenite::connect_async(request),
64 );
65 let (inner, _) = conectar
66 .await
67 .map_err(|_| TransportError::Timeout {
68 phase: "ws-connect".into(),
69 ms: cfg.connect_timeout_secs * 1000,
70 })?
71 .map_err(|e| TransportError::Io(e.to_string()))?;
72 tracing::debug!(url, "websocket conectado");
73 Ok(Self {
74 inner,
75 url: url.to_string(),
76 })
77 }
78
79 pub async fn connect_con_reintentos(
81 url: &str,
82 headers: Vec<(String, String)>,
83 cfg: TransportConfig,
84 ) -> Result<Self, TransportError> {
85 with_retry(&cfg, "ws-connect", || {
86 let cfg_local = cfg.clone();
87 let pares: Vec<(&str, &str)> = headers
88 .iter()
89 .map(|(k, v)| (k.as_str(), v.as_str()))
90 .collect();
91 async move { Self::connect(url, &pares, &cfg_local).await }
92 })
93 .await
94 }
95
96 pub fn url(&self) -> &str {
97 &self.url
98 }
99
100 pub async fn enviar(
102 &mut self,
103 name: &str,
104 msg: &Value,
105 request_id: &str,
106 ) -> Result<(), TransportError> {
107 let frame = json!({ "name": name, "msg": msg, "request_id": request_id });
108 tracing::debug!(name, request_id, "ws enviar");
109 self.inner
110 .send(Message::Text(frame.to_string()))
111 .await
112 .map_err(|e| TransportError::Io(e.to_string()))
113 }
114
115 pub async fn enviar_sin_id(&mut self, name: &str, msg: &Value) -> Result<(), TransportError> {
117 let frame = json!({ "name": name, "msg": msg });
118 self.inner
119 .send(Message::Text(frame.to_string()))
120 .await
121 .map_err(|e| TransportError::Io(e.to_string()))
122 }
123
124 pub async fn siguiente(&mut self) -> Option<Result<WsFrame, TransportError>> {
128 loop {
129 let mensaje = match self.inner.next().await {
130 Some(Ok(m)) => m,
131 Some(Err(e)) => return Some(Err(TransportError::Io(e.to_string()))),
132 None => return None,
133 };
134 let texto = match mensaje {
135 Message::Text(t) => t,
136 Message::Ping(datos) => {
137 let _ = self.inner.send(Message::Pong(datos)).await;
138 continue;
139 }
140 Message::Pong(_) => continue,
141 Message::Close(_) => return None,
142 Message::Binary(datos) => match String::from_utf8(datos) {
143 Ok(t) => t,
144 Err(_) => return Some(Err(TransportError::Codec("binario no utf-8".into()))),
145 },
146 Message::Frame(_) => continue,
147 };
148 return match parsear(&texto) {
149 Ok(frame) => Some(Ok(frame)),
150 Err(e) => Some(Err(e)),
151 };
152 }
153 }
154
155 pub async fn cerrar(&mut self) -> Result<(), TransportError> {
157 self.inner
158 .close(None)
159 .await
160 .map_err(|e| TransportError::Io(e.to_string()))
161 }
162}
163
164pub fn parsear(texto: &str) -> Result<WsFrame, TransportError> {
166 let valor: Value = serde_json::from_str(texto)
167 .map_err(|e| TransportError::Codec(format!("json inválido: {e}")))?;
168 let name = valor
169 .get("name")
170 .and_then(|n| n.as_str())
171 .ok_or_else(|| TransportError::Codec("falta 'name' en el mensaje".into()))?
172 .to_string();
173 let msg = valor.get("msg").cloned().unwrap_or(Value::Null);
174 let request_id = valor
175 .get("request_id")
176 .and_then(|r| r.as_str())
177 .filter(|s| !s.is_empty())
178 .map(str::to_string);
179 Ok(WsFrame {
180 name,
181 msg,
182 request_id,
183 })
184}
185
186#[cfg(test)]
187mod tests {
188 use super::*;
189 use serde_json::json;
190
191 #[test]
192 fn parsea_envelope_completo() {
193 let frame =
194 parsear(r#"{"name":"profile","msg":{"balance":1},"request_id":"abc-1"}"#).unwrap();
195 assert_eq!(frame.name, "profile");
196 assert_eq!(frame.request_id.as_deref(), Some("abc-1"));
197 assert_eq!(frame.msg, json!({"balance": 1}));
198 }
199
200 #[test]
201 fn parsea_sin_request_id() {
202 let frame = parsear(r#"{"name":"timeSync","msg":1790000000000}"#).unwrap();
203 assert_eq!(frame.name, "timeSync");
204 assert!(frame.request_id.is_none());
205 }
206
207 #[test]
208 fn request_id_vacio_se_trata_como_ausente() {
209 let frame = parsear(r#"{"name":"x","msg":null,"request_id":""}"#).unwrap();
210 assert!(frame.request_id.is_none());
211 }
212
213 #[test]
214 fn sin_name_es_error_de_codec() {
215 let err = parsear(r#"{"msg":null}"#).expect_err("falta name");
216 assert!(matches!(err, TransportError::Codec(_)));
217 }
218
219 #[test]
220 fn json_invalido_es_error_de_codec() {
221 assert!(matches!(parsear("no-json"), Err(TransportError::Codec(_))));
222 }
223}