referrerpolicy=no-referrer-when-downgrade
parachain_template_node::rpc

Type Alias RpcExtension

Source
pub type RpcExtension = RpcModule<()>;
Expand description

A type representing all RPC extensions.

Aliased Type§

struct RpcExtension { /* private fields */ }

Implementations

§

impl<Context> RpcModule<Context>

pub fn new(ctx: Context) -> RpcModule<Context>

Create a new module with a given shared Context.

pub fn from_arc(ctx: Arc<Context>) -> RpcModule<Context>

Create a new module from an already shared Context.

This is useful if Context needs to be shared outside of an [RpcModule].

pub fn remove_context(self) -> RpcModule<()>

Transform a module into an RpcModule<()> (unit context).

§

impl<Context> RpcModule<Context>
where Context: Send + Sync + 'static,

pub fn register_method<R, F>( &mut self, method_name: &'static str, callback: F, ) -> Result<&mut MethodCallback, RegisterMethodError>
where Context: Send + Sync + 'static, R: IntoResponse + 'static, F: Fn(Params<'_>, &Context, &Extensions) -> R + Send + Sync + 'static,

Register a new synchronous RPC method, which computes the response with the given callback.

§Examples
use jsonrpsee_core::server::RpcModule;

let mut module = RpcModule::new(());
module.register_method("say_hello", |_params, _ctx, _| "lo").unwrap();

pub fn remove_method( &mut self, method_name: &'static str, ) -> Option<MethodCallback>

Removes the method if it exists.

Be aware that a subscription consist of two methods, subscribe and unsubscribe and it’s the caller responsibility to remove both subscribe and unsubscribe methods for subscriptions.

pub fn register_async_method<R, Fun, Fut>( &mut self, method_name: &'static str, callback: Fun, ) -> Result<&mut MethodCallback, RegisterMethodError>
where R: IntoResponse + 'static, Fut: Future<Output = R> + Send, Fun: Fn(Params<'static>, Arc<Context>, Extensions) -> Fut + Clone + Send + Sync + 'static,

Register a new asynchronous RPC method, which computes the response with the given callback.

§Examples
use jsonrpsee_core::server::RpcModule;

let mut module = RpcModule::new(());
module.register_async_method("say_hello", |_params, _ctx, _| async { "lo" }).unwrap();

pub fn register_blocking_method<R, F>( &mut self, method_name: &'static str, callback: F, ) -> Result<&mut MethodCallback, RegisterMethodError>
where Context: Send + Sync + 'static, R: IntoResponse + 'static, F: Fn(Params<'_>, Arc<Context>, Extensions) -> R + Clone + Send + Sync + 'static,

Register a new blocking synchronous RPC method, which computes the response with the given callback. Unlike the regular register_method, this method can block its thread and perform expensive computations.

pub fn register_subscription<R, F, Fut>( &mut self, subscribe_method_name: &'static str, notif_method_name: &'static str, unsubscribe_method_name: &'static str, callback: F, ) -> Result<&mut MethodCallback, RegisterMethodError>
where Context: Send + Sync + 'static, F: Fn(Params<'static>, PendingSubscriptionSink, Arc<Context>, Extensions) -> Fut + Send + Sync + Clone + 'static, Fut: Future<Output = R> + Send + 'static, R: IntoSubscriptionCloseResponse + Send,

Register a new publish/subscribe interface using JSON-RPC notifications.

It implements the ethereum pubsub specification with an option to choose custom subscription ID generation.

Furthermore, it generates the unsubscribe implementation where a bool is used as the result to indicate whether the subscription was successfully unsubscribed to or not. For instance an unsubscribe call may fail if a non-existent subscription ID is used in the call.

This method ensures that the subscription_method_name and unsubscription_method_name are unique. The notif_method_name argument sets the content of the method field in the JSON document that the server sends back to the client. The uniqueness of this value is not machine checked and it’s up to the user to ensure it is not used in any other [RpcModule] used in the server.

§Arguments
  • subscription_method_name - name of the method to call to initiate a subscription
  • notif_method_name - name of method to be used in the subscription payload (technically a JSON-RPC notification)
  • unsubscription_method - name of the method to call to terminate a subscription
  • callback - A callback to invoke on each subscription; it takes three parameters:
    • [Params]: JSON-RPC parameters in the subscription call.
    • [PendingSubscriptionSink]: A pending subscription waiting to be accepted, in order to send out messages on the subscription
    • Context: Any type that can be embedded into the [RpcModule].
§Returns

An async block which returns something that implements [crate::server::IntoSubscriptionCloseResponse] which decides what action to take when the subscription ends whether such as to sent out another message on the subscription stream before closing down it.

NOTE: The return value is ignored if [PendingSubscriptionSink] hasn’t been called or is unsuccessful, as the subscription is not allowed to send out subscription notifications before the actual subscription has been established.

This is implemented for Result<T, E> and ().

It’s recommended to use Result if you want to propagate the error as special error notification Another option is to implement [crate::server::IntoSubscriptionCloseResponse] if you want customized behaviour.

The error notification has the following format:

{
 "jsonrpc": "2.0",
 "method": "<method>",
 "params": {
   "subscription": "<subscriptionID>",
   "error": <your msg>
   }
 }
}
§Examples

use jsonrpsee_core::server::{RpcModule, SubscriptionSink, SubscriptionMessage};
use jsonrpsee_types::ErrorObjectOwned;

let mut ctx = RpcModule::new(99_usize);
ctx.register_subscription("sub", "notif_name", "unsub", |params, pending, ctx, _| async move {

    let x = match params.one::<usize>() {
        Ok(x) => x,
        Err(e) => {
           pending.reject(ErrorObjectOwned::from(e)).await;
           // If the subscription has not been "accepted" then
           // the return value will be "ignored" as it's not
           // allowed to send out any further notifications on
           // on the subscription.
           return Ok(());
        }
    };

    // Mark the subscription is accepted after the params has been parsed successful.
    // This is actually responds the underlying RPC method call and may fail if the
    // connection is closed.
    let sink = pending.accept().await?;
    let sum = x + (*ctx);

    // This will send out an error notification if it fails.
    //
    // If you need some other behavior implement or custom format of the error field
    // you need to manually handle that.
    let msg = SubscriptionMessage::from_json(&sum)?;

    // This fails only if the connection is closed
    sink.send(msg).await?;

    Ok(())
});

pub fn register_subscription_raw<R, F>( &mut self, subscribe_method_name: &'static str, notif_method_name: &'static str, unsubscribe_method_name: &'static str, callback: F, ) -> Result<&mut MethodCallback, RegisterMethodError>
where Context: Send + Sync + 'static, F: Fn(Params<'_>, PendingSubscriptionSink, Arc<Context>, &Extensions) -> R + Send + Sync + Clone + 'static, R: IntoSubscriptionCloseResponse,

Similar to [RpcModule::register_subscription] but a little lower-level API where handling the subscription is managed the user i.e, polling the subscription such as spawning a separate task to do so.

This is more efficient as this doesn’t require cloning the params in the subscription and it won’t send out a close message. Such things are delegated to the user of this API

§Examples

use jsonrpsee_core::server::{RpcModule, SubscriptionSink, SubscriptionMessage};
use jsonrpsee_types::ErrorObjectOwned;

let mut ctx = RpcModule::new(99_usize);
ctx.register_subscription_raw("sub", "notif_name", "unsub", |params, pending, ctx, _| {

    // The params are parsed outside the async block below to avoid cloning the bytes.
    let val = match params.one::<usize>() {
        Ok(val) => val,
        Err(e) => {
            // If the subscription has not been "accepted" then
            // the return value will be "ignored" as it's not
            // allowed to send out any further notifications on
            // on the subscription.
            tokio::spawn(pending.reject(ErrorObjectOwned::from(e)));
            return;
        }
    };

    tokio::spawn(async move {
        // Mark the subscription is accepted after the params has been parsed successful.
        // This is actually responds the underlying RPC method call and may fail if the
        // connection is closed.
        let sink = pending.accept().await.unwrap();
        let sum = val + (*ctx);

        let msg = SubscriptionMessage::from_json(&sum).unwrap();

        // This fails only if the connection is closed
        sink.send(msg).await.unwrap();
    });
});

pub fn register_alias( &mut self, alias: &'static str, existing_method: &'static str, ) -> Result<(), RegisterMethodError>

Register an alias for an existing_method. Alias uniqueness is enforced.

Trait Implementations

§

impl<Context> Clone for RpcModule<Context>
where Context: Clone,

§

fn clone(&self) -> RpcModule<Context>

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
§

impl<Context> Debug for RpcModule<Context>
where Context: Debug,

§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl<Context> Deref for RpcModule<Context>

§

type Target = Methods

The resulting type after dereferencing.
§

fn deref(&self) -> &Methods

Dereferences the value.
§

impl<Context> DerefMut for RpcModule<Context>

§

fn deref_mut(&mut self) -> &mut Methods

Mutably dereferences the value.