modelexpress-server 0.7.0

High-performance gRPC server for model serving and management
Documentation
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
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

use clap::Parser;
use config::ConfigError;
use modelexpress_common::config::{LogFormat, LogLevel, load_layered_config};
use serde::{Deserialize, Serialize};
use std::net::SocketAddr;
use std::num::NonZeroU16;
use std::path::PathBuf;
use tracing::Level;

use crate::cache::CacheEvictionConfig;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, clap::ValueEnum, Default)]
#[serde(rename_all = "lowercase")]
pub enum AuthMode {
    #[default]
    Off,
    Enforce,
}

/// A `<namespace>:<serviceaccount>` pair, parsed from `ns:sa`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ServiceAccountRef {
    pub namespace: String,
    pub service_account: String,
}

impl std::fmt::Display for ServiceAccountRef {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}:{}", self.namespace, self.service_account)
    }
}

impl std::str::FromStr for ServiceAccountRef {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let (namespace, service_account) = s
            .split_once(':')
            .ok_or_else(|| format!("expected '<namespace>:<serviceaccount>', got '{s}'"))?;
        let namespace = namespace.trim();
        let service_account = service_account.trim();
        if namespace.is_empty() || service_account.is_empty() {
            return Err(format!(
                "namespace and service account must both be non-empty in '{s}'"
            ));
        }
        Ok(Self {
            namespace: namespace.to_string(),
            service_account: service_account.to_string(),
        })
    }
}

/// Comma-separated CLI/env list of `T`, ignoring blank entries.
#[derive(Debug, Clone)]
pub struct CommaList<T>(Vec<T>);

impl<T> CommaList<T> {
    #[must_use]
    pub fn into_inner(self) -> Vec<T> {
        self.0
    }
}

impl<T: std::str::FromStr> std::str::FromStr for CommaList<T> {
    type Err = T::Err;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let items = s
            .split(',')
            .map(str::trim)
            .filter(|part| !part.is_empty())
            .map(T::from_str)
            .collect::<Result<Vec<_>, _>>()?;
        Ok(Self(items))
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct SecurityConfig {
    pub mode: Option<AuthMode>,
    pub token_audiences: Vec<String>,
    pub allowed_service_accounts: Vec<ServiceAccountRef>,
    pub cache_ttl_secs: u64,
}

impl Default for SecurityConfig {
    fn default() -> Self {
        Self {
            mode: None,
            token_audiences: Vec::new(),
            allowed_service_accounts: Vec::new(),
            cache_ttl_secs: 60,
        }
    }
}

impl SecurityConfig {
    #[must_use]
    pub fn resolve_mode(&self) -> AuthMode {
        self.mode.unwrap_or(AuthMode::Off)
    }

    pub fn validate_resolved(&self, mode: AuthMode) -> Result<(), String> {
        if mode == AuthMode::Enforce {
            if self.token_audiences.is_empty() {
                return Err(
                    "security mode 'enforce' requires at least one token audience \
                    (security.token_audiences)"
                        .to_string(),
                );
            }
            if self.allowed_service_accounts.is_empty() {
                return Err(
                    "security mode 'enforce' requires a non-empty service account \
                    allowlist (security.allowed_service_accounts)"
                        .to_string(),
                );
            }
        }
        Ok(())
    }
}

#[derive(clap::Args, Debug, Default)]
pub struct SecurityArgs {
    /// ServiceAccount auth mode (off, enforce). Off by default.
    #[arg(
        long = "security-mode",
        env = modelexpress_common::envs::MODEL_EXPRESS_SECURITY_MODE,
        value_enum
    )]
    pub mode: Option<AuthMode>,

    /// Comma-separated SA token audiences the caller's token must carry.
    #[arg(
        long = "security-token-audiences",
        env = modelexpress_common::envs::MODEL_EXPRESS_SECURITY_TOKEN_AUDIENCES
    )]
    pub token_audiences: Option<CommaList<String>>,

    /// Comma-separated allowed callers as `<namespace>:<serviceaccount>`.
    #[arg(
        long = "security-allowed-service-accounts",
        env = modelexpress_common::envs::MODEL_EXPRESS_SECURITY_ALLOWED_SERVICE_ACCOUNTS
    )]
    pub allowed_service_accounts: Option<CommaList<ServiceAccountRef>>,

    /// TTL for the verified-token and rejection caches, in seconds.
    #[arg(
        long = "security-cache-ttl-secs",
        env = modelexpress_common::envs::MODEL_EXPRESS_SECURITY_CACHE_TTL_SECS
    )]
    pub cache_ttl_secs: Option<u64>,
}

