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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
//! gRPC server implementation

///  module svc_storage generated from svc-storage.proto
mod grpc_server {
    #![allow(unused_qualifications, missing_docs)]
    tonic::include_proto!("grpc");
}

pub use crate::amqp::init_mq;
use crate::region::RestrictionDetails;
pub use grpc_server::rpc_service_server::{RpcService, RpcServiceServer};
pub use grpc_server::{FlightPlanRequest, FlightPlanResponse};
pub use grpc_server::{FlightReleaseRequest, FlightReleaseResponse};
pub use grpc_server::{ReadyRequest, ReadyResponse};
use svc_gis_client_grpc::prelude::*;

use crate::config::Config;
use crate::region::RegionInterface;
use crate::shutdown_signal;

use core::fmt;
use std::collections::HashMap;
use std::net::SocketAddr;
use tonic::transport::Server;
use tonic::{Request, Response, Status};

/// struct to implement the gRPC server functions
pub struct ServerImpl {
    /// AMQP channel
    pub mq_channel: Option<lapin::Channel>,

    /// Region interface
    pub region: Box<dyn RegionInterface + Send + Sync>,
}

/// Results of updating restrictions
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum UpdateRestrictionsStatus {
    /// Restrictions were updated
    Success,

    /// No restrictions were updated
    NoRestrictions,

    /// Request to gRPC server failed
    RequestFailure,
}

/// Results of updating waypoints
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum UpdateWaypointsStatus {
    /// Waypoints were updated
    Success,

    /// No waypoints were updated
    NoWaypoints,

    /// Request to gRPC server failed
    RequestFailure,
}

impl fmt::Debug for ServerImpl {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ServerImpl")
            .field("region", &"RegionInterface (not printable)")
            .finish()
    }
}

#[cfg(not(feature = "stub_server"))]
#[tonic::async_trait]
impl RpcService for ServerImpl {
    /// Returns ready:true when service is available
    async fn is_ready(
        &self,
        request: Request<ReadyRequest>,
    ) -> Result<Response<ReadyResponse>, Status> {
        let region = self.region.get_region();
        grpc_info!("(is_ready)[{}] compliance server.", region);
        grpc_debug!("(is_ready)[{}] [{:?}].", region, request);
        let response = ReadyResponse { ready: true };
        Ok(Response::new(response))
    }

    async fn submit_flight_plan(
        &self,
        request: Request<FlightPlanRequest>,
    ) -> Result<Response<FlightPlanResponse>, Status> {
        let region = self.region.get_region();
        grpc_info!("(submit_flight_plan)[{}] compliance server.", region);
        grpc_debug!("(submit_flight_plan)[{}] [{:?}].", region, request);
        let request = request.into_inner();
        let response = self.region.submit_flight_plan(request.clone())?;

        // send flight plan to AMQP
        if let Some(mq_channel) = &self.mq_channel {
            let Ok(payload) = serde_json::to_vec(&request) else {
                grpc_error!("(submit_flight_plan) Could not serialize flight plan.");
                return Ok(response);
            };

            let result = mq_channel
                .basic_publish(
                    crate::amqp::EXCHANGE_NAME_FLIGHTPLAN,
                    crate::amqp::QUEUE_NAME_CARGO,
                    lapin::options::BasicPublishOptions::default(),
                    &payload,
                    lapin::BasicProperties::default(),
                )
                .await;

            match result {
                Ok(_) => grpc_info!("(submit_flight_plan) Telemetry pushed to RabbitMQ."),
                Err(e) => {
                    grpc_error!("(submit_flight_plan) Telemetry push to RabbitMQ failed: {e}")
                }
            }
        }

        Ok(response)
    }

    async fn request_flight_release(
        &self,
        request: Request<FlightReleaseRequest>,
    ) -> Result<Response<FlightReleaseResponse>, Status> {
        let region = self.region.get_region();
        grpc_info!("(request_flight_release)[{}] compliance server.", region);
        grpc_debug!("(request_flight_release)[{}] [{:?}].", region, request);
        self.region.request_flight_release(request)
    }
}

