nostr-rs-relay/src/conn.rs

120 lines
3.6 KiB
Rust
Raw Permalink Normal View History

2021-12-11 22:43:41 -05:00
//! Client connection state
use crate::close::Close;
use crate::error::Error;
use crate::error::Result;
use crate::subscription::Subscription;
use std::collections::HashMap;
use tracing::{debug, trace};
use uuid::Uuid;
2021-12-11 22:43:41 -05:00
/// A subscription identifier has a maximum length
const MAX_SUBSCRIPTION_ID_LEN: usize = 256;
2021-12-11 22:43:41 -05:00
/// State for a client connection
pub struct ClientConn {
2022-11-02 19:33:44 -04:00
/// Client IP (either from socket, or configured proxy header
client_ip_addr: String,
2021-12-11 22:43:41 -05:00
/// Unique client identifier generated at connection time
client_id: Uuid,
2021-12-11 22:43:41 -05:00
/// The current set of active client subscriptions
subscriptions: HashMap<String, Subscription>,
2021-12-11 22:43:41 -05:00
/// Per-connection maximum concurrent subscriptions
max_subs: usize,
}
2021-12-11 22:56:52 -05:00
impl Default for ClientConn {
fn default() -> Self {
2022-11-02 19:33:44 -04:00
Self::new("unknown".to_owned())
2021-12-11 22:56:52 -05:00
}
}
impl ClientConn {
2021-12-11 22:43:41 -05:00
/// Create a new, empty connection state.
2022-09-24 10:01:09 -04:00
#[must_use]
pub fn new(client_ip_addr: String) -> Self {
let client_id = Uuid::new_v4();
ClientConn {
client_ip_addr,
2021-12-11 22:43:41 -05:00
client_id,
subscriptions: HashMap::new(),
max_subs: 32,
}
}
#[must_use] pub fn subscriptions(&self) -> &HashMap<String, Subscription> {
&self.subscriptions
}
/// Check if the given subscription already exists
#[must_use] pub fn has_subscription(&self, sub: &Subscription) -> bool {
self.subscriptions.values().any(|x| x == sub)
}
2021-12-11 22:43:41 -05:00
/// Get a short prefix of the client's unique identifier, suitable
/// for logging.
2022-09-24 10:01:09 -04:00
#[must_use]
pub fn get_client_prefix(&self) -> String {
self.client_id.to_string().chars().take(8).collect()
}
2022-11-02 19:33:44 -04:00
#[must_use]
pub fn ip(&self) -> &str {
&self.client_ip_addr
2022-11-02 19:33:44 -04:00
}
2021-12-11 22:43:41 -05:00
/// Add a new subscription for this connection.
2022-09-24 10:19:16 -04:00
/// # Errors
///
/// Will return `Err` if the client has too many subscriptions, or
/// if the provided name is excessively long.
pub fn subscribe(&mut self, s: Subscription) -> Result<()> {
let k = s.get_id();
let sub_id_len = k.len();
2021-12-11 22:43:41 -05:00
// prevent arbitrarily long subscription identifiers from
// being used.
if sub_id_len > MAX_SUBSCRIPTION_ID_LEN {
debug!(
2021-12-12 11:03:28 -05:00
"ignoring sub request with excessive length: ({})",
sub_id_len
);
return Err(Error::SubIdMaxLengthError);
}
// check if an existing subscription exists, and replace if so
if self.subscriptions.contains_key(&k) {
self.subscriptions.remove(&k);
self.subscriptions.insert(k, s.clone());
trace!(
"replaced existing subscription (cid: {}, sub: {:?})",
self.get_client_prefix(),
s.get_id()
);
return Ok(());
}
// check if there is room for another subscription.
if self.subscriptions.len() >= self.max_subs {
return Err(Error::SubMaxExceededError);
}
// add subscription
self.subscriptions.insert(k, s);
trace!(
"registered new subscription, currently have {} active subs (cid: {})",
self.subscriptions.len(),
self.get_client_prefix(),
);
2021-12-11 22:56:52 -05:00
Ok(())
}
2021-12-11 22:43:41 -05:00
/// Remove the subscription for this connection.
2022-09-24 10:19:16 -04:00
pub fn unsubscribe(&mut self, c: &Close) {
// TODO: return notice if subscription did not exist.
2021-12-11 22:43:41 -05:00
self.subscriptions.remove(&c.id);
trace!(
"removed subscription, currently have {} active subs (cid: {})",
self.subscriptions.len(),
self.get_client_prefix(),
);
}
}