swadhinbiswas 📦 v2.0.8: security fixes, documentation, testing improvements · 7/28/2026
3e270a0
162 lines · 4.6 KB
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
use bytes::{Buf, BufMut};
use http::{Request, Response};
use hyper::body::Incoming;
use std::future::Future;
use std::pin::Pin;
use tonic::codec::{Codec, DecodeBuf, Decoder, EncodeBuf, Encoder};
use tonic::server::{Grpc, UnaryService};
use tonic::Status;
use tower::Service;

#[derive(Default, Clone)]
pub struct RawBytesCodec;

impl Codec for RawBytesCodec {
    type Encode = Vec<u8>;
    type Decode = Vec<u8>;
    type Encoder = RawBytesEncoder;
    type Decoder = RawBytesDecoder;

    fn encoder(&mut self) -> Self::Encoder {
        RawBytesEncoder
    }
    fn decoder(&mut self) -> Self::Decoder {
        RawBytesDecoder::default()
    }
}

#[derive(Default, Clone)]
pub struct RawBytesEncoder;

impl Encoder for RawBytesEncoder {
    type Item = Vec<u8>;
    type Error = Status;

    fn encode(&mut self, item: Self::Item, dst: &mut EncodeBuf<'_>) -> Result<(), Self::Error> {
        dst.put_slice(&item);
        Ok(())
    }
}

/// Maximum allowed gRPC message size (4 MiB default).
const MAX_GRPC_MESSAGE_SIZE: usize = 4 * 1024 * 1024;

#[derive(Clone)]
pub struct RawBytesDecoder {
    max_message_size: usize,
}

impl Default for RawBytesDecoder {
    fn default() -> Self {
        Self { max_message_size: MAX_GRPC_MESSAGE_SIZE }
    }
}

impl RawBytesDecoder {
    pub fn new(max_message_size: usize) -> Self {
        Self { max_message_size }
    }
}

impl Decoder for RawBytesDecoder {
    type Item = Vec<u8>;
    type Error = Status;

    fn decode(&mut self, src: &mut DecodeBuf<'_>) -> Result<Option<Self::Item>, Self::Error> {
        if src.has_remaining() {
            let remaining = src.chunk().len();
            if remaining > self.max_message_size {
                return Err(Status::resource_exhausted(format!(
                    "gRPC message too large: {} bytes (max {})",
                    remaining, self.max_message_size
                )));
            }
            let chunk = src.chunk().to_vec();
            src.advance(chunk.len());
            Ok(Some(chunk))
        } else {
            Ok(None)
        }
    }
}

pub type GrpcHandler = Box<
    dyn Fn(
            http::Uri,
            Vec<u8>,
        ) -> Pin<Box<dyn Future<Output = Result<Vec<u8>, Status>> + Send + 'static>>
        + Send
        + Sync
        + 'static,
>;

#[derive(Clone)]
pub struct DynamicGrpcService {
    handler: std::sync::Arc<GrpcHandler>,
}

impl DynamicGrpcService {
    pub fn new(handler: GrpcHandler) -> Self {
        Self { handler: std::sync::Arc::new(handler) }
    }
}

impl Service<Request<Incoming>> for DynamicGrpcService {
    type Response = Response<tonic::body::Body>;
    type Error = std::convert::Infallible;
    type Future =
        Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send + 'static>>;

    fn poll_ready(
        &mut self,
        _cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Result<(), Self::Error>> {
        std::task::Poll::Ready(Ok(()))
    }

    fn call(&mut self, req: Request<Incoming>) -> Self::Future {
        let handler = self.handler.clone();
        let uri = req.uri().clone();

        Box::pin(async move {
            struct TempSvc {
                uri: http::Uri,
                handler: std::sync::Arc<GrpcHandler>,
            }

            impl UnaryService<Vec<u8>> for TempSvc {
                type Response = Vec<u8>;
                type Future = Pin<
                    Box<
                        dyn Future<Output = Result<tonic::Response<Self::Response>, tonic::Status>>
                            + Send
                            + 'static,
                    >,
                >;

                fn call(&mut self, request: tonic::Request<Vec<u8>>) -> Self::Future {
                    let uri = self.uri.clone();
                    let handler = self.handler.clone();
                    Box::pin(async move {
                        let res = (handler)(uri, request.into_inner()).await?;
                        Ok(tonic::Response::new(res))
                    })
                }
            }

            let mut grpc = Grpc::new(RawBytesCodec);

            // UnaryService expects Request<Incoming> and returns Response<BoxBody>.
            // Since we need to return Response<tonic::body::Body>, we can just map it!
            let res = grpc.unary(TempSvc { uri, handler }, req).await;

            // In tonic 0.14, grpc.unary() returns http::Response<tonic::body::BoxBody> ?
            // Wait, I should just map the body:
            let (parts, body) = res.into_parts();
            let body = tonic::body::Body::new(body); // or similar

            Ok(Response::from_parts(parts, body))
        })
    }
}