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
use std::fmt::Debug;
use std::io;
use std::io::ErrorKind;
use std::net::SocketAddr;
use std::path::{Path, PathBuf};

use clap::Parser;
use figment::providers::{Env, Format, Serialized, Toml};
use figment::Figment;
use http::header::HeaderName;
use http::Method;
use serde::{Deserialize, Serialize};
use serde_with::with_prefix;
use tracing::info;
use tracing::instrument;
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::{fmt, EnvFilter, Registry};

use crate::config::cors::{AllowType, CorsConfig, HeaderValue, TaggedAllowTypes};
use crate::resolver::Resolver;
use crate::types::Scheme;
use crate::types::Scheme::{Http, Https};

pub mod cors;

/// Represents a usage string for htsget-rs.
pub const USAGE: &str =
  "htsget-rs can be configured using a config file or environment variables. \
See the documentation of the htsget-config crate for more information.";

const ENVIRONMENT_VARIABLE_PREFIX: &str = "HTSGET_";

pub(crate) fn default_localstorage_addr() -> &'static str {
  "127.0.0.1:8081"
}

fn default_addr() -> &'static str {
  "127.0.0.1:8080"
}

fn default_server_origin() -> &'static str {
  "http://localhost:8080"
}

pub(crate) fn default_path() -> &'static str {
  "data"
}

pub(crate) fn default_serve_at() -> &'static str {
  "/data"
}

/// The command line arguments allowed for the htsget-rs executables.
#[derive(Parser, Debug)]
#[command(author, version, about, long_about = USAGE)]
struct Args {
  #[arg(
    short,
    long,
    env = "HTSGET_CONFIG",
    help = "Set the location of the config file"
  )]
  config: Option<PathBuf>,
  #[arg(short, long, exclusive = true, help = "Print a default config file")]
  print_default_config: bool,
}

with_prefix!(data_server_prefix "data_server_");

/// Configuration for the htsget server.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(default)]
pub struct Config {
  #[serde(flatten)]
  ticket_server: TicketServerConfig,
  #[serde(flatten, with = "data_server_prefix")]
  data_server: DataServerConfig,
  resolvers: Vec<Resolver>,
}

with_prefix!(ticket_server_cors_prefix "ticket_server_cors_");

/// Configuration for the htsget ticket server.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(default)]
pub struct TicketServerConfig {
  ticket_server_addr: SocketAddr,
  #[serde(flatten, with = "ticket_server_cors_prefix")]
  cors: CorsConfig,
  #[serde(flatten)]
  service_info: ServiceInfo,
}

impl TicketServerConfig {
  /// Create a new ticket server config.
  pub fn new(ticket_server_addr: SocketAddr, cors: CorsConfig, service_info: ServiceInfo) -> Self {
    Self {
      ticket_server_addr,
      cors,
      service_info,
    }
  }

  /// Get the addr.
  pub fn addr(&self) -> SocketAddr {
    self.ticket_server_addr
  }

  /// Get cors config.
  pub fn cors(&self) -> &CorsConfig {
    &self.cors
  }

  /// Get service info.
  pub fn service_info(&self) -> &ServiceInfo {
    &self.service_info
  }

  /// Get allow credentials.
  pub fn allow_credentials(&self) -> bool {
    self.cors.allow_credentials()
  }

  /// Get allow origins.
  pub fn allow_origins(&self) -> &AllowType<HeaderValue, TaggedAllowTypes> {
    self.cors.allow_origins()
  }

  /// Get allow headers.
  pub fn allow_headers(&self) -> &AllowType<HeaderName> {
    self.cors.allow_headers()
  }

  /// Get allow methods.
  pub fn allow_methods(&self) -> &AllowType<Method> {
    self.cors.allow_methods()
  }

  /// Get max age.
  pub fn max_age(&self) -> usize {
    self.cors.max_age()
  }

  /// Get expose headers.
  pub fn expose_headers(&self) -> &AllowType<HeaderName> {
    self.cors.expose_headers()
  }

  /// Get id.
  pub fn id(&self) -> Option<&str> {
    self.service_info.id()
  }

  /// Get name.
  pub fn name(&self) -> Option<&str> {
    self.service_info.name()
  }

  /// Get version.
  pub fn version(&self) -> Option<&str> {
    self.service_info.version()
  }

  /// Get organization name.
  pub fn organization_name(&self) -> Option<&str> {
    self.service_info.organization_name()
  }

  /// Get the organization url.
  pub fn organization_url(&self) -> Option<&str> {
    self.service_info.organization_url()
  }

