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
/// A library to process Server.toml files

#[macro_use] mod error;
mod core;
mod actix;

use actix_http::{KeepAlive as ActixKeepAlive, Request, Response};
use actix_service::{IntoServiceFactory, ServiceFactory};
use actix_web::{Error as WebError, HttpServer};
use actix_web::dev::{AppConfig, MessageBody, Service};
pub use crate::core::Parse;
pub use crate::actix::*;
pub use crate::error::{AtError, AtResult};
use serde_derive::Deserialize;
use std::env::{self, VarError};
use std::io::{Read, Write};
use std::fmt::Debug;
use std::fs::File;
use std::path::Path;

#[derive(Debug, Clone, Deserialize, PartialEq, Eq, Hash)]
#[serde(bound = "A: serde::de::Deserialize<'de>")]
pub struct BasicSettings<A> {
    pub actix: ActixSettings,
    pub application: A,
}

pub type Settings = BasicSettings::<NoSettings>;

#[derive(Debug, Clone, Deserialize, PartialEq, Eq, Hash)]
pub struct NoSettings {/* NOTE: **DO NOT** turn this into a unit struct */}


impl<A> BasicSettings<A>
where A: for<'de> serde::de::Deserialize<'de> {

    /// NOTE **DO NOT** mess with the ordering of the tables in this template.
    ///      Especially the `[application]` table needs to be last in order
    ///      for some tests to keep working.
    pub(crate) const DEFAULT_TOML_TEMPLATE: &'static str = r#"
[actix]
# For more info, see: https://docs.rs/actix-web/3.1.0/actix_web/struct.HttpServer.html.

hosts = [
    ["0.0.0.0", 9000]      # This should work for both development and deployment...
    #                      # ... but other entries are possible, as well.
]
mode = "development"       # Either "development" or "production".
enable-compression = true  # Toggle compression middleware.
enable-log = true          # Toggle logging middleware.

# The number of workers that the server should start.
# By default the number of available logical cpu cores is used.
# Takes a string value: Either "default", or an integer N > 0 e.g. "6".
num-workers = "default"

# The maximum number of pending connections.  This refers to the number of clients
# that can be waiting to be served.  Exceeding this number results in the client
# getting an error when attempting to connect.  It should only affect servers under
# significant load.  Generally set in the 64-2048 range.  The default value is 2048.
# Takes a string value: Either "default", or an integer N > 0 e.g. "6".
backlog = "default"

# Sets the maximum per-worker number of concurrent connections.  All socket listeners
# will stop accepting connections when this limit is reached for each worker.
# By default max connections is set to a 25k.
# Takes a string value: Either "default", or an integer N > 0 e.g. "6".
max-connections = "default"

# Sets the maximum per-worker concurrent connection establish process.  All listeners
# will stop accepting connections when this limit is reached. It can be used to limit
# the global TLS CPU usage.  By default max connections is set to a 256.
# Takes a string value: Either "default", or an integer N > 0 e.g. "6".
max-connection-rate = "default"

# Set server keep-alive setting.  By default keep alive is set to 5 seconds.
# Takes a string value: Either "default", "disabled", "os",
# or a string of the format "N seconds" where N is an integer > 0 e.g. "6 seconds".
keep-alive = "default"

# Set server client timeout in milliseconds for first request.  Defines a timeout
# for reading client request header. If a client does not transmit the entire set of
# headers within this time, the request is terminated with the 408 (Request Time-out)
# error.  To disable timeout, set the value to 0.
# By default client timeout is set to 5000 milliseconds.
# Takes a string value: Either "default", or a string of the format "N milliseconds"
# where N is an integer > 0 e.g. "6 milliseconds".
client-timeout = "default"

# Set server connection shutdown timeout in milliseconds.  Defines a timeout for
# shutdown connection. If a shutdown procedure does not complete within this time,
# the request is dropped.  To disable timeout set value to 0.
# By default client timeout is set to 5000 milliseconds.
# Takes a string value: Either "default", or a string of the format "N milliseconds"
# where N is an integer > 0 e.g. "6 milliseconds".
client-shutdown = "default"

# Timeout for graceful workers shutdown. After receiving a stop signal, workers have
# this much time to finish serving requests. Workers still alive after the timeout
# are force dropped.  By default shutdown timeout sets to 30 seconds.
# Takes a string value: Either "default", or a string of the format "N seconds"
# where N is an integer > 0 e.g. "6 seconds".
shutdown-timeout = "default"

[actix.ssl] # SSL is disabled by default because the certs don't exist
enabled = false
certificate = "path/to/cert/cert.pem"
private-key = "path/to/cert/key.pem"

# The `application` table be used to express application-specific settings.
# See the `README.md` file for more details on how to use this.
[application]
"#;

    /// Parse an instance of `Self` from a `TOML` file located at `filepath`.
    /// If the file doesn't exist, it is generated from the default `TOML`
    /// template, after which the newly generated file is read in and parsed.
    pub fn parse_toml<P>(filepath: P) -> AtResult<Self>
    where P: AsRef<Path> {
        let filepath = filepath.as_ref();
        if !filepath.exists() { Self::write_toml_file(filepath)?; }
        let mut f = File::open(filepath)?;
        let mut contents = String::with_capacity(f.metadata()?.len() as usize);
        f.read_to_string(&mut contents)?;
        Ok(toml::from_str::<Self>(&contents)?)
    }

    /// Parse an instance of `Self` straight from the default `TOML` template.
    pub fn from_default_template() -> AtResult<Self> {
        Self::from_template(Self::DEFAULT_TOML_TEMPLATE)
    }

    /// Parse an instance of `Self` straight from the default `TOML` template.
    pub fn from_template(template: &str) -> AtResult<Self> {
        Ok(toml::from_str::<Self>(template)?)
    }

    /// Write the default `TOML` template to a new file, to be located
    /// at `filepath`.  Return a `Error::FileExists(_)` error if a
    /// file already exists at that location.
    pub fn write_toml_file<P>(filepath: P) -> AtResult<()>
    where P: AsRef<Path> {
        let filepath = filepath.as_ref();
        let contents = Self::DEFAULT_TOML_TEMPLATE.trim();
        if filepath.exists() {
            return Err(AtError::FileExists(filepath.to_path_buf()));
        }
        let mut file = File::create(filepath)?;
        file.write_all(contents.as_bytes())?;
        file.flush()?;
        Ok(())
    }

    pub fn override_field<F, V>(
        field: &mut F,
        value: V
    ) -> AtResult<()>
    where F: Parse,
          V: AsRef<str> {
        *field = F::parse(value.as_ref())?;
        Ok(())
    }

    pub fn override_field_with_env_var<F, N>(
        field: &mut F,
        var_name: N,
    ) -> AtResult<()>
    where F: Parse,
          N: AsRef<str> {
        match env::var(var_name.as_ref()) {
            Err(VarError::NotPresent) => Ok((/*NOP*/)),
            Err(var_error) => Err(AtError::from(var_error)),
            Ok(value) => Self::override_field(field, value),
        }
    }
}