/// Command line arguments for the server
#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
pub struct ServerArgs {
    /// Configuration file path
    #[arg(short, long, value_name = "FILE")]
    pub config: Option<PathBuf>,

    /// Server port
    #[arg(short, long, env = modelexpress_common::envs::MODEL_EXPRESS_SERVER_PORT)]
    pub port: Option<NonZeroU16>,

    /// Server host address
    #[arg(long, env = modelexpress_common::envs::MODEL_EXPRESS_SERVER_HOST)]
    pub host: Option<String>,

    // This clap override is the ONLY path that reaches
    // `ServerSettings::metrics_port`. The layered config loader builds its
    // environment source as
    // `Environment::with_prefix("MODEL_EXPRESS").separator("_")`, so
    // `MODEL_EXPRESS_SERVER_METRICS_PORT` resolves to the key path
    // `server.metrics.port`, matches no field, and is dropped by serde without a
    // warning. Do not "simplify" this by deleting the override. Kept as a plain
    // comment rather than a doc comment so it stays out of `--help`.
    /// Prometheus `/metrics` port. `0` disables the metrics listener.
    #[arg(long, env = modelexpress_common::envs::MODEL_EXPRESS_SERVER_METRICS_PORT)]
    pub metrics_port: Option<u16>,

    /// Log level
    #[arg(short, long, env = modelexpress_common::envs::MODEL_EXPRESS_LOG_LEVEL, value_enum)]
    pub log_level: Option<LogLevel>,

    /// Log format
    #[arg(long, env = modelexpress_common::envs::MODEL_EXPRESS_LOG_FORMAT, value_enum)]
    pub log_format: Option<LogFormat>,

    /// Cache directory path
    #[arg(long, env = modelexpress_common::envs::MODEL_EXPRESS_CACHE_DIRECTORY)]
    pub cache_directory: Option<PathBuf>,

    /// Enable cache eviction
    #[arg(long, env = modelexpress_common::envs::MODEL_EXPRESS_CACHE_EVICTION_ENABLED)]
    pub cache_eviction_enabled: Option<bool>,

    #[command(flatten)]
    pub security: SecurityArgs,

    /// Validate configuration and exit
    #[arg(long)]
    pub validate_config: bool,
}

/// Complete server configuration
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ServerConfig {
    /// Server settings
    pub server: ServerSettings,
    /// Cache configuration
    pub cache: CacheConfig,
    /// Logging configuration
    pub logging: LoggingConfig,
    #[serde(default)]
    pub security: SecurityConfig,
}

/// Server-specific settings
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerSettings {
    /// Server host address
    pub host: String,
    /// Server port
    pub port: NonZeroU16,
    /// Prometheus `/metrics` port. `0` disables the listener.
    ///
    /// Two properties here are load-bearing, and both exist because
    /// `load_layered_config` swallows any deserialization error and silently
    /// returns `T::default()` — so anything this field rejects is not "the
    /// field is ignored" but "the entire config file is ignored", with no log
    /// line at any level. The gRPC port, cache directory, eviction policy and
    /// **auth settings** would all revert to defaults because of a typo here.
    ///
    /// 1. `#[serde(default)]` covers the missing-key case. `ServerSettings` has
    ///    no struct-level default, so without it every existing
    ///    `model-express.yaml` — none of which mention this field — would fail
    ///    to parse.
    /// 2. The type is `u16`, not `NonZeroU16`. `0` is the documented disable
    ///    value, and `NonZeroU16` rejects it during deserialization, which is
    ///    exactly the silent-total-fallback case above. Normalization to
    ///    "disabled" happens in [`ServerConfig::metrics_socket_addr`].
    #[serde(default = "default_metrics_port")]
    pub metrics_port: u16,
}

