1use std::collections::HashMap;
20use std::fmt;
21use std::future::{Future, IntoFuture};
22use std::marker::PhantomData;
23use std::pin::Pin;
24use std::sync::atomic::{AtomicBool, Ordering};
25use std::sync::{Arc, Mutex};
26use std::task::{Context, Poll};
27use std::time::{Duration, Instant};
28
29use futures_core::Stream;
30use http_body::Body as _;
31use tonic::body::Body;
32use tonic::client::Grpc;
33use tonic::codegen::http::uri::PathAndQuery;
34use tonic::metadata::MetadataMap;
35use tonic::transport::{Channel, ClientTlsConfig, Endpoint};
36use tonic_prost::ProstCodec;
37use tower_layer::Layer;
38use tower_service::Service;
39
40use crate::opentelemetry::trace::FutureExt as _;
41
42use super::{CallError, Settings, base_url_of, invalid_header};
43use crate::ErrCode;
44use crate::services::{self, Propagate, PropagateLayer};
45
46type Sending<'c, T> = Pin<Box<dyn Future<Output = Result<T, CallError>> + Send + 'c>>;
48
49type BoxError = Box<dyn std::error::Error + Send + Sync>;
50
51pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
54
55const MAX_CHANNELS: usize = 64;
58
59const IDLE_CHANNEL: Duration = Duration::from_secs(5 * 60);
61
62const MAX_ERROR_BODY: usize = 4096;
64
65struct Call<'c> {
67 service: &'c services::Client,
68 client: &'c Settings,
69 settings: Settings,
70 path: &'static str,
71}
72
73struct Prepared<T> {
75 grpc: Grpc<Watched>,
77 request: tonic::Request<T>,
79 deadline: Option<Instant>,
81 heard: Arc<Heard>,
83}
84
85impl Call<'_> {
86 fn prepare<T>(&self, message: T) -> Result<Prepared<T>, CallError> {
88 let settings = self.settings.under(self.client);
89 let heard = Arc::new(Heard::default());
90 let grpc = grpc(base_url_of(self.service, &settings)?, &heard)?;
91 let mut request = tonic::Request::from_parts(
92 metadata(&settings.headers)?,
93 tonic::Extensions::default(),
94 message,
95 );
96 let deadline = deadline(&mut request, settings.limit());
97 Ok(Prepared {
98 grpc,
99 request,
100 deadline,
101 heard,
102 })
103 }
104
105 fn path(&self) -> PathAndQuery {
106 PathAndQuery::from_static(self.path)
107 }
108}
109
110fn metadata(headers: &[(String, String)]) -> Result<MetadataMap, CallError> {
114 let mut map = http::HeaderMap::new();
115 for (name, value) in headers {
116 let key = http::HeaderName::from_bytes(name.to_ascii_lowercase().as_bytes())
117 .map_err(|e| invalid_header(name, e))?;
118 let value = http::HeaderValue::from_str(value).map_err(|e| invalid_header(name, e))?;
119 map.insert(key, value);
120 }
121 let metadata = MetadataMap::from_headers(map);
122 for (name, _) in headers {
123 let name = name.to_ascii_lowercase();
124 if !name.ends_with("-bin") {
125 continue;
126 }
127 if let Some(Err(err)) = metadata.get_bin(name.as_str()).map(|v| v.to_bytes()) {
128 return Err(invalid_header(
129 &name,
130 format_args!("binary metadata is sent base64-encoded: {err}"),
131 ));
132 }
133 }
134 Ok(metadata)
135}
136
137fn grpc(base: &str, heard: &Arc<Heard>) -> Result<Grpc<Watched>, CallError> {
141 static CHANNELS: Mutex<Channels<Channel>> = Mutex::new(Channels::new());
142 let origin: http::Uri = base.parse().map_err(|e| invalid_base(base, e))?;
143 let channel =
144 CHANNELS
145 .lock()
146 .unwrap_or_else(|e| e.into_inner())
147 .get(base, Instant::now(), || connect(base, &origin))?;
148 Ok(Grpc::with_origin(
149 Watched {
150 inner: PropagateLayer.layer(channel),
151 heard: heard.clone(),
152 },
153 origin,
154 ))
155}
156
157fn invalid_base(base: &str, err: impl fmt::Display) -> CallError {
159 CallError::failed(
160 ErrCode::InvalidArgument,
161 format!("invalid base URL {base:?}: {err}"),
162 )
163}
164
165struct Channels<C> {
170 kept: Option<HashMap<String, (C, Instant)>>,
171}
172
173impl<C: Clone> Channels<C> {
174 const fn new() -> Self {
175 Channels { kept: None }
176 }
177
178 fn get(
181 &mut self,
182 base: &str,
183 now: Instant,
184 connect: impl FnOnce() -> Result<C, CallError>,
185 ) -> Result<C, CallError> {
186 let kept = self.kept.get_or_insert_with(HashMap::new);
187 kept.retain(|_, (_, used)| now.saturating_duration_since(*used) < IDLE_CHANNEL);
188 if let Some((channel, used)) = kept.get_mut(base) {
189 *used = now;
190 return Ok(channel.clone());
191 }
192 let channel = connect()?;
193 if kept.len() >= MAX_CHANNELS {
194 let oldest = kept
195 .iter()
196 .min_by_key(|(_, (_, used))| *used)
197 .map(|(base, _)| base.clone());
198 if let Some(oldest) = oldest {
199 kept.remove(&oldest);
200 }
201 }
202 kept.insert(base.to_string(), (channel.clone(), now));
203 Ok(channel)
204 }
205}
206
207fn connect(base: &str, origin: &http::Uri) -> Result<Channel, CallError> {
210 let mut endpoint = Endpoint::from_shared(base.to_string())
211 .map_err(|e| invalid_base(base, e))?
212 .connect_timeout(CONNECT_TIMEOUT);
213 match origin.scheme_str() {
214 Some("http") => {}
215 Some("https") => {
216 let tls = ClientTlsConfig::new()
217 .with_native_roots()
218 .timeout(CONNECT_TIMEOUT);
219 endpoint = endpoint.tls_config(tls).map_err(|err| {
220 CallError::failed(
221 ErrCode::Unavailable,
222 format!("configuring TLS for {base}: {err}"),
223 )
224 .caused_by(err)
225 })?;
226 }
227 _ => return Err(invalid_base(base, "gRPC is called at http:// or https://")),
228 }
229 let _runtime = crate::runtime::core().tokio_handle().enter();
232 Ok(endpoint.connect_lazy())
233}
234
235#[derive(Debug, Default)]
237struct Heard {
238 answered: AtomicBool,
240 status: AtomicBool,
242}
243
244#[derive(Clone)]
248struct Watched {
249 inner: Propagate<Channel>,
250 heard: Arc<Heard>,
251}
252
253impl Service<http::Request<Body>> for Watched {
254 type Response = http::Response<Body>;
255 type Error = BoxError;
256 type Future = Pin<Box<dyn Future<Output = Result<Self::Response, BoxError>> + Send>>;
257
258 fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), BoxError>> {
259 self.inner.poll_ready(cx).map_err(Into::into)
260 }
261
262 fn call(&mut self, request: http::Request<Body>) -> Self::Future {
263 let heard = self.heard.clone();
264 let response = self.inner.call(request);
265 Box::pin(async move {
266 let response = response.await?;
267 heard.answered.store(true, Ordering::Release);
268 if response.headers().contains_key("grpc-status") {
269 heard.status.store(true, Ordering::Release);
270 } else if let Some(not_grpc) = NotGrpc::of(&response) {
271 return Err(Box::new(not_grpc.read(response.into_body()).await) as BoxError);
272 }
273 Ok(response.map(|body| Body::new(Trailers { body, heard })))
274 })
275 }
276}
277
278struct Trailers {
280 body: Body,
281 heard: Arc<Heard>,
282}
283
284impl http_body::Body for Trailers {
285 type Data = bytes::Bytes;
286 type Error = tonic::Status;
287
288 fn poll_frame(
289 mut self: Pin<&mut Self>,
290 cx: &mut Context<'_>,
291 ) -> Poll<Option<Result<http_body::Frame<bytes::Bytes>, tonic::Status>>> {
292 let frame = Pin::new(&mut self.body).poll_frame(cx);
293 if let Poll::Ready(Some(Ok(frame))) = &frame
294 && frame
295 .trailers_ref()
296 .is_some_and(|t| t.contains_key("grpc-status"))
297 {
298 self.heard.status.store(true, Ordering::Release);
299 }
300 frame
301 }
302
303 fn is_end_stream(&self) -> bool {
304 self.body.is_end_stream()
305 }
306
307 fn size_hint(&self) -> http_body::SizeHint {
308 self.body.size_hint()
309 }
310}
311
312#[derive(Debug)]
316struct NotGrpc {
317 status: http::StatusCode,
318 content_type: String,
319 code: ErrCode,
320 message: String,
321}
322
323impl NotGrpc {
324 fn of<B>(response: &http::Response<B>) -> Option<NotGrpc> {
326 let status = response.status();
327 let content_type = response
328 .headers()
329 .get(http::header::CONTENT_TYPE)
330 .and_then(|v| v.to_str().ok())
331 .unwrap_or_default()
332 .to_ascii_lowercase();
333 let grpc = content_type
334 .strip_prefix("application/grpc")
335 .is_some_and(|rest| rest.is_empty() || rest.starts_with(['+', ';']));
336 if status == http::StatusCode::OK && grpc {
337 return None;
338 }
339 let code = match status.as_u16() {
341 400 => ErrCode::Internal,
342 401 => ErrCode::Unauthenticated,
343 403 => ErrCode::PermissionDenied,
344 404 => ErrCode::Unimplemented,
345 429 | 502 | 503 | 504 => ErrCode::Unavailable,
346 _ => ErrCode::Unknown,
347 };
348 Some(NotGrpc {
349 status,
350 content_type,
351 code,
352 message: String::new(),
353 })
354 }
355
356 async fn read(mut self, mut body: Body) -> NotGrpc {
358 let mut text = Vec::new();
359 while text.len() < MAX_ERROR_BODY {
360 match std::future::poll_fn(|cx| Pin::new(&mut body).poll_frame(cx)).await {
361 Some(Ok(frame)) => {
362 if let Ok(data) = frame.into_data() {
363 text.extend_from_slice(&data);
364 }
365 }
366 _ => break,
367 }
368 }
369 text.truncate(MAX_ERROR_BODY);
370 self.message = self.message_for(&String::from_utf8_lossy(&text));
371 self
372 }
373
374 fn message_for(&self, text: &str) -> String {
377 if self.content_type.starts_with("text/") && !text.trim().is_empty() {
378 return text.trim().to_string();
379 }
380 let content_type = match self.content_type.as_str() {
381 "" => "no content type",
382 ct => ct,
383 };
384 format!(
385 "service responded with {} ({content_type}), not gRPC",
386 self.status
387 )
388 }
389
390 fn error(&self) -> CallError {
392 let err = CallError::new(self.code, self.message.clone());
393 if self.status.is_client_error() || self.status.is_server_error() {
394 err.with_status(self.status.as_u16())
395 } else {
396 err
397 }
398 }
399}
400
401impl fmt::Display for NotGrpc {
402 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
403 f.write_str(&self.message)
404 }
405}
406
407impl std::error::Error for NotGrpc {}
408
409const MAX_TIMEOUT: Duration = Duration::from_secs(99_999_999 * 3600);
411
412fn deadline<T>(request: &mut tonic::Request<T>, timeout: Option<Duration>) -> Option<Instant> {
416 let timeout = timeout.filter(|t| *t <= MAX_TIMEOUT)?;
417 let deadline = Instant::now().checked_add(timeout)?;
418 request.set_timeout(timeout);
419 Some(deadline)
420}
421
422async fn within<T>(
424 deadline: Option<Instant>,
425 call: impl Future<Output = Result<T, CallError>>,
426) -> Result<T, CallError> {
427 let Some(deadline) = deadline else {
428 return call.await;
429 };
430 tokio::time::timeout_at(deadline.into(), call)
431 .await
432 .unwrap_or_else(|_| Err(timed_out()))
433}
434
435fn timed_out() -> CallError {
437 CallError::failed(ErrCode::DeadlineExceeded, "call exceeded its timeout")
438}
439
440#[derive(Clone, PartialEq, prost::Message)]
442struct RpcStatus {
443 #[prost(int32, tag = "1")]
444 code: i32,
445 #[prost(string, tag = "2")]
446 message: String,
447 #[prost(message, repeated, tag = "3")]
448 details: Vec<prost_types::Any>,
449}
450
451fn status_error(status: tonic::Status, deadline: Option<Instant>, heard: &Heard) -> CallError {
461 if let Some(not_grpc) = find::<NotGrpc>(&status) {
462 return not_grpc.error().caused_by(status);
463 }
464 let past_deadline = deadline.is_some_and(|d| Instant::now() >= d);
465 let sent = heard.status.load(Ordering::Acquire) && std::error::Error::source(&status).is_none();
466 let code = if past_deadline
467 && matches!(
468 status.code(),
469 tonic::Code::Cancelled | tonic::Code::DeadlineExceeded
470 ) {
471 ErrCode::DeadlineExceeded
472 } else if sent {
473 code_of(status.code())
474 } else if lost(&status, heard.answered.load(Ordering::Acquire)) {
475 ErrCode::Unavailable
476 } else {
477 code_of(status.code())
478 };
479 let message = status.message().to_string();
480 let err = if sent {
481 let mut err = CallError::new(code, message);
482 if let Ok(details) = <RpcStatus as prost::Message>::decode(status.details()) {
483 err.grpc_details = details.details;
484 }
485 err
486 } else {
487 CallError::failed(code, message)
488 };
489 err.caused_by(status)
490}
491
492fn lost(status: &tonic::Status, answered: bool) -> bool {
496 match find::<h2::Error>(status) {
497 Some(err) if err.is_reset() && err.is_remote() => false,
498 Some(err) if err.is_io() || err.is_go_away() => true,
499 _ => !answered,
500 }
501}
502
503fn find<E: std::error::Error + 'static>(status: &tonic::Status) -> Option<&E> {
505 let mut source = std::error::Error::source(status);
506 while let Some(err) = source {
507 if let Some(found) = err.downcast_ref::<E>() {
508 return Some(found);
509 }
510 source = err.source();
511 }
512 None
513}
514
515fn code_of(code: tonic::Code) -> ErrCode {
517 match code {
518 tonic::Code::Ok | tonic::Code::Unknown => ErrCode::Unknown,
519 tonic::Code::Cancelled => ErrCode::Canceled,
520 tonic::Code::InvalidArgument => ErrCode::InvalidArgument,
521 tonic::Code::DeadlineExceeded => ErrCode::DeadlineExceeded,
522 tonic::Code::NotFound => ErrCode::NotFound,
523 tonic::Code::AlreadyExists => ErrCode::AlreadyExists,
524 tonic::Code::PermissionDenied => ErrCode::PermissionDenied,
525 tonic::Code::ResourceExhausted => ErrCode::ResourceExhausted,
526 tonic::Code::FailedPrecondition => ErrCode::FailedPrecondition,
527 tonic::Code::Aborted => ErrCode::Aborted,
528 tonic::Code::OutOfRange => ErrCode::OutOfRange,
529 tonic::Code::Unimplemented => ErrCode::Unimplemented,
530 tonic::Code::Internal => ErrCode::Internal,
531 tonic::Code::Unavailable => ErrCode::Unavailable,
532 tonic::Code::DataLoss => ErrCode::DataLoss,
533 tonic::Code::Unauthenticated => ErrCode::Unauthenticated,
534 }
535}
536
537async fn ready(grpc: &mut Grpc<Watched>) -> Result<(), CallError> {
539 grpc.ready().await.map_err(|err| {
540 let status = tonic::Status::from_error(err);
541 CallError::failed(ErrCode::Unavailable, format!("connecting: {status}")).caused_by(status)
542 })
543}
544
545macro_rules! settings {
547 () => {
548 pub fn timeout(mut self, timeout: Duration) -> Self {
555 self.call.settings = self.call.settings.timeout(timeout);
556 self
557 }
558
559 pub fn no_timeout(mut self) -> Self {
561 self.call.settings = self.call.settings.no_timeout();
562 self
563 }
564
565 pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
571 self.call.settings = self.call.settings.header(name, value);
572 self
573 }
574 };
575}
576
577#[must_use = "a call is not sent until awaited"]
579pub struct Unary<'c, Req, Resp> {
580 call: Call<'c>,
581 message: Req,
582 answer: PhantomData<fn() -> Resp>,
583}
584
585impl<'c, Req, Resp> Unary<'c, Req, Resp> {
586 #[doc(hidden)]
588 pub fn new(
589 service: &'c services::Client,
590 client: &'c Settings,
591 path: &'static str,
592 message: Req,
593 ) -> Self {
594 Unary {
595 call: Call {
596 service,
597 client,
598 settings: Settings::new(),
599 path,
600 },
601 message,
602 answer: PhantomData,
603 }
604 }
605
606 settings!();
607}
608
609impl<'c, Req, Resp> IntoFuture for Unary<'c, Req, Resp>
610where
611 Req: prost::Message + Send + Sync + 'static,
612 Resp: prost::Message + Default + Send + Sync + 'static,
613{
614 type Output = Result<Resp, CallError>;
615 type IntoFuture = Sending<'c, Resp>;
616
617 fn into_future(self) -> Self::IntoFuture {
621 Box::pin(super::sent(async move {
622 let Prepared {
623 mut grpc,
624 request,
625 deadline,
626 heard,
627 } = self.call.prepare(self.message)?;
628 let path = self.call.path();
629 within(deadline, async move {
630 ready(&mut grpc).await?;
631 let codec = ProstCodec::<Req, Resp>::default();
632 grpc.unary(request, path, codec)
633 .await
634 .map(tonic::Response::into_inner)
635 .map_err(|s| status_error(s, deadline, &heard))
636 })
637 .await
638 }))
639 }
640}
641
642#[must_use = "a call is not sent until awaited"]
644pub struct ServerStreaming<'c, Req, Resp> {
645 call: Call<'c>,
646 message: Req,
647 answer: PhantomData<fn() -> Resp>,
648}
649
650impl<'c, Req, Resp> ServerStreaming<'c, Req, Resp> {
651 #[doc(hidden)]
653 pub fn new(
654 service: &'c services::Client,
655 client: &'c Settings,
656 path: &'static str,
657 message: Req,
658 ) -> Self {
659 ServerStreaming {
660 call: Call {
661 service,
662 client,
663 settings: Settings::new(),
664 path,
665 },
666 message,
667 answer: PhantomData,
668 }
669 }
670
671 settings!();
672}
673
674impl<'c, Req, Resp> IntoFuture for ServerStreaming<'c, Req, Resp>
675where
676 Req: prost::Message + Send + Sync + 'static,
677 Resp: prost::Message + Default + Send + Sync + 'static,
678{
679 type Output = Result<Streaming<Resp>, CallError>;
680 type IntoFuture = Sending<'c, Streaming<Resp>>;
681
682 fn into_future(self) -> Self::IntoFuture {
686 Box::pin(super::sent(async move {
687 let Prepared {
688 mut grpc,
689 request,
690 deadline,
691 heard,
692 } = self.call.prepare(self.message)?;
693 let path = self.call.path();
694 let inner = within(deadline, async {
695 ready(&mut grpc).await?;
696 let codec = ProstCodec::<Req, Resp>::default();
697 grpc.server_streaming(request, path, codec)
698 .await
699 .map_err(|s| status_error(s, deadline, &heard))
700 })
701 .await?
702 .into_inner();
703 Ok(Streaming::new(
704 State::Open(Box::new(inner)),
705 deadline,
706 heard,
707 ))
708 }))
709 }
710}
711
712#[must_use = "a call is not sent until awaited"]
714pub struct ClientStreaming<'c, S, Resp> {
715 call: Call<'c>,
716 messages: S,
717 answer: PhantomData<fn() -> Resp>,
718}
719
720impl<'c, S, Resp> ClientStreaming<'c, S, Resp> {
721 #[doc(hidden)]
723 pub fn new(
724 service: &'c services::Client,
725 client: &'c Settings,
726 path: &'static str,
727 messages: S,
728 ) -> Self {
729 ClientStreaming {
730 call: Call {
731 service,
732 client,
733 settings: Settings::new(),
734 path,
735 },
736 messages,
737 answer: PhantomData,
738 }
739 }
740
741 settings!();
742}
743
744impl<'c, S, Resp> IntoFuture for ClientStreaming<'c, S, Resp>
745where
746 S: Stream + Send + 'static,
747 S::Item: prost::Message + Send + Sync + 'static,
748 Resp: prost::Message + Default + Send + Sync + 'static,
749{
750 type Output = Result<Resp, CallError>;
751 type IntoFuture = Sending<'c, Resp>;
752
753 fn into_future(self) -> Self::IntoFuture {
757 Box::pin(super::sent(async move {
758 let Prepared {
759 mut grpc,
760 request,
761 deadline,
762 heard,
763 } = self.call.prepare(self.messages)?;
764 let path = self.call.path();
765 within(deadline, async move {
766 ready(&mut grpc).await?;
767 let codec = ProstCodec::<S::Item, Resp>::default();
768 grpc.client_streaming(request, path, codec)
769 .await
770 .map(tonic::Response::into_inner)
771 .map_err(|s| status_error(s, deadline, &heard))
772 })
773 .await
774 }))
775 }
776}
777
778#[must_use = "a call is not sent until awaited"]
781pub struct BidiStreaming<'c, S, Resp> {
782 call: Call<'c>,
783 messages: S,
784 answer: PhantomData<fn() -> Resp>,
785}
786
787impl<'c, S, Resp> BidiStreaming<'c, S, Resp> {
788 #[doc(hidden)]
790 pub fn new(
791 service: &'c services::Client,
792 client: &'c Settings,
793 path: &'static str,
794 messages: S,
795 ) -> Self {
796 BidiStreaming {
797 call: Call {
798 service,
799 client,
800 settings: Settings::new(),
801 path,
802 },
803 messages,
804 answer: PhantomData,
805 }
806 }
807
808 settings!();
809}
810
811impl<'c, S, Resp> IntoFuture for BidiStreaming<'c, S, Resp>
812where
813 S: Stream + Send + 'static,
814 S::Item: prost::Message + Send + Sync + 'static,
815 Resp: prost::Message + Default + Send + Sync + 'static,
816{
817 type Output = Result<Streaming<Resp>, CallError>;
818 type IntoFuture = Sending<'c, Streaming<Resp>>;
819
820 fn into_future(self) -> Self::IntoFuture {
828 Box::pin(super::sent(async move {
829 let Prepared {
830 mut grpc,
831 request,
832 deadline,
833 heard,
834 } = self.call.prepare(self.messages)?;
835 let path = self.call.path();
836 let answering = heard.clone();
837 let mut call: Answering<Resp> = Box::pin(
838 async move {
839 ready(&mut grpc).await?;
840 let codec = ProstCodec::<S::Item, Resp>::default();
841 grpc.streaming(request, path, codec)
842 .await
843 .map(tonic::Response::into_inner)
844 .map_err(|s| status_error(s, deadline, &answering))
845 }
846 .with_context(crate::opentelemetry::Context::current()),
847 );
848 let state = std::future::poll_fn(|cx| match call.as_mut().poll(cx) {
850 Poll::Ready(Ok(messages)) => Poll::Ready(Ok(Some(messages))),
851 Poll::Ready(Err(err)) => Poll::Ready(Err(err)),
852 Poll::Pending => Poll::Ready(Ok(None)),
853 })
854 .await?;
855 let state = match state {
856 Some(messages) => State::Open(Box::new(messages)),
857 None => State::Answering(call),
858 };
859 Ok(Streaming::new(state, deadline, heard))
860 }))
861 }
862}
863
864pub struct Streaming<T> {
871 state: State<T>,
872 deadline: Option<Instant>,
873 timer: Option<Pin<Box<tokio::time::Sleep>>>,
875 heard: Arc<Heard>,
876}
877
878type Answering<T> = Pin<Box<dyn Future<Output = Result<tonic::Streaming<T>, CallError>> + Send>>;
880
881enum State<T> {
883 Answering(Answering<T>),
885 Open(Box<tonic::Streaming<T>>),
887 Ended,
889}
890
891impl<T> Streaming<T> {
892 fn new(state: State<T>, deadline: Option<Instant>, heard: Arc<Heard>) -> Self {
893 Streaming {
894 state,
895 deadline,
896 timer: deadline.map(|d| Box::pin(tokio::time::sleep_until(d.into()))),
897 heard,
898 }
899 }
900
901 pub async fn message(&mut self) -> Result<Option<T>, CallError> {
903 std::future::poll_fn(|cx| Pin::new(&mut *self).poll_next(cx))
904 .await
905 .transpose()
906 }
907}
908
909impl<T> std::fmt::Debug for Streaming<T> {
910 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
911 f.debug_struct("Streaming").finish_non_exhaustive()
912 }
913}
914
915impl<T> Stream for Streaming<T> {
916 type Item = Result<T, CallError>;
917
918 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
919 let this = &mut *self;
920 if matches!(this.state, State::Ended) {
921 return Poll::Ready(None);
922 }
923 let past_deadline = this
924 .timer
925 .as_mut()
926 .is_some_and(|timer| timer.as_mut().poll(cx).is_ready());
927 let item = loop {
928 if past_deadline {
929 break Some(Err(timed_out()));
930 }
931 match &mut this.state {
932 State::Answering(call) => match call.as_mut().poll(cx) {
933 Poll::Ready(Ok(messages)) => this.state = State::Open(Box::new(messages)),
934 Poll::Ready(Err(err)) => break Some(Err(err)),
935 Poll::Pending => return Poll::Pending,
936 },
937 State::Open(messages) => match Pin::new(messages).poll_next(cx) {
938 Poll::Ready(Some(Ok(message))) => return Poll::Ready(Some(Ok(message))),
939 Poll::Ready(Some(Err(status))) => {
940 break Some(Err(status_error(status, this.deadline, &this.heard)));
941 }
942 Poll::Ready(None) => break None,
943 Poll::Pending => return Poll::Pending,
944 },
945 State::Ended => break None,
946 }
947 };
948 this.state = State::Ended;
950 this.timer = None;
951 Poll::Ready(item)
952 }
953}
954
955#[cfg(test)]
956mod tests {
957 use super::*;
958
959 fn answered() -> Heard {
961 Heard {
962 answered: AtomicBool::new(true),
963 status: AtomicBool::new(true),
964 }
965 }
966
967 fn headers_only() -> Heard {
969 Heard {
970 answered: AtomicBool::new(true),
971 status: AtomicBool::new(false),
972 }
973 }
974
975 #[test]
976 fn a_cancel_past_the_deadline_is_deadline_exceeded() {
977 let past = Some(Instant::now() - Duration::from_millis(1));
978 let future = Some(Instant::now() + Duration::from_secs(60));
979 let none = Heard::default();
980 assert_eq!(
981 status_error(tonic::Status::cancelled("Timeout expired"), past, &none).code,
982 ErrCode::DeadlineExceeded
983 );
984 assert_eq!(
985 status_error(
986 tonic::Status::cancelled("Timeout expired"),
987 future,
988 &answered()
989 )
990 .code,
991 ErrCode::Canceled
992 );
993 assert_eq!(
994 status_error(
995 tonic::Status::cancelled("Timeout expired"),
996 None,
997 &answered()
998 )
999 .code,
1000 ErrCode::Canceled
1001 );
1002 let err = status_error(
1003 tonic::Status::not_found("no such product"),
1004 None,
1005 &answered(),
1006 );
1007 assert_eq!((err.code, err.status), (ErrCode::NotFound, 404));
1008 assert_eq!(err.message, "no such product");
1009 }
1010
1011 #[test]
1012 fn a_timeout_too_long_to_send_is_none() {
1013 let mut request = tonic::Request::new(());
1014 assert_eq!(deadline(&mut request, Some(Duration::MAX)), None);
1015 assert!(request.metadata().get("grpc-timeout").is_none());
1016 assert!(deadline(&mut request, Some(Duration::from_secs(1))).is_some());
1017 assert!(request.metadata().get("grpc-timeout").is_some());
1018 }
1019
1020 #[test]
1021 fn only_a_status_the_service_sent_has_an_http_status() {
1022 let past = Some(Instant::now() - Duration::from_millis(1));
1023 let timed_out = status_error(
1024 tonic::Status::cancelled("Timeout expired"),
1025 past,
1026 &Heard::default(),
1027 );
1028 assert_eq!(timed_out.status, 0);
1029 let refused = tonic::Status::from_error(Box::new(std::io::Error::from(
1030 std::io::ErrorKind::ConnectionRefused,
1031 )));
1032 assert_eq!(status_error(refused, None, &Heard::default()).status, 0);
1033 let sent = status_error(tonic::Status::unavailable("draining"), None, &answered());
1034 assert_eq!((sent.code, sent.status), (ErrCode::Unavailable, 503));
1035 let undecodable = status_error(tonic::Status::internal("bad frame"), None, &headers_only());
1038 assert_eq!(
1039 (undecodable.code, undecodable.status),
1040 (ErrCode::Internal, 0)
1041 );
1042 }
1043
1044 #[test]
1045 fn no_answer_is_unavailable() {
1046 for status in [
1049 tonic::Status::from_error(Box::new(std::io::Error::from(
1050 std::io::ErrorKind::ConnectionReset,
1051 ))),
1052 tonic::Status::from_error(Box::new(h2::Error::from(h2::Reason::PROTOCOL_ERROR))),
1053 ] {
1054 let err = status_error(status, None, &Heard::default());
1055 assert_eq!((err.code, err.status), (ErrCode::Unavailable, 0), "{err}");
1056 }
1057 }
1058
1059 #[test]
1060 fn a_status_keeps_its_details() {
1061 let detail = prost_types::Any {
1062 type_url: "type.googleapis.com/conformance.v1.Detail".into(),
1063 value: vec![0x0a, 0x03, b'w', b'h', b'y'],
1064 };
1065 let details = prost::Message::encode_to_vec(&RpcStatus {
1066 code: 5,
1067 message: "nope".into(),
1068 details: vec![detail.clone()],
1069 });
1070 let status = tonic::Status::with_details(tonic::Code::NotFound, "nope", details.into());
1071 let err = status_error(status, None, &answered());
1072 assert_eq!(
1073 (err.code, err.message.as_str()),
1074 (ErrCode::NotFound, "nope")
1075 );
1076 assert_eq!(err.grpc_details, [detail]);
1077 let err = status_error(tonic::Status::not_found("nope"), None, &answered());
1078 assert!(err.grpc_details.is_empty());
1079 }
1080
1081 #[test]
1082 fn an_answer_that_is_not_grpc_is_its_http_status() {
1083 let response = |status: u16, content_type: &str| {
1084 http::Response::builder()
1085 .status(status)
1086 .header("content-type", content_type)
1087 .body(())
1088 .unwrap()
1089 };
1090 assert!(NotGrpc::of(&response(200, "application/grpc")).is_none());
1091 assert!(NotGrpc::of(&response(200, "application/grpc+proto")).is_none());
1092 let mut bad_gateway = NotGrpc::of(&response(502, "text/plain")).unwrap();
1093 bad_gateway.message = bad_gateway.message_for("service down\n");
1094 let err = bad_gateway.error();
1095 assert_eq!(
1096 (err.code, err.status, err.message.as_str()),
1097 (ErrCode::Unavailable, 502, "service down")
1098 );
1099 let status = tonic::Status::from_error(Box::new(bad_gateway));
1101 let err = status_error(status, None, &Heard::default());
1102 assert_eq!((err.code, err.status), (ErrCode::Unavailable, 502));
1103
1104 for (status, code) in [
1105 (400, ErrCode::Internal),
1106 (401, ErrCode::Unauthenticated),
1107 (403, ErrCode::PermissionDenied),
1108 (404, ErrCode::Unimplemented),
1109 (429, ErrCode::Unavailable),
1110 (503, ErrCode::Unavailable),
1111 (504, ErrCode::Unavailable),
1112 (500, ErrCode::Unknown),
1113 ] {
1114 let answer = NotGrpc::of(&response(status, "application/json")).unwrap();
1115 assert_eq!(answer.code, code, "{status}");
1116 assert_eq!(answer.error().status, status);
1117 }
1118 let html = NotGrpc::of(&response(200, "text/html")).unwrap();
1119 assert_eq!(html.code, ErrCode::Unknown);
1120 assert_eq!(html.error().status, 500);
1121 assert_eq!(
1122 html.message_for(""),
1123 "service responded with 200 OK (text/html), not gRPC"
1124 );
1125 }
1126
1127 #[test]
1128 fn binary_metadata_is_base64() {
1129 let headers = |pairs: &[(&str, &str)]| -> Vec<(String, String)> {
1130 pairs
1131 .iter()
1132 .map(|(k, v)| (k.to_string(), v.to_string()))
1133 .collect()
1134 };
1135 let metadata = metadata(&headers(&[("X-Id-Bin", "AP8Q"), ("x-plain", "a")])).unwrap();
1136 assert_eq!(
1137 metadata.get_bin("x-id-bin").unwrap().to_bytes().unwrap(),
1138 &[0x00, 0xff, 0x10][..]
1139 );
1140 assert_eq!(metadata.get("x-plain").unwrap(), "a");
1141 let err = super::metadata(&headers(&[("x-id-bin", "not base64!")])).unwrap_err();
1142 assert_eq!(err.code, ErrCode::InvalidArgument);
1143 assert!(err.message.contains("base64"), "{err}");
1144 let err = super::metadata(&headers(&[("x y", "a")])).unwrap_err();
1145 assert_eq!(err.code, ErrCode::InvalidArgument);
1146 }
1147
1148 #[test]
1149 fn channels_are_dropped_when_idle_or_too_many() {
1150 let mut channels = Channels::<usize>::new();
1151 let start = Instant::now();
1152 let mut made = 0;
1153 let mut get = |channels: &mut Channels<usize>, base: &str, at: Duration| {
1154 channels
1155 .get(base, start + at, || {
1156 made += 1;
1157 Ok(made)
1158 })
1159 .unwrap()
1160 };
1161 assert_eq!(get(&mut channels, "http://a", Duration::ZERO), 1);
1162 assert_eq!(get(&mut channels, "http://a", Duration::from_secs(1)), 1);
1163 let later = Duration::from_secs(1) + IDLE_CHANNEL;
1165 assert_eq!(get(&mut channels, "http://a", later), 2);
1166 for i in 0..MAX_CHANNELS * 2 {
1167 let at = later + Duration::from_millis(i as u64);
1168 get(&mut channels, &format!("http://{i}"), at);
1169 }
1170 let kept = channels.kept.as_ref().unwrap();
1171 assert_eq!(kept.len(), MAX_CHANNELS);
1172 assert!(kept.contains_key(&format!("http://{}", MAX_CHANNELS * 2 - 1)));
1174 assert!(!kept.contains_key("http://0"));
1175 }
1176}