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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
//! Library providing the routing and http responses for aws lambda requests.
//!

use std::collections::HashMap;
use std::sync::Arc;

use lambda_http::ext::RequestExt;
use lambda_http::http::{Method, StatusCode, Uri};
use lambda_http::tower::ServiceBuilder;
use lambda_http::{http, service_fn, Body, Request, Response};
use lambda_runtime::Error;
use tracing::instrument;
use tracing::{debug, info};

use htsget_config::config::cors::CorsConfig;
pub use htsget_config::config::{Config, DataServerConfig, ServiceInfo, TicketServerConfig};
pub use htsget_config::storage::Storage;
use htsget_http::{Endpoint, PostRequest};
use htsget_search::htsget::HtsGet;
use htsget_search::storage::configure_cors;

use crate::handlers::get::get;
use crate::handlers::post::post;
use crate::handlers::service_info::get_service_info_json;

pub mod handlers;

/// A request route, with a method, endpoint and route type.
#[derive(Debug, PartialEq, Eq)]
pub struct Route {
  method: HtsgetMethod,
  endpoint: Endpoint,
  route_type: RouteType,
}

/// Valid htsget http request methods.
#[derive(Debug, PartialEq, Eq)]
pub enum HtsgetMethod {
  Get,
  Post,
}

/// A route type, which is either the service info endpoint, or an id represented by a string.
#[derive(Debug, PartialEq, Eq)]
pub enum RouteType {
  ServiceInfo,
  Id(String),
}

impl Route {
  pub fn new(method: HtsgetMethod, endpoint: Endpoint, route_type: RouteType) -> Self {
    Self {
      method,
      endpoint,
      route_type,
    }
  }
}

/// A Router is a struct which handles routing any htsget requests to the htsget search, using the config.
pub struct Router<'a, H> {
  searcher: Arc<H>,
  config_service_info: &'a ServiceInfo,
}

impl<'a, H: HtsGet + Send + Sync + 'static> Router<'a, H> {
  pub fn new(searcher: Arc<H>, config_service_info: &'a ServiceInfo) -> Self {
    Self {
      searcher,
      config_service_info,
    }
  }

  /// Gets the Route if the request is valid, otherwise returns None.
  fn get_route(&self, method: &Method, uri: &Uri) -> Option<Route> {
    let with_endpoint = |endpoint: Endpoint, endpoint_type: &str| {
      if endpoint_type.is_empty() {
        None
      } else {
        let method = match *method {
          Method::GET => Some(HtsgetMethod::Get),
          Method::POST => Some(HtsgetMethod::Post),
          _ => None,
        }?;
        if endpoint_type == "service-info" {
          Some(Route::new(method, endpoint, RouteType::ServiceInfo))
        } else {
          Some(Route::new(
            method,
            endpoint,
            RouteType::Id(endpoint_type.to_string()),
          ))
        }
      }
    };

    uri.path().strip_prefix("/reads/").map_or_else(
      || {
        uri
          .path()
          .strip_prefix("/variants/")
          .and_then(|variants| with_endpoint(Endpoint::Variants, variants))
      },
      |reads| with_endpoint(Endpoint::Reads, reads),
    )
  }

  /// Routes the request to the relevant htsget search endpoint using the lambda request, returning a http response.
  pub async fn route_request(&self, request: Request) -> http::Result<Response<Body>> {
    match self.get_route(request.method(), &request.raw_http_path().parse::<Uri>()?) {
      Some(Route {
        endpoint,
        route_type: RouteType::ServiceInfo,
        ..
      }) => get_service_info_json(self.searcher.clone(), endpoint, self.config_service_info),
      Some(Route {
        method: HtsgetMethod::Get,
        endpoint,
        route_type: RouteType::Id(id),
      }) => {
        get(
          id,
          self.searcher.clone(),
          Self::extract_query(&request),
          endpoint,
        )
        .await
      }
      Some(Route {
        method: HtsgetMethod::Post,
        endpoint,
        route_type: RouteType::Id(id),
      }) => match Self::extract_query_from_payload(&request) {
        None => Ok(
          Response::builder()
            .status(StatusCode::UNSUPPORTED_MEDIA_TYPE)
            .body(Body::Empty)?,
        ),
        Some(query) => post(id, self.searcher.clone(), query, endpoint).await,
      },
      _ => Ok(
        Response::builder()
          .status(StatusCode::METHOD_NOT_ALLOWED)
          .body(Body::Empty)?,
      ),
    }
  }

  /// Extracts post request query parameters.
  #[instrument(level = "debug", ret)]
  fn extract_query_from_payload(request: &Request) -> Option<PostRequest> {
    if request.body().is_empty() {
      Some(PostRequest::default())
    } else {
      let payload = request.payload::<PostRequest>();
      debug!(payload = ?payload, "POST request payload");
      // Allows null/empty bodies.
      payload.ok()?
    }
  }

  /// Extract get request query parameters.
  #[instrument(level = "debug", ret)]
  fn extract_query(request: &Request) -> HashMap<String, String> {
    let mut query = HashMap::new();
    // Silently ignores all but the last query key, for keys that are present more than once.
    // This is the way actix-web does it, but should we return an error instead if a key is present
    // more than once?
    for (key, value) in request.query_string_parameters().iter() {
      query.insert(key.to_string(), value.to_string());
    }
    debug!(query = ?query, "GET request query");
    query
  }
}

