Skip to main content

hyperlane_plugin_grpc/
impl.rs

1use super::*;
2
3/// Inherent implementation of [`GrpcStatus`].
4impl GrpcStatus {
5    /// Returns the canonical numeric gRPC status code (`0..=16`).
6    ///
7    /// # Returns
8    ///
9    /// - `u8` - Numeric status code.
10    #[inline(always)]
11    pub fn code(self) -> u8 {
12        self as u8
13    }
14
15    /// Returns the pre-formatted static ASCII string for this gRPC status code.
16    ///
17    /// # Returns
18    ///
19    /// - `&'static str` - Numeric code string (`"0"`..=`"16"`).
20    #[inline(always)]
21    pub(crate) fn code_str(self) -> &'static str {
22        GRPC_STATUS_CODE_STRS[self as usize]
23    }
24
25    /// Converts a numeric code (`0..=16`) back into a [`GrpcStatus`].
26    ///
27    /// # Arguments
28    ///
29    /// - `u8` - Numeric gRPC status code.
30    ///
31    /// # Returns
32    ///
33    /// - `Self` - Matching status variant, or [`GrpcStatus::Unknown`] for unrecognised codes.
34    #[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
59/// Formatting / debug-printing for [`GrpcError`].
60impl Display for GrpcError {
61    /// Formats the [`GrpcError`] via the supplied formatter.
62    ///
63    /// # Arguments
64    ///
65    /// - `&mut Formatter<'_>` - The formatter receiving the formatted output.
66    ///
67    /// # Returns
68    ///
69    /// - `fmt::Result` - A `fmt::Result` value.
70    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
80/// Implements [`Error`] for [`GrpcError`].
81impl Error for GrpcError {}
82
83/// Inherent implementation of [`GrpcError`].
84impl GrpcError {
85    /// Creates a new [`GrpcError`] with the supplied status code and message.
86    ///
87    /// # Arguments
88    ///
89    /// - `GrpcStatus` - Canonical gRPC status code.
90    /// - `M` - Error message convertible into `String`.
91    ///
92    /// # Returns
93    ///
94    /// - `Self` - Constructed gRPC error.
95    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    /// Returns the percent-encoded `grpc-message` header value.
106    ///
107    /// # Returns
108    ///
109    /// - `String` - Wire-safe percent-encoded message.
110    #[inline]
111    pub fn encoded_message(&self) -> String {
112        percent_encode_grpc_message(self.get_message())
113    }
114}
115
116/// Default construction for [`GrpcConfig`].
117impl Default for GrpcConfig {
118    /// Constructs a default [`GrpcConfig`] value.
119    fn default() -> Self {
120        Self {
121            max_message_size: DEFAULT_GRPC_MAX_MESSAGE_SIZE,
122            compression: Compress::Unknown,
123        }
124    }
125}
126
127/// Inherent implementation of [`GrpcConfig`].
128impl GrpcConfig {
129    /// Sets the maximum encoded and decoded message size in bytes.
130    ///
131    /// # Arguments
132    ///
133    /// - `usize` - Maximum message length in bytes.
134    ///
135    /// # Returns
136    ///
137    /// - `Self` - Updated configuration.
138    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    /// Sets the outgoing response frame compression algorithm.
144    ///
145    /// # Arguments
146    ///
147    /// - `Compress` - Compression coding (`Compress::Unknown` = identity).
148    ///
149    /// # Returns
150    ///
151    /// - `Self` - Updated configuration.
152    pub fn with_compression(mut self, compression: Compress) -> Self {
153        self.set_compression(compression);
154        self
155    }
156}
157
158/// Inherent implementation of [`GrpcFrame`].
159impl GrpcFrame {
160    /// Creates an uncompressed [`GrpcFrame`] carrying `payload`.
161    ///
162    /// # Arguments
163    ///
164    /// - `Vec<u8>` - Raw message payload bytes.
165    ///
166    /// # Returns
167    ///
168    /// - `Self` - Uncompressed frame.
169    #[inline]
170    pub fn new(payload: Vec<u8>) -> Self {
171        Self {
172            compressed: false,
173            payload,
174        }
175    }
176
177    /// Encodes this frame directly into `out` in the 5-byte gRPC Length-Prefixed-Message wire format.
178    ///
179    /// # Arguments
180    ///
181    /// - `Compress` - Compression coding to apply (`Compress::Unknown` sends uncompressed).
182    /// - `&mut Vec<u8>` - Destination wire buffer (appended to).
183    ///
184    /// # Returns
185    ///
186    /// - `Result<(), GrpcError>` - `Ok(())` on success, or [`GrpcStatus::ResourceExhausted`] on length overflow.
187    #[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    /// Encodes this frame into the 5-byte gRPC Length-Prefixed-Message wire format.
217    ///
218    /// # Arguments
219    ///
220    /// - `Compress` - Compression coding to apply (`Compress::Unknown` sends uncompressed).
221    ///
222    /// # Returns
223    ///
224    /// - `Result<Vec<u8>, GrpcError>` - Wire bytes, or [`GrpcStatus::ResourceExhausted`] on length overflow.
225    #[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    /// Decodes one 5-byte length-prefixed gRPC wire frame with optional spare capacity for in-place re-framing.
245    ///
246    /// # Arguments
247    ///
248    /// - `&[u8]` - Raw HTTP/2 request body bytes.
249    /// - `Compress` - Negotiated `grpc-encoding` coding (`Compress::Unknown` for identity).
250    /// - `usize` - Maximum allowed encoded and decoded payload length.
251    /// - `usize` - Extra spare capacity bytes reserved in the decoded uncompressed `Vec<u8>`.
252    ///
253    /// # Returns
254    ///
255    /// - `Result<(Self, usize), GrpcError>` - Decoded frame and consumed byte length.
256    #[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    /// Decodes one 5-byte length-prefixed gRPC wire frame enforcing `max_message_size` and decompression caps.
329    ///
330    /// # Arguments
331    ///
332    /// - `&[u8]` - Raw HTTP/2 request body bytes.
333    /// - `Compress` - Negotiated `grpc-encoding` coding (`Compress::Unknown` for identity).
334    /// - `usize` - Maximum allowed encoded and decoded payload length.
335    ///
336    /// # Returns
337    ///
338    /// - `Result<Self, GrpcError>` - Decoded frame or canonical [`GrpcError`].
339    #[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    /// Decodes a sequence of concatenated gRPC frames up to `max_frames` for streaming batches.
351    ///
352    /// # Arguments
353    ///
354    /// - `&[u8]` - Raw HTTP/2 body containing zero or more length-prefixed frames.
355    /// - `Compress` - Negotiated `grpc-encoding` coding.
356    /// - `usize` - Maximum allowed per-frame size in bytes.
357    /// - `usize` - Maximum number of frames permitted to prevent DoS fan-out.
358    ///
359    /// # Returns
360    ///
361    /// - `Result<Vec<Self>, GrpcError>` - Decoded frames in wire order.
362    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
386/// Default construction for [`GrpcRouter`].
387impl Default for GrpcRouter {
388    /// Constructs an empty [`GrpcRouter`].
389    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
398/// Inherent implementation of [`GrpcRouter`].
399impl GrpcRouter {
400    /// Creates an empty [`GrpcRouter`].
401    ///
402    /// # Returns
403    ///
404    /// - `Self` - Empty service router.
405    pub fn new() -> Self {
406        Self::default()
407    }
408
409    /// Registers an extensible [`GrpcInterceptor`] invoked before every service dispatch.
410    ///
411    /// # Arguments
412    ///
413    /// - `Arc<dyn GrpcInterceptor>` - Interceptor implementation.
414    ///
415    /// # Returns
416    ///
417    /// - `&mut Self` - This router for fluent chaining.
418    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    /// Registers a unary async gRPC method handler under full path `/package.Service/Method`.
425    ///
426    /// # Arguments
427    ///
428    /// - `P` - Full gRPC method path convertible into `String`.
429    /// - `F` - Async handler receiving decoded request bytes and returning response bytes.
430    ///
431    /// # Returns
432    ///
433    /// - `&mut Self` - This router for fluent chaining.
434    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    /// Looks up a registered handler by path, using linear scan for small routers to skip hashing.
464    ///
465    /// # Arguments
466    ///
467    /// - `&str` - Full gRPC method path.
468    ///
469    /// # Returns
470    ///
471    /// - `Option<&GrpcHandler>` - Borrowed handler if registered.
472    #[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    /// Reports whether `path` is registered on this router.
491    ///
492    /// # Arguments
493    ///
494    /// - `&str` - Full gRPC path.
495    ///
496    /// # Returns
497    ///
498    /// - `bool` - `true` when registered.
499    #[inline]
500    pub fn has_method(&self, path: &str) -> bool {
501        self.find_handler(path).is_some()
502    }
503
504    /// Dispatches one gRPC unary call with interceptor check, frame decoding, optional timeout, and response framing.
505    ///
506    /// # Arguments
507    ///
508    /// - `&str` - Full gRPC method path.
509    /// - `&[u8]` - Raw HTTP/2 request body bytes.
510    /// - `Compress` - Incoming `grpc-encoding` coding.
511    /// - `Option<Duration>` - Optional client `grpc-timeout` budget.
512    /// - `&GrpcConfig` - Max message size and outgoing compression config.
513    ///
514    /// # Returns
515    ///
516    /// - `(GrpcStatus, String, Vec<u8>)` - `(status, percent_encoded_message, framed_response_body)`.
517    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
588/// Inherent implementation of [`GrpcPlugin`].
589impl GrpcPlugin {
590    /// Initializes the global [`GrpcPlugin`] once with `config` and `router`.
591    ///
592    /// # Arguments
593    ///
594    /// - `GrpcConfig` - gRPC plugin configuration.
595    /// - `GrpcRouter` - Registered service router.
596    ///
597    /// # Returns
598    ///
599    /// - `&'static Self` - Reference to the initialized global plugin.
600    pub fn init(config: GrpcConfig, router: GrpcRouter) -> &'static Self {
601        GRPC_PLUGIN.get_or_init(|| Self { config, router })
602    }
603
604    /// Returns the initialized global [`GrpcPlugin`], if [`GrpcPlugin::init`] was called.
605    ///
606    /// # Returns
607    ///
608    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
609    #[inline(always)]
610    pub fn get() -> Option<&'static Self> {
611        GRPC_PLUGIN.get()
612    }
613
614    /// Returns the active [`GrpcConfig`].
615    ///
616    /// # Returns
617    ///
618    /// - `&GrpcConfig` - Active configuration.
619    #[inline(always)]
620    pub fn get_config(&self) -> &GrpcConfig {
621        &self.config
622    }
623
624    /// Returns the active [`GrpcRouter`].
625    ///
626    /// # Returns
627    ///
628    /// - `&GrpcRouter` - Registered service router.
629    #[inline(always)]
630    pub fn get_router(&self) -> &GrpcRouter {
631        &self.router
632    }
633}
634
635/// Implements [`ServerHook`] for [`GrpcHook`].
636impl ServerHook for GrpcHook {
637    /// Constructs a per-request [`GrpcHook`].
638    ///
639    /// # Arguments
640    ///
641    /// - `&mut Stream` - Connection stream.
642    /// - `&mut Context` - Request context.
643    ///
644    /// # Returns
645    ///
646    /// - `Self` - Hook instance.
647    #[inline(always)]
648    async fn new(_: &mut Stream, _: &mut Context) -> Self {
649        Self
650    }
651
652    /// Dispatches incoming gRPC requests carrying `Content-Type: application/grpc*`.
653    ///
654    /// # Arguments
655    ///
656    /// - `Self` - Hook instance.
657    /// - `&mut Stream` - Connection stream.
658    /// - `&mut Context` - Request context.
659    ///
660    /// # Returns
661    ///
662    /// - `Status` - `Status::Continue` when unconfigured or non-gRPC; `Status::Reject` once answered.
663    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}