Skip to main content

lellm_graph/
stream_emitter.rs

1//! StreamEmitter — 数据面发射器。
2//!
3//! 不直接暴露 Sender,未来可扩展 emit_batch()、emit_throttled()、emit_if_subscribed() 等。
4
5use tokio::sync::mpsc;
6
7use crate::stream_chunk::StreamChunk;
8
9/// 数据面发射器。
10///
11/// 封装 mpsc::Sender<StreamChunk>,提供统一的发射接口。
12pub struct StreamEmitter {
13    tx: mpsc::Sender<StreamChunk>,
14}
15
16impl Clone for StreamEmitter {
17    fn clone(&self) -> Self {
18        Self {
19            tx: self.tx.clone(),
20        }
21    }
22}
23
24impl StreamEmitter {
25    /// 创建新的 StreamEmitter。
26    pub fn new(tx: mpsc::Sender<StreamChunk>) -> Self {
27        Self { tx }
28    }
29
30    /// 发射数据面事件。
31    pub fn emit(&self, chunk: StreamChunk) {
32        // 非阻塞发送,失败则静默丢弃
33        let _ = self.tx.try_send(chunk);
34    }
35
36    /// 发射数据面事件(异步,可能阻塞)。
37    pub async fn emit_async(
38        &self,
39        chunk: StreamChunk,
40    ) -> Result<(), mpsc::error::TrySendError<StreamChunk>> {
41        self.tx.send(chunk).await.map_err(|e| match e {
42            mpsc::error::SendError(chunk) => mpsc::error::TrySendError::Full(chunk),
43        })
44    }
45
46    /// 获取底层 Sender 的 clone(用于子组件)。
47    pub fn sender(&self) -> mpsc::Sender<StreamChunk> {
48        self.tx.clone()
49    }
50}