qubit_http/sse/mod.rs
1/*******************************************************************************
2 *
3 * Copyright (c) 2025 - 2026.
4 * Haixing Hu, Qubit Co. Ltd.
5 *
6 * All rights reserved.
7 *
8 ******************************************************************************/
9//! # SSE Decoding
10//!
11//! SSE utilities built on top of [`HttpByteStream`](crate::HttpByteStream).
12//!
13//! # Author
14//!
15//! Haixing Hu
16
17use std::time::Duration;
18
19mod done_marker_policy;
20mod frame_decoder;
21mod json_decoder;
22mod line_decoder;
23mod sse_chunk;
24mod sse_chunk_stream;
25mod sse_event;
26mod sse_event_stream;
27mod sse_json_mode;
28
29use crate::HttpByteStream;
30
31pub use done_marker_policy::DoneMarkerPolicy;
32pub use sse_chunk::SseChunk;
33pub use sse_chunk_stream::SseChunkStream;
34pub use sse_event::SseEvent;
35pub use sse_event_stream::SseEventStream;
36pub use sse_json_mode::SseJsonMode;
37
38pub(crate) use json_decoder::decode_json_chunks_from_stream_with_limits;
39
40/// Reconnect behavior options for [`crate::HttpClient::execute_sse_with_reconnect`].
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct SseReconnectOptions {
43 /// Maximum reconnect attempts after the first connection.
44 pub max_reconnects: u32,
45 /// Base reconnect delay between attempts.
46 pub reconnect_delay: Duration,
47 /// Whether to reconnect when the SSE stream ends without an explicit error.
48 pub reconnect_on_eof: bool,
49 /// Whether to honor SSE `retry:` field as the next reconnect delay.
50 pub honor_server_retry: bool,
51}
52
53impl Default for SseReconnectOptions {
54 /// Builds default SSE reconnect options.
55 ///
56 /// # Returns
57 /// Default reconnect options with bounded reconnect attempts.
58 fn default() -> Self {
59 Self {
60 max_reconnects: 3,
61 reconnect_delay: Duration::from_secs(1),
62 reconnect_on_eof: true,
63 honor_server_retry: true,
64 }
65 }
66}
67
68impl SseReconnectOptions {
69 /// Creates default SSE reconnect options.
70 ///
71 /// # Returns
72 /// Same as [`SseReconnectOptions::default`].
73 pub fn new() -> Self {
74 Self::default()
75 }
76}
77
78/// Parses SSE frames from a body byte stream with explicit line/frame size limits.
79///
80/// # Parameters
81/// - `stream`: Body byte stream whose payload is SSE text.
82/// - `max_line_bytes`: Maximum allowed bytes for one SSE line.
83/// - `max_frame_bytes`: Maximum allowed bytes for one SSE frame.
84///
85/// # Returns
86/// Stream yielding [`SseEvent`] values or protocol/transport errors.
87pub(crate) fn decode_events_from_stream_with_limits(
88 stream: HttpByteStream,
89 max_line_bytes: usize,
90 max_frame_bytes: usize,
91) -> SseEventStream {
92 let lines = line_decoder::decode_lines(stream, max_line_bytes);
93 frame_decoder::decode_frames(lines, max_frame_bytes)
94}