1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
//! Conditional publishing for declarative message publishing
//!
//! This module provides a fluent API for conditional and throttled publishing.
//!
//! # Examples
//!
//! ## Conditional Publishing
//!
//! ```rust
//! use mecha10::prelude::*;
//! use mecha10::topics::perception;
//!
//! # async fn example(ctx: &Context, detections: Vec<Detection>) -> Result<()> {
//! // Only publish when detections are non-empty
//! ctx.publish_to(perception::DETECTIONS, &detections)
//! .when(|d| !d.is_empty())
//! .await?;
//! # Ok(())
//! # }
//! ```
//!
//! ## Throttled Publishing
//!
//! ```rust
//! use mecha10::prelude::*;
//! use mecha10::topics::system;
//!
//! # async fn example(ctx: &Context, status: String) -> Result<()> {
//! // Publish at most once per second
//! ctx.publish_to(system::NODE_STATUS, &status)
//! .throttle(Duration::from_secs(1))
//! .await?;
//! # Ok(())
//! # }
//! ```
use crate::context::Context;
use crate::error::Result;
use crate::messages::Message;
use crate::topics::Topic;
use serde::Serialize;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::Mutex;
/// Global throttle state for tracking last publish times
static THROTTLE_STATE: once_cell::sync::Lazy<Arc<Mutex<HashMap<String, Instant>>>> =
once_cell::sync::Lazy::new(|| Arc::new(Mutex::new(HashMap::new())));
/// Builder for conditional/throttled publishing
///
/// This builder allows chaining operations to create declarative
/// publishing behavior.
pub struct PublishBuilder<'a, 'b, T: Message + Serialize> {
ctx: &'a Context,
topic: Topic<T>,
message: &'b T,
#[allow(clippy::type_complexity)]
condition: Option<Box<dyn Fn(&T) -> bool + Send + Sync>>,
throttle_duration: Option<Duration>,
}
impl<'a, 'b, T: Message + Serialize> PublishBuilder<'a, 'b, T> {
/// Create a new publish builder
pub fn new(ctx: &'a Context, topic: Topic<T>, message: &'b T) -> Self {
Self {
ctx,
topic,
message,
condition: None,
throttle_duration: None,
}
}
/// Only publish if condition is true
///
/// If the predicate returns `false`, the message will not be published.
///
/// # Example
///
/// ```rust
/// # use mecha10::prelude::*;
/// # async fn example(ctx: &Context, detections: Vec<Detection>) -> Result<()> {
/// ctx.publish_to(perception::DETECTIONS, &detections)
/// .when(|d| !d.is_empty())
/// .await?;
/// # Ok(())
/// # }
/// ```
pub fn when<F>(mut self, predicate: F) -> Self
where
F: Fn(&T) -> bool + Send + Sync + 'static,
{
self.condition = Some(Box::new(predicate));
self
}
crate::builder_setter!(
/// Throttle publishing to a maximum rate
///
/// Messages will be rate-limited to at most one per `duration`.
/// If you try to publish more frequently, the message will be dropped.
///
/// # Example
///
/// ```rust
/// # use mecha10::prelude::*;
/// # async fn example(ctx: &Context, status: String) -> Result<()> {
/// // Max once per second
/// ctx.publish_to(system::NODE_STATUS, &status)
/// .throttle(Duration::from_secs(1))
/// .await?;
/// # Ok(())
/// # }
/// ```
into_some, throttle, throttle_duration, Duration
);
/// Execute the publish with all configured conditions
///
/// This method applies all the configured filters and throttling,
/// then publishes the message if all conditions are met.
pub async fn execute(self) -> Result<()> {
// Apply condition check
if let Some(ref condition) = self.condition {
if !condition(self.message) {
// Condition not met, skip publishing
return Ok(());
}
}
// Apply throttle check
if let Some(throttle_dur) = self.throttle_duration {
let topic_key = format!("{}-{}", self.ctx.node_id(), self.topic.path());
let mut throttle_state = THROTTLE_STATE.lock().await;
if let Some(last_time) = throttle_state.get(&topic_key) {
let elapsed = last_time.elapsed();
if elapsed < throttle_dur {
// Throttle limit not reached, skip publishing
return Ok(());
}
}
// Update last publish time
throttle_state.insert(topic_key, Instant::now());
}
// All conditions met, publish the message
self.ctx.publish_to(self.topic, self.message).await
}
}
/// Extension trait to add conditional publishing to Context
pub trait ContextPublishExt {
/// Start building a conditional publish operation
fn publish_with<'a, 'b, T>(&'a self, topic: Topic<T>, message: &'b T) -> PublishBuilder<'a, 'b, T>
where
T: Message + Serialize;
}
impl ContextPublishExt for Context {
fn publish_with<'a, 'b, T>(&'a self, topic: Topic<T>, message: &'b T) -> PublishBuilder<'a, 'b, T>
where
T: Message + Serialize,
{
PublishBuilder::new(self, topic, message)
}
}
// Allow PublishBuilder to be awaited directly
impl<'a, 'b, T: Message + Serialize> std::future::IntoFuture for PublishBuilder<'a, 'b, T>
where
'b: 'a,
{
type Output = Result<()>;
type IntoFuture = std::pin::Pin<Box<dyn std::future::Future<Output = Result<()>> + Send + 'a>>;
fn into_future(self) -> Self::IntoFuture {
Box::pin(self.execute())
}
}