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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
use bytes::{Bytes, BytesMut};
use reqwest::header::{HeaderMap, HeaderValue, ACCEPT};
use reqwest::Client;
use std::time::Duration;
use tokio::sync::{mpsc, oneshot};
use tokio::time;
use tokio_stream::StreamExt;
use super::CancellationToken;
const BUFFER_CAPACITY: usize = 1024;
const ENDPOINT_SSE_EVENT: &str = "endpoint";
/// Server-Sent Events (SSE) stream handler
///
/// Manages an SSE connection, handling reconnection logic and streaming data to a channel.
pub(crate) struct SseStream {
/// HTTP client for making SSE requests
pub sse_client: Client,
/// URL of the SSE endpoint
pub sse_url: String,
/// Maximum number of retry attempts for failed connections
pub max_retries: usize,
/// Delay between retry attempts
pub retry_delay: Duration,
/// Sender for transmitting received data to the readable channel
pub read_tx: mpsc::Sender<Bytes>,
}
impl SseStream {
/// Runs the SSE stream, processing incoming events and handling reconnections
///
/// Continuously attempts to connect to the SSE endpoint in case connection is lost, processes incoming data,
/// and sends it to the read channel. Handles retries and cancellation.
///
/// # Arguments
/// * `endpoint_event_tx` - Optional one-shot sender for the messages endpoint
/// * `cancellation_token` - Token for monitoring cancellation requests
pub(crate) async fn run(
&self,
mut endpoint_event_tx: Option<oneshot::Sender<Option<String>>>,
cancellation_token: CancellationToken,
custom_headers: &Option<HeaderMap>,
) {
let mut retry_count = 0;
let mut buffer = BytesMut::with_capacity(BUFFER_CAPACITY);
let mut endpoint_event_received = false;
let mut request_headers: HeaderMap = custom_headers.to_owned().unwrap_or_default();
request_headers.insert(ACCEPT, HeaderValue::from_static("text/event-stream"));
// Main loop for reconnection attempts
loop {
// Check for cancellation before attempting connection
if cancellation_token.is_cancelled() {
tracing::info!("SSE cancelled before connection attempt");
return;
}
// Send GET request to the SSE endpoint
let response = match self
.sse_client
.get(&self.sse_url)
.headers(request_headers.clone())
.send()
.await
{
Ok(resp) => resp,
Err(e) => {
tracing::error!("Failed to connect to SSE: {e}");
if retry_count >= self.max_retries {
tracing::error!("Max retries reached, giving up");
if let Some(tx) = endpoint_event_tx.take() {
let _ = tx.send(None);
}
return;
}
retry_count += 1;
time::sleep(self.retry_delay).await;
continue;
}
};
// Create a stream from the response bytes
let mut stream = response.bytes_stream();
// Inner loop for processing stream chunks
loop {
let next_chunk = tokio::select! {
// Wait for the next stream chunk
chunk = stream.next() => {
match chunk {
Some(chunk) => chunk,
None => {
if retry_count >= self.max_retries {
tracing::error!("Max retries ({}) reached, giving up",self.max_retries);
if let Some(tx) = endpoint_event_tx.take() {
let _ = tx.send(None);
}
return;
}
retry_count += 1;
time::sleep(self.retry_delay).await;
break; // Stream ended, break from inner loop to reconnect
}
}
}
// Wait for cancellation
_ = cancellation_token.cancelled() => {
return;
}
};
match next_chunk {
Ok(bytes) => {
buffer.extend_from_slice(&bytes);
let mut batch = Vec::new();
// collect complete lines for processing
while let Some(pos) = buffer.iter().position(|&b| b == b'\n') {
let line = buffer.split_to(pos + 1).freeze();
// Skip empty lines
if line.len() > 1 {
batch.push(line);
}
}
let mut current_event: Option<String> = None;
// Process complete lines
for line in batch {
// Parse line as UTF-8, keep the trailing newline
let line_str = String::from_utf8_lossy(&line);
if let Some(event_name) = line_str.strip_prefix("event: ") {
current_event = Some(event_name.trim().to_string());
continue;
}
// Extract content after data: or :
let content = if let Some(data) = line_str.strip_prefix("data: ") {
let payload = data.trim_start();
if !endpoint_event_received {
if let Some(ENDPOINT_SSE_EVENT) = current_event.as_deref() {
if let Some(tx) = endpoint_event_tx.take() {
endpoint_event_received = true;
let _ = tx.send(Some(payload.trim().to_owned()));
continue;
}
}
}
payload
} else if let Some(comment) = line_str.strip_prefix(":") {
comment.trim_start()
} else {
continue;
};
if !content.is_empty() {
let bytes = Bytes::copy_from_slice(content.as_bytes());
if self.read_tx.send(bytes).await.is_err() {
tracing::error!(
"Readable stream closed, shutting down SSE task"
);
if !endpoint_event_received {
if let Some(tx) = endpoint_event_tx.take() {
let _ = tx.send(None);
}
}
return;
}
}
}
retry_count = 0; // Reset retry count on successful chunk
}
Err(e) => {
tracing::error!("SSE stream error: {}", e);
if retry_count >= self.max_retries {
tracing::error!("Max retries reached, giving up");
if !endpoint_event_received {
if let Some(tx) = endpoint_event_tx.take() {
let _ = tx.send(None);
}
}
return;
}
retry_count += 1;
time::sleep(self.retry_delay).await;
break; // Break inner loop to reconnect
}
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::utils::CancellationTokenSource;
use reqwest::header::{HeaderMap, HeaderValue};
use tokio::time::Duration;
use wiremock::matchers::{header, method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
#[tokio::test]
async fn test_sse_client_sends_custom_headers_on_connection() {
// Start WireMock server
let mock_server = MockServer::builder().start().await;
// Create WireMock stub with connection close
Mock::given(method("GET"))
.and(path("/sse"))
.and(header("Accept", "text/event-stream"))
.and(header("X-Custom-Header", "CustomValue"))
.respond_with(
ResponseTemplate::new(200)
.set_body_string("event: endpoint\ndata: mock-endpoint\n\n")
.append_header("Content-Type", "text/event-stream")
.append_header("Connection", "close"), // Ensure connection closes
)
.expect(1) // Expect exactly one request
.mount(&mock_server)
.await;
// Create custom headers
let mut custom_headers = HeaderMap::new();
custom_headers.insert("X-Custom-Header", HeaderValue::from_static("CustomValue"));
// Create channel and SseStream
let (read_tx, _read_rx) = mpsc::channel::<Bytes>(64);
let sse = SseStream {
sse_client: reqwest::Client::new(),
sse_url: format!("{}/sse", mock_server.uri()),
max_retries: 0, // to receive one request only
retry_delay: Duration::from_millis(100),
read_tx,
};
// Create cancellation token and endpoint channel
let (cancellation_source, cancellation_token) = CancellationTokenSource::new();
let (endpoint_event_tx, endpoint_event_rx) = oneshot::channel::<Option<String>>();
// Spawn the run method
let sse_task = tokio::spawn({
async move {
sse.run(
Some(endpoint_event_tx),
cancellation_token,
&Some(custom_headers),
)
.await;
}
});
// Wait for the endpoint event or timeout
let event_result =
tokio::time::timeout(Duration::from_millis(500), endpoint_event_rx).await;
// Cancel the task to ensure loop exits
let _ = cancellation_source.cancel();
// Wait for the task to complete with a timeout
match tokio::time::timeout(Duration::from_secs(1), sse_task).await {
Ok(result) => result.unwrap(),
Err(_) => panic!("Test timed out after 1 second"),
}
// Verify the endpoint event was received
match event_result {
Ok(Ok(Some(event))) => assert_eq!(event, "mock-endpoint", "Expected endpoint event"),
_ => panic!("Did not receive expected endpoint event"),
}
}
}