pub trait ApplySettings {
    #[must_use]
    /// Apply a [`BasicSettings`] value to `self`.
    ///
    /// [`BasicSettings`]: ./struct.BasicSettings.html
    fn apply_settings<A>(self, settings: &BasicSettings<A>) -> Self
    where A: for<'de> serde::de::Deserialize<'de>;
}

impl<F, I, S, B> ApplySettings for HttpServer<F, I, S, B>
where
    F: Fn() -> I + Send + Clone + 'static,
    I: IntoServiceFactory<S>,
    S: ServiceFactory<Config = AppConfig, Request = Request>,
    S::Error: Into<WebError> + 'static,
    S::InitError: Debug,
    S::Response: Into<Response<B>> + 'static,
    <S::Service as Service>::Future: 'static,
    B: MessageBody + 'static
{
    fn apply_settings<A>(mut self, settings: &BasicSettings<A>) -> Self
    where A: for<'de> serde::de::Deserialize<'de> {
        if settings.actix.ssl.enabled {
            // for Address { host, port } in &settings.actix.hosts {
            //     self = self.bind(format!("{}:{}", host, port))
            //         .unwrap(/*TODO*/);
            // }
            todo!("[ApplySettings] SSL support has not been implemented yet.");
        } else {
            for Address { host, port } in &settings.actix.hosts {
                self = self.bind(format!("{}:{}", host, port))
                    .unwrap(/*TODO*/);
            }
        }
        self = match settings.actix.num_workers {
            NumWorkers::Default   => self,
            NumWorkers::Manual(n) => self.workers(n),
        };
        self = match settings.actix.backlog {
            Backlog::Default   => self,
            Backlog::Manual(n) => self.backlog(n as i32),
        };
        self = match settings.actix.max_connections {
            MaxConnections::Default   => self,
            MaxConnections::Manual(n) => self.max_connections(n),
        };
        self = match settings.actix.max_connection_rate {
            MaxConnectionRate::Default   => self,
            MaxConnectionRate::Manual(n) => self.max_connection_rate(n),
        };
        self = match settings.actix.keep_alive {
            KeepAlive::Default    => self,
            KeepAlive::Disabled   => self.keep_alive(ActixKeepAlive::Disabled),
            KeepAlive::Os         => self.keep_alive(ActixKeepAlive::Os),
            KeepAlive::Seconds(n) => self.keep_alive(n),
        };
        self = match settings.actix.client_timeout {
            Timeout::Default         => self,
            Timeout::Milliseconds(n) => self.client_timeout(n as u64),
            Timeout::Seconds(n)      => self.client_timeout(n as u64 * 1000),
        };
        self = match settings.actix.client_shutdown {
            Timeout::Default         => self,
            Timeout::Milliseconds(n) => self.client_shutdown(n as u64),
            Timeout::Seconds(n)      => self.client_shutdown(n as u64 * 1000),
        };
        self = match settings.actix.shutdown_timeout {
            Timeout::Default         => self,
            Timeout::Milliseconds(_) => self.shutdown_timeout(1),
            Timeout::Seconds(n)      => self.shutdown_timeout(n as u64),
        };
        self
    }
}



