Skip to main content

vtcode_llm/providers/gemini/wire/streaming/
processor.rs

1//! Streaming processor for handling real-time responses from the Gemini API
2//!
3//! This module provides functionality to process streaming responses from the Gemini API,
4//! parse them in real-time, and provide callbacks for handling each chunk of data.
5
6use super::super::models::{Content, Part};
7use super::{StreamingCandidate, StreamingError, StreamingMetrics, StreamingResponse};
8use futures::stream::StreamExt;
9use reqwest::Response;
10use serde_json::Value;
11use std::time::Instant;
12use tokio::time::{Duration, timeout};
13use tracing;
14
15/// Configuration for the streaming processor
16#[derive(Debug, Clone)]
17pub struct StreamingConfig {
18    /// Timeout for reading each chunk
19    chunk_timeout: Duration,
20    /// Maximum time to wait for the first chunk
21    first_chunk_timeout: Duration,
22    /// Maximum total time for entire streaming request (0 means no limit)
23    total_timeout: Duration,
24    /// Buffer size for chunk processing
25    buffer_size: usize,
26}
27
28impl Default for StreamingConfig {
29    fn default() -> Self {
30        Self {
31            chunk_timeout: Duration::from_secs(30),
32            first_chunk_timeout: Duration::from_secs(60),
33            total_timeout: Duration::from_secs(600),
34            buffer_size: 1024,
35        }
36    }
37}
38
39impl StreamingConfig {
40    /// Create config with custom total timeout (in seconds)
41    pub(crate) fn with_total_timeout(total_timeout_secs: u64) -> Self {
42        Self {
43            total_timeout: Duration::from_secs(total_timeout_secs),
44            ..Default::default()
45        }
46    }
47}
48
49/// Callback for streaming timeout progress updates
50pub type ProgressCallback = Box<dyn Fn(f32) + Send + Sync>;
51
52/// Streaming processor for handling real-time responses from the Gemini API
53pub struct StreamingProcessor {
54    config: StreamingConfig,
55    metrics: StreamingMetrics,
56    current_event_data: String,
57    progress_callback: Option<ProgressCallback>,
58    warning_threshold: f32,
59}
60
61impl StreamingProcessor {
62    /// Create a new streaming processor with default configuration
63    pub(crate) fn new() -> Self {
64        Self {
65            config: StreamingConfig::default(),
66            metrics: StreamingMetrics::default(),
67            // Optimize: Pre-allocate for typical JSON event size
68            current_event_data: String::with_capacity(512),
69            progress_callback: None,
70            warning_threshold: 0.8,
71        }
72    }
73
74    /// Create a new streaming processor with custom configuration
75    pub(crate) fn with_config(config: StreamingConfig) -> Self {
76        Self {
77            config,
78            metrics: StreamingMetrics::default(),
79            // Optimize: Pre-allocate for typical JSON event size
80            current_event_data: String::with_capacity(512),
81            progress_callback: None,
82            warning_threshold: 0.8,
83        }
84    }
85
86    /// Set a progress callback that reports timeout progress as a ratio (0.0-1.0)
87    pub fn with_progress_callback(mut self, callback: ProgressCallback) -> Self {
88        self.progress_callback = Some(callback);
89        self
90    }
91
92    /// Set the warning threshold for timeout progress (0.0-1.0, default 0.8)
93    pub fn with_warning_threshold(mut self, threshold: f32) -> Self {
94        self.warning_threshold = threshold.clamp(0.0, 1.0);
95        self
96    }
97
98    /// Process a streaming response from the Gemini API
99    ///
100    /// This method takes a response and processes it in real-time, calling the provided
101    /// callback for each chunk of content received.
102    ///
103    /// # Arguments
104    ///
105    /// * `response` - The HTTP response from the Gemini API
106    /// * `on_chunk` - A callback function that will be called for each text chunk received
107    ///
108    /// # Returns
109    ///
110    /// A result containing the final accumulated response or a streaming error
111    pub(crate) async fn process_stream<F>(
112        &mut self,
113        response: Response,
114        mut on_chunk: F,
115    ) -> Result<StreamingResponse, StreamingError>
116    where
117        F: FnMut(&str) -> Result<(), StreamingError>,
118    {
119        self.metrics.request_start_time = Some(Instant::now());
120        self.metrics.total_requests += 1;
121        self.current_event_data.clear();
122
123        // Get the response stream
124        let mut stream = response.bytes_stream();
125
126        let mut accumulated_response = StreamingResponse { candidates: Vec::new(), usage_metadata: None };
127
128        let mut _has_valid_content = false;
129        // Optimize: Pre-allocate buffer with typical SSE line size to reduce reallocations
130        let mut buffer = String::with_capacity(self.config.buffer_size);
131        let mut decoder = crate::providers::shared::Utf8StreamDecoder::new();
132        let request_start = Instant::now();
133
134        // Wait for the first chunk with a longer timeout
135        let first_chunk_start = Instant::now();
136        let first_chunk_result = timeout(self.config.first_chunk_timeout, stream.next()).await;
137
138        match first_chunk_result {
139            Ok(Some(Ok(bytes))) => {
140                self.metrics.first_chunk_time = Some(Instant::now());
141                self.metrics.total_bytes += bytes.len();
142                self.report_progress(first_chunk_start, request_start);
143
144                // Process the first chunk
145                buffer.push_str(&decoder.push(&bytes));
146                match self.process_buffer(&mut buffer, &mut accumulated_response, &mut on_chunk) {
147                    Ok(valid) => _has_valid_content = valid,
148                    Err(e) => return Err(e),
149                }
150            }
151            Ok(Some(Err(e))) => {
152                self.metrics.error_count += 1;
153                return Err(StreamingError::NetworkError {
154                    message: format!("Failed to read first chunk: {e}"),
155                    is_retryable: true,
156                });
157            }
158            Ok(None) => {
159                return Err(StreamingError::StreamingError {
160                    message: "Empty streaming response".to_owned(),
161                    partial_content: None,
162                });
163            }
164            Err(_) => {
165                self.metrics.error_count += 1;
166                self.report_progress(first_chunk_start, request_start);
167                return Err(StreamingError::TimeoutError {
168                    operation: "first_chunk".to_owned(),
169                    duration: self.config.first_chunk_timeout,
170                });
171            }
172        }
173
174        // Process subsequent chunks
175        while let Some(result) = stream.next().await {
176            let elapsed = request_start.elapsed();
177
178            // Check if total timeout has been exceeded
179            if self.config.total_timeout.as_secs() > 0 {
180                if elapsed > self.config.total_timeout {
181                    self.metrics.error_count += 1;
182                    self.report_progress_at_timeout(elapsed);
183                    return Err(StreamingError::TimeoutError {
184                        operation: "streaming".to_owned(),
185                        duration: elapsed,
186                    });
187                }
188                // Report progress towards timeout
189                self.report_progress_with_timeout(elapsed);
190            }
191
192            match result {
193                Ok(bytes) => {
194                    self.metrics.total_bytes += bytes.len();
195
196                    // Add to buffer
197                    buffer.push_str(&decoder.push(&bytes));
198
199                    // Process buffer
200                    match self.process_buffer(&mut buffer, &mut accumulated_response, &mut on_chunk) {
201                        Ok(valid) => {
202                            if valid {
203                                _has_valid_content = true;
204                            }
205                        }
206                        Err(e) => return Err(e),
207                    }
208                }
209                Err(e) => {
210                    self.metrics.error_count += 1;
211                    self.report_progress_at_timeout(elapsed);
212                    return Err(StreamingError::NetworkError {
213                        message: format!("Failed to read chunk: {e}"),
214                        is_retryable: true,
215                    });
216                }
217            }
218
219            self.metrics.total_chunks += 1;
220        }
221
222        // Process any remaining data in the buffer
223        if !buffer.is_empty() {
224            match self.process_remaining_buffer(&mut buffer, &mut accumulated_response, &mut on_chunk) {
225                Ok(valid) => {
226                    if valid {
227                        _has_valid_content = true;
228                    }
229                }
230                Err(e) => return Err(e),
231            }
232        }
233
234        if !_has_valid_content {
235            return Err(StreamingError::ContentError {
236                message: "No valid content received from streaming API".to_owned(),
237            });
238        }
239
240        Ok(accumulated_response)
241    }
242
243    fn process_buffer<F>(
244        &mut self,
245        buffer: &mut String,
246        accumulated_response: &mut StreamingResponse,
247        on_chunk: &mut F,
248    ) -> Result<bool, StreamingError>
249    where
250        F: FnMut(&str) -> Result<(), StreamingError>,
251    {
252        let mut _has_valid_content = false;
253        let mut processed_chars = 0;
254
255        while let Some(newline_pos) = buffer[processed_chars..].find('\n') {
256            let line_end = processed_chars + newline_pos;
257            let line = &buffer[processed_chars..line_end];
258            processed_chars = line_end + 1;
259
260            _has_valid_content |= self.handle_line(line, accumulated_response, on_chunk)?;
261        }
262
263        // Optimize: Use drain to avoid allocation when removing processed content
264        if processed_chars > 0 {
265            buffer.drain(..processed_chars);
266        }
267
268        // Fail closed when the retained tail tops the shared SSE bound: a peer
269        // that never emits a newline would otherwise grow the buffer for the
270        // stream lifetime. Measured after the drain so complete events still
271        // parse. `partial_content` stays `None` — cloning the multi-megabyte
272        // tail into the error would double the spike.
273        crate::providers::shared::check_sse_tail_bound(buffer.len()).map_err(|overflow| {
274            StreamingError::StreamingError {
275                message: overflow.to_string(),
276                partial_content: None,
277            }
278        })?;
279
280        Ok(_has_valid_content)
281    }
282
283    /// Process any remaining data in the buffer after streaming is complete
284    fn process_remaining_buffer<F>(
285        &mut self,
286        buffer: &mut String,
287        accumulated_response: &mut StreamingResponse,
288        on_chunk: &mut F,
289    ) -> Result<bool, StreamingError>
290    where
291        F: FnMut(&str) -> Result<(), StreamingError>,
292    {
293        let mut _has_valid_content = false;
294
295        if !buffer.is_empty() {
296            let remaining_line = buffer.trim_end_matches('\r');
297            if !remaining_line.trim().is_empty() {
298                _has_valid_content |= self.handle_line(remaining_line, accumulated_response, on_chunk)?;
299            }
300        }
301
302        buffer.clear();
303
304        _has_valid_content |= self.finalize_current_event(accumulated_response, on_chunk)?;
305
306        Ok(_has_valid_content)
307    }
308
309    /// Handle a single SSE line
310    fn handle_line<F>(
311        &mut self,
312        raw_line: &str,
313        accumulated_response: &mut StreamingResponse,
314        on_chunk: &mut F,
315    ) -> Result<bool, StreamingError>
316    where
317        F: FnMut(&str) -> Result<(), StreamingError>,
318    {
319        let mut _has_valid_content = false;
320        let line = raw_line.trim_end_matches('\r');
321
322        if line.is_empty() {
323            _has_valid_content |= self.finalize_current_event(accumulated_response, on_chunk)?;
324            return Ok(_has_valid_content);
325        }
326
327        let trimmed = line.trim();
328
329        if trimmed.is_empty() {
330            return Ok(false);
331        }
332
333        if trimmed.starts_with(':') {
334            return Ok(false);
335        }
336
337        if trimmed.starts_with("event:") || trimmed.starts_with("id:") {
338            return Ok(false);
339        }
340
341        if let Some(data_segment) = trimmed.strip_prefix("data:") {
342            let data_segment = data_segment.trim_start();
343            if data_segment == "[DONE]" {
344                _has_valid_content |= self.finalize_current_event(accumulated_response, on_chunk)?;
345                return Ok(_has_valid_content);
346            }
347
348            if !data_segment.is_empty() {
349                if !self.current_event_data.is_empty() {
350                    self.current_event_data.push('\n');
351                }
352                self.current_event_data.push_str(data_segment);
353
354                _has_valid_content |= self.try_flush_current_event(accumulated_response, on_chunk)?;
355            }
356            return Ok(_has_valid_content);
357        }
358
359        if trimmed.starts_with('{') || trimmed.starts_with('[') {
360            if !self.current_event_data.is_empty() {
361                self.current_event_data.push('\n');
362            }
363            self.current_event_data.push_str(trimmed);
364            return Ok(false);
365        }
366
367        if !self.current_event_data.is_empty() {
368            self.current_event_data.push('\n');
369        }
370        self.current_event_data.push_str(trimmed);
371
372        Ok(false)
373    }
374
375    fn finalize_current_event<F>(
376        &mut self,
377        accumulated_response: &mut StreamingResponse,
378        on_chunk: &mut F,
379    ) -> Result<bool, StreamingError>
380    where
381        F: FnMut(&str) -> Result<(), StreamingError>,
382    {
383        if self.current_event_data.trim().is_empty() {
384            self.current_event_data.clear();
385            return Ok(false);
386        }
387
388        let event_data = std::mem::take(&mut self.current_event_data);
389        self.process_event(event_data, accumulated_response, on_chunk)
390    }
391
392    fn try_flush_current_event<F>(
393        &mut self,
394        accumulated_response: &mut StreamingResponse,
395        on_chunk: &mut F,
396    ) -> Result<bool, StreamingError>
397    where
398        F: FnMut(&str) -> Result<(), StreamingError>,
399    {
400        let trimmed = self.current_event_data.trim();
401        if trimmed.is_empty() {
402            return Ok(false);
403        }
404
405        match serde_json::from_str::<Value>(trimmed) {
406            Ok(parsed) => {
407                self.current_event_data.clear();
408                self.process_event_value(parsed, accumulated_response, on_chunk)
409            }
410            Err(parse_err) => {
411                if parse_err.is_eof() {
412                    return Ok(false);
413                }
414
415                Err(StreamingError::ParseError {
416                    message: format!("Failed to parse streaming JSON: {parse_err}"),
417                    raw_response: trimmed.to_owned(),
418                })
419            }
420        }
421    }
422
423    fn process_event<F>(
424        &mut self,
425        event_data: String,
426        accumulated_response: &mut StreamingResponse,
427        on_chunk: &mut F,
428    ) -> Result<bool, StreamingError>
429    where
430        F: FnMut(&str) -> Result<(), StreamingError>,
431    {
432        let trimmed = event_data.trim();
433
434        if trimmed.is_empty() {
435            return Ok(false);
436        }
437
438        match serde_json::from_str::<Value>(trimmed) {
439            Ok(parsed) => self.process_event_value(parsed, accumulated_response, on_chunk),
440            Err(parse_err) => {
441                if parse_err.is_eof() {
442                    self.current_event_data = trimmed.to_owned();
443                    return Ok(false);
444                }
445
446                Err(StreamingError::ParseError {
447                    message: format!("Failed to parse streaming JSON: {parse_err}"),
448                    raw_response: trimmed.to_owned(),
449                })
450            }
451        }
452    }
453
454    fn append_text_candidate(&mut self, accumulated_response: &mut StreamingResponse, text: &str) {
455        if text.is_empty() {
456            return;
457        }
458
459        if let Some(last_candidate) = accumulated_response.candidates.last_mut() {
460            Self::merge_parts(
461                &mut last_candidate.content.parts,
462                vec![Part::Text { text: text.to_owned(), thought_signature: None }],
463            );
464            return;
465        }
466
467        let index = accumulated_response.candidates.len();
468
469        accumulated_response.candidates.push(StreamingCandidate {
470            content: Content {
471                role: "model".to_owned(),
472                parts: vec![Part::Text { text: text.to_owned(), thought_signature: None }],
473            },
474            finish_reason: None,
475            index: Some(index),
476        });
477    }
478
479    /// Process a streaming candidate and extract content
480    fn process_candidate<F>(&self, candidate: &StreamingCandidate, on_chunk: &mut F) -> Result<bool, StreamingError>
481    where
482        F: FnMut(&str) -> Result<(), StreamingError>,
483    {
484        let mut _has_valid_content = false;
485
486        if candidate.finish_reason.is_some() {
487            _has_valid_content = true;
488        }
489
490        // Process each part of the content
491        for part in &candidate.content.parts {
492            match part {
493                Part::Text { text, .. } => {
494                    if !text.trim().is_empty() {
495                        on_chunk(text)?;
496                        _has_valid_content = true;
497                    }
498                }
499                Part::InlineData { .. } => {
500                    _has_valid_content = true;
501                }
502                Part::FunctionCall { .. } => {
503                    // Function calls are handled separately in the tool execution flow
504                    _has_valid_content = true;
505                }
506                Part::FunctionResponse { .. } => {
507                    _has_valid_content = true;
508                }
509                Part::ToolCall { .. }
510                | Part::ToolResponse { .. }
511                | Part::ExecutableCode { .. }
512                | Part::CodeExecutionResult { .. } => {
513                    _has_valid_content = true;
514                }
515                Part::CacheControl { .. } => {}
516            }
517        }
518
519        Ok(_has_valid_content)
520    }
521
522    fn process_event_value<F>(
523        &mut self,
524        value: Value,
525        accumulated_response: &mut StreamingResponse,
526        on_chunk: &mut F,
527    ) -> Result<bool, StreamingError>
528    where
529        F: FnMut(&str) -> Result<(), StreamingError>,
530    {
531        match value {
532            Value::Array(items) => {
533                let mut has_valid = false;
534                for item in items {
535                    if self.process_event_value(item, accumulated_response, on_chunk)? {
536                        has_valid = true;
537                    }
538                }
539                Ok(has_valid)
540            }
541            Value::Object(mut map) => {
542                if let Some(error_value) = map.get("error") {
543                    let message = error_value
544                        .get("message")
545                        .and_then(Value::as_str)
546                        .unwrap_or("Gemini streaming error")
547                        .to_owned();
548                    #[allow(
549                        clippy::cast_sign_loss,
550                        reason = "Intentional compatibility, platform, or test-only suppression."
551                    )]
552                    let code = error_value.get("code").and_then(Value::as_i64).unwrap_or(500) as u16;
553                    return Err(StreamingError::ApiError {
554                        status_code: code,
555                        message,
556                        is_retryable: code == 429,
557                    });
558                }
559
560                if let Some(usage) = map.remove("usageMetadata") {
561                    accumulated_response.usage_metadata = Some(usage);
562                }
563
564                let mut has_valid = false;
565
566                if let Some(candidates_value) = map.remove("candidates") {
567                    let candidate_values: Vec<Value> = match candidates_value {
568                        Value::Array(items) => items,
569                        Value::Object(_) => vec![candidates_value],
570                        _ => Vec::new(),
571                    };
572
573                    for candidate_value in candidate_values {
574                        match serde_json::from_value::<StreamingCandidate>(candidate_value.clone()) {
575                            Ok(candidate) => {
576                                if self.process_candidate(&candidate, on_chunk)? {
577                                    has_valid = true;
578                                }
579                                self.merge_candidate(accumulated_response, candidate);
580                            }
581                            Err(err) => {
582                                if let Some(text) = Self::extract_text_from_value(&candidate_value) {
583                                    if !text.trim().is_empty() {
584                                        on_chunk(&text)?;
585                                        self.append_text_candidate(accumulated_response, &text);
586                                        has_valid = true;
587                                    }
588                                } else {
589                                    return Err(StreamingError::ParseError {
590                                        message: format!("Failed to parse candidate: {err}"),
591                                        raw_response: candidate_value.to_string(),
592                                    });
593                                }
594                            }
595                        }
596                    }
597                }
598
599                if let Some(text_value) = map.remove("text").and_then(|v| v.as_str().map(|s| s.to_owned()))
600                    && !text_value.trim().is_empty()
601                {
602                    on_chunk(&text_value)?;
603                    self.append_text_candidate(accumulated_response, &text_value);
604                    has_valid = true;
605                }
606
607                Ok(has_valid)
608            }
609            Value::String(text) => {
610                if text.trim().is_empty() {
611                    Ok(false)
612                } else {
613                    on_chunk(&text)?;
614                    self.append_text_candidate(accumulated_response, &text);
615                    Ok(true)
616                }
617            }
618            _ => Ok(false),
619        }
620    }
621
622    fn merge_candidate(&mut self, accumulated_response: &mut StreamingResponse, mut candidate: StreamingCandidate) {
623        let index = candidate.index.unwrap_or(accumulated_response.candidates.len());
624
625        if let Some(existing) = accumulated_response
626            .candidates
627            .iter_mut()
628            .find(|existing| existing.index.unwrap_or(index) == index)
629        {
630            if existing.content.role.is_empty() {
631                existing.content.role = candidate.content.role.clone();
632            }
633
634            Self::merge_parts(&mut existing.content.parts, candidate.content.parts);
635
636            if candidate.finish_reason.is_some() {
637                existing.finish_reason = candidate.finish_reason;
638            }
639        } else {
640            candidate.index = Some(index);
641            accumulated_response.candidates.push(candidate);
642        }
643    }
644
645    fn merge_parts(target: &mut Vec<Part>, source_parts: Vec<Part>) {
646        if target.is_empty() {
647            *target = source_parts;
648            return;
649        }
650
651        for part in source_parts {
652            match (target.last_mut(), &part) {
653                (
654                    Some(Part::Text { text: existing, thought_signature: existing_sig }),
655                    Part::Text { text: new_text, thought_signature: new_sig },
656                ) => {
657                    existing.push_str(new_text);
658                    // Preserve thought signature if it arrives in a later chunk
659                    if existing_sig.is_none() && new_sig.is_some() {
660                        *existing_sig = new_sig.clone();
661                    }
662                }
663                _ => target.push(part),
664            }
665        }
666    }
667
668    fn extract_text_from_value(value: &Value) -> Option<String> {
669        match value {
670            Value::String(text) => {
671                if text.trim().is_empty() {
672                    None
673                } else {
674                    Some(text.clone())
675                }
676            }
677            Value::Array(items) => Self::extract_text_from_array(items),
678            Value::Object(map) => {
679                if let Some(text) = map.get("text").and_then(Value::as_str)
680                    && !text.trim().is_empty()
681                {
682                    return Some(text.to_owned());
683                }
684
685                if let Some(parts) = map.get("parts").and_then(Value::as_array)
686                    && let Some(parts_text) = Self::extract_text_from_array(parts)
687                {
688                    return Some(parts_text);
689                }
690
691                for nested in map.values() {
692                    if let Some(nested_text) = Self::extract_text_from_value(nested)
693                        && !nested_text.trim().is_empty()
694                    {
695                        return Some(nested_text);
696                    }
697                }
698
699                None
700            }
701            _ => None,
702        }
703    }
704
705    /// Collect text fragments from a JSON array without materializing an
706    /// intermediate `Value::Array` (avoids a `Vec<Value>` clone on the
707    /// fallback extraction path).
708    fn extract_text_from_array(items: &[Value]) -> Option<String> {
709        let mut collected = String::new();
710        for item in items {
711            if let Some(fragment) = Self::extract_text_from_value(item) {
712                collected.push_str(&fragment);
713            }
714        }
715        if collected.is_empty() { None } else { Some(collected) }
716    }
717
718    /// Report progress towards the timeout threshold
719    fn report_progress_with_timeout(&self, elapsed: Duration) {
720        if self.config.total_timeout.as_secs() == 0 {
721            return;
722        }
723
724        let progress = elapsed.as_secs_f32() / self.config.total_timeout.as_secs_f32();
725        let progress_clamped = progress.min(0.99); // Cap at 99% to avoid premature completion
726
727        if let Some(ref callback) = self.progress_callback {
728            callback(progress_clamped);
729        }
730
731        // Warn if approaching warning threshold
732        if progress >= self.warning_threshold {
733            tracing::warn!(
734                "Streaming operation at {:.0}% of timeout limit ({}/{:?} elapsed). Approaching timeout.",
735                progress_clamped * 100.0,
736                elapsed.as_secs(),
737                self.config.total_timeout
738            );
739        }
740    }
741
742    /// Report progress when timeout/error occurs
743    fn report_progress_at_timeout(&self, _elapsed: Duration) {
744        if let Some(ref callback) = self.progress_callback {
745            callback(1.0); // Report as complete/failed
746        }
747    }
748
749    /// Report immediate progress (e.g., after first chunk)
750    fn report_progress(&self, _event_time: Instant, _start_time: Instant) {
751        if let Some(ref callback) = self.progress_callback {
752            callback(0.1); // Report early progress
753        }
754    }
755
756    /// Get current streaming metrics
757    fn metrics(&self) -> &StreamingMetrics {
758        &self.metrics
759    }
760
761    /// Reset streaming metrics
762    pub fn reset_metrics(&mut self) {
763        self.metrics = StreamingMetrics::default();
764    }
765}
766
767impl Default for StreamingProcessor {
768    fn default() -> Self {
769        Self::new()
770    }
771}
772
773#[cfg(test)]
774mod tests {
775    use super::*;
776
777    #[test]
778    fn test_streaming_processor_creation() {
779        let processor = StreamingProcessor::new();
780        assert_eq!(processor.metrics().total_requests, 0);
781    }
782
783    #[test]
784    fn test_streaming_processor_with_config() {
785        use std::time::Duration;
786
787        let config = StreamingConfig {
788            chunk_timeout: Duration::from_secs(10),
789            first_chunk_timeout: Duration::from_secs(30),
790            total_timeout: Duration::from_secs(120),
791            buffer_size: 512,
792        };
793
794        let processor = StreamingProcessor::with_config(config);
795        assert_eq!(processor.metrics().total_requests, 0);
796    }
797
798    #[test]
799    fn test_streaming_config_default() {
800        let config = StreamingConfig::default();
801        assert_eq!(config.buffer_size, 1024);
802    }
803
804    #[test]
805    fn test_handles_back_to_back_data_lines_without_blank_lines() {
806        let mut processor = StreamingProcessor::new();
807        let mut accumulated = StreamingResponse { candidates: Vec::new(), usage_metadata: None };
808        let mut received_chunks: Vec<String> = Vec::new();
809        let mut buffer = String::from(
810            "data: {\"candidates\":[{\"index\":0,\"content\":{\"role\":\"model\",\"parts\":[{\"text\":\"Hello\"}]}}]}\n",
811        );
812        buffer.push_str(
813            "data: {\"candidates\":[{\"index\":0,\"content\":{\"role\":\"model\",\"parts\":[{\"text\":\" world\"}]}}]}\n",
814        );
815
816        {
817            let mut on_chunk = |chunk: &str| {
818                received_chunks.push(chunk.to_owned());
819                Ok(())
820            };
821            let has_valid = processor
822                .process_buffer(&mut buffer, &mut accumulated, &mut on_chunk)
823                .expect("processing should succeed");
824            assert!(has_valid);
825        }
826
827        assert_eq!(received_chunks, vec!["Hello", " world"]);
828        assert_eq!(accumulated.candidates.len(), 1);
829        let combined = match &accumulated.candidates[0].content.parts[0] {
830            Part::Text { text, .. } => text.clone(),
831            _ => String::new(),
832        };
833        assert_eq!(combined, "Hello world");
834    }
835
836    #[test]
837    fn process_buffer_fails_closed_on_boundary_less_tail() {
838        use crate::providers::shared::MAX_SSE_TAIL_BYTES;
839
840        let mut processor = StreamingProcessor::new();
841        let mut accumulated = StreamingResponse { candidates: Vec::new(), usage_metadata: None };
842        // No newline anywhere: the whole 16 MiB + 1 stays retained.
843        let mut buffer = "x".repeat(MAX_SSE_TAIL_BYTES + 1);
844        let mut on_chunk = |_: &str| Ok(());
845
846        let error = processor
847            .process_buffer(&mut buffer, &mut accumulated, &mut on_chunk)
848            .expect_err("boundary-less tail past the cap must trip");
849        assert!(
850            matches!(error, StreamingError::StreamingError { partial_content: None, .. }),
851            "overflow must not clone the tail into the error: {error:?}"
852        );
853        assert!(error.to_string().contains("without an event boundary"), "{error}");
854    }
855
856    #[test]
857    fn process_buffer_accepts_complete_event_past_the_cap() {
858        use crate::providers::shared::MAX_SSE_TAIL_BYTES;
859
860        // Asymmetric control: the same oversized payload with a trailing
861        // newline parses and drains, so nothing is retained and the bound
862        // must not trip — the check measures the tail, not the chunk.
863        let mut processor = StreamingProcessor::new();
864        let mut accumulated = StreamingResponse { candidates: Vec::new(), usage_metadata: None };
865        let mut buffer = "x".repeat(MAX_SSE_TAIL_BYTES + 1);
866        buffer.push('\n');
867        let mut on_chunk = |_: &str| Ok(());
868        processor
869            .process_buffer(&mut buffer, &mut accumulated, &mut on_chunk)
870            .expect("drained event must pass");
871        assert!(buffer.is_empty());
872    }
873}