Skip to main content

plexus_substrate/activations/echo/
activation.rs

1//! Echo activation - demonstrates hub-macro 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;
14use async_stream::stream;
15use futures::Stream;
16use std::time::Duration;
17
18/// Echo activation - echoes messages back
19#[derive(Clone)]
20pub struct Echo;
21
22impl Echo {
23    pub fn new() -> Self {
24        Echo
25    }
26}
27
28impl Default for Echo {
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::hub_methods(
40    namespace = "echo",
41    version = "1.0.0",
42    description = "Echo messages back - demonstrates plexus-macros usage"
43)]
44impl Echo {
45    /// Echo a message back
46    #[plexus_macros::hub_method(
47        description = "Echo a message back the specified number of times",
48        params(
49            message = "The message to echo",
50            count = "Number of times to repeat (default: 1)"
51        )
52    )]
53    async fn echo(
54        &self,
55        message: String,
56        count: u32,
57    ) -> impl Stream<Item = EchoEvent> + Send + 'static {
58        let count = if count == 0 { 1 } else { count };
59        stream! {
60            for i in 0..count {
61                if i > 0 {
62                    tokio::time::sleep(Duration::from_millis(500)).await;
63                }
64                yield EchoEvent::Echo {
65                    message: message.clone(),
66                    count: i + 1,
67                };
68            }
69        }
70    }
71
72    /// Echo a simple message once
73    #[plexus_macros::hub_method(
74        description = "Echo a message once",
75        params(message = "The message to echo")
76    )]
77    async fn once(&self, message: String) -> impl Stream<Item = EchoEvent> + Send + 'static {
78        stream! {
79            yield EchoEvent::Echo {
80                message,
81                count: 1,
82            };
83        }
84    }
85}