Skip to main content

plexus_core/activations/echo/
activation.rs

1//! Echo activation - demonstrates plexus-macros usage with caller-wraps streaming
2//!
3//! This is a minimal example showing how to create an activation using the
4//! `#[hub_methods]` macro. The macro generates:
5//!
6//! - RPC trait and server implementation
7//! - Activation trait implementation
8//! - Method enum with JSON schemas
9//!
10//! Event types are plain domain types (no special traits needed).
11//! The macro handles wrapping with `wrap_stream()` at the call site.
12
13use super::types::{EchoEvent, Message};
14use async_stream::stream;
15use futures::Stream;
16use std::time::Duration;
17
18/// Echo activation - echoes messages back
19#[derive(Clone)]
20pub struct EchoActivation;
21
22impl EchoActivation {
23    pub fn new() -> Self {
24        EchoActivation
25    }
26}
27
28impl Default for EchoActivation {
29    fn default() -> Self {
30        Self::new()
31    }
32}
33
34/// Hub-macro generates all the boilerplate for this impl block:
35/// - EchoRpc trait with JSON-RPC subscription methods
36/// - EchoRpcServer implementation
37/// - Activation trait implementation
38/// - EchoMethod enum with JSON schemas
39#[plexus_macros::activation(
40    version = "1.0.0",
41    description = "Echo messages back - demonstrates hub-macro usage",
42    // MACRO-12: the example — `message` is a `Message`, not a `String`.
43    typed_params
44)]
45impl EchoActivation {
46    /// Echo a message back
47    #[plexus_macros::method(
48        description = "Echo a message back the specified number of times",
49        params(
50            message = "The message to echo",
51            count = "Number of times to repeat (default: 1)"
52        )
53    )]
54    async fn echo(
55        &self,
56        message: Message,
57        count: u32,
58    ) -> impl Stream<Item = EchoEvent> + Send + 'static {
59        let count = if count == 0 { 1 } else { count };
60        let message = message.into_string();
61        stream! {
62            for i in 0..count {
63                if i > 0 {
64                    tokio::time::sleep(Duration::from_millis(500)).await;
65                }
66                yield EchoEvent::Echo {
67                    message: message.clone(),
68                    count: i + 1,
69                };
70            }
71        }
72    }
73
74    /// Echo a simple message once
75    #[plexus_macros::method(
76        description = "Echo a message once",
77        params(message = "The message to echo")
78    )]
79    async fn once(&self, message: Message) -> impl Stream<Item = EchoEvent> + Send + 'static {
80        stream! {
81            yield EchoEvent::Echo {
82                message: message.into_string(),
83                count: 1,
84            };
85        }
86    }
87}