use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use async_trait::async_trait;
use futures_util::stream::{SplitSink, SplitStream};
use futures_util::{SinkExt, Stream, StreamExt};
use serde::de::DeserializeOwned;
use serde_json::{json, Value};
use tokio::net::TcpStream;
use tokio::sync::{mpsc, oneshot, Mutex};
use tokio_tungstenite::tungstenite::Message;
use tokio_tungstenite::{MaybeTlsStream, WebSocketStream};
use crate::error::SdkError;
use crate::provider::json_rpc::{JsonRpcNotification, JsonRpcRequest, JsonRpcResponse};
use crate::provider::transport::Transport;
use crate::provider::RootProvider;
use crate::types::{Address, Event, LogFilter, TxHash};
type WsStream = WebSocketStream<MaybeTlsStream<TcpStream>>;
type WsWrite = SplitSink<WsStream, Message>;
type WsRead = SplitStream<WsStream>;
const SUBSCRIPTION_CHANNEL_DEPTH: usize = 1024;
const MAX_PENDING_NOTIF_BUCKETS: usize = 128;
const MAX_PENDING_NOTIF_DEPTH: usize = 256;
pub struct WsTransport {
inner: Arc<WsInner>,
}
struct WsInner {
write: Mutex<WsWrite>,
pending: Mutex<HashMap<u64, oneshot::Sender<Result<Value, SdkError>>>>,
subscriptions: Mutex<HashMap<String, mpsc::Sender<Value>>>,
pending_notifs: Mutex<HashMap<String, Vec<Value>>>,
next_id: AtomicU64,
}
impl WsTransport {
pub async fn connect(url: &str) -> Result<Self, SdkError> {
let (stream, _resp) = tokio_tungstenite::connect_async(url)
.await
.map_err(|e| SdkError::Connection(format!("ws connect {url}: {e}")))?;
let (write, read) = stream.split();
let inner = Arc::new(WsInner {
write: Mutex::new(write),
pending: Mutex::new(HashMap::new()),
subscriptions: Mutex::new(HashMap::new()),
pending_notifs: Mutex::new(HashMap::new()),
next_id: AtomicU64::new(1),
});
tokio::spawn(read_loop(read, Arc::clone(&inner)));
Ok(Self { inner })
}
async fn send_raw(&self, method: &str, params: Value) -> Result<Value, SdkError> {
let id = self.inner.next_id.fetch_add(1, Ordering::Relaxed);
let req = JsonRpcRequest::new(id, method, params);
let body = serde_json::to_string(&req)
.map_err(|e| SdkError::Other(format!("ws encode request: {e}")))?;
let (tx, rx) = oneshot::channel();
{
let mut pending = self.inner.pending.lock().await;
pending.insert(id, tx);
}
{
let mut write = self.inner.write.lock().await;
write
.send(Message::Text(body))
.await
.map_err(|e| SdkError::Connection(format!("ws send {method}: {e}")))?;
}
rx.await
.map_err(|_| SdkError::Connection("ws connection closed".into()))?
}
async fn register_subscription(&self, sub_id: String, tx: mpsc::Sender<Value>) {
{
let mut subs = self.inner.subscriptions.lock().await;
subs.insert(sub_id.clone(), tx.clone());
}
let buffered = self.inner.pending_notifs.lock().await.remove(&sub_id);
if let Some(notifs) = buffered {
for n in notifs {
let _ = tx.try_send(n);
}
}
}
async fn drop_subscription(&self, sub_id: &str) {
let mut subs = self.inner.subscriptions.lock().await;
subs.remove(sub_id);
}
}
#[async_trait]
impl Transport for WsTransport {
async fn send(&self, method: &str, params: Value) -> Result<Value, SdkError> {
self.send_raw(method, params).await
}
}
impl std::fmt::Debug for WsTransport {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("WsTransport").finish_non_exhaustive()
}
}
async fn read_loop(mut read: WsRead, inner: Arc<WsInner>) {
while let Some(frame) = read.next().await {
let text = match frame {
Ok(Message::Text(t)) => t.to_string(),
Ok(Message::Binary(b)) => String::from_utf8_lossy(&b).to_string(),
Ok(Message::Close(_)) | Err(_) => break,
Ok(Message::Ping(_) | Message::Pong(_) | Message::Frame(_)) => continue,
};
dispatch_frame(&text, &inner).await;
}
let mut pending = inner.pending.lock().await;
for (_, tx) in pending.drain() {
let _ = tx.send(Err(SdkError::Connection("ws connection closed".into())));
}
inner.subscriptions.lock().await.clear();
}
async fn dispatch_frame(text: &str, inner: &Arc<WsInner>) {
if let Ok(notif) = serde_json::from_str::<JsonRpcNotification>(text) {
if notif.method == "pyde_subscription" {
if let Some(sub_id) = notif.params.get("subscription").and_then(Value::as_str) {
let result = notif.params.get("result").cloned().unwrap_or(Value::Null);
let sender = inner.subscriptions.lock().await.get(sub_id).cloned();
match sender {
Some(tx) => {
let _ = tx.try_send(result);
}
None => {
let mut notifs = inner.pending_notifs.lock().await;
let bucket_exists = notifs.contains_key(sub_id);
if bucket_exists || notifs.len() < MAX_PENDING_NOTIF_BUCKETS {
let bucket = notifs.entry(sub_id.to_string()).or_default();
if bucket.len() < MAX_PENDING_NOTIF_DEPTH {
bucket.push(result);
}
}
}
}
}
return;
}
}
if let Ok(resp) = serde_json::from_str::<JsonRpcResponse>(text) {
if let Some(id) = resp.id.as_ref().and_then(Value::as_u64) {
let mut pending = inner.pending.lock().await;
if let Some(sender) = pending.remove(&id) {
let _ = sender.send(resp.into_result());
}
}
}
}
pub struct Subscription<T> {
rx: mpsc::Receiver<Value>,
sub_id: String,
transport: Arc<WsTransport>,
_phantom: std::marker::PhantomData<T>,
}
impl<T: DeserializeOwned> Subscription<T> {
pub async fn recv(&mut self) -> Option<Result<T, SdkError>> {
let v = self.rx.recv().await?;
Some(
serde_json::from_value(v)
.map_err(|e| SdkError::InvalidResponse(format!("subscription event decode: {e}"))),
)
}
#[must_use]
pub fn id(&self) -> &str {
&self.sub_id
}
pub async fn unsubscribe(self) -> Result<(), SdkError> {
let result = self
.transport
.send("pyde_unsubscribe", json!([&self.sub_id]))
.await;
self.transport.drop_subscription(&self.sub_id).await;
result.map(|_| ())
}
pub fn into_stream(self) -> impl Stream<Item = Result<T, SdkError>>
where
T: Unpin,
{
SubscriptionStream {
sub: self,
_phantom: std::marker::PhantomData,
}
}
}
impl<T: DeserializeOwned> std::fmt::Debug for Subscription<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Subscription")
.field("id", &self.sub_id)
.finish()
}
}
struct SubscriptionStream<T> {
sub: Subscription<T>,
_phantom: std::marker::PhantomData<T>,
}
impl<T: DeserializeOwned + Unpin> Stream for SubscriptionStream<T> {
type Item = Result<T, SdkError>;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Self::Item>> {
match self.sub.rx.poll_recv(cx) {
std::task::Poll::Ready(Some(v)) => {
std::task::Poll::Ready(Some(serde_json::from_value(v).map_err(|e| {
SdkError::InvalidResponse(format!("subscription event decode: {e}"))
})))
}
std::task::Poll::Ready(None) => std::task::Poll::Ready(None),
std::task::Poll::Pending => std::task::Poll::Pending,
}
}
}
pub type WsProvider = RootProvider<WsTransport>;
impl WsProvider {
pub async fn connect_ws(url: &str) -> Result<Arc<Self>, SdkError> {
let transport = WsTransport::connect(url).await?;
Ok(Arc::new(Self::new(transport)))
}
pub async fn subscribe_logs(&self, filter: LogFilter) -> Result<Subscription<Event>, SdkError> {
self.subscribe_inner("logs", json!(filter)).await
}
pub async fn subscribe_new_waves(&self) -> Result<Subscription<serde_json::Value>, SdkError> {
Err(unsupported_subscription("newWaves"))
}
pub async fn subscribe_pending_txs(&self) -> Result<Subscription<TxHash>, SdkError> {
Err(unsupported_subscription("pendingTransactions"))
}
pub async fn subscribe_events(
&self,
_contract: Address,
_topic: [u8; 32],
) -> Result<Subscription<Event>, SdkError> {
Err(unsupported_subscription("events"))
}
async fn subscribe_inner<T: DeserializeOwned>(
&self,
kind: &str,
filter: Value,
) -> Result<Subscription<T>, SdkError> {
let v = self
.transport()
.send_raw("pyde_subscribe", json!([kind, filter]))
.await?;
let sub_id = v
.as_str()
.ok_or_else(|| {
SdkError::InvalidResponse(format!(
"pyde_subscribe: expected string sub_id, got {v}"
))
})?
.to_string();
let (tx, rx) = mpsc::channel(SUBSCRIPTION_CHANNEL_DEPTH);
self.transport()
.register_subscription(sub_id.clone(), tx)
.await;
Ok(Subscription {
rx,
sub_id,
transport: Arc::new(self.transport_arc()),
_phantom: std::marker::PhantomData,
})
}
fn transport_arc(&self) -> WsTransport {
WsTransport {
inner: Arc::clone(&self.transport().inner),
}
}
}
fn unsupported_subscription(kind: &str) -> SdkError {
SdkError::Other(format!(
"subscription kind {kind:?} is not yet supported by engine v1 — only \"logs\" \
ships today; this method becomes available when the engine adds it"
))
}