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
//! Client Library: Client Functions, Structs, Traits
#![allow(unused_qualifications)]
include!("grpc.rs");

use super::*;

#[cfg(any(not(feature = "stub_client"), feature = "stub_backends"))]
use lib_common::grpc::ClientConnect;
use lib_common::grpc::{Client, GrpcClient};
use rpc_service_client::RpcServiceClient;
/// GrpcClient implementation of the RpcServiceClient
pub type ComplianceClient = GrpcClient<RpcServiceClient<Channel>>;

cfg_if::cfg_if! {
    if #[cfg(feature = "stub_backends")] {
        use svc_compliance::grpc::server::{RpcServiceServer, ServerImpl};

        #[tonic::async_trait]
        impl lib_common::grpc::ClientConnect<RpcServiceClient<Channel>> for ComplianceClient {
            /// Get a connected client object
            async fn connect(
                &self,
            ) -> Result<RpcServiceClient<Channel>, tonic::transport::Error> {
                let (client, server) = tokio::io::duplex(1024);

                let region = Box::<svc_compliance::region::RegionImpl>::default();

                let grpc_service = ServerImpl {
                    mq_channel: None,
                    region,
                };

                lib_common::grpc::mock::start_mock_server(
                    server,
                    RpcServiceServer::new(grpc_service),
                )
                .await?;

                // Move client to an option so we can _move_ the inner value
                // on the first attempt to connect. All other attempts will fail.
                let mut client = Some(client);
                let channel = tonic::transport::Endpoint::try_from("http://[::]:50051")?
                    .connect_with_connector(tower::service_fn(move |_: tonic::transport::Uri| {
                        let client = client.take();

                        async move {
                            if let Some(client) = client {
                                Ok(client)
                            } else {
                                Err(std::io::Error::new(
                                    std::io::ErrorKind::Other,
                                    "Client already taken",
                                ))
                            }
                        }
                    }))
                    .await?;

                Ok(RpcServiceClient::new(channel))
            }
        }

        super::log_macros!("grpc", "app::client::mock::compliance");
    } else {
        lib_common::grpc_client!(RpcServiceClient);
        super::log_macros!("grpc", "app::client::compliance");
    }
}

#[cfg(not(feature = "stub_client"))]
#[async_trait]
impl service::Client<RpcServiceClient<Channel>> for ComplianceClient {
    type ReadyRequest = ReadyRequest;
    type ReadyResponse = ReadyResponse;

    async fn is_ready(
        &self,
        request: Self::ReadyRequest,
    ) -> Result<tonic::Response<Self::ReadyResponse>, tonic::Status> {
        grpc_info!("(is_ready) {} client.", self.get_name());
        grpc_debug!("(is_ready) request: {:?}", request);
        self.get_client().await?.is_ready(request).await
    }

    async fn submit_flight_plan(
        &self,
        request: FlightPlanRequest,
    ) -> Result<tonic::Response<FlightPlanResponse>, tonic::Status> {
        grpc_warn!("(submit_flight_plan) {} client.", self.get_name());
        grpc_debug!("(submit_flight_plan) request: {:?}", request);
        self.get_client().await?.submit_flight_plan(request).await
    }

    async fn request_flight_release(
        &self,
        request: FlightReleaseRequest,
    ) -> Result<tonic::Response<FlightReleaseResponse>, tonic::Status> {
        grpc_warn!("(request_flight_release) {} client.", self.get_name());
        grpc_debug!("(request_flight_release) request: {:?}", request);
        self.get_client()
            .await?
            .request_flight_release(request)
            .await
    }
}

#[cfg(feature = "stub_client")]
#[async_trait]
impl service::Client<RpcServiceClient<Channel>> for ComplianceClient {
    type ReadyRequest = ReadyRequest;
    type ReadyResponse = ReadyResponse;

    async fn is_ready(
        &self,
        request: Self::ReadyRequest,
    ) -> Result<tonic::Response<Self::ReadyResponse>, tonic::Status> {
        grpc_warn!("(is_ready MOCK) {} client.", self.get_name());
        grpc_debug!("(is_ready MOCK) request: {:?}", request);
        Ok(tonic::Response::new(ReadyResponse { ready: true }))
    }
    async fn submit_flight_plan(
        &self,
        request: FlightPlanRequest,
    ) -> Result<tonic::Response<FlightPlanResponse>, tonic::Status> {
        grpc_warn!("(submit_flight_plan MOCK) {} client.", self.get_name());
        grpc_debug!("(submit_flight_plan MOCK) request: {:?}", request);
        Ok(tonic::Response::new(FlightPlanResponse {
            flight_plan_id: request.flight_plan_id,
            submitted: true,
            result: None,
        }))
    }

    async fn request_flight_release(
        &self,
        request: FlightReleaseRequest,
    ) -> Result<tonic::Response<FlightReleaseResponse>, tonic::Status> {
        grpc_warn!("(request_flight_release MOCK) {} client.", self.get_name());
        grpc_debug!("(request_flight_release MOCK) request: {:?}", request);
        Ok(tonic::Response::new(FlightReleaseResponse {
            flight_plan_id: request.flight_plan_id,
            released: true,
            result: None,
        }))
    }
}

#[cfg(test)]
mod tests {
    use crate::service::Client as ServiceClient;
    // use lib_common::grpc::ClientConnect;

    use super::*;

    #[tokio::test]
    #[cfg(not(feature = "stub_client"))]
    async fn test_client_connect() {
        let name = "compliance";
        let (server_host, server_port) =
            lib_common::grpc::get_endpoint_from_env("GRPC_HOST", "GRPC_PORT");

        let client = ComplianceClient::new_client(&server_host, server_port, name);
        assert_eq!(client.get_name(), name);

        let client = client.get_client().await;
        println!("{:?}", client);
        assert!(client.is_ok());
    }

    #[tokio::test]
    async fn test_client_is_ready_request() {
        let name = "compliance";
        let (server_host, server_port) =
            lib_common::grpc::get_endpoint_from_env("GRPC_HOST", "GRPC_PORT");

        let client = ComplianceClient::new_client(&server_host, server_port, name);

        let result = client.is_ready(ReadyRequest {}).await;
        println!("{:?}", result);
        assert!(result.is_ok());
        assert_eq!(result.unwrap().into_inner().ready, true);
    }

    #[tokio::test]
    async fn test_client_submit_flight_plan() {
        let name = "compliance";
        let (server_host, server_port) =
            lib_common::grpc::get_endpoint_from_env("GRPC_HOST", "GRPC_PORT");

        let client = ComplianceClient::new_client(&server_host, server_port, name);

        let result = client
            .submit_flight_plan(FlightPlanRequest {
                flight_plan_id: "".to_string(),
                data: "".to_string(),
            })
            .await;

        assert!(result.is_ok());
        let result: FlightPlanResponse = result.unwrap().into_inner();
        println!("{:?}", result);
        assert_eq!(result.submitted, true);
    }

    #[tokio::test]
    async fn test_grpc_request_flight_release() {
        let name = "compliance";
        let (server_host, server_port) =
            lib_common::grpc::get_endpoint_from_env("GRPC_HOST", "GRPC_PORT");

        let client = ComplianceClient::new_client(&server_host, server_port, name);

        let result = client
            .request_flight_release(FlightReleaseRequest {
                flight_plan_id: "".to_string(),
                data: "".to_string(),
            })
            .await;

        assert!(result.is_ok());
        let result: FlightReleaseResponse = result.unwrap().into_inner();
        println!("{:?}", result);
        assert_eq!(result.released, true);
    }
}