#[cfg(test)]
mod tests {
    #![allow(non_snake_case)]

    use actix_web::{App, HttpServer};
    use crate::{ApplySettings, AtResult, BasicSettings, Settings};
    use crate::actix::*; // used for value construction in assertions
    use serde::Deserialize;
    use std::path::Path;

    #[test]
    fn apply_settings() -> AtResult<()> {
        let settings = Settings::parse_toml("Server.toml")?;
        let _ = HttpServer::new(|| { App::new() })
            .apply_settings(&settings);
        Ok(())
    }

    #[test]
    fn override_field__hosts() -> AtResult<()> {
        let mut settings = Settings::from_default_template()?;
        assert_eq!(settings.actix.hosts, vec![
            Address { host: "0.0.0.0".into(),   port: 9000 },
        ]);
        Settings::override_field(&mut settings.actix.hosts, r#"[
            ["0.0.0.0",   1234],
            ["localhost", 2345]
        ]"#)?;
        assert_eq!(settings.actix.hosts, vec![
            Address { host: "0.0.0.0".into(),   port: 1234 },
            Address { host: "localhost".into(), port: 2345 },
        ]);
        Ok(())
    }

    #[test]
    fn override_field_with_env_var__hosts() -> AtResult<()> {
        let mut settings = Settings::from_default_template()?;
        assert_eq!(settings.actix.hosts, vec![
            Address { host: "0.0.0.0".into(),   port: 9000 },
        ]);
        std::env::set_var("OVERRIDE__HOSTS", r#"[
            ["0.0.0.0",   1234],
            ["localhost", 2345]
        ]"#);
        Settings::override_field_with_env_var(
            &mut settings.actix.hosts, "OVERRIDE__HOSTS"
        )?;
        assert_eq!(settings.actix.hosts, vec![
            Address { host: "0.0.0.0".into(),   port: 1234 },
            Address { host: "localhost".into(), port: 2345 },
        ]);
        Ok(())
    }

    #[test]
    fn override_field__mode() -> AtResult<()> {
        let mut settings = Settings::from_default_template()?;
        assert_eq!(settings.actix.mode, Mode::Development);
        Settings::override_field(&mut settings.actix.mode, "production")?;
        assert_eq!(settings.actix.mode, Mode::Production);
        Ok(())
    }

    #[test]
    fn override_field_with_env_var__mode() -> AtResult<()> {
        let mut settings = Settings::from_default_template()?;
        assert_eq!(settings.actix.mode, Mode::Development);
        std::env::set_var("OVERRIDE__MODE", "production");
        Settings::override_field_with_env_var(
            &mut settings.actix.mode, "OVERRIDE__MODE"
        )?;
        assert_eq!(settings.actix.mode, Mode::Production);
        Ok(())
    }

    #[test]
    fn override_field__enable_compression() -> AtResult<()> {
        let mut settings = Settings::from_default_template()?;
        assert!(settings.actix.enable_compression);
        Settings::override_field(&mut settings.actix.enable_compression, "false")?;
        assert!(!settings.actix.enable_compression);
        Ok(())
    }

