Skip to main content

telemetry/
handle.rs

1//! `TelemetryHandle` — 插桩侧持有的 channel sender。
2
3use crate::events::TelemetryEvent;
4use std::collections::HashMap;
5use std::sync::Arc;
6
7/// 按事件类型(`EventPayload::kind()`)预计算的开关表。
8///
9/// 从 `TelemetryConfig::event_toggles`/`default_event_enabled` 构建一次,
10/// 之后每次 `record()` 只是一次 `HashMap` 查表,不重新解析配置。
11#[derive(Debug, Clone)]
12pub struct EventFilter {
13    toggles: HashMap<String, bool>,
14    default_enabled: bool,
15}
16
17impl EventFilter {
18    /// 从配置构建。
19    pub fn from_config(config: &crate::config::TelemetryConfig) -> Self {
20        Self {
21            toggles: config.event_toggles.clone(),
22            default_enabled: config.default_event_enabled,
23        }
24    }
25
26    /// 全部放行——未按配置初始化的 handle(如测试、直接构造)的默认行为。
27    pub fn all_enabled() -> Self {
28        Self {
29            toggles: HashMap::new(),
30            default_enabled: true,
31        }
32    }
33
34    /// 该事件类型是否应该被记录。
35    pub fn is_enabled(&self, kind: &str) -> bool {
36        self.toggles
37            .get(kind)
38            .copied()
39            .unwrap_or(self.default_enabled)
40    }
41}
42
43impl Default for EventFilter {
44    fn default() -> Self {
45        Self::all_enabled()
46    }
47}
48
49/// 插桩侧句柄:Clone + Send,可注入到 Engine / Gate / Client 中。
50///
51/// 内部是 `tokio::sync::mpsc::Sender`,所有 `record` 调用是**非阻塞**的
52///(channel 满时直接丢弃——遥测不应阻塞主流程)。按点过滤在 `record()`
53/// 内部完成,被过滤掉的事件连 channel 都不会进入。
54#[derive(Debug, Clone)]
55pub struct TelemetryHandle {
56    tx: tokio::sync::mpsc::Sender<TelemetryEvent>,
57    filter: Arc<EventFilter>,
58}
59
60/// `telemetry::record()` 可能返回的错误。
61#[derive(Debug, Clone, thiserror::Error)]
62pub enum TelemetryHandleError {
63    /// Channel 满,事件被丢弃。
64    #[error("telemetry channel full, event dropped")]
65    ChannelFull,
66    /// 遥测未启用(handle 是 Noop)。
67    #[error("telemetry not enabled")]
68    NotEnabled,
69    /// A recorder could not write the event.
70    #[error("telemetry recorder could not write: {0}")]
71    Io(String),
72}
73
74impl TelemetryHandle {
75    /// 创建新 handle,不做按点过滤(全部放行)。一般情况下通过
76    /// `telemetry::spawn` 获取按配置过滤的 handle;此构造函数暴露以支持
77    /// 集成测试(in-memory pipeline)。
78    pub fn new(tx: tokio::sync::mpsc::Sender<TelemetryEvent>) -> Self {
79        Self {
80            tx,
81            filter: Arc::new(EventFilter::all_enabled()),
82        }
83    }
84
85    /// 创建新 handle,按 `filter` 做按点过滤。`telemetry::spawn` 用这个
86    /// 构造函数把 `TelemetryConfig::event_toggles` 接进来。
87    pub fn new_with_filter(
88        tx: tokio::sync::mpsc::Sender<TelemetryEvent>,
89        filter: Arc<EventFilter>,
90    ) -> Self {
91        Self { tx, filter }
92    }
93
94    /// Create a noop handle — events are silently dropped.
95    pub fn noop() -> Self {
96        let (tx, _rx) = tokio::sync::mpsc::channel(1);
97        Self {
98            tx,
99            filter: Arc::new(EventFilter::all_enabled()),
100        }
101    }
102
103    /// 记录一个遥测事件。
104    ///
105    /// 先按 `filter` 判断该事件类型是否放行——关闭的类型直接丢弃,连
106    /// channel 都不进,不占用 channel 容量。放行的事件走非阻塞 `try_send`:
107    /// channel 满时丢弃事件而非等待,channel 关闭(receiver 已 drop,
108    /// 如 disabled mode)时静默忽略而非返回错误。
109    pub fn record(&self, event: TelemetryEvent) -> Result<(), TelemetryHandleError> {
110        if !self.filter.is_enabled(event.kind()) {
111            return Ok(());
112        }
113        match self.tx.try_send(event) {
114            Ok(()) => Ok(()),
115            Err(tokio::sync::mpsc::error::TrySendError::Full(_)) => {
116                tracing::warn!("telemetry channel full, event dropped");
117                Err(TelemetryHandleError::ChannelFull)
118            }
119            Err(tokio::sync::mpsc::error::TrySendError::Closed(_)) => {
120                // Receiver dropped (deliberate, e.g. disabled mode) — silently noop
121                Ok(())
122            }
123        }
124    }
125
126    /// 优雅关闭:等待 backlog 排出后返回。
127    pub async fn shutdown(&self) {
128        self.tx.closed().await;
129    }
130}
131
132/// 什么都不做的 handle —— 遥测关闭时代的替身。
133#[derive(Debug, Clone)]
134pub struct NoopHandle;
135
136impl NoopHandle {
137    /// 创建。
138    pub fn new() -> Self {
139        Self
140    }
141    /// record 永远 Ok。
142    pub fn record(&self, _event: TelemetryEvent) -> Result<(), TelemetryHandleError> {
143        Ok(())
144    }
145    /// shutdown 是立即完成。
146    pub async fn shutdown(&self) {}
147}
148
149impl Default for NoopHandle {
150    fn default() -> Self {
151        Self::new()
152    }
153}
154
155// 让两个 handle 可互换的 trait —— 插桩点统一接收 `impl TelemetryRecorder`。
156//
157// 使用方式:
158// ```rust
159// fn run_turn(&self, telemetry: impl TelemetryRecorder) { ... }
160// ```
161// 或存储 `Box<dyn TelemetryRecorder + Send + Sync>`。
162
163/// 统一遥测记录接口(方便 inject 时不需要 enum)。
164pub trait TelemetryRecorder: Send + Sync + 'static {
165    /// 记录一个事件。
166    fn record(&self, event: TelemetryEvent) -> Result<(), TelemetryHandleError>;
167    /// 等待关闭(Boxed future 以保持 dyn 兼容)。
168    fn shutdown(&self) -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send + '_>>;
169}
170
171impl TelemetryRecorder for TelemetryHandle {
172    fn record(&self, event: TelemetryEvent) -> Result<(), TelemetryHandleError> {
173        self.record(event)
174    }
175    fn shutdown(&self) -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send + '_>> {
176        Box::pin(self.shutdown())
177    }
178}
179
180impl TelemetryRecorder for NoopHandle {
181    fn record(&self, event: TelemetryEvent) -> Result<(), TelemetryHandleError> {
182        self.record(event)
183    }
184    fn shutdown(&self) -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send + '_>> {
185        Box::pin(self.shutdown())
186    }
187}
188
189// 为 Arc-wrapped handle 实现 TelemetryRecorder(用于多人共享)
190impl<T: TelemetryRecorder> TelemetryRecorder for Arc<T> {
191    fn record(&self, event: TelemetryEvent) -> Result<(), TelemetryHandleError> {
192        (**self).record(event)
193    }
194    fn shutdown(&self) -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send + '_>> {
195        (**self).shutdown()
196    }
197}
198
199#[cfg(test)]
200mod tests {
201    use super::*;
202    use crate::events::TurnStartPayload;
203
204    fn dummy_event() -> TelemetryEvent {
205        TelemetryEvent::turn_start(
206            "test-session",
207            1,
208            None,
209            TurnStartPayload {
210                resumed: false,
211                is_retry: false,
212            },
213        )
214    }
215
216    #[test]
217    fn handle_record_normal_send_ok() {
218        let (tx, _rx) = tokio::sync::mpsc::channel(16);
219        let handle = TelemetryHandle::new(tx);
220        // try_send is synchronous
221        assert!(handle.record(dummy_event()).is_ok());
222    }
223
224    #[test]
225    fn handle_record_full_channel_returns_error() {
226        let (tx, _rx) = tokio::sync::mpsc::channel(1);
227        let handle = TelemetryHandle::new(tx);
228
229        // Fill the channel (capacity is 1)
230        assert!(handle.record(dummy_event()).is_ok());
231        // Second send should fail
232        let result = handle.record(dummy_event());
233        assert!(
234            matches!(result, Err(TelemetryHandleError::ChannelFull)),
235            "expected ChannelFull, got {:?}",
236            result
237        );
238    }
239
240    #[test]
241    fn handle_record_closed_channel_silently_ok() {
242        let (tx, rx) = tokio::sync::mpsc::channel(16);
243        let handle = TelemetryHandle::new(tx);
244        drop(rx); // close receiver
245
246        // Should return Ok, not error, when receiver is gone
247        assert!(handle.record(dummy_event()).is_ok());
248    }
249
250    #[test]
251    fn disabled_kind_is_dropped_before_entering_channel() {
252        let (tx, mut rx) = tokio::sync::mpsc::channel(16);
253        let filter = EventFilter {
254            toggles: HashMap::from([("turn_start".to_string(), false)]),
255            default_enabled: true,
256        };
257        let handle = TelemetryHandle::new_with_filter(tx, Arc::new(filter));
258
259        assert!(handle.record(dummy_event()).is_ok());
260        drop(handle);
261        assert!(
262            rx.try_recv().is_err(),
263            "disabled kind should never reach the channel"
264        );
265    }
266
267    #[test]
268    fn enabled_kind_passes_through_filter() {
269        let (tx, mut rx) = tokio::sync::mpsc::channel(16);
270        let filter = EventFilter {
271            toggles: HashMap::from([("turn_start".to_string(), true)]),
272            default_enabled: false,
273        };
274        let handle = TelemetryHandle::new_with_filter(tx, Arc::new(filter));
275
276        assert!(handle.record(dummy_event()).is_ok());
277        assert!(rx.try_recv().is_ok());
278    }
279
280    #[test]
281    fn event_filter_from_config_respects_toggles_and_default() {
282        let mut toggles = HashMap::new();
283        toggles.insert("tool_execution".to_string(), false);
284        let config = crate::config::TelemetryConfig {
285            event_toggles: toggles,
286            default_event_enabled: true,
287            ..Default::default()
288        };
289        let filter = EventFilter::from_config(&config);
290        assert!(!filter.is_enabled("tool_execution"));
291        assert!(filter.is_enabled("turn_complete"));
292    }
293
294    #[test]
295    fn noop_handle_always_ok() {
296        let noop = NoopHandle::new();
297        assert!(noop.record(dummy_event()).is_ok());
298        assert!(noop.record(dummy_event()).is_ok());
299    }
300
301    #[test]
302    fn noop_handle_default_ok() {
303        let noop = NoopHandle;
304        assert!(noop.record(dummy_event()).is_ok());
305    }
306
307    #[test]
308    fn telemetry_recorder_trait_dispatch_handle() {
309        let (tx, _rx) = tokio::sync::mpsc::channel(16);
310        let handle = TelemetryHandle::new(tx);
311        let recorder: &dyn TelemetryRecorder = &handle;
312        assert!(recorder.record(dummy_event()).is_ok());
313    }
314
315    #[test]
316    fn telemetry_recorder_trait_dispatch_noop() {
317        let noop = NoopHandle::new();
318        let recorder: &dyn TelemetryRecorder = &noop;
319        assert!(recorder.record(dummy_event()).is_ok());
320    }
321
322    #[test]
323    fn arc_handle_delegates_record() {
324        let (tx, _rx) = tokio::sync::mpsc::channel(16);
325        let handle = Arc::new(TelemetryHandle::new(tx));
326        let recorder: &dyn TelemetryRecorder = &handle as &dyn TelemetryRecorder;
327        assert!(recorder.record(dummy_event()).is_ok());
328    }
329}