1use a2a_protocol_types::{JsonRpcResponse, StreamResponse};
48use hyper::body::Bytes;
49use tokio::sync::mpsc;
50use tokio::task::AbortHandle;
51
52use crate::error::{ClientError, ClientResult};
53use crate::streaming::sse_parser::SseParser;
54
55#[cfg(feature = "tracing")]
56pub(crate) mod call;
57mod poll;
58#[cfg(test)]
59mod stream_tests;
60
61pub(crate) type BodyChunk = ClientResult<Bytes>;
65
66const EVENT_BRIDGE_CAPACITY: usize = 64;
72
73pub struct EventStream {
113 rx: mpsc::Receiver<BodyChunk>,
115 parser: SseParser,
117 phase: Phase,
119 abort_handle: Option<AbortHandle>,
121 status_code: u16,
128 jsonrpc_envelope: bool,
134 first_event_timeout: Option<std::time::Duration>,
142 idle_timeout: Option<std::time::Duration>,
145 last_activity: tokio::time::Instant,
150 first_chunk_received: bool,
153 silence: Option<poll::Silence>,
159 at_final_event: bool,
163 events_received: u64,
165 last_event_id: Option<String>,
167 held: Option<
180 Box<dyn std::any::Any + Send + Sync + std::panic::UnwindSafe + std::panic::RefUnwindSafe>,
181 >,
182 #[cfg(feature = "tracing")]
187 call: Option<std::panic::AssertUnwindSafe<Box<call::StreamCall>>>,
188 content: crate::content::ContentKeys,
190 expected_id: Option<serde_json::Value>,
194}
195
196impl EventStream {
197 #[must_use]
203 #[cfg(any(test, feature = "websocket"))]
204 pub(crate) fn new(rx: mpsc::Receiver<BodyChunk>) -> Self {
205 Self {
206 rx,
207 parser: SseParser::new(),
208 phase: Phase::Open,
209 abort_handle: None,
210 status_code: 200,
211 jsonrpc_envelope: true,
212 first_event_timeout: None,
213 idle_timeout: Some(crate::config::DEFAULT_STREAM_IDLE_TIMEOUT),
214 last_activity: tokio::time::Instant::now(),
215 first_chunk_received: false,
216 silence: None,
217 at_final_event: false,
218 events_received: 0,
219 last_event_id: None,
220 held: None,
221 #[cfg(feature = "tracing")]
222 call: None,
223 content: crate::content::ContentKeys::default(),
224 expected_id: None,
225 }
226 }
227
228 #[must_use]
233 #[cfg(test)]
234 pub(crate) fn with_abort_handle(
235 rx: mpsc::Receiver<BodyChunk>,
236 abort_handle: AbortHandle,
237 ) -> Self {
238 Self {
239 rx,
240 parser: SseParser::new(),
241 phase: Phase::Open,
242 abort_handle: Some(abort_handle),
243 status_code: 200,
244 jsonrpc_envelope: true,
245 first_event_timeout: None,
246 idle_timeout: Some(crate::config::DEFAULT_STREAM_IDLE_TIMEOUT),
247 last_activity: tokio::time::Instant::now(),
248 first_chunk_received: false,
249 silence: None,
250 at_final_event: false,
251 events_received: 0,
252 last_event_id: None,
253 held: None,
254 #[cfg(feature = "tracing")]
255 call: None,
256 content: crate::content::ContentKeys::default(),
257 expected_id: None,
258 }
259 }
260
261 #[must_use]
308 pub fn from_event_channel(mut rx: mpsc::Receiver<ClientResult<StreamResponse>>) -> Self {
309 let (tx, body_rx) = mpsc::channel::<BodyChunk>(EVENT_BRIDGE_CAPACITY);
310
311 let bridge = tokio::spawn(async move {
317 while let Some(event) = rx.recv().await {
318 let chunk = match event {
319 Ok(ref ev) => serde_json::to_string(ev).map_or_else(
320 |e| Err(ClientError::Serialization(e)),
321 |json| {
322 Ok(Bytes::from(format!(
323 "data: {{\"jsonrpc\":\"2.0\",\"id\":null,\"result\":{json}}}\n\n"
324 )))
325 },
326 ),
327 Err(e) => Err(e),
328 };
329 if tx.send(chunk).await.is_err() {
330 break;
331 }
332 }
333 });
334
335 Self::with_status(body_rx, bridge.abort_handle(), 200)
336 }
337
338 #[must_use]
341 pub(crate) fn with_status(
342 rx: mpsc::Receiver<BodyChunk>,
343 abort_handle: AbortHandle,
344 status_code: u16,
345 ) -> Self {
346 Self {
347 rx,
348 parser: SseParser::new(),
349 phase: Phase::Open,
350 abort_handle: Some(abort_handle),
351 status_code,
352 jsonrpc_envelope: true,
353 first_event_timeout: None,
354 idle_timeout: Some(crate::config::DEFAULT_STREAM_IDLE_TIMEOUT),
355 last_activity: tokio::time::Instant::now(),
356 first_chunk_received: false,
357 silence: None,
358 at_final_event: false,
359 events_received: 0,
360 last_event_id: None,
361 held: None,
362 #[cfg(feature = "tracing")]
363 call: None,
364 content: crate::content::ContentKeys::default(),
365 expected_id: None,
366 }
367 }
368
369 #[must_use]
381 pub(crate) fn expecting_id(mut self, id: serde_json::Value) -> Self {
382 self.expected_id = Some(id);
383 self
384 }
385
386 #[must_use]
391 #[cfg_attr(not(feature = "signing"), allow(clippy::missing_const_for_fn))]
394 pub(crate) fn with_content_keys(mut self, content: crate::content::ContentKeys) -> Self {
395 self.content = content;
396 self
397 }
398
399 pub(crate) const fn with_jsonrpc_envelope(mut self, envelope: bool) -> Self {
400 self.jsonrpc_envelope = envelope;
401 self
402 }
403
404 #[must_use]
419 pub const fn with_first_event_timeout(mut self, timeout: std::time::Duration) -> Self {
420 self.first_event_timeout = Some(timeout);
421 self
422 }
423
424 #[must_use]
439 pub const fn with_idle_timeout(mut self, timeout: Option<std::time::Duration>) -> Self {
440 self.idle_timeout = timeout;
441 self
442 }
443
444 #[must_use]
450 pub const fn with_max_event_size(mut self, max_bytes: usize) -> Self {
451 self.parser.set_max_event_size(max_bytes);
452 self
453 }
454
455 #[must_use]
474 pub(crate) fn holding(
475 mut self,
476 resource: impl std::any::Any
477 + Send
478 + Sync
479 + std::panic::UnwindSafe
480 + std::panic::RefUnwindSafe
481 + 'static,
482 ) -> Self {
483 self.held = Some(Box::new((self.held.take(), resource)));
484 self
485 }
486
487 #[must_use]
492 pub const fn status_code(&self) -> u16 {
493 self.status_code
494 }
495
496 #[must_use]
507 pub fn last_event_id(&self) -> Option<&str> {
508 self.last_event_id.as_deref()
509 }
510
511 pub async fn next(&mut self) -> Option<ClientResult<StreamResponse>> {
529 std::future::poll_fn(|cx| self.poll_next_checked(cx)).await
530 }
531
532 fn silence_deadline(&self) -> Option<(tokio::time::Instant, std::time::Duration)> {
541 let bound = if self.first_chunk_received {
542 self.idle_timeout
543 } else {
544 self.first_event_timeout
545 }?;
546 Some((self.last_activity.checked_add(bound)?, bound))
547 }
548
549 fn fail_silent(&mut self, bound: std::time::Duration) -> ClientError {
554 self.phase = Phase::Finished;
555 if let Some(handle) = self.abort_handle.take() {
556 handle.abort();
557 }
558 if self.first_chunk_received {
559 ClientError::Timeout(format!(
560 "stream idle timeout: no data, not even a keep-alive comment, for {bound:?} \
561 since the last data received; the task on the server is not cancelled, \
562 so resubscribe to continue"
563 ))
564 } else {
565 ClientError::Timeout(format!(
566 "stream produced no data before the first-event timeout ({bound:?})"
567 ))
568 }
569 }
570
571 fn judge_end(&self) -> Option<ClientError> {
574 let partial = self.parser.incomplete_event_len();
575 if self.at_final_event {
576 if let Some(bytes) = partial {
577 trace_warn!(
580 bytes,
581 "SSE body ended mid-frame after the stream's final event; \
582 discarding the unterminated frame"
583 );
584 let _ = bytes;
585 }
586 return None;
587 }
588 let detail = match (partial, self.events_received) {
589 (Some(bytes), _) => format!(
590 "the connection closed mid-frame, discarding {bytes} bytes of an \
591 unterminated event"
592 ),
593 (None, 0) => "the body ended before any event".to_owned(),
594 (None, n) => format!(
595 "the body ended after {n} event(s), none of them a final one \
596 (a Message, or a terminal or interrupted task state)"
597 ),
598 };
599 Some(ClientError::IncompleteStream {
600 last_event_id: self.last_event_id.clone(),
601 detail,
602 })
603 }
604
605 const fn record(&mut self, event: &StreamResponse) {
607 self.events_received += 1;
608 self.at_final_event = ends_stream(event);
609 }
610
611 fn decode_frame(&mut self, data: &str) -> ClientResult<StreamResponse> {
612 if self.jsonrpc_envelope {
613 let envelope: JsonRpcResponse<StreamResponse> =
615 serde_json::from_str(data).map_err(ClientError::Serialization)?;
616
617 match envelope {
618 JsonRpcResponse::Success(ok) => {
619 if self
620 .expected_id
621 .as_ref()
622 .is_some_and(|expected| ok.id.as_ref() != Some(expected))
623 {
624 let _expected = self.expected_id.take();
626 trace_warn!(
627 expected = ?_expected,
628 got = ?ok.id,
629 "JSON-RPC stream frame id mismatch: the frame does not echo \
630 the request id (spec §9.4.2); delivered, since the HTTP \
631 response binds it to this request"
632 );
633 }
634 self.record(&ok.result);
635 if is_terminal(&ok.result) {
636 self.phase = Phase::Finished;
637 }
638 Ok(ok.result)
639 }
640 JsonRpcResponse::Error(err) => {
641 self.phase = Phase::Finished;
642 Err(crate::transport::jsonrpc_client_error(
643 err.error.code,
644 err.error.message,
645 err.error.data,
646 ))
647 }
648 }
649 } else {
650 let event: StreamResponse = match serde_json::from_str(data) {
655 Ok(event) => event,
656 Err(e) => {
657 return Err(
658 match crate::transport::rest::error_frame::decode_stream_error_frame(data) {
659 Some(a2a) => {
660 self.phase = Phase::Finished;
661 ClientError::Protocol(a2a)
662 }
663 None => ClientError::Serialization(e),
664 },
665 );
666 }
667 };
668 self.record(&event);
669 if is_terminal(&event) {
670 self.phase = Phase::Finished;
671 }
672 Ok(event)
673 }
674 }
675}
676
677#[cfg(not(feature = "tracing"))]
679impl EventStream {
680 #[allow(clippy::unused_self, clippy::needless_pass_by_ref_mut)]
681 pub(crate) const fn fail_call(&mut self, _: &ClientError) {}
682}
683
684impl Drop for EventStream {
685 fn drop(&mut self) {
686 #[cfg(feature = "tracing")]
687 if self.phase != Phase::Finished
688 && let Some(call) = self.call.as_mut()
689 {
690 call.0.abandon();
691 }
692 if let Some(handle) = self.abort_handle.take() {
693 handle.abort();
694 }
695 drop(self.held.take());
702 }
703}
704
705#[allow(clippy::missing_fields_in_debug)]
706impl std::fmt::Debug for EventStream {
707 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
708 f.debug_struct("EventStream")
710 .field("done", &(self.phase == Phase::Finished))
711 .field("pending_frames", &self.parser.pending_count())
712 .finish()
713 }
714}
715
716#[derive(Debug, Clone, Copy, PartialEq, Eq)]
718enum Phase {
719 Open,
721 BodyEnded,
724 Finished,
726}
727
728const fn ends_stream(event: &StreamResponse) -> bool {
739 let state = match event {
740 StreamResponse::Message(_) => return true,
741 StreamResponse::Task(task) => task.status.state,
742 StreamResponse::StatusUpdate(update) => update.status.state,
743 _ => return false,
744 };
745 state.is_terminal() || state.is_interrupted()
746}
747
748const fn is_terminal(event: &StreamResponse) -> bool {
750 matches!(
751 event,
752 StreamResponse::StatusUpdate(ev) if ev.status.state.is_terminal()
753 )
754}
755
756#[cfg(test)]
770const fn _event_stream_is_unwind_safe() {
771 const fn assert_unwind_safe<T: std::panic::UnwindSafe + std::panic::RefUnwindSafe>() {}
772 assert_unwind_safe::<EventStream>();
773}
774
775#[cfg(test)]
776mod tests {
777 use super::*;
778 use a2a_protocol_types::{
779 JsonRpcSuccessResponse, JsonRpcVersion, TaskId, TaskState, TaskStatus,
780 TaskStatusUpdateEvent,
781 };
782 use std::time::Duration;
783
784 const TEST_TIMEOUT: Duration = Duration::from_secs(5);
787
788 fn make_status_event(state: TaskState, _is_final: bool) -> StreamResponse {
789 StreamResponse::StatusUpdate(TaskStatusUpdateEvent::new(
790 TaskId::new("t1"),
791 a2a_protocol_types::ContextId::new("c1"),
792 TaskStatus::new(state),
793 ))
794 }
795
796 fn sse_frame(event: &StreamResponse) -> String {
797 let resp = JsonRpcSuccessResponse {
798 jsonrpc: JsonRpcVersion,
799 id: Some(serde_json::json!(1)),
800 result: event.clone(),
801 };
802 let json = serde_json::to_string(&resp).unwrap();
803 format!("data: {json}\n\n")
804 }
805
806 #[tokio::test]
807 async fn stream_delivers_events() {
808 let (tx, rx) = mpsc::channel(8);
809 let mut stream = EventStream::new(rx);
810
811 let event = make_status_event(TaskState::Working, false);
812 let sse_bytes = sse_frame(&event);
813 tx.send(Ok(Bytes::from(sse_bytes))).await.unwrap();
814 drop(tx);
815
816 let result = tokio::time::timeout(TEST_TIMEOUT, stream.next())
817 .await
818 .expect("timed out")
819 .unwrap()
820 .unwrap();
821 assert!(
822 matches!(result, StreamResponse::StatusUpdate(ref ev) if ev.status.state == TaskState::Working)
823 );
824 }
825
826 #[tokio::test]
827 async fn stream_ends_on_final_event() {
828 let (tx, rx) = mpsc::channel(8);
829 let mut stream = EventStream::new(rx);
830
831 let event = make_status_event(TaskState::Completed, true);
832 let sse_bytes = sse_frame(&event);
833 tx.send(Ok(Bytes::from(sse_bytes))).await.unwrap();
834
835 let result = tokio::time::timeout(TEST_TIMEOUT, stream.next())
837 .await
838 .expect("timed out waiting for final event")
839 .unwrap()
840 .unwrap();
841 assert!(
842 matches!(result, StreamResponse::StatusUpdate(ref ev) if ev.status.state == TaskState::Completed)
843 );
844
845 let end = tokio::time::timeout(TEST_TIMEOUT, stream.next())
847 .await
848 .expect("timed out waiting for stream end");
849 assert!(end.is_none());
850 }
851
852 #[tokio::test]
853 async fn stream_propagates_body_error() {
854 let (tx, rx) = mpsc::channel(8);
855 let mut stream = EventStream::new(rx);
856
857 tx.send(Err(ClientError::Transport("network error".into())))
858 .await
859 .unwrap();
860
861 let result = tokio::time::timeout(TEST_TIMEOUT, stream.next())
862 .await
863 .expect("timed out")
864 .unwrap();
865 assert!(result.is_err());
866 }
867
868 #[tokio::test]
871 async fn a_channel_closed_before_any_event_is_incomplete() {
872 let (tx, rx) = mpsc::channel(8);
873 let mut stream = EventStream::new(rx);
874 drop(tx);
875
876 let result = tokio::time::timeout(TEST_TIMEOUT, stream.next())
877 .await
878 .expect("timed out");
879 match result {
880 Some(Err(ClientError::IncompleteStream {
881 last_event_id,
882 detail,
883 })) => {
884 assert_eq!(last_event_id, None);
885 assert_eq!(detail, "the body ended before any event");
886 }
887 other => panic!("expected IncompleteStream, got {other:?}"),
888 }
889 assert!(
890 stream.next().await.is_none(),
891 "reported once, then finished"
892 );
893 }
894
895 #[tokio::test]
898 async fn the_end_of_the_body_is_judged_by_the_last_event() {
899 for (states, clean) in [
900 (vec![TaskState::Working, TaskState::InputRequired], true),
901 (vec![TaskState::Working, TaskState::AuthRequired], true),
902 (vec![TaskState::InputRequired, TaskState::Working], false),
903 (vec![TaskState::Submitted, TaskState::Working], false),
904 ] {
905 let (tx, rx) = mpsc::channel(8);
906 let mut stream = EventStream::new(rx).with_jsonrpc_envelope(false);
907 for state in &states {
908 let ev = make_status_event(*state, false);
909 tx.send(Ok(Bytes::from(bare_sse_frame(&ev)))).await.unwrap();
910 }
911 drop(tx);
912 for _ in &states {
913 assert!(matches!(stream.next().await, Some(Ok(_))), "{states:?}");
914 }
915 let end = stream.next().await;
916 if clean {
917 assert!(end.is_none(), "{states:?}: a completion, got {end:?}");
918 } else {
919 match end {
920 Some(Err(ClientError::IncompleteStream { detail, .. })) => {
921 assert!(detail.contains("after 2 event(s)"), "{detail}");
922 }
923 other => panic!("{states:?}: expected IncompleteStream, got {other:?}"),
924 }
925 }
926 assert!(stream.next().await.is_none());
927 }
928 }
929
930 #[test]
933 fn ends_stream_covers_final_events_only() {
934 use a2a_protocol_types::{Message, MessageId, MessageRole, Part, Task};
935 for state in [
936 TaskState::Completed,
937 TaskState::Failed,
938 TaskState::Canceled,
939 TaskState::Rejected,
940 TaskState::InputRequired,
941 TaskState::AuthRequired,
942 ] {
943 assert!(ends_stream(&make_status_event(state, false)), "{state:?}");
944 }
945 for state in [TaskState::Submitted, TaskState::Working] {
946 assert!(!ends_stream(&make_status_event(state, false)), "{state:?}");
947 }
948 let task = |state| {
949 StreamResponse::Task(Task::new(
950 TaskId::new("t"),
951 a2a_protocol_types::ContextId::new("c"),
952 TaskStatus::new(state),
953 ))
954 };
955 assert!(ends_stream(&task(TaskState::Completed)));
956 assert!(ends_stream(&task(TaskState::InputRequired)));
957 assert!(!ends_stream(&task(TaskState::Working)));
958 let message = StreamResponse::Message(Message::new(
959 MessageId::new("m"),
960 MessageRole::Agent,
961 vec![Part::text("hi")],
962 ));
963 assert!(ends_stream(&message));
964 }
965
966 #[tokio::test]
969 async fn a_partial_frame_after_the_final_event_is_not_an_error() {
970 let (tx, rx) = mpsc::channel(8);
971 let mut stream = EventStream::new(rx).with_jsonrpc_envelope(false);
972 let ev = make_status_event(TaskState::InputRequired, false);
973 tx.send(Ok(Bytes::from(bare_sse_frame(&ev)))).await.unwrap();
974 tx.send(Ok(Bytes::from_static(b"data: {\"trunc")))
975 .await
976 .unwrap();
977 drop(tx);
978 assert!(matches!(stream.next().await, Some(Ok(_))));
979 assert!(stream.next().await.is_none());
980 }
981
982 #[tokio::test]
985 async fn last_event_id_persists_across_frames_without_one() {
986 let (tx, rx) = mpsc::channel(8);
987 let mut stream = EventStream::new(rx).with_jsonrpc_envelope(false);
988 let ev = bare_sse_frame(&make_status_event(TaskState::Working, false));
989 tx.send(Ok(Bytes::from(format!("id: 4\n{ev}{ev}"))))
990 .await
991 .unwrap();
992 assert!(matches!(stream.next().await, Some(Ok(_))));
993 assert_eq!(stream.last_event_id(), Some("4"));
994 assert!(matches!(stream.next().await, Some(Ok(_))));
995 assert_eq!(stream.last_event_id(), Some("4"), "persists");
996 }
997
998 #[tokio::test]
1006 async fn from_event_channel_delivers_events() {
1007 let (tx, rx) = mpsc::channel(8);
1008 let mut stream = EventStream::from_event_channel(rx);
1009
1010 let event = StreamResponse::StatusUpdate(TaskStatusUpdateEvent::new(
1011 TaskId::new("task-1"),
1012 a2a_protocol_types::ContextId::new("ctx-1"),
1013 TaskStatus::new(TaskState::Working),
1014 ));
1015 tx.send(Ok(event)).await.expect("send");
1016 drop(tx);
1017
1018 let received = tokio::time::timeout(TEST_TIMEOUT, stream.next())
1019 .await
1020 .expect("timed out")
1021 .expect("a sent event must arrive")
1022 .expect("and must not be an error");
1023
1024 match received {
1025 StreamResponse::StatusUpdate(ev) => {
1026 assert_eq!(ev.task_id, TaskId::new("task-1"));
1027 assert_eq!(ev.status.state, TaskState::Working);
1028 }
1029 other => panic!("expected a status update, got {other:?}"),
1030 }
1031 }
1032
1033 #[tokio::test]
1037 async fn from_event_channel_propagates_errors() {
1038 let (tx, rx) = mpsc::channel(8);
1039 let mut stream = EventStream::from_event_channel(rx);
1040
1041 tx.send(Err(ClientError::Transport("frame decode failed".into())))
1042 .await
1043 .expect("send");
1044 drop(tx);
1045
1046 let received = tokio::time::timeout(TEST_TIMEOUT, stream.next())
1047 .await
1048 .expect("timed out")
1049 .expect("an error must be delivered, not swallowed");
1050
1051 assert!(
1052 matches!(received, Err(ClientError::Transport(ref m)) if m == "frame decode failed"),
1053 "the transport's own error must survive the bridge: {received:?}"
1054 );
1055 }
1056
1057 #[tokio::test]
1060 async fn from_event_channel_ends_when_sender_drops() {
1061 let (tx, rx) = mpsc::channel::<ClientResult<StreamResponse>>(8);
1062 let mut stream = EventStream::from_event_channel(rx);
1063 drop(tx);
1064
1065 let result = tokio::time::timeout(TEST_TIMEOUT, stream.next())
1066 .await
1067 .expect("timed out");
1068
1069 assert!(
1070 matches!(result, Some(Err(ClientError::IncompleteStream { .. }))),
1071 "closing before a final event is incomplete: {result:?}"
1072 );
1073 assert!(stream.next().await.is_none(), "and then the stream ends");
1074 }
1075
1076 #[tokio::test]
1080 async fn from_event_channel_honours_terminal_events() {
1081 let (tx, rx) = mpsc::channel(8);
1082 let mut stream = EventStream::from_event_channel(rx);
1083
1084 tx.send(Ok(StreamResponse::StatusUpdate(
1085 TaskStatusUpdateEvent::new(
1086 TaskId::new("task-1"),
1087 a2a_protocol_types::ContextId::new("ctx-1"),
1088 TaskStatus::new(TaskState::Completed),
1089 ),
1090 )))
1091 .await
1092 .expect("send");
1093
1094 let first = tokio::time::timeout(TEST_TIMEOUT, stream.next())
1095 .await
1096 .expect("timed out")
1097 .expect("the terminal event itself is delivered");
1098 assert!(first.is_ok());
1099
1100 let next = tokio::time::timeout(TEST_TIMEOUT, stream.next())
1103 .await
1104 .expect("timed out");
1105 assert!(
1106 next.is_none(),
1107 "a terminal event must end the stream even with the sender alive"
1108 );
1109 }
1110
1111 #[tokio::test]
1112 async fn drop_aborts_background_task() {
1113 let (tx, rx) = mpsc::channel::<BodyChunk>(8);
1114 let handle = tokio::spawn(async move {
1116 let _tx = tx;
1118 tokio::time::sleep(Duration::from_hours(1)).await;
1120 });
1121 let abort_handle = handle.abort_handle();
1122 let stream = EventStream::with_abort_handle(rx, abort_handle);
1123 drop(stream);
1125 let result = tokio::time::timeout(TEST_TIMEOUT, handle)
1127 .await
1128 .expect("timed out waiting for task abort");
1129 assert!(result.is_err(), "task should have been aborted");
1130 assert!(
1131 result.unwrap_err().is_cancelled(),
1132 "task should be cancelled"
1133 );
1134 }
1135
1136 #[test]
1137 fn debug_output_contains_fields() {
1138 let (_tx, rx) = mpsc::channel::<BodyChunk>(8);
1139 let stream = EventStream::new(rx);
1140 let debug = format!("{stream:?}");
1141 assert!(debug.contains("EventStream"), "should contain struct name");
1142 assert!(debug.contains("done: false"), "a fresh stream is not done");
1143 assert!(
1144 debug.contains("pending_frames"),
1145 "should contain 'pending_frames' field"
1146 );
1147 }
1148
1149 #[tokio::test]
1151 async fn debug_output_reports_a_finished_stream_as_done() {
1152 let (tx, rx) = mpsc::channel::<BodyChunk>(8);
1153 let mut stream = EventStream::new(rx);
1154 drop(tx);
1155 let _ = stream.next().await;
1156 assert!(format!("{stream:?}").contains("done: true"));
1157 }
1158
1159 #[test]
1160 fn is_terminal_returns_false_for_working() {
1161 let event = make_status_event(TaskState::Working, false);
1162 assert!(!is_terminal(&event), "Working state should not be terminal");
1163 }
1164
1165 #[test]
1166 fn is_terminal_returns_true_for_completed() {
1167 let event = make_status_event(TaskState::Completed, true);
1168 assert!(is_terminal(&event), "Completed state should be terminal");
1169 }
1170
1171 #[tokio::test]
1174 async fn stream_decodes_jsonrpc_error_as_protocol_error() {
1175 use a2a_protocol_types::{JsonRpcErrorResponse, JsonRpcVersion};
1176
1177 let (tx, rx) = mpsc::channel(8);
1178 let mut stream = EventStream::new(rx);
1179
1180 let error_resp = JsonRpcErrorResponse {
1182 jsonrpc: JsonRpcVersion,
1183 id: Some(serde_json::json!(1)),
1184 error: a2a_protocol_types::JsonRpcError {
1185 code: -32601,
1186 message: "method not found".into(),
1187 data: None,
1188 },
1189 };
1190 let json = serde_json::to_string(&error_resp).unwrap();
1191 let sse_data = format!("data: {json}\n\n");
1192 tx.send(Ok(Bytes::from(sse_data))).await.unwrap();
1193 drop(tx);
1194
1195 let result = tokio::time::timeout(TEST_TIMEOUT, stream.next())
1196 .await
1197 .expect("timed out")
1198 .unwrap();
1199 assert!(result.is_err(), "JSON-RPC error should produce Err");
1200 match result.unwrap_err() {
1201 ClientError::Protocol(err) => {
1202 assert!(
1203 format!("{err}").contains("method not found"),
1204 "error message should be preserved"
1205 );
1206 }
1207 other => panic!("expected Protocol error, got {other:?}"),
1208 }
1209
1210 let end = tokio::time::timeout(TEST_TIMEOUT, stream.next())
1212 .await
1213 .expect("timed out");
1214 assert!(end.is_none(), "stream should end after JSON-RPC error");
1215 }
1216
1217 #[tokio::test]
1220 async fn stream_invalid_json_returns_serialization_error() {
1221 let (tx, rx) = mpsc::channel(8);
1222 let mut stream = EventStream::new(rx);
1223
1224 let sse_data = "data: {not valid json}\n\n";
1225 tx.send(Ok(Bytes::from(sse_data))).await.unwrap();
1226 drop(tx);
1227
1228 let result = tokio::time::timeout(TEST_TIMEOUT, stream.next())
1229 .await
1230 .expect("timed out")
1231 .unwrap();
1232 assert!(result.is_err(), "invalid JSON should produce Err");
1233 assert!(
1234 matches!(result.unwrap_err(), ClientError::Serialization(_)),
1235 "should be a Serialization error"
1236 );
1237 }
1238
1239 #[tokio::test]
1242 async fn stream_drains_parser_after_channel_close() {
1243 let (tx, rx) = mpsc::channel(8);
1244 let mut stream = EventStream::new(rx);
1245
1246 let event = make_status_event(TaskState::Working, false);
1249 let sse_bytes = sse_frame(&event);
1250 let (first_half, second_half) = sse_bytes.split_at(sse_bytes.len() / 2);
1251
1252 tx.send(Ok(Bytes::from(first_half.to_owned())))
1253 .await
1254 .unwrap();
1255 tx.send(Ok(Bytes::from(second_half.to_owned())))
1256 .await
1257 .unwrap();
1258 drop(tx);
1259
1260 let result = tokio::time::timeout(TEST_TIMEOUT, stream.next())
1261 .await
1262 .expect("timed out")
1263 .unwrap();
1264 let event = result.unwrap();
1265 assert!(
1266 matches!(event, StreamResponse::StatusUpdate(ref ev) if ev.status.state == TaskState::Working),
1267 "should deliver Working event from drained parser"
1268 );
1269 }
1270
1271 #[tokio::test]
1273 async fn status_code_returns_set_value() {
1274 let (_tx, rx) = mpsc::channel::<BodyChunk>(8);
1275 let stream = EventStream::new(rx);
1276 assert_eq!(stream.status_code(), 200, "default status should be 200");
1277 }
1278
1279 #[tokio::test]
1281 async fn status_code_with_custom_value() {
1282 let (_tx, rx) = mpsc::channel::<BodyChunk>(8);
1283 let task = tokio::spawn(async { tokio::time::sleep(Duration::from_secs(60)).await });
1284 let stream = EventStream::with_status(rx, task.abort_handle(), 201);
1285 assert_eq!(stream.status_code(), 201);
1286 }
1287
1288 #[tokio::test]
1291 async fn first_event_timeout_fires_when_no_data_arrives() {
1292 let (_tx, rx) = mpsc::channel::<BodyChunk>(8);
1294 let mut stream = EventStream::new(rx).with_first_event_timeout(Duration::from_millis(50));
1295 let result = tokio::time::timeout(Duration::from_secs(2), stream.next())
1298 .await
1299 .expect("first-event timeout must fire well within 2s");
1300 assert!(
1301 matches!(result, Some(Err(ClientError::Timeout(ref m))) if m.contains("first-event")),
1302 "expected first-event timeout, got {result:?}"
1303 );
1304 let done = tokio::time::timeout(Duration::from_secs(2), stream.next())
1306 .await
1307 .expect("a completed stream must return promptly");
1308 assert!(done.is_none());
1309 }
1310
1311 #[tokio::test]
1314 async fn first_event_timeout_lifted_after_first_chunk() {
1315 let (tx, rx) = mpsc::channel(8);
1316 let mut stream = EventStream::new(rx)
1317 .with_jsonrpc_envelope(false)
1318 .with_first_event_timeout(Duration::from_millis(50));
1319 let event = make_status_event(TaskState::Working, false);
1321 tx.send(Ok(Bytes::from(bare_sse_frame(&event))))
1322 .await
1323 .unwrap();
1324 let first = stream.next().await;
1325 assert!(
1326 matches!(first, Some(Ok(_))),
1327 "first event should parse, got {first:?}"
1328 );
1329 let pending = tokio::time::timeout(Duration::from_millis(120), stream.next()).await;
1332 assert!(
1333 pending.is_err(),
1334 "stream must remain open (pending) after first chunk, got {pending:?}"
1335 );
1336 }
1337
1338 const IDLE: Duration = Duration::from_secs(10);
1344
1345 async fn stream_after_one_event() -> (mpsc::Sender<BodyChunk>, EventStream) {
1347 let (tx, rx) = mpsc::channel(8);
1348 let mut stream = EventStream::new(rx)
1349 .with_jsonrpc_envelope(false)
1350 .with_idle_timeout(Some(IDLE));
1351 let event = make_status_event(TaskState::Working, false);
1352 tx.send(Ok(Bytes::from(bare_sse_frame(&event))))
1353 .await
1354 .unwrap();
1355 assert!(matches!(stream.next().await, Some(Ok(_))));
1356 (tx, stream)
1357 }
1358
1359 #[tokio::test(start_paused = true)]
1363 async fn idle_timeout_fires_after_the_first_event() {
1364 let (_tx, mut stream) = stream_after_one_event().await;
1365 let start = tokio::time::Instant::now();
1366 let result = stream.next().await;
1367 assert_eq!(start.elapsed(), IDLE, "fires exactly at the bound");
1368 match result {
1369 Some(Err(ClientError::Timeout(msg))) => {
1370 assert!(msg.contains("idle timeout"), "{msg}");
1371 assert!(msg.contains("10s"), "names the bound: {msg}");
1372 }
1373 other => panic!("expected idle Timeout, got {other:?}"),
1374 }
1375 assert!(stream.next().await.is_none(), "the stream has ended");
1376 }
1377
1378 #[tokio::test(start_paused = true)]
1382 async fn cancelled_polls_do_not_restart_the_idle_clock() {
1383 let (_tx, mut stream) = stream_after_one_event().await;
1384 for _ in 0..3 {
1385 let poll = tokio::time::timeout(IDLE / 4, stream.next()).await;
1386 assert!(poll.is_err(), "still inside the bound: {poll:?}");
1387 }
1388 let start = tokio::time::Instant::now();
1391 let result = tokio::time::timeout(IDLE, stream.next())
1392 .await
1393 .expect("the original deadline falls inside this poll");
1394 assert_eq!(start.elapsed(), IDLE / 4);
1395 assert!(matches!(result, Some(Err(ClientError::Timeout(_)))));
1396 }
1397
1398 #[tokio::test(start_paused = true)]
1401 async fn a_keep_alive_comment_restarts_the_idle_clock() {
1402 let (tx, mut stream) = stream_after_one_event().await;
1403 let quiet = IDLE * 3 / 4;
1404 tokio::time::advance(quiet).await;
1405 tx.send(Ok(Bytes::from_static(b": keep-alive\n\n")))
1406 .await
1407 .unwrap();
1408 let poll = tokio::time::timeout(quiet, stream.next()).await;
1410 assert!(poll.is_err(), "the comment renewed the bound: {poll:?}");
1411 let result = stream.next().await;
1413 assert!(matches!(result, Some(Err(ClientError::Timeout(_)))));
1414 }
1415
1416 #[tokio::test(start_paused = true)]
1419 async fn an_absent_or_unrepresentable_idle_bound_never_fires() {
1420 for bound in [None, Some(Duration::MAX)] {
1421 let (tx, rx) = mpsc::channel(8);
1422 let mut stream = EventStream::new(rx)
1423 .with_jsonrpc_envelope(false)
1424 .with_idle_timeout(bound);
1425 let event = make_status_event(TaskState::Working, false);
1426 tx.send(Ok(Bytes::from(bare_sse_frame(&event))))
1427 .await
1428 .unwrap();
1429 assert!(matches!(stream.next().await, Some(Ok(_))));
1430 let poll = tokio::time::timeout(IDLE * 1000, stream.next()).await;
1431 assert!(poll.is_err(), "{bound:?} must not fire: {poll:?}");
1432 }
1433 }
1434
1435 #[tokio::test(start_paused = true)]
1437 async fn streams_carry_the_default_idle_bound() {
1438 let (tx, rx) = mpsc::channel(8);
1439 let mut stream = EventStream::new(rx).with_jsonrpc_envelope(false);
1440 let event = make_status_event(TaskState::Working, false);
1441 tx.send(Ok(Bytes::from(bare_sse_frame(&event))))
1442 .await
1443 .unwrap();
1444 assert!(matches!(stream.next().await, Some(Ok(_))));
1445 let start = tokio::time::Instant::now();
1446 let result = stream.next().await;
1447 assert_eq!(
1448 start.elapsed(),
1449 crate::config::DEFAULT_STREAM_IDLE_TIMEOUT,
1450 "the default bound applies"
1451 );
1452 assert!(matches!(result, Some(Err(ClientError::Timeout(_)))));
1453 }
1454
1455 #[tokio::test(start_paused = true)]
1458 async fn idle_expiry_aborts_the_body_reader() {
1459 let (tx, rx) = mpsc::channel::<BodyChunk>(8);
1460 let reader = tokio::spawn(async move {
1461 let event = make_status_event(TaskState::Working, false);
1462 let _ = tx.send(Ok(Bytes::from(bare_sse_frame(&event)))).await;
1463 std::future::pending::<()>().await;
1464 });
1465 let mut stream = EventStream::with_abort_handle(rx, reader.abort_handle())
1466 .with_jsonrpc_envelope(false)
1467 .with_idle_timeout(Some(IDLE));
1468 assert!(matches!(stream.next().await, Some(Ok(_))));
1469 assert!(matches!(
1470 stream.next().await,
1471 Some(Err(ClientError::Timeout(_)))
1472 ));
1473 let joined = reader.await;
1474 assert!(
1475 joined.is_err_and(|e| e.is_cancelled()),
1476 "the reader must be aborted at expiry while the stream is still alive"
1477 );
1478 drop(stream);
1479 }
1480
1481 #[tokio::test]
1484 async fn stream_transport_error_from_channel() {
1485 let (tx, rx) = mpsc::channel(8);
1486 let mut stream = EventStream::new(rx);
1487
1488 tx.send(Err(ClientError::HttpClient("connection reset".into())))
1490 .await
1491 .unwrap();
1492
1493 let result = tokio::time::timeout(TEST_TIMEOUT, stream.next())
1494 .await
1495 .expect("timed out")
1496 .unwrap();
1497 match result {
1498 Err(ClientError::HttpClient(msg)) => {
1499 assert!(msg.contains("connection reset"));
1500 }
1501 other => panic!("expected HttpClient error, got {other:?}"),
1502 }
1503
1504 let end = tokio::time::timeout(TEST_TIMEOUT, stream.next())
1506 .await
1507 .expect("timed out");
1508 assert!(end.is_none(), "stream should end after transport error");
1509 }
1510
1511 #[tokio::test]
1512 async fn non_terminal_event_does_not_end_stream() {
1513 let (tx, rx) = mpsc::channel(8);
1514 let mut stream = EventStream::new(rx);
1515
1516 let working = make_status_event(TaskState::Working, false);
1518 let completed = make_status_event(TaskState::Completed, true);
1519 tx.send(Ok(Bytes::from(sse_frame(&working)))).await.unwrap();
1520 tx.send(Ok(Bytes::from(sse_frame(&completed))))
1521 .await
1522 .unwrap();
1523
1524 let first = tokio::time::timeout(TEST_TIMEOUT, stream.next())
1526 .await
1527 .expect("timed out on first event")
1528 .unwrap()
1529 .unwrap();
1530 assert!(
1531 matches!(first, StreamResponse::StatusUpdate(ref ev) if ev.status.state == TaskState::Working)
1532 );
1533
1534 let second = tokio::time::timeout(TEST_TIMEOUT, stream.next())
1536 .await
1537 .expect("timed out on second event")
1538 .unwrap()
1539 .unwrap();
1540 assert!(
1541 matches!(second, StreamResponse::StatusUpdate(ref ev) if ev.status.state == TaskState::Completed)
1542 );
1543
1544 let end = tokio::time::timeout(TEST_TIMEOUT, stream.next())
1546 .await
1547 .expect("timed out waiting for stream end");
1548 assert!(end.is_none());
1549 }
1550
1551 fn bare_sse_frame(event: &StreamResponse) -> String {
1555 let json = serde_json::to_string(event).unwrap();
1556 format!("data: {json}\n\n")
1557 }
1558
1559 #[tokio::test]
1560 async fn bare_stream_delivers_events() {
1561 let (tx, rx) = mpsc::channel(8);
1562 let mut stream = EventStream::new(rx).with_jsonrpc_envelope(false);
1563
1564 let event = make_status_event(TaskState::Working, false);
1565 tx.send(Ok(Bytes::from(bare_sse_frame(&event))))
1566 .await
1567 .unwrap();
1568 drop(tx);
1569
1570 let result = tokio::time::timeout(TEST_TIMEOUT, stream.next())
1571 .await
1572 .expect("timed out")
1573 .unwrap()
1574 .unwrap();
1575 assert!(
1576 matches!(result, StreamResponse::StatusUpdate(ref ev) if ev.status.state == TaskState::Working)
1577 );
1578 }
1579
1580 #[tokio::test]
1581 async fn bare_stream_ends_on_terminal() {
1582 let (tx, rx) = mpsc::channel(8);
1583 let mut stream = EventStream::new(rx).with_jsonrpc_envelope(false);
1584
1585 let event = make_status_event(TaskState::Completed, true);
1586 tx.send(Ok(Bytes::from(bare_sse_frame(&event))))
1587 .await
1588 .unwrap();
1589
1590 let result = tokio::time::timeout(TEST_TIMEOUT, stream.next())
1591 .await
1592 .expect("timed out")
1593 .unwrap()
1594 .unwrap();
1595 assert!(
1596 matches!(result, StreamResponse::StatusUpdate(ref ev) if ev.status.state == TaskState::Completed)
1597 );
1598
1599 let end = tokio::time::timeout(TEST_TIMEOUT, stream.next())
1600 .await
1601 .expect("timed out");
1602 assert!(end.is_none(), "bare stream should end after terminal event");
1603 }
1604
1605 #[tokio::test]
1606 async fn bare_stream_rejects_jsonrpc_envelope() {
1607 let (tx, rx) = mpsc::channel(8);
1608 let mut stream = EventStream::new(rx).with_jsonrpc_envelope(false);
1609
1610 let event = make_status_event(TaskState::Working, false);
1612 let envelope_frame = sse_frame(&event); tx.send(Ok(Bytes::from(envelope_frame))).await.unwrap();
1614 drop(tx);
1615
1616 let result = tokio::time::timeout(TEST_TIMEOUT, stream.next())
1617 .await
1618 .expect("timed out")
1619 .unwrap();
1620 assert!(
1621 result.is_err(),
1622 "bare stream should reject JSON-RPC envelope as invalid"
1623 );
1624 }
1625
1626 #[tokio::test]
1627 async fn envelope_stream_rejects_bare_response() {
1628 let (tx, rx) = mpsc::channel(8);
1629 let mut stream = EventStream::new(rx); let event = make_status_event(TaskState::Working, false);
1633 let bare_frame = bare_sse_frame(&event);
1634 tx.send(Ok(Bytes::from(bare_frame))).await.unwrap();
1635 drop(tx);
1636
1637 let result = tokio::time::timeout(TEST_TIMEOUT, stream.next())
1638 .await
1639 .expect("timed out")
1640 .unwrap();
1641 assert!(
1642 result.is_err(),
1643 "envelope stream should reject bare StreamResponse"
1644 );
1645 }
1646
1647 #[tokio::test]
1648 async fn bare_stream_multiple_events() {
1649 let (tx, rx) = mpsc::channel(8);
1650 let mut stream = EventStream::new(rx).with_jsonrpc_envelope(false);
1651
1652 let working = make_status_event(TaskState::Working, false);
1653 let completed = make_status_event(TaskState::Completed, true);
1654 tx.send(Ok(Bytes::from(bare_sse_frame(&working))))
1655 .await
1656 .unwrap();
1657 tx.send(Ok(Bytes::from(bare_sse_frame(&completed))))
1658 .await
1659 .unwrap();
1660
1661 let first = tokio::time::timeout(TEST_TIMEOUT, stream.next())
1662 .await
1663 .expect("timed out")
1664 .unwrap()
1665 .unwrap();
1666 assert!(
1667 matches!(first, StreamResponse::StatusUpdate(ref ev) if ev.status.state == TaskState::Working)
1668 );
1669
1670 let second = tokio::time::timeout(TEST_TIMEOUT, stream.next())
1671 .await
1672 .expect("timed out")
1673 .unwrap()
1674 .unwrap();
1675 assert!(
1676 matches!(second, StreamResponse::StatusUpdate(ref ev) if ev.status.state == TaskState::Completed)
1677 );
1678
1679 let end = tokio::time::timeout(TEST_TIMEOUT, stream.next())
1680 .await
1681 .expect("timed out");
1682 assert!(end.is_none());
1683 }
1684}