use crate::{JsonRpcClient, Middleware, Provider, TransactionStream};
use ethers_core::types::{TxHash, U256};
use futures_util::stream::Stream;
use pin_project::{pin_project, pinned_drop};
use serde::de::DeserializeOwned;
use serde_json::value::RawValue;
use std::{
collections::VecDeque,
marker::PhantomData,
pin::Pin,
task::{Context, Poll},
};
use tracing::error;
pub trait PubsubClient: JsonRpcClient {
type NotificationStream: futures_core::Stream<Item = Box<RawValue>> + Send + Unpin;
fn subscribe<T: Into<U256>>(&self, id: T) -> Result<Self::NotificationStream, Self::Error>;
fn unsubscribe<T: Into<U256>>(&self, id: T) -> Result<(), Self::Error>;
}
#[must_use = "subscriptions do nothing unless you stream them"]
#[pin_project(PinnedDrop)]
pub struct SubscriptionStream<'a, P: PubsubClient, R: DeserializeOwned> {
pub id: U256,
loaded_elements: VecDeque<R>,
provider: &'a Provider<P>,
#[pin]
rx: P::NotificationStream,
ret: PhantomData<R>,
}
impl<'a, P, R> SubscriptionStream<'a, P, R>
where
P: PubsubClient,
R: DeserializeOwned,
{
pub fn new(id: U256, provider: &'a Provider<P>) -> Result<Self, P::Error> {
let rx = provider.as_ref().subscribe(id)?;
Ok(Self { id, provider, rx, ret: PhantomData, loaded_elements: VecDeque::new() })
}
pub async fn unsubscribe(&self) -> Result<bool, crate::ProviderError> {
self.provider.unsubscribe(self.id).await
}
pub fn set_loaded_elements(&mut self, loaded_elements: VecDeque<R>) {
self.loaded_elements = loaded_elements;
}
}
impl<'a, P, R> Stream for SubscriptionStream<'a, P, R>
where
P: PubsubClient,
R: DeserializeOwned,
{
type Item = R;
fn poll_next(self: Pin<&mut Self>, ctx: &mut Context) -> Poll<Option<Self::Item>> {
if !self.loaded_elements.is_empty() {
let next_element = self.get_mut().loaded_elements.pop_front();
return Poll::Ready(next_element)
}
let this = self.project();
match futures_util::ready!(this.rx.poll_next(ctx)) {
Some(item) => match serde_json::from_str(item.get()) {
Ok(res) => Poll::Ready(Some(res)),
Err(err) => {
error!("failed to deserialize item {:?}", err);
Poll::Pending
}
},
None => Poll::Ready(None),
}
}
}
#[pinned_drop]
impl<P, R> PinnedDrop for SubscriptionStream<'_, P, R>
where
P: PubsubClient,
R: DeserializeOwned,
{
fn drop(self: Pin<&mut Self>) {
let _ = (*self.provider).as_ref().unsubscribe(self.id);
}
}
impl<'a, P> SubscriptionStream<'a, P, TxHash>
where
P: PubsubClient,
{
pub fn transactions_unordered(self, n: usize) -> TransactionStream<'a, P, Self> {
TransactionStream::new(self.provider, self, n)
}
}