/// Serde default for [`ServerSettings::metrics_port`]. Server metrics are on by
/// default; the client's stay opt-in.
fn default_metrics_port() -> u16 {
    modelexpress_common::constants::DEFAULT_METRICS_PORT.get()
}

/// Cache configuration wrapper
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CacheConfig {
    /// Cache eviction settings
    pub eviction: CacheEvictionConfig,
    /// Cache directory path
    pub directory: PathBuf,
    /// Maximum cache size in bytes
    pub max_size_bytes: Option<u64>,
}

/// Logging configuration
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct LoggingConfig {
    /// Log level
    #[serde(default)]
    pub level: LogLevel,
    /// Log format (json, pretty, compact)
    #[serde(default)]
    pub format: LogFormat,
    /// Log to file
    pub file: Option<PathBuf>,
    /// Enable structured logging
    pub structured: bool,
}

impl Default for ServerSettings {
    fn default() -> Self {
        Self {
            host: "0.0.0.0".to_string(),
            port: modelexpress_common::constants::DEFAULT_GRPC_PORT,
            metrics_port: default_metrics_port(),
        }
    }
}

impl Default for CacheConfig {
    fn default() -> Self {
        Self {
            eviction: CacheEvictionConfig::default(),
            directory: PathBuf::from("./cache"),
            max_size_bytes: None,
        }
    }
}

impl ServerConfig {
    /// Load configuration from multiple sources in order of precedence:
    /// 1. Command line arguments (highest priority)
    /// 2. Environment variables
    /// 3. Configuration file
    /// 4. Default values (lowest priority)
    pub fn load(args: ServerArgs) -> Result<Self, ConfigError> {
        Self::load_internal(args, false)
    }

    /// Load and validate configuration file strictly without fallbacks.
    /// This method should be used when validating configuration files.
    /// It will return an error if the file has invalid syntax or values.
    pub fn load_and_validate_strict(args: ServerArgs) -> Result<Self, ConfigError> {
        Self::load_internal(args, true)
    }

    /// Internal method to load configuration with optional strict mode
    fn load_internal(args: ServerArgs, strict_mode: bool) -> Result<Self, ConfigError> {
        let mut config = if strict_mode {
            // Use strict loading - fail on any configuration errors
            if let Some(ref config_file) = args.config {
                // Load file strictly without fallbacks
                modelexpress_common::config::validate_config_file(config_file)?
            } else {
                // No config file specified, use defaults
                Self::default()
            }
        } else {
            // Use layered config loading with fallbacks to defaults
            load_layered_config(
                args.config.clone(),
                modelexpress_common::envs::MODEL_EXPRESS_PREFIX,
                Self::default(),
            )?
        };

        // Apply command line overrides (same for both modes)
        if let Some(port) = args.port {
            config.server.port = port;
        }

        if let Some(host) = args.host {
            config.server.host = host;
        }

        // `0` is the documented "off" value. Env-only deployments (Helm) have no
        // other way to turn the listener off.
        if let Some(metrics_port) = args.metrics_port {
            config.server.metrics_port = metrics_port;
        }

        if let Some(log_level) = args.log_level {
            config.logging.level = log_level;
        }

        if let Some(log_format) = args.log_format {
            config.logging.format = log_format;
        }

        // Apply cache overrides
        if let Some(cache_directory) = args.cache_directory {
            config.cache.directory = cache_directory;
        }

        if let Some(cache_eviction_enabled) = args.cache_eviction_enabled {
            config.cache.eviction.enabled = cache_eviction_enabled;
        }

        // Apply security overrides
        if let Some(mode) = args.security.mode {
            config.security.mode = Some(mode);
        }
        if let Some(token_audiences) = args.security.token_audiences {
            config.security.token_audiences = token_audiences.into_inner();
        }
        if let Some(allowed) = args.security.allowed_service_accounts {
            config.security.allowed_service_accounts = allowed.into_inner();
        }
        if let Some(cache_ttl_secs) = args.security.cache_ttl_secs {
            config.security.cache_ttl_secs = cache_ttl_secs;
        }

        // Validate the final configuration
        config.validate()?;

        Ok(config)
    }

