dynamo_runtime/component/
component.rs

1// SPDX-FileCopyrightText: Copyright (c) 2024-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4use anyhow::Context;
5use async_trait::async_trait;
6use futures::stream::StreamExt;
7use futures::{Stream, TryStreamExt};
8
9use super::*;
10
11use crate::traits::events::{EventPublisher, EventSubscriber};
12
13#[async_trait]
14impl EventPublisher for Component {
15    fn subject(&self) -> String {
16        format!("namespace.{}.component.{}", self.namespace.name, self.name)
17    }
18
19    async fn publish(
20        &self,
21        event_name: impl AsRef<str> + Send + Sync,
22        event: &(impl Serialize + Send + Sync),
23    ) -> Result<()> {
24        let bytes = serde_json::to_vec(event)?;
25        self.publish_bytes(event_name, bytes).await
26    }
27
28    async fn publish_bytes(
29        &self,
30        event_name: impl AsRef<str> + Send + Sync,
31        bytes: Vec<u8>,
32    ) -> Result<()> {
33        let subject = format!("{}.{}", self.subject(), event_name.as_ref());
34        Ok(self
35            .drt()
36            .nats_client()
37            .client()
38            .publish(subject, bytes.into())
39            .await?)
40    }
41}
42
43#[async_trait]
44impl EventSubscriber for Component {
45    async fn subscribe(
46        &self,
47        event_name: impl AsRef<str> + Send + Sync,
48    ) -> Result<async_nats::Subscriber> {
49        let subject = format!("{}.{}", self.subject(), event_name.as_ref());
50        Ok(self.drt().nats_client().client().subscribe(subject).await?)
51    }
52
53    async fn subscribe_with_type<T: for<'de> Deserialize<'de> + Send + 'static>(
54        &self,
55        event_name: impl AsRef<str> + Send + Sync,
56    ) -> Result<impl Stream<Item = Result<T>> + Send> {
57        let subscriber = self.subscribe(event_name).await?;
58
59        // Transform the subscriber into a stream of deserialized events
60        let stream = subscriber.map(move |msg| {
61            serde_json::from_slice::<T>(&msg.payload)
62                .with_context(|| format!("Failed to deserialize event payload: {:?}", msg.payload))
63        });
64
65        Ok(stream)
66    }
67}
68
69#[cfg(feature = "integration")]
70#[cfg(test)]
71mod tests {
72    use super::*;
73
74    // todo - make a distributed runtime fixture
75    // todo - two options - fully mocked or integration test
76    #[tokio::test]
77    async fn test_publish_and_subscribe() {
78        let rt = Runtime::from_current().unwrap();
79        let dtr = DistributedRuntime::from_settings(rt.clone()).await.unwrap();
80        let ns = dtr.namespace("test_component".to_string()).unwrap();
81        let cp = ns.component("test_component".to_string()).unwrap();
82
83        // Create a subscriber on the component
84        let mut subscriber = cp.subscribe("test_event").await.unwrap();
85
86        // Publish a message from the component
87        cp.publish("test_event", &"test_message".to_string())
88            .await
89            .unwrap();
90
91        // Receive the message
92        if let Some(msg) = subscriber.next().await {
93            let received = String::from_utf8(msg.payload.to_vec()).unwrap();
94            assert_eq!(received, "\"test_message\"");
95        }
96
97        rt.shutdown();
98    }
99}