o402 0.1.2

OpenAI-compatible gateway, paid with x402.
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
//! TOML-facing types. Field names match the operator file.

use std::net::{Ipv4Addr, SocketAddr};

use indexmap::IndexMap;
use serde::Deserialize;
use url::Url;

use super::secret::Secret;
use super::{
    AcceptConfig, Config, ConfigError, FacilitatorAuth, FacilitatorConfig, LogFormat, ModelConfig,
    ObservabilityConfig, PaymentConfig, PricingConfig, PricingDefault, Scheduler, ServerConfig,
    SettlementConfig, UpstreamConfig, UsagePolicy,
};

/// Root TOML document.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub(super) struct RawConfig {
    /// HTTP bind and limits.
    #[serde(default)]
    server: RawServer,
    /// Logs and optional metrics bind.
    #[serde(default)]
    observability: RawObservability,
    /// Payment gate. `enabled` has no default.
    payment: RawPayment,
    /// Upstream LLM providers. At least one is required after validation.
    #[serde(default)]
    upstreams: Vec<RawUpstream>,
    /// Model catalog. Required when payment is on.
    #[serde(default)]
    models: Vec<RawModel>,
    /// Default rates. Required when payment is on.
    #[serde(default)]
    pricing: Option<RawPricing>,
}

/// `[server]` table.
#[derive(Debug, Deserialize)]
#[serde(default, deny_unknown_fields)]
struct RawServer {
    /// Listen address.
    bind: SocketAddr,
    /// Public origin; required when payment is on.
    base_url: Option<Url>,
    /// Drain budget after SIGINT/SIGTERM.
    shutdown_timeout_secs: u64,
    /// Max buffered request body.
    body_limit_bytes: usize,
    /// Non-stream handler timeout.
    request_timeout_secs: u64,
    /// CORS origin list. Empty disables CORS.
    cors: RawCors,
}

impl Default for RawServer {
    fn default() -> Self {
        Self {
            bind: SocketAddr::from((Ipv4Addr::UNSPECIFIED, 8080)),
            base_url: None,
            shutdown_timeout_secs: 30,
            body_limit_bytes: 8_388_608,
            request_timeout_secs: 180,
            cors: RawCors::default(),
        }
    }
}

/// `[server.cors]` table.
#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawCors {
    /// Allowed origins. `["*"]` is allowed and logged as a warning later.
    #[serde(default)]
    origins: Vec<String>,
}

/// `[observability]` table.
#[derive(Debug, Deserialize)]
#[serde(default, deny_unknown_fields)]
struct RawObservability {
    /// Fallback when `RUST_LOG` is unset.
    level: String,
    /// `json` or `pretty`.
    format: LogFormat,
    /// Optional Prometheus bind.
    metrics_bind: Option<SocketAddr>,
}

impl Default for RawObservability {
    fn default() -> Self {
        Self {
            level: "info".to_owned(),
            format: LogFormat::Json,
            metrics_bind: None,
        }
    }
}

/// `[payment]` table.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawPayment {
    /// Required. No default: the operator must choose.
    enabled: bool,
    /// Missing-usage policy for `upto`.
    #[serde(default)]
    missing_usage: UsagePolicy,
    /// Client-abort policy for `upto`.
    #[serde(default)]
    abort_usage: UsagePolicy,
    /// `PriceTag` timeout.
    #[serde(default = "default_max_timeout_seconds")]
    max_timeout_seconds: u64,
    /// Remote facilitator. Required when `enabled`.
    #[serde(default)]
    facilitator: Option<RawFacilitator>,
    /// Per-(scheme, stream) schedulers.
    #[serde(default)]
    settlement: RawSettlement,
    /// CAIP-2 pattern → pay-to address.
    #[serde(default)]
    pay_to: IndexMap<String, String>,
    /// Advertised accepts. Required non-empty when `enabled`.
    #[serde(default)]
    accepts: Vec<RawAccept>,
}

const fn default_max_timeout_seconds() -> u64 {
    300
}

/// `[payment.facilitator]` table.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawFacilitator {
    /// Facilitator base URL.
    url: Option<Url>,
    /// HTTP timeout for verify/settle/supported.
    #[serde(default = "default_facilitator_timeout")]
    timeout_secs: u64,
    /// `/supported` cache TTL. `0` means no cache.
    #[serde(default = "default_supported_cache_ttl")]
    supported_cache_ttl_secs: u64,
    /// Path-keyed auth header maps.
    #[serde(default)]
    auth: Option<RawFacilitatorAuth>,
}