pub async fn handle_request<H>(cors: CorsConfig, router: &Router<'_, H>) -> Result<(), Error>
where
  H: HtsGet + Send + Sync + 'static,
{
  let cors_layer = configure_cors(cors)?;

  let handler =
    ServiceBuilder::new()
      .layer(cors_layer)
      .service(service_fn(|event: Request| async move {
        info!(event = ?event, "received request");
        router.route_request(event).await
      }));

  lambda_http::run(handler).await?;

  Ok(())
}

#[cfg(test)]
mod tests {
  use std::future::Future;
  use std::path::Path;
  use std::str::FromStr;
  use std::sync::Arc;

  use async_trait::async_trait;
  use lambda_http::http::header::HeaderName;
  use lambda_http::http::Uri;
  use lambda_http::tower::ServiceExt;
  use lambda_http::Body::Text;
  use lambda_http::{Request, RequestExt, Service};
  use query_map::QueryMap;
  use tempfile::TempDir;

  use htsget_config::resolver::Resolver;
  use htsget_config::types::{Class, JsonResponse};
  use htsget_http::Endpoint;
  use htsget_search::storage::configure_cors;
  use htsget_search::storage::data_server::BindDataServer;
  use htsget_test::http_tests::{config_with_tls, default_test_config, get_test_file};
  use htsget_test::http_tests::{Header, Response as TestResponse, TestRequest, TestServer};
  use htsget_test::server_tests::{expected_url_path, test_response, test_response_service_info};
  use htsget_test::{cors_tests, server_tests};

  use super::*;

  struct LambdaTestServer {
    config: Config,
  }

  struct LambdaTestRequest<T>(T);

  impl TestRequest for LambdaTestRequest<Request> {
    fn insert_header(mut self, header: Header<impl Into<String>>) -> Self {
      self.0.headers_mut().insert(
        HeaderName::from_str(&header.name.into()).expect("expected valid header name"),
        header
          .value
          .into()
          .parse()
          .expect("expected valid header value"),
      );
      self
    }

    fn set_payload(mut self, payload: impl Into<String>) -> Self {
      *self.0.body_mut() = Text(payload.into());
      self
    }

    fn uri(mut self, uri: impl Into<String>) -> Self {
      let uri = uri.into();
      *self.0.uri_mut() = uri.parse().expect("expected valid uri");
      if let Some(query) = self.0.uri().query().map(|s| s.to_string()) {
        Self(
          self
            .0
            .with_query_string_parameters(
              query
                .parse::<QueryMap>()
                .expect("expected valid query parameters"),
            )
            .with_raw_http_path(&uri),
        )
      } else {
        Self(self.0.with_raw_http_path(&uri))
      }
    }

    fn method(mut self, method: impl Into<String>) -> Self {
      *self.0.method_mut() = method.into().parse().expect("expected valid method");
      self
    }
  }

  impl Default for LambdaTestServer {
    fn default() -> Self {
      Self {
        config: default_test_config(),
      }
    }
  }

  #[async_trait(?Send)]
  impl TestServer<LambdaTestRequest<Request>> for LambdaTestServer {
    async fn get_expected_path(&self) -> String {
      spawn_server(self.get_config()).await
    }

    fn get_config(&self) -> &Config {
      &self.config
    }

    fn get_request(&self) -> LambdaTestRequest<Request> {
      LambdaTestRequest(Request::default())
    }

    async fn test_server(
      &self,
      request: LambdaTestRequest<Request>,
      expected_path: String,
    ) -> TestResponse {
      let router = Router::new(
        Arc::new(self.config.clone().owned_resolvers()),
        self.config.ticket_server().service_info(),
      );

      route_request_to_response(request.0, router, expected_path, &self.config).await
    }
  }

  impl LambdaTestServer {
    fn new_with_tls<P: AsRef<Path>>(path: P) -> Self {
      Self {
        config: config_with_tls(path),
      }
    }
  }

  #[tokio::test]
  async fn get_http_tickets() {
    server_tests::test_get::<JsonResponse, _>(&LambdaTestServer::default()).await;
  }

  #[tokio::test]
  async fn post_http_tickets() {
    server_tests::test_post::<JsonResponse, _>(&LambdaTestServer::default()).await;
  }

  #[tokio::test]
  async fn parameterized_get_http_tickets() {
    server_tests::test_parameterized_get::<JsonResponse, _>(&LambdaTestServer::default()).await;
  }

  #[tokio::test]
  async fn parameterized_post_http_tickets() {
    server_tests::test_parameterized_post::<JsonResponse, _>(&LambdaTestServer::default()).await;
  }

  #[tokio::test]
  async fn parameterized_post_class_header_http_tickets() {
    server_tests::test_parameterized_post_class_header::<JsonResponse, _>(
      &LambdaTestServer::default(),
    )
    .await;
  }

  #[tokio::test]
  async fn cors_simple_request() {
    cors_tests::test_cors_simple_request(&LambdaTestServer::default()).await;
  }

  #[tokio::test]
  async fn cors_preflight_request() {
    cors_tests::test_cors_preflight_request(&LambdaTestServer::default()).await;
  }

  #[tokio::test]
  async fn get_https_tickets() {
    let base_path = TempDir::new().unwrap();
    server_tests::test_get::<JsonResponse, _>(&LambdaTestServer::new_with_tls(base_path.path()))
      .await;
  }

  #[tokio::test]
  async fn post_https_tickets() {
    let base_path = TempDir::new().unwrap();
    server_tests::test_post::<JsonResponse, _>(&LambdaTestServer::new_with_tls(base_path.path()))
      .await;
  }

  #[tokio::test]
  async fn parameterized_get_https_tickets() {
    let base_path = TempDir::new().unwrap();
    server_tests::test_parameterized_get::<JsonResponse, _>(&LambdaTestServer::new_with_tls(
      base_path.path(),
    ))
    .await;
  }

  #[tokio::test]
  async fn parameterized_post_https_tickets() {
    let base_path = TempDir::new().unwrap();
    server_tests::test_parameterized_post::<JsonResponse, _>(&LambdaTestServer::new_with_tls(
      base_path.path(),
    ))
    .await;
  }

  #[tokio::test]
  async fn parameterized_post_class_header_https_tickets() {
    let base_path = TempDir::new().unwrap();
    server_tests::test_parameterized_post_class_header::<JsonResponse, _>(
      &LambdaTestServer::new_with_tls(base_path.path()),
    )
    .await;
  }

  #[tokio::test]
  async fn service_info() {
    server_tests::test_service_info(&LambdaTestServer::default()).await;
  }

  #[tokio::test]
  async fn get_from_file_http_tickets() {
    let config = default_test_config();
    endpoint_from_file("events/event_get.json", Class::Body, &config).await;
  }

  #[tokio::test]
  async fn post_from_file_http_tickets() {
    let config = default_test_config();
    endpoint_from_file("events/event_post.json", Class::Body, &config).await;
  }

  #[tokio::test]
  async fn parameterized_get_from_file_http_tickets() {
    let config = default_test_config();
    endpoint_from_file(
      "events/event_parameterized_get.json",
      Class::Header,
      &config,
    )
    .await;
  }

  #[tokio::test]
  async fn parameterized_post_from_file_http_tickets() {
    let config = default_test_config();
    endpoint_from_file("events/event_parameterized_post.json", Class::Body, &config).await;
  }

  #[tokio::test]
  async fn parameterized_post_class_header_from_file_http_tickets() {
    let config = default_test_config();
    endpoint_from_file(
      "events/event_parameterized_post_class_header.json",
      Class::Header,
      &config,
    )
    .await;
  }

  #[tokio::test]
  async fn get_from_file_https_tickets() {
    let base_path = TempDir::new().unwrap();
    let config = config_with_tls(base_path.path());
    endpoint_from_file("events/event_get.json", Class::Body, &config).await;
  }

  #[tokio::test]
  async fn post_from_file_https_tickets() {
    let base_path = TempDir::new().unwrap();
    let config = config_with_tls(base_path.path());
    endpoint_from_file("events/event_post.json", Class::Body, &config).await;
  }

  #[tokio::test]
  async fn parameterized_get_from_file_https_tickets() {
    let base_path = TempDir::new().unwrap();
    let config = config_with_tls(base_path.path());
    endpoint_from_file(
      "events/event_parameterized_get.json",
      Class::Header,
      &config,
    )
    .await;
  }

  #[tokio::test]
  async fn parameterized_post_from_file_https_tickets() {
    let base_path = TempDir::new().unwrap();
    let config = config_with_tls(base_path.path());
    endpoint_from_file("events/event_parameterized_post.json", Class::Body, &config).await;
  }

  #[tokio::test]
  async fn parameterized_post_class_header_from_file_https_tickets() {
    let base_path = TempDir::new().unwrap();
    let config = config_with_tls(base_path.path());
    endpoint_from_file(
      "events/event_parameterized_post_class_header.json",
      Class::Header,
      &config,
    )
    .await;
  }

  #[tokio::test]
  async fn service_info_from_file() {
    let config = default_test_config();
    test_service_info_from_file("events/event_service_info.json", &config).await;
  }

  #[tokio::test]
  async fn get_route_invalid_method() {
    let config = default_test_config();
    with_router(
      |router| async move {
        let uri = Uri::builder().path_and_query("/reads/id").build().unwrap();
        assert!(router.get_route(&Method::DELETE, &uri).is_none());
      },
      &config,
    )
    .await;
  }

  #[tokio::test]
  async fn get_route_no_path() {
    let config = default_test_config();
    with_router(
      |router| async move {
        let uri = Uri::builder().path_and_query("").build().unwrap();
        assert!(router.get_route(&Method::GET, &uri).is_none());
      },
      &config,
    )
    .await;
  }

  #[tokio::test]
  async fn get_route_no_endpoint() {
    let config = default_test_config();
    with_router(
      |router| async move {
        let uri = Uri::builder().path_and_query("/path/").build().unwrap();
        assert!(router.get_route(&Method::GET, &uri).is_none());
      },
      &config,
    )
    .await;
  }

  #[tokio::test]
  async fn get_route_reads_no_id() {
    let config = default_test_config();
    with_router(
      |router| async move {
        let uri = Uri::builder().path_and_query("/reads/").build().unwrap();
        assert!(router.get_route(&Method::GET, &uri).is_none());
      },
      &config,
    )
    .await;
  }

  #[tokio::test]
  async fn get_route_variants_no_id() {
    let config = default_test_config();
    with_router(
      |router| async move {
        let uri = Uri::builder().path_and_query("/variants/").build().unwrap();
        assert!(router.get_route(&Method::GET, &uri).is_none());
      },
      &config,
    )
    .await;
  }

  #[tokio::test]
  async fn get_route_reads_service_info() {
    let config = default_test_config();
    with_router(
      |router| async move {
        let uri = Uri::builder()
          .path_and_query("/reads/service-info")
          .build()
          .unwrap();
        let route = router.get_route(&Method::GET, &uri);
        assert_eq!(
          route,
          Some(Route {
            method: HtsgetMethod::Get,
            endpoint: Endpoint::Reads,
            route_type: RouteType::ServiceInfo
          })
        );
      },
      &config,
    )
    .await;
  }

  #[tokio::test]
  async fn get_route_variants_service_info() {
    let config = default_test_config();
    with_router(
      |router| async move {
        let uri = Uri::builder()
          .path_and_query("/variants/service-info")
          .build()
          .unwrap();
        let route = router.get_route(&Method::GET, &uri);
        assert_eq!(
          route,
          Some(Route {
            method: HtsgetMethod::Get,
            endpoint: Endpoint::Variants,
            route_type: RouteType::ServiceInfo
          })
        );
      },
      &config,
    )
    .await;
  }

  #[tokio::test]
  async fn get_route_reads_id() {
    let config = default_test_config();
    with_router(
      |router| async move {
        let uri = Uri::builder().path_and_query("/reads/id").build().unwrap();
        let route = router.get_route(&Method::GET, &uri);
        assert_eq!(
          route,
          Some(Route {
            method: HtsgetMethod::Get,
            endpoint: Endpoint::Reads,
            route_type: RouteType::Id("id".to_string())
          })
        );
      },
      &config,
    )
    .await;
  }

  #[tokio::test]
  async fn get_route_variants_id() {
    let config = default_test_config();
    with_router(
      |router| async move {
        let uri = Uri::builder()
          .path_and_query("/variants/id")
          .build()
          .unwrap();
        let route = router.get_route(&Method::GET, &uri);
        assert_eq!(
          route,
          Some(Route {
            method: HtsgetMethod::Get,
            endpoint: Endpoint::Variants,
            route_type: RouteType::Id("id".to_string())
          })
        );
      },
      &config,
    )
    .await;
  }

  async fn with_router<'a, F, Fut>(test: F, config: &'a Config)
  where
    F: FnOnce(Router<'a, Vec<Resolver>>) -> Fut,
    Fut: Future<Output = ()>,
  {
    let router = Router::new(
      Arc::new(config.clone().owned_resolvers()),
      config.ticket_server().service_info(),
    );
    test(router).await;
  }

  fn get_request_from_file(file_path: &str) -> Request {
    let event = get_test_file(file_path);
    lambda_http::request::from_str(&event).expect("Failed to create lambda request.")
  }

  async fn spawn_server(config: &Config) -> String {
    let mut bind_data_server = BindDataServer::try_from(config.data_server().clone()).unwrap();
    let server = bind_data_server.bind_data_server().await.unwrap();
    let addr = server.local_addr();

    let path = config.data_server().local_path().to_path_buf();
    tokio::spawn(async move { server.serve(path).await.unwrap() });

    expected_url_path(config, addr)
  }

  async fn endpoint_from_file(file_path: &str, class: Class, config: &Config) {
    let expected_path = spawn_server(config).await;

    with_router(
      |router| async move {
        let response = route_request_to_response(
          get_request_from_file(file_path),
          router,
          expected_path,
          config,
        )
        .await;
        test_response::<JsonResponse>(response, class).await;
      },
      config,
    )
    .await;
  }

  async fn test_service_info_from_file(file_path: &str, config: &Config) {
    let expected_path = expected_url_path(config, config.data_server().addr());

    with_router(
      |router| async {
        let response = route_request_to_response(
          get_request_from_file(file_path),
          router,
          expected_path,
          config,
        )
        .await;
        test_response_service_info(&response);
      },
      config,
    )
    .await;
  }

  async fn route_request_to_response<T: HtsGet + Send + Sync + 'static>(
    request: Request,
    router: Router<'_, T>,
    expected_path: String,
    config: &Config,
  ) -> TestResponse {
    let response = ServiceBuilder::new()
      .layer(configure_cors(config.ticket_server().cors().clone()).unwrap())
      .service(service_fn(|event: Request| async {
        router.route_request(event).await
      }))
      .ready()
      .await
      .unwrap()
      .call(request)
      .await
      .expect("failed to route request");

    let status: u16 = response.status().into();
    let body = response.body().to_vec();

    TestResponse::new(status, response.headers().clone(), body, expected_path)
  }
}