  /// Get the contact url.
  pub fn contact_url(&self) -> Option<&str> {
    self.service_info.contact_url()
  }

  /// Get the documentation url.
  pub fn documentation_url(&self) -> Option<&str> {
    self.service_info.documentation_url()
  }

  /// Get created at.
  pub fn created_at(&self) -> Option<&str> {
    self.service_info.created_at()
  }

  /// Get updated at.
  pub fn updated_at(&self) -> Option<&str> {
    self.service_info.updated_at()
  }

  /// Get the environment.
  pub fn environment(&self) -> Option<&str> {
    self.service_info.environment()
  }
}

/// A trait to determine which scheme a key pair option has.
pub trait KeyPairScheme {
  /// Get the scheme.
  fn get_scheme(&self) -> Scheme;
}

/// A certificate and key pair used for TLS.
/// This is the path to the PEM formatted X.509 certificate and private key.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct CertificateKeyPair {
  cert: PathBuf,
  key: PathBuf,
}

impl CertificateKeyPair {
  /// Create a new certificate key pair.
  pub fn new(cert: PathBuf, key: PathBuf) -> Self {
    Self { cert, key }
  }

  /// Get the cert.
  pub fn cert(&self) -> &Path {
    &self.cert
  }

  /// Get the key.
  pub fn key(&self) -> &Path {
    &self.key
  }
}

impl KeyPairScheme for Option<&CertificateKeyPair> {
  fn get_scheme(&self) -> Scheme {
    match self {
      None => Http,
      Some(_) => Https,
    }
  }
}

with_prefix!(cors_prefix "cors_");

/// Configuration for the htsget server.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(default)]
pub struct DataServerConfig {
  enabled: bool,
  addr: SocketAddr,
  local_path: PathBuf,
  serve_at: String,
  #[serde(flatten)]
  tls: Option<CertificateKeyPair>,
  #[serde(flatten, with = "cors_prefix")]
  cors: CorsConfig,
}

impl DataServerConfig {
  /// Create a new data server config.
  pub fn new(
    enabled: bool,
    addr: SocketAddr,
    local_path: PathBuf,
    serve_at: String,
    tls: Option<CertificateKeyPair>,
    cors: CorsConfig,
  ) -> Self {
    Self {
      enabled,
      addr,
      local_path,
      serve_at,
      tls,
      cors,
    }
  }

  /// Get the address.
  pub fn addr(&self) -> SocketAddr {
    self.addr
  }

  /// Get the local path.
  pub fn local_path(&self) -> &Path {
    &self.local_path
  }

  /// Get the serve at path.
  pub fn serve_at(&self) -> &str {
    &self.serve_at
  }

  /// Get the TLS config
  pub fn tls(&self) -> Option<&CertificateKeyPair> {
    self.tls.as_ref()
  }

  /// Get the TLS config
  pub fn into_tls(self) -> Option<CertificateKeyPair> {
    self.tls
  }

  /// Get cors config.
  pub fn cors(&self) -> &CorsConfig {
    &self.cors
  }

  /// Get allow credentials.
  pub fn allow_credentials(&self) -> bool {
    self.cors.allow_credentials()
  }

  /// Get allow origins.
  pub fn allow_origins(&self) -> &AllowType<HeaderValue, TaggedAllowTypes> {
    self.cors.allow_origins()
  }

  /// Get allow headers.
  pub fn allow_headers(&self) -> &AllowType<HeaderName> {
    self.cors.allow_headers()
  }

  /// Get allow methods.
  pub fn allow_methods(&self) -> &AllowType<Method> {
    self.cors.allow_methods()
  }

  /// Get the max age.
  pub fn max_age(&self) -> usize {
    self.cors.max_age()
  }

  /// Get the expose headers.
  pub fn expose_headers(&self) -> &AllowType<HeaderName> {
    self.cors.expose_headers()
  }

  /// Is the data server disabled
  pub fn enabled(&self) -> bool {
    self.enabled
  }
}

impl Default for DataServerConfig {
  fn default() -> Self {
    Self {
      enabled: true,
      addr: default_localstorage_addr()
        .parse()
        .expect("expected valid address"),
      local_path: default_path().into(),
      serve_at: default_serve_at().into(),
      tls: None,
      cors: CorsConfig::default(),
    }
  }
}

/// Configuration of the service info.
#[derive(Serialize, Deserialize, Debug, Clone, Default)]
#[serde(default)]
pub struct ServiceInfo {
  id: Option<String>,
  name: Option<String>,
  version: Option<String>,
  organization_name: Option<String>,
  organization_url: Option<String>,
  contact_url: Option<String>,
  documentation_url: Option<String>,
  created_at: Option<String>,
  updated_at: Option<String>,
  environment: Option<String>,
}

