remove duplicate filter types

only use nostrdb::Filter

Signed-off-by: William Casarin <jb55@jb55.com>
This commit is contained in:
William Casarin
2024-08-04 10:40:59 -07:00
parent 8c458f8f78
commit 9328ef2dff
18 changed files with 156 additions and 225 deletions

View File

@@ -1,8 +1,9 @@
use crate::{Filter, Note};
use crate::{Error, Note};
use nostrdb::Filter;
use serde_json::json;
/// Messages sent by clients, received by relays
#[derive(Debug, Eq, PartialEq)]
#[derive(Debug)]
pub enum ClientMessage {
Event {
note: Note,
@@ -34,23 +35,25 @@ impl ClientMessage {
ClientMessage::Close { sub_id }
}
pub fn to_json(&self) -> String {
match self {
pub fn to_json(&self) -> Result<String, Error> {
Ok(match self {
Self::Event { note } => json!(["EVENT", note]).to_string(),
Self::Raw(raw) => raw.clone(),
Self::Req { sub_id, filters } => {
let mut json = json!(["REQ", sub_id]);
let mut filters = json!(filters);
if let Some(json) = json.as_array_mut() {
if let Some(filters) = filters.as_array_mut() {
json.append(filters);
}
if filters.is_empty() {
format!("[\"REQ\",\"{}\",{{ }}]", sub_id)
} else if filters.len() == 1 {
let filters_json_str = filters[0].json()?;
format!("[\"REQ\",\"{}\",{}]", sub_id, filters_json_str)
} else {
let filters_json_str: Result<Vec<String>, Error> = filters
.into_iter()
.map(|f| f.json().map_err(Into::<Error>::into))
.collect();
format!("[\"REQ\",\"{}\",{}]", sub_id, filters_json_str?.join(","))
}
json.to_string()
}
Self::Close { sub_id } => json!(["CLOSE", sub_id]).to_string(),
}
})
}
}

View File

@@ -14,6 +14,7 @@ pub enum Error {
InvalidPublicKey,
// Secp(secp256k1::Error),
Json(serde_json::Error),
Nostrdb(nostrdb::Error),
Generic(String),
}
@@ -29,6 +30,7 @@ impl std::cmp::PartialEq for Error {
// This is slightly wrong but whatevs
(Error::Json(..), Error::Json(..)) => true,
(Error::Generic(left), Error::Generic(right)) => left == right,
(Error::Nostrdb(left), Error::Nostrdb(right)) => left == right,
//(Error::Secp(left), Error::Secp(right)) => left == right,
_ => false,
}
@@ -47,6 +49,7 @@ impl fmt::Display for Error {
Self::InvalidPublicKey => write!(f, "invalid public key"),
//Self::Secp(e) => write!(f, "{e}"),
Self::Json(e) => write!(f, "{e}"),
Self::Nostrdb(e) => write!(f, "{e}"),
Self::Generic(e) => write!(f, "{e}"),
}
}
@@ -85,3 +88,9 @@ impl From<serde_json::Error> for Error {
Error::Json(e)
}
}
impl From<nostrdb::Error> for Error {
fn from(e: nostrdb::Error) -> Self {
Error::Nostrdb(e)
}
}

View File

@@ -1,91 +1 @@
use crate::{NoteId, Pubkey};
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone)]
pub struct Filter {
#[serde(skip_serializing_if = "Option::is_none")]
pub ids: Option<Vec<NoteId>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub authors: Option<Vec<Pubkey>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub kinds: Option<Vec<u64>>,
#[serde(rename = "#e")]
#[serde(skip_serializing_if = "Option::is_none")]
pub events: Option<Vec<NoteId>>,
#[serde(rename = "#p")]
#[serde(skip_serializing_if = "Option::is_none")]
pub pubkeys: Option<Vec<Pubkey>>,
#[serde(rename = "#t")]
#[serde(skip_serializing_if = "Option::is_none")]
pub hashtags: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub since: Option<u64>, // unix timestamp seconds
#[serde(skip_serializing_if = "Option::is_none")]
pub until: Option<u64>, // unix timestamp seconds
#[serde(skip_serializing_if = "Option::is_none")]
pub limit: Option<u16>,
}
impl Filter {
pub fn new() -> Filter {
Filter {
ids: None,
authors: None,
kinds: None,
events: None,
pubkeys: None,
hashtags: None,
since: None,
until: None,
limit: None,
}
}
pub fn default_limit() -> u16 {
250
}
pub fn default_remote_limit() -> u16 {
150
}
pub fn ids(mut self, ids: Vec<NoteId>) -> Self {
self.ids = Some(ids);
self
}
pub fn authors(mut self, authors: Vec<Pubkey>) -> Self {
self.authors = Some(authors);
self
}
pub fn kinds(mut self, kinds: Vec<u64>) -> Self {
self.kinds = Some(kinds);
self
}
pub fn events(mut self, events: Vec<NoteId>) -> Self {
self.events = Some(events);
self
}
pub fn pubkeys(mut self, pubkeys: Vec<Pubkey>) -> Self {
self.pubkeys = Some(pubkeys);
self
}
pub fn since(mut self, since: u64) -> Self {
self.since = Some(since);
self
}
pub fn until(mut self, until: u64) -> Self {
self.until = Some(until);
self
}
pub fn limit(mut self, limit: u16) -> Self {
self.limit = Some(limit);
self
}
}
pub type Filter = nostrdb::Filter;

