1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
use crate::codec::compression::{
CompressionEncoding, EnabledCompressionEncodings, SingleMessageCompressionOverride,
};
use crate::codec::EncodeBody;
use crate::metadata::GRPC_CONTENT_TYPE;
use crate::{
body::BoxBody,
codec::{Codec, Streaming},
server::{ClientStreamingService, ServerStreamingService, StreamingService, UnaryService},
Request, Status,
};
use http_body::Body;
use std::{fmt, pin::pin};
use tokio_stream::{Stream, StreamExt};
macro_rules! t {
($result:expr) => {
match $result {
Ok(value) => value,
Err(status) => return status.into_http(),
}
};
}
/// A gRPC Server handler.
///
/// This will wrap some inner [`Codec`] and provide utilities to handle
/// inbound unary, client side streaming, server side streaming, and
/// bi-directional streaming.
///
/// Each request handler method accepts some service that implements the
/// corresponding service trait and a http request that contains some body that
/// implements some [`Body`].
pub struct Grpc<T> {
codec: T,
/// Which compression encodings does the server accept for requests?
accept_compression_encodings: EnabledCompressionEncodings,
/// Which compression encodings might the server use for responses.
send_compression_encodings: EnabledCompressionEncodings,
/// Limits the maximum size of a decoded message.
max_decoding_message_size: Option<usize>,
/// Limits the maximum size of an encoded message.
max_encoding_message_size: Option<usize>,
}
impl<T> Grpc<T>
where
T: Codec,
{
/// Creates a new gRPC server with the provided [`Codec`].
pub fn new(codec: T) -> Self {
Self {
codec,
accept_compression_encodings: EnabledCompressionEncodings::default(),
send_compression_encodings: EnabledCompressionEncodings::default(),
max_decoding_message_size: None,
max_encoding_message_size: None,
}
}
/// Enable accepting compressed requests.
///
/// If a request with an unsupported encoding is received the server will respond with
/// [`Code::UnUnimplemented`](crate::Code).
///
/// # Example
///
/// The most common way of using this is through a server generated by tonic-build:
///
/// ```rust
/// # enum CompressionEncoding { Gzip }
/// # struct Svc;
/// # struct ExampleServer<T>(T);
/// # impl<T> ExampleServer<T> {
/// # fn new(svc: T) -> Self { Self(svc) }
/// # fn accept_compressed(self, _: CompressionEncoding) -> Self { self }
/// # }
/// # #[tonic::async_trait]
/// # trait Example {}
///
/// #[tonic::async_trait]
/// impl Example for Svc {
/// // ...
/// }
///
/// let service = ExampleServer::new(Svc).accept_compressed(CompressionEncoding::Gzip);
/// ```
pub fn accept_compressed(mut self, encoding: CompressionEncoding) -> Self {
self.accept_compression_encodings.enable(encoding);
self
}
/// Enable sending compressed responses.
///
/// Requires the client to also support receiving compressed responses.
///
/// # Example
///
/// The most common way of using this is through a server generated by tonic-build:
///
/// ```rust
/// # enum CompressionEncoding { Gzip }
/// # struct Svc;
/// # struct ExampleServer<T>(T);
/// # impl<T> ExampleServer<T> {
/// # fn new(svc: T) -> Self { Self(svc) }
/// # fn send_compressed(self, _: CompressionEncoding) -> Self { self }
/// # }
/// # #[tonic::async_trait]
/// # trait Example {}
///
/// #[tonic::async_trait]
/// impl Example for Svc {
/// // ...
/// }
///
/// let service = ExampleServer::new(Svc).send_compressed(CompressionEncoding::Gzip);
/// ```
pub fn send_compressed(mut self, encoding: CompressionEncoding) -> Self {
self.send_compression_encodings.enable(encoding);
self
}
/// Limits the maximum size of a decoded message.
///
/// # Example
///
/// The most common way of using this is through a server generated by tonic-build:
///
/// ```rust
/// # struct Svc;
/// # struct ExampleServer<T>(T);
/// # impl<T> ExampleServer<T> {
/// # fn new(svc: T) -> Self { Self(svc) }
/// # fn max_decoding_message_size(self, _: usize) -> Self { self }
/// # }
/// # #[tonic::async_trait]
/// # trait Example {}
///
/// #[tonic::async_trait]
/// impl Example for Svc {
/// // ...
/// }
///
/// // Set the limit to 2MB, Defaults to 4MB.
/// let limit = 2 * 1024 * 1024;
/// let service = ExampleServer::new(Svc).max_decoding_message_size(limit);
/// ```
pub fn max_decoding_message_size(mut self, limit: usize) -> Self {
self.max_decoding_message_size = Some(limit);
self
}
/// Limits the maximum size of a encoded message.
///
/// # Example
///
/// The most common way of using this is through a server generated by tonic-build:
///
/// ```rust
/// # struct Svc;
/// # struct ExampleServer<T>(T);
/// # impl<T> ExampleServer<T> {
/// # fn new(svc: T) -> Self { Self(svc) }
/// # fn max_encoding_message_size(self, _: usize) -> Self { self }
/// # }
/// # #[tonic::async_trait]
/// # trait Example {}
///
/// #[tonic::async_trait]
/// impl Example for Svc {
/// // ...
/// }
///
/// // Set the limit to 2MB, Defaults to 4MB.
/// let limit = 2 * 1024 * 1024;
/// let service = ExampleServer::new(Svc).max_encoding_message_size(limit);
/// ```
pub fn max_encoding_message_size(mut self, limit: usize) -> Self {
self.max_encoding_message_size = Some(limit);
self
}
#[doc(hidden)]
pub fn apply_compression_config(
self,
accept_encodings: EnabledCompressionEncodings,
send_encodings: EnabledCompressionEncodings,
) -> Self {
let mut this = self;
for &encoding in CompressionEncoding::ENCODINGS {
if accept_encodings.is_enabled(encoding) {
this = this.accept_compressed(encoding);
}
if send_encodings.is_enabled(encoding) {
this = this.send_compressed(encoding);
}
}
this
}
#[doc(hidden)]
pub fn apply_max_message_size_config(
self,
max_decoding_message_size: Option<usize>,
max_encoding_message_size: Option<usize>,
) -> Self {
let mut this = self;
if let Some(limit) = max_decoding_message_size {
this = this.max_decoding_message_size(limit);
}
if let Some(limit) = max_encoding_message_size {
this = this.max_encoding_message_size(limit);
}
this
}
/// Handle a single unary gRPC request.
pub async fn unary<S, B>(
&mut self,
mut service: S,
req: http::Request<B>,
) -> http::Response<BoxBody>
where
S: UnaryService<T::Decode, Response = T::Encode>,
B: Body + Send + 'static,
B::Error: Into<crate::Error> + Send,
{
let accept_encoding = CompressionEncoding::from_accept_encoding_header(
req.headers(),
self.send_compression_encodings,
);
let request = match self.map_request_unary(req).await {
Ok(r) => r,
Err(status) => {
return self.map_response::<tokio_stream::Once<Result<T::Encode, Status>>>(
Err(status),
accept_encoding,
SingleMessageCompressionOverride::default(),
self.max_encoding_message_size,
);
}
};
let response = service
.call(request)
.await
.map(|r| r.map(|m| tokio_stream::once(Ok(m))));
let compression_override = compression_override_from_response(&response);
self.map_response(
response,
accept_encoding,
compression_override,
self.max_encoding_message_size,
)
}
/// Handle a server side streaming request.
pub async fn server_streaming<S, B>(
&mut self,
mut service: S,
req: http::Request<B>,
) -> http::Response<BoxBody>
where
S: ServerStreamingService<T::Decode, Response = T::Encode>,
S::ResponseStream: Send + 'static,
B: Body + Send + 'static,
B::Error: Into<crate::Error> + Send,
{
let accept_encoding = CompressionEncoding::from_accept_encoding_header(
req.headers(),
self.send_compression_encodings,
);
let request = match self.map_request_unary(req).await {
Ok(r) => r,
Err(status) => {
return self.map_response::<S::ResponseStream>(
Err(status),
accept_encoding,
SingleMessageCompressionOverride::default(),
self.max_encoding_message_size,
);
}
};
let response = service.call(request).await;
self.map_response(
response,
accept_encoding,
// disabling compression of individual stream items must be done on
// the items themselves
SingleMessageCompressionOverride::default(),
self.max_encoding_message_size,
)
}
/// Handle a client side streaming gRPC request.
pub async fn client_streaming<S, B>(
&mut self,
mut service: S,
req: http::Request<B>,
) -> http::Response<BoxBody>
where
S: ClientStreamingService<T::Decode, Response = T::Encode>,
B: Body + Send + 'static,
B::Error: Into<crate::Error> + Send + 'static,
{
let accept_encoding = CompressionEncoding::from_accept_encoding_header(
req.headers(),
self.send_compression_encodings,
);
let request = t!(self.map_request_streaming(req));
let response = service
.call(request)
.await
.map(|r| r.map(|m| tokio_stream::once(Ok(m))));
let compression_override = compression_override_from_response(&response);
self.map_response(
response,
accept_encoding,
compression_override,
self.max_encoding_message_size,
)
}
/// Handle a bi-directional streaming gRPC request.
pub async fn streaming<S, B>(
&mut self,
mut service: S,
req: http::Request<B>,
) -> http::Response<BoxBody>
where
S: StreamingService<T::Decode, Response = T::Encode> + Send,
S::ResponseStream: Send + 'static,
B: Body + Send + 'static,
B::Error: Into<crate::Error> + Send,
{
let accept_encoding = CompressionEncoding::from_accept_encoding_header(
req.headers(),
self.send_compression_encodings,
);
let request = t!(self.map_request_streaming(req));
let response = service.call(request).await;
self.map_response(
response,
accept_encoding,
SingleMessageCompressionOverride::default(),
self.max_encoding_message_size,
)
}
async fn map_request_unary<B>(
&mut self,
request: http::Request<B>,
) -> Result<Request<T::Decode>, Status>
where
B: Body + Send + 'static,
B::Error: Into<crate::Error> + Send,
{
let request_compression_encoding = self.request_encoding_if_supported(&request)?;
let (parts, body) = request.into_parts();
let mut stream = pin!(Streaming::new_request(
self.codec.decoder(),
body,
request_compression_encoding,
self.max_decoding_message_size,
));
let message = stream
.try_next()
.await?
.ok_or_else(|| Status::internal("Missing request message."))?;
let mut req = Request::from_http_parts(parts, message);
if let Some(trailers) = stream.trailers().await? {
req.metadata_mut().merge(trailers);
}
Ok(req)
}
fn map_request_streaming<B>(
&mut self,
request: http::Request<B>,
) -> Result<Request<Streaming<T::Decode>>, Status>
where
B: Body + Send + 'static,
B::Error: Into<crate::Error> + Send,
{
let encoding = self.request_encoding_if_supported(&request)?;
let request = request.map(|body| {
Streaming::new_request(
self.codec.decoder(),
body,
encoding,
self.max_decoding_message_size,
)
});
Ok(Request::from_http(request))
}
fn map_response<B>(
&mut self,
response: Result<crate::Response<B>, Status>,
accept_encoding: Option<CompressionEncoding>,
compression_override: SingleMessageCompressionOverride,
max_message_size: Option<usize>,
) -> http::Response<BoxBody>
where
B: Stream<Item = Result<T::Encode, Status>> + Send + 'static,
{
let response = t!(response);
let (mut parts, body) = response.into_http().into_parts();
// Set the content type
parts
.headers
.insert(http::header::CONTENT_TYPE, GRPC_CONTENT_TYPE);
#[cfg(any(feature = "gzip", feature = "zstd"))]
if let Some(encoding) = accept_encoding {
// Set the content encoding
parts.headers.insert(
crate::codec::compression::ENCODING_HEADER,
encoding.into_header_value(),
);
}
let body = EncodeBody::new_server(
self.codec.encoder(),
body,
accept_encoding,
compression_override,
max_message_size,
);
http::Response::from_parts(parts, BoxBody::new(body))
}
fn request_encoding_if_supported<B>(
&self,
request: &http::Request<B>,
) -> Result<Option<CompressionEncoding>, Status> {
CompressionEncoding::from_encoding_header(
request.headers(),
self.accept_compression_encodings,
)
}
}
impl<T: fmt::Debug> fmt::Debug for Grpc<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut f = f.debug_struct("Grpc");
f.field("codec", &self.codec);
f.field(
"accept_compression_encodings",
&self.accept_compression_encodings,
);
f.field(
"send_compression_encodings",
&self.send_compression_encodings,
);
f.finish()
}
}
fn compression_override_from_response<B, E>(
res: &Result<crate::Response<B>, E>,
) -> SingleMessageCompressionOverride {
res.as_ref()
.ok()
.and_then(|response| {
response
.extensions()
.get::<SingleMessageCompressionOverride>()
.copied()
})
.unwrap_or_default()
}