impl ServiceInfo {
  /// Get the id.
  pub fn id(&self) -> Option<&str> {
    self.id.as_deref()
  }

  /// Get the name.
  pub fn name(&self) -> Option<&str> {
    self.name.as_deref()
  }

  /// Get the version.
  pub fn version(&self) -> Option<&str> {
    self.version.as_deref()
  }

  /// Get the organization name.
  pub fn organization_name(&self) -> Option<&str> {
    self.organization_name.as_deref()
  }

  /// Get the organization url.
  pub fn organization_url(&self) -> Option<&str> {
    self.organization_url.as_deref()
  }

  /// Get the contact url.
  pub fn contact_url(&self) -> Option<&str> {
    self.contact_url.as_deref()
  }

  /// Get the documentation url.
  pub fn documentation_url(&self) -> Option<&str> {
    self.documentation_url.as_deref()
  }

  /// Get created at.
  pub fn created_at(&self) -> Option<&str> {
    self.created_at.as_deref()
  }

  /// Get updated at.
  pub fn updated_at(&self) -> Option<&str> {
    self.updated_at.as_deref()
  }

  /// Get environment.
  pub fn environment(&self) -> Option<&str> {
    self.environment.as_deref()
  }
}

impl Default for TicketServerConfig {
  fn default() -> Self {
    Self {
      ticket_server_addr: default_addr().parse().expect("expected valid address"),
      cors: CorsConfig::default(),
      service_info: ServiceInfo::default(),
    }
  }
}

impl Default for Config {
  fn default() -> Self {
    Self {
      ticket_server: TicketServerConfig::default(),
      data_server: DataServerConfig::default(),
      resolvers: vec![Resolver::default()],
    }
  }
}

impl Config {
  /// Create a new config.
  pub fn new(
    ticket_server: TicketServerConfig,
    data_server: DataServerConfig,
    resolvers: Vec<Resolver>,
  ) -> Self {
    Self {
      ticket_server,
      data_server,
      resolvers,
    }
  }

  /// Parse the command line arguments
  pub fn parse_args() -> Option<PathBuf> {
    let args = Args::parse();

    if args.print_default_config {
      println!(
        "{}",
        toml::ser::to_string_pretty(&Config::default()).unwrap()
      );
      None
    } else {
      Some(args.config.unwrap_or_else(|| "".into()))
    }
  }

  /// Read a config struct from a TOML file.
  #[instrument]
  pub fn from_path(path: &Path) -> io::Result<Self> {
    let config: Config = Figment::from(Serialized::defaults(Config::default()))
      .merge(Toml::file(path))
      .merge(Env::prefixed(ENVIRONMENT_VARIABLE_PREFIX))
      .extract()
      .map_err(|err| io::Error::new(ErrorKind::Other, format!("failed to parse config: {err}")))?;

    info!(config = ?config, "config created from environment variables");

    Ok(config.resolvers_from_data_server_config())
  }

  /// Setup tracing, using a global subscriber.
  pub fn setup_tracing() -> io::Result<()> {
    let env_filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info"));
    let fmt_layer = fmt::Layer::default();

    let subscriber = Registry::default().with(env_filter).with(fmt_layer);

    tracing::subscriber::set_global_default(subscriber).map_err(|err| {
      io::Error::new(
        ErrorKind::Other,
        format!("failed to install `tracing` subscriber: {err}"),
      )
    })?;

    Ok(())
  }

  /// Get the ticket server.
  pub fn ticket_server(&self) -> &TicketServerConfig {
    &self.ticket_server
  }

  /// Get the data server.
  pub fn data_server(&self) -> &DataServerConfig {
    &self.data_server
  }

  /// Get the owned data server.
  pub fn into_data_server(self) -> DataServerConfig {
    self.data_server
  }

  /// Get the resolvers.
  pub fn resolvers(&self) -> &[Resolver] {
    &self.resolvers
  }

  /// Get owned resolvers.
  pub fn owned_resolvers(self) -> Vec<Resolver> {
    self.resolvers
  }

  /// Set the local resolvers from the data server config.
  pub fn resolvers_from_data_server_config(self) -> Self {
    let Config {
      ticket_server,
      data_server,
      mut resolvers,
    } = self;
    resolvers
      .iter_mut()
      .for_each(|resolver| resolver.resolvers_from_data_server_config(&data_server));

    Self::new(ticket_server, data_server, resolvers)
  }
}