    #[test]
    fn override_field_with_env_var__enable_compression() -> AtResult<()> {
        let mut settings = Settings::from_default_template()?;
        assert!(settings.actix.enable_compression);
        std::env::set_var("OVERRIDE__ENABLE_COMPRESSION", "false");
        Settings::override_field_with_env_var(
            &mut settings.actix.enable_compression, "OVERRIDE__ENABLE_COMPRESSION"
        )?;
        assert!(!settings.actix.enable_compression);
        Ok(())
    }

    #[test]
    fn override_field__enable_log() -> AtResult<()> {
        let mut settings = Settings::from_default_template()?;
        assert!(settings.actix.enable_log);
        Settings::override_field(&mut settings.actix.enable_log, "false")?;
        assert!(!settings.actix.enable_log);
        Ok(())
    }

    #[test]
    fn override_field_with_env_var__enable_log() -> AtResult<()> {
        let mut settings = Settings::from_default_template()?;
        assert!(settings.actix.enable_log);
        std::env::set_var("OVERRIDE__ENABLE_LOG", "false");
        Settings::override_field_with_env_var(
            &mut settings.actix.enable_log, "OVERRIDE__ENABLE_LOG"
        )?;
        assert!(!settings.actix.enable_log);
        Ok(())
    }

    #[test]
    fn override_field__num_workers() -> AtResult<()> {
        let mut settings = Settings::from_default_template()?;
        assert_eq!(settings.actix.num_workers, NumWorkers::Default);
        Settings::override_field(&mut settings.actix.num_workers, "42")?;
        assert_eq!(settings.actix.num_workers, NumWorkers::Manual(42));
        Ok(())
    }

    #[test]
    fn override_field_with_env_var__num_workers() -> AtResult<()> {
        let mut settings = Settings::from_default_template()?;
        assert_eq!(settings.actix.num_workers, NumWorkers::Default);
        std::env::set_var("OVERRIDE__NUM_WORKERS", "42");
        Settings::override_field_with_env_var(
            &mut settings.actix.num_workers, "OVERRIDE__NUM_WORKERS"
        )?;
        assert_eq!(settings.actix.num_workers, NumWorkers::Manual(42));
        Ok(())
    }

    #[test]
    fn override_field__backlog() -> AtResult<()> {
        let mut settings = Settings::from_default_template()?;
        assert_eq!(settings.actix.backlog, Backlog::Default);
        Settings::override_field(&mut settings.actix.backlog, "42")?;
        assert_eq!(settings.actix.backlog, Backlog::Manual(42));
        Ok(())
    }

    #[test]
    fn override_field_with_env_var__backlog() -> AtResult<()> {
        let mut settings = Settings::from_default_template()?;
        assert_eq!(settings.actix.backlog, Backlog::Default);
        std::env::set_var("OVERRIDE__BACKLOG", "42");
        Settings::override_field_with_env_var(
            &mut settings.actix.backlog, "OVERRIDE__BACKLOG"
        )?;
        assert_eq!(settings.actix.backlog, Backlog::Manual(42));
        Ok(())
    }

    #[test]
    fn override_field__max_connections() -> AtResult<()> {
        let mut settings = Settings::from_default_template()?;
        assert_eq!(settings.actix.max_connections, MaxConnections::Default);
        Settings::override_field(&mut settings.actix.max_connections, "42")?;
        assert_eq!(settings.actix.max_connections, MaxConnections::Manual(42));
        Ok(())
    }

    #[test]
    fn override_field_with_env_var__max_connections() -> AtResult<()> {
        let mut settings = Settings::from_default_template()?;
        assert_eq!(settings.actix.max_connections, MaxConnections::Default);
        std::env::set_var("OVERRIDE__MAX_CONNECTIONS", "42");
        Settings::override_field_with_env_var(
            &mut settings.actix.max_connections, "OVERRIDE__MAX_CONNECTIONS"
        )?;
        assert_eq!(settings.actix.max_connections, MaxConnections::Manual(42));
        Ok(())
    }

    #[test]
    fn override_field__max_connection_rate() -> AtResult<()> {
        let mut settings = Settings::from_default_template()?;
        assert_eq!(settings.actix.max_connection_rate, MaxConnectionRate::Default);
        Settings::override_field(&mut settings.actix.max_connection_rate, "42")?;
        assert_eq!(settings.actix.max_connection_rate, MaxConnectionRate::Manual(42));
        Ok(())
    }

