Skip to main content

ag_ui/encode/
sse.rs

1//! Server-Sent Events framing.
2
3use crate::encode::{EventStreamFormatter, SSE_MEDIA_TYPE};
4use crate::error::Result;
5use crate::event::Event;
6
7/// A data event or an SSE transport comment.
8///
9/// Comments are independent of the AG-UI event lifecycle. They can carry
10/// replay boundaries without manufacturing a protocol event. Each line is
11/// escaped as a comment by the SDK, so input cannot inject a data frame.
12///
13/// `#[non_exhaustive]`: `text/event-stream` has fields this enum does not
14/// write yet, such as `id` and `retry`, and a frame for one can be added
15/// without a breaking release.
16#[derive(Clone, Debug, PartialEq)]
17#[non_exhaustive]
18pub enum SseFrame<E = Event> {
19    /// One serializable value. Standard live producers use `Event` and its
20    /// `metadata` field. Other representations are a host compatibility choice,
21    /// not an extension of the protocol schema.
22    Event(E),
23    /// A comment ignored by standard SSE event consumers.
24    Comment(String),
25}
26
27/// Encodes events as `text/event-stream` frames.
28///
29/// Each event becomes a single `data:` block holding its JSON, exactly as the
30/// TypeScript SDK writes it:
31///
32/// ```text
33/// data: {"type":"TEXT_MESSAGE_END","messageId":"msg-1"}
34///
35/// ```
36#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
37pub struct SseFormatter;
38
39impl SseFormatter {
40    /// Builds a formatter. It holds no state.
41    pub const fn new() -> Self {
42        Self
43    }
44
45    /// Lower-level encoding for supplied serializable values, including
46    /// compatibility replay representations.
47    ///
48    /// This does not validate or extend the AG-UI schema. Standard producers
49    /// use [`Event`] and its `metadata` field for application metadata.
50    pub fn encode_serializable(&self, event: &impl serde::Serialize) -> Result<String> {
51        Ok(frame(&self.event_json(event)?))
52    }
53
54    /// Encodes a value or comment without depending on an HTTP framework.
55    pub fn encode_frame<E: serde::Serialize>(&self, value: &SseFrame<E>) -> Result<String> {
56        match value {
57            SseFrame::Event(event) => self.encode_serializable(event),
58            SseFrame::Comment(text) => Ok(comment(text)),
59        }
60    }
61
62    // Axum adds its own SSE framing, so its adapter consumes JSON only.
63    pub(crate) fn event_json(&self, event: &impl serde::Serialize) -> Result<String> {
64        Ok(serde_json::to_string(event)?)
65    }
66
67    /// Encodes one event as an SSE frame.
68    pub fn encode_to_string(&self, event: &Event) -> Result<String> {
69        self.encode_serializable(event)
70    }
71}
72
73impl EventStreamFormatter for SseFormatter {
74    fn content_type(&self) -> &'static str {
75        SSE_MEDIA_TYPE
76    }
77
78    fn encode(&self, event: &Event) -> Result<Vec<u8>> {
79        Ok(self.encode_to_string(event)?.into_bytes())
80    }
81}
82
83/// Wraps an arbitrary payload in an SSE `data:` block.
84///
85/// A payload containing line breaks becomes one `data:` line per line, which is
86/// what the SSE decoder rejoins with `\n`; a payload with none becomes a single
87/// line. Serialized JSON is always single-line — `serde_json` escapes control
88/// characters — so this only matters for callers that frame something else, but
89/// getting it wrong would silently truncate an event at the first newline.
90///
91/// ```
92/// # use ag_ui::encode::sse::frame;
93/// assert_eq!(frame("one\ntwo"), "data: one\ndata: two\n\n");
94/// ```
95pub fn frame(payload: &str) -> String {
96    let mut out = String::with_capacity(payload.len() + 8);
97    let mut rest = payload;
98
99    loop {
100        match rest.find(['\r', '\n']) {
101            Some(index) => {
102                out.push_str("data: ");
103                out.push_str(&rest[..index]);
104                out.push('\n');
105                // A CRLF is one break, not two.
106                let width = if rest[index..].starts_with("\r\n") {
107                    2
108                } else {
109                    1
110                };
111                rest = &rest[index + width..];
112            }
113            None => {
114                out.push_str("data: ");
115                out.push_str(rest);
116                out.push('\n');
117                break;
118            }
119        }
120    }
121
122    out.push('\n');
123    out
124}
125
126/// Encodes an SSE comment, prefixing every line to prevent frame injection.
127pub fn comment(payload: &str) -> String {
128    let mut output = String::with_capacity(payload.len() + 4);
129    for line in comment_lines(payload) {
130        output.push_str(": ");
131        output.push_str(line);
132        output.push('\n');
133    }
134    output.push('\n');
135    output
136}
137
138/// CRLF is one boundary; lone CR/LF and a trailing empty line are preserved.
139pub(crate) fn comment_lines(payload: &str) -> impl Iterator<Item = &str> {
140    let mut rest = Some(payload);
141    std::iter::from_fn(move || {
142        let value = rest.take()?;
143        match value.find(['\r', '\n']) {
144            Some(index) => {
145                let width = if value[index..].starts_with("\r\n") {
146                    2
147                } else {
148                    1
149                };
150                rest = Some(&value[index + width..]);
151                Some(&value[..index])
152            }
153            None => Some(value),
154        }
155    })
156}