|
@@ -7,7 +7,10 @@ use nostr_rs_types::{
|
|
|
};
|
|
|
use parking_lot::{RwLock, RwLockReadGuard};
|
|
|
use std::{collections::HashMap, ops::Deref};
|
|
|
-use tokio::{net::TcpStream, sync::mpsc::Sender};
|
|
|
+use tokio::{
|
|
|
+ net::TcpStream,
|
|
|
+ sync::mpsc::{channel, Receiver, Sender},
|
|
|
+};
|
|
|
|
|
|
#[derive(Clone, Debug, Default, Eq, PartialEq, Hash)]
|
|
|
pub struct SubscriptionType {
|
|
@@ -22,38 +25,48 @@ pub struct Relayer {
|
|
|
storage: RocksDb,
|
|
|
subscriptions: RwLock<HashMap<SubscriptionType, RwLock<Subscriptions>>>,
|
|
|
clients: RwLock<HashMap<u128, Connection>>,
|
|
|
+ receiver: Receiver<(u128, Request)>,
|
|
|
+ sender: Sender<(u128, Request)>,
|
|
|
}
|
|
|
|
|
|
impl Relayer {
|
|
|
pub fn new(storage: RocksDb) -> Self {
|
|
|
+ let (sender, receiver) = channel(100_000);
|
|
|
Self {
|
|
|
storage,
|
|
|
subscriptions: RwLock::new(HashMap::new()),
|
|
|
clients: RwLock::new(HashMap::new()),
|
|
|
+ receiver,
|
|
|
+ sender,
|
|
|
}
|
|
|
}
|
|
|
|
|
|
pub async fn add_connection(&self, stream: TcpStream) -> Result<(), Error> {
|
|
|
- let client = Connection::new(stream).await?;
|
|
|
+ let client = Connection::new(self.sender.clone(), stream).await?;
|
|
|
let mut clients = self.clients.write();
|
|
|
clients.insert(client.conn_id, client);
|
|
|
|
|
|
Ok(())
|
|
|
}
|
|
|
|
|
|
- pub async fn recv(&self, conn_id: u128, request: Request) -> Result<(), Error> {
|
|
|
- let connections = self.clients.read();
|
|
|
+ pub async fn recv(&mut self) -> Result<Option<Request>, Error> {
|
|
|
+ let (conn_id, request) = if let Some(request) = self.receiver.recv().await {
|
|
|
+ request
|
|
|
+ } else {
|
|
|
+ return Ok(None);
|
|
|
+ };
|
|
|
|
|
|
+ let connections = self.clients.read();
|
|
|
let connection = connections
|
|
|
.get(&conn_id)
|
|
|
.ok_or(Error::UnknownConnection(conn_id))?;
|
|
|
|
|
|
- match request {
|
|
|
+ match &request {
|
|
|
Request::Event(event) => {
|
|
|
self.store_and_broadcast(event.deref());
|
|
|
}
|
|
|
Request::Request(request) => {
|
|
|
- for filter in request.filters.into_iter() {
|
|
|
+ for filter in request.filters.clone().into_iter() {
|
|
|
// Create subscription
|
|
|
let (conn_id, sub_id, receiver) =
|
|
|
connection.create_connection(request.subscription_id.deref().to_owned())?;
|
|
@@ -85,10 +98,13 @@ impl Relayer {
|
|
|
);
|
|
|
});
|
|
|
}
|
|
|
+ let _ = connection
|
|
|
+ .send(relayer::EndOfStoredEvents(request.subscription_id.clone()).into());
|
|
|
}
|
|
|
Request::Close(_close) => {}
|
|
|
};
|
|
|
- Ok(())
|
|
|
+
|
|
|
+ Ok(Some(request))
|
|
|
}
|
|
|
|
|
|
#[inline]
|