    #[test]
    fn override_field_with_env_var__max_connection_rate() -> AtResult<()> {
        let mut settings = Settings::from_default_template()?;
        assert_eq!(settings.actix.max_connection_rate, MaxConnectionRate::Default);
        std::env::set_var("OVERRIDE__MAX_CONNECTION_RATE", "42");
        Settings::override_field_with_env_var(
            &mut settings.actix.max_connection_rate, "OVERRIDE__MAX_CONNECTION_RATE"
        )?;
        assert_eq!(settings.actix.max_connection_rate, MaxConnectionRate::Manual(42));
        Ok(())
    }

    #[test]
    fn override_field__keep_alive() -> AtResult<()> {
        let mut settings = Settings::from_default_template()?;
        assert_eq!(settings.actix.keep_alive, KeepAlive::Default);
        Settings::override_field(&mut settings.actix.keep_alive, "42 seconds")?;
        assert_eq!(settings.actix.keep_alive, KeepAlive::Seconds(42));
        Ok(())
    }

    #[test]
    fn override_field_with_env_var__keep_alive() -> AtResult<()> {
        let mut settings = Settings::from_default_template()?;
        assert_eq!(settings.actix.keep_alive, KeepAlive::Default);
        std::env::set_var("OVERRIDE__KEEP_ALIVE", "42 seconds");
        Settings::override_field_with_env_var(
            &mut settings.actix.keep_alive, "OVERRIDE__KEEP_ALIVE"
        )?;
        assert_eq!(settings.actix.keep_alive, KeepAlive::Seconds(42));
        Ok(())
    }

    #[test]
    fn override_field__client_timeout() -> AtResult<()> {
        let mut settings = Settings::from_default_template()?;
        assert_eq!(settings.actix.client_timeout, Timeout::Default);
        Settings::override_field(&mut settings.actix.client_timeout, "42 seconds")?;
        assert_eq!(settings.actix.client_timeout, Timeout::Seconds(42));
        Ok(())
    }

    #[test]
    fn override_field_with_env_var__client_timeout() -> AtResult<()> {
        let mut settings = Settings::from_default_template()?;
        assert_eq!(settings.actix.client_timeout, Timeout::Default);
        std::env::set_var("OVERRIDE__CLIENT_TIMEOUT", "42 seconds");
        Settings::override_field_with_env_var(
            &mut settings.actix.client_timeout, "OVERRIDE__CLIENT_TIMEOUT"
        )?;
        assert_eq!(settings.actix.client_timeout, Timeout::Seconds(42));
        Ok(())
    }

    #[test]
    fn override_field__client_shutdown() -> AtResult<()> {
        let mut settings = Settings::from_default_template()?;
        assert_eq!(settings.actix.client_shutdown, Timeout::Default);
        Settings::override_field(&mut settings.actix.client_shutdown, "42 seconds")?;
        assert_eq!(settings.actix.client_shutdown, Timeout::Seconds(42));
        Ok(())
    }

    #[test]
    fn override_field_with_env_var__client_shutdown() -> AtResult<()> {
        let mut settings = Settings::from_default_template()?;
        assert_eq!(settings.actix.client_shutdown, Timeout::Default);
        std::env::set_var("OVERRIDE__CLIENT_SHUTDOWN", "42 seconds");
        Settings::override_field_with_env_var(
            &mut settings.actix.client_shutdown, "OVERRIDE__CLIENT_SHUTDOWN"
        )?;
        assert_eq!(settings.actix.client_shutdown, Timeout::Seconds(42));
        Ok(())
    }

    #[test]
    fn override_field__shutdown_timeout() -> AtResult<()> {
        let mut settings = Settings::from_default_template()?;
        assert_eq!(settings.actix.shutdown_timeout, Timeout::Default);
        Settings::override_field(&mut settings.actix.shutdown_timeout, "42 seconds")?;
        assert_eq!(settings.actix.shutdown_timeout, Timeout::Seconds(42));
        Ok(())
    }

    #[test]
    fn override_field_with_env_var__shutdown_timeout() -> AtResult<()> {
        let mut settings = Settings::from_default_template()?;
        assert_eq!(settings.actix.shutdown_timeout, Timeout::Default);
        std::env::set_var("OVERRIDE__SHUTDOWN_TIMEOUT", "42 seconds");
        Settings::override_field_with_env_var(
            &mut settings.actix.shutdown_timeout, "OVERRIDE__SHUTDOWN_TIMEOUT"
        )?;
        assert_eq!(settings.actix.shutdown_timeout, Timeout::Seconds(42));
        Ok(())
    }