async fn update_waypoints(
    host: String,
    port: u16,
    waypoints: &HashMap<String, gis::Coordinates>,
) -> UpdateWaypointsStatus {
    let nodes: Vec<gis::Waypoint> = waypoints
        .iter()
        .map(|(label, coordinates)| gis::Waypoint {
            identifier: label.clone(),
            location: Some(*coordinates),
        })
        .collect();

    if nodes.is_empty() {
        grpc_warn!("(update_waypoints) No waypoints to update.");
        return UpdateWaypointsStatus::NoWaypoints;
    }

    let client = GisClient::new_client(&host, port, "gis");
    match client
        .update_waypoints(gis::UpdateWaypointsRequest { waypoints: nodes })
        .await
    {
        Ok(response) => {
            grpc_debug!("(update_waypoints) Got response: {:?}", response);
            UpdateWaypointsStatus::Success
        }
        Err(e) => {
            grpc_error!("(update_waypoints) {:?}", e);
            UpdateWaypointsStatus::RequestFailure
        }
    }
}

/// Periodically pulls down waypoints from the regional interface and
///  pushes them to the GIS microservice
pub async fn waypoints_loop(config: Config, region: Box<dyn RegionInterface + Send + Sync>) {
    let host = config.gis_host_grpc;
    let port = config.gis_port_grpc;

    grpc_debug!(
        "(waypoints_loop) Starting loop with interval: {} seconds.",
        config.interval_seconds_refresh_waypoints
    );

    let mut cache: HashMap<String, gis::Coordinates> = HashMap::new();

    loop {
        // Pull down waypoints from regional interface
        region.acquire_waypoints(&mut cache).await;
        update_waypoints(host.clone(), port, &cache).await;
        std::thread::sleep(std::time::Duration::from_secs(
            config.interval_seconds_refresh_waypoints as u64,
        ));
    }
}

async fn update_restrictions(
    host: String,
    port: u16,
    restrictions: &HashMap<String, RestrictionDetails>,
) -> UpdateRestrictionsStatus {
    let mut zones: Vec<gis::Zone> = vec![];

    for (label, details) in restrictions.iter() {
        let time_start = details.timestamp_start.map(|t| t.into());
        let time_end = details.timestamp_end.map(|t| t.into());

        zones.push(gis::Zone {
            identifier: label.clone(),
            zone_type: details.zone_type as i32,
            altitude_meters_max: details.altitude_meters_max,
            altitude_meters_min: details.altitude_meters_min,
            vertices: details
                .vertices
                .iter()
                .map(|v| gis::Coordinates {
                    latitude: v.latitude,
                    longitude: v.longitude,
                })
                .collect(),
            time_start,
            time_end,
        });
    }

    if zones.is_empty() {
        grpc_warn!("(update_restrictions) No restrictions to update.");
        return UpdateRestrictionsStatus::NoRestrictions;
    }

    let client = GisClient::new_client(&host, port, "gis");
    match client.update_zones(gis::UpdateZonesRequest { zones }).await {
        Ok(response) => {
            grpc_debug!("(update_restrictions) Got response: {:?}", response);
            UpdateRestrictionsStatus::Success
        }
        Err(e) => {
            grpc_error!("(update_restrictions) {:?}", e);
            UpdateRestrictionsStatus::RequestFailure
        }
    }
}

/// Periodically pulls down restrictions from the regional interface and
///  pushes them to the GIS microservice
pub async fn restrictions_loop(config: Config, region: Box<dyn RegionInterface + Send + Sync>) {
    let host = config.gis_host_grpc;
    let port = config.gis_port_grpc;
    let mut cache: HashMap<String, RestrictionDetails> = HashMap::new();

    grpc_info!(
        "(restrictions_loop) Starting loop with interval: {} seconds.",
        config.interval_seconds_refresh_zones
    );

    loop {
        region.acquire_restrictions(&mut cache).await;
        update_restrictions(host.clone(), port, &cache).await;
        std::thread::sleep(std::time::Duration::from_secs(
            config.interval_seconds_refresh_zones as u64,
        ));
    }
}