    /// Validate the configuration
    pub fn validate(&self) -> Result<(), ConfigError> {
        // Validate cache directory
        if let Some(parent) = self.cache.directory.parent()
            && !parent.exists()
        {
            return Err(ConfigError::Message(format!(
                "Cache directory parent does not exist: {}",
                parent.display()
            )));
        }

        let mode = self.security.resolve_mode();
        self.security
            .validate_resolved(mode)
            .map_err(ConfigError::Message)?;

        Ok(())
    }

    /// Get the server socket address
    pub fn socket_addr(&self) -> Result<SocketAddr, ConfigError> {
        let addr = format!("{}:{}", self.server.host, self.server.port);
        addr.parse()
            .map_err(|e| ConfigError::Message(format!("Invalid server address {addr}: {e}")))
    }

    /// Socket address for the Prometheus `/metrics` listener, or `None` when
    /// metrics are disabled.
    ///
    /// # Errors
    /// Returns an error when host and metrics port do not form a valid address.
    pub fn metrics_socket_addr(&self) -> Result<Option<SocketAddr>, ConfigError> {
        // `0` is the disable sentinel. Normalizing here rather than in the field
        // type keeps `0` deserializable from a config file; see
        // `ServerSettings::metrics_port`.
        let Some(metrics_port) = NonZeroU16::new(self.server.metrics_port) else {
            return Ok(None);
        };
        let addr = format!("{}:{}", self.server.host, metrics_port);
        addr.parse()
            .map(Some)
            .map_err(|e| ConfigError::Message(format!("Invalid metrics address {addr}: {e}")))
    }

    /// Get the logging level as a tracing Level
    pub fn log_level(&self) -> Level {
        self.logging.level.into()
    }

