Skip to content

Commit

Permalink
database: sort RawEvent ASC before index
Browse files Browse the repository at this point in the history
  • Loading branch information
yukibtc committed Dec 6, 2023
1 parent 4224ea7 commit 69701db
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions crates/nostr-database/src/index.rs
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,27 @@ impl From<Filter> for FilterIndex {
}
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct WrappedRawEvent {
raw: RawEvent,
}

impl PartialOrd for WrappedRawEvent {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}

impl Ord for WrappedRawEvent {
fn cmp(&self, other: &Self) -> Ordering {
if self.raw.created_at != other.raw.created_at {
self.raw.created_at.cmp(&other.raw.created_at)
} else {
self.raw.id.cmp(&other.raw.id)
}
}
}

/// Event Index Result
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct EventIndexResult {
Expand Down Expand Up @@ -215,8 +236,15 @@ impl DatabaseIndexes {
let mut to_discard: HashSet<EventId> = HashSet::new();
let now = Timestamp::now();

// Sort ASC to prevent issues during index
let events: BTreeSet<WrappedRawEvent> = events
.into_iter()
.map(|raw| WrappedRawEvent { raw })
.collect();

events
.into_iter()
.map(|w| w.raw)
.filter(|raw| !raw.is_expired(&now) && !raw.is_ephemeral())
.for_each(|event| {
let _ = self.index_raw_event(&mut index, &mut deleted, &mut to_discard, event);
Expand Down Expand Up @@ -299,6 +327,8 @@ impl DatabaseIndexes {
let filter: Filter = coordinate.into();
let filter: Filter = filter.until(timestamp);
for ev in self.internal_query(index, deleted, filter) {
// Not check if ev.pubkey match the pubkey_prefix because asume that query
// returned only the events owned by pubkey_prefix
to_discard.insert(ev.event_id);
}
}
Expand Down

0 comments on commit 69701db

Please sign in to comment.