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
pub(crate) mod http_request_to_grpc_frames_typed;
pub(crate) mod http_response_to_grpc_frames;
pub(crate) mod http_response_to_grpc_frames_typed;
pub(crate) mod req_sink;
pub(crate) mod types;

use bytes::Bytes;

use httpbis::ClientTlsOption;
use httpbis::Header;
use httpbis::Headers;
use httpbis::HttpScheme;

use crate::method::MethodDescriptor;

use crate::result;

use crate::client::http_request_to_grpc_frames_typed::http_req_to_grpc_frames_typed;
use crate::client::http_response_to_grpc_frames_typed::http_response_to_grpc_frames_typed;
use crate::client::req_sink::ClientRequestSink;
use crate::error;
use futures::future;

use futures::future::TryFutureExt;

use crate::or_static::arc::ArcOrStatic;
use crate::proto::grpc_frame::write_grpc_frame_cb;
use crate::req::*;
use crate::resp::*;
use std::future::Future;
use std::pin::Pin;
use tokio::runtime::Handle;

/// Client configuration.
#[derive(Default, Debug, Clone)]
pub struct ClientConf {
    /// HTTP/2 client configuration.
    pub http: httpbis::ClientConf,
}

impl ClientConf {
    /// Create default configuration.
    pub fn new() -> ClientConf {
        Default::default()
    }
}

enum ClientBuilderType<'a> {
    Tcp { port: u16, host: &'a str },
    Unix { socket: &'a str },
}

enum Tls<T: tls_api::TlsConnector> {
    Explict(ClientTlsOption<T>),
    Implicit,
    None,
}

/// Builder for [`Client`].
pub struct ClientBuilder<'a, T: tls_api::TlsConnector> {
    client_type: ClientBuilderType<'a>,
    http_scheme: HttpScheme,
    event_loop: Option<Handle>,
    pub conf: ClientConf,
    tls: Tls<T>,
}

impl<'a, T: tls_api::TlsConnector> ClientBuilder<'a, T> {
    pub fn with_event_loop(mut self, event_loop: Handle) -> Self {
        self.event_loop = Some(event_loop);
        self
    }

    pub fn conf(mut self, config: ClientConf) -> Self {
        self.conf = config;
        self
    }

    pub fn build(self) -> result::Result<Client> {
        let mut builder = httpbis::ClientBuilder::<T>::new();
        let mut conf = self.conf;
        conf.http.thread_name = Some(
            conf.http
                .thread_name
                .unwrap_or_else(|| "grpc-client-loop".to_owned()),
        );
        let (host, port) = match self.client_type {
            ClientBuilderType::Tcp { host, port } => {
                if self.http_scheme == HttpScheme::Https {
                    builder.set_tls(host)?;
                }
                builder.set_addr((host, port))?;
                (host, Some(port))
            }
            ClientBuilderType::Unix { socket } => {
                builder.set_unix_addr(socket)?;
                (socket, None)
            }
        };
        builder.event_loop = self.event_loop;
        builder.conf = conf.http;
        match self.tls {
            Tls::Explict(tls) => {
                builder.tls = tls;
            }
            Tls::Implicit | Tls::None => {}
        }

        Ok(Client {
            client: ::std::sync::Arc::new(builder.build()?),
            host: host.to_owned(),
            http_scheme: self.http_scheme,
            port,
        })
    }
}

impl<'a> ClientBuilder<'a, tls_api_stub::TlsConnector> {
    pub fn new(host: &'a str, port: u16) -> Self {
        ClientBuilder {
            client_type: ClientBuilderType::Tcp { port, host },
            http_scheme: HttpScheme::Http,
            event_loop: None,
            conf: Default::default(),
            tls: Tls::None,
        }
    }

    pub fn new_unix(addr: &'a str) -> Self {
        ClientBuilder {
            client_type: ClientBuilderType::Unix { socket: addr },
            http_scheme: HttpScheme::Http,
            event_loop: None,
            conf: Default::default(),
            tls: Tls::None,
        }
    }

    pub fn tls<TLS: tls_api::TlsConnector>(self) -> ClientBuilder<'a, TLS> {
        ClientBuilder {
            client_type: self.client_type,
            http_scheme: HttpScheme::Https,
            event_loop: self.event_loop,
            conf: self.conf,
            tls: Tls::Implicit,
        }
    }

    pub fn explicit_tls<TLS: tls_api::TlsConnector>(
        self,
        tls: ClientTlsOption<TLS>,
    ) -> ClientBuilder<'a, TLS> {
        ClientBuilder {
            client_type: self.client_type,
            http_scheme: tls.http_scheme(),
            event_loop: self.event_loop,
            conf: self.conf,
            tls: Tls::Explict(tls),
        }
    }
}

/// gRPC client implementation.
/// Used by generated code.
#[derive(Debug)]
pub struct Client {
    client: ::std::sync::Arc<httpbis::Client>,
    host: String,
    http_scheme: HttpScheme,
    port: Option<u16>,
}