    /// Print the configuration for debugging
    pub fn print_config(&self) {
        use tracing::info;

        info!("Server Configuration:");
        info!("  Host: {}", self.server.host);
        info!("  Port: {}", self.server.port);
        match NonZeroU16::new(self.server.metrics_port) {
            Some(port) => info!("  Metrics Port: {port} (/metrics)"),
            None => info!("  Metrics Port: disabled"),
        }

        info!("Cache Configuration:");
        info!("  Directory: {}", self.cache.directory.display());
        info!("  Max Size: {:?}", self.cache.max_size_bytes);
        info!("  Eviction Enabled: {}", self.cache.eviction.enabled);
        info!(
            "  Eviction Check Interval: {}s",
            self.cache.eviction.check_interval.num_seconds()
        );

        info!("Logging Configuration:");
        info!("  Level: {}", self.logging.level);
        info!("  Format: {}", self.logging.format);
        info!("  File: {:?}", self.logging.file);
        info!("  Structured: {}", self.logging.structured);

        info!("Security Configuration:");
        info!("  Mode: {:?}", self.security.resolve_mode());
        info!("  Token audiences: {:?}", self.security.token_audiences);
        info!(
            "  Allowed service accounts: {}",
            self.security
                .allowed_service_accounts
                .iter()
                .map(ToString::to_string)
                .collect::<Vec<_>>()
                .join(", ")
        );
        info!("  Cache TTL: {}s", self.security.cache_ttl_secs);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::Duration;
    use clap::Parser;
    use modelexpress_common::config::{DurationConfig, parse_duration_string};
    use std::fs;
    use tempfile::tempdir;

    #[test]
    fn test_log_level_enum_parsing() {
        // Test valid log levels
        let valid_levels = [
            ("trace", LogLevel::Trace),
            ("debug", LogLevel::Debug),
            ("info", LogLevel::Info),
            ("warn", LogLevel::Warn),
            ("error", LogLevel::Error),
        ];

        for (level_str, expected_level) in &valid_levels {
            let args = vec!["test", "--log-level", level_str];
            if let Ok(parsed_args) = ServerArgs::try_parse_from(args) {
                assert_eq!(parsed_args.log_level, Some(*expected_level));

                // Test conversion to string
                assert_eq!(expected_level.to_string(), *level_str);

                // Test conversion to tracing::Level
                let tracing_level: Level = (*expected_level).into();
                // Just verify the conversion works - the exact debug format may vary
                match expected_level {
                    LogLevel::Trace => assert_eq!(tracing_level, Level::TRACE),
                    LogLevel::Debug => assert_eq!(tracing_level, Level::DEBUG),
                    LogLevel::Info => assert_eq!(tracing_level, Level::INFO),
                    LogLevel::Warn => assert_eq!(tracing_level, Level::WARN),
                    LogLevel::Error => assert_eq!(tracing_level, Level::ERROR),
                }
            } else {
                panic!("Failed to parse valid log level: {level_str}");
            }
        }
    }

    #[test]
    fn test_log_level_enum_invalid() {
        // Test invalid log level
        let args = vec!["test", "--log-level", "invalid"];
        let result = ServerArgs::try_parse_from(args);
        assert!(result.is_err());
    }

    #[test]
    fn test_log_level_display() {
        assert_eq!(LogLevel::Trace.to_string(), "trace");
        assert_eq!(LogLevel::Debug.to_string(), "debug");
        assert_eq!(LogLevel::Info.to_string(), "info");
        assert_eq!(LogLevel::Warn.to_string(), "warn");
        assert_eq!(LogLevel::Error.to_string(), "error");
    }

    #[test]
    #[allow(clippy::expect_used)]
    fn test_log_level_from_str() {
        assert_eq!(
            "trace"
                .parse::<LogLevel>()
                .expect("Failed to parse 'trace'"),
            LogLevel::Trace
        );
        assert_eq!(
            "debug"
                .parse::<LogLevel>()
                .expect("Failed to parse 'debug'"),
            LogLevel::Debug
        );
        assert_eq!(
            "info".parse::<LogLevel>().expect("Failed to parse 'info'"),
            LogLevel::Info
        );
        assert_eq!(
            "warn".parse::<LogLevel>().expect("Failed to parse 'warn'"),
            LogLevel::Warn
        );
        assert_eq!(
            "error"
                .parse::<LogLevel>()
                .expect("Failed to parse 'error'"),
            LogLevel::Error
        );

        // Test case insensitive
        assert_eq!(
            "TRACE"
                .parse::<LogLevel>()
                .expect("Failed to parse 'TRACE'"),
            LogLevel::Trace
        );
        assert_eq!(
            "Info".parse::<LogLevel>().expect("Failed to parse 'Info'"),
            LogLevel::Info
        );

        // Test invalid
        assert!("invalid".parse::<LogLevel>().is_err());
    }

    #[test]
    fn test_log_format_display() {
        assert_eq!(LogFormat::Json.to_string(), "json");
        assert_eq!(LogFormat::Pretty.to_string(), "pretty");
        assert_eq!(LogFormat::Compact.to_string(), "compact");
    }

    #[test]
    #[allow(clippy::expect_used)]
    fn test_log_format_from_str() {
        assert_eq!(
            "json".parse::<LogFormat>().expect("Failed to parse 'json'"),
            LogFormat::Json
        );
        assert_eq!(
            "pretty"
                .parse::<LogFormat>()
                .expect("Failed to parse 'pretty'"),
            LogFormat::Pretty
        );
        assert_eq!(
            "compact"
                .parse::<LogFormat>()
                .expect("Failed to parse 'compact'"),
            LogFormat::Compact
        );

        // Test case insensitive
        assert_eq!(
            "JSON".parse::<LogFormat>().expect("Failed to parse 'JSON'"),
            LogFormat::Json
        );
        assert_eq!(
            "Pretty"
                .parse::<LogFormat>()
                .expect("Failed to parse 'Pretty'"),
            LogFormat::Pretty
        );

        // Test invalid
        assert!("invalid".parse::<LogFormat>().is_err());
    }

    #[test]
    #[allow(clippy::expect_used)]
    fn test_parse_duration_string() {
        // Test various duration formats
        assert_eq!(
            parse_duration_string("30m")
                .expect("Failed to parse 30m")
                .num_seconds(),
            30 * 60
        );
        assert_eq!(
            parse_duration_string("45s")
                .expect("Failed to parse 45s")
                .num_seconds(),
            45
        );
        assert_eq!(
            parse_duration_string("1d")
                .expect("Failed to parse 1d")
                .num_seconds(),
            24 * 3600
        );
        assert_eq!(
            parse_duration_string("2h")
                .expect("Failed to parse 2h")
                .num_seconds(),
            2 * 3600
        );
        assert_eq!(
            parse_duration_string("2h30m")
                .expect("Failed to parse 2h30m")
                .num_seconds(),
            2 * 3600 + 30 * 60
        );

        // Test invalid format
        assert!(parse_duration_string("invalid").is_err());
    }

    #[test]
    fn test_duration_config() {
        // Test creation
        let duration_config = DurationConfig::new(Duration::hours(2));
        assert_eq!(duration_config.num_seconds(), 2 * 3600);
        assert_eq!(duration_config.as_chrono_duration(), Duration::hours(2));

        // Test hours constructor
        let duration_config = DurationConfig::hours(3);
        assert_eq!(duration_config.num_seconds(), 3 * 3600);

        // Test display
        assert_eq!(duration_config.to_string(), "10800s");
    }

    #[test]
    #[allow(clippy::expect_used)]
    fn test_duration_config_serde() {
        // Test deserializing from string
        let json = r#""2h""#;
        let duration_config: DurationConfig = serde_json::from_str(json).expect("Failed to parse");
        assert_eq!(duration_config.num_seconds(), 2 * 3600);

        // Test deserializing from number (seconds)
        let json = r#"3600"#;
        let duration_config: DurationConfig = serde_json::from_str(json).expect("Failed to parse");
        assert_eq!(duration_config.num_seconds(), 3600);

        // Test serializing (it should serialize as just the number)
        let duration_config = DurationConfig::hours(1);
        let serialized = serde_json::to_string(&duration_config).expect("Failed to serialize");
        assert_eq!(serialized, r#"3600"#);
    }

    #[test]
    #[allow(clippy::expect_used)]
    fn test_server_config_load_and_validate_strict_valid_config() {
        let temp_dir = tempdir().expect("Failed to create temp dir");
        let config_file = temp_dir.path().join("valid_server_config.yaml");

        let valid_config = r#"
            server:
              host: "127.0.0.1"
              port: 8002
            cache:
              eviction:
                enabled: false
                policy:
                  type: lru
                  unused_threshold: "3d"
                  max_models: 10
                  min_free_space_bytes: 1000000
                check_interval: "30m"
              directory: "./test_cache"
              max_size_bytes: 5000000
            logging:
              level: Debug
              format: Json
              file: null
              structured: true
        "#;

        fs::write(&config_file, valid_config).expect("Failed to write config file");

        let args = ServerArgs {
            config: Some(config_file),
            port: None,
            host: None,
            metrics_port: None,
            log_level: None,
            log_format: None,
            cache_directory: None,
            cache_eviction_enabled: None,
            security: SecurityArgs::default(),
            validate_config: false,
        };

        let result = ServerConfig::load_and_validate_strict(args);
        assert!(result.is_ok());

        let config = result.expect("Expected successful config parsing");
        assert_eq!(config.server.host, "127.0.0.1");
        assert_eq!(config.server.port.get(), 8002);
        assert!(!config.cache.eviction.enabled);
        assert_eq!(config.logging.level, LogLevel::Debug);
        assert_eq!(config.logging.format, LogFormat::Json);
    }

    #[test]
    #[allow(clippy::expect_used)]
    fn test_server_config_load_and_validate_strict_invalid_config() {
        let temp_dir = tempdir().expect("Failed to create temp dir");
        let config_file = temp_dir.path().join("invalid_server_config.yaml");

        let invalid_config = r#"
            server:
              host: "127.0.0.1"
              port: 8002
            cache:
              eviction:
                enabled: "not_a_boolean"  # Invalid type
        "#;

        fs::write(&config_file, invalid_config).expect("Failed to write config file");

        let args = ServerArgs {
            config: Some(config_file),
            port: None,
            host: None,
            metrics_port: None,
            log_level: None,
            log_format: None,
            cache_directory: None,
            cache_eviction_enabled: None,
            security: SecurityArgs::default(),
            validate_config: false,
        };

        let result = ServerConfig::load_and_validate_strict(args);
        assert!(result.is_err());
    }

    #[test]
    #[allow(clippy::expect_used)]
    fn test_server_config_load_and_validate_strict_with_cli_overrides() {
        let temp_dir = tempdir().expect("Failed to create temp dir");
        let config_file = temp_dir.path().join("override_test_config.yaml");

        let base_config = r#"
            server:
              host: "127.0.0.1"
              port: 8002
            cache:
              eviction:
                enabled: true
                policy:
                  type: lru
                  unused_threshold: "1d"
                  max_models: null
                  min_free_space_bytes: null
                check_interval: "1h"
              directory: "./cache"
              max_size_bytes: null
            logging:
              level: Info
              format: Pretty
              file: null
              structured: false
        "#;

        fs::write(&config_file, base_config).expect("Failed to write config file");

        let args = ServerArgs {
            config: Some(config_file),
            port: Some(NonZeroU16::new(9000).expect("9000 is non-zero")),
            host: Some("0.0.0.0".to_string()),
            metrics_port: None,
            log_level: Some(LogLevel::Error),
            log_format: Some(LogFormat::Json),
            cache_directory: Some(PathBuf::from("/tmp/override_cache")),
            cache_eviction_enabled: Some(false),
            security: SecurityArgs::default(),
            validate_config: false,
        };

        let result = ServerConfig::load_and_validate_strict(args);
        assert!(result.is_ok());

        let config = result.expect("Expected successful config parsing");
        // CLI overrides should be applied
        assert_eq!(config.server.host, "0.0.0.0");
        assert_eq!(config.server.port.get(), 9000);
        assert_eq!(config.logging.level, LogLevel::Error);
        assert_eq!(config.logging.format, LogFormat::Json);
        assert_eq!(config.cache.directory, PathBuf::from("/tmp/override_cache"));
        assert!(!config.cache.eviction.enabled);
    }

    #[test]
    #[allow(clippy::expect_used)]
    fn test_server_config_load_and_validate_strict_no_config_file() {
        let args = ServerArgs {
            config: None,
            port: Some(NonZeroU16::new(9001).expect("9001 is non-zero")),
            host: Some("localhost".to_string()),
            metrics_port: None,
            log_level: Some(LogLevel::Warn),
            log_format: None,
            cache_directory: None,
            cache_eviction_enabled: None,
            security: SecurityArgs::default(),
            validate_config: false,
        };

        // When no config file is specified, it should fall back to normal loading
        let result = ServerConfig::load_and_validate_strict(args);
        assert!(result.is_ok());

        let config = result.expect("Expected successful config parsing");
        assert_eq!(config.server.host, "localhost");
        assert_eq!(config.server.port.get(), 9001);
        assert_eq!(config.logging.level, LogLevel::Warn);
    }

    #[test]
    fn security_defaults_to_off() {
        let security = SecurityConfig::default();
        assert_eq!(security.resolve_mode(), AuthMode::Off);
        assert!(security.token_audiences.is_empty());
        assert!(security.allowed_service_accounts.is_empty());
    }

    #[test]
    #[allow(clippy::expect_used)]
    fn service_account_ref_parses_namespace_and_sa() {
        let parsed: ServiceAccountRef = "vllm:worker".parse().expect("valid ns:sa");
        assert_eq!(parsed.namespace, "vllm");
        assert_eq!(parsed.service_account, "worker");
        assert_eq!(parsed.to_string(), "vllm:worker");
        let trimmed: ServiceAccountRef = "  ns : sa ".parse().expect("trims");
        assert_eq!(trimmed, "ns:sa".parse().expect("valid"));
    }

    #[test]
    fn service_account_ref_rejects_malformed() {
        assert!("noseparator".parse::<ServiceAccountRef>().is_err());
        assert!(":sa".parse::<ServiceAccountRef>().is_err());
        assert!("ns:".parse::<ServiceAccountRef>().is_err());
    }

    #[test]
    #[allow(clippy::expect_used)]
    fn comma_list_parses_and_skips_blanks() {
        let list: CommaList<ServiceAccountRef> =
            "a:one, b:two ,, c:three".parse().expect("valid list");
        let items = list.into_inner();
        assert_eq!(items.len(), 3);
        assert_eq!(items[1].namespace, "b");
        assert_eq!(items[2].service_account, "three");

        let empty: CommaList<String> = "  ".parse().expect("empty");
        assert!(empty.into_inner().is_empty());
    }

    #[test]
    fn enforce_requires_audience_and_allowlist() {
        let mut security = SecurityConfig {
            mode: Some(AuthMode::Enforce),
            ..SecurityConfig::default()
        };
        assert!(security.validate_resolved(AuthMode::Enforce).is_err());

        security.token_audiences = vec!["modelexpress".to_string()];
        assert!(security.validate_resolved(AuthMode::Enforce).is_err());

        security.allowed_service_accounts = vec![ServiceAccountRef {
            namespace: "vllm".to_string(),
            service_account: "worker".to_string(),
        }];
        assert!(security.validate_resolved(AuthMode::Enforce).is_ok());
    }

    /// A config file must survive both spellings of the metrics port.
    ///
    /// `load_layered_config` swallows every deserialization error and returns
    /// `T::default()` with no log line, so any value this field rejects costs the
    /// operator the gRPC port, the cache directory, the eviction policy and the
    /// auth settings -- silently. That is why `metrics_port` is a `u16` and not a
    /// `NonZeroU16` (`0` has to deserialize, and is normalized afterwards), and
    /// why it carries `#[serde(default)]` (no existing model-express.yaml mentions
    /// it). Both cases assert the *rest* of the file survived, because that is how
    /// the failure would present.
    #[test]
    #[allow(clippy::expect_used)]
    fn metrics_port_never_costs_the_rest_of_the_config_file() {
        // (metrics_port line, expected port, expected metrics address)
        let cases = [
            ("metrics_port: 0", 0_u16, None),
            ("", default_metrics_port(), Some(default_metrics_port())),
        ];

        for (metrics_line, expected_metrics_port, expects_addr) in cases {
            let temp_dir = tempdir().expect("Failed to create temp dir");
            let config_file = temp_dir.path().join("metrics_port.yaml");
            fs::write(
                &config_file,
                format!(
                    r#"
            server:
              host: "127.0.0.1"
              port: 18012
              {metrics_line}
            cache:
              eviction:
                enabled: false
                policy:
                  type: lru
                  unused_threshold: "3d"
                  max_models: 10
                  min_free_space_bytes: 1000000
                check_interval: "30m"
              directory: "./cache"
              max_size_bytes: 5000000
            logging:
              level: Debug
              format: Json
              file: null
              structured: true
        "#
                ),
            )
            .expect("Failed to write config file");

            let args = ServerArgs {
                config: Some(config_file),
                port: None,
                host: None,
                metrics_port: None,
                log_level: None,
                log_format: None,
                cache_directory: None,
                cache_eviction_enabled: None,
                security: SecurityArgs::default(),
                validate_config: false,
            };
            let config = ServerConfig::load(args).expect("config should load");

            assert_eq!(config.server.metrics_port, expected_metrics_port);
            assert_eq!(
                config
                    .metrics_socket_addr()
                    .expect("metrics address should resolve")
                    .map(|addr| addr.port()),
                expects_addr,
                "0 must mean disabled and nothing else"
            );
            // The rest of the file survived. If this regresses these fail
            // together, because the whole file was dropped.
            assert_eq!(config.server.port.get(), 18012, "the file was dropped");
            assert_eq!(config.server.host, "127.0.0.1");
            assert!(!config.cache.eviction.enabled);
            assert_eq!(config.logging.level, LogLevel::Debug);
        }
    }

    /// The env var must stay wired through clap.
    ///
    /// `load_layered_config` reads env as
    /// `Environment::with_prefix("MODEL_EXPRESS").separator("_")`, so
    /// `MODEL_EXPRESS_SERVER_METRICS_PORT` resolves to the key path
    /// `server.metrics.port`, matches no field, and serde drops it without a
    /// warning. The clap `#[arg(env = ...)]` override is the only path that
    /// reaches the field, and `--metrics-port` is what the Helm chart drives.
    #[test]
    fn metrics_port_is_reachable_from_the_command_line() {
        use clap::Parser as _;

        let args = ServerArgs::parse_from(["modelexpress-server", "--metrics-port", "9999"]);
        assert_eq!(args.metrics_port, Some(9999));

        let off = ServerArgs::parse_from(["modelexpress-server", "--metrics-port", "0"]);
        assert_eq!(
            off.metrics_port,
            Some(0),
            "0 is the documented disable value"
        );
    }
}