dynamo_runtime/component/
component.rs1use anyhow::Context;
17use async_trait::async_trait;
18use futures::stream::StreamExt;
19use futures::{Stream, TryStreamExt};
20
21use super::*;
22
23use crate::traits::events::{EventPublisher, EventSubscriber};
24
25#[async_trait]
26impl EventPublisher for Component {
27 fn subject(&self) -> String {
28 format!("namespace.{}.component.{}", self.namespace.name, self.name)
29 }
30
31 async fn publish(
32 &self,
33 event_name: impl AsRef<str> + Send + Sync,
34 event: &(impl Serialize + Send + Sync),
35 ) -> Result<()> {
36 let bytes = serde_json::to_vec(event)?;
37 self.publish_bytes(event_name, bytes).await
38 }
39
40 async fn publish_bytes(
41 &self,
42 event_name: impl AsRef<str> + Send + Sync,
43 bytes: Vec<u8>,
44 ) -> Result<()> {
45 let subject = format!("{}.{}", self.subject(), event_name.as_ref());
46 Ok(self
47 .drt()
48 .nats_client()
49 .client()
50 .publish(subject, bytes.into())
51 .await?)
52 }
53}
54
55#[async_trait]
56impl EventSubscriber for Component {
57 async fn subscribe(
58 &self,
59 event_name: impl AsRef<str> + Send + Sync,
60 ) -> Result<async_nats::Subscriber> {
61 let subject = format!("{}.{}", self.subject(), event_name.as_ref());
62 Ok(self.drt().nats_client().client().subscribe(subject).await?)
63 }
64
65 async fn subscribe_with_type<T: for<'de> Deserialize<'de> + Send + 'static>(
66 &self,
67 event_name: impl AsRef<str> + Send + Sync,
68 ) -> Result<impl Stream<Item = Result<T>> + Send> {
69 let subscriber = self.subscribe(event_name).await?;
70
71 let stream = subscriber.map(move |msg| {
73 serde_json::from_slice::<T>(&msg.payload)
74 .with_context(|| format!("Failed to deserialize event payload: {:?}", msg.payload))
75 });
76
77 Ok(stream)
78 }
79}
80
81#[cfg(feature = "integration")]
82#[cfg(test)]
83mod tests {
84 use super::*;
85
86 #[tokio::test]
89 async fn test_publish_and_subscribe() {
90 let rt = Runtime::from_current().unwrap();
91 let dtr = DistributedRuntime::from_settings(rt.clone()).await.unwrap();
92 let ns = dtr.namespace("test_component".to_string()).unwrap();
93 let cp = ns.component("test_component".to_string()).unwrap();
94
95 let mut subscriber = cp.subscribe("test_event").await.unwrap();
97
98 cp.publish("test_event", &"test_message".to_string())
100 .await
101 .unwrap();
102
103 if let Some(msg) = subscriber.next().await {
105 let received = String::from_utf8(msg.payload.to_vec()).unwrap();
106 assert_eq!(received, "\"test_message\"");
107 }
108
109 rt.shutdown();
110 }
111}