use super::{OfflineClient, OfflineClientT};
use crate::{
blocks::BlocksClient,
constants::ConstantsClient,
error::Error,
events::EventsClient,
rpc::{
types::{RuntimeVersion, Subscription},
Rpc, RpcClientT,
},
runtime_api::RuntimeApiClient,
storage::StorageClient,
tx::TxClient,
Config, Metadata,
};
use derivative::Derivative;
use futures::future;
use std::sync::{Arc, RwLock};
pub trait OnlineClientT<T: Config>: OfflineClientT<T> {
fn rpc(&self) -> &Rpc<T>;
}
#[derive(Derivative)]
#[derivative(Clone(bound = ""))]
pub struct OnlineClient<T: Config> {
inner: Arc<RwLock<Inner<T>>>,
rpc: Rpc<T>,
}
#[derive(Derivative)]
#[derivative(Debug(bound = ""))]
struct Inner<T: Config> {
genesis_hash: T::Hash,
runtime_version: RuntimeVersion,
metadata: Metadata,
}
impl<T: Config> std::fmt::Debug for OnlineClient<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Client")
.field("rpc", &"RpcClient")
.field("inner", &self.inner)
.finish()
}
}
#[cfg(any(
feature = "jsonrpsee-ws",
all(feature = "jsonrpsee-web", target_arch = "wasm32")
))]
pub async fn default_rpc_client<U: AsRef<str>>(url: U) -> Result<impl RpcClientT, Error> {
let client = jsonrpsee_helpers::client(url.as_ref())
.await
.map_err(|e| crate::error::RpcError::ClientError(Box::new(e)))?;
Ok(client)
}
#[cfg(any(
feature = "jsonrpsee-ws",
all(feature = "jsonrpsee-web", target_arch = "wasm32")
))]
impl<T: Config> OnlineClient<T> {
pub async fn new() -> Result<OnlineClient<T>, Error> {
let url = "ws://127.0.0.1:9944";
OnlineClient::from_url(url).await
}
pub async fn from_url(url: impl AsRef<str>) -> Result<OnlineClient<T>, Error> {
let client = default_rpc_client(url).await?;
OnlineClient::from_rpc_client(Arc::new(client)).await
}
}
impl<T: Config> OnlineClient<T> {
pub async fn from_rpc_client<R: RpcClientT>(
rpc_client: Arc<R>,
) -> Result<OnlineClient<T>, Error> {
let rpc = Rpc::<T>::new(rpc_client.clone());
let (genesis_hash, runtime_version, metadata) = future::join3(
rpc.genesis_hash(),
rpc.runtime_version(None),
OnlineClient::fetch_metadata(&rpc),
)
.await;
OnlineClient::from_rpc_client_with(genesis_hash?, runtime_version?, metadata?, rpc_client)
}
pub fn from_rpc_client_with<R: RpcClientT>(
genesis_hash: T::Hash,
runtime_version: RuntimeVersion,
metadata: impl Into<Metadata>,
rpc_client: Arc<R>,
) -> Result<OnlineClient<T>, Error> {
Ok(OnlineClient {
inner: Arc::new(RwLock::new(Inner {
genesis_hash,
runtime_version,
metadata: metadata.into(),
})),
rpc: Rpc::new(rpc_client),
})
}
async fn fetch_metadata(rpc: &Rpc<T>) -> Result<Metadata, Error> {
#[cfg(feature = "unstable-metadata")]
{
const V15_METADATA_VERSION: u32 = u32::MAX;
match rpc.metadata_at_version(V15_METADATA_VERSION).await {
Ok(bytes) => Ok(bytes),
Err(_) => rpc.metadata().await,
}
}
#[cfg(not(feature = "unstable-metadata"))]
rpc.metadata().await
}
pub fn updater(&self) -> ClientRuntimeUpdater<T> {
ClientRuntimeUpdater(self.clone())
}
pub fn metadata(&self) -> Metadata {
let inner = self.inner.read().expect("shouldn't be poisoned");
inner.metadata.clone()
}
pub fn set_metadata(&self, metadata: impl Into<Metadata>) {
let mut inner = self.inner.write().expect("shouldn't be poisoned");
inner.metadata = metadata.into();
}
pub fn genesis_hash(&self) -> T::Hash {
let inner = self.inner.read().expect("shouldn't be poisoned");
inner.genesis_hash
}
pub fn set_genesis_hash(&self, genesis_hash: T::Hash) {
let mut inner = self.inner.write().expect("shouldn't be poisoned");
inner.genesis_hash = genesis_hash;
}
pub fn runtime_version(&self) -> RuntimeVersion {
let inner = self.inner.read().expect("shouldn't be poisoned");
inner.runtime_version.clone()
}
pub fn set_runtime_version(&self, runtime_version: RuntimeVersion) {
let mut inner = self.inner.write().expect("shouldn't be poisoned");
inner.runtime_version = runtime_version;
}
pub fn rpc(&self) -> &Rpc<T> {
&self.rpc
}
pub fn offline(&self) -> OfflineClient<T> {
let inner = self.inner.read().expect("shouldn't be poisoned");
OfflineClient::new(
inner.genesis_hash,
inner.runtime_version.clone(),
inner.metadata.clone(),
)
}
pub fn tx(&self) -> TxClient<T, Self> {
<Self as OfflineClientT<T>>::tx(self)
}
pub fn events(&self) -> EventsClient<T, Self> {
<Self as OfflineClientT<T>>::events(self)
}
pub fn storage(&self) -> StorageClient<T, Self> {
<Self as OfflineClientT<T>>::storage(self)
}
pub fn constants(&self) -> ConstantsClient<T, Self> {
<Self as OfflineClientT<T>>::constants(self)
}
pub fn blocks(&self) -> BlocksClient<T, Self> {
<Self as OfflineClientT<T>>::blocks(self)
}
pub fn runtime_api(&self) -> RuntimeApiClient<T, Self> {
<Self as OfflineClientT<T>>::runtime_api(self)
}
}
impl<T: Config> OfflineClientT<T> for OnlineClient<T> {
fn metadata(&self) -> Metadata {
self.metadata()
}
fn genesis_hash(&self) -> T::Hash {
self.genesis_hash()
}
fn runtime_version(&self) -> RuntimeVersion {
self.runtime_version()
}
}
impl<T: Config> OnlineClientT<T> for OnlineClient<T> {
fn rpc(&self) -> &Rpc<T> {
&self.rpc
}
}
pub struct ClientRuntimeUpdater<T: Config>(OnlineClient<T>);
impl<T: Config> ClientRuntimeUpdater<T> {
fn is_runtime_version_different(&self, new: &RuntimeVersion) -> bool {
let curr = self.0.inner.read().expect("shouldn't be poisoned");
&curr.runtime_version != new
}
fn do_update(&self, update: Update) {
let mut writable = self.0.inner.write().expect("shouldn't be poisoned");
writable.metadata = update.metadata;
writable.runtime_version = update.runtime_version;
}
pub fn apply_update(&self, update: Update) -> Result<(), UpgradeError> {
if !self.is_runtime_version_different(&update.runtime_version) {
return Err(UpgradeError::SameVersion);
}
self.do_update(update);
Ok(())
}
pub async fn perform_runtime_updates(&self) -> Result<(), Error> {
let mut runtime_version_stream = self.runtime_updates().await?;
while let Some(update) = runtime_version_stream.next().await {
let update = update?;
let _ = self.apply_update(update);
}
Ok(())
}
pub async fn runtime_updates(&self) -> Result<RuntimeUpdaterStream<T>, Error> {
let stream = self.0.rpc().subscribe_runtime_version().await?;
Ok(RuntimeUpdaterStream {
stream,
client: self.0.clone(),
})
}
}
pub struct RuntimeUpdaterStream<T: Config> {
stream: Subscription<RuntimeVersion>,
client: OnlineClient<T>,
}
impl<T: Config> RuntimeUpdaterStream<T> {
pub async fn next(&mut self) -> Option<Result<Update, Error>> {
let maybe_runtime_version = self.stream.next().await?;
let runtime_version = match maybe_runtime_version {
Ok(runtime_version) => runtime_version,
Err(err) => return Some(Err(err)),
};
let metadata = match self.client.rpc().metadata().await {
Ok(metadata) => metadata,
Err(err) => return Some(Err(err)),
};
Some(Ok(Update {
metadata,
runtime_version,
}))
}
}
#[non_exhaustive]
#[derive(Debug, Clone)]
pub enum UpgradeError {
SameVersion,
}
pub struct Update {
runtime_version: RuntimeVersion,
metadata: Metadata,
}
impl Update {
pub fn runtime_version(&self) -> &RuntimeVersion {
&self.runtime_version
}
pub fn metadata(&self) -> &Metadata {
&self.metadata
}
}
#[cfg(feature = "jsonrpsee-ws")]
mod jsonrpsee_helpers {
pub use jsonrpsee::{
client_transport::ws::{InvalidUri, Receiver, Sender, Uri, WsTransportClientBuilder},
core::{
client::{Client, ClientBuilder},
Error,
},
};
pub async fn client(url: &str) -> Result<Client, Error> {
let (sender, receiver) = ws_transport(url).await?;
Ok(ClientBuilder::default()
.max_notifs_per_subscription(4096)
.build_with_tokio(sender, receiver))
}
async fn ws_transport(url: &str) -> Result<(Sender, Receiver), Error> {
let url: Uri = url
.parse()
.map_err(|e: InvalidUri| Error::Transport(e.into()))?;
WsTransportClientBuilder::default()
.build(url)
.await
.map_err(|e| Error::Transport(e.into()))
}
}
#[cfg(all(feature = "jsonrpsee-web", target_arch = "wasm32"))]
mod jsonrpsee_helpers {
pub use jsonrpsee::{
client_transport::web,
core::{
client::{Client, ClientBuilder},
Error,
},
};
pub async fn client(url: &str) -> Result<Client, Error> {
let (sender, receiver) = web::connect(url).await.unwrap();
Ok(ClientBuilder::default()
.max_notifs_per_subscription(4096)
.build_with_wasm(sender, receiver))
}
}