Skip to content

Commit

Permalink
db: add DatabaseOptions
Browse files Browse the repository at this point in the history
  • Loading branch information
yukibtc committed Oct 23, 2023
1 parent 78c2aea commit 05ce732
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 14 deletions.
5 changes: 3 additions & 2 deletions crates/nostr-sdk-db/examples/memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,13 @@ use std::time::{Duration, Instant};

use nostr::{EventBuilder, Filter, Keys, Kind, Metadata, Tag};
use nostr_sdk_db::memory::MemoryDatabase;
use nostr_sdk_db::NostrDatabase;
use nostr_sdk_db::{DatabaseOptions, NostrDatabase};

#[tokio::main]
async fn main() {
let keys = Keys::generate();
let database = MemoryDatabase::new(true);
let opts = DatabaseOptions::default();
let database = MemoryDatabase::new(opts);

for i in 0..50_000 {
let event = EventBuilder::new_text_note(format!("Event #{i}"), &[])
Expand Down
5 changes: 5 additions & 0 deletions crates/nostr-sdk-db/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,10 @@ use nostr::{Event, EventId, Filter, Url};

mod error;
pub mod memory;
mod options;

pub use self::error::DatabaseError;
pub use self::options::DatabaseOptions;

/// Backend
pub enum Backend {
Expand Down Expand Up @@ -44,6 +46,9 @@ pub trait NostrDatabase: AsyncTraitDeps {
/// Name of the backend database used (ex. rocksdb, lmdb, sqlite, indexeddb, ...)
fn backend(&self) -> Backend;

/// Database options
fn opts(&self) -> DatabaseOptions;

/// Save [`Event`] into store
///
/// Return `true` if event was successfully saved into database.
Expand Down
25 changes: 13 additions & 12 deletions crates/nostr-sdk-db/src/memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use nostr::{Event, EventId, Filter, FiltersMatchEvent, Url};
use thiserror::Error;
use tokio::sync::RwLock;

use crate::{Backend, DatabaseError, NostrDatabase};
use crate::{Backend, DatabaseError, DatabaseOptions, NostrDatabase};

/// Memory Database Error
#[derive(Debug, Error)]
Expand All @@ -26,26 +26,23 @@ impl From<Error> for DatabaseError {
/// Memory Database (RAM)
#[derive(Debug)]
pub struct MemoryDatabase {
store_events: bool,
opts: DatabaseOptions,
seen_event_ids: Arc<RwLock<HashMap<EventId, HashSet<Url>>>>,
events: Arc<RwLock<HashMap<EventId, Event>>>,
// TODO: add messages queue? (messages not sent)
}

impl Default for MemoryDatabase {
fn default() -> Self {
Self::new(false)
Self::new(DatabaseOptions { events: false })
}
}

impl MemoryDatabase {
/// New Memory database
///
/// If `store_events` arg is set to `true`, the seen events will be stored in memory (a lot of it could be used).
/// If it's set to `false`, only the [`EventId`] will be stored (instead of the full [`Event`])
pub fn new(store_events: bool) -> Self {
pub fn new(opts: DatabaseOptions) -> Self {
Self {
store_events,
opts,
seen_event_ids: Arc::new(RwLock::new(HashMap::new())),
events: Arc::new(RwLock::new(HashMap::new())),
}
Expand Down Expand Up @@ -95,7 +92,7 @@ impl MemoryDatabase {
) -> Result<bool, DatabaseError> {
self.event_id_seen(event.id, None).await?;

if self.store_events {
if self.opts.events {
if event.is_expired() || event.is_ephemeral() {
tracing::warn!("Event {} not saved: expired or ephemeral", event.id);
return Ok(false);
Expand Down Expand Up @@ -156,6 +153,10 @@ impl NostrDatabase for MemoryDatabase {
Backend::Memory
}

fn opts(&self) -> DatabaseOptions {
self.opts
}

async fn save_event(&self, event: &Event) -> Result<bool, Self::Err> {
let mut events = self.events.write().await;
self._save_event(&mut events, event.clone()).await
Expand Down Expand Up @@ -198,7 +199,7 @@ impl NostrDatabase for MemoryDatabase {
}

async fn event_by_id(&self, event_id: EventId) -> Result<Event, Self::Err> {
if self.store_events {
if self.opts.events {
let events = self.events.read().await;
events
.get(&event_id)
Expand All @@ -210,7 +211,7 @@ impl NostrDatabase for MemoryDatabase {
}

async fn query(&self, filters: Vec<Filter>) -> Result<Vec<Event>, Self::Err> {
if self.store_events {
if self.opts.events {
let events = self.events.read().await;
self._query(&events, filters).await
} else {
Expand All @@ -219,7 +220,7 @@ impl NostrDatabase for MemoryDatabase {
}

async fn event_ids_by_filters(&self, filters: Vec<Filter>) -> Result<Vec<EventId>, Self::Err> {
if self.store_events {
if self.opts.events {
let events = self.events.read().await;
let mut list: Vec<EventId> = Vec::new();
for event in events.values() {
Expand Down
24 changes: 24 additions & 0 deletions crates/nostr-sdk-db/src/options.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// Copyright (c) 2022-2023 Yuki Kishimoto
// Distributed under the MIT software license

//! Database options
/// Database options
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct DatabaseOptions {
/// Store events (?)
pub events: bool,
}

impl Default for DatabaseOptions {
fn default() -> Self {
Self { events: true }
}
}

impl DatabaseOptions {
/// New default database options
pub fn new() -> Self {
Self::default()
}
}

0 comments on commit 05ce732

Please sign in to comment.