const fn default_facilitator_timeout() -> u64 {
    30
}

const fn default_supported_cache_ttl() -> u64 {
    600
}

/// `[payment.facilitator.auth]` table.
#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawFacilitatorAuth {
    /// Headers for `POST /verify`.
    #[serde(default)]
    verify: IndexMap<String, Secret<String>>,
    /// Headers for `POST /settle`.
    #[serde(default)]
    settle: IndexMap<String, Secret<String>>,
    /// Headers for `GET /supported`.
    #[serde(default)]
    supported: IndexMap<String, Secret<String>>,
}

/// `[payment.settlement]` table.
#[derive(Debug, Deserialize)]
#[serde(default, deny_unknown_fields)]
struct RawSettlement {
    /// Exact non-stream scheduler.
    exact_non_stream: Scheduler,
    /// Exact stream scheduler.
    exact_stream: Scheduler,
    /// Upto non-stream scheduler.
    upto_non_stream: Scheduler,
    /// Upto stream scheduler. Only `stream-then-settle`.
    upto_stream: Scheduler,
}

impl Default for RawSettlement {
    fn default() -> Self {
        Self {
            exact_non_stream: Scheduler::SequentialWaitSettle,
            exact_stream: Scheduler::Wait2xxThenSpawn,
            upto_non_stream: Scheduler::SequentialWaitSettle,
            upto_stream: Scheduler::StreamThenSettle,
        }
    }
}

/// One `[[payment.accepts]]` row.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawAccept {
    /// `exact` or `upto`.
    scheme: String,
    /// CAIP-2 network.
    network: String,
    /// Named ticker for this namespace xor `asset_address` + `decimals`.
    #[serde(default)]
    asset: Option<String>,
    /// Custom asset address.
    #[serde(default)]
    asset_address: Option<String>,
    /// Custom asset decimals.
    #[serde(default)]
    decimals: Option<u32>,
    /// EVM or Tron exact transfer method.
    #[serde(default)]
    transfer_method: Option<String>,
    /// EIP-712 name for custom EVM assets.
    #[serde(default)]
    eip712_name: Option<String>,
    /// EIP-712 version for custom EVM assets.
    #[serde(default)]
    eip712_version: Option<String>,
}

/// One `[[upstreams]]` row.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawUpstream {
    /// Catalog name referenced by `[[models]]`.
    name: String,
    /// OpenAI-compatible origin.
    base_url: Url,
    /// Injected as `Authorization: Bearer …`. Whole-string `$VAR`.
    api_key: Secret<String>,
    /// Request timeout including streaming generation.
    #[serde(default = "default_upstream_timeout")]
    timeout_secs: u64,
    /// TCP connect timeout.
    #[serde(default = "default_connect_timeout")]
    connect_timeout_secs: u64,
    /// Required for non-HTTPS, non-loopback origins.
    #[serde(default)]
    allow_insecure: bool,
}

const fn default_upstream_timeout() -> u64 {
    120
}

const fn default_connect_timeout() -> u64 {
    10
}

/// One `[[models]]` row.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawModel {
    /// Client-facing model id.
    id: String,
    /// `[[upstreams]]` name.
    upstream: String,
    /// Upstream model id when different from `id`.
    #[serde(default)]
    upstream_model: Option<String>,
    /// OpenAI `owned_by`.
    #[serde(default)]
    owned_by: Option<String>,
    /// `exact` or `upto`. Falls back to `[pricing.default]`.
    #[serde(default)]
    scheme: Option<String>,
    /// Per-million uncached input.
    #[serde(default)]
    input_per_million: Option<String>,
    /// Per-million non-reasoning output.
    #[serde(default)]
    output_per_million: Option<String>,
    /// Per-million cached input.
    #[serde(default)]
    cached_input_per_million: Option<String>,
    /// Per-million reasoning output.
    #[serde(default)]
    reasoning_per_million: Option<String>,
    /// Request floor.
    #[serde(default)]
    request_floor: Option<String>,
    /// Ceiling multiplier.
    #[serde(default)]
    ceiling_multiplier: Option<String>,
    /// Hard ceiling.
    #[serde(default)]
    max_ceiling: Option<String>,
    /// Max input tokens for ceiling.
    #[serde(default)]
    max_input_tokens: Option<u32>,
    /// Default max output tokens for ceiling.
    #[serde(default)]
    default_max_output_tokens: Option<u32>,
    /// Exact per-request price.
    #[serde(default)]
    price: Option<String>,
}