View File

@@ -1,9 +1,9 @@
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use crate::Error;
use log::debug;
use nostr::bech32::Hrp;
use std::fmt;
use tracing::debug;
#[derive(Debug, Eq, PartialEq, Clone, Hash)]
pub struct Pubkey([u8; 32]);

View File

@@ -161,7 +161,7 @@ mod tests {
#[test]
fn test_handle_valid_event() -> Result<()> {
use log::debug;
use tracing::debug;
env_logger::init();
let valid_event_msg = r#"["EVENT", "random_string", {"id":"70b10f70c1318967eddf12527799411b1a9780ad9c43858f5e5fcd45486a13a5","pubkey":"379e863e8357163b5bce5d2688dc4f1dcc2d505222fb8d74db600f30535dfdfe","created_at":1612809991,"kind":1,"tags":[],"content":"test","sig":"273a9cd5d11455590f4359500bccb7a89428262b96b3ea87a756b770964472f8c3e87f5d5e64d8d2e859a71462a3f477b554565c4f2f326cb01dd7620db71502"}]"#;

View File

@@ -1,9 +1,10 @@
use ewebsock::{WsMessage, WsReceiver, WsSender};
use crate::{ClientMessage, Filter, Result};
use log::info;
use crate::{ClientMessage, Result};
use nostrdb::Filter;
use std::fmt;
use std::hash::{Hash, Hasher};
use tracing::{debug, error, info};
pub mod message;
pub mod pool;
@@ -60,7 +61,18 @@ impl Relay {
}
pub fn send(&mut self, msg: &ClientMessage) {
let txt = WsMessage::Text(msg.to_json());
let json = match msg.to_json() {
Ok(json) => {
debug!("sending {} to {}", json, self.url);
json
}
Err(e) => {
error!("error serializing json for filter: {e}");
return;
}
};
let txt = WsMessage::Text(json);
self.sender.send(txt);
}

View File

@@ -1,5 +1,6 @@
use crate::relay::{Relay, RelayStatus};
use crate::{ClientMessage, Result};
use nostrdb::Filter;
use std::time::{Duration, Instant};
@@ -71,6 +72,12 @@ impl RelayPool {
}
}
pub fn subscribe(&mut self, subid: String, filter: Vec<Filter>) {
for relay in &mut self.relays {
relay.relay.subscribe(subid.clone(), filter.clone());
}
}
/// Keep relay connectiongs alive by pinging relays that haven't been
/// pinged in awhile. Adjust ping rate with [`ping_rate`].
pub fn keepalive_ping(&mut self, wakeup: impl Fn() + Send + Sync + Clone + 'static) {