Skip to main content

dynamo_runtime/traits/
events.rs

1// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4use std::fmt::Debug;
5
6use anyhow::Result;
7use async_trait::async_trait;
8use serde::{Deserialize, Serialize};
9
10// #[async_trait]
11// pub trait Publisher: Debug + Clone + Send + Sync {
12//     async fn publish(&self, event: &(impl Serialize + Send + Sync)) -> Result<()>;
13// }
14
15/// An [EventPublisher] is an object that can publish events.
16///
17/// Each implementation of [EventPublisher] will define the root subject.
18#[async_trait]
19pub trait EventPublisher {
20    /// The base subject used for this implementation of the [EventPublisher].
21    fn subject(&self) -> String;
22
23    /// Publish a single event to the event plane. The `event_name` will be `.` concatenated with the
24    /// base subject provided by the implementation.
25    async fn publish(
26        &self,
27        event_name: impl AsRef<str> + Send + Sync,
28        event: &(impl Serialize + Send + Sync),
29    ) -> Result<()>;
30
31    /// Publish a single event as bytes to the event plane. The `event_name` will be `.` concatenated with the
32    /// base subject provided by the implementation.
33    async fn publish_bytes(
34        &self,
35        event_name: impl AsRef<str> + Send + Sync,
36        bytes: Vec<u8>,
37    ) -> Result<()>;
38
39    // /// Create a new publisher for the given event name. The `event_name` will be `.` concatenated with the
40    // /// base subject provided by the implementation.
41    // fn publisher(&self, event_name: impl AsRef<str>) -> impl Publisher;
42
43    // /// Create a new publisher for the given event name. The `event_name` will be `.` concatenated with the
44    // fn publisher(&self, event_name: impl AsRef<str>) -> Result<Publisher>;
45    // fn publisher_bytes(&self, event_name: impl AsRef<str>) -> &PublisherBytes;
46}
47
48/// An [EventSubscriber] is an object that can subscribe to events.
49///
50/// This trait provides methods to subscribe to events published on specific subjects.
51#[async_trait]
52pub trait EventSubscriber {
53    /// Subscribe to events with the given event name.
54    /// The `event_name` will be `.` concatenated with the base subject provided by the implementation.
55    /// Returns a subscriber that can be used to receive events.
56    async fn subscribe(
57        &self,
58        event_name: impl AsRef<str> + Send + Sync,
59    ) -> Result<async_nats::Subscriber>;
60
61    /// Subscribe to events with the given event name and deserialize them to the specified type.
62    /// This is a convenience method that combines subscribe and deserialization.
63    async fn subscribe_with_type<T: for<'de> Deserialize<'de> + Send + 'static>(
64        &self,
65        event_name: impl AsRef<str> + Send + Sync,
66    ) -> Result<impl futures::Stream<Item = Result<T>> + Send>;
67}