/// Starts the grpc servers for this microservice using the provided configuration
///
/// # Example:
/// ```
/// use svc_compliance::grpc::server::grpc_server;
/// use svc_compliance::config::Config;
/// async fn example() -> Result<(), tokio::task::JoinError> {
///     let config = Config::default();
///     tokio::spawn(grpc_server(config, None)).await
/// }
/// ```
#[cfg(not(tarpaulin_include))]
// no_coverage: Can not be tested in unittest, should be part of integration
// tests
pub async fn grpc_server(config: Config, shutdown_rx: Option<tokio::sync::oneshot::Receiver<()>>) {
    grpc_debug!("(grpc_server) entry.");

    // Grpc Server
    let grpc_port = config.docker_port_grpc;
    let full_grpc_addr: SocketAddr = match format!("[::]:{}", grpc_port).parse() {
        Ok(addr) => addr,
        Err(e) => {
            grpc_error!("(grpc_server) Failed to parse gRPC address: {}", e);
            return;
        }
    };

    // RabbitMQ Channel
    let Ok(mq_channel) = init_mq(config.clone()).await else {
        grpc_error!("(grpc_server) Could not create channel to amqp server.");
        return;
    };

    let imp = ServerImpl {
        mq_channel: Some(mq_channel),
        region: Box::<crate::region::RegionImpl>::default(),
    };

    tokio::spawn(restrictions_loop(
        config.clone(),
        Box::<crate::region::RegionImpl>::default(),
    ));

    tokio::spawn(waypoints_loop(
        config.clone(),
        Box::<crate::region::RegionImpl>::default(),
    ));

    let (mut health_reporter, health_service) = tonic_health::server::health_reporter();
    health_reporter
        .set_serving::<RpcServiceServer<ServerImpl>>()
        .await;

    //start server
    grpc_info!(
        "(grpc_server)[{}] Starting gRPC services on: {}",
        imp.region.get_region(),
        full_grpc_addr
    );
    match Server::builder()
        .add_service(health_service)
        .add_service(RpcServiceServer::new(imp))
        .serve_with_shutdown(full_grpc_addr, shutdown_signal("grpc", shutdown_rx))
        .await
    {
        Ok(_) => grpc_info!("(grpc_server) gRPC server running at: {}", full_grpc_addr),
        Err(e) => {
            grpc_error!("(grpc_server) Could not start gRPC server: {}", e);
        }
    };
}

#[cfg(feature = "stub_server")]
#[tonic::async_trait]
impl RpcService for ServerImpl {
    async fn is_ready(
        &self,
        request: Request<ReadyRequest>,
    ) -> Result<Response<ReadyResponse>, Status> {
        let region = self.region.get_region();
        grpc_warn!("(is_ready MOCK)[{}] compliance server.", region);
        grpc_debug!("(is_ready MOCK)[{}] [{:?}].", region, request);
        let response = ReadyResponse { ready: true };
        Ok(Response::new(response))
    }

    async fn submit_flight_plan(
        &self,
        request: Request<FlightPlanRequest>,
    ) -> Result<Response<FlightPlanResponse>, Status> {
        let region = self.region.get_region();
        grpc_warn!("(submit_flight_plan MOCK)[{}] compliance server.", region);
        grpc_debug!("(submit_flight_plan MOCK)[{}] [{:?}].", region, request);
        let request = request.into_inner();
        Ok(tonic::Response::new(FlightPlanResponse {
            flight_plan_id: request.flight_plan_id,
            submitted: true,
            result: None,
        }))
    }