/// `[pricing]` table.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawPricing {
    /// Defaults inherited by `[[models]]`.
    #[serde(default)]
    default: Option<RawPricingDefault>,
}

/// `[pricing.default]` table.
#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawPricingDefault {
    /// Default scheme.
    #[serde(default)]
    scheme: Option<String>,
    /// Default request floor.
    #[serde(default)]
    request_floor: Option<String>,
    /// Default uncached input rate.
    #[serde(default)]
    input_per_million: Option<String>,
    /// Default output rate.
    #[serde(default)]
    output_per_million: Option<String>,
    /// Default cached input rate.
    #[serde(default)]
    cached_input_per_million: Option<String>,
    /// Default reasoning rate.
    #[serde(default)]
    reasoning_per_million: Option<String>,
    /// Default ceiling multiplier.
    #[serde(default)]
    ceiling_multiplier: Option<String>,
    /// Default hard ceiling.
    #[serde(default)]
    max_ceiling: Option<String>,
    /// Default max input tokens.
    #[serde(default)]
    max_input_tokens: Option<u32>,
    /// Default max output tokens.
    #[serde(default)]
    default_max_output_tokens: Option<u32>,
    /// Default exact price.
    #[serde(default)]
    price: Option<String>,
}

impl RawConfig {
    /// Validate and convert to the runtime config.
    pub(super) fn into_config(self) -> Result<Config, ConfigError> {
        validate_cors(&self.server.cors.origins)?;
        if self.observability.level.trim().is_empty() {
            return Err(ConfigError::Validation(
                "observability.level must not be empty".to_owned(),
            ));
        }
        if let Some(metrics_bind) = self.observability.metrics_bind
            && metrics_bind_overlaps(metrics_bind, self.server.bind)
        {
            return Err(ConfigError::Validation(
                "observability.metrics_bind port overlaps server.bind".to_owned(),
            ));
        }

        let payment = self.payment.into_config(self.server.base_url.as_ref())?;
        let upstreams = validate_upstreams(&self.upstreams)?;
        let pricing = validate_pricing(self.pricing, payment.enabled)?;
        let models = validate_models(&self.models, &upstreams, payment.enabled, pricing.as_ref())?;

        Ok(Config {
            server: ServerConfig {
                bind: self.server.bind,
                base_url: self.server.base_url,
                shutdown_timeout_secs: self.server.shutdown_timeout_secs,
                body_limit_bytes: self.server.body_limit_bytes,
                request_timeout_secs: self.server.request_timeout_secs,
                cors_origins: self.server.cors.origins,
            },
            observability: ObservabilityConfig {
                level: self.observability.level,
                format: self.observability.format,
                metrics_bind: self.observability.metrics_bind,
            },
            payment,
            upstreams,
            models,
            pricing,
        })
    }
}

impl RawPayment {
    fn into_config(self, base_url: Option<&Url>) -> Result<PaymentConfig, ConfigError> {
        validate_settlement(&self.settlement)?;
        if self.enabled {
            validate_enabled_payment(&self, base_url)?;
        }

        let facilitator = self
            .facilitator
            .map(|fac| FacilitatorConfig {
                url: fac.url,
                timeout_secs: fac.timeout_secs,
                supported_cache_ttl_secs: fac.supported_cache_ttl_secs,
                auth: fac.auth.map(|auth| FacilitatorAuth {
                    verify: auth.verify,
                    settle: auth.settle,
                    supported: auth.supported,
                }),
            })
            .filter(|fac| self.enabled || fac.url.is_some());

        Ok(PaymentConfig {
            enabled: self.enabled,
            missing_usage: self.missing_usage,
            abort_usage: self.abort_usage,
            max_timeout_seconds: self.max_timeout_seconds,
            facilitator,
            settlement: SettlementConfig {
                exact_non_stream: self.settlement.exact_non_stream,
                exact_stream: self.settlement.exact_stream,
                upto_non_stream: self.settlement.upto_non_stream,
                upto_stream: self.settlement.upto_stream,
            },
            pay_to: self.pay_to,
            accepts: self
                .accepts
                .into_iter()
                .map(|row| AcceptConfig {
                    scheme: row.scheme,
                    network: row.network,
                    asset: row.asset,
                    asset_address: row.asset_address,
                    decimals: row.decimals,
                    transfer_method: row.transfer_method,
                    eip712_name: row.eip712_name,
                    eip712_version: row.eip712_version,
                })
                .collect(),
        })
    }
}

