medea_control_api_proto/grpc/
server.rs

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
//! [`ControlApi`] server and [`CallbackApi`] client [gRPC] implementations.
//!
//! [gRPC]: https://grpc.io

use std::collections::HashMap;

use async_trait::async_trait;
use derive_more::{Display, Error, From};
use tonic::codegen::{Body, Bytes};

use crate::{
    callback::Request as CallbackRequest,
    control::Request as ControlRequest,
    grpc::{
        api::{
            self as control_proto,
            control_api_server::ControlApi as GrpcControlApiService,
        },
        callback as callback_proto, CallbackApiClient, ProtobufError,
    },
    CallbackApi, ControlApi,
};

/// [`Box`]ed [`Error`] with [`Send`] and [`Sync`].
type StdError = Box<dyn Error + Send + Sync + 'static>;

#[async_trait]
impl<T: ?Sized> GrpcControlApiService for T
where
    T: ControlApi + Send + Sync + 'static,
    T::Error: From<ProtobufError>,
    control_proto::Error: From<T::Error>,
{
    async fn create(
        &self,
        request: tonic::Request<control_proto::CreateRequest>,
    ) -> Result<tonic::Response<control_proto::CreateResponse>, tonic::Status>
    {
        let fut = async {
            self.create(ControlRequest::try_from(request.into_inner())?)
                .await
        };

        Ok(tonic::Response::new(match fut.await {
            Ok(sids) => control_proto::CreateResponse {
                sid: sids
                    .into_iter()
                    .map(|(id, sid)| (id.to_string(), sid.to_uri_string()))
                    .collect(),
                error: None,
            },
            Err(e) => control_proto::CreateResponse {
                sid: HashMap::new(),
                error: Some(e.into()),
            },
        }))
    }

    async fn delete(
        &self,
        request: tonic::Request<control_proto::IdRequest>,
    ) -> Result<tonic::Response<control_proto::Response>, tonic::Status> {
        let ids = request
            .into_inner()
            .fid
            .into_iter()
            .map(|fid| fid.parse().map_err(ProtobufError::from))
            .collect::<Result<Vec<_>, _>>();

        let result = match ids {
            Ok(ids) => self.delete(&ids).await,
            Err(e) => Err(e.into()),
        };

        Ok(tonic::Response::new(match result {
            Ok(()) => control_proto::Response { error: None },
            Err(e) => control_proto::Response {
                error: Some(e.into()),
            },
        }))
    }

    async fn get(
        &self,
        request: tonic::Request<control_proto::IdRequest>,
    ) -> Result<tonic::Response<control_proto::GetResponse>, tonic::Status>
    {
        let ids = request
            .into_inner()
            .fid
            .into_iter()
            .map(|fid| fid.parse().map_err(ProtobufError::from))
            .collect::<Result<Vec<_>, _>>();

        let result = match ids {
            Ok(ids) => self.get(&ids).await,
            Err(e) => Err(e.into()),
        };

        Ok(tonic::Response::new(match result {
            Ok(elements) => control_proto::GetResponse {
                elements: elements
                    .into_iter()
                    .map(|(id, el)| {
                        let s = id.to_string();
                        (id, el).try_into().map(|proto| (s, proto))
                    })
                    .collect::<Result<_, _>>()?,
                error: None,
            },
            Err(e) => control_proto::GetResponse {
                elements: HashMap::new(),
                error: Some(e.into()),
            },
        }))
    }

    async fn apply(
        &self,
        request: tonic::Request<control_proto::ApplyRequest>,
    ) -> Result<tonic::Response<control_proto::CreateResponse>, tonic::Status>
    {
        let result = async {
            let req = ControlRequest::try_from(request.into_inner())?;
            self.apply(req).await
        };

        Ok(tonic::Response::new(match result.await {
            Ok(sids) => control_proto::CreateResponse {
                sid: sids
                    .into_iter()
                    .map(|(id, sid)| (id.to_string(), sid.to_uri_string()))
                    .collect(),
                error: None,
            },
            Err(e) => control_proto::CreateResponse {
                sid: HashMap::new(),
                error: Some(e.into()),
            },
        }))
    }

    async fn healthz(
        &self,
        request: tonic::Request<control_proto::Ping>,
    ) -> Result<tonic::Response<control_proto::Pong>, tonic::Status> {
        self.healthz(request.into_inner().into())
            .await
            .map(|pong| tonic::Response::new(pong.into()))
            .map_err(|e| {
                let e = control_proto::Error::from(e);
                let message = [&e.doc, &e.element, &e.text].into_iter().fold(
                    e.code.to_string(),
                    |mut acc, s| {
                        if !s.is_empty() {
                            acc.push_str(": ");
                            acc.push_str(s);
                        }
                        acc
                    },
                );
                tonic::Status::unknown(message)
            })
    }
}

#[async_trait]
impl<T> CallbackApi for CallbackApiClient<T>
where
    T: tonic::client::GrpcService<tonic::body::BoxBody> + Clone + Send + Sync,
    T::Future: Send,
    T::ResponseBody: Body<Data = Bytes> + Send + 'static,
    <T::ResponseBody as Body>::Error: Send,
    StdError: From<<T::ResponseBody as Body>::Error>,
{
    type Error = CallbackApiClientError;

    async fn on_event(
        &self,
        request: CallbackRequest,
    ) -> Result<(), Self::Error> {
        // It's OK to `.clone()` `tonic::client`:
        // https://docs.rs/tonic/latest/tonic/client/index.html#concurrent-usage
        let mut this = self.clone();

        Self::on_event(&mut this, callback_proto::Request::from(request))
            .await
            .map(drop)
            .map_err(Into::into)
    }
}

/// Possible errors of [`CallbackApiClient`].
#[derive(Debug, Display, From, Error)]
pub enum CallbackApiClientError {
    /// [gRPC] server errored.
    ///
    /// [gRPC]: https://grpc.io
    #[display("gRPC server errored: {_0}")]
    Tonic(tonic::Status),

    /// Failed to convert from [gRPC] response.
    ///
    /// [gRPC]: https://grpc.io
    #[display("Failed to convert from gRPC response: {_0}")]
    InvalidProtobuf(ProtobufError),
}