impl Client {
    fn call_impl<Req, Resp>(
        &self,
        options: RequestOptions,
        req: Option<Req>,
        method: ArcOrStatic<MethodDescriptor<Req, Resp>>,
    ) -> Pin<
        Box<
            dyn Future<Output = crate::Result<(ClientRequestSink<Req>, StreamingResponse<Resp>)>>
                + Send,
        >,
    >
    where
        Req: Send + 'static,
        Resp: Send + 'static,
    {
        let mut authority = self.host.clone();
        if let Some(port_value) = self.port {
            authority = format!("{}:{}", authority, port_value);
        }

        debug!("start call {}/{}", authority, method.name);

        if options.cachable {
            // TODO: GET
            // https://github.com/grpc/grpc/issues/18230
        }

        let mut headers = Headers::from_vec(vec![
            Header::new(Bytes::from_static(b":method"), Bytes::from_static(b"POST")),
            // TODO: do not allocate static
            Header::new(Bytes::from_static(b":path"), method.name.to_string()),
            Header::new(Bytes::from_static(b":authority"), authority),
            Header::new(
                Bytes::from_static(b":scheme"),
                Bytes::from_static(self.http_scheme.as_bytes()),
            ),
            Header::new(
                Bytes::from_static(b"content-type"),
                Bytes::from_static(b"application/grpc"),
            ),
            Header::new(Bytes::from_static(b"te"), Bytes::from_static(b"trailers")),
        ]);

        headers.extend(options.metadata.into_headers());

        let req_bytes = match req {
            Some(req) => {
                let mut frame = Vec::new();
                let size_estimate = match method.req_marshaller.write_size_estimate(&req) {
                    Ok(len) => len,
                    Err(e) => return Box::pin(future::err(e)),
                };
                match write_grpc_frame_cb(&mut frame, size_estimate, |frame| {
                    method.req_marshaller.write(&req, size_estimate, frame)
                }) {
                    Ok(()) => {}
                    Err(e) => return Box::pin(future::err(e)),
                }
                Some(Bytes::from(frame))
            }
            None => None,
        };

        let end_stream = req_bytes.is_some();

        //        let request_frames = {
        //            let method = method.clone();
        //            req.0
        //                .and_then(move |req| {
        //                    let grpc_frame = method.req_marshaller.write(&req)?;
        //                    Ok(Bytes::from(write_grpc_frame_to_vec(&grpc_frame)))
        //                }).map_err(|_e| httpbis::Error::Other("grpc error")) // TODO: preserve error
        //        };

        let http_future = self
            .client
            .start_request(headers, req_bytes, None, end_stream);

        let http_future = http_future.map_err(error::Error::from);

        let req_marshaller = method.req_marshaller.clone();
        let resp_marshaller = method.resp_marshaller.clone();

        Box::pin(http_future.map_ok(move |(req, resp)| {
            let grpc_req = http_req_to_grpc_frames_typed(req, req_marshaller);
            let grpc_resp = http_response_to_grpc_frames_typed(resp, resp_marshaller);
            (grpc_req, grpc_resp)
        }))

        //        Box::new(http_future
        //            .map(|(req, resp)| {
        //                let grpc_req = ClientRequestSink {
        //                    common: SinkCommon {
        //                        marshaller: method.req_marshaller,
        //                        sink: req,
        //                    }
    }

    pub fn call_unary<Req, Resp>(
        &self,
        o: RequestOptions,
        req: Req,
        method: ArcOrStatic<MethodDescriptor<Req, Resp>>,
    ) -> SingleResponse<Resp>
    where
        Req: Send + 'static,
        Resp: Send + 'static,
    {
        SingleResponse::new(
            self.call_impl(o, Some(req), method)
                .and_then(|(_req, resp)| resp.single()),
        )
    }

    pub fn call_server_streaming<Req, Resp>(
        &self,
        o: RequestOptions,
        req: Req,
        method: ArcOrStatic<MethodDescriptor<Req, Resp>>,
    ) -> StreamingResponse<Resp>
    where
        Req: Send + 'static,
        Resp: Send + 'static,
    {
        let f = self.call_impl(o, Some(req), method);
        StreamingResponse::new(async move {
            let (_req, resp) = f.await?;
            resp.0.await
        })
    }

    pub fn call_client_streaming<Req, Resp>(
        &self,
        o: RequestOptions,
        method: ArcOrStatic<MethodDescriptor<Req, Resp>>,
    ) -> impl Future<Output = crate::Result<(ClientRequestSink<Req>, SingleResponse<Resp>)>>
    where
        Req: Send + 'static,
        Resp: Send + 'static,
    {
        TryFutureExt::map_ok(self.call_impl(o, None, method), |(req, resp)| {
            (req, resp.single())
        })
    }

    pub fn call_bidi<Req, Resp>(
        &self,
        o: RequestOptions,
        method: ArcOrStatic<MethodDescriptor<Req, Resp>>,
    ) -> impl Future<Output = crate::Result<(ClientRequestSink<Req>, StreamingResponse<Resp>)>>
    where
        Req: Send + 'static,
        Resp: Send + 'static,
    {
        self.call_impl(o, None, method)
    }
}

fn _assert_types() {
    crate::assert_types::assert_send::<Client>();
    crate::assert_types::assert_sync::<Client>();
}