/// Reject mixed `*` and explicit origins.
fn validate_cors(origins: &[String]) -> Result<(), ConfigError> {
    let star = origins.iter().filter(|origin| *origin == "*").count();
    if star > 0 && origins.len() != 1 {
        return Err(ConfigError::Validation(
            "server.cors.origins cannot mix '*' with explicit origins".to_owned(),
        ));
    }
    for origin in origins {
        if origin.is_empty() {
            return Err(ConfigError::Validation(
                "server.cors.origins entries must not be empty".to_owned(),
            ));
        }
    }
    Ok(())
}

fn validate_settlement(settlement: &RawSettlement) -> Result<(), ConfigError> {
    if settlement.exact_non_stream != Scheduler::SequentialWaitSettle {
        return Err(ConfigError::Validation(
            "payment.settlement.exact_non_stream must be sequential-wait-settle".to_owned(),
        ));
    }
    if settlement.exact_stream != Scheduler::Wait2xxThenSpawn {
        return Err(ConfigError::Validation(
            "payment.settlement.exact_stream must be wait-2xx-then-spawn".to_owned(),
        ));
    }
    if settlement.upto_non_stream != Scheduler::SequentialWaitSettle {
        return Err(ConfigError::Validation(
            "payment.settlement.upto_non_stream must be sequential-wait-settle".to_owned(),
        ));
    }
    if settlement.upto_stream != Scheduler::StreamThenSettle {
        return Err(ConfigError::Validation(
            "payment.settlement.upto_stream must be stream-then-settle".to_owned(),
        ));
    }
    Ok(())
}

/// Checks that only apply when `payment.enabled = true`.
fn validate_enabled_payment(
    payment: &RawPayment,
    base_url: Option<&Url>,
) -> Result<(), ConfigError> {
    let Some(base_url) = base_url else {
        return Err(ConfigError::Validation(
            "server.base_url is required when payment.enabled = true".to_owned(),
        ));
    };
    validate_public_base_url(base_url)?;

    let Some(facilitator) = payment.facilitator.as_ref() else {
        return Err(ConfigError::Validation(
            "payment.facilitator.url is required when payment.enabled = true".to_owned(),
        ));
    };
    if facilitator.url.is_none() {
        return Err(ConfigError::Validation(
            "payment.facilitator.url is required when payment.enabled = true".to_owned(),
        ));
    }
    if payment.pay_to.is_empty() {
        return Err(ConfigError::Validation(
            "payment.pay_to is required when payment.enabled = true".to_owned(),
        ));
    }
    if payment.accepts.is_empty() {
        return Err(ConfigError::Validation(
            "payment.accepts must contain at least one entry when payment.enabled = true"
                .to_owned(),
        ));
    }
    for accept in &payment.accepts {
        validate_accept(accept)?;
    }
    Ok(())
}

/// Loopback may be `http`; anything else must be `https`.
fn validate_public_base_url(url: &Url) -> Result<(), ConfigError> {
    match url.scheme() {
        "https" => Ok(()),
        "http" if is_loopback(url) => Ok(()),
        "http" => Err(ConfigError::Validation(
            "server.base_url must be https except on loopback".to_owned(),
        )),
        other => Err(ConfigError::Validation(format!(
            "server.base_url scheme '{other}' is not supported"
        ))),
    }
}

