apache_dubbo/protocol/grpc/
grpc_server.rs

1/*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements.  See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License.  You may obtain a copy of the License at
8 *
9 *     http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18use std::task::Context;
19use std::task::Poll;
20
21use tonic::codegen::BoxFuture;
22use tonic::transport;
23use tonic::transport::NamedService;
24use tower::Service;
25
26use crate::common::url::Url;
27use crate::utils::boxed_clone::BoxCloneService;
28
29// 每个service对应一个Server
30#[derive(Clone)]
31pub struct GrpcServer {
32    inner: transport::Server,
33    name: String,
34}
35
36impl GrpcServer {
37    pub fn new(name: String) -> GrpcServer {
38        Self {
39            inner: transport::Server::builder(),
40            name,
41        }
42    }
43
44    pub async fn serve(mut self, url: Url) {
45        let addr = url.to_url().parse().unwrap();
46        let svc = super::GRPC_SERVICES
47            .read()
48            .unwrap()
49            .get(self.name.as_str())
50            .unwrap()
51            .clone();
52        tracing::info!("server{:?} start...", url);
53        self.inner
54            .add_service(MakeSvc::new(svc))
55            .serve(addr)
56            .await
57            .unwrap();
58    }
59}
60
61struct MakeSvc<T, U, E> {
62    inner: BoxCloneService<T, U, E>,
63}
64
65impl<T, U, E> MakeSvc<T, U, E> {
66    pub fn new(inner: BoxCloneService<T, U, E>) -> Self {
67        Self { inner }
68    }
69}
70
71impl<T, U, E> NamedService for MakeSvc<T, U, E> {
72    const NAME: &'static str = "helloworld.Greeter";
73}
74
75impl<T, U, E> Service<T> for MakeSvc<T, U, E> {
76    type Response = U;
77    type Error = E;
78    type Future = BoxFuture<U, E>;
79
80    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), E>> {
81        self.inner.poll_ready(cx)
82    }
83
84    fn call(&mut self, request: T) -> BoxFuture<U, E> {
85        self.inner.call(request)
86    }
87}
88
89impl<T, U, E> Clone for MakeSvc<T, U, E> {
90    fn clone(&self) -> Self {
91        Self {
92            inner: self.inner.clone(),
93        }
94    }
95}