jsonrpsee_core/server/rpc_module.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
27use std::{
28 collections::hash_map::Entry,
29 fmt::Debug,
30 future::Future,
31 ops::{Deref, DerefMut},
32 sync::{
33 atomic::{AtomicUsize, Ordering},
34 Arc,
35 },
36};
37
38use crate::{
39 error::RegisterMethodError,
40 id_providers::RandomIntegerIdProvider,
41 server::{
42 helpers::MethodSink,
43 subscription::{
44 notification_prefix, sub_message_to_json, BoundedSubscriptions,
45 IntoSubscriptionCloseResponse, PendingSubscriptionSink, Subscribers,
46 SubscriptionCloseResponse, SubscriptionKey, SubscriptionPermit, SubscriptionState,
47 },
48 MethodResponse, ResponsePayload, ResponseSizeHint, ResponseStream, LOG_TARGET,
49 },
50};
51use futures_util::{future::BoxFuture, FutureExt};
52use jsonrpsee_types::{
53 error::{ErrorCode, ErrorObject, ErrorObjectOwned},
54 Id, Params, Request, SubscriptionId as RpcSubscriptionId,
55};
56use rustc_hash::FxHashMap;
57use tokio::sync::{mpsc, oneshot};
58
59use super::{sub_err_to_json, IntoResponse};
60
61/// A `MethodCallback` is an RPC endpoint, callable with a standard JSON-RPC request,
62/// implemented as a function pointer to a `Fn` function taking four arguments:
63/// the `id`, `params`, a channel the function uses to communicate the result (or error)
64/// back to `jsonrpsee`, and the connection ID (useful for the websocket transport).
65pub type SyncMethod = Arc<dyn Send + Sync + Fn(Id, Params, MaxResponseSize) -> MethodResponse>;
66/// Similar to [`SyncMethod`], but represents an asynchronous handler.
67///
68/// The params are only borrowed for the call, so a handler that needs them in its future takes
69/// ownership with [`Params::into_owned`].
70pub type AsyncMethod<'a> = Arc<
71 dyn Send
72 + Sync
73 + Fn(Id<'a>, Params<'_>, ConnectionId, MaxResponseSize) -> BoxFuture<'a, MethodResponse>,
74>;
75
76/// Method callback for subscriptions.
77pub type SubscriptionMethod<'a> = Arc<
78 dyn Send
79 + Sync
80 + Fn(Id, Params, MethodSink, SubscriptionState) -> BoxFuture<'a, MethodResponse>,
81>;
82// Method callback to unsubscribe.
83type UnsubscriptionMethod =
84 Arc<dyn Send + Sync + Fn(Id, Params, ConnectionId, MaxResponseSize) -> MethodResponse>;
85
86/// Connection ID.
87#[derive(
88 Debug, Copy, Clone, PartialEq, Eq, Hash, Default, serde::Deserialize, serde::Serialize,
89)]
90pub struct ConnectionId(pub usize);
91
92impl ConnectionId {
93 /// Owner of subscriptions created by in-process calls such as
94 /// [`Methods::raw_json_request`].
95 ///
96 /// Servers count connections upwards from zero and never reach this value, so no transport
97 /// connection can unsubscribe an in-process subscription.
98 pub const IN_PROCESS: Self = Self(usize::MAX);
99
100 /// Returns an id that no other live connection in this process shares.
101 ///
102 /// Together with the subscription id this scopes a subscription, and servers of different
103 /// transports can serve one shared subscription table, so the id has to be unique across every
104 /// server in the process and not only within a single accept loop. Counting per server would
105 /// give the first connection of each transport the same id, and an unsubscribe on one of them
106 /// would then cancel a subscription of another.
107 ///
108 /// A `usize` cannot wrap in practice on 64-bit targets, so ids are never reused and never reach
109 /// [`Self::IN_PROCESS`].
110 pub fn next_unique() -> Self {
111 static NEXT: AtomicUsize = AtomicUsize::new(0);
112
113 Self(NEXT.fetch_add(1, Ordering::Relaxed))
114 }
115}
116
117impl From<usize> for ConnectionId {
118 fn from(id: usize) -> Self {
119 Self(id)
120 }
121}
122
123/// Max response size.
124pub type MaxResponseSize = usize;
125
126/// Callback wrapper that can be either sync or async.
127#[derive(Clone)]
128pub enum MethodCallback {
129 /// Synchronous method handler.
130 Sync(SyncMethod),
131 /// Asynchronous method handler.
132 Async(AsyncMethod<'static>),
133 /// Subscription method handler.
134 Subscription(SubscriptionMethod<'static>),
135 /// Unsubscription method handler.
136 Unsubscription(UnsubscriptionMethod),
137}
138
139impl Debug for MethodCallback {
140 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
141 match self {
142 Self::Async(_) => write!(f, "Async"),
143 Self::Sync(_) => write!(f, "Sync"),
144 Self::Subscription(_) => write!(f, "Subscription"),
145 Self::Unsubscription(_) => write!(f, "Unsubscription"),
146 }
147 }
148}
149
150/// Reference-counted, clone-on-write collection of synchronous and asynchronous methods.
151#[derive(Default, Debug, Clone)]
152pub struct Methods {
153 callbacks: Arc<FxHashMap<&'static str, MethodCallback>>,
154}
155
156impl Methods {
157 /// Creates a new empty [`Methods`].
158 pub fn new() -> Self {
159 Self::default()
160 }
161
162 /// Verifies that the method name is not already taken, and returns an error if it is.
163 pub fn verify_method_name(&mut self, name: &'static str) -> Result<(), RegisterMethodError> {
164 if self.callbacks.contains_key(name) {
165 return Err(RegisterMethodError::AlreadyRegistered(name.into()));
166 }
167
168 Ok(())
169 }
170
171 /// Inserts the method callback for a given name, or returns an error if the name was already
172 /// taken. On success it returns a mut reference to the [`MethodCallback`] just inserted.
173 pub fn verify_and_insert(
174 &mut self,
175 name: &'static str,
176 callback: MethodCallback,
177 ) -> Result<&mut MethodCallback, RegisterMethodError> {
178 match self.mut_callbacks().entry(name) {
179 Entry::Occupied(_) => Err(RegisterMethodError::AlreadyRegistered(name.into())),
180 Entry::Vacant(vacant) => Ok(vacant.insert(callback)),
181 }
182 }
183
184 /// Helper for obtaining a mut ref to the callbacks HashMap.
185 fn mut_callbacks(&mut self) -> &mut FxHashMap<&'static str, MethodCallback> {
186 Arc::make_mut(&mut self.callbacks)
187 }
188
189 /// Merge two [`Methods`]'s by adding all [`MethodCallback`]s from `other` into `self`.
190 /// Fails if any of the methods in `other` is present already.
191 pub fn merge(&mut self, other: impl Into<Methods>) -> Result<(), RegisterMethodError> {
192 let mut other = other.into();
193
194 for name in other.callbacks.keys() {
195 self.verify_method_name(name)?;
196 }
197
198 let callbacks = self.mut_callbacks();
199
200 for (name, callback) in other.mut_callbacks().drain() {
201 callbacks.insert(name, callback);
202 }
203
204 Ok(())
205 }
206
207 /// Returns the method callback.
208 pub fn method(&self, method_name: &str) -> Option<&MethodCallback> {
209 self.callbacks.get(method_name)
210 }
211
212 /// Make a request (JSON-RPC method call or subscription) by using raw JSON.
213 ///
214 /// Returns the raw JSON response to the call and a stream to receive notifications if the call
215 /// was a subscription.
216 ///
217 /// # Examples
218 ///
219 /// ```
220 /// #[tokio::main]
221 /// async fn main() {
222 /// use jsonrpsee::{RpcModule, SubscriptionMessage};
223 /// use jsonrpsee::types::{response::Success, Response};
224 /// use jsonrpsee::core::to_json_raw_value;
225 /// use futures_util::StreamExt;
226 ///
227 /// let mut module = RpcModule::new(());
228 /// module.register_subscription("hi", "hi", "goodbye", |_, pending, _| async {
229 /// let sink = pending.accept().await?;
230 ///
231 /// // see comment above.
232 /// let msg = to_json_raw_value(&"one answer").unwrap();
233 /// sink.send(msg).await?;
234 ///
235 /// Ok(())
236 /// }).unwrap();
237 /// let (resp, mut stream) = module.raw_json_request(r#"{"jsonrpc":"2.0","method":"hi","id":0}"#, 1).await.unwrap();
238 /// // If the response is an error converting it to `Success` will fail.
239 /// let resp: Success<u64> = serde_json::from_str::<Response<u64>>(&resp).unwrap().try_into().unwrap();
240 /// let sub_resp = stream.recv().await.unwrap();
241 /// assert_eq!(
242 /// format!(r#"{{"jsonrpc":"2.0","method":"hi","params":{{"subscription":{},"result":"one answer"}}}}"#, resp.result),
243 /// sub_resp
244 /// );
245 /// }
246 /// ```
247 pub async fn raw_json_request(
248 &self,
249 request: &str,
250 buf_size: usize,
251 ) -> Result<(String, mpsc::Receiver<String>), serde_json::Error> {
252 tracing::trace!("[Methods::raw_json_request] Request: {:?}", request);
253 let req: Request = serde_json::from_str(request)?;
254 let (resp, rx) = self.inner_call(req, buf_size, mock_subscription_permit()).await;
255
256 Ok((resp, rx))
257 }
258
259 /// Execute a callback.
260 async fn inner_call(
261 &self,
262 req: Request<'_>,
263 buf_size: usize,
264 subscription_permit: SubscriptionPermit,
265 ) -> (String, mpsc::Receiver<String>) {
266 let (tx, mut rx) = mpsc::channel(buf_size);
267 let Request { id, method, params, .. } = req;
268 let params = Params::new(params.as_ref().map(|params| params.as_ref().get()));
269 let max_response_size = usize::MAX;
270 let conn_id = ConnectionId::IN_PROCESS;
271
272 let response = match self.method(&method) {
273 None => MethodResponse::error(id, ErrorObject::from(ErrorCode::MethodNotFound)),
274 Some(MethodCallback::Sync(cb)) => (cb)(id, params, max_response_size),
275 Some(MethodCallback::Async(cb)) => {
276 (cb)(id.into_owned(), params, conn_id, max_response_size).await
277 }
278 Some(MethodCallback::Subscription(cb)) => {
279 let conn_state = SubscriptionState {
280 conn_id,
281 id_provider: &RandomIntegerIdProvider,
282 subscription_permit,
283 };
284 let res = (cb)(id, params, MethodSink::new(tx.clone()), conn_state).await;
285
286 // Accept and reject also queue the response on the sink. Dropping a pending
287 // subscription returns an internal error only through the callback.
288 if res.is_subscription() {
289 rx.recv().await;
290 }
291
292 res
293 }
294 Some(MethodCallback::Unsubscription(cb)) => {
295 (cb)(id, params, conn_id, max_response_size)
296 }
297 };
298
299 let rp = response.buffer().await.into_json();
300 tracing::trace!(target: LOG_TARGET, "[Methods::inner_call] Method: {}, response: {}", method, rp);
301
302 (rp, rx)
303 }
304
305 /// Returns an `Iterator` with all the method names registered on this server.
306 pub fn method_names(&self) -> impl Iterator<Item = &'static str> + '_ {
307 self.callbacks.keys().copied()
308 }
309}
310
311impl<Context> Deref for RpcModule<Context> {
312 type Target = Methods;
313
314 fn deref(&self) -> &Methods {
315 &self.methods
316 }
317}
318
319impl<Context> DerefMut for RpcModule<Context> {
320 fn deref_mut(&mut self) -> &mut Methods {
321 &mut self.methods
322 }
323}
324
325/// Sets of JSON-RPC methods can be organized into "module"s that are in turn registered on the
326/// server or, alternatively, merged with other modules to construct a cohesive API. [`RpcModule`]
327/// wraps an additional context argument that can be used to access data during call execution.
328#[derive(Debug, Clone)]
329pub struct RpcModule<Context> {
330 ctx: Arc<Context>,
331 methods: Methods,
332}
333
334impl<Context> RpcModule<Context> {
335 /// Create a new module with a given shared `Context`.
336 pub fn new(ctx: Context) -> Self {
337 Self::from_arc(Arc::new(ctx))
338 }
339
340 /// Create a new module from an already shared `Context`.
341 ///
342 /// This is useful if `Context` needs to be shared outside of an [`RpcModule`].
343 pub fn from_arc(ctx: Arc<Context>) -> Self {
344 Self { ctx, methods: Default::default() }
345 }
346
347 /// Transform a module into an `RpcModule<()>` (unit context).
348 pub fn remove_context(self) -> RpcModule<()> {
349 let mut module = RpcModule::new(());
350 module.methods = self.methods;
351 module
352 }
353}
354
355impl<Context> From<RpcModule<Context>> for Methods {
356 fn from(module: RpcModule<Context>) -> Methods {
357 module.methods
358 }
359}
360
361impl<Context: Send + Sync + 'static> RpcModule<Context> {
362 /// Register a new synchronous RPC method, which computes the response with the given callback.
363 ///
364 /// ## Examples
365 ///
366 /// ```
367 /// use jsonrpsee_core::server::RpcModule;
368 ///
369 /// let mut module = RpcModule::new(());
370 /// module.register_method("say_hello", |_params, _ctx| "lo").unwrap();
371 /// ```
372 pub fn register_method<R, F>(
373 &mut self,
374 method_name: &'static str,
375 callback: F,
376 ) -> Result<&mut MethodCallback, RegisterMethodError>
377 where
378 Context: Send + Sync + 'static,
379 R: IntoResponse + 'static,
380 F: Fn(Params, &Context) -> R + Send + Sync + 'static,
381 {
382 let ctx = self.ctx.clone();
383 let size_hint = ResponseSizeHint::new();
384 self.methods.verify_and_insert(
385 method_name,
386 MethodCallback::Sync(Arc::new(move |id, params, max_response_size| {
387 let rp = callback(params, &*ctx).into_response();
388 MethodResponse::sized_response(id, rp, max_response_size, &size_hint)
389 })),
390 )
391 }
392
393 /// Removes the method if it exists.
394 ///
395 /// Be aware that a subscription consist of two methods, `subscribe` and `unsubscribe` and
396 /// it's the caller responsibility to remove both `subscribe` and `unsubscribe` methods for
397 /// subscriptions.
398 pub fn remove_method(&mut self, method_name: &'static str) -> Option<MethodCallback> {
399 self.methods.mut_callbacks().remove(method_name)
400 }
401
402 /// Register a new asynchronous RPC method, which computes the response with the given callback.
403 ///
404 /// The params are copied for every call, so the callback's future can own them.
405 /// [`register_async_method_raw`](RpcModule::register_async_method_raw) avoids the copy.
406 ///
407 /// ## Examples
408 ///
409 /// ```
410 /// use jsonrpsee_core::server::RpcModule;
411 ///
412 /// let mut module = RpcModule::new(());
413 /// module.register_async_method("say_hello", |_params, _ctx| async { "lo" }).unwrap();
414 /// ```
415 pub fn register_async_method<R, Fun, Fut>(
416 &mut self,
417 method_name: &'static str,
418 callback: Fun,
419 ) -> Result<&mut MethodCallback, RegisterMethodError>
420 where
421 R: IntoResponse + 'static,
422 Fut: Future<Output = R> + Send,
423 Fun: (Fn(Params<'static>, Arc<Context>) -> Fut) + Clone + Send + Sync + 'static,
424 {
425 let ctx = self.ctx.clone();
426 let size_hint = Arc::new(ResponseSizeHint::new());
427 self.methods.verify_and_insert(
428 method_name,
429 MethodCallback::Async(Arc::new(move |id, params, _, max_response_size| {
430 let ctx = ctx.clone();
431 let callback = callback.clone();
432 let size_hint = size_hint.clone();
433 let params = params.into_owned();
434
435 let future = async move {
436 let rp = callback(params, ctx).await.into_response();
437 MethodResponse::sized_response(id, rp, max_response_size, &size_hint)
438 };
439 future.boxed()
440 })),
441 )
442 }
443
444 /// Similar to [`RpcModule::register_async_method`], but the callback only borrows the params:
445 /// it decodes them and returns either the error to respond with, or a closure that starts the
446 /// call once the call's future is polled.
447 ///
448 /// This is more efficient as the params are not copied for the call's future.
449 ///
450 /// The callback runs while [`RpcServiceT::call`](crate::middleware::RpcServiceT::call) builds
451 /// the call's future, so middleware that acts when that future is polled does not cover the
452 /// decoding.
453 ///
454 /// ## Examples
455 ///
456 /// ```
457 /// use jsonrpsee_core::server::RpcModule;
458 ///
459 /// let mut module = RpcModule::new(());
460 /// module
461 /// .register_async_method_raw("add_one", |params, _ctx| {
462 /// let n = params.one::<u64>()?;
463 /// Ok(move || async move { n + 1 })
464 /// })
465 /// .unwrap();
466 /// ```
467 pub fn register_async_method_raw<R, Fun, Call, Fut>(
468 &mut self,
469 method_name: &'static str,
470 callback: Fun,
471 ) -> Result<&mut MethodCallback, RegisterMethodError>
472 where
473 R: IntoResponse + 'static,
474 Fut: Future<Output = R> + Send,
475 Call: FnOnce() -> Fut + Send + 'static,
476 Fun: Fn(Params<'_>, Arc<Context>) -> Result<Call, ErrorObjectOwned> + Send + Sync + 'static,
477 {
478 let ctx = self.ctx.clone();
479 let size_hint = Arc::new(ResponseSizeHint::new());
480 self.methods.verify_and_insert(
481 method_name,
482 MethodCallback::Async(Arc::new(move |id, params, _, max_response_size| {
483 let call = match callback(params, ctx.clone()) {
484 Ok(call) => call,
485 Err(err) => {
486 let rp = ResponsePayload::<()>::error(err);
487 let rp =
488 MethodResponse::sized_response(id, rp, max_response_size, &size_hint);
489 return std::future::ready(rp).boxed();
490 }
491 };
492 let size_hint = size_hint.clone();
493
494 // The call's future is created inside the boxed future, so it is built in place
495 // instead of being moved into the box.
496 let future = async move {
497 let rp = call().await.into_response();
498 MethodResponse::sized_response(id, rp, max_response_size, &size_hint)
499 };
500 future.boxed()
501 })),
502 )
503 }
504
505 /// Register a new asynchronous RPC method whose result is sent in parts while it is produced.
506 ///
507 /// The callback returns a [`ResponseStream`] whose producer the transport polls while it sends
508 /// the response. The first 1 MiB of the result is buffered, so a smaller result is answered as
509 /// a whole. After that, HTTP sends each part as soon as it is produced. WebSocket, IPC,
510 /// in-process calls and batch entries wait for the whole result, see
511 /// [`MethodResponse::buffer`].
512 ///
513 /// The response size limit applies to the whole result. A result that fails or exceeds the
514 /// limit within its first 1 MiB is answered with a JSON-RPC error. Once HTTP has sent a part,
515 /// it aborts the response instead.
516 pub fn register_streaming_method<Fun, Fut>(
517 &mut self,
518 method_name: &'static str,
519 callback: Fun,
520 ) -> Result<&mut MethodCallback, RegisterMethodError>
521 where
522 Fut: Future<Output = Result<ResponseStream, ErrorObjectOwned>> + Send,
523 Fun: (Fn(Params<'static>, Arc<Context>) -> Fut) + Clone + Send + Sync + 'static,
524 {
525 let ctx = self.ctx.clone();
526 self.methods.verify_and_insert(
527 method_name,
528 MethodCallback::Async(Arc::new(move |id, params, _, max_response_size| {
529 let ctx = ctx.clone();
530 let callback = callback.clone();
531 let params = params.into_owned();
532
533 let future = async move {
534 match callback(params, ctx).await {
535 Ok(stream) => MethodResponse::stream(id, stream, max_response_size).await,
536 Err(err) => MethodResponse::bounded_error(id, err, max_response_size),
537 }
538 };
539 future.boxed()
540 })),
541 )
542 }
543
544 /// Register a new **blocking** synchronous RPC method, which computes the response with the
545 /// given callback. Unlike the regular [`register_method`](RpcModule::register_method), this
546 /// method runs on tokio's blocking thread pool, so it can block its thread and perform
547 /// expensive computations.
548 pub fn register_blocking_method<R, F>(
549 &mut self,
550 method_name: &'static str,
551 callback: F,
552 ) -> Result<&mut MethodCallback, RegisterMethodError>
553 where
554 Context: Send + Sync + 'static,
555 R: IntoResponse + 'static,
556 F: Fn(Params<'static>, Arc<Context>) -> R + Clone + Send + Sync + 'static,
557 {
558 let ctx = self.ctx.clone();
559 let size_hint = Arc::new(ResponseSizeHint::new());
560 self.methods.verify_and_insert(
561 method_name,
562 MethodCallback::Async(Arc::new(move |id, params, _, max_response_size| {
563 let ctx = ctx.clone();
564 let callback = callback.clone();
565 let size_hint = size_hint.clone();
566 let error_id = id.clone();
567 let params = params.into_owned();
568
569 tokio::task::spawn_blocking(move || {
570 let rp = callback(params, ctx).into_response();
571 MethodResponse::sized_response(id, rp, max_response_size, &size_hint)
572 })
573 .map(|result| {
574 result.unwrap_or_else(|err| {
575 tracing::error!(target: LOG_TARGET, "Join error for blocking RPC method: {:?}", err);
576 MethodResponse::error(error_id, ErrorObject::from(ErrorCode::InternalError))
577 })
578 })
579 .boxed()
580 })),
581 )
582 }
583
584 /// Register a new publish/subscribe interface using JSON-RPC notifications.
585 ///
586 /// It implements the [ethereum pubsub specification](https://geth.ethereum.org/docs/rpc/pubsub)
587 /// with an option to choose custom subscription ID generation.
588 ///
589 /// Furthermore, it generates the `unsubscribe implementation` where a `bool` is used as
590 /// the result to indicate whether the subscription was successfully unsubscribed to or not.
591 /// For instance an `unsubscribe call` may fail if a non-existent subscription ID is used in the
592 /// call.
593 ///
594 /// This method ensures that the `subscription_method_name` and `unsubscription_method_name` are
595 /// unique. The `notif_method_name` argument sets the content of the `method` field in the
596 /// JSON document that the server sends back to the client. The uniqueness of this value is
597 /// not machine checked and it's up to the user to ensure it is not used in any other
598 /// [`RpcModule`] used in the server.
599 ///
600 /// # Arguments
601 ///
602 /// * `subscription_method_name` - name of the method to call to initiate a subscription
603 /// * `notif_method_name` - name of method to be used in the subscription payload (technically a
604 /// JSON-RPC notification)
605 /// * `unsubscription_method` - name of the method to call to terminate a subscription
606 /// * `callback` - A callback to invoke on each subscription; it takes three parameters:
607 /// - [`Params`]: JSON-RPC parameters in the subscription call.
608 /// - [`PendingSubscriptionSink`]: A pending subscription waiting to be accepted, in order
609 /// to send out messages on the subscription
610 /// - Context: Any type that can be embedded into the [`RpcModule`].
611 ///
612 /// # Returns
613 ///
614 /// An async block which returns something that implements
615 /// [`crate::server::IntoSubscriptionCloseResponse`] which decides what action to take when
616 /// the subscription ends whether such as to sent out another message on the subscription
617 /// stream before closing down it.
618 ///
619 /// NOTE: The return value is ignored if [`PendingSubscriptionSink`] hasn't been called or is
620 /// unsuccessful, as the subscription is not allowed to send out subscription notifications
621 /// before the actual subscription has been established.
622 ///
623 /// This is implemented for `Result<T, E>` and `()`.
624 ///
625 /// It's recommended to use `Result` if you want to propagate the error as special error
626 /// notification Another option is to implement
627 /// [`crate::server::IntoSubscriptionCloseResponse`] if you want customized behaviour.
628 ///
629 /// The error notification has the following format:
630 ///
631 /// ```json
632 /// {
633 /// "jsonrpc": "2.0",
634 /// "method": "<method>",
635 /// "params": {
636 /// "subscription": "<subscriptionID>",
637 /// "error": <your msg>
638 /// }
639 /// }
640 /// }
641 /// ```
642 ///
643 /// # Examples
644 ///
645 /// ```no_run
646 /// use jsonrpsee_core::server::{RpcModule, SubscriptionMessage, SubscriptionSink};
647 /// use jsonrpsee_types::ErrorObjectOwned;
648 ///
649 /// let mut ctx = RpcModule::new(99_usize);
650 /// ctx.register_subscription("sub", "notif_name", "unsub", |params, pending, ctx| async move {
651 /// let x = match params.one::<usize>() {
652 /// Ok(x) => x,
653 /// Err(e) => {
654 /// pending.reject(ErrorObjectOwned::from(e)).await;
655 /// // If the subscription has not been "accepted" then
656 /// // the return value will be "ignored" as it's not
657 /// // allowed to send out any further notifications on
658 /// // on the subscription.
659 /// return Ok(());
660 /// }
661 /// };
662 ///
663 /// // Mark the subscription is accepted after the params has been parsed successful.
664 /// // This is actually responds the underlying RPC method call and may fail if the
665 /// // connection is closed.
666 /// let sink = pending.accept().await?;
667 /// let sum = x + (*ctx);
668 ///
669 /// // This will send out an error notification if it fails.
670 /// //
671 /// // If you need some other behavior implement or custom format of the error field
672 /// // you need to manually handle that.
673 /// let msg = serde_json::value::to_raw_value(&sum).unwrap();
674 ///
675 /// // This fails only if the connection is closed
676 /// sink.send(msg).await?;
677 ///
678 /// Ok(())
679 /// });
680 /// ```
681 pub fn register_subscription<R, F, Fut>(
682 &mut self,
683 subscribe_method_name: &'static str,
684 notif_method_name: &'static str,
685 unsubscribe_method_name: &'static str,
686 callback: F,
687 ) -> Result<&mut MethodCallback, RegisterMethodError>
688 where
689 Context: Send + Sync + 'static,
690 F: (Fn(Params<'static>, PendingSubscriptionSink, Arc<Context>) -> Fut)
691 + Send
692 + Sync
693 + Clone
694 + 'static,
695 Fut: Future<Output = R> + Send + 'static,
696 R: IntoSubscriptionCloseResponse + Send,
697 {
698 let subscribers =
699 self.verify_and_register_unsubscribe(subscribe_method_name, unsubscribe_method_name)?;
700 let ctx = self.ctx.clone();
701
702 // Subscribe
703 let callback = {
704 self.methods.verify_and_insert(
705 subscribe_method_name,
706 MethodCallback::Subscription(Arc::new(move |id, params, method_sink, conn| {
707 let uniq_sub = SubscriptionKey {
708 conn_id: conn.conn_id,
709 sub_id: conn.id_provider.next_id(),
710 };
711
712 // response to the subscription call.
713 let (tx, rx) = oneshot::channel();
714 let (accepted_tx, accepted_rx) = oneshot::channel();
715
716 let sub_id = uniq_sub.sub_id.clone();
717 let method = notif_method_name;
718
719 let sink = PendingSubscriptionSink {
720 inner: method_sink.clone(),
721 method: notif_method_name,
722 subscribers: subscribers.clone(),
723 uniq_sub,
724 id: id.clone().into_owned(),
725 subscribe: tx,
726 permit: conn.subscription_permit,
727 };
728
729 // The subscription callback is a future from the subscription
730 // definition and not the as same when the subscription call has been
731 // completed.
732 //
733 // This runs until the subscription callback has completed.
734 let sub_fut = callback(params.into_owned(), sink, ctx.clone());
735
736 tokio::spawn(async move {
737 // This will wait for the subscription future to be resolved
738 let response = match futures_util::future::try_join(
739 sub_fut.map(|f| Ok(f)),
740 accepted_rx,
741 )
742 .await
743 {
744 Ok((r, _)) => r.into_response(),
745 // The accept call failed i.e, the subscription was not accepted.
746 Err(_) => return,
747 };
748
749 match response {
750 SubscriptionCloseResponse::Notif(msg) => {
751 let json =
752 sub_message_to_json(msg, ¬ification_prefix(method, &sub_id));
753 let _ = method_sink.send(json).await;
754 }
755 SubscriptionCloseResponse::NotifErr(err) => {
756 let json = sub_err_to_json(err, sub_id, method);
757 let _ = method_sink.send(json).await;
758 }
759 SubscriptionCloseResponse::None => (),
760 }
761 });
762
763 let id = id.clone().into_owned();
764
765 Box::pin(async move {
766 match rx.await {
767 Ok(rp) => {
768 // If the subscription was accepted then send a message
769 // to subscription task otherwise rely on the drop impl.
770 if rp.is_success() {
771 let _ = accepted_tx.send(());
772 }
773 rp
774 }
775 Err(_) => MethodResponse::error(id, ErrorCode::InternalError),
776 }
777 })
778 })),
779 )?
780 };
781
782 Ok(callback)
783 }
784
785 /// Similar to [`RpcModule::register_subscription`] but a little lower-level API
786 /// where handling the subscription is managed the user i.e, polling the subscription
787 /// such as spawning a separate task to do so.
788 ///
789 /// This is more efficient as this doesn't require cloning the `params` in the subscription
790 /// and it won't send out a close message. Such things are delegated to the user of this API
791 ///
792 /// # Examples
793 ///
794 /// ```no_run
795 /// use jsonrpsee_core::server::{RpcModule, SubscriptionMessage, SubscriptionSink};
796 /// use jsonrpsee_types::ErrorObjectOwned;
797 ///
798 /// let mut ctx = RpcModule::new(99_usize);
799 /// ctx.register_subscription_raw("sub", "notif_name", "unsub", |params, pending, ctx| {
800 /// // The params are parsed outside the async block below to avoid cloning the bytes.
801 /// let val = match params.one::<usize>() {
802 /// Ok(val) => val,
803 /// Err(e) => {
804 /// // If the subscription has not been "accepted" then
805 /// // the return value will be "ignored" as it's not
806 /// // allowed to send out any further notifications on
807 /// // on the subscription.
808 /// tokio::spawn(pending.reject(ErrorObjectOwned::from(e)));
809 /// return;
810 /// }
811 /// };
812 ///
813 /// tokio::spawn(async move {
814 /// // Mark the subscription is accepted after the params has been parsed successful.
815 /// // This is actually responds the underlying RPC method call and may fail if the
816 /// // connection is closed.
817 /// let sink = pending.accept().await.unwrap();
818 /// let sum = val + (*ctx);
819 ///
820 /// let msg = serde_json::value::to_raw_value(&sum).unwrap();
821 ///
822 /// // This fails only if the connection is closed
823 /// sink.send(msg).await.unwrap();
824 /// });
825 /// });
826 /// ```
827 pub fn register_subscription_raw<R, F>(
828 &mut self,
829 subscribe_method_name: &'static str,
830 notif_method_name: &'static str,
831 unsubscribe_method_name: &'static str,
832 callback: F,
833 ) -> Result<&mut MethodCallback, RegisterMethodError>
834 where
835 Context: Send + Sync + 'static,
836 F: (Fn(Params, PendingSubscriptionSink, Arc<Context>) -> R) + Send + Sync + Clone + 'static,
837 R: IntoSubscriptionCloseResponse,
838 {
839 let subscribers =
840 self.verify_and_register_unsubscribe(subscribe_method_name, unsubscribe_method_name)?;
841 let ctx = self.ctx.clone();
842
843 // Subscribe
844 let callback = {
845 self.methods.verify_and_insert(
846 subscribe_method_name,
847 MethodCallback::Subscription(Arc::new(move |id, params, method_sink, conn| {
848 let uniq_sub = SubscriptionKey {
849 conn_id: conn.conn_id,
850 sub_id: conn.id_provider.next_id(),
851 };
852
853 // response to the subscription call.
854 let (tx, rx) = oneshot::channel();
855
856 let sink = PendingSubscriptionSink {
857 inner: method_sink.clone(),
858 method: notif_method_name,
859 subscribers: subscribers.clone(),
860 uniq_sub,
861 id: id.clone().into_owned(),
862 subscribe: tx,
863 permit: conn.subscription_permit,
864 };
865
866 callback(params, sink, ctx.clone());
867
868 let id = id.clone().into_owned();
869
870 Box::pin(async move {
871 match rx.await {
872 Ok(rp) => rp,
873 Err(_) => MethodResponse::error(id, ErrorCode::InternalError),
874 }
875 })
876 })),
877 )?
878 };
879
880 Ok(callback)
881 }
882
883 /// Helper to verify the subscription can be created
884 /// and register the unsubscribe handler.
885 fn verify_and_register_unsubscribe(
886 &mut self,
887 subscribe_method_name: &'static str,
888 unsubscribe_method_name: &'static str,
889 ) -> Result<Subscribers, RegisterMethodError> {
890 if subscribe_method_name == unsubscribe_method_name {
891 return Err(RegisterMethodError::SubscriptionNameConflict(subscribe_method_name.into()));
892 }
893
894 self.methods.verify_method_name(subscribe_method_name)?;
895 self.methods.verify_method_name(unsubscribe_method_name)?;
896
897 let subscribers = Subscribers::default();
898
899 // Unsubscribe
900 {
901 let subscribers = subscribers.clone();
902 self.methods.mut_callbacks().insert(
903 unsubscribe_method_name,
904 MethodCallback::Unsubscription(Arc::new(move |id, params, conn_id, max_response_size| {
905 let sub_id = match params.one::<RpcSubscriptionId>() {
906 Ok(sub_id) => sub_id,
907 Err(_) => {
908 // The params and request id are client input, so only their size is logged.
909 tracing::debug!(
910 target: LOG_TARGET,
911 "Unsubscribe call `{}` failed: couldn't parse subscription id from {} bytes of params",
912 unsubscribe_method_name,
913 params.len_bytes(),
914 );
915
916 return MethodResponse::response(id, ResponsePayload::success(false), max_response_size);
917 }
918 };
919
920 let key = SubscriptionKey { conn_id, sub_id: sub_id.into_owned() };
921 let mut subs = subscribers.lock();
922 let removed = subs.remove(&key);
923 let result = removed.is_some();
924 // Dropping the entry's receiver marks the sink inactive, which
925 // `SubscriptionSink::drop` checks under the lock, so drop it before unlocking.
926 drop(removed);
927 drop(subs);
928
929 if !result {
930 tracing::debug!(
931 target: LOG_TARGET,
932 "Unsubscribe call `{}` subscription key={:?} not an active subscription",
933 unsubscribe_method_name,
934 key,
935 );
936 }
937
938 MethodResponse::response(id, ResponsePayload::success(result), max_response_size)
939 })),
940 );
941 }
942
943 Ok(subscribers)
944 }
945
946 /// Register an alias for an existing_method. Alias uniqueness is enforced.
947 pub fn register_alias(
948 &mut self,
949 alias: &'static str,
950 existing_method: &'static str,
951 ) -> Result<(), RegisterMethodError> {
952 self.methods.verify_method_name(alias)?;
953
954 let callback = match self.methods.callbacks.get(existing_method) {
955 Some(callback) => callback.clone(),
956 None => return Err(RegisterMethodError::MethodNotFound(existing_method.into())),
957 };
958
959 self.methods.mut_callbacks().insert(alias, callback);
960
961 Ok(())
962 }
963}
964
965fn mock_subscription_permit() -> SubscriptionPermit {
966 BoundedSubscriptions::new(1).acquire().expect("1 permit should exist; qed")
967}