Skip to main content

erpc_sdk/
subscriptions.rs

1use std::{collections::HashMap, sync::Arc, time::Duration};
2
3use futures_util::{SinkExt, StreamExt};
4use serde::{Deserialize, Serialize, de::DeserializeOwned};
5use serde_json::Value;
6use tokio::sync::{Mutex, broadcast, mpsc, oneshot};
7use tokio_tungstenite::{connect_async, tungstenite::Message};
8use tokio_util::sync::CancellationToken;
9use url::Url;
10
11use crate::{
12    ErpcError, JsonRpcErrorObject, Result,
13    error::{invalid_response, rpc_error_with_secrets, timeout},
14    rpc::{decode_json, parse_json_rpc_id},
15};
16
17/// JSON-RPC subscription identifier.
18#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
19#[serde(untagged)]
20pub enum SubscriptionId {
21    /// Numeric identifier used by Solana subscriptions.
22    Number(u64),
23    /// String identifier used by Ethereum subscriptions.
24    String(String),
25}
26
27/// One JSON-RPC notification received over WebSocket.
28#[derive(Clone, Debug, Deserialize, PartialEq)]
29pub struct RpcNotification {
30    /// JSON-RPC protocol version.
31    pub jsonrpc: String,
32    /// Wire-compatible notification method.
33    pub method: String,
34    /// Notification parameters.
35    pub params: Value,
36}
37
38type PendingMap = Arc<Mutex<HashMap<u64, oneshot::Sender<Result<Value>>>>>;
39
40pub(crate) struct WebSocketJsonRpcTransport {
41    connection_url: Url,
42    public_endpoint: String,
43    redaction_secrets: Vec<String>,
44    timeout: Duration,
45    next_id: std::sync::atomic::AtomicU64,
46    outbound: Mutex<Option<mpsc::UnboundedSender<Message>>>,
47    pending: PendingMap,
48    notifications: broadcast::Sender<RpcNotification>,
49    configured: bool,
50    namespace: String,
51}
52
53impl WebSocketJsonRpcTransport {
54    pub fn new(connection_url: Url, timeout: Duration) -> Self {
55        let credential = connection_url
56            .query_pairs()
57            .find_map(|(key, value)| (key == "api-key").then(|| value.into_owned()))
58            .unwrap_or_default();
59        let redaction_secrets = (!credential.is_empty())
60            .then_some(vec![credential])
61            .unwrap_or_default();
62        Self::from_parts(
63            connection_url,
64            redaction_secrets,
65            timeout,
66            "subscriptions",
67            true,
68        )
69    }
70
71    pub(crate) fn new_direct(
72        connection_url: Url,
73        redaction_secrets: Vec<String>,
74        timeout: Duration,
75        namespace: impl Into<String>,
76    ) -> Self {
77        Self::from_parts(connection_url, redaction_secrets, timeout, namespace, true)
78    }
79
80    pub(crate) fn unavailable(namespace: impl Into<String>, timeout: Duration) -> Self {
81        Self::from_parts(
82            Url::parse("ws://127.0.0.1/").expect("static unavailable endpoint"),
83            Vec::new(),
84            timeout,
85            namespace,
86            false,
87        )
88    }
89
90    fn from_parts(
91        connection_url: Url,
92        redaction_secrets: Vec<String>,
93        timeout: Duration,
94        namespace: impl Into<String>,
95        configured: bool,
96    ) -> Self {
97        let mut public = connection_url.clone();
98        public.set_query(None);
99        public.set_fragment(None);
100        let public_endpoint = if configured {
101            public.to_string()
102        } else {
103            String::new()
104        };
105        let (notifications, _) = broadcast::channel(256);
106        Self {
107            connection_url,
108            public_endpoint,
109            redaction_secrets,
110            timeout,
111            next_id: std::sync::atomic::AtomicU64::new(1),
112            outbound: Mutex::new(None),
113            pending: Arc::new(Mutex::new(HashMap::new())),
114            notifications,
115            configured,
116            namespace: namespace.into(),
117        }
118    }
119
120    pub fn endpoint(&self) -> &str {
121        &self.public_endpoint
122    }
123
124    async fn connect(&self) -> Result<mpsc::UnboundedSender<Message>> {
125        self.ensure_configured()?;
126        let mut outbound = self.outbound.lock().await;
127        if let Some(sender) = outbound.as_ref() {
128            if !sender.is_closed() {
129                return Ok(sender.clone());
130            }
131        }
132        let connection =
133            tokio::time::timeout(self.timeout, connect_async(self.connection_url.as_str()))
134                .await
135                .map_err(|_| timeout(self.timeout))?
136                .map_err(|_| {
137                    ErpcError::Transport("Unable to connect to ERPC WebSocket".to_owned())
138                })?;
139        let (mut sink, mut stream) = connection.0.split();
140        let (sender, mut receiver) = mpsc::unbounded_channel();
141        *outbound = Some(sender.clone());
142
143        let pending_for_writer = Arc::clone(&self.pending);
144        tokio::spawn(async move {
145            while let Some(message) = receiver.recv().await {
146                if sink.send(message).await.is_err() {
147                    break;
148                }
149            }
150            let mut pending = pending_for_writer.lock().await;
151            for (_, response) in pending.drain() {
152                let _ = response.send(Err(ErpcError::Transport(
153                    "ERPC WebSocket connection closed".to_owned(),
154                )));
155            }
156        });
157
158        let pending_for_reader = Arc::clone(&self.pending);
159        let notifications = self.notifications.clone();
160        let redaction_secrets = self.redaction_secrets.clone();
161        tokio::spawn(async move {
162            while let Some(message) = stream.next().await {
163                let Ok(message) = message else { break };
164                let text = match message {
165                    Message::Text(text) => text.to_string(),
166                    Message::Binary(bytes) => String::from_utf8_lossy(&bytes).into_owned(),
167                    Message::Close(_) => break,
168                    _ => continue,
169                };
170                let Ok(value) = decode_json::<Value>(&text) else {
171                    continue;
172                };
173                if let Value::Array(values) = value {
174                    for value in values {
175                        dispatch(
176                            value,
177                            &pending_for_reader,
178                            &notifications,
179                            &redaction_secrets,
180                        )
181                        .await;
182                    }
183                } else {
184                    dispatch(
185                        value,
186                        &pending_for_reader,
187                        &notifications,
188                        &redaction_secrets,
189                    )
190                    .await;
191                }
192            }
193            let mut pending = pending_for_reader.lock().await;
194            for (_, response) in pending.drain() {
195                let _ = response.send(Err(ErpcError::Transport(
196                    "ERPC WebSocket connection closed".to_owned(),
197                )));
198            }
199        });
200        Ok(sender)
201    }
202
203    pub async fn request<T: DeserializeOwned>(
204        &self,
205        method: &str,
206        params: Value,
207        cancellation: Option<&CancellationToken>,
208    ) -> Result<T> {
209        let sender = self.connect().await?;
210        let id = self
211            .next_id
212            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
213        let request = serde_json::json!({
214            "jsonrpc": "2.0",
215            "id": id,
216            "method": method,
217            "params": params,
218        });
219        let text = serde_json::to_string(&request)
220            .map_err(|_| ErpcError::Config("RPC parameters could not be serialized".to_owned()))?;
221        let (response_sender, response_receiver) = oneshot::channel();
222        self.pending.lock().await.insert(id, response_sender);
223        if sender.send(Message::Text(text.into())).is_err() {
224            self.pending.lock().await.remove(&id);
225            return Err(ErpcError::Transport(
226                "Unable to send ERPC WebSocket request".to_owned(),
227            ));
228        }
229        let response = if let Some(cancellation) = cancellation {
230            tokio::select! {
231                () = cancellation.cancelled() => {
232                    self.pending.lock().await.remove(&id);
233                    return Err(ErpcError::Aborted);
234                }
235                response = tokio::time::timeout(self.timeout, response_receiver) => response,
236            }
237        } else {
238            tokio::time::timeout(self.timeout, response_receiver).await
239        };
240        let value = response
241            .map_err(|_| timeout(self.timeout))?
242            .map_err(|_| ErpcError::Transport("ERPC WebSocket connection closed".to_owned()))??;
243        serde_json::from_value(value)
244            .map_err(|_| invalid_response("ERPC returned an unexpected result shape"))
245    }
246
247    pub fn subscribe_notifications(&self) -> broadcast::Receiver<RpcNotification> {
248        self.notifications.subscribe()
249    }
250
251    pub async fn close(&self) {
252        if let Some(sender) = self.outbound.lock().await.take() {
253            let _ = sender.send(Message::Close(None));
254        }
255    }
256
257    fn ensure_configured(&self) -> Result<()> {
258        if self.configured {
259            Ok(())
260        } else {
261            Err(ErpcError::NotConfigured(self.namespace.clone()))
262        }
263    }
264}
265
266async fn dispatch(
267    value: Value,
268    pending: &PendingMap,
269    notifications: &broadcast::Sender<RpcNotification>,
270    redaction_secrets: &[String],
271) {
272    let Some(object) = value.as_object() else {
273        return;
274    };
275    if object.contains_key("id") {
276        let Some(crate::JsonRpcId::Number(id)) = object
277            .get("id")
278            .and_then(|value| parse_json_rpc_id(value).ok())
279        else {
280            return;
281        };
282        let Some(response) = pending.lock().await.remove(&id) else {
283            return;
284        };
285        if let Some(error) = object.get("error") {
286            let result = serde_json::from_value::<JsonRpcErrorObject>(error.clone()).map_or_else(
287                |_| Err(invalid_response("ERPC returned an invalid RPC error")),
288                |error| Err(rpc_error_with_secrets(error, redaction_secrets)),
289            );
290            let _ = response.send(result);
291        } else if let Some(result) = object.get("result") {
292            let _ = response.send(Ok(result.clone()));
293        } else {
294            let _ = response.send(Err(invalid_response("ERPC returned an invalid response")));
295        }
296        return;
297    }
298    if object.get("jsonrpc").and_then(Value::as_str) == Some("2.0")
299        && object.get("method").and_then(Value::as_str).is_some()
300        && object.contains_key("params")
301    {
302        let notification = RpcNotification {
303            jsonrpc: "2.0".to_owned(),
304            method: object["method"].as_str().unwrap_or_default().to_owned(),
305            params: object["params"].clone(),
306        };
307        let _ = notifications.send(notification);
308    }
309}
310
311/// Active subscription with typed notification retrieval and idempotent unsubscribe.
312pub struct RpcSubscription {
313    /// Server subscription identifier.
314    pub id: SubscriptionId,
315    transport: Arc<WebSocketJsonRpcTransport>,
316    unsubscribe_method: String,
317    receiver: Mutex<broadcast::Receiver<RpcNotification>>,
318    closed: std::sync::atomic::AtomicBool,
319}
320
321impl RpcSubscription {
322    pub(crate) fn new(
323        id: SubscriptionId,
324        transport: Arc<WebSocketJsonRpcTransport>,
325        unsubscribe_method: impl Into<String>,
326        receiver: broadcast::Receiver<RpcNotification>,
327    ) -> Self {
328        Self {
329            id,
330            transport,
331            unsubscribe_method: unsubscribe_method.into(),
332            receiver: Mutex::new(receiver),
333            closed: std::sync::atomic::AtomicBool::new(false),
334        }
335    }
336
337    /// Waits for the next matching notification and deserializes its `result`.
338    pub async fn next<T: DeserializeOwned>(&self) -> Result<T> {
339        loop {
340            let notification = self.receiver.lock().await.recv().await.map_err(|_| {
341                ErpcError::Transport("ERPC WebSocket notification stream closed".to_owned())
342            })?;
343            let Some(params) = notification.params.as_object() else {
344                continue;
345            };
346            let Some(subscription) = params.get("subscription") else {
347                continue;
348            };
349            let Ok(subscription) = serde_json::from_value::<SubscriptionId>(subscription.clone())
350            else {
351                continue;
352            };
353            if subscription != self.id {
354                continue;
355            }
356            let result = params
357                .get("result")
358                .cloned()
359                .ok_or_else(|| invalid_response("ERPC returned an invalid notification"))?;
360            return serde_json::from_value(result)
361                .map_err(|_| invalid_response("ERPC returned an unexpected result shape"));
362        }
363    }
364
365    /// Unsubscribes. Calls after a successful unsubscribe return `true`.
366    pub async fn unsubscribe(&self) -> Result<bool> {
367        if self.closed.load(std::sync::atomic::Ordering::Acquire) {
368            return Ok(true);
369        }
370        let result: bool = self
371            .transport
372            .request(&self.unsubscribe_method, serde_json::json!([self.id]), None)
373            .await?;
374        if result {
375            self.closed
376                .store(true, std::sync::atomic::Ordering::Release);
377        }
378        Ok(result)
379    }
380}