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