1use 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
49pub type Subscribers = Arc<Mutex<FxHashMap<SubscriptionKey, (MethodSink, mpsc::Receiver<()>)>>>;
51pub type SubscriptionPermit = OwnedSemaphorePermit;
53
54pub trait IntoSubscriptionCloseResponse {
57 fn into_response(self) -> SubscriptionCloseResponse;
59}
60
61#[derive(Debug)]
63pub enum SubscriptionCloseResponse {
64 None,
66 Notif(SubscriptionMessage),
82 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#[derive(Debug, Clone)]
123pub enum SubscriptionMessageInner {
124 Complete(String),
126 NeedsData(Box<RawValue>),
128 Shared(SharedResult),
130}
131
132#[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 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 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#[derive(Debug, Clone)]
175pub struct SharedResult(Arc<str>);
176
177impl SharedResult {
178 pub fn new(result: &impl Serialize) -> Result<Self, serde_json::Error> {
182 Ok(Self(serde_json::to_string(result)?.into()))
183 }
184}
185
186#[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#[derive(Debug, Clone)]
197pub struct IsUnsubscribed(mpsc::Sender<()>);
198
199impl IsUnsubscribed {
200 pub fn is_unsubscribed(&self) -> bool {
206 self.0.is_closed()
207 }
208
209 pub async fn unsubscribed(&self) {
216 self.0.closed().await;
217 }
218}
219
220#[derive(Debug)]
228#[must_use = "PendingSubscriptionSink does nothing unless `accept` or `reject` is called"]
229pub struct PendingSubscriptionSink {
230 pub(crate) inner: MethodSink,
232 pub(crate) method: &'static str,
234 pub(crate) subscribers: Subscribers,
236 pub(crate) uniq_sub: SubscriptionKey,
238 pub(crate) id: Id<'static>,
241 pub(crate) subscribe: oneshot::Sender<MethodResponse>,
243 pub(crate) permit: OwnedSemaphorePermit,
245}
246
247impl PendingSubscriptionSink {
248 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 pub async fn accept(self) -> Result<SubscriptionSink, PendingSubscriptionAcceptError> {
270 let (tx, rx) = mpsc::channel(1);
271
272 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 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 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 Err(PendingSubscriptionAcceptError)
319 }
320 }
321
322 pub fn subscription_id(&self) -> SubscriptionId<'static> {
324 self.uniq_sub.sub_id.clone()
325 }
326
327 pub fn connection_id(&self) -> ConnectionId {
329 self.uniq_sub.conn_id
330 }
331
332 pub fn capacity(&self) -> usize {
334 self.inner.capacity()
335 }
336
337 pub fn max_capacity(&self) -> usize {
339 self.inner.max_capacity()
340 }
341
342 pub fn method_name(&self) -> &str {
344 self.method
345 }
346}
347
348#[derive(Debug, Clone)]
353pub struct SubscriptionSink {
354 inner: MethodSink,
356 method: &'static str,
358 subscribers: Subscribers,
360 notification_prefix: Arc<str>,
362 uniq_sub: SubscriptionKey,
364 unsubscribe: IsUnsubscribed,
366 _permit: Option<Arc<SubscriptionPermit>>,
368}
369
370impl SubscriptionSink {
371 pub fn subscription_id(&self) -> SubscriptionId<'static> {
373 self.uniq_sub.sub_id.clone()
374 }
375
376 pub fn method_name(&self) -> &str {
378 self.method
379 }
380
381 pub fn connection_id(&self) -> ConnectionId {
383 self.uniq_sub.conn_id
384 }
385
386 pub async fn send(&self, msg: impl Into<SubscriptionMessage>) -> Result<(), DisconnectError> {
397 let msg = msg.into();
398
399 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 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 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 pub fn try_send(&mut self, msg: impl Into<SubscriptionMessage>) -> Result<(), TrySendError> {
432 let msg = msg.into();
433
434 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 pub fn is_closed(&self) -> bool {
445 self.inner.is_closed() || !self.is_active_subscription()
446 }
447
448 pub async fn closed(&self) {
450 tokio::select! {
452 _ = self.inner.closed() => (),
453 _ = self.unsubscribe.unsubscribed() => (),
454 }
455 }
456
457 pub fn capacity(&self) -> usize {
459 self.inner.capacity()
460 }
461
462 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 let mut subs = self.subscribers.lock();
477 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#[derive(Debug, Clone)]
490pub struct BoundedSubscriptions {
491 guard: Arc<Semaphore>,
492 max: u32,
493}
494
495impl BoundedSubscriptions {
496 pub fn new(max_subscriptions: u32) -> Self {
498 Self { guard: Arc::new(Semaphore::new(max_subscriptions as usize)), max: max_subscriptions }
499 }
500
501 pub fn acquire(&self) -> Option<SubscriptionPermit> {
505 Arc::clone(&self.guard).try_acquire_owned().ok()
506 }
507
508 pub const fn max(&self) -> u32 {
510 self.max
511 }
512}
513
514#[derive(Debug)]
515pub struct SubscriptionState<'a> {
517 pub conn_id: ConnectionId,
519 pub id_provider: &'a dyn IdProvider,
521 pub subscription_permit: SubscriptionPermit,
523}
524
525pub(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
536const NOTIFICATION_SUFFIX: &str = "}}";
538
539pub(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
552fn 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 #[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 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 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 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(¶ms)), 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 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 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 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 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 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 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 #[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 let _stop = StopOnDrop(&stop);
834
835 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}