1use super::super::models::{Content, Part};
7use super::{StreamingCandidate, StreamingError, StreamingMetrics, StreamingResponse};
8use crate::providers::gemini::UNSUPPORTED_MEDIA_OUTPUT_MESSAGE;
9use futures::stream::StreamExt;
10use reqwest::Response;
11use serde_json::Value;
12use std::time::Instant;
13use tokio::time::{Duration, timeout};
14use tracing;
15
16#[derive(Debug, Clone)]
18pub struct StreamingConfig {
19 chunk_timeout: Duration,
21 first_chunk_timeout: Duration,
23 total_timeout: Duration,
25 buffer_size: usize,
27}
28
29impl Default for StreamingConfig {
30 fn default() -> Self {
31 Self {
32 chunk_timeout: Duration::from_secs(30),
33 first_chunk_timeout: Duration::from_secs(60),
34 total_timeout: Duration::from_secs(600),
35 buffer_size: 1024,
36 }
37 }
38}
39
40impl StreamingConfig {
41 pub(crate) fn with_total_timeout(total_timeout_secs: u64) -> Self {
43 Self {
44 total_timeout: Duration::from_secs(total_timeout_secs),
45 ..Default::default()
46 }
47 }
48}
49
50pub type ProgressCallback = Box<dyn Fn(f32) + Send + Sync>;
52
53pub struct StreamingProcessor {
55 config: StreamingConfig,
56 metrics: StreamingMetrics,
57 current_event_data: String,
58 progress_callback: Option<ProgressCallback>,
59 warning_threshold: f32,
60}
61
62impl StreamingProcessor {
63 pub(crate) fn new() -> Self {
65 Self {
66 config: StreamingConfig::default(),
67 metrics: StreamingMetrics::default(),
68 current_event_data: String::with_capacity(512),
70 progress_callback: None,
71 warning_threshold: 0.8,
72 }
73 }
74
75 pub(crate) fn with_config(config: StreamingConfig) -> Self {
77 Self {
78 config,
79 metrics: StreamingMetrics::default(),
80 current_event_data: String::with_capacity(512),
82 progress_callback: None,
83 warning_threshold: 0.8,
84 }
85 }
86
87 pub fn with_progress_callback(mut self, callback: ProgressCallback) -> Self {
89 self.progress_callback = Some(callback);
90 self
91 }
92
93 pub fn with_warning_threshold(mut self, threshold: f32) -> Self {
95 self.warning_threshold = threshold.clamp(0.0, 1.0);
96 self
97 }
98
99 pub(crate) async fn process_stream<F>(
113 &mut self,
114 response: Response,
115 mut on_chunk: F,
116 ) -> Result<StreamingResponse, StreamingError>
117 where
118 F: FnMut(&str) -> Result<(), StreamingError>,
119 {
120 self.metrics.request_start_time = Some(Instant::now());
121 self.metrics.total_requests += 1;
122 self.current_event_data.clear();
123
124 let mut stream = response.bytes_stream();
126
127 let mut accumulated_response = StreamingResponse { candidates: Vec::new(), usage_metadata: None };
128
129 let mut _has_valid_content = false;
130 let mut buffer = String::with_capacity(self.config.buffer_size);
132 let mut decoder = crate::providers::shared::Utf8StreamDecoder::new();
133 let request_start = Instant::now();
134
135 let first_chunk_start = Instant::now();
137 let first_chunk_result = timeout(self.config.first_chunk_timeout, stream.next()).await;
138
139 match first_chunk_result {
140 Ok(Some(Ok(bytes))) => {
141 self.metrics.first_chunk_time = Some(Instant::now());
142 self.metrics.total_bytes += bytes.len();
143 self.report_progress(first_chunk_start, request_start);
144
145 buffer.push_str(&decoder.push(&bytes));
147 match self.process_buffer(&mut buffer, &mut accumulated_response, &mut on_chunk) {
148 Ok(valid) => _has_valid_content = valid,
149 Err(e) => return Err(e),
150 }
151 }
152 Ok(Some(Err(e))) => {
153 self.metrics.error_count += 1;
154 return Err(StreamingError::NetworkError {
155 message: format!("Failed to read first chunk: {e}"),
156 is_retryable: true,
157 });
158 }
159 Ok(None) => {
160 return Err(StreamingError::StreamingError {
161 message: "Empty streaming response".to_owned(),
162 partial_content: None,
163 });
164 }
165 Err(_) => {
166 self.metrics.error_count += 1;
167 self.report_progress(first_chunk_start, request_start);
168 return Err(StreamingError::TimeoutError {
169 operation: "first_chunk".to_owned(),
170 duration: self.config.first_chunk_timeout,
171 });
172 }
173 }
174
175 while let Some(result) = stream.next().await {
177 let elapsed = request_start.elapsed();
178
179 if self.config.total_timeout.as_secs() > 0 {
181 if elapsed > self.config.total_timeout {
182 self.metrics.error_count += 1;
183 self.report_progress_at_timeout(elapsed);
184 return Err(StreamingError::TimeoutError {
185 operation: "streaming".to_owned(),
186 duration: elapsed,
187 });
188 }
189 self.report_progress_with_timeout(elapsed);
191 }
192
193 match result {
194 Ok(bytes) => {
195 self.metrics.total_bytes += bytes.len();
196
197 buffer.push_str(&decoder.push(&bytes));
199
200 match self.process_buffer(&mut buffer, &mut accumulated_response, &mut on_chunk) {
202 Ok(valid) => {
203 if valid {
204 _has_valid_content = true;
205 }
206 }
207 Err(e) => return Err(e),
208 }
209 }
210 Err(e) => {
211 self.metrics.error_count += 1;
212 self.report_progress_at_timeout(elapsed);
213 return Err(StreamingError::NetworkError {
214 message: format!("Failed to read chunk: {e}"),
215 is_retryable: true,
216 });
217 }
218 }
219
220 self.metrics.total_chunks += 1;
221 }
222
223 if !buffer.is_empty() {
225 match self.process_remaining_buffer(&mut buffer, &mut accumulated_response, &mut on_chunk) {
226 Ok(valid) => {
227 if valid {
228 _has_valid_content = true;
229 }
230 }
231 Err(e) => return Err(e),
232 }
233 }
234
235 if !_has_valid_content {
236 return Err(StreamingError::ContentError {
237 message: "No valid content received from streaming API".to_owned(),
238 });
239 }
240
241 Ok(accumulated_response)
242 }
243
244 fn process_buffer<F>(
245 &mut self,
246 buffer: &mut String,
247 accumulated_response: &mut StreamingResponse,
248 on_chunk: &mut F,
249 ) -> Result<bool, StreamingError>
250 where
251 F: FnMut(&str) -> Result<(), StreamingError>,
252 {
253 let mut _has_valid_content = false;
254 let mut processed_chars = 0;
255
256 while let Some(newline_pos) = buffer[processed_chars..].find('\n') {
257 let line_end = processed_chars + newline_pos;
258 let line = &buffer[processed_chars..line_end];
259 processed_chars = line_end + 1;
260
261 _has_valid_content |= self.handle_line(line, accumulated_response, on_chunk)?;
262 }
263
264 if processed_chars > 0 {
266 buffer.drain(..processed_chars);
267 }
268
269 crate::providers::shared::check_sse_tail_bound(buffer.len()).map_err(|overflow| {
275 StreamingError::StreamingError {
276 message: overflow.to_string(),
277 partial_content: None,
278 }
279 })?;
280
281 Ok(_has_valid_content)
282 }
283
284 fn process_remaining_buffer<F>(
286 &mut self,
287 buffer: &mut String,
288 accumulated_response: &mut StreamingResponse,
289 on_chunk: &mut F,
290 ) -> Result<bool, StreamingError>
291 where
292 F: FnMut(&str) -> Result<(), StreamingError>,
293 {
294 let mut _has_valid_content = false;
295
296 if !buffer.is_empty() {
297 let remaining_line = buffer.trim_end_matches('\r');
298 if !remaining_line.trim().is_empty() {
299 _has_valid_content |= self.handle_line(remaining_line, accumulated_response, on_chunk)?;
300 }
301 }
302
303 buffer.clear();
304
305 _has_valid_content |= self.finalize_current_event(accumulated_response, on_chunk)?;
306
307 Ok(_has_valid_content)
308 }
309
310 fn handle_line<F>(
312 &mut self,
313 raw_line: &str,
314 accumulated_response: &mut StreamingResponse,
315 on_chunk: &mut F,
316 ) -> Result<bool, StreamingError>
317 where
318 F: FnMut(&str) -> Result<(), StreamingError>,
319 {
320 let mut _has_valid_content = false;
321 let line = raw_line.trim_end_matches('\r');
322
323 if line.is_empty() {
324 _has_valid_content |= self.finalize_current_event(accumulated_response, on_chunk)?;
325 return Ok(_has_valid_content);
326 }
327
328 let trimmed = line.trim();
329
330 if trimmed.is_empty() {
331 return Ok(false);
332 }
333
334 if trimmed.starts_with(':') {
335 return Ok(false);
336 }
337
338 if trimmed.starts_with("event:") || trimmed.starts_with("id:") {
339 return Ok(false);
340 }
341
342 if let Some(data_segment) = trimmed.strip_prefix("data:") {
343 let data_segment = data_segment.trim_start();
344 if data_segment == "[DONE]" {
345 _has_valid_content |= self.finalize_current_event(accumulated_response, on_chunk)?;
346 return Ok(_has_valid_content);
347 }
348
349 if !data_segment.is_empty() {
350 if !self.current_event_data.is_empty() {
351 self.current_event_data.push('\n');
352 }
353 self.current_event_data.push_str(data_segment);
354
355 _has_valid_content |= self.try_flush_current_event(accumulated_response, on_chunk)?;
356 }
357 return Ok(_has_valid_content);
358 }
359
360 if trimmed.starts_with('{') || trimmed.starts_with('[') {
361 if !self.current_event_data.is_empty() {
362 self.current_event_data.push('\n');
363 }
364 self.current_event_data.push_str(trimmed);
365 return Ok(false);
366 }
367
368 if !self.current_event_data.is_empty() {
369 self.current_event_data.push('\n');
370 }
371 self.current_event_data.push_str(trimmed);
372
373 Ok(false)
374 }
375
376 fn finalize_current_event<F>(
377 &mut self,
378 accumulated_response: &mut StreamingResponse,
379 on_chunk: &mut F,
380 ) -> Result<bool, StreamingError>
381 where
382 F: FnMut(&str) -> Result<(), StreamingError>,
383 {
384 if self.current_event_data.trim().is_empty() {
385 self.current_event_data.clear();
386 return Ok(false);
387 }
388
389 let event_data = std::mem::take(&mut self.current_event_data);
390 self.process_event(event_data, accumulated_response, on_chunk)
391 }
392
393 fn try_flush_current_event<F>(
394 &mut self,
395 accumulated_response: &mut StreamingResponse,
396 on_chunk: &mut F,
397 ) -> Result<bool, StreamingError>
398 where
399 F: FnMut(&str) -> Result<(), StreamingError>,
400 {
401 let trimmed = self.current_event_data.trim();
402 if trimmed.is_empty() {
403 return Ok(false);
404 }
405
406 match serde_json::from_str::<Value>(trimmed) {
407 Ok(parsed) => {
408 self.current_event_data.clear();
409 self.process_event_value(parsed, accumulated_response, on_chunk)
410 }
411 Err(parse_err) => {
412 if parse_err.is_eof() {
413 return Ok(false);
414 }
415
416 Err(StreamingError::ParseError {
417 message: format!("Failed to parse streaming JSON: {parse_err}"),
418 raw_response: trimmed.to_owned(),
419 })
420 }
421 }
422 }
423
424 fn process_event<F>(
425 &mut self,
426 event_data: String,
427 accumulated_response: &mut StreamingResponse,
428 on_chunk: &mut F,
429 ) -> Result<bool, StreamingError>
430 where
431 F: FnMut(&str) -> Result<(), StreamingError>,
432 {
433 let trimmed = event_data.trim();
434
435 if trimmed.is_empty() {
436 return Ok(false);
437 }
438
439 match serde_json::from_str::<Value>(trimmed) {
440 Ok(parsed) => self.process_event_value(parsed, accumulated_response, on_chunk),
441 Err(parse_err) => {
442 if parse_err.is_eof() {
443 self.current_event_data = trimmed.to_owned();
444 return Ok(false);
445 }
446
447 Err(StreamingError::ParseError {
448 message: format!("Failed to parse streaming JSON: {parse_err}"),
449 raw_response: trimmed.to_owned(),
450 })
451 }
452 }
453 }
454
455 fn append_text_candidate(&mut self, accumulated_response: &mut StreamingResponse, text: &str) {
456 if text.is_empty() {
457 return;
458 }
459
460 if let Some(last_candidate) = accumulated_response.candidates.last_mut() {
461 Self::merge_parts(
462 &mut last_candidate.content.parts,
463 vec![Part::Text { text: text.to_owned(), thought_signature: None }],
464 );
465 return;
466 }
467
468 let index = accumulated_response.candidates.len();
469
470 accumulated_response.candidates.push(StreamingCandidate {
471 content: Content {
472 role: "model".to_owned(),
473 parts: vec![Part::Text { text: text.to_owned(), thought_signature: None }],
474 },
475 finish_reason: None,
476 index: Some(index),
477 });
478 }
479
480 fn process_candidate<F>(&self, candidate: &StreamingCandidate, on_chunk: &mut F) -> Result<bool, StreamingError>
482 where
483 F: FnMut(&str) -> Result<(), StreamingError>,
484 {
485 if candidate
486 .content
487 .parts
488 .iter()
489 .any(|part| matches!(part, Part::InlineData { .. }))
490 {
491 return Err(StreamingError::ContentError {
492 message: UNSUPPORTED_MEDIA_OUTPUT_MESSAGE.to_owned(),
493 });
494 }
495
496 let mut _has_valid_content = false;
497
498 if candidate.finish_reason.is_some() {
499 _has_valid_content = true;
500 }
501
502 for part in &candidate.content.parts {
504 match part {
505 Part::Text { text, .. } => {
506 if !text.trim().is_empty() {
507 on_chunk(text)?;
508 _has_valid_content = true;
509 }
510 }
511 Part::InlineData { .. } => {
512 return Err(StreamingError::ContentError {
513 message: UNSUPPORTED_MEDIA_OUTPUT_MESSAGE.to_owned(),
514 });
515 }
516 Part::FunctionCall { .. } => {
517 _has_valid_content = true;
519 }
520 Part::FunctionResponse { .. } => {
521 _has_valid_content = true;
522 }
523 Part::ToolCall { .. }
524 | Part::ToolResponse { .. }
525 | Part::ExecutableCode { .. }
526 | Part::CodeExecutionResult { .. } => {
527 _has_valid_content = true;
528 }
529 Part::CacheControl { .. } => {}
530 }
531 }
532
533 Ok(_has_valid_content)
534 }
535
536 fn process_event_value<F>(
537 &mut self,
538 value: Value,
539 accumulated_response: &mut StreamingResponse,
540 on_chunk: &mut F,
541 ) -> Result<bool, StreamingError>
542 where
543 F: FnMut(&str) -> Result<(), StreamingError>,
544 {
545 match value {
546 Value::Array(items) => {
547 let mut has_valid = false;
548 for item in items {
549 if self.process_event_value(item, accumulated_response, on_chunk)? {
550 has_valid = true;
551 }
552 }
553 Ok(has_valid)
554 }
555 Value::Object(mut map) => {
556 if let Some(error_value) = map.get("error") {
557 let message = error_value
558 .get("message")
559 .and_then(Value::as_str)
560 .unwrap_or("Gemini streaming error")
561 .to_owned();
562 #[allow(
563 clippy::cast_sign_loss,
564 reason = "Intentional compatibility, platform, or test-only suppression."
565 )]
566 let code = error_value.get("code").and_then(Value::as_i64).unwrap_or(500) as u16;
567 return Err(StreamingError::ApiError {
568 status_code: code,
569 message,
570 is_retryable: code == 429,
571 });
572 }
573
574 if let Some(usage) = map.remove("usageMetadata") {
575 accumulated_response.usage_metadata = Some(usage);
576 }
577
578 let mut has_valid = false;
579
580 if let Some(candidates_value) = map.remove("candidates") {
581 let candidate_values: Vec<Value> = match candidates_value {
582 Value::Array(items) => items,
583 Value::Object(_) => vec![candidates_value],
584 _ => Vec::new(),
585 };
586
587 for candidate_value in candidate_values {
588 match serde_json::from_value::<StreamingCandidate>(candidate_value.clone()) {
589 Ok(candidate) => {
590 if self.process_candidate(&candidate, on_chunk)? {
591 has_valid = true;
592 }
593 self.merge_candidate(accumulated_response, candidate);
594 }
595 Err(err) => {
596 if let Some(text) = Self::extract_text_from_value(&candidate_value) {
597 if !text.trim().is_empty() {
598 on_chunk(&text)?;
599 self.append_text_candidate(accumulated_response, &text);
600 has_valid = true;
601 }
602 } else {
603 return Err(StreamingError::ParseError {
604 message: format!("Failed to parse candidate: {err}"),
605 raw_response: candidate_value.to_string(),
606 });
607 }
608 }
609 }
610 }
611 }
612
613 if let Some(text_value) = map.remove("text").and_then(|v| v.as_str().map(|s| s.to_owned()))
614 && !text_value.trim().is_empty()
615 {
616 on_chunk(&text_value)?;
617 self.append_text_candidate(accumulated_response, &text_value);
618 has_valid = true;
619 }
620
621 Ok(has_valid)
622 }
623 Value::String(text) => {
624 if text.trim().is_empty() {
625 Ok(false)
626 } else {
627 on_chunk(&text)?;
628 self.append_text_candidate(accumulated_response, &text);
629 Ok(true)
630 }
631 }
632 _ => Ok(false),
633 }
634 }
635
636 fn merge_candidate(&mut self, accumulated_response: &mut StreamingResponse, mut candidate: StreamingCandidate) {
637 let index = candidate.index.unwrap_or(accumulated_response.candidates.len());
638
639 if let Some(existing) = accumulated_response
640 .candidates
641 .iter_mut()
642 .find(|existing| existing.index.unwrap_or(index) == index)
643 {
644 if existing.content.role.is_empty() {
645 existing.content.role = candidate.content.role.clone();
646 }
647
648 Self::merge_parts(&mut existing.content.parts, candidate.content.parts);
649
650 if candidate.finish_reason.is_some() {
651 existing.finish_reason = candidate.finish_reason;
652 }
653 } else {
654 candidate.index = Some(index);
655 accumulated_response.candidates.push(candidate);
656 }
657 }
658
659 fn merge_parts(target: &mut Vec<Part>, source_parts: Vec<Part>) {
660 if target.is_empty() {
661 *target = source_parts;
662 return;
663 }
664
665 for part in source_parts {
666 match (target.last_mut(), &part) {
667 (
668 Some(Part::Text { text: existing, thought_signature: existing_sig }),
669 Part::Text { text: new_text, thought_signature: new_sig },
670 ) => {
671 existing.push_str(new_text);
672 if existing_sig.is_none() && new_sig.is_some() {
674 *existing_sig = new_sig.clone();
675 }
676 }
677 _ => target.push(part),
678 }
679 }
680 }
681
682 fn extract_text_from_value(value: &Value) -> Option<String> {
683 match value {
684 Value::String(text) => {
685 if text.trim().is_empty() {
686 None
687 } else {
688 Some(text.clone())
689 }
690 }
691 Value::Array(items) => Self::extract_text_from_array(items),
692 Value::Object(map) => {
693 if let Some(text) = map.get("text").and_then(Value::as_str)
694 && !text.trim().is_empty()
695 {
696 return Some(text.to_owned());
697 }
698
699 if let Some(parts) = map.get("parts").and_then(Value::as_array)
700 && let Some(parts_text) = Self::extract_text_from_array(parts)
701 {
702 return Some(parts_text);
703 }
704
705 for nested in map.values() {
706 if let Some(nested_text) = Self::extract_text_from_value(nested)
707 && !nested_text.trim().is_empty()
708 {
709 return Some(nested_text);
710 }
711 }
712
713 None
714 }
715 _ => None,
716 }
717 }
718
719 fn extract_text_from_array(items: &[Value]) -> Option<String> {
723 let mut collected = String::new();
724 for item in items {
725 if let Some(fragment) = Self::extract_text_from_value(item) {
726 collected.push_str(&fragment);
727 }
728 }
729 if collected.is_empty() { None } else { Some(collected) }
730 }
731
732 fn report_progress_with_timeout(&self, elapsed: Duration) {
734 if self.config.total_timeout.as_secs() == 0 {
735 return;
736 }
737
738 let progress = elapsed.as_secs_f32() / self.config.total_timeout.as_secs_f32();
739 let progress_clamped = progress.min(0.99); if let Some(ref callback) = self.progress_callback {
742 callback(progress_clamped);
743 }
744
745 if progress >= self.warning_threshold {
747 tracing::warn!(
748 "Streaming operation at {:.0}% of timeout limit ({}/{:?} elapsed). Approaching timeout.",
749 progress_clamped * 100.0,
750 elapsed.as_secs(),
751 self.config.total_timeout
752 );
753 }
754 }
755
756 fn report_progress_at_timeout(&self, _elapsed: Duration) {
758 if let Some(ref callback) = self.progress_callback {
759 callback(1.0); }
761 }
762
763 fn report_progress(&self, _event_time: Instant, _start_time: Instant) {
765 if let Some(ref callback) = self.progress_callback {
766 callback(0.1); }
768 }
769
770 fn metrics(&self) -> &StreamingMetrics {
772 &self.metrics
773 }
774
775 pub fn reset_metrics(&mut self) {
777 self.metrics = StreamingMetrics::default();
778 }
779}
780
781impl Default for StreamingProcessor {
782 fn default() -> Self {
783 Self::new()
784 }
785}
786
787#[cfg(test)]
788mod tests;