Skip to main content

docsrs_cli/
config.rs

1//! Configuration: defaults, XDG TOML, env allowlist, CLI override.
2
3use std::fs;
4use std::io::Write;
5use std::path::{Path, PathBuf};
6use std::time::Duration;
7
8use directories::ProjectDirs;
9use serde::{Deserialize, Serialize};
10
11use crate::error::{AppError, AppResult, ErrorKind};
12use crate::platform::{restrict_private_dir, restrict_private_file};
13
14/// Default wall-clock timeout (seconds) for one operation.
15pub const DEFAULT_TIMEOUT_SECS: u64 = 30;
16/// Default TCP connect timeout (seconds).
17pub const DEFAULT_CONNECT_TIMEOUT_SECS: u64 = 10;
18/// Default maximum downloaded response body size (bytes).
19pub const DEFAULT_MAX_BODY_BYTES: u64 = 10_485_760;
20/// Hard ceiling for HTTP body size (CLI / TOML / env cannot raise above this).
21///
22/// Equal to [`DEFAULT_MAX_BODY_BYTES`] so operators may only lower the cap.
23/// Prevents multi-GiB allocations from untrusted Content-Length or config.
24pub const HARD_MAX_BODY_BYTES: u64 = DEFAULT_MAX_BODY_BYTES;
25/// Default maximum emitted stdout payload size (bytes).
26pub const DEFAULT_MAX_OUTPUT_BYTES: u64 = 2_097_152;
27/// Hard ceiling for emitted stdout payload size (CLI / TOML / env cannot raise above).
28pub const HARD_MAX_OUTPUT_BYTES: u64 = DEFAULT_MAX_OUTPUT_BYTES;
29/// Default maximum HTTP redirects followed.
30pub const DEFAULT_MAX_REDIRECTS: u32 = 5;
31/// Default maximum retries for transient HTTP errors.
32pub const DEFAULT_MAX_RETRIES: u32 = crate::retry::DEFAULT_MAX_RETRIES;
33/// Base backoff delay (milliseconds) for retries.
34pub const DEFAULT_RETRY_BASE_MS: u64 = crate::retry::DEFAULT_RETRY_BASE_MS;
35/// Default ceiling for a single retry sleep (milliseconds).
36pub const DEFAULT_RETRY_MAX_DELAY_MS: u64 = crate::retry::DEFAULT_RETRY_MAX_DELAY_MS;
37/// Default minimum delay between requests to the same host (milliseconds).
38pub const DEFAULT_RATE_LIMIT_DELAY_MS: u64 = 1000;
39/// Default `per_page` for crates.io search.
40pub const DEFAULT_PER_PAGE: u32 = 10;
41/// Default hit limit for search-in-crate.
42pub const DEFAULT_SEARCH_LIMIT: u32 = 100;
43/// Maximum `per_page` accepted for crates.io search.
44pub const MAX_PER_PAGE: u32 = 100;
45/// Maximum hit limit for search-in-crate.
46pub const MAX_SEARCH_IN_CRATE_LIMIT: u32 = 1000;
47/// Maximum query string length.
48pub const MAX_QUERY_CHARS: usize = 256;
49/// Maximum crate name length.
50pub const MAX_CRATE_NAME_CHARS: usize = 64;
51/// Maximum rustdoc item path length.
52pub const MAX_ITEM_PATH_CHARS: usize = 512;
53/// Maximum version string length.
54pub const MAX_VERSION_CHARS: usize = 64;
55/// Maximum User-Agent length.
56pub const MAX_USER_AGENT_CHARS: usize = 256;
57/// Default HTTP disk cache TTL (seconds).
58pub const DEFAULT_CACHE_TTL_SECS: u64 = crate::cache::DEFAULT_CACHE_TTL_SECS;
59/// Default HTTP disk cache budget in bytes (256 MiB). `0` = unlimited.
60pub const DEFAULT_MAX_CACHE_BYTES: u64 = crate::cache::DEFAULT_MAX_CACHE_BYTES;
61/// Product binary / crate name.
62pub const APP_NAME: &str = "docsrs-cli";
63/// Package version from Cargo.
64pub const APP_VERSION: &str = env!("CARGO_PKG_VERSION");
65/// Minimum supported Rust version.
66pub const MSRV: &str = "1.88.0";
67/// JSON envelope `schema_version` constant.
68pub const SCHEMA_VERSION: u32 = 1;
69
70/// crates.io host allowlist entry.
71pub const HOST_CRATES_IO: &str = "crates.io";
72/// docs.rs host allowlist entry.
73pub const HOST_DOCS_RS: &str = "docs.rs";
74/// static.docs.rs host allowlist entry (redirects).
75pub const HOST_STATIC_DOCS_RS: &str = "static.docs.rs";
76/// Official stdlib rustdoc host (`std` / `core` / `alloc`).
77pub const HOST_DOC_RUST_LANG_ORG: &str = "doc.rust-lang.org";
78
79/// Which layer won when resolving a storage path (XDG hierarchy diagnostics).
80///
81/// Product has no API keys; layers for OS keyring / cloud secret managers are
82/// out of scope. Precedence for paths: CLI/env dir override → `DOCSRS_CLI_HOME`
83/// sandbox → `ProjectDirs` XDG/AppData/Library.
84#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
85#[serde(rename_all = "kebab-case")]
86pub enum PathSource {
87    /// `--config-dir` / `--cache-dir` or clap env aliases for those flags.
88    CliOrEnv,
89    /// `{DOCSRS_CLI_HOME}/config` or `{DOCSRS_CLI_HOME}/cache`.
90    HomeSandbox,
91    /// `directories::ProjectDirs` platform defaults.
92    Xdg,
93    /// No path could be resolved.
94    #[default]
95    Unresolved,
96}
97
98impl PathSource {
99    /// Stable machine token for doctor / config path JSON.
100    pub const fn as_str(self) -> &'static str {
101        match self {
102            Self::CliOrEnv => "cli-or-env",
103            Self::HomeSandbox => "home-sandbox",
104            Self::Xdg => "xdg",
105            Self::Unresolved => "unresolved",
106        }
107    }
108}
109
110/// Default `config.toml` body written by `config init` (commented template).
111///
112/// Values are documentation only until the user uncomments. Runtime still
113/// applies defaults when keys are absent. No secrets — product is public HTTP.
114pub const DEFAULT_CONFIG_TOML: &str = r#"# docsrs-cli XDG configuration
115# Precedence: CLI flags > this file (XDG) > built-in defaults.
116# Path: /docsrs-cli/config.toml (or platform equivalent).
117# No .env file is required after cargo install. Product stores no API keys.
118# Product settings are NOT read from DOCSRS_CLI_* environment variables.
119#
120# timeout_secs = 30
121# connect_timeout_secs = 10
122# max_body_bytes = 10485760
123# max_output_bytes = 2097152
124# max_redirects = 5
125# max_retries = 3
126# retry_base_ms = 200
127# retry_max_delay_ms = 30000
128# disable_retry = false
129# rate_limit_delay_ms = 1000
130# max_concurrency = 0
131# user_agent = "docsrs-cli/0.1.2 (+https://github.com/danilo-aguiar-br/docsrs-cli)"
132# contact = "https://github.com/danilo-aguiar-br/docsrs-cli"
133# lang = "en"
134# crates_io_origin = "https://crates.io"
135# docs_rs_origin = "https://docs.rs"
136# cache_ttl_secs = 86400
137# max_cache_bytes = 268435456
138# no_cache = false
139"#;
140
141/// Runtime configuration resolved from defaults, XDG TOML, env, and CLI.
142#[derive(Debug, Clone, Serialize, Deserialize)]
143pub struct Config {
144    /// Wall-clock timeout in seconds for one operation.
145    pub timeout_secs: u64,
146    /// TCP connect timeout in seconds.
147    pub connect_timeout_secs: u64,
148    /// Maximum downloaded HTTP body size in bytes.
149    pub max_body_bytes: u64,
150    /// Maximum emitted stdout payload size in bytes.
151    pub max_output_bytes: u64,
152    /// Maximum HTTP redirects followed.
153    pub max_redirects: u32,
154    /// Maximum retries for transient HTTP errors.
155    pub max_retries: u32,
156    /// Base backoff delay in milliseconds between retries.
157    pub retry_base_ms: u64,
158    /// Ceiling for a single retry sleep in milliseconds.
159    pub retry_max_delay_ms: u64,
160    /// Kill switch: when true, HTTP never retries (incident / debug).
161    pub disable_retry: bool,
162    /// Minimum delay between requests to the same host in milliseconds.
163    pub rate_limit_delay_ms: u64,
164    /// Max concurrent CPU (`spawn_blocking`) tasks; `0` = auto from CPUs/RAM.
165    ///
166    /// See [`crate::concurrency::resolve_max_concurrency`].
167    pub max_concurrency: u32,
168    /// HTTP User-Agent header value.
169    pub user_agent: String,
170    /// Optional contact URL or email embedded in the default User-Agent.
171    pub contact: Option<String>,
172    /// Preferred human-message locale (`en` or `pt-BR`).
173    pub lang: Option<String>,
174    /// Resolved XDG (or override) config directory.
175    pub config_dir: Option<PathBuf>,
176    /// XDG (or override) root for HTTP response cache between process runs.
177    pub cache_dir: Option<PathBuf>,
178    /// Disk cache TTL in seconds (default 24h).
179    pub cache_ttl_secs: u64,
180    /// Soft cap on disk cache size in bytes (`0` = unlimited).
181    pub max_cache_bytes: u64,
182    /// When true, skip disk cache read/write (`--no-cache`).
183    pub no_cache: bool,
184    /// Origin for crates.io API (default `https://crates.io`). Overridable for offline mocks.
185    pub crates_io_origin: String,
186    /// Origin for docs.rs pages (default `https://docs.rs`). Overridable for offline mocks.
187    pub docs_rs_origin: String,
188    /// Layer that resolved [`Self::config_dir`].
189    pub config_path_source: PathSource,
190    /// Layer that resolved [`Self::cache_dir`].
191    pub cache_path_source: PathSource,
192    /// True when `config.toml` existed and was applied during load.
193    pub config_toml_loaded: bool,
194}
195
196impl Default for Config {
197    fn default() -> Self {
198        // Contact comes from TOML `contact` or CLI `--user-agent`, not process env.
199        let contact: Option<String> = None;
200        let ua = default_user_agent(contact.as_deref());
201        Self {
202            timeout_secs: DEFAULT_TIMEOUT_SECS,
203            connect_timeout_secs: DEFAULT_CONNECT_TIMEOUT_SECS,
204            max_body_bytes: DEFAULT_MAX_BODY_BYTES,
205            max_output_bytes: DEFAULT_MAX_OUTPUT_BYTES,
206            max_redirects: DEFAULT_MAX_REDIRECTS,
207            max_retries: DEFAULT_MAX_RETRIES,
208            retry_base_ms: DEFAULT_RETRY_BASE_MS,
209            retry_max_delay_ms: DEFAULT_RETRY_MAX_DELAY_MS,
210            disable_retry: false,
211            rate_limit_delay_ms: DEFAULT_RATE_LIMIT_DELAY_MS,
212            max_concurrency: 0,
213            user_agent: ua,
214            contact,
215            lang: None,
216            config_dir: None,
217            cache_dir: None,
218            cache_ttl_secs: DEFAULT_CACHE_TTL_SECS,
219            max_cache_bytes: DEFAULT_MAX_CACHE_BYTES,
220            no_cache: false,
221            crates_io_origin: format!("https://{HOST_CRATES_IO}"),
222            docs_rs_origin: format!("https://{HOST_DOCS_RS}"),
223            config_path_source: PathSource::Unresolved,
224            cache_path_source: PathSource::Unresolved,
225            config_toml_loaded: false,
226        }
227    }
228}
229
230/// Builds the default User-Agent, optionally including a contact token.
231pub fn default_user_agent(contact: Option<&str>) -> String {
232    match contact {
233        Some(c) if !c.is_empty() => {
234            if c.starts_with("http://") || c.starts_with("https://") {
235                format!("{APP_NAME}/{APP_VERSION} (+{c})")
236            } else {
237                format!("{APP_NAME}/{APP_VERSION} ({c})")
238            }
239        }
240        _ => format!("{APP_NAME}/{APP_VERSION} (+https://github.com/danilo-aguiar-br/docsrs-cli)"),
241    }
242}
243
244/// Strip trailing slash from an origin base URL.
245pub fn normalize_origin(raw: &str) -> String {
246    raw.trim().trim_end_matches('/').to_string()
247}
248
249#[derive(Debug, Default, Deserialize)]
250struct TomlConfig {
251    timeout_secs: Option<u64>,
252    connect_timeout_secs: Option<u64>,
253    max_body_bytes: Option<u64>,
254    max_output_bytes: Option<u64>,
255    max_redirects: Option<u32>,
256    max_retries: Option<u32>,
257    retry_base_ms: Option<u64>,
258    retry_max_delay_ms: Option<u64>,
259    disable_retry: Option<bool>,
260    rate_limit_delay_ms: Option<u64>,
261    max_concurrency: Option<u32>,
262    user_agent: Option<String>,
263    contact: Option<String>,
264    lang: Option<String>,
265    crates_io_origin: Option<String>,
266    docs_rs_origin: Option<String>,
267    cache_ttl_secs: Option<u64>,
268    max_cache_bytes: Option<u64>,
269    no_cache: Option<bool>,
270}
271
272impl Config {
273    /// Loads configuration with an optional config-directory override.
274    ///
275    /// # Errors
276    ///
277    /// Returns [`ErrorKind::Config`] when the TOML file is unreadable or invalid.
278    pub fn load(config_dir_override: Option<PathBuf>) -> AppResult<Self> {
279        Self::load_with_cache_dir(config_dir_override, None)
280    }
281
282    /// Load config with optional config-dir and cache-dir overrides (CLI / tests).
283    ///
284    /// # Errors
285    ///
286    /// Returns [`ErrorKind::Config`] when `config.toml` is unreadable or invalid TOML.
287    pub fn load_with_cache_dir(
288        config_dir_override: Option<PathBuf>,
289        cache_dir_override: Option<PathBuf>,
290    ) -> AppResult<Self> {
291        let mut cfg = Self::default();
292
293        let (config_dir, config_source) = resolve_config_dir_with_source(config_dir_override);
294        cfg.config_path_source = config_source;
295
296        let (cache_dir, cache_source) =
297            crate::cache::resolve_cache_dir_with_source(cache_dir_override);
298        cfg.cache_dir = cache_dir;
299        cfg.cache_path_source = cache_source;
300
301        // Borrow for TOML load, then move into `cfg` (no PathBuf clone).
302        if let Some(dir) = &config_dir {
303            let path = dir.join("config.toml");
304            if path.is_file() {
305                let text = fs::read_to_string(&path).map_err(|e| {
306                    AppError::with_source(
307                        ErrorKind::Config,
308                        format!("failed to read {}", path.display()),
309                        e,
310                    )
311                })?;
312                let parsed: TomlConfig = toml::from_str(&text).map_err(|e| {
313                    AppError::with_source(ErrorKind::Config, "invalid config.toml", e)
314                })?;
315                cfg.apply_toml(parsed);
316                cfg.config_toml_loaded = true;
317            }
318        }
319        cfg.config_dir = config_dir;
320
321        cfg.apply_env()?;
322        cfg.clamp_resource_limits();
323        Ok(cfg)
324    }
325
326    /// Absolute path to `config.toml` under the resolved config directory, if any.
327    pub fn config_file_path(&self) -> Option<PathBuf> {
328        self.config_dir.as_ref().map(|d| d.join("config.toml"))
329    }
330
331    /// Clamp body/output budgets so config, env, or CLI cannot force multi-GiB allocs.
332    ///
333    /// Call after every mutation path (TOML, env, CLI). Values above the hard
334    /// ceilings are silently reduced to [`HARD_MAX_BODY_BYTES`] /
335    /// [`HARD_MAX_OUTPUT_BYTES`]. Zero is left as-is (fail-closed for body reads).
336    pub fn clamp_resource_limits(&mut self) {
337        self.max_body_bytes = self.max_body_bytes.min(HARD_MAX_BODY_BYTES);
338        self.max_output_bytes = self.max_output_bytes.min(HARD_MAX_OUTPUT_BYTES);
339        self.max_retries = self.max_retries.min(crate::retry::HARD_MAX_RETRIES);
340        if self.retry_base_ms == 0 {
341            self.retry_base_ms = DEFAULT_RETRY_BASE_MS;
342        }
343        if self.retry_max_delay_ms == 0 {
344            self.retry_max_delay_ms = DEFAULT_RETRY_MAX_DELAY_MS;
345        }
346        self.retry_max_delay_ms = self
347            .retry_max_delay_ms
348            .min(crate::retry::HARD_MAX_DELAY_MS)
349            .max(self.retry_base_ms);
350    }
351
352    fn apply_toml(&mut self, t: TomlConfig) {
353        if let Some(v) = t.timeout_secs {
354            self.timeout_secs = v;
355        }
356        if let Some(v) = t.connect_timeout_secs {
357            self.connect_timeout_secs = v;
358        }
359        if let Some(v) = t.max_body_bytes {
360            self.max_body_bytes = v;
361        }
362        if let Some(v) = t.max_output_bytes {
363            self.max_output_bytes = v;
364        }
365        if let Some(v) = t.max_redirects {
366            self.max_redirects = v;
367        }
368        if let Some(v) = t.max_retries {
369            self.max_retries = v;
370        }
371        if let Some(v) = t.retry_base_ms {
372            self.retry_base_ms = v;
373        }
374        if let Some(v) = t.retry_max_delay_ms {
375            self.retry_max_delay_ms = v;
376        }
377        if let Some(v) = t.disable_retry {
378            self.disable_retry = v;
379        }
380        if let Some(v) = t.rate_limit_delay_ms {
381            self.rate_limit_delay_ms = v;
382        }
383        if let Some(v) = t.max_concurrency {
384            self.max_concurrency = v;
385        }
386        if let Some(v) = t.contact {
387            self.contact = Some(v);
388        }
389        if let Some(v) = t.user_agent {
390            self.user_agent = v;
391        } else if let Some(c) = &self.contact {
392            self.user_agent = default_user_agent(Some(c));
393        }
394        if let Some(v) = t.lang {
395            self.lang = Some(v);
396        }
397        if let Some(v) = t.crates_io_origin {
398            self.crates_io_origin = normalize_origin(&v);
399        }
400        if let Some(v) = t.docs_rs_origin {
401            self.docs_rs_origin = normalize_origin(&v);
402        }
403        if let Some(v) = t.cache_ttl_secs {
404            self.cache_ttl_secs = v;
405        }
406        if let Some(v) = t.max_cache_bytes {
407            self.max_cache_bytes = v;
408        }
409        if let Some(v) = t.no_cache {
410            self.no_cache = v;
411        }
412    }
413
414    /// Resolve cache path when still unset (XDG / test sandbox).
415    ///
416    /// Product knobs are **not** read from `DOCSRS_CLI_*` environment variables
417    /// (flags + XDG TOML only). Path sandbox `DOCSRS_CLI_HOME` remains available
418    /// for tests via [`crate::cache::resolve_cache_dir_with_source`].
419    fn apply_env(&mut self) -> AppResult<()> {
420        if self.cache_dir.is_none() {
421            let (dir, source) = crate::cache::resolve_cache_dir_with_source(None);
422            self.cache_dir = dir;
423            self.cache_path_source = source;
424        }
425        Ok(())
426    }
427}
428
429/// Resolve config directory: CLI/env override, then `DOCSRS_CLI_HOME/config`, then XDG.
430///
431/// Precedence:
432/// 1. Explicit override (`--config-dir` / `DOCSRS_CLI_CONFIG_DIR`)
433/// 2. `{DOCSRS_CLI_HOME}/config` when `DOCSRS_CLI_HOME` is set (sandbox / tests)
434/// 3. `directories::ProjectDirs` config dir (platform XDG / AppData / Library)
435pub fn resolve_config_dir(override_dir: Option<PathBuf>) -> Option<PathBuf> {
436    resolve_config_dir_with_source(override_dir).0
437}
438
439/// Resolve config directory and report which layer won.
440pub fn resolve_config_dir_with_source(
441    override_dir: Option<PathBuf>,
442) -> (Option<PathBuf>, PathSource) {
443    if let Some(p) = override_dir {
444        return (Some(p), PathSource::CliOrEnv);
445    }
446    if let Some(p) = std::env::var_os("DOCSRS_CLI_CONFIG_DIR") {
447        return (Some(PathBuf::from(p)), PathSource::CliOrEnv);
448    }
449    if let Some(p) = home_config_dir() {
450        return (Some(p), PathSource::HomeSandbox);
451    }
452    if let Some(p) = ProjectDirs::from("", "", APP_NAME).map(|d| d.config_dir().to_path_buf()) {
453        return (Some(p), PathSource::Xdg);
454    }
455    (None, PathSource::Unresolved)
456}
457
458/// `{DOCSRS_CLI_HOME}/config` when the home override is set.
459fn home_config_dir() -> Option<PathBuf> {
460    std::env::var_os("DOCSRS_CLI_HOME").map(|h| PathBuf::from(h).join("config"))
461}
462
463/// Result of `config init`.
464#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
465pub struct ConfigInitResult {
466    /// Absolute path written (or already present when not forced).
467    pub path: String,
468    /// Directory that holds the file.
469    pub config_dir: String,
470    /// Layer that resolved the directory.
471    pub source: PathSource,
472    /// True when the file was created or overwritten in this call.
473    pub created: bool,
474    /// True when an existing file was replaced (`--force`).
475    pub overwritten: bool,
476}
477
478/// Create default `config.toml` under the resolved config directory.
479///
480/// # Errors
481///
482/// - [`ErrorKind::Config`] when the directory cannot be resolved or created,
483///   when the file already exists without `force`, or on I/O failure.
484pub fn init_config_toml(
485    config_dir_override: Option<PathBuf>,
486    force: bool,
487) -> AppResult<ConfigInitResult> {
488    let (dir, source) = resolve_config_dir_with_source(config_dir_override);
489    let dir = dir.ok_or_else(|| {
490        AppError::new(
491            ErrorKind::Config,
492            "config directory could not be resolved (set --config-dir or DOCSRS_CLI_CONFIG_DIR)",
493        )
494    })?;
495    fs::create_dir_all(&dir).map_err(|e| {
496        AppError::with_source(
497            ErrorKind::Config,
498            format!("failed to create config dir {}", dir.display()),
499            e,
500        )
501    })?;
502    restrict_private_dir(&dir);
503
504    let path = dir.join("config.toml");
505    let existed = path.is_file();
506    if existed && !force {
507        return Err(AppError::new(
508            ErrorKind::Config,
509            format!(
510                "config already exists: {} (pass --force to overwrite)",
511                path.display()
512            ),
513        ));
514    }
515
516    // Atomic-ish write: tempfile in same dir then rename.
517    let tmp = dir.join("config.toml.docsrs-cli.tmp");
518    {
519        let mut f = fs::File::create(&tmp).map_err(|e| {
520            AppError::with_source(
521                ErrorKind::Config,
522                format!("failed to create {}", tmp.display()),
523                e,
524            )
525        })?;
526        f.write_all(DEFAULT_CONFIG_TOML.as_bytes()).map_err(|e| {
527            AppError::with_source(
528                ErrorKind::Config,
529                format!("failed to write {}", tmp.display()),
530                e,
531            )
532        })?;
533        f.sync_all().map_err(|e| {
534            AppError::with_source(
535                ErrorKind::Config,
536                format!("failed to sync {}", tmp.display()),
537                e,
538            )
539        })?;
540    }
541    restrict_private_file(&tmp);
542    fs::rename(&tmp, &path).map_err(|e| {
543        let _ = fs::remove_file(&tmp);
544        AppError::with_source(
545            ErrorKind::Config,
546            format!("failed to install {}", path.display()),
547            e,
548        )
549    })?;
550    restrict_private_file(&path);
551
552    Ok(ConfigInitResult {
553        path: path.display().to_string(),
554        config_dir: dir.display().to_string(),
555        source,
556        created: true,
557        overwritten: existed,
558    })
559}
560
561/// Path inventory for `config path` (agent-readable).
562#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
563pub struct ConfigPathData {
564    /// Resolved config directory, if any.
565    pub config_dir: Option<String>,
566    /// Layer that resolved the config directory.
567    pub config_source: PathSource,
568    /// Absolute `config.toml` path (even if the file does not exist yet).
569    pub config_file: Option<String>,
570    /// Whether `config.toml` is present on disk.
571    pub config_file_exists: bool,
572    /// Whether load applied TOML keys (same as exists for normal runs).
573    pub config_toml_loaded: bool,
574    /// Resolved cache directory, if any.
575    pub cache_dir: Option<String>,
576    /// Layer that resolved the cache directory.
577    pub cache_source: PathSource,
578    /// Product does not use `.env` at runtime after install.
579    pub dotenv_runtime: bool,
580    /// Product stores no API keys; keyring/cloud secret layers are unused.
581    pub secrets_layers: &'static str,
582}
583
584/// Build path inventory from a loaded [`Config`].
585pub fn config_path_data(cfg: &Config) -> ConfigPathData {
586    let config_file = cfg.config_file_path();
587    let exists = config_file.as_ref().is_some_and(|p| p.is_file());
588    ConfigPathData {
589        config_dir: cfg.config_dir.as_ref().map(|p| p.display().to_string()),
590        config_source: cfg.config_path_source,
591        config_file: config_file.as_ref().map(|p| p.display().to_string()),
592        config_file_exists: exists,
593        config_toml_loaded: cfg.config_toml_loaded,
594        cache_dir: cfg.cache_dir.as_ref().map(|p| p.display().to_string()),
595        cache_source: cfg.cache_path_source,
596        dotenv_runtime: false,
597        secrets_layers: "none (public HTTP only; no API keys)",
598    }
599}
600
601/// Ensure `path` is under a directory (used by tests / path display).
602pub fn config_toml_under(dir: &Path) -> PathBuf {
603    dir.join("config.toml")
604}
605
606impl Config {
607    /// Wall-clock timeout duration (at least one second).
608    pub fn timeout(&self) -> Duration {
609        Duration::from_secs(self.timeout_secs.max(1))
610    }
611
612    /// TCP connect timeout duration (at least one second).
613    pub fn connect_timeout(&self) -> Duration {
614        Duration::from_secs(self.connect_timeout_secs.max(1))
615    }
616
617    /// Per-host rate-limit delay duration.
618    pub fn rate_limit_delay(&self) -> Duration {
619        Duration::from_millis(self.rate_limit_delay_ms)
620    }
621
622    /// TTL for disk cache entries.
623    pub fn cache_ttl(&self) -> Duration {
624        Duration::from_secs(self.cache_ttl_secs)
625    }
626
627    /// Whether disk cache should be used for HTTP GET bodies.
628    pub fn cache_enabled(&self) -> bool {
629        !self.no_cache && self.cache_dir.is_some()
630    }
631}
632
633/// Validate crate name (compat wrapper over [`crate::domain::CrateName::parse`]).
634///
635/// # Errors
636///
637/// Propagates [`ErrorKind::InvalidInput`] from [`crate::domain::CrateName::parse`].
638pub fn validate_crate_name(name: &str) -> AppResult<()> {
639    crate::domain::CrateName::parse(name).map(|_| ())
640}
641
642/// True for Rust standard library crates documented on `doc.rust-lang.org`.
643pub fn is_stdlib_crate(name: &str) -> bool {
644    matches!(name, "std" | "core" | "alloc")
645}
646
647/// Resolve docs origin for a crate: stdlib → doc.rust-lang.org, else configured docs.rs origin.
648pub fn docs_origin_for_crate(cfg: &Config, crate_name: &str) -> String {
649    if is_stdlib_crate(crate_name) {
650        format!("https://{HOST_DOC_RUST_LANG_ORG}")
651    } else {
652        cfg.docs_rs_origin.clone()
653    }
654}
655
656/// Map CLI version token to a rustdoc channel for stdlib paths.
657///
658/// `latest` → `stable`. Accepts `stable` / `beta` / `nightly` and other path-safe tokens.
659pub fn stdlib_channel(version: &str) -> &str {
660    match version {
661        "latest" => "stable",
662        other => other,
663    }
664}
665
666/// Validate search query (compat wrapper over [`crate::domain::SearchQuery::parse`]).
667///
668/// # Errors
669///
670/// Propagates [`ErrorKind::InvalidInput`] from [`crate::domain::SearchQuery::parse`].
671pub fn validate_query(query: &str, allow_empty: bool) -> AppResult<()> {
672    crate::domain::SearchQuery::parse(query, allow_empty).map(|_| ())
673}
674
675/// Validate item path (compat wrapper over [`crate::domain::ItemPath::parse`]).
676///
677/// # Errors
678///
679/// Propagates [`ErrorKind::InvalidInput`] from [`crate::domain::ItemPath::parse`].
680pub fn validate_item_path(path: &str) -> AppResult<Vec<String>> {
681    crate::domain::ItemPath::parse(path).map(|p| p.into_segments())
682}
683
684/// Resolve version argument: `latest` or SemVer without `v` prefix / build metadata.
685///
686/// # Errors
687///
688/// Propagates [`ErrorKind::InvalidInput`] from [`crate::domain::VersionArg::parse_opt`].
689pub fn resolve_version_arg(raw: Option<&str>) -> AppResult<String> {
690    crate::domain::VersionArg::parse_opt(raw).map(|v| v.as_str().to_string())
691}
692
693#[cfg(test)]
694mod tests {
695    use super::*;
696    use std::fs;
697    use std::io::Write;
698
699    #[test]
700    fn crate_name_rules() {
701        assert!(validate_crate_name("serde").is_ok());
702        assert!(validate_crate_name("async-trait").is_ok());
703        // std/core/alloc are valid; docs are fetched from doc.rust-lang.org.
704        assert!(validate_crate_name("std").is_ok());
705        assert!(validate_crate_name("core").is_ok());
706        assert!(validate_crate_name("alloc").is_ok());
707        assert!(is_stdlib_crate("std"));
708        assert!(!is_stdlib_crate("serde"));
709        assert!(validate_crate_name("").is_err());
710        assert!(validate_crate_name("1bad").is_err());
711        assert!(validate_crate_name(&"a".repeat(MAX_CRATE_NAME_CHARS + 1)).is_err());
712    }
713
714    #[test]
715    fn version_policy() {
716        assert_eq!(resolve_version_arg(None).unwrap(), "latest");
717        assert_eq!(resolve_version_arg(Some("")).unwrap(), "latest");
718        assert_eq!(resolve_version_arg(Some("1.0.0")).unwrap(), "1.0.0");
719        assert_eq!(
720            resolve_version_arg(Some("1.0.0-rc.1")).unwrap(),
721            "1.0.0-rc.1"
722        );
723        assert!(resolve_version_arg(Some("v1.0.0")).is_err());
724        assert!(resolve_version_arg(Some("1.0.0+build")).is_err());
725        assert!(resolve_version_arg(Some("not-a-version")).is_err());
726    }
727
728    #[test]
729    fn query_and_path_rules() {
730        assert!(validate_query("serde", false).is_ok());
731        assert!(validate_query("", false).is_err());
732        assert!(validate_query("", true).is_ok());
733        assert!(validate_query(&"q".repeat(MAX_QUERY_CHARS + 1), true).is_err());
734        let segs = validate_item_path("clap::Parser").unwrap();
735        assert_eq!(segs, vec!["clap", "Parser"]);
736        assert!(validate_item_path("::").is_err());
737        assert!(validate_item_path("").is_err());
738        assert!(validate_item_path(&format!("a::{}", "b".repeat(MAX_ITEM_PATH_CHARS))).is_err());
739    }
740
741    #[test]
742    fn item_path_accepts_slash_and_rejects_bad_segments() {
743        let segs = validate_item_path("runtime/Runtime").unwrap();
744        assert_eq!(segs, vec!["runtime", "Runtime"]);
745        let mixed = validate_item_path("tokio::runtime/Runtime").unwrap();
746        assert_eq!(mixed, vec!["tokio", "runtime", "Runtime"]);
747        assert_eq!(
748            validate_item_path("async_trait").unwrap(),
749            vec!["async_trait"]
750        );
751        assert!(validate_item_path("has space").is_err());
752        assert!(validate_item_path("foo.bar").is_err());
753        assert!(validate_item_path("..").is_err());
754        assert!(validate_item_path("a/../b").is_err());
755        assert!(validate_item_path("/").is_err());
756    }
757
758    #[test]
759    fn default_user_agent_variants() {
760        let ua = default_user_agent(None);
761        assert!(ua.contains(APP_NAME));
762        let ua2 = default_user_agent(Some("dev@example.com"));
763        assert!(ua2.contains("dev@example.com"));
764        let ua3 = default_user_agent(Some("https://example.com"));
765        assert!(ua3.contains("+https://example.com"));
766    }
767
768    #[test]
769    fn config_load_toml_and_durations() {
770        let dir = tempfile::tempdir().unwrap();
771        let path = dir.path().join("config.toml");
772        let mut f = fs::File::create(&path).unwrap();
773        writeln!(
774            f,
775            "timeout_secs = 12\nrate_limit_delay_ms = 50\ncontact = \"a@b.c\"\ncrates_io_origin = \"http://127.0.0.1:9/\"\ndocs_rs_origin = \"http://127.0.0.1:9/\"\nlang = \"pt-BR\"\nmax_retries = 2\nmax_body_bytes = 1000\nmax_output_bytes = 2000\ncache_ttl_secs = 3600\nno_cache = false\n"
776        )
777        .unwrap();
778        let cache_dir = dir.path().join("cache");
779        let cfg =
780            Config::load_with_cache_dir(Some(dir.path().to_path_buf()), Some(cache_dir.clone()))
781                .unwrap();
782        assert_eq!(cfg.timeout_secs, 12);
783        assert_eq!(cfg.rate_limit_delay_ms, 50);
784        assert!(cfg.user_agent.contains("a@b.c"));
785        assert_eq!(cfg.timeout(), Duration::from_secs(12));
786        assert_eq!(cfg.rate_limit_delay(), Duration::from_millis(50));
787        assert!(cfg.connect_timeout() >= Duration::from_secs(1));
788        assert_eq!(cfg.crates_io_origin, "http://127.0.0.1:9");
789        assert_eq!(cfg.docs_rs_origin, "http://127.0.0.1:9");
790        assert_eq!(cfg.lang.as_deref(), Some("pt-BR"));
791        assert_eq!(cfg.max_retries, 2);
792        assert_eq!(cfg.max_body_bytes, 1000);
793        assert_eq!(cfg.max_output_bytes, 2000);
794        assert_eq!(cfg.cache_ttl_secs, 3600);
795        assert_eq!(cfg.cache_dir.as_deref(), Some(cache_dir.as_path()));
796        assert!(cfg.cache_enabled());
797    }
798
799    #[test]
800    fn config_invalid_toml_errors() {
801        let dir = tempfile::tempdir().unwrap();
802        fs::write(dir.path().join("config.toml"), "timeout_secs = [\n").unwrap();
803        let err = Config::load(Some(dir.path().to_path_buf())).unwrap_err();
804        assert_eq!(err.kind(), ErrorKind::Config);
805    }
806
807    #[test]
808    fn normalize_origin_trims_slash() {
809        assert_eq!(normalize_origin(" https://docs.rs/ "), "https://docs.rs");
810    }
811
812    #[test]
813    fn resolve_config_dir_prefers_explicit_override() {
814        let explicit = PathBuf::from("/tmp/docsrs-cli-explicit-config");
815        let got = resolve_config_dir(Some(explicit.clone()));
816        assert_eq!(got.as_deref(), Some(explicit.as_path()));
817    }
818
819    #[test]
820    fn resolve_cache_dir_home_layout() {
821        // Pure path join contract (no env mutation): HOME root + "cache".
822        let home = PathBuf::from("/tmp/docsrs-cli-home-sandbox");
823        let cache = home.join("cache");
824        assert_eq!(cache.file_name().and_then(|s| s.to_str()), Some("cache"));
825        // resolve_cache_dir with explicit override must win over env/XDG.
826        let got = crate::cache::resolve_cache_dir(Some(cache.clone()));
827        assert_eq!(got.as_deref(), Some(cache.as_path()));
828    }
829
830    #[test]
831    fn config_defaults_positive() {
832        let cfg = Config::default();
833        assert!(cfg.timeout_secs >= 1);
834        assert!(cfg.max_body_bytes > 0);
835        assert!(cfg.user_agent.contains(APP_NAME));
836    }
837
838    #[test]
839    fn clamp_resource_limits_caps_body_and_output() {
840        let mut cfg = Config {
841            max_body_bytes: HARD_MAX_BODY_BYTES.saturating_mul(8),
842            max_output_bytes: HARD_MAX_OUTPUT_BYTES.saturating_mul(8),
843            ..Config::default()
844        };
845        cfg.clamp_resource_limits();
846        assert_eq!(cfg.max_body_bytes, HARD_MAX_BODY_BYTES);
847        assert_eq!(cfg.max_output_bytes, HARD_MAX_OUTPUT_BYTES);
848        // Lowering remains allowed (tests / tight budgets).
849        cfg.max_body_bytes = 64;
850        cfg.max_output_bytes = 32;
851        cfg.clamp_resource_limits();
852        assert_eq!(cfg.max_body_bytes, 64);
853        assert_eq!(cfg.max_output_bytes, 32);
854    }
855
856    #[test]
857    fn toml_cannot_raise_max_body_above_hard_ceiling() {
858        let dir = tempfile::tempdir().unwrap();
859        let path = dir.path().join("config.toml");
860        let huge_body = HARD_MAX_BODY_BYTES.saturating_mul(10);
861        let huge_out = HARD_MAX_OUTPUT_BYTES.saturating_mul(10);
862        fs::write(
863            &path,
864            format!("max_body_bytes = {huge_body}\nmax_output_bytes = {huge_out}\n"),
865        )
866        .unwrap();
867        let cfg = Config::load(Some(dir.path().to_path_buf())).unwrap();
868        assert_eq!(cfg.max_body_bytes, HARD_MAX_BODY_BYTES);
869        assert_eq!(cfg.max_output_bytes, HARD_MAX_OUTPUT_BYTES);
870    }
871
872    #[test]
873    fn hard_ceilings_equal_defaults() {
874        // Product policy: operators may only lower body/output caps, never raise.
875        assert_eq!(HARD_MAX_BODY_BYTES, DEFAULT_MAX_BODY_BYTES);
876        assert_eq!(HARD_MAX_OUTPUT_BYTES, DEFAULT_MAX_OUTPUT_BYTES);
877        assert_eq!(Config::default().max_body_bytes, HARD_MAX_BODY_BYTES);
878        assert_eq!(Config::default().max_output_bytes, HARD_MAX_OUTPUT_BYTES);
879    }
880
881    #[test]
882    fn path_source_tokens_are_stable() {
883        assert_eq!(PathSource::CliOrEnv.as_str(), "cli-or-env");
884        assert_eq!(PathSource::HomeSandbox.as_str(), "home-sandbox");
885        assert_eq!(PathSource::Xdg.as_str(), "xdg");
886        assert_eq!(PathSource::Unresolved.as_str(), "unresolved");
887    }
888
889    #[test]
890    fn resolve_config_dir_with_source_reports_cli() {
891        let explicit = PathBuf::from("/tmp/docsrs-cli-src-explicit");
892        let (got, source) = resolve_config_dir_with_source(Some(explicit.clone()));
893        assert_eq!(got.as_deref(), Some(explicit.as_path()));
894        assert_eq!(source, PathSource::CliOrEnv);
895    }
896
897    #[test]
898    fn init_config_toml_creates_and_refuses_without_force() {
899        let dir = tempfile::tempdir().unwrap();
900        let r1 = init_config_toml(Some(dir.path().to_path_buf()), false).unwrap();
901        assert!(r1.created);
902        assert!(!r1.overwritten);
903        assert!(Path::new(&r1.path).is_file());
904        let text = fs::read_to_string(&r1.path).unwrap();
905        assert!(text.contains("docsrs-cli XDG configuration"));
906        assert!(text.contains("No .env file is required"));
907        #[cfg(unix)]
908        {
909            use std::os::unix::fs::PermissionsExt;
910            let mode = fs::metadata(&r1.path).unwrap().permissions().mode() & 0o777;
911            assert_eq!(mode, 0o600);
912        }
913        let err = init_config_toml(Some(dir.path().to_path_buf()), false).unwrap_err();
914        assert_eq!(err.kind(), ErrorKind::Config);
915        let r2 = init_config_toml(Some(dir.path().to_path_buf()), true).unwrap();
916        assert!(r2.created);
917        assert!(r2.overwritten);
918    }
919
920    #[test]
921    fn config_load_marks_toml_loaded() {
922        let dir = tempfile::tempdir().unwrap();
923        fs::write(dir.path().join("config.toml"), "timeout_secs = 9\n").unwrap();
924        let cfg = Config::load(Some(dir.path().to_path_buf())).unwrap();
925        assert!(cfg.config_toml_loaded);
926        assert_eq!(cfg.timeout_secs, 9);
927        assert_eq!(cfg.config_path_source, PathSource::CliOrEnv);
928        let inv = config_path_data(&cfg);
929        assert!(inv.config_file_exists);
930        assert!(!inv.dotenv_runtime);
931    }
932
933    #[test]
934    fn config_load_without_toml_is_not_loaded() {
935        let dir = tempfile::tempdir().unwrap();
936        let cfg = Config::load(Some(dir.path().to_path_buf())).unwrap();
937        assert!(!cfg.config_toml_loaded);
938        assert!(!config_path_data(&cfg).config_file_exists);
939    }
940}