|
| 1 | +use std::sync::Arc; |
| 2 | + |
| 3 | +use nostr::prelude::BoxedFuture; |
| 4 | +use nostr::{Event, RelayUrl, SubscriptionId}; |
| 5 | +use nostr_gossip::NostrGossip; |
| 6 | +use nostr_relay_pool::policy::{AdmitPolicy, AdmitStatus, PolicyError}; |
| 7 | + |
| 8 | +#[derive(Debug)] |
| 9 | +pub(crate) struct AdmissionPolicyMiddleware { |
| 10 | + pub(crate) gossip: Option<Arc<dyn NostrGossip>>, |
| 11 | + pub(crate) external_policy: Option<Arc<dyn AdmitPolicy>>, |
| 12 | +} |
| 13 | + |
| 14 | +impl AdmitPolicy for AdmissionPolicyMiddleware { |
| 15 | + fn admit_connection<'a>( |
| 16 | + &'a self, |
| 17 | + relay_url: &'a RelayUrl, |
| 18 | + ) -> BoxedFuture<'a, Result<AdmitStatus, PolicyError>> { |
| 19 | + Box::pin(async move { |
| 20 | + match &self.external_policy { |
| 21 | + Some(policy) => policy.admit_connection(relay_url).await, |
| 22 | + None => Ok(AdmitStatus::Success), |
| 23 | + } |
| 24 | + }) |
| 25 | + } |
| 26 | + |
| 27 | + fn admit_event<'a>( |
| 28 | + &'a self, |
| 29 | + relay_url: &'a RelayUrl, |
| 30 | + subscription_id: &'a SubscriptionId, |
| 31 | + event: &'a Event, |
| 32 | + ) -> BoxedFuture<'a, Result<AdmitStatus, PolicyError>> { |
| 33 | + Box::pin(async move { |
| 34 | + // Process event in gossip |
| 35 | + if let Some(gossip) = &self.gossip { |
| 36 | + gossip |
| 37 | + .process(event, Some(relay_url)) |
| 38 | + .await |
| 39 | + .map_err(PolicyError::backend)?; |
| 40 | + } |
| 41 | + |
| 42 | + // Check if event is allowed by external policy |
| 43 | + match &self.external_policy { |
| 44 | + Some(policy) => policy.admit_event(relay_url, subscription_id, event).await, |
| 45 | + None => Ok(AdmitStatus::Success), |
| 46 | + } |
| 47 | + }) |
| 48 | + } |
| 49 | +} |
0 commit comments