fn validate_accept(accept: &RawAccept) -> Result<(), ConfigError> {
    match accept.scheme.as_str() {
        "exact" => {}
        "upto" => {
            let namespace = accept
                .network
                .split_once(':')
                .map_or("", |(namespace, _)| namespace);
            if namespace != "eip155" {
                return Err(ConfigError::Validation(format!(
                    "scheme = \"upto\" is only supported on eip155 networks (got {})",
                    accept.network
                )));
            }
            if accept.transfer_method.is_some() {
                return Err(ConfigError::Validation(
                    "transfer_method is not valid on upto accepts".to_owned(),
                ));
            }
        }
        other => {
            return Err(ConfigError::Validation(format!(
                "payment.accepts scheme '{other}' is not supported"
            )));
        }
    }
    let named = accept.asset.is_some();
    let custom = accept.asset_address.is_some() || accept.decimals.is_some();
    match (named, custom) {
        (true, false) => Ok(()),
        (false, true) if accept.asset_address.is_some() && accept.decimals.is_some() => Ok(()),
        (false, true) => Err(ConfigError::Validation(
            "custom payment.accepts entries need both asset_address and decimals".to_owned(),
        )),
        (true, true) => Err(ConfigError::Validation(
            "payment.accepts cannot set both asset and asset_address".to_owned(),
        )),
        (false, false) => Err(ConfigError::Validation(
            "payment.accepts needs a named asset or asset_address + decimals".to_owned(),
        )),
    }
}

fn validate_upstreams(rows: &[RawUpstream]) -> Result<Vec<UpstreamConfig>, ConfigError> {
    if rows.is_empty() {
        return Err(ConfigError::Validation(
            "at least one [[upstreams]] entry is required".to_owned(),
        ));
    }
    let mut names = hashbrown::HashSet::new();
    let mut out = Vec::with_capacity(rows.len());
    for row in rows {
        if row.name.is_empty() {
            return Err(ConfigError::Validation(
                "upstreams.name must not be empty".to_owned(),
            ));
        }
        if !names.insert(row.name.as_str()) {
            return Err(ConfigError::Validation(format!(
                "duplicate upstream name '{}'",
                row.name
            )));
        }
        if row.base_url.scheme() != "https" && !is_loopback(&row.base_url) && !row.allow_insecure {
            return Err(ConfigError::Validation(format!(
                "upstream '{}' is not HTTPS; set allow_insecure = true for non-loopback HTTP",
                row.name
            )));
        }
        out.push(UpstreamConfig {
            name: row.name.clone(),
            base_url: row.base_url.clone(),
            api_key: row.api_key.clone(),
            timeout_secs: row.timeout_secs,
            connect_timeout_secs: row.connect_timeout_secs,
            allow_insecure: row.allow_insecure,
        });
    }
    Ok(out)
}

fn validate_models(
    rows: &[RawModel],
    upstreams: &[UpstreamConfig],
    payment_enabled: bool,
    pricing: Option<&PricingConfig>,
) -> Result<Vec<ModelConfig>, ConfigError> {
    let mut ids = hashbrown::HashSet::new();
    let mut out = Vec::with_capacity(rows.len());
    for row in rows {
        if row.id.is_empty() {
            return Err(ConfigError::Validation(
                "models.id must not be empty".to_owned(),
            ));
        }
        if !ids.insert(row.id.as_str()) {
            return Err(ConfigError::Validation(format!(
                "duplicate model id '{}'",
                row.id
            )));
        }
        if !upstreams.iter().any(|up| up.name == row.upstream) {
            return Err(ConfigError::Validation(format!(
                "model '{}' references unknown upstream '{}'",
                row.id, row.upstream
            )));
        }
        if let Some(scheme) = row.scheme.as_deref()
            && scheme != "exact"
            && scheme != "upto"
        {
            return Err(ConfigError::Validation(format!(
                "model '{}' scheme '{scheme}' is not supported",
                row.id
            )));
        }
        if payment_enabled && row.scheme.is_some() {
            validate_paid_model(row, pricing)?;
        }
        out.push(ModelConfig {
            id: row.id.clone(),
            upstream: row.upstream.clone(),
            upstream_model: row.upstream_model.clone(),
            owned_by: row.owned_by.clone(),
            scheme: row.scheme.clone(),
            input_per_million: row.input_per_million.clone(),
            output_per_million: row.output_per_million.clone(),
            cached_input_per_million: row.cached_input_per_million.clone(),
            reasoning_per_million: row.reasoning_per_million.clone(),
            request_floor: row.request_floor.clone(),
            ceiling_multiplier: row.ceiling_multiplier.clone(),
            max_ceiling: row.max_ceiling.clone(),
            max_input_tokens: row.max_input_tokens,
            default_max_output_tokens: row.default_max_output_tokens,
            price: row.price.clone(),
        });
    }
    Ok(out)
}

