1use super::*;
2
3impl GrpcStatus {
5 #[inline(always)]
11 pub fn code(self) -> u8 {
12 self as u8
13 }
14
15 #[inline(always)]
21 pub(crate) fn code_str(self) -> &'static str {
22 GRPC_STATUS_CODE_STRS[self as usize]
23 }
24
25 #[inline]
35 pub fn from_code(code: u8) -> Self {
36 match code {
37 0 => Self::Ok,
38 1 => Self::Cancelled,
39 2 => Self::Unknown,
40 3 => Self::InvalidArgument,
41 4 => Self::DeadlineExceeded,
42 5 => Self::NotFound,
43 6 => Self::AlreadyExists,
44 7 => Self::PermissionDenied,
45 8 => Self::ResourceExhausted,
46 9 => Self::FailedPrecondition,
47 10 => Self::Aborted,
48 11 => Self::OutOfRange,
49 12 => Self::Unimplemented,
50 13 => Self::Internal,
51 14 => Self::Unavailable,
52 15 => Self::DataLoss,
53 16 => Self::Unauthenticated,
54 _ => Self::Unknown,
55 }
56 }
57}
58
59impl Display for GrpcError {
61 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
71 write!(
72 f,
73 "gRPC status {}: {}",
74 self.get_status().code(),
75 self.get_message()
76 )
77 }
78}
79
80impl Error for GrpcError {}
82
83impl GrpcError {
85 pub fn new<M>(status: GrpcStatus, message: M) -> Self
96 where
97 M: Into<String>,
98 {
99 Self {
100 status,
101 message: message.into(),
102 }
103 }
104
105 #[inline]
111 pub fn encoded_message(&self) -> String {
112 percent_encode_grpc_message(self.get_message())
113 }
114}
115
116impl Default for GrpcConfig {
118 fn default() -> Self {
120 Self {
121 max_message_size: DEFAULT_GRPC_MAX_MESSAGE_SIZE,
122 compression: Compress::Unknown,
123 }
124 }
125}
126
127impl GrpcConfig {
129 pub fn with_max_message_size(mut self, max_message_size: usize) -> Self {
139 self.set_max_message_size(max_message_size);
140 self
141 }
142
143 pub fn with_compression(mut self, compression: Compress) -> Self {
153 self.set_compression(compression);
154 self
155 }
156}
157
158impl GrpcFrame {
160 #[inline]
170 pub fn new(payload: Vec<u8>) -> Self {
171 Self {
172 compressed: false,
173 payload,
174 }
175 }
176
177 #[inline]
188 pub fn encode_into(&self, encoding: Compress, out: &mut Vec<u8>) -> Result<(), GrpcError> {
189 let payload: &[u8] = self.get_payload().as_slice();
190 if matches!(encoding, Compress::Unknown) {
191 let len_u32: u32 = u32::try_from(payload.len()).map_err(|_| {
192 GrpcError::new(GrpcStatus::ResourceExhausted, ERR_GRPC_MSG_TOO_LARGE)
193 })?;
194 let len_bytes: [u8; 4] = len_u32.to_be_bytes();
195 let header: [u8; GRPC_FRAME_HEADER_LEN] =
196 [0u8, len_bytes[0], len_bytes[1], len_bytes[2], len_bytes[3]];
197 out.reserve(GRPC_FRAME_HEADER_LEN + payload.len());
198 out.extend_from_slice(&header);
199 out.extend_from_slice(payload);
200 return Ok(());
201 }
202 let compressed: Vec<u8> = encoding
203 .encode(payload, GRPC_DECOMPRESS_BUF_SIZE)
204 .into_owned();
205 let len_u32: u32 = u32::try_from(compressed.len())
206 .map_err(|_| GrpcError::new(GrpcStatus::ResourceExhausted, ERR_GRPC_MSG_TOO_LARGE))?;
207 let len_bytes: [u8; 4] = len_u32.to_be_bytes();
208 let header: [u8; GRPC_FRAME_HEADER_LEN] =
209 [1u8, len_bytes[0], len_bytes[1], len_bytes[2], len_bytes[3]];
210 out.reserve(GRPC_FRAME_HEADER_LEN + compressed.len());
211 out.extend_from_slice(&header);
212 out.extend_from_slice(&compressed);
213 Ok(())
214 }
215
216 #[inline]
226 pub fn encode(&self, encoding: Compress) -> Result<Vec<u8>, GrpcError> {
227 if matches!(encoding, Compress::Unknown) {
228 let payload: &[u8] = self.get_payload().as_slice();
229 let len_u32: u32 = u32::try_from(payload.len()).map_err(|_| {
230 GrpcError::new(GrpcStatus::ResourceExhausted, ERR_GRPC_MSG_TOO_LARGE)
231 })?;
232 let len_bytes: [u8; 4] = len_u32.to_be_bytes();
233 let mut wire: Vec<u8> = Vec::with_capacity(GRPC_FRAME_HEADER_LEN + payload.len());
234 wire.extend_from_slice(&[0u8, len_bytes[0], len_bytes[1], len_bytes[2], len_bytes[3]]);
235 wire.extend_from_slice(payload);
236 return Ok(wire);
237 }
238 let mut wire: Vec<u8> =
239 Vec::with_capacity(GRPC_FRAME_HEADER_LEN + self.get_payload().len());
240 self.encode_into(encoding, &mut wire)?;
241 Ok(wire)
242 }
243
244 #[inline]
257 fn decode_prefix_with_spare(
258 raw: &[u8],
259 encoding: Compress,
260 max_message_size: usize,
261 spare_cap: usize,
262 ) -> Result<(Self, usize), GrpcError> {
263 if raw.len() < GRPC_FRAME_HEADER_LEN {
264 return Err(GrpcError::new(
265 GrpcStatus::Internal,
266 ERR_GRPC_TRUNCATED_HEADER,
267 ));
268 }
269 let flag: u8 = raw[0];
270 if flag > 1 {
271 return Err(GrpcError::new(GrpcStatus::Internal, ERR_GRPC_INVALID_FLAG));
272 }
273 let declared_len: usize = u32::from_be_bytes([raw[1], raw[2], raw[3], raw[4]]) as usize;
274 if declared_len > max_message_size {
275 return Err(GrpcError::new(
276 GrpcStatus::ResourceExhausted,
277 ERR_GRPC_MSG_TOO_LARGE,
278 ));
279 }
280 let body_end: usize = GRPC_FRAME_HEADER_LEN.saturating_add(declared_len);
281 if raw.len() < body_end {
282 return Err(GrpcError::new(
283 GrpcStatus::Internal,
284 ERR_GRPC_TRUNCATED_BODY,
285 ));
286 }
287 let frame_slice: &[u8] = &raw[GRPC_FRAME_HEADER_LEN..body_end];
288 if flag == 0 {
289 let payload: Vec<u8> = if spare_cap == 0 {
290 frame_slice.to_vec()
291 } else {
292 let mut buf: Vec<u8> = Vec::with_capacity(declared_len.saturating_add(spare_cap));
293 buf.extend_from_slice(frame_slice);
294 buf
295 };
296 return Ok((
297 Self {
298 compressed: false,
299 payload,
300 },
301 body_end,
302 ));
303 }
304 if matches!(encoding, Compress::Unknown) {
305 return Err(GrpcError::new(
306 GrpcStatus::Unimplemented,
307 ERR_GRPC_UNSUPPORTED_ENCODING,
308 ));
309 }
310 let decoded: Vec<u8> = encoding
311 .decode(frame_slice, GRPC_DECOMPRESS_BUF_SIZE)
312 .into_owned();
313 if decoded.len() > max_message_size {
314 return Err(GrpcError::new(
315 GrpcStatus::ResourceExhausted,
316 ERR_GRPC_MSG_TOO_LARGE,
317 ));
318 }
319 Ok((
320 Self {
321 compressed: true,
322 payload: decoded,
323 },
324 body_end,
325 ))
326 }
327
328 #[inline]
340 pub fn decode(
341 raw: &[u8],
342 encoding: Compress,
343 max_message_size: usize,
344 ) -> Result<Self, GrpcError> {
345 let (frame, _): (Self, usize) =
346 Self::decode_prefix_with_spare(raw, encoding, max_message_size, 0)?;
347 Ok(frame)
348 }
349
350 pub fn decode_many(
363 raw: &[u8],
364 encoding: Compress,
365 max_message_size: usize,
366 max_frames: usize,
367 ) -> Result<Vec<Self>, GrpcError> {
368 let mut frames: Vec<Self> = Vec::with_capacity(if raw.is_empty() { 0 } else { 1 });
369 let mut offset: usize = 0;
370 while offset < raw.len() {
371 if frames.len() >= max_frames {
372 return Err(GrpcError::new(
373 GrpcStatus::ResourceExhausted,
374 ERR_GRPC_MSG_TOO_LARGE,
375 ));
376 }
377 let (frame, consumed): (Self, usize) =
378 Self::decode_prefix_with_spare(&raw[offset..], encoding, max_message_size, 0)?;
379 frames.push(frame);
380 offset = offset.saturating_add(consumed);
381 }
382 Ok(frames)
383 }
384}
385
386impl Default for GrpcRouter {
388 fn default() -> Self {
390 Self {
391 small_methods: Vec::new(),
392 methods: hash_map_xx_hash3_64(),
393 interceptors: Vec::new(),
394 }
395 }
396}
397
398impl GrpcRouter {
400 pub fn new() -> Self {
406 Self::default()
407 }
408
409 pub fn add_interceptor(&mut self, interceptor: Arc<dyn GrpcInterceptor>) -> &mut Self {
419 let Self { interceptors, .. } = self;
420 interceptors.push(interceptor);
421 self
422 }
423
424 pub fn register<P, F, Fut>(&mut self, path: P, handler: F) -> &mut Self
435 where
436 P: Into<String>,
437 F: Fn(Vec<u8>) -> Fut + Send + Sync + 'static,
438 Fut: Future<Output = Result<Vec<u8>, GrpcError>> + Send + 'static,
439 {
440 let Self {
441 small_methods,
442 methods,
443 ..
444 } = self;
445 let path_str: String = path.into();
446 let boxed: GrpcHandler = Arc::new(move |payload: Vec<u8>| Box::pin(handler(payload)));
447 methods.insert(path_str.clone(), Arc::clone(&boxed));
448 if methods.len() <= GRPC_SMALL_METHODS_LIMIT {
449 if let Some((_, slot)) = small_methods
450 .iter_mut()
451 .find(|(existing, _): &&mut (String, GrpcHandler)| existing == &path_str)
452 {
453 *slot = boxed;
454 } else {
455 small_methods.push((path_str, boxed));
456 }
457 } else {
458 small_methods.clear();
459 }
460 self
461 }
462
463 #[inline(always)]
473 fn find_handler(&self, path: &str) -> Option<&GrpcHandler> {
474 let Self {
475 small_methods,
476 methods,
477 ..
478 } = self;
479 if !small_methods.is_empty() {
480 for (registered, handler) in small_methods {
481 if registered.as_str() == path {
482 return Some(handler);
483 }
484 }
485 return None;
486 }
487 methods.get(path)
488 }
489
490 #[inline]
500 pub fn has_method(&self, path: &str) -> bool {
501 self.find_handler(path).is_some()
502 }
503
504 pub async fn dispatch(
518 &self,
519 path: &str,
520 raw_body: &[u8],
521 req_encoding: Compress,
522 deadline: Option<Duration>,
523 config: &GrpcConfig,
524 ) -> (GrpcStatus, String, Vec<u8>) {
525 let Self { interceptors, .. } = self;
526 for interceptor in interceptors {
527 if let Err(err) = interceptor.before_call(path) {
528 return (err.get_status(), err.encoded_message(), Vec::new());
529 }
530 }
531 let Some(handler) = self.find_handler(path) else {
532 return (
533 GrpcStatus::Unimplemented,
534 ERR_GRPC_UNIMPLEMENTED.to_owned(),
535 Vec::new(),
536 );
537 };
538 let spare_cap: usize = if matches!(config.get_compression(), Compress::Unknown) {
539 GRPC_FRAME_HEADER_LEN
540 } else {
541 0
542 };
543 let frame: GrpcFrame = match GrpcFrame::decode_prefix_with_spare(
544 raw_body,
545 req_encoding,
546 config.get_max_message_size(),
547 spare_cap,
548 ) {
549 Ok((decoded, _)) => decoded,
550 Err(err) => return (err.get_status(), err.encoded_message(), Vec::new()),
551 };
552 let outcome: Result<Vec<u8>, GrpcError> = match deadline {
553 Some(limit) => match timeout(limit, handler(frame.payload)).await {
554 Ok(res) => res,
555 Err(_) => Err(GrpcError::new(
556 GrpcStatus::DeadlineExceeded,
557 ERR_GRPC_DEADLINE_EXCEEDED,
558 )),
559 },
560 None => handler(frame.payload).await,
561 };
562 match outcome {
563 Ok(resp_payload) => {
564 if resp_payload.len() > config.get_max_message_size() {
565 return (
566 GrpcStatus::ResourceExhausted,
567 ERR_GRPC_MSG_TOO_LARGE.to_owned(),
568 Vec::new(),
569 );
570 }
571 let compression: Compress = config.get_compression();
572 let encoded: Result<Vec<u8>, GrpcError> =
573 if matches!(compression, Compress::Unknown) {
574 encode_uncompressed_payload(resp_payload)
575 } else {
576 GrpcFrame::new(resp_payload).encode(compression)
577 };
578 match encoded {
579 Ok(wire) => (GrpcStatus::Ok, String::new(), wire),
580 Err(err) => (err.get_status(), err.encoded_message(), Vec::new()),
581 }
582 }
583 Err(err) => (err.get_status(), err.encoded_message(), Vec::new()),
584 }
585 }
586}
587
588impl GrpcPlugin {
590 pub fn init(config: GrpcConfig, router: GrpcRouter) -> &'static Self {
601 GRPC_PLUGIN.get_or_init(|| Self { config, router })
602 }
603
604 #[inline(always)]
610 pub fn get() -> Option<&'static Self> {
611 GRPC_PLUGIN.get()
612 }
613
614 #[inline(always)]
620 pub fn get_config(&self) -> &GrpcConfig {
621 &self.config
622 }
623
624 #[inline(always)]
630 pub fn get_router(&self) -> &GrpcRouter {
631 &self.router
632 }
633}
634
635impl ServerHook for GrpcHook {
637 #[inline(always)]
648 async fn new(_: &mut Stream, _: &mut Context) -> Self {
649 Self
650 }
651
652 async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
664 let Some(plugin) = GrpcPlugin::get() else {
665 return Status::Continue;
666 };
667 let req: &Request = ctx.get_request();
668 let is_grpc: bool =
669 request_header_back(req, CONTENT_TYPE).is_some_and(is_grpc_content_type);
670 if !is_grpc {
671 return Status::Continue;
672 }
673 if !req.get_method().is_post() {
674 ctx.get_mut_response()
675 .set_status_code(HttpStatus::MethodNotAllowed.code())
676 .set_body(&[] as &[u8]);
677 let _: Result<(), ResponseError> = ctx.try_send_response(stream).await;
678 return Status::Reject;
679 }
680 let req_encoding: Compress =
681 parse_grpc_encoding(request_header_back(req, GRPC_ENCODING_HEADER));
682 let deadline: Option<Duration> =
683 request_header_back(req, GRPC_TIMEOUT_HEADER).and_then(parse_grpc_timeout);
684 let config: &GrpcConfig = plugin.get_config();
685 let (status, encoded_msg, wire_body): (GrpcStatus, String, Vec<u8>) = plugin
686 .get_router()
687 .dispatch(
688 req.get_path(),
689 req.get_body(),
690 req_encoding,
691 deadline,
692 config,
693 )
694 .await;
695 let is_h2: bool = ctx.get_request().get_version().is_http2();
696 let can_fast_wire: bool = (is_h2 || ctx.get_request().get_version().is_http1_1())
697 && ctx.get_response().get_headers().is_empty()
698 && encoded_msg.is_empty()
699 && matches!(config.get_compression(), Compress::Unknown);
700 if can_fast_wire {
701 let wire_prefix: &[u8] = if is_h2 {
702 GRPC_WIRE_H2_PREFIX
703 } else {
704 GRPC_WIRE_PREFIX
705 };
706 let status_bytes: &[u8] = status.code_str().as_bytes();
707 let mut len_buf: [u8; GRPC_LEN_STACK_BUF] = [0u8; GRPC_LEN_STACK_BUF];
708 let len_bytes: &[u8] = format_usize_stack(wire_body.len(), &mut len_buf);
709 let total_len: usize = wire_prefix.len()
710 + status_bytes.len()
711 + GRPC_WIRE_CL.len()
712 + len_bytes.len()
713 + GRPC_WIRE_END.len()
714 + wire_body.len();
715 if total_len <= GRPC_WIRE_FAST_STACK_CAP {
716 let mut stack: [u8; GRPC_WIRE_FAST_STACK_CAP] = [0u8; GRPC_WIRE_FAST_STACK_CAP];
717 let mut off: usize = 0;
718 stack[off..off + wire_prefix.len()].copy_from_slice(wire_prefix);
719 off += wire_prefix.len();
720 stack[off..off + status_bytes.len()].copy_from_slice(status_bytes);
721 off += status_bytes.len();
722 stack[off..off + GRPC_WIRE_CL.len()].copy_from_slice(GRPC_WIRE_CL);
723 off += GRPC_WIRE_CL.len();
724 stack[off..off + len_bytes.len()].copy_from_slice(len_bytes);
725 off += len_bytes.len();
726 stack[off..off + GRPC_WIRE_END.len()].copy_from_slice(GRPC_WIRE_END);
727 off += GRPC_WIRE_END.len();
728 stack[off..off + wire_body.len()].copy_from_slice(&wire_body);
729 let _: Result<(), ResponseError> = stream.try_send(&stack[..total_len]).await;
730 return Status::Reject;
731 }
732 if total_len <= GRPC_WIRE_STACK_CAP {
733 let mut stack: [u8; GRPC_WIRE_STACK_CAP] = [0u8; GRPC_WIRE_STACK_CAP];
734 let mut off: usize = 0;
735 stack[off..off + wire_prefix.len()].copy_from_slice(wire_prefix);
736 off += wire_prefix.len();
737 stack[off..off + status_bytes.len()].copy_from_slice(status_bytes);
738 off += status_bytes.len();
739 stack[off..off + GRPC_WIRE_CL.len()].copy_from_slice(GRPC_WIRE_CL);
740 off += GRPC_WIRE_CL.len();
741 stack[off..off + len_bytes.len()].copy_from_slice(len_bytes);
742 off += len_bytes.len();
743 stack[off..off + GRPC_WIRE_END.len()].copy_from_slice(GRPC_WIRE_END);
744 off += GRPC_WIRE_END.len();
745 stack[off..off + wire_body.len()].copy_from_slice(&wire_body);
746 let _: Result<(), ResponseError> = stream.try_send(&stack[..total_len]).await;
747 return Status::Reject;
748 }
749 }
750 let response: &mut Response = ctx.get_mut_response();
751 response
752 .set_status_code(HttpStatus::Ok.code())
753 .set_header(CONTENT_TYPE, GRPC_CONTENT_TYPE)
754 .set_header(GRPC_STATUS_HEADER, status.code_str())
755 .set_body(wire_body);
756 if !encoded_msg.is_empty() {
757 response.set_header(GRPC_MESSAGE_HEADER, encoded_msg);
758 }
759 if !matches!(config.get_compression(), Compress::Unknown) && status == GrpcStatus::Ok {
760 response.set_header(GRPC_ENCODING_HEADER, config.get_compression().as_str());
761 }
762 let _: Result<(), ResponseError> = ctx.try_send_response(stream).await;
763 Status::Reject
764 }
765}