    async fn request_flight_release(
        &self,
        request: Request<FlightReleaseRequest>,
    ) -> Result<Response<FlightReleaseResponse>, Status> {
        let region = self.region.get_region();
        grpc_warn!(
            "(request_flight_release MOCK)[{}] compliance server.",
            region
        );
        grpc_debug!("(request_flight_release MOCK)[{}] [{:?}].", region, request);
        let request = request.into_inner();
        Ok(tonic::Response::new(FlightReleaseResponse {
            flight_plan_id: request.flight_plan_id,
            released: true,
            result: None,
        }))
    }
}

#[cfg(test)]
mod tests {
    use super::grpc_server::*;
    use super::*;

    fn get_server_impl() -> ServerImpl {
        let region = Box::<crate::region::RegionImpl>::default();
        ServerImpl {
            mq_channel: None,
            region,
        }
    }

    #[tokio::test]
    async fn test_region_code() {
        crate::get_log_handle().await;
        ut_info!("(test_region_code) Start.");

        let imp = get_server_impl();
        cfg_if::cfg_if! {
            if #[cfg(feature = "nl")] {
                assert_eq!(imp.region.get_region(), "nl");
            } else {
                assert_eq!(imp.region.get_region(), "us");
            }
        }

        ut_info!("(test_region_code) Success.");
    }

    #[tokio::test]
    async fn test_grpc_server_is_ready() {
        crate::get_log_handle().await;
        ut_info!("(test_grpc_server_is_ready) Start.");

        let imp = get_server_impl();
        let result = imp.is_ready(Request::new(ReadyRequest {})).await;
        assert!(result.is_ok());
        let result: ReadyResponse = result.unwrap().into_inner();
        assert_eq!(result.ready, true);

        ut_info!("(test_grpc_server_is_ready) Success.");
    }

    #[tokio::test]
    async fn test_grpc_submit_flight_plan() {
        crate::get_log_handle().await;
        ut_info!("(test_grpc_submit_flight_plan) Start.");

        let imp = get_server_impl();
        let result = imp
            .submit_flight_plan(Request::new(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);

        ut_info!("(test_grpc_submit_flight_plan) Success.");
    }

    #[tokio::test]
    async fn test_grpc_request_flight_release() {
        crate::get_log_handle().await;
        ut_info!("(test_grpc_request_flight_release) Start.");

        let imp = get_server_impl();
        let result = imp
            .request_flight_release(Request::new(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);

        ut_info!("(test_grpc_request_flight_release) Success.");
    }

    #[tokio::test]
    async fn test_update_restrictions() {
        crate::get_log_handle().await;
        ut_info!("(test_update_restrictions) Start.");

        let host = "localhost".to_string();
        let port = 50008;

        let mut cache: HashMap<String, RestrictionDetails> = HashMap::new();
        let result = update_restrictions(host.clone(), port, &cache).await;
        assert_eq!(result, UpdateRestrictionsStatus::NoRestrictions);

        cache.insert(
            "test".to_string(),
            RestrictionDetails {
                vertices: vec![],
                timestamp_start: Some(chrono::Utc::now()),
                timestamp_end: None,
                altitude_meters_max: 0.,
                altitude_meters_min: 200.,
                zone_type: gis::ZoneType::Restriction,
            },
        );

        let result = update_restrictions(host.clone(), port, &cache).await;
        assert_eq!(result, UpdateRestrictionsStatus::Success);

        ut_info!("(test_update_restrictions) Success.");
    }

    #[tokio::test]
    async fn test_update_waypoints() {
        crate::get_log_handle().await;
        ut_info!("(test_update_waypoints) Start.");

        let host = "localhost".to_string();
        let port = 50008;

        let mut cache: HashMap<String, gis::Coordinates> = HashMap::new();
        let result = update_waypoints(host.clone(), port, &cache).await;
        assert_eq!(result, UpdateWaypointsStatus::NoWaypoints);

        cache.insert(
            "ARROW-WAY-1".to_string(),
            gis::Coordinates {
                latitude: 0.0,
                longitude: 0.0,
            },
        );

        let result = update_waypoints(host.clone(), port, &cache).await;
        assert_eq!(result, UpdateWaypointsStatus::Success);

        ut_info!("(test_update_waypoints) Success.");
    }
}