1use std::pin::Pin;
31use std::sync::Arc;
32use std::sync::OnceLock;
33use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
34use std::task::{Context, Poll};
35use std::time::Instant;
36
37use axum::body::{Body, HttpBody};
38use axum::extract::{OriginalUri, State};
39use axum::http::header::CONTENT_LENGTH;
40use axum::http::{HeaderMap, HeaderName, Method, StatusCode, Uri, header};
41use axum::response::Response;
42use bytes::Bytes;
43use http_body::Frame;
44use http_body::SizeHint;
45use http_body_util::BodyExt;
46use hyper_util::client::legacy::Client;
47use hyper_util::client::legacy::connect::HttpConnector;
48use hyper_util::rt::TokioExecutor;
49use percent_encoding::percent_decode_str;
50use tokio::time::Instant as TokioInstant;
51use tokio::time::Sleep;
52use tokio_stream::Stream;
53use tokio_stream::StreamExt;
54
55use crate::ai::config::{AiConfig, AiUpstream, valid_upstream_id};
56use crate::ai::json_error;
57use crate::backend::ComputeBackend;
58use crate::state::AppState;
59
60const SSE_TRUNCATION_MARKER: &str = ": waratah-proxy-truncated\n\n";
65
66const MAX_DECODE_ROUNDS: usize = 5;
70
71#[derive(Default)]
74struct ProxyCounts {
75 bytes_in: AtomicU64,
76 bytes_out: AtomicU64,
77 request_exceeded: AtomicBool,
81}
82
83pub struct AiService {
90 pub config: AiConfig,
92 client: OnceLock<Option<Client<hyper_rustls::HttpsConnector<HttpConnector>, CountingBody>>>,
93}
94
95impl std::fmt::Debug for AiService {
96 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
97 f.debug_struct("AiService")
99 .field("config", &self.config)
100 .finish_non_exhaustive()
101 }
102}
103
104impl AiService {
105 pub fn new(config: AiConfig) -> Self {
107 Self {
108 config,
109 client: OnceLock::new(),
110 }
111 }
112
113 fn client(&self) -> Option<&Client<hyper_rustls::HttpsConnector<HttpConnector>, CountingBody>> {
116 self.client
117 .get_or_init(|| {
118 let mut http = HttpConnector::new();
119 http.set_connect_timeout(Some(self.config.connect_timeout));
120 http.enforce_http(false);
128 let https = hyper_rustls::HttpsConnectorBuilder::new()
129 .with_native_roots()
130 .ok()?
131 .https_or_http()
132 .enable_http1()
133 .wrap_connector(http);
134 Some(Client::builder(TokioExecutor::new()).build(https))
135 })
136 .as_ref()
137 }
138}
139
140struct CountingBody {
144 inner: Body,
145 remaining: usize,
146 exceeded: bool,
151 counts: Arc<ProxyCounts>,
152}
153
154impl CountingBody {
155 fn new(inner: Body, limit: usize, counts: Arc<ProxyCounts>) -> Self {
156 Self {
157 inner,
158 remaining: limit,
159 exceeded: false,
160 counts,
161 }
162 }
163}
164
165impl HttpBody for CountingBody {
166 type Data = Bytes;
167 type Error = axum::BoxError;
168
169 fn poll_frame(
170 self: Pin<&mut Self>,
171 cx: &mut Context<'_>,
172 ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
173 let this = self.get_mut();
174 if this.exceeded {
175 return Poll::Ready(Some(Err(
177 "request body exceeds the configured maximum".into()
178 )));
179 }
180 let Poll::Ready(frame) = Pin::new(&mut this.inner).poll_frame(cx) else {
181 return Poll::Pending;
182 };
183 let Some(frame) = frame else {
184 return Poll::Ready(None);
185 };
186 let Ok(frame) = frame else {
187 return Poll::Ready(Some(Err("request body read failed".into())));
188 };
189 if let Some(data) = frame.data_ref() {
190 let len = data.len();
191 this.counts
192 .bytes_in
193 .fetch_add(len as u64, Ordering::Relaxed);
194 if len > this.remaining {
195 this.exceeded = true;
196 this.counts.request_exceeded.store(true, Ordering::Relaxed);
197 return Poll::Ready(Some(Err(
198 "request body exceeds the configured maximum".into()
199 )));
200 }
201 this.remaining -= len;
202 }
203 Poll::Ready(Some(Ok(frame)))
204 }
205
206 fn size_hint(&self) -> SizeHint {
207 self.inner.size_hint()
208 }
209}
210
211struct ProxyLog {
215 upstream: String,
216 method: String,
217 path: String,
218 status: u16,
219 started: Instant,
220 counts: Arc<ProxyCounts>,
221 completed: bool,
224 truncated: bool,
226}
227
228impl Drop for ProxyLog {
229 fn drop(&mut self) {
230 let state = if self.truncated {
231 "truncated"
232 } else if self.completed {
233 "complete"
234 } else {
235 "aborted"
236 };
237 eprintln!(
238 "ai-proxy: upstream={} method={} path={} status={} duration_ms={} bytes_in={} bytes_out={} state={}",
239 self.upstream,
240 self.method,
241 self.path,
242 self.status,
243 self.started.elapsed().as_millis(),
244 self.counts.bytes_in.load(Ordering::Relaxed),
245 self.counts.bytes_out.load(Ordering::Relaxed),
246 state,
247 );
248 }
249}
250
251enum Tail {
254 Streaming,
255 MarkerSent,
256}
257
258struct ProxiedStream {
270 inner: Pin<Box<dyn Stream<Item = Result<Bytes, axum::BoxError>> + Send>>,
271 deadline: Pin<Box<Sleep>>,
272 sse_content_type: bool,
273 tail: Tail,
274 counts: Arc<ProxyCounts>,
275 log: Option<ProxyLog>,
276}
277
278impl Stream for ProxiedStream {
279 type Item = Result<Bytes, axum::BoxError>;
280
281 fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
282 let this = self.get_mut();
283 if matches!(this.tail, Tail::MarkerSent) {
284 if let Some(log) = this.log.as_mut() {
286 log.truncated = true;
287 }
288 return Poll::Ready(None);
289 }
290 match this.inner.as_mut().poll_next(cx) {
291 Poll::Ready(Some(Ok(chunk))) => {
292 this.counts
293 .bytes_out
294 .fetch_add(chunk.len() as u64, Ordering::Relaxed);
295 Poll::Ready(Some(Ok(chunk)))
296 }
297 Poll::Ready(Some(Err(error))) => Poll::Ready(Some(Err(error))),
298 Poll::Ready(None) => {
299 if let Some(log) = this.log.as_mut() {
300 log.completed = true;
301 }
302 Poll::Ready(None)
303 }
304 Poll::Pending => {
305 if this.deadline.as_mut().poll(cx).is_ready() {
309 if let Some(log) = this.log.as_mut() {
310 log.truncated = true;
311 }
312 if this.sse_content_type {
313 this.tail = Tail::MarkerSent;
314 return Poll::Ready(Some(Ok(Bytes::from_static(
315 SSE_TRUNCATION_MARKER.as_bytes(),
316 ))));
317 }
318 return Poll::Ready(None);
319 }
320 Poll::Pending
321 }
322 }
323 }
324}
325
326pub(crate) async fn ai_proxy<C>(
332 State(state): State<AppState<C>>,
333 OriginalUri(uri): OriginalUri,
334 method: Method,
335 headers: HeaderMap,
336 body: Body,
337) -> Response
338where
339 C: ComputeBackend + Clone + Send + Sync + 'static,
340{
341 let started = Instant::now();
342 let Some(ai) = &state.ai else {
343 return json_error(StatusCode::NOT_IMPLEMENTED, "ai features are not enabled");
344 };
345 let Some((id, path)) = split_upstream_path(uri.path()) else {
346 return json_error(StatusCode::NOT_FOUND, "unknown upstream");
347 };
348 let Some(upstream) = ai.config.upstreams.iter().find(|u| u.id == id) else {
349 return json_error(StatusCode::NOT_FOUND, "unknown upstream");
350 };
351 if !matches!(method, Method::GET | Method::POST) {
352 return json_error(StatusCode::METHOD_NOT_ALLOWED, "method not allowed");
353 }
354 let path = path.unwrap_or_default();
358 if !path.is_empty() && !valid_proxy_path(&path) {
359 return json_error(StatusCode::BAD_REQUEST, "invalid proxy path");
360 }
361 let Ok(target) = upstream_uri(&upstream.base_url, &path, uri.query()) else {
362 return json_error(StatusCode::BAD_REQUEST, "invalid proxy request");
363 };
364
365 let counts = Arc::new(ProxyCounts::default());
366 if content_length(&headers)
369 .is_some_and(|declared| declared > ai.config.max_request_body_bytes as u64)
370 {
371 eprintln!(
372 "ai-proxy: upstream={} method={} path={} status=413 duration_ms={} state=rejected",
373 upstream.id,
374 method,
375 path,
376 started.elapsed().as_millis()
377 );
378 return json_error(
379 StatusCode::PAYLOAD_TOO_LARGE,
380 "request body exceeds the configured maximum",
381 );
382 }
383
384 let mut builder = axum::http::Request::builder()
385 .method(method.clone())
386 .uri(target);
387 for (name, value) in &headers {
388 if !forward_request_header(name) {
389 continue;
390 }
391 if name == header::AUTHORIZATION && upstream.api_key_env.is_some() {
395 continue;
396 }
397 builder = builder.header(name.clone(), value.clone());
398 }
399 if let Some(env_name) = &upstream.api_key_env {
400 match std::env::var(env_name) {
401 Ok(value) => builder = builder.header(header::AUTHORIZATION, value),
403 Err(_) => {
404 eprintln!("ai-proxy: api key env {env_name} is not set");
405 return json_error(
406 StatusCode::BAD_GATEWAY,
407 "upstream api key environment variable is not set",
408 );
409 }
410 }
411 }
412 let request = match builder.body(CountingBody::new(
413 body,
414 ai.config.max_request_body_bytes,
415 Arc::clone(&counts),
416 )) {
417 Ok(request) => request,
418 Err(_) => return json_error(StatusCode::BAD_REQUEST, "invalid proxy request"),
419 };
420
421 let Some(client) = ai.client() else {
422 return json_error(
423 StatusCode::BAD_GATEWAY,
424 "tls initialization failed (no native root certificates?)",
425 );
426 };
427 let deadline = TokioInstant::now() + ai.config.request_timeout;
428 match tokio::time::timeout_at(deadline, client.request(request)).await {
429 Ok(Ok(upstream_response)) => stream_back(
430 upstream_response,
431 deadline,
432 id,
433 method.to_string(),
434 path,
435 started,
436 counts,
437 ),
438 Ok(Err(error)) => {
439 classify_upstream_error(&error, upstream, &method, &path, &started, &counts)
440 }
441 Err(_) => {
442 eprintln!(
443 "ai-proxy: upstream={} method={} path={} status=504 duration_ms={} bytes_in={} state=timeout",
444 upstream.id,
445 method,
446 path,
447 started.elapsed().as_millis(),
448 counts.bytes_in.load(Ordering::Relaxed),
449 );
450 json_error(StatusCode::GATEWAY_TIMEOUT, "upstream request timed out")
451 }
452 }
453}
454
455fn classify_upstream_error(
460 error: &hyper_util::client::legacy::Error,
461 upstream: &AiUpstream,
462 method: &Method,
463 path: &str,
464 started: &Instant,
465 counts: &ProxyCounts,
466) -> Response {
467 let status = if counts.request_exceeded.load(Ordering::Relaxed) {
468 StatusCode::PAYLOAD_TOO_LARGE
469 } else if is_timeout_error(error) {
470 StatusCode::GATEWAY_TIMEOUT
471 } else {
472 StatusCode::BAD_GATEWAY
473 };
474 let mut cause = String::new();
478 let mut source = std::error::Error::source(error);
479 while let Some(current) = source {
480 cause.push_str(": ");
481 cause.push_str(¤t.to_string());
482 source = current.source();
483 }
484 eprintln!(
485 "ai-proxy: upstream={} method={} path={} status={} duration_ms={} state=error: {error}{cause}",
486 upstream.id,
487 method,
488 path,
489 status.as_u16(),
490 started.elapsed().as_millis(),
491 );
492 match status {
493 StatusCode::PAYLOAD_TOO_LARGE => {
494 json_error(status, "request body exceeds the configured maximum")
495 }
496 StatusCode::GATEWAY_TIMEOUT => json_error(status, "upstream request timed out"),
497 _ => json_error(status, "upstream unavailable"),
498 }
499}
500
501fn is_timeout_error(error: &(dyn std::error::Error + 'static)) -> bool {
509 let mut source = Some(error);
510 while let Some(current) = source {
511 if let Some(io) = current.downcast_ref::<std::io::Error>()
512 && io.kind() == std::io::ErrorKind::TimedOut
513 {
514 return true;
515 }
516 source = current.source();
517 }
518 false
519}
520
521fn stream_back<B>(
524 upstream_response: axum::http::Response<B>,
525 deadline: TokioInstant,
526 upstream_id: String,
527 method: String,
528 path: String,
529 started: Instant,
530 counts: Arc<ProxyCounts>,
531) -> Response
532where
533 B: HttpBody<Data = Bytes> + Send + 'static,
534 B::Error: Into<axum::BoxError>,
535{
536 let (parts, incoming) = upstream_response.into_parts();
537 let sse_content_type = crate::compress::content_media_type(&parts.headers)
542 .is_some_and(|media_type| media_type == "text/event-stream");
543 let mut builder = Response::builder().status(parts.status);
544 for (name, value) in &parts.headers {
545 if forward_response_header(name) {
546 builder = builder.header(name.clone(), value.clone());
547 }
548 }
549 let stream = ProxiedStream {
550 inner: Box::pin(
551 incoming
552 .into_data_stream()
553 .map(|item| item.map_err(|error| -> axum::BoxError { error.into() })),
554 ),
555 deadline: Box::pin(tokio::time::sleep_until(deadline)),
556 sse_content_type,
557 tail: Tail::Streaming,
558 counts: Arc::clone(&counts),
559 log: Some(ProxyLog {
560 upstream: upstream_id,
561 method,
562 path,
563 status: parts.status.as_u16(),
564 started,
565 counts,
566 completed: false,
567 truncated: false,
568 }),
569 };
570 match builder.body(Body::from_stream(stream)) {
571 Ok(response) => response,
572 Err(_) => json_error(StatusCode::BAD_GATEWAY, "upstream unavailable"),
573 }
574}
575
576fn forward_request_header(name: &HeaderName) -> bool {
579 name == header::AUTHORIZATION
580 || name == header::CONTENT_TYPE
581 || name == header::ACCEPT
582 || name == header::USER_AGENT
583 || name == HeaderName::from_static("openai-organization")
584}
585
586fn forward_response_header(name: &HeaderName) -> bool {
589 name == header::CONTENT_TYPE
590 || name == header::CONTENT_ENCODING
591 || name == header::CONTENT_DISPOSITION
592 || name == header::CONTENT_LANGUAGE
593 || name == header::CACHE_CONTROL
594 || name == header::VARY
595}
596
597fn content_length(headers: &HeaderMap) -> Option<u64> {
599 headers
600 .get(CONTENT_LENGTH)
601 .and_then(|value| value.to_str().ok())
602 .and_then(|value| value.parse().ok())
603}
604
605fn split_upstream_path(path: &str) -> Option<(String, Option<String>)> {
612 let rest = path.strip_prefix("/waratah/ai/upstreams/")?;
613 let (raw_id, raw_path) = match rest.split_once('/') {
614 Some((id, path)) => (id, Some(path)),
615 None => (rest, None),
616 };
617 let id = percent_decode_fixpoint(raw_id)?;
622 if !valid_upstream_id(&id) {
623 return None;
624 }
625 let path = match raw_path {
626 Some(raw) => Some(percent_decode_fixpoint(raw)?),
627 None => None,
628 };
629 Some((id, path))
630}
631
632fn percent_decode_fixpoint(raw: &str) -> Option<String> {
640 let mut current = raw.to_owned();
641 for _ in 0..MAX_DECODE_ROUNDS {
642 let decoded = percent_decode_str(¤t).decode_utf8().ok()?;
643 if decoded == current {
644 return Some(current);
645 }
646 current = decoded.into_owned();
647 }
648 None
649}
650
651fn valid_proxy_path(path: &str) -> bool {
654 !path.split('/').any(|segment| {
655 segment.is_empty()
656 || segment == "."
657 || segment == ".."
658 || segment.contains(['\\', '\0', '?', '#'])
659 })
660}
661
662fn upstream_uri(base: &str, path: &str, query: Option<&str>) -> Result<Uri, ()> {
665 if path.contains(['\r', '\n', '\0']) || base.contains(['\r', '\n', '\0']) {
666 return Err(());
667 }
668 let mut raw = if path.is_empty() {
673 base.to_owned()
674 } else {
675 format!("{base}/{}", percent_encode_path(path))
676 };
677 if let Some(query) = query {
678 if query.contains(['\r', '\n', '\0']) {
679 return Err(());
680 }
681 raw.push('?');
682 raw.push_str(query);
683 }
684 raw.parse().map_err(|_| ())
685}
686
687const PATH_SAFE: &percent_encoding::AsciiSet = &percent_encoding::NON_ALPHANUMERIC
692 .remove(b'-')
693 .remove(b'.')
694 .remove(b'_')
695 .remove(b'~')
696 .remove(b'!')
697 .remove(b'$')
698 .remove(b'&')
699 .remove(b'\'')
700 .remove(b'(')
701 .remove(b')')
702 .remove(b'*')
703 .remove(b'+')
704 .remove(b',')
705 .remove(b';')
706 .remove(b'=')
707 .remove(b':')
708 .remove(b'@')
709 .remove(b'/');
710
711fn percent_encode_path(path: &str) -> String {
721 percent_encoding::percent_encode(path.as_bytes(), PATH_SAFE).to_string()
722}
723
724#[cfg(test)]
725mod tests {
726 use super::*;
727 use pretty_assertions::assert_eq;
728
729 #[test]
730 fn request_header_allowlist_matches_the_contract() {
731 for name in [
732 "authorization",
733 "content-type",
734 "accept",
735 "user-agent",
736 "openai-organization",
737 ] {
738 assert!(
739 forward_request_header(&HeaderName::from_static(name)),
740 "{name} forwarded"
741 );
742 }
743 for name in [
744 "cookie",
745 "origin",
746 "referer",
747 "host",
748 "connection",
749 "x-custom",
750 "content-length",
751 ] {
752 assert!(
753 !forward_request_header(&HeaderName::from_static(name)),
754 "{name} dropped"
755 );
756 }
757 }
758
759 #[test]
760 fn response_header_allowlist_matches_the_cluster_proxy() {
761 for name in [
762 "content-type",
763 "content-encoding",
764 "content-disposition",
765 "content-language",
766 "cache-control",
767 "vary",
768 ] {
769 assert!(forward_response_header(&HeaderName::from_static(name)));
770 }
771 for name in ["transfer-encoding", "server", "set-cookie", "date"] {
772 assert!(!forward_response_header(&HeaderName::from_static(name)));
773 }
774 }
775
776 #[test]
777 fn upstream_uri_joins_base_path_and_query() {
778 let uri = upstream_uri(
779 "https://opencode.ai/zen/v1",
780 "chat/completions",
781 Some("a=1"),
782 )
783 .unwrap();
784 assert_eq!(
785 uri.to_string(),
786 "https://opencode.ai/zen/v1/chat/completions?a=1"
787 );
788 let uri = upstream_uri("http://h", "m", Some("x=%2F&y=z")).unwrap();
790 assert_eq!(uri.to_string(), "http://h/m?x=%2F&y=z");
791 assert!(upstream_uri("http://h", "m", Some("a\r\nb")).is_err());
792 assert!(upstream_uri("http://h", "m\n", None).is_err());
793 }
794
795 #[test]
796 fn upstream_uri_sends_only_reencoded_path_bytes() {
797 let uri = upstream_uri("http://h", "a b%cé", None).unwrap();
800 assert_eq!(
801 uri.path(),
802 "/a%20b%25c%C3%A9",
803 "wire path keeps % only as %25"
804 );
805 let uri = upstream_uri("http://h/v1", "chat/completions", None).unwrap();
807 assert_eq!(uri.path(), "/v1/chat/completions");
808 }
809
810 #[test]
811 fn percent_encode_path_leaks_no_decode_candidates() {
812 for validated in ["a b", "..a..", "a.b/c", "x", "a%zz"] {
818 assert_eq!(
819 percent_decode_fixpoint(validated).as_deref(),
820 Some(validated),
821 "sample must be fixpoint-stable to be representative"
822 );
823 let wire = percent_encode_path(validated);
824 let once = percent_decode_str(&wire)
825 .decode_utf8()
826 .unwrap()
827 .into_owned();
828 assert_eq!(once, validated, "one decode must round-trip {validated:?}");
829 let twice = percent_decode_str(&once)
830 .decode_utf8()
831 .unwrap()
832 .into_owned();
833 assert_eq!(twice, validated, "second decode must be a no-op");
834 assert!(
835 !wire.contains("%2e")
836 && !wire.contains("%2E")
837 && !wire.contains("%2f")
838 && !wire.contains("%2F"),
839 "wire {wire:?} carries decodable dot/slash escapes"
840 );
841 }
842 }
843
844 #[test]
845 fn double_encoded_traversal_collapses_before_validation() {
846 let (id, path) = split_upstream_path("/waratah/ai/upstreams/zen/%252e%252e/admin")
850 .expect("split succeeds; validation is the next gate");
851 assert_eq!(id, "zen");
852 assert_eq!(path.as_deref(), Some("../admin"));
853 assert!(!valid_proxy_path(path.as_deref().unwrap()), "must 400");
854 let (_, path) = split_upstream_path("/waratah/ai/upstreams/zen/a%252fb").unwrap();
856 assert_eq!(path.as_deref(), Some("a/b"));
857 assert!(valid_proxy_path("a/b"), "a legit mid-segment slash is fine");
858 }
859
860 #[test]
861 fn fixpoint_decoding_is_bounded_and_stable() {
862 assert_eq!(percent_decode_fixpoint("plain").as_deref(), Some("plain"));
863 assert_eq!(percent_decode_fixpoint("a%20b").as_deref(), Some("a b"));
864 assert_eq!(percent_decode_fixpoint("%252e").as_deref(), Some("."));
866 assert_eq!(percent_decode_fixpoint("%25252e").as_deref(), Some("."));
867 assert_eq!(percent_decode_fixpoint("%2525252e").as_deref(), Some("."));
869 assert_eq!(percent_decode_fixpoint("%252525252e"), None);
870 assert_eq!(percent_decode_fixpoint("%ff"), None);
872 }
873
874 #[test]
875 fn proxy_paths_reject_traversal_and_empty_segments() {
876 assert!(valid_proxy_path("models"));
877 assert!(valid_proxy_path("chat/completions"));
878 assert!(!valid_proxy_path("models//list"));
879 assert!(!valid_proxy_path("a/../b"));
880 assert!(!valid_proxy_path("a\\b"));
881 assert!(!valid_proxy_path("a?b"));
882 }
883
884 #[test]
885 fn upstream_path_splits_id_and_rest() {
886 let (id, path) = split_upstream_path("/waratah/ai/upstreams/zen/models").unwrap();
887 assert_eq!(id, "zen");
888 assert_eq!(path.as_deref(), Some("models"));
889 let (id, path) = split_upstream_path("/waratah/ai/upstreams/zen").unwrap();
890 assert_eq!(id, "zen");
891 assert_eq!(path, None);
892 let (id, _) = split_upstream_path("/waratah/ai/upstreams/lo%2Dcal/m").unwrap();
895 assert_eq!(id, "lo-cal");
896 assert!(split_upstream_path("/waratah/ai/upstreams/").is_none());
897 assert!(split_upstream_path("/waratah/ai/upstreams/../x/m").is_none());
898 }
899
900 #[derive(Debug, thiserror::Error)]
903 #[error("wrapped: {0}")]
904 struct WrappedIo(#[source] std::io::Error);
905
906 #[test]
907 fn only_timedout_is_classified_as_a_timeout() {
908 assert!(is_timeout_error(&WrappedIo(std::io::Error::from(
909 std::io::ErrorKind::TimedOut
910 ))));
911 assert!(!is_timeout_error(&WrappedIo(std::io::Error::from(
914 std::io::ErrorKind::WouldBlock
915 ))));
916 assert!(!is_timeout_error(&WrappedIo(std::io::Error::other("boom"))));
917 }
918
919 #[tokio::test]
920 async fn elapsed_deadline_never_steals_ready_upstream_frames() {
921 let waker = std::task::Waker::noop();
934 let mut cx = std::task::Context::from_waker(waker);
935 let mut deadline = Box::pin(tokio::time::sleep_until(TokioInstant::now()));
936 let _ = deadline.as_mut().poll(&mut cx);
937 tokio::time::sleep(std::time::Duration::from_millis(1)).await;
940
941 let stream = ProxiedStream {
942 inner: Box::pin(tokio_stream::iter(vec![Ok(Bytes::from_static(
943 b"data: one\n\n",
944 ))])),
945 deadline,
946 sse_content_type: true,
947 tail: Tail::Streaming,
948 counts: Arc::new(ProxyCounts::default()),
949 log: Some(ProxyLog {
950 upstream: "up".to_owned(),
951 method: "GET".to_owned(),
952 path: "stream".to_owned(),
953 status: 200,
954 started: Instant::now(),
955 counts: Arc::new(ProxyCounts::default()),
956 completed: false,
957 truncated: false,
958 }),
959 };
960 let mut stream = std::pin::pin!(stream);
961 let first = stream.as_mut().poll_next(&mut cx);
962 assert!(
963 matches!(first, Poll::Ready(Some(Ok(chunk))) if chunk == "data: one\n\n"),
964 "ready data beats the elapsed deadline"
965 );
966 let second = stream.as_mut().poll_next(&mut cx);
967 assert!(
968 matches!(second, Poll::Ready(None)),
969 "clean EOF after the data"
970 );
971 let log = stream.log.take().unwrap();
973 assert!(log.completed);
974 assert!(!log.truncated);
975 }
976
977 #[tokio::test]
978 async fn counting_body_fuses_after_the_limit_error() {
979 let (tx, rx) = tokio::sync::mpsc::channel::<Result<bytes::Bytes, std::io::Error>>(8);
984 for _ in 0..3 {
985 tx.send(Ok(bytes::Bytes::from(vec![0u8; 48])))
986 .await
987 .unwrap();
988 }
989 drop(tx);
990 let counts = Arc::new(ProxyCounts::default());
991 let mut body = CountingBody::new(
992 Body::from_stream(tokio_stream::wrappers::ReceiverStream::new(rx)),
993 64,
994 Arc::clone(&counts),
995 );
996 let first = std::future::poll_fn(|cx| Pin::new(&mut body).poll_frame(cx)).await;
997 assert!(matches!(first, Some(Ok(_))), "first frame fits");
998 let second = std::future::poll_fn(|cx| Pin::new(&mut body).poll_frame(cx)).await;
999 assert!(
1000 matches!(second, Some(Err(_))),
1001 "second frame trips the limit"
1002 );
1003 for _ in 0..2 {
1004 let again = std::future::poll_fn(|cx| Pin::new(&mut body).poll_frame(cx)).await;
1005 assert!(
1006 matches!(again, Some(Err(_))),
1007 "fused: later polls repeat the error, not a clean end"
1008 );
1009 }
1010 assert!(counts.request_exceeded.load(Ordering::Relaxed));
1011 }
1012}