1use std::{collections::HashMap, str::FromStr, time::Duration};
4
5use serde::{Deserialize, Deserializer, Serialize, de::Error as _};
6
7use crate::{
8 error::Error,
9 model::{DEFAULT_MODEL, Model},
10 provider::Provider,
11};
12
13pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10);
15pub const DEFAULT_MAX_ATTEMPTS: u32 = 3;
17pub const DEFAULT_INITIAL_BACKOFF: Duration = Duration::from_millis(200);
19pub const DEFAULT_MAX_BACKOFF: Duration = Duration::from_secs(2);
21
22#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
39#[serde(rename_all = "camelCase")]
40pub enum Surface {
41 #[default]
43 Decisions,
44 SystemOne,
46}
47
48impl Surface {
49 #[must_use]
51 pub fn path(self) -> &'static str {
52 match self {
53 Surface::Decisions => "/api/alpha/decisions",
54 Surface::SystemOne => "/api/v1/systemone",
55 }
56 }
57}
58
59#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
78#[serde(rename_all = "camelCase", default)]
79pub struct RetryConfig {
80 pub max_attempts: u32,
82 #[serde(with = "duration_millis", rename = "initialBackoffMs")]
84 pub initial_backoff: Duration,
85 #[serde(with = "duration_millis", rename = "maxBackoffMs")]
87 pub max_backoff: Duration,
88}
89
90impl Default for RetryConfig {
91 fn default() -> Self {
92 RetryConfig {
93 max_attempts: DEFAULT_MAX_ATTEMPTS,
94 initial_backoff: DEFAULT_INITIAL_BACKOFF,
95 max_backoff: DEFAULT_MAX_BACKOFF,
96 }
97 }
98}
99
100impl RetryConfig {
101 #[must_use]
103 pub fn disabled() -> Self {
104 RetryConfig {
105 max_attempts: 1,
106 ..Self::default()
107 }
108 }
109
110 #[must_use]
112 pub fn with_max_attempts(mut self, max_attempts: u32) -> Self {
113 self.max_attempts = max_attempts;
114 self
115 }
116
117 #[must_use]
119 pub fn with_initial_backoff(mut self, backoff: Duration) -> Self {
120 self.initial_backoff = backoff;
121 self
122 }
123
124 #[must_use]
126 pub fn with_max_backoff(mut self, backoff: Duration) -> Self {
127 self.max_backoff = backoff;
128 self
129 }
130}
131
132mod duration_millis {
134 use std::time::Duration;
135
136 use serde::{Deserialize, Deserializer, Serializer};
137
138 pub(super) fn serialize<S: Serializer>(d: &Duration, s: S) -> Result<S::Ok, S::Error> {
139 s.serialize_u64(u64::try_from(d.as_millis()).unwrap_or(u64::MAX))
140 }
141
142 pub(super) fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Duration, D::Error> {
143 let ms = u64::deserialize(d)?;
144 Ok(Duration::from_millis(ms))
145 }
146}
147
148#[derive(Debug, Clone, Default, PartialEq, Serialize)]
170#[serde(transparent)]
171pub struct Thresholds(HashMap<String, f64>);
172
173impl Thresholds {
174 #[must_use]
176 pub fn new() -> Self {
177 Thresholds(HashMap::new())
178 }
179
180 pub fn insert(&mut self, name: impl Into<String>, value: f64) -> Result<(), Error> {
186 validate_threshold(value)?;
187 self.0.insert(name.into(), value);
188 Ok(())
189 }
190
191 #[must_use]
193 pub fn get(&self, name: &str) -> Option<f64> {
194 self.0.get(name).copied()
195 }
196
197 pub fn require(&self, name: &str) -> Result<f64, Error> {
203 self.get(name).ok_or_else(|| Error::Invalid {
204 field: format!("thresholds.{name}"),
205 reason: "no threshold configured for this name".to_string(),
206 })
207 }
208}
209
210fn validate_threshold(value: f64) -> Result<(), Error> {
212 if !value.is_finite() || !(0.0..=1.0).contains(&value) {
213 return Err(Error::Invalid {
214 field: "threshold".to_string(),
215 reason: format!("must be finite and within 0.0..=1.0, got {value}"),
216 });
217 }
218 Ok(())
219}
220
221impl<'de> Deserialize<'de> for Thresholds {
222 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
223 where
224 D: Deserializer<'de>,
225 {
226 let map = HashMap::<String, f64>::deserialize(deserializer)?;
227 let mut thresholds = Thresholds::new();
228 for (name, value) in map {
229 thresholds.insert(name, value).map_err(D::Error::custom)?;
230 }
231 Ok(thresholds)
232 }
233}
234
235#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
270#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
271pub struct Config {
272 pub provider: Provider,
274 #[serde(with = "model_as_string")]
276 pub model: Model,
277 pub surface: Surface,
279 #[serde(skip_serializing_if = "Option::is_none")]
281 pub api_base: Option<url::Url>,
282 #[serde(with = "duration_millis", rename = "timeoutMs")]
284 pub timeout: Duration,
285 pub retry: RetryConfig,
287 pub thresholds: Thresholds,
289 pub context_check: bool,
291 #[serde(skip_serializing_if = "Option::is_none")]
294 pub default_session_id: Option<String>,
295 #[serde(skip_serializing_if = "Option::is_none")]
298 pub default_user: Option<String>,
299}
300
301impl Default for Config {
302 fn default() -> Self {
303 Config {
304 provider: Provider::default(),
305 model: DEFAULT_MODEL,
306 surface: Surface::default(),
307 api_base: None,
308 timeout: DEFAULT_TIMEOUT,
309 retry: RetryConfig::default(),
310 thresholds: Thresholds::default(),
311 context_check: true,
312 default_session_id: None,
313 default_user: None,
314 }
315 }
316}
317
318mod model_as_string {
320 use serde::{Deserialize, Deserializer, Serializer};
321
322 use super::{FromStr, Model};
323
324 pub(super) fn serialize<S: Serializer>(m: &Model, s: S) -> Result<S::Ok, S::Error> {
325 s.serialize_str(&m.to_string())
326 }
327
328 pub(super) fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Model, D::Error> {
329 let s = String::deserialize(d)?;
330 Model::from_str(&s).map_err(serde::de::Error::custom)
331 }
332}
333
334#[cfg(test)]
335mod tests {
336 use super::*;
337
338 #[test]
339 fn test_should_default_config_to_pinned_model_and_decisions_surface() {
340 let config = Config::default();
341 assert_eq!(config.model, DEFAULT_MODEL);
342 assert_eq!(config.provider, Provider::OpenRouter);
343 assert_eq!(config.surface, Surface::Decisions);
344 assert!(config.context_check);
345 }
346
347 #[test]
348 fn test_should_deserialize_config_from_yaml() {
349 let yaml = r#"
350model: typesafe/jev-1.13
351surface: systemOne
352timeoutMs: 5000
353retry:
354 maxAttempts: 5
355 initialBackoffMs: 100
356 maxBackoffMs: 1000
357thresholds:
358 isBugYes: 0.9
359contextCheck: false
360"#;
361 let config: Config = serde_norway::from_str(yaml).unwrap();
362 assert_eq!(config.model, Model::Jev113);
363 assert_eq!(config.surface, Surface::SystemOne);
364 assert_eq!(config.timeout, Duration::from_millis(5000));
365 assert_eq!(config.retry.max_attempts, 5);
366 assert_eq!(config.thresholds.get("isBugYes"), Some(0.9));
367 assert!(!config.context_check);
368 }
369
370 #[test]
371 fn test_should_reject_unknown_config_field() {
372 let yaml = "model: jev-1.13\nbogusField: 1\n";
373 assert!(serde_norway::from_str::<Config>(yaml).is_err());
374 }
375
376 #[test]
377 fn test_should_reject_out_of_range_threshold_in_config() {
378 let yaml = "thresholds:\n bad: 1.5\n";
379 assert!(serde_norway::from_str::<Config>(yaml).is_err());
380 }
381
382 #[test]
383 fn test_should_reject_out_of_range_threshold_on_insert() {
384 let mut thresholds = Thresholds::new();
385 assert!(thresholds.insert("bad", 1.5).is_err());
386 assert!(thresholds.insert("bad", f64::NAN).is_err());
387 assert!(thresholds.insert("good", 0.5).is_ok());
388 }
389
390 #[test]
391 fn test_should_require_return_error_for_missing_threshold() {
392 let thresholds = Thresholds::new();
393 assert!(matches!(
394 thresholds.require("missing"),
395 Err(Error::Invalid { .. })
396 ));
397 }
398
399 #[test]
400 fn test_should_build_retry_config_via_builder_methods() {
401 let retry = RetryConfig::default()
402 .with_max_attempts(5)
403 .with_initial_backoff(Duration::from_millis(50))
404 .with_max_backoff(Duration::from_secs(1));
405 assert_eq!(retry.max_attempts, 5);
406 assert_eq!(retry.initial_backoff, Duration::from_millis(50));
407 assert_eq!(retry.max_backoff, Duration::from_secs(1));
408 }
409
410 #[test]
411 fn test_should_disable_retry_with_one_attempt() {
412 assert_eq!(RetryConfig::disabled().max_attempts, 1);
413 }
414
415 #[test]
416 fn test_surface_path_matches_documented_endpoints() {
417 assert_eq!(Surface::Decisions.path(), "/api/alpha/decisions");
418 assert_eq!(Surface::SystemOne.path(), "/api/v1/systemone");
419 }
420}