    #[test]
    fn override_field__ssl__enabled() -> AtResult<()> {
        let mut settings = Settings::from_default_template()?;
        assert!(!settings.actix.ssl.enabled);
        Settings::override_field(&mut settings.actix.ssl.enabled, "true")?;
        assert!(settings.actix.ssl.enabled);
        Ok(())
    }

    #[test]
    fn override_field_with_env_var__ssl__enabled() -> AtResult<()> {
        let mut settings = Settings::from_default_template()?;
        assert!(!settings.actix.ssl.enabled);
        std::env::set_var("OVERRIDE__SSL_ENABLED", "true");
        Settings::override_field_with_env_var(
            &mut settings.actix.ssl.enabled, "OVERRIDE__SSL_ENABLED"
        )?;
        assert!(settings.actix.ssl.enabled);
        Ok(())
    }

    #[test]
    fn override_field__ssl__certificate() -> AtResult<()> {
        let mut settings = Settings::from_default_template()?;
        assert_eq!(settings.actix.ssl.certificate, Path::new("path/to/cert/cert.pem"));
        Settings::override_field(
            &mut settings.actix.ssl.certificate, "/overridden/path/to/cert/cert.pem"
        )?;
        assert_eq!(
            settings.actix.ssl.certificate, Path::new("/overridden/path/to/cert/cert.pem")
        );
        Ok(())
    }

    #[test]
    fn override_field_with_env_var__ssl__certificate() -> AtResult<()> {
        let mut settings = Settings::from_default_template()?;
        assert_eq!(settings.actix.ssl.certificate, Path::new("path/to/cert/cert.pem"));
        std::env::set_var(
            "OVERRIDE__SSL_CERTIFICATE", "/overridden/path/to/cert/cert.pem"
        );
        Settings::override_field_with_env_var(
            &mut settings.actix.ssl.certificate, "OVERRIDE__SSL_CERTIFICATE"
        )?;
        assert_eq!(
            settings.actix.ssl.certificate,
            Path::new("/overridden/path/to/cert/cert.pem")
        );
        Ok(())
    }

    #[test]
    fn override_field__ssl__private_key() -> AtResult<()> {
        let mut settings = Settings::from_default_template()?;
        assert_eq!(settings.actix.ssl.private_key, Path::new("path/to/cert/key.pem"));
        Settings::override_field(
            &mut settings.actix.ssl.private_key, "/overridden/path/to/cert/key.pem"
        )?;
        assert_eq!(
            settings.actix.ssl.private_key, Path::new("/overridden/path/to/cert/key.pem")
        );
        Ok(())
    }

    #[test]
    fn override_field_with_env_var__ssl__private_key() -> AtResult<()> {
        let mut settings = Settings::from_default_template()?;
        assert_eq!(settings.actix.ssl.private_key, Path::new("path/to/cert/key.pem"));
        std::env::set_var(
            "OVERRIDE__SSL_PRIVATE_KEY", "/overridden/path/to/cert/key.pem"
        );
        Settings::override_field_with_env_var(
            &mut settings.actix.ssl.private_key, "OVERRIDE__SSL_PRIVATE_KEY"
        )?;
        assert_eq!(
            settings.actix.ssl.private_key,
            Path::new("/overridden/path/to/cert/key.pem")
        );
        Ok(())
    }

    #[test]
    fn override_extended_field_with_custom_type() -> AtResult<()> {
        #[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
        struct NestedSetting {
            foo: String,
            bar: bool,
        }
        #[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
        struct AppSettings {
            #[serde(rename = "example-name")]
            example_name: String,
            #[serde(rename = "nested-field")]
            nested_field: NestedSetting,
        }
        type CustomSettings = BasicSettings<AppSettings>;
        let mut settings = CustomSettings::from_template(&(
            CustomSettings::DEFAULT_TOML_TEMPLATE.to_string()
                // NOTE: Add these entries to the `[application]` table:
                + "\nexample-name = \"example value\""
                + "\nnested-field = { foo = \"foo\", bar = false }"
        ))?;
        assert_eq!(settings.application, AppSettings {
            example_name: "example value".into(),
            nested_field: NestedSetting {
                foo: "foo".into(),
                bar: false,
            },
        });
        CustomSettings::override_field(
            &mut settings.application.example_name,
            "/overridden/path/to/cert/key.pem".to_string()
        )?;
        assert_eq!(settings.application, AppSettings {
            example_name: "/overridden/path/to/cert/key.pem".into(),
            nested_field: NestedSetting {
                foo: "foo".into(),
                bar: false,
            },
        });
        Ok(())
    }

}