fn validate_pricing(
    pricing: Option<RawPricing>,
    payment_enabled: bool,
) -> Result<Option<PricingConfig>, ConfigError> {
    let missing = || {
        ConfigError::Validation(
            "pricing.default is required when payment.enabled = true".to_owned(),
        )
    };
    let Some(pricing) = pricing else {
        return if payment_enabled {
            Err(missing())
        } else {
            Ok(None)
        };
    };
    let Some(default) = pricing.default else {
        return if payment_enabled {
            Err(missing())
        } else {
            Ok(Some(PricingConfig { default: None }))
        };
    };
    if payment_enabled {
        if default.price.is_none() {
            return Err(ConfigError::Validation(
                "pricing.default.price is required when payment.enabled = true".to_owned(),
            ));
        }
        if default.input_per_million.is_none()
            || default.output_per_million.is_none()
            || default.max_input_tokens.is_none()
        {
            return Err(ConfigError::Validation(
                "pricing.default needs input_per_million, output_per_million, and max_input_tokens when payment.enabled = true"
                    .to_owned(),
            ));
        }
    }
    Ok(Some(PricingConfig {
        default: Some(PricingDefault {
            scheme: default.scheme,
            request_floor: default.request_floor,
            input_per_million: default.input_per_million,
            output_per_million: default.output_per_million,
            cached_input_per_million: default.cached_input_per_million,
            reasoning_per_million: default.reasoning_per_million,
            ceiling_multiplier: default.ceiling_multiplier,
            max_ceiling: default.max_ceiling,
            max_input_tokens: default.max_input_tokens,
            default_max_output_tokens: default.default_max_output_tokens,
            price: default.price,
        }),
    }))
}

fn validate_paid_model(row: &RawModel, pricing: Option<&PricingConfig>) -> Result<(), ConfigError> {
    let default = pricing.and_then(|pricing| pricing.default.as_ref());
    let scheme = row
        .scheme
        .as_deref()
        .or_else(|| default.and_then(|defaults| defaults.scheme.as_deref()))
        .ok_or_else(|| {
            ConfigError::Validation(format!(
                "model '{}' needs scheme or pricing.default.scheme when payment.enabled = true",
                row.id
            ))
        })?;
    match scheme {
        "upto" => {
            let input = row
                .input_per_million
                .as_deref()
                .or_else(|| default.and_then(|defaults| defaults.input_per_million.as_deref()));
            if input.is_none() {
                return Err(ConfigError::Validation(format!(
                    "model '{}' requires input_per_million when scheme is upto",
                    row.id
                )));
            }
            let max_input = row
                .max_input_tokens
                .or_else(|| default.and_then(|defaults| defaults.max_input_tokens));
            if max_input.is_none() {
                return Err(ConfigError::Validation(format!(
                    "model '{}' requires max_input_tokens when scheme is upto",
                    row.id
                )));
            }
            let output = row
                .output_per_million
                .as_deref()
                .or_else(|| default.and_then(|defaults| defaults.output_per_million.as_deref()));
            if output.is_none() {
                return Err(ConfigError::Validation(format!(
                    "model '{}' requires output_per_million when scheme is upto",
                    row.id
                )));
            }
        }
        "exact" => {
            let price = row
                .price
                .as_deref()
                .or_else(|| default.and_then(|defaults| defaults.price.as_deref()));
            if price.is_none() {
                return Err(ConfigError::Validation(format!(
                    "model '{}' requires price when scheme is exact",
                    row.id
                )));
            }
        }
        other => {
            return Err(ConfigError::Validation(format!(
                "model '{}' scheme '{other}' is not supported",
                row.id
            )));
        }
    }
    Ok(())
}

/// Same port plus equal IPs, or either side unspecified (`0.0.0.0` / `::`).
fn metrics_bind_overlaps(metrics: SocketAddr, server: SocketAddr) -> bool {
    metrics.port() == server.port()
        && (metrics.ip() == server.ip()
            || metrics.ip().is_unspecified()
            || server.ip().is_unspecified())
}

pub(crate) fn is_loopback(url: &Url) -> bool {
    match url.host() {
        Some(url::Host::Ipv4(addr)) => addr.is_loopback(),
        Some(url::Host::Ipv6(addr)) => addr.is_loopback(),
        Some(url::Host::Domain(host)) => host.eq_ignore_ascii_case("localhost"),
        None => false,
    }
}