Skip to content

Commit

Permalink
Event dispatcher should know nothing about GiftWrappedReportRequest
Browse files Browse the repository at this point in the history
  • Loading branch information
dcadenas committed Apr 27, 2024
1 parent bf94938 commit 149318e
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 31 deletions.
26 changes: 23 additions & 3 deletions src/actors/gift_unwrapper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,22 @@ impl Actor for GiftUnwrapper {
state: &mut Self::State,
) -> Result<(), ActorProcessingErr> {
match message {
// Decrypts and forwards private messages to the output port.
GiftUnwrapperMessage::UnwrapEvent(gift_wrap) => {
// Decrypts and forwards private messages so they can be sent to
// google pubsub or whatever is hooked to the output port.
//
// Note that this is a good example of what we are trying to achieve
// in terms of separation of concerns, keeping the actor logic just
// as an orchestrator for our domain code. The brains of the
// operation are in the domain model.
GiftUnwrapperMessage::UnwrapEvent(maybe_gift_wrap) => {
// 1) The actor's message handling, which includes the message From<Event>
// implementation, deal with massaging the message to gather the
// input for...
let Some(gift_wrap) = maybe_gift_wrap else {
return Ok(());
};

// 2) The domain model, which does the real work.
let report_request = match gift_wrap.extract_report_request(&state.keys) {
Ok(report_request) => report_request,
Err(e) => {
Expand All @@ -50,6 +64,9 @@ impl Actor for GiftUnwrapper {
}
};

// 3) Resulting model output is used to create events
// that are sent to the output port for the next actor or any other
// IO needed
info!(
"Request from {} to moderate event {}",
report_request.reporter_pubkey(),
Expand Down Expand Up @@ -128,10 +145,13 @@ mod tests {

cast!(
parser_actor_ref,
GiftUnwrapperMessage::UnwrapEvent(gift_wrapped_event)
GiftUnwrapperMessage::UnwrapEvent(Some(gift_wrapped_event))
)
.unwrap();

// This happens when during the From<Event> conversion, the event
cast!(parser_actor_ref, GiftUnwrapperMessage::UnwrapEvent(None)).unwrap();

tokio::spawn(async move {
sleep(Duration::from_secs(1)).await;
parser_actor_ref.stop(None);
Expand Down
22 changes: 17 additions & 5 deletions src/actors/messages.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
use crate::domain_objects::*;
use metrics::counter;
use nostr_sdk::prelude::*;
use ractor::{port::OutputPortSubscriber, RpcReplyPort};
use std::fmt::Debug;
use tracing::error;

pub enum SupervisorMessage {
Publish(ModeratedReport),
Expand All @@ -11,21 +13,31 @@ pub enum SupervisorMessage {
pub enum RelayEventDispatcherMessage {
Connect,
Reconnect,
SubscribeToEventReceived(OutputPortSubscriber<GiftWrappedReportRequest>),
SubscribeToEventReceived(OutputPortSubscriber<Event>),
EventReceived(Event),
Publish(ModeratedReport),
GetNip05(PublicKey, RpcReplyPort<Option<String>>),
}

pub enum GiftUnwrapperMessage {
UnwrapEvent(GiftWrappedReportRequest),
// If an event couldn't be mapped to a GiftWrappedReportRequest, it will be None
UnwrapEvent(Option<GiftWrappedReportRequest>),
SubscribeToEventUnwrapped(OutputPortSubscriber<ReportRequest>),
}

// How to subscribe to actors that publish DM messages like RelayEventDispatcher
impl From<GiftWrappedReportRequest> for GiftUnwrapperMessage {
fn from(gift_wrap: GiftWrappedReportRequest) -> Self {
GiftUnwrapperMessage::UnwrapEvent(gift_wrap)
impl From<Event> for GiftUnwrapperMessage {
fn from(event: Event) -> Self {
let gift_wrapped_report_request = match GiftWrappedReportRequest::try_from(event) {
Ok(gift) => Some(gift),
Err(e) => {
counter!("event_received_error").increment(1);
error!("Failed to get gift wrap event: {}", e);
None
}
};

GiftUnwrapperMessage::UnwrapEvent(gift_wrapped_report_request)
}
}

Expand Down
23 changes: 4 additions & 19 deletions src/actors/relay_event_dispatcher.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use crate::actors::messages::RelayEventDispatcherMessage;
use crate::domain_objects::GiftWrappedReportRequest;
use crate::service_manager::ServiceManager;
use anyhow::Result;
use metrics::counter;
Expand All @@ -20,7 +19,7 @@ impl<T: NostrPort> Default for RelayEventDispatcher<T> {
}
}
pub struct State<T: NostrPort> {
event_received_output_port: OutputPort<GiftWrappedReportRequest>,
event_received_output_port: OutputPort<Event>,
subscription_task_manager: Option<ServiceManager>,
nostr_client: T,
}
Expand Down Expand Up @@ -153,18 +152,7 @@ impl<T: NostrPort> Actor for RelayEventDispatcher<T> {
subscriber.subscribe_to_port(&state.event_received_output_port);
}
RelayEventDispatcherMessage::EventReceived(event) => {
let gift_wrapped_report_request = match GiftWrappedReportRequest::try_from(event) {
Ok(gift) => gift,
Err(e) => {
counter!("event_received_error").increment(1);
error!("Failed to get gift wrap event: {}", e);
return Ok(());
}
};

state
.event_received_output_port
.send(gift_wrapped_report_request);
state.event_received_output_port.send(event);
counter!("event_received").increment(1);
}
RelayEventDispatcherMessage::Publish(moderated_report) => {
Expand Down Expand Up @@ -314,7 +302,7 @@ mod tests {
.await
.unwrap();

let received_messages = Arc::new(Mutex::new(Vec::<GiftWrappedReportRequest>::new()));
let received_messages = Arc::new(Mutex::new(Vec::<Event>::new()));

let (receiver_ref, receiver_handle) =
Actor::spawn(None, TestActor::default(), Some(received_messages.clone()))
Expand Down Expand Up @@ -343,10 +331,7 @@ mod tests {

assert_eq!(
received_messages.lock().await.as_ref(),
[
GiftWrappedReportRequest::try_from(first_event).unwrap(),
GiftWrappedReportRequest::try_from(second_event).unwrap()
]
[first_event, second_event]
);
}
}
7 changes: 3 additions & 4 deletions src/domain_objects/as_gift_wrap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,7 @@ pub trait AsGiftWrap {
fn random_time_in_last_two_days(&self) -> Timestamp {
let now = Timestamp::now();
let two_days = 2 * 24 * 60 * 60;
let random_time = now - (rand::random::<u64>() % two_days);
random_time
now - (rand::random::<u64>() % two_days)
}
}

Expand Down Expand Up @@ -69,10 +68,10 @@ mod tests {
async fn test_as_gift_wrap() {
let reporter_keys = Keys::generate();
let receiver_keys = Keys::generate();
let rumor = EventBuilder::text_note("Hello", [])
let event_to_report = EventBuilder::text_note("Hello", [])
.to_event(&reporter_keys)
.unwrap();
let report_request = ReportRequest::new(rumor, reporter_keys.public_key(), None);
let report_request = ReportRequest::new(event_to_report, reporter_keys.public_key(), None);

let gift_wrap = report_request
.as_gift_wrap(&reporter_keys, &receiver_keys.public_key())
Expand Down

0 comments on commit 149318e

Please sign in to comment.