#[cfg(test)]
pub(crate) mod tests {
  use std::fmt::Display;

  use figment::Jail;
  use http::uri::Authority;

  use crate::storage::Storage;

  use super::*;

  fn test_config<K, V, F>(contents: Option<&str>, env_variables: Vec<(K, V)>, test_fn: F)
  where
    K: AsRef<str>,
    V: Display,
    F: FnOnce(Config),
  {
    Jail::expect_with(|jail| {
      if let Some(contents) = contents {
        jail.create_file("test.toml", contents)?;
      }

      for (key, value) in env_variables {
        jail.set_env(key, value);
      }

      test_fn(Config::from_path(Path::new("test.toml")).map_err(|err| err.to_string())?);

      Ok(())
    });
  }

  pub(crate) fn test_config_from_env<K, V, F>(env_variables: Vec<(K, V)>, test_fn: F)
  where
    K: AsRef<str>,
    V: Display,
    F: FnOnce(Config),
  {
    test_config(None, env_variables, test_fn);
  }

  pub(crate) fn test_config_from_file<F>(contents: &str, test_fn: F)
  where
    F: FnOnce(Config),
  {
    test_config(Some(contents), Vec::<(&str, &str)>::new(), test_fn);
  }

  #[test]
  fn config_ticket_server_addr_env() {
    test_config_from_env(
      vec![("HTSGET_TICKET_SERVER_ADDR", "127.0.0.1:8082")],
      |config| {
        assert_eq!(
          config.ticket_server().addr(),
          "127.0.0.1:8082".parse().unwrap()
        );
      },
    );
  }

  #[test]
  fn config_ticket_server_cors_allow_origin_env() {
    test_config_from_env(
      vec![("HTSGET_TICKET_SERVER_CORS_ALLOW_CREDENTIALS", true)],
      |config| {
        assert!(config.ticket_server().allow_credentials());
      },
    );
  }

  #[test]
  fn config_service_info_id_env() {
    test_config_from_env(vec![("HTSGET_ID", "id")], |config| {
      assert_eq!(config.ticket_server().id(), Some("id"));
    });
  }

  #[test]
  fn config_data_server_addr_env() {
    test_config_from_env(
      vec![("HTSGET_DATA_SERVER_ADDR", "127.0.0.1:8082")],
      |config| {
        assert_eq!(
          config.data_server().addr(),
          "127.0.0.1:8082".parse().unwrap()
        );
      },
    );
  }

  #[test]
  fn config_no_data_server_env() {
    test_config_from_env(vec![("HTSGET_DATA_SERVER_ENABLED", "true")], |config| {
      assert!(config.data_server().enabled());
    });
  }

  #[test]
  fn config_ticket_server_addr_file() {
    test_config_from_file(r#"ticket_server_addr = "127.0.0.1:8082""#, |config| {
      assert_eq!(
        config.ticket_server().addr(),
        "127.0.0.1:8082".parse().unwrap()
      );
    });
  }

  #[test]
  fn config_ticket_server_cors_allow_origin_file() {
    test_config_from_file(r#"ticket_server_cors_allow_credentials = true"#, |config| {
      assert!(config.ticket_server().allow_credentials());
    });
  }

  #[test]
  fn config_service_info_id_file() {
    test_config_from_file(r#"id = "id""#, |config| {
      assert_eq!(config.ticket_server().id(), Some("id"));
    });
  }

  #[test]
  fn config_data_server_addr_file() {
    test_config_from_file(r#"data_server_addr = "127.0.0.1:8082""#, |config| {
      assert_eq!(
        config.data_server().addr(),
        "127.0.0.1:8082".parse().unwrap()
      );
    });
  }

  #[test]
  fn config_no_data_server_file() {
    test_config_from_file(r#"data_server_enabled = true"#, |config| {
      assert!(config.data_server().enabled());
    });
  }

  #[test]
  fn resolvers_from_data_server_config() {
    test_config_from_file(
      r#"
    data_server_addr = "127.0.0.1:8080"
    data_server_local_path = "path"
    data_server_serve_at = "/path"

    [[resolvers]]
    storage = "Local"
    "#,
      |config| {
        assert_eq!(config.resolvers.len(), 1);

        assert!(matches!(config.resolvers.first().unwrap().storage(),
      Storage::Local { local_storage } if local_storage.local_path() == "path" && local_storage.scheme() == Http && local_storage.authority() == &Authority::from_static("127.0.0.1:8080") && local_storage.path_prefix() == "/path"));
      },
    );
  }
}