Skip to main content

jsonrpsee_core/server/
subscription.rs

1// Copyright 2019-2021 Parity Technologies (UK) Ltd.
2//
3// Permission is hereby granted, free of charge, to any
4// person obtaining a copy of this software and associated
5// documentation files (the "Software"), to deal in the
6// Software without restriction, including without
7// limitation the rights to use, copy, modify, merge,
8// publish, distribute, sublicense, and/or sell copies of
9// the Software, and to permit persons to whom the Software
10// is furnished to do so, subject to the following
11// conditions:
12//
13// The above copyright notice and this permission notice
14// shall be included in all copies or substantial portions
15// of the Software.
16//
17// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
18// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
19// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
20// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
21// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
22// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
23// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
24// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
25// DEALINGS IN THE SOFTWARE.
26
27//! Subscription related types and traits for server implementations.
28
29use super::{helpers::MethodSink, MethodResponse, ResponsePayload};
30use crate::{
31    error::SubscriptionError,
32    server::{
33        error::{DisconnectError, PendingSubscriptionAcceptError, SendTimeoutError, TrySendError},
34        rpc_module::ConnectionId,
35    },
36    traits::IdProvider,
37};
38use jsonrpsee_types::{
39    response::SubscriptionPayloadError, ErrorCode, ErrorObjectOwned, Id, SubscriptionId,
40    SubscriptionPayload, SubscriptionResponse,
41};
42use parking_lot::Mutex;
43use rustc_hash::FxHashMap;
44use serde::Serialize;
45use serde_json::value::RawValue;
46use std::{collections::hash_map::Entry, sync::Arc, time::Duration};
47use tokio::sync::{mpsc, oneshot, OwnedSemaphorePermit, Semaphore};
48
49/// Type-alias for subscribers.
50pub type Subscribers = Arc<Mutex<FxHashMap<SubscriptionKey, (MethodSink, mpsc::Receiver<()>)>>>;
51/// Subscription permit.
52pub type SubscriptionPermit = OwnedSemaphorePermit;
53
54/// Convert something into a subscription close notification
55/// before a subscription is terminated.
56pub trait IntoSubscriptionCloseResponse {
57    /// Convert something into a subscription response
58    fn into_response(self) -> SubscriptionCloseResponse;
59}
60
61/// Represents what action that will sent when a subscription callback returns.
62#[derive(Debug)]
63pub enum SubscriptionCloseResponse {
64    /// No further message will be sent.
65    None,
66    /// Send a subscription notification.
67    ///
68    /// The subscription notification has the following format:
69    ///
70    /// ```json
71    /// {
72    ///  "jsonrpc": "2.0",
73    ///  "method": "<method>",
74    ///  "params": {
75    ///    "subscription": "<subscriptionID>",
76    ///    "result": <your msg>
77    ///    }
78    ///  }
79    /// }
80    /// ```
81    Notif(SubscriptionMessage),
82    /// Send a subscription error notification
83    ///
84    /// The error notification has the following format:
85    ///
86    /// ```json
87    /// {
88    ///  "jsonrpc": "2.0",
89    ///  "method": "<method>",
90    ///  "params": {
91    ///    "subscription": "<subscriptionID>",
92    ///    "error": <your msg>
93    ///    }
94    ///  }
95    /// }
96    /// ```
97    NotifErr(SubscriptionError),
98}
99
100impl IntoSubscriptionCloseResponse for Result<(), SubscriptionError> {
101    fn into_response(self) -> SubscriptionCloseResponse {
102        match self {
103            Ok(()) => SubscriptionCloseResponse::None,
104            Err(e) => SubscriptionCloseResponse::NotifErr(e),
105        }
106    }
107}
108
109impl IntoSubscriptionCloseResponse for () {
110    fn into_response(self) -> SubscriptionCloseResponse {
111        SubscriptionCloseResponse::None
112    }
113}
114
115impl IntoSubscriptionCloseResponse for SubscriptionCloseResponse {
116    fn into_response(self) -> Self {
117        self
118    }
119}
120
121/// A complete subscription message or partial subscription message.
122#[derive(Debug, Clone)]
123pub enum SubscriptionMessageInner {
124    /// Complete JSON message.
125    Complete(String),
126    /// Need subscription ID and method name.
127    NeedsData(Box<RawValue>),
128    /// A result shared with other subscriptions, which needs the subscription ID and method name.
129    Shared(SharedResult),
130}
131
132/// Subscription message.
133#[derive(Debug, Clone)]
134pub struct SubscriptionMessage(pub(crate) SubscriptionMessageInner);
135
136impl From<Box<RawValue>> for SubscriptionMessage {
137    fn from(json: Box<RawValue>) -> Self {
138        Self(SubscriptionMessageInner::NeedsData(json))
139    }
140}
141
142impl SubscriptionMessage {
143    /// Create a subscription message this is more efficient than [`SubscriptionMessage::from`]
144    /// because it only allocates once.
145    ///
146    /// Fails if the json `result` couldn't be serialized.
147    pub fn new(
148        method: &str,
149        subscription: SubscriptionId,
150        result: &impl Serialize,
151    ) -> Result<Self, serde_json::Error> {
152        let json = serde_json::to_string(&SubscriptionResponse::new(
153            method.into(),
154            SubscriptionPayload { subscription, result },
155        ))?;
156        Ok(Self::from_complete_message(json))
157    }
158
159    /// Create a subscription message from a result that was serialized once for many
160    /// subscriptions. Sending it only copies the result into the notification.
161    pub fn from_shared(result: SharedResult) -> Self {
162        Self(SubscriptionMessageInner::Shared(result))
163    }
164
165    pub(crate) fn from_complete_message(msg: String) -> Self {
166        SubscriptionMessage(SubscriptionMessageInner::Complete(msg))
167    }
168}
169
170/// A subscription result that is serialized once and sent to any number of subscriptions.
171///
172/// It can only be created by serializing a value, so it always holds valid JSON. Clones share the
173/// serialized result.
174#[derive(Debug, Clone)]
175pub struct SharedResult(Arc<str>);
176
177impl SharedResult {
178    /// Serializes `result` for use in [`SubscriptionMessage::from_shared`].
179    ///
180    /// Fails if `result` couldn't be serialized.
181    pub fn new(result: &impl Serialize) -> Result<Self, serde_json::Error> {
182        Ok(Self(serde_json::to_string(result)?.into()))
183    }
184}
185
186/// Represent a unique subscription entry based on [`SubscriptionId`] and [`ConnectionId`].
187#[derive(Clone, Debug, PartialEq, Eq, Hash)]
188pub struct SubscriptionKey {
189    pub(crate) conn_id: ConnectionId,
190    pub(crate) sub_id: SubscriptionId<'static>,
191}
192
193/// Represents a subscription until it is unsubscribed.
194// NOTE: The reason why we use `mpsc` here is because it allows `IsUnsubscribed::unsubscribed`
195// to be &self instead of &mut self.
196#[derive(Debug, Clone)]
197pub struct IsUnsubscribed(mpsc::Sender<()>);
198
199impl IsUnsubscribed {
200    /// Returns true if the unsubscribe method has been invoked or the subscription has been
201    /// canceled.
202    ///
203    /// This can be called multiple times as the element in the channel is never
204    /// removed.
205    pub fn is_unsubscribed(&self) -> bool {
206        self.0.is_closed()
207    }
208
209    /// Wrapper over [`tokio::sync::mpsc::Sender::closed`]
210    ///
211    /// # Cancel safety
212    ///
213    /// This method is cancel safe. Once the channel is closed,
214    /// it stays closed forever and all future calls to closed will return immediately.
215    pub async fn unsubscribed(&self) {
216        self.0.closed().await;
217    }
218}
219
220/// Represents a single subscription that is waiting to be accepted or rejected.
221///
222/// If this is dropped without calling `PendingSubscription::reject` or
223/// `PendingSubscriptionSink::accept` a default error is sent out as response to the subscription
224/// call.
225///
226/// Thus, if you want a customized error message then `PendingSubscription::reject` must be called.
227#[derive(Debug)]
228#[must_use = "PendingSubscriptionSink does nothing unless `accept` or `reject` is called"]
229pub struct PendingSubscriptionSink {
230    /// Sink.
231    pub(crate) inner: MethodSink,
232    /// MethodCallback.
233    pub(crate) method: &'static str,
234    /// Shared Mutex of subscriptions for this method.
235    pub(crate) subscribers: Subscribers,
236    /// Unique subscription.
237    pub(crate) uniq_sub: SubscriptionKey,
238    /// ID of the `subscription call` (i.e. not the same as subscription id) which is used
239    /// to reply to subscription method call and must only be used once.
240    pub(crate) id: Id<'static>,
241    /// Sender to answer the subscribe call.
242    pub(crate) subscribe: oneshot::Sender<MethodResponse>,
243    /// Subscription permit.
244    pub(crate) permit: OwnedSemaphorePermit,
245}
246
247impl PendingSubscriptionSink {
248    /// Reject the subscription by responding to the subscription method call with
249    /// the error message from [`jsonrpsee_types::error::ErrorObject`].
250    ///
251    /// # Note
252    ///
253    /// If this is used in the async subscription callback
254    /// the return value is simply ignored because no further notification are propagated
255    /// once reject has been called.
256    pub async fn reject(self, err: impl Into<ErrorObjectOwned>) {
257        let err = MethodResponse::subscription_error(self.id, err.into());
258        _ = self.inner.send(err.to_json()).await;
259        _ = self.subscribe.send(err);
260    }
261
262    /// Attempt to accept the subscription and respond the subscription method call.
263    ///
264    /// # Errors
265    ///
266    /// Fails if the connection is closed, or if the subscription response exceeds the
267    /// `max_response_size`. In the latter case the call is answered with an oversized response
268    /// error and the subscription is not registered.
269    pub async fn accept(self) -> Result<SubscriptionSink, PendingSubscriptionAcceptError> {
270        let (tx, rx) = mpsc::channel(1);
271
272        // The key is reserved before the acknowledgement is sent: an occupied key belongs to a live
273        // subscription of this connection, which must not be replaced.
274        let reserved = match self.subscribers.lock().entry(self.uniq_sub.clone()) {
275            Entry::Vacant(entry) => {
276                entry.insert((self.inner.clone(), rx));
277                true
278            }
279            Entry::Occupied(_) => false,
280        };
281
282        if !reserved {
283            self.reject(ErrorCode::InternalError).await;
284            return Err(PendingSubscriptionAcceptError);
285        }
286
287        // Dropping the sink releases the reservation again if the acknowledgement isn't delivered.
288        let sink = SubscriptionSink {
289            inner: self.inner,
290            method: self.method,
291            subscribers: self.subscribers,
292            notification_prefix: notification_prefix(self.method, &self.uniq_sub.sub_id),
293            uniq_sub: self.uniq_sub,
294            unsubscribe: IsUnsubscribed(tx),
295            _permit: Some(Arc::new(self.permit)),
296        };
297
298        let response = MethodResponse::subscription_response(
299            self.id,
300            ResponsePayload::success_borrowed(&sink.uniq_sub.sub_id),
301            sink.inner.max_response_size() as usize,
302        );
303        let success = response.is_success();
304
305        // TODO: #1052
306        //
307        // Ideally the message should be sent only once.
308        //
309        // The same message is sent twice here because one is sent directly to the transport layer
310        // and the other one is sent internally to accept the subscription.
311        sink.inner.send(response.to_json()).await.map_err(|_| PendingSubscriptionAcceptError)?;
312        self.subscribe.send(response).map_err(|_| PendingSubscriptionAcceptError)?;
313
314        if success {
315            Ok(sink)
316        } else {
317            // The response exceeded the max response size and the call was answered with an error.
318            Err(PendingSubscriptionAcceptError)
319        }
320    }
321
322    /// Get the subscription ID.
323    pub fn subscription_id(&self) -> SubscriptionId<'static> {
324        self.uniq_sub.sub_id.clone()
325    }
326
327    /// Returns connection identifier, which was used to perform pending subscription request
328    pub fn connection_id(&self) -> ConnectionId {
329        self.uniq_sub.conn_id
330    }
331
332    /// Get the capacity of the channel.
333    pub fn capacity(&self) -> usize {
334        self.inner.capacity()
335    }
336
337    /// Get the max capacity of the channel.
338    pub fn max_capacity(&self) -> usize {
339        self.inner.max_capacity()
340    }
341
342    /// Get the method name.
343    pub fn method_name(&self) -> &str {
344        self.method
345    }
346}
347
348/// A handle to an active subscription.
349///
350/// Clones share the same subscription. The subscription is torn down when the last
351/// clone is dropped or the client explicitly unsubscribes.
352#[derive(Debug, Clone)]
353pub struct SubscriptionSink {
354    /// Sink.
355    inner: MethodSink,
356    /// MethodCallback.
357    method: &'static str,
358    /// Shared Mutex of subscriptions for this method.
359    subscribers: Subscribers,
360    /// The start of every notification of this subscription, see [`notification_prefix`].
361    notification_prefix: Arc<str>,
362    /// Unique subscription.
363    uniq_sub: SubscriptionKey,
364    /// A future to that fires once the unsubscribe method has been called.
365    unsubscribe: IsUnsubscribed,
366    /// Subscription permit.
367    _permit: Option<Arc<SubscriptionPermit>>,
368}
369
370impl SubscriptionSink {
371    /// Get the subscription ID.
372    pub fn subscription_id(&self) -> SubscriptionId<'static> {
373        self.uniq_sub.sub_id.clone()
374    }
375
376    /// Get the method name.
377    pub fn method_name(&self) -> &str {
378        self.method
379    }
380
381    /// Get the connection ID.
382    pub fn connection_id(&self) -> ConnectionId {
383        self.uniq_sub.conn_id
384    }
385
386    /// Send out a response on the subscription and wait until there is capacity.
387    ///
388    ///
389    /// Returns
390    /// - `Ok(())` if the message could be sent.
391    /// - `Err(unsent_msg)` if the connection or subscription was closed.
392    ///
393    /// # Cancel safety
394    ///
395    /// This method is cancel-safe and dropping a future loses its spot in the waiting queue.
396    pub async fn send(&self, msg: impl Into<SubscriptionMessage>) -> Result<(), DisconnectError> {
397        let msg = msg.into();
398
399        // Only possible to trigger when the connection is dropped.
400        if self.is_closed() {
401            return Err(DisconnectError(msg));
402        }
403
404        let json = sub_message_to_json(msg, &self.notification_prefix);
405        self.inner.send(json).await
406    }
407
408    /// Similar to `SubscriptionSink::send` but only waits for a limited time.
409    pub async fn send_timeout(
410        &self,
411        msg: impl Into<SubscriptionMessage>,
412        timeout: Duration,
413    ) -> Result<(), SendTimeoutError> {
414        let msg = msg.into();
415
416        // Only possible to trigger when the connection is dropped.
417        if self.is_closed() {
418            return Err(SendTimeoutError::Closed(msg));
419        }
420
421        let json = sub_message_to_json(msg, &self.notification_prefix);
422        self.inner.send_timeout(json, timeout).await
423    }
424
425    /// Attempts to immediately send out the message as JSON string to the subscribers but fails if
426    /// the channel is full or the connection/subscription is closed
427    ///
428    ///
429    /// This differs from [`SubscriptionSink::send`] where it will until there is capacity
430    /// in the channel.
431    pub fn try_send(&mut self, msg: impl Into<SubscriptionMessage>) -> Result<(), TrySendError> {
432        let msg = msg.into();
433
434        // Only possible to trigger when the connection is dropped.
435        if self.is_closed() {
436            return Err(TrySendError::Closed(msg));
437        }
438
439        let json = sub_message_to_json(msg, &self.notification_prefix);
440        self.inner.try_send(json)
441    }
442
443    /// Returns whether the subscription is closed.
444    pub fn is_closed(&self) -> bool {
445        self.inner.is_closed() || !self.is_active_subscription()
446    }
447
448    /// Completes when the subscription has been closed.
449    pub async fn closed(&self) {
450        // Both are cancel-safe thus ok to use select here.
451        tokio::select! {
452            _ = self.inner.closed() => (),
453            _ = self.unsubscribe.unsubscribed() => (),
454        }
455    }
456
457    /// Get the capacity of the subscription.
458    pub fn capacity(&self) -> usize {
459        self.inner.capacity()
460    }
461
462    /// Get the max capacity of the subscription.
463    pub fn max_capacity(&self) -> usize {
464        self.inner.max_capacity()
465    }
466
467    fn is_active_subscription(&self) -> bool {
468        !self.unsubscribe.is_unsubscribed()
469    }
470}
471
472impl Drop for SubscriptionSink {
473    fn drop(&mut self) {
474        // The activity check must happen under the lock: unsubscribing removes the entry (which
475        // marks this sink inactive) under the lock, and the same key can then be registered again.
476        let mut subs = self.subscribers.lock();
477        // Only the last clone should tear down the subscription (see #1622).
478        // The lock serializes concurrent drops so that exactly one `try_unwrap` succeeds.
479        if self.is_active_subscription() &&
480            self._permit.take().is_some_and(|p| Arc::try_unwrap(p).is_ok())
481        {
482            subs.remove(&self.uniq_sub);
483        }
484    }
485}
486
487/// This wraps [`tokio::sync::Semaphore`] and is used to limit the number of subscriptions per
488/// connection.
489#[derive(Debug, Clone)]
490pub struct BoundedSubscriptions {
491    guard: Arc<Semaphore>,
492    max: u32,
493}
494
495impl BoundedSubscriptions {
496    /// Create a new bounded subscription.
497    pub fn new(max_subscriptions: u32) -> Self {
498        Self { guard: Arc::new(Semaphore::new(max_subscriptions as usize)), max: max_subscriptions }
499    }
500
501    /// Attempts to acquire a subscription slot.
502    ///
503    /// Fails if `max_subscriptions` have been exceeded.
504    pub fn acquire(&self) -> Option<SubscriptionPermit> {
505        Arc::clone(&self.guard).try_acquire_owned().ok()
506    }
507
508    /// Get the maximum number of permitted subscriptions.
509    pub const fn max(&self) -> u32 {
510        self.max
511    }
512}
513
514#[derive(Debug)]
515/// Helper struct to manage subscriptions.
516pub struct SubscriptionState<'a> {
517    /// Connection ID
518    pub conn_id: ConnectionId,
519    /// ID provider.
520    pub id_provider: &'a dyn IdProvider,
521    /// Subscription limit
522    pub subscription_permit: SubscriptionPermit,
523}
524
525/// Returns the start of every notification of a subscription, up to its `result` value.
526///
527/// Followed by a result and [`NOTIFICATION_SUFFIX`], it matches what serializing a
528/// [`SubscriptionResponse`] produces byte for byte.
529pub(crate) fn notification_prefix(method: &str, sub_id: &SubscriptionId) -> Arc<str> {
530    let method = serde_json::to_string(method).expect("Serialize infallible; qed");
531    let sub_id = serde_json::to_string(sub_id).expect("Serialize infallible; qed");
532    format!(r#"{{"jsonrpc":"2.0","method":{method},"params":{{"subscription":{sub_id},"result":"#)
533        .into()
534}
535
536/// Closes the objects that [`notification_prefix`] opens.
537const NOTIFICATION_SUFFIX: &str = "}}";
538
539/// Returns the notification JSON for `msg`, given the subscription's [`notification_prefix`].
540pub(crate) fn sub_message_to_json(msg: SubscriptionMessage, notification_prefix: &str) -> String {
541    match msg.0 {
542        SubscriptionMessageInner::Complete(msg) => msg,
543        SubscriptionMessageInner::NeedsData(result) => {
544            splice_notification(notification_prefix, result.get())
545        }
546        SubscriptionMessageInner::Shared(SharedResult(result)) => {
547            splice_notification(notification_prefix, &result)
548        }
549    }
550}
551
552/// Builds a notification from a [`notification_prefix`] and a result with one allocation.
553fn splice_notification(notification_prefix: &str, result: &str) -> String {
554    let mut json =
555        String::with_capacity(notification_prefix.len() + result.len() + NOTIFICATION_SUFFIX.len());
556    json.push_str(notification_prefix);
557    json.push_str(result);
558    json.push_str(NOTIFICATION_SUFFIX);
559    json
560}
561
562pub(crate) fn sub_err_to_json(
563    error: SubscriptionError,
564    sub_id: SubscriptionId,
565    method: &str,
566) -> String {
567    serde_json::to_string(&jsonrpsee_types::response::SubscriptionError::new(
568        method.into(),
569        SubscriptionPayloadError { subscription: sub_id, error },
570    ))
571    .expect("Serialize infallible; qed")
572}
573
574#[cfg(test)]
575mod tests {
576    use super::*;
577    use crate::server::{MethodCallback, Methods, RpcModule};
578    use futures_util::FutureExt;
579    use jsonrpsee_types::Params;
580    use serde_json::value::to_raw_value;
581    use std::{
582        sync::atomic::{AtomicBool, Ordering},
583        time::Instant,
584    };
585
586    const SUB_ID: &str = "0xdeadbeef";
587
588    /// Id provider that hands out the same id for every subscription.
589    #[derive(Debug)]
590    struct ConstantId;
591
592    impl IdProvider for ConstantId {
593        fn next_id(&self) -> SubscriptionId<'static> {
594            SUB_ID.to_string().into()
595        }
596    }
597
598    /// Drives the callbacks that `RpcModule::register_subscription_raw` registers.
599    struct Harness {
600        methods: Methods,
601        pending: mpsc::UnboundedReceiver<PendingSubscriptionSink>,
602        permits: BoundedSubscriptions,
603    }
604
605    impl Harness {
606        fn new() -> Self {
607            let (pending_tx, pending) = mpsc::unbounded_channel();
608            let mut module = RpcModule::new(pending_tx);
609            module
610                .register_subscription_raw("sub", "notif", "unsub", |_, pending, ctx| {
611                    ctx.send(pending).unwrap();
612                })
613                .unwrap();
614
615            Self {
616                methods: Methods::clone(&module),
617                pending,
618                permits: BoundedSubscriptions::new(16),
619            }
620        }
621
622        /// Calls the subscribe method with request id `id` and returns the pending subscription
623        /// together with the future that resolves to the answer of the subscribe call.
624        fn subscribe(
625            &mut self,
626            id: u64,
627            conn_id: ConnectionId,
628            sink: &mpsc::Sender<String>,
629        ) -> (PendingSubscriptionSink, futures_util::future::BoxFuture<'static, MethodResponse>)
630        {
631            let state = SubscriptionState {
632                conn_id,
633                id_provider: &ConstantId,
634                subscription_permit: self.permits.acquire().unwrap(),
635            };
636            let Some(MethodCallback::Subscription(subscribe)) = self.methods.method("sub") else {
637                panic!("`sub` is a subscription");
638            };
639            let response =
640                subscribe(Id::Number(id), Params::new(None), MethodSink::new(sink.clone()), state);
641            (self.pending.try_recv().unwrap(), response)
642        }
643
644        /// Calls the unsubscribe method for `SUB_ID` and returns its json answer.
645        fn unsubscribe(&self, id: u64, conn_id: ConnectionId) -> String {
646            call_unsubscribe(&self.methods, SUB_ID, id, conn_id)
647        }
648    }
649
650    struct StopOnDrop<'a>(&'a AtomicBool);
651
652    impl Drop for StopOnDrop<'_> {
653        fn drop(&mut self) {
654            self.0.store(true, Ordering::Relaxed);
655        }
656    }
657
658    fn call_unsubscribe(methods: &Methods, sub_id: &str, id: u64, conn_id: ConnectionId) -> String {
659        let params = format!(r#"["{sub_id}"]"#);
660        let Some(MethodCallback::Unsubscription(unsubscribe)) = methods.method("unsub") else {
661            panic!("`unsub` is an unsubscription");
662        };
663        unsubscribe(Id::Number(id), Params::new(Some(&params)), conn_id, usize::MAX).into_json()
664    }
665
666    #[tokio::test]
667    async fn colliding_subscription_id_keeps_existing_subscription() {
668        let mut harness = Harness::new();
669        let conn_id = ConnectionId(0);
670        let (tx, mut rx) = mpsc::channel(8);
671
672        let (pending, response) = harness.subscribe(1, conn_id, &tx);
673        let first = pending.accept().await.unwrap();
674        let ack = r#"{"jsonrpc":"2.0","id":1,"result":"0xdeadbeef"}"#;
675        assert_eq!(response.await.into_json(), ack);
676        assert_eq!(rx.recv().await.unwrap(), ack);
677
678        // The provider hands out the id again: the second call fails with exactly one error.
679        let (pending, response) = harness.subscribe(2, conn_id, &tx);
680        assert!(matches!(pending.accept().await, Err(PendingSubscriptionAcceptError)));
681        let error =
682            r#"{"jsonrpc":"2.0","id":2,"error":{"code":-32603,"message":"Internal error"}}"#;
683        assert_eq!(response.await.into_json(), error);
684        assert_eq!(rx.recv().await.unwrap(), error);
685        assert!(rx.try_recv().is_err());
686
687        // The first subscription is untouched and still delivers items.
688        assert!(!first.is_closed());
689        first.send(to_raw_value(&"item").unwrap()).await.unwrap();
690        assert_eq!(
691            rx.recv().await.unwrap(),
692            r#"{"jsonrpc":"2.0","method":"notif","params":{"subscription":"0xdeadbeef","result":"item"}}"#
693        );
694
695        // It can be unsubscribed, which removes it.
696        assert_eq!(harness.unsubscribe(3, conn_id), r#"{"jsonrpc":"2.0","id":3,"result":true}"#);
697        assert!(first.is_closed());
698        assert_eq!(harness.unsubscribe(4, conn_id), r#"{"jsonrpc":"2.0","id":4,"result":false}"#);
699    }
700
701    #[test]
702    fn spliced_notifications_match_serialized_notifications() {
703        let results = [
704            serde_json::json!(null),
705            serde_json::json!(42),
706            serde_json::json!("quote \" backslash \\ newline \n emoji \u{1F600}"),
707            serde_json::json!({"nested": [1, "two", {"three": 3.5}], "empty": {}}),
708        ];
709        let ids = [
710            SubscriptionId::Num(7),
711            SubscriptionId::Str(SUB_ID.into()),
712            SubscriptionId::Str("needs \"escaping\"".into()),
713        ];
714
715        for method in ["eth_subscription", "odd \"method\""] {
716            for id in &ids {
717                let prefix = notification_prefix(method, id);
718                for result in &results {
719                    let serialized = SubscriptionMessage::new(method, id.clone(), result).unwrap();
720                    let expected = sub_message_to_json(serialized, &prefix);
721
722                    let shared =
723                        SubscriptionMessage::from_shared(SharedResult::new(result).unwrap());
724                    assert_eq!(sub_message_to_json(shared, &prefix), expected);
725                    let raw = SubscriptionMessage::from(to_raw_value(result).unwrap());
726                    assert_eq!(sub_message_to_json(raw, &prefix), expected);
727                }
728            }
729        }
730    }
731
732    #[tokio::test]
733    async fn shared_result_as_close_notification() {
734        let mut module = RpcModule::new(());
735        module
736            .register_subscription("sub", "notif", "unsub", |_, pending, _| async move {
737                let _sink = pending.accept().await.unwrap();
738                let result = SharedResult::new(&"last").unwrap();
739                SubscriptionCloseResponse::Notif(SubscriptionMessage::from_shared(result))
740            })
741            .unwrap();
742
743        let (response, mut rx) =
744            module.raw_json_request(r#"{"jsonrpc":"2.0","id":1,"method":"sub"}"#, 1).await.unwrap();
745        let response: serde_json::Value = serde_json::from_str(&response).unwrap();
746        let sub_id = &response["result"];
747        assert!(sub_id.is_u64(), "{response}");
748        assert_eq!(
749            rx.recv().await.unwrap(),
750            format!(
751                r#"{{"jsonrpc":"2.0","method":"notif","params":{{"subscription":{sub_id},"result":"last"}}}}"#
752            )
753        );
754    }
755
756    #[tokio::test]
757    async fn same_subscription_id_on_different_connections() {
758        let mut harness = Harness::new();
759        let (tx, _rx) = mpsc::channel(8);
760
761        let (pending, _first_response) = harness.subscribe(1, ConnectionId(0), &tx);
762        let first = pending.accept().await.unwrap();
763        let (pending, _second_response) = harness.subscribe(1, ConnectionId(1), &tx);
764        let second = pending.accept().await.unwrap();
765
766        assert_eq!(
767            harness.unsubscribe(2, ConnectionId(0)),
768            r#"{"jsonrpc":"2.0","id":2,"result":true}"#
769        );
770        assert!(first.is_closed());
771        assert!(!second.is_closed());
772        assert_eq!(
773            harness.unsubscribe(3, ConnectionId(1)),
774            r#"{"jsonrpc":"2.0","id":3,"result":true}"#
775        );
776        assert!(second.is_closed());
777    }
778
779    #[tokio::test]
780    async fn failed_acknowledgement_releases_subscription_id() {
781        let mut harness = Harness::new();
782        let conn_id = ConnectionId(0);
783
784        // The connection is gone, so the acknowledgement can't be delivered.
785        let (tx, rx) = mpsc::channel(8);
786        drop(rx);
787        let (pending, _) = harness.subscribe(1, conn_id, &tx);
788        assert!(matches!(pending.accept().await, Err(PendingSubscriptionAcceptError)));
789        assert_eq!(harness.unsubscribe(2, conn_id), r#"{"jsonrpc":"2.0","id":2,"result":false}"#);
790
791        // The id isn't blocked for later subscriptions.
792        let (tx, _rx) = mpsc::channel(8);
793        let (pending, _response) = harness.subscribe(3, conn_id, &tx);
794        let sink = pending.accept().await.unwrap();
795        assert_eq!(harness.unsubscribe(4, conn_id), r#"{"jsonrpc":"2.0","id":4,"result":true}"#);
796        assert!(sink.is_closed());
797    }
798
799    #[tokio::test]
800    async fn dropping_unsubscribed_sink_keeps_replacement_subscription() {
801        let mut harness = Harness::new();
802        let conn_id = ConnectionId(0);
803        let (tx, _rx) = mpsc::channel(8);
804
805        let (pending, _first_response) = harness.subscribe(1, conn_id, &tx);
806        let first = pending.accept().await.unwrap();
807        assert_eq!(harness.unsubscribe(2, conn_id), r#"{"jsonrpc":"2.0","id":2,"result":true}"#);
808
809        // The same id is registered again while the sink of the old subscription is still alive.
810        let (pending, _second_response) = harness.subscribe(3, conn_id, &tx);
811        let second = pending.accept().await.unwrap();
812
813        drop(first);
814        assert!(!second.is_closed());
815        assert_eq!(harness.unsubscribe(4, conn_id), r#"{"jsonrpc":"2.0","id":4,"result":true}"#);
816        assert!(second.is_closed());
817    }
818
819    /// Drops the sink of a subscription while it is unsubscribed and registered again under the
820    /// same id from another thread. The replacement must survive in every interleaving.
821    #[test]
822    fn dropping_sink_races_with_unsubscribe_and_resubscribe() {
823        let mut harness = Harness::new();
824        let methods = harness.methods.clone();
825        let conn_id = ConnectionId(0);
826        let (tx, mut rx) = mpsc::channel(8);
827        let deadline = Instant::now() + Duration::from_secs(1);
828        let stop = AtomicBool::new(false);
829        let mut removed_replacements = 0;
830
831        std::thread::scope(|scope| {
832            // Stops the contending threads even if an assertion below panics.
833            let _stop = StopOnDrop(&stop);
834
835            // Contend for the registry lock like other connections do.
836            for i in 0..4 {
837                let (methods, stop) = (&methods, &stop);
838                scope.spawn(move || {
839                    while !stop.load(Ordering::Relaxed) {
840                        call_unsubscribe(methods, "other", 0, ConnectionId(1000 + i));
841                    }
842                });
843            }
844
845            while Instant::now() < deadline {
846                while rx.try_recv().is_ok() {}
847
848                let (pending, _first_response) = harness.subscribe(1, conn_id, &tx);
849                let first = pending.accept().now_or_never().unwrap().unwrap();
850                let (pending, _second_response) = harness.subscribe(2, conn_id, &tx);
851
852                let go = AtomicBool::new(false);
853                let second = std::thread::scope(|race| {
854                    let (methods, go) = (&methods, &go);
855                    let dropper = race.spawn(move || {
856                        while !go.load(Ordering::Acquire) {
857                            std::hint::spin_loop();
858                        }
859                        drop(first);
860                    });
861                    let replacer = race.spawn(move || {
862                        while !go.load(Ordering::Acquire) {
863                            std::hint::spin_loop();
864                        }
865                        call_unsubscribe(methods, SUB_ID, 3, conn_id);
866                        pending.accept().now_or_never().unwrap().unwrap()
867                    });
868                    go.store(true, Ordering::Release);
869                    dropper.join().unwrap();
870                    replacer.join().unwrap()
871                });
872
873                if second.is_closed() {
874                    removed_replacements += 1;
875                }
876            }
877        });
878
879        assert_eq!(removed_replacements, 0);
880    }
881}