nostr-rs-relay/src/proto.rs

146 lines
4.6 KiB
Rust
Raw Normal View History

2021-11-24 16:22:31 -05:00
use crate::close::Close;
2021-11-24 13:25:38 -05:00
use crate::error::{Error, Result};
2021-11-24 16:22:31 -05:00
use crate::event::Event;
use crate::subscription::Subscription;
2021-11-24 13:25:38 -05:00
use log::{debug, info};
2021-11-24 16:28:15 -05:00
use std::collections::HashMap;
2021-11-24 13:25:38 -05:00
use uuid::Uuid;
// A protocol handler/helper. Use one per client.
pub struct Proto {
client_id: Uuid,
2021-11-24 16:22:31 -05:00
// current set of subscriptions
2021-11-24 16:28:15 -05:00
subscriptions: HashMap<String, Subscription>,
max_subs: usize,
2021-11-24 13:25:38 -05:00
}
2021-11-24 16:40:39 -05:00
const MAX_SUBSCRIPTION_ID_LEN: usize = 256;
2021-11-24 13:25:38 -05:00
impl Proto {
pub fn new() -> Self {
let p = Proto {
client_id: Uuid::new_v4(),
2021-11-24 16:28:15 -05:00
subscriptions: HashMap::new(),
max_subs: 128,
2021-11-24 13:25:38 -05:00
};
debug!("New client: {:?}", p.client_id);
p
}
// TODO: figure out NOTICE handling for errors here
pub fn process_message(&mut self, cmd: String) -> Result<()> {
2021-11-24 13:25:38 -05:00
info!(
"Processing message in proto for client: {:?}",
self.client_id
);
let message = parse_cmd(cmd)?;
info!("Parsed message: {:?}", message);
match message {
NostrRequest::EvReq(_) => {}
NostrRequest::SubReq(sub) => self.subscribe(sub),
NostrRequest::CloseReq(close) => self.unsubscribe(close),
};
Ok(())
2021-11-24 13:25:38 -05:00
}
2021-11-24 16:22:31 -05:00
2021-11-24 16:28:15 -05:00
pub fn subscribe(&mut self, s: Subscription) {
2021-11-24 16:40:39 -05:00
// TODO: add NOTICE responses for error conditions. At the
// moment, we are silently dropping subscription requests that
// aren't perfect.
// check if the subscription key is reasonable.
let k = s.get_id();
let sub_id_len = k.len();
if sub_id_len > MAX_SUBSCRIPTION_ID_LEN {
info!("Dropping subscription with huge ({}) length", sub_id_len);
return;
}
// check if an existing subscription exists.
if self.subscriptions.contains_key(&k) {
info!("Client requested a subscription with an already-existing key");
return;
}
// check if there is room for another subscription.
if self.subscriptions.len() >= self.max_subs {
info!("Client has reached the maximum number of unique subscriptions");
return;
}
// add subscription
self.subscriptions.insert(k, s);
info!(
"Registered new subscription, currently have {} active subs",
self.subscriptions.len()
);
2021-11-24 16:22:31 -05:00
}
2021-11-24 16:28:15 -05:00
pub fn unsubscribe(&mut self, c: Close) {
2021-11-24 16:40:39 -05:00
self.subscriptions.remove(&c.get_id());
info!(
"Removed subscription, currently have {} active subs",
self.subscriptions.len()
);
2021-11-24 16:22:31 -05:00
}
2021-11-24 13:25:38 -05:00
}
// A raw message with the expected type
#[derive(PartialEq, Debug)]
pub enum NostrRawMessage {
2021-11-24 16:22:31 -05:00
EvRaw(String),
SubRaw(String),
CloseRaw(String),
2021-11-24 13:25:38 -05:00
}
// A fully parsed request
#[derive(PartialEq, Debug)]
pub enum NostrRequest {
2021-11-24 16:22:31 -05:00
EvReq(Event),
SubReq(Subscription),
CloseReq(Close),
2021-11-24 13:25:38 -05:00
}
// Wrap the message in the expected request type
fn msg_type_wrapper(msg: String) -> Result<NostrRawMessage> {
// check prefix.
if msg.starts_with(r#"["EVENT","#) {
2021-11-24 16:22:31 -05:00
Ok(NostrRawMessage::EvRaw(msg))
2021-11-24 13:25:38 -05:00
} else if msg.starts_with(r#"["REQ","#) {
2021-11-24 16:22:31 -05:00
Ok(NostrRawMessage::SubRaw(msg))
2021-11-24 13:25:38 -05:00
} else if msg.starts_with(r#"["CLOSE","#) {
2021-11-24 16:22:31 -05:00
Ok(NostrRawMessage::CloseRaw(msg))
2021-11-24 13:25:38 -05:00
} else {
Err(Error::CommandNotFound)
}
}
pub fn parse_cmd(msg: String) -> Result<NostrRequest> {
2021-11-24 13:25:38 -05:00
// turn this raw string into a parsed request
let typ = msg_type_wrapper(msg)?;
match typ {
2021-11-24 16:22:31 -05:00
NostrRawMessage::EvRaw(_) => Err(Error::EventParseFailed),
NostrRawMessage::SubRaw(m) => Ok(NostrRequest::SubReq(Subscription::parse(&m)?)),
NostrRawMessage::CloseRaw(m) => Ok(NostrRequest::CloseReq(Close::parse(&m)?)),
2021-11-24 13:25:38 -05:00
}
}
// Parse the request into a fully deserialized type
// The protocol-handling process looks something like:
// Receive a message (bytes).
// Determine the type. We could do this with an untagged deserialization in serde. Or we can peek at the prefix.
// Wrap the message string in the client request type (either Event, Req, Close)
// For Req/Close, we can fully parse these.
// For Event, we want to be more cautious.
// Before we admit an event, we should reject any duplicates.
// duplicates in the datastore will have already been sent out to interested subscribers.
// No point in verifying an event that we already have.
// Event pipeline looks like:
// Get message. (./)
// Verify it is an event. (./)
// Parse into string / number components from JSON.
// Perform validation, re-serialize (or can we re-use the original?)
// Publish to subscribers.
// Push to datastore.