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/1.1.0 (+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!(
241            "{APP_NAME}/{APP_VERSION} (+https://github.com/danilo-aguiar-br/docsrs-cli)"
242        ),
243    }
244}
245
246/// Strip trailing slash from an origin base URL.
247pub fn normalize_origin(raw: &str) -> String {
248    raw.trim().trim_end_matches('/').to_string()
249}
250
251#[derive(Debug, Default, Deserialize)]
252struct TomlConfig {
253    timeout_secs: Option<u64>,
254    connect_timeout_secs: Option<u64>,
255    max_body_bytes: Option<u64>,
256    max_output_bytes: Option<u64>,
257    max_redirects: Option<u32>,
258    max_retries: Option<u32>,
259    retry_base_ms: Option<u64>,
260    retry_max_delay_ms: Option<u64>,
261    disable_retry: Option<bool>,
262    rate_limit_delay_ms: Option<u64>,
263    max_concurrency: Option<u32>,
264    user_agent: Option<String>,
265    contact: Option<String>,
266    lang: Option<String>,
267    crates_io_origin: Option<String>,
268    docs_rs_origin: Option<String>,
269    cache_ttl_secs: Option<u64>,
270    max_cache_bytes: Option<u64>,
271    no_cache: Option<bool>,
272}
273
274impl Config {
275    /// Loads configuration with an optional config-directory override.
276    ///
277    /// # Errors
278    ///
279    /// Returns [`ErrorKind::Config`] when the TOML file is unreadable or invalid.
280    pub fn load(config_dir_override: Option<PathBuf>) -> AppResult<Self> {
281        Self::load_with_cache_dir(config_dir_override, None)
282    }
283
284    /// Load config with optional config-dir and cache-dir overrides (CLI / tests).
285    ///
286    /// # Errors
287    ///
288    /// Returns [`ErrorKind::Config`] when `config.toml` is unreadable or invalid TOML.
289    pub fn load_with_cache_dir(
290        config_dir_override: Option<PathBuf>,
291        cache_dir_override: Option<PathBuf>,
292    ) -> AppResult<Self> {
293        let mut cfg = Self::default();
294
295        let (config_dir, config_source) = resolve_config_dir_with_source(config_dir_override);
296        cfg.config_path_source = config_source;
297
298        let (cache_dir, cache_source) =
299            crate::cache::resolve_cache_dir_with_source(cache_dir_override);
300        cfg.cache_dir = cache_dir;
301        cfg.cache_path_source = cache_source;
302
303        // Borrow for TOML load, then move into `cfg` (no PathBuf clone).
304        if let Some(dir) = &config_dir {
305            let path = dir.join("config.toml");
306            if path.is_file() {
307                let text = fs::read_to_string(&path).map_err(|e| {
308                    AppError::with_source(
309                        ErrorKind::Config,
310                        format!("failed to read {}", path.display()),
311                        e,
312                    )
313                })?;
314                let parsed: TomlConfig = toml::from_str(&text).map_err(|e| {
315                    AppError::with_source(ErrorKind::Config, "invalid config.toml", e)
316                })?;
317                cfg.apply_toml(parsed);
318                cfg.config_toml_loaded = true;
319            }
320        }
321        cfg.config_dir = config_dir;
322
323        cfg.apply_env()?;
324        cfg.clamp_resource_limits();
325        Ok(cfg)
326    }
327
328    /// Absolute path to `config.toml` under the resolved config directory, if any.
329    pub fn config_file_path(&self) -> Option<PathBuf> {
330        self.config_dir.as_ref().map(|d| d.join("config.toml"))
331    }
332
333    /// Clamp body/output budgets so config, env, or CLI cannot force multi-GiB allocs.
334    ///
335    /// Call after every mutation path (TOML, env, CLI). Values above the hard
336    /// ceilings are silently reduced to [`HARD_MAX_BODY_BYTES`] /
337    /// [`HARD_MAX_OUTPUT_BYTES`]. Zero is left as-is (fail-closed for body reads).
338    pub fn clamp_resource_limits(&mut self) {
339        self.max_body_bytes = self.max_body_bytes.min(HARD_MAX_BODY_BYTES);
340        self.max_output_bytes = self.max_output_bytes.min(HARD_MAX_OUTPUT_BYTES);
341        self.max_retries = self.max_retries.min(crate::retry::HARD_MAX_RETRIES);
342        if self.retry_base_ms == 0 {
343            self.retry_base_ms = DEFAULT_RETRY_BASE_MS;
344        }
345        if self.retry_max_delay_ms == 0 {
346            self.retry_max_delay_ms = DEFAULT_RETRY_MAX_DELAY_MS;
347        }
348        self.retry_max_delay_ms = self
349            .retry_max_delay_ms
350            .min(crate::retry::HARD_MAX_DELAY_MS)
351            .max(self.retry_base_ms);
352    }
353
354    fn apply_toml(&mut self, t: TomlConfig) {
355        if let Some(v) = t.timeout_secs {
356            self.timeout_secs = v;
357        }
358        if let Some(v) = t.connect_timeout_secs {
359            self.connect_timeout_secs = v;
360        }
361        if let Some(v) = t.max_body_bytes {
362            self.max_body_bytes = v;
363        }
364        if let Some(v) = t.max_output_bytes {
365            self.max_output_bytes = v;
366        }
367        if let Some(v) = t.max_redirects {
368            self.max_redirects = v;
369        }
370        if let Some(v) = t.max_retries {
371            self.max_retries = v;
372        }
373        if let Some(v) = t.retry_base_ms {
374            self.retry_base_ms = v;
375        }
376        if let Some(v) = t.retry_max_delay_ms {
377            self.retry_max_delay_ms = v;
378        }
379        if let Some(v) = t.disable_retry {
380            self.disable_retry = v;
381        }
382        if let Some(v) = t.rate_limit_delay_ms {
383            self.rate_limit_delay_ms = v;
384        }
385        if let Some(v) = t.max_concurrency {
386            self.max_concurrency = v;
387        }
388        if let Some(v) = t.contact {
389            self.contact = Some(v);
390        }
391        if let Some(v) = t.user_agent {
392            self.user_agent = v;
393        } else if let Some(c) = &self.contact {
394            self.user_agent = default_user_agent(Some(c));
395        }
396        if let Some(v) = t.lang {
397            self.lang = Some(v);
398        }
399        if let Some(v) = t.crates_io_origin {
400            self.crates_io_origin = normalize_origin(&v);
401        }
402        if let Some(v) = t.docs_rs_origin {
403            self.docs_rs_origin = normalize_origin(&v);
404        }
405        if let Some(v) = t.cache_ttl_secs {
406            self.cache_ttl_secs = v;
407        }
408        if let Some(v) = t.max_cache_bytes {
409            self.max_cache_bytes = v;
410        }
411        if let Some(v) = t.no_cache {
412            self.no_cache = v;
413        }
414    }
415
416    /// Resolve cache path when still unset (XDG / test sandbox).
417    ///
418    /// Product knobs are **not** read from `DOCSRS_CLI_*` environment variables
419    /// (flags + XDG TOML only). Path sandbox `DOCSRS_CLI_HOME` remains available
420    /// for tests via [`crate::cache::resolve_cache_dir_with_source`].
421    fn apply_env(&mut self) -> AppResult<()> {
422        if self.cache_dir.is_none() {
423            let (dir, source) = crate::cache::resolve_cache_dir_with_source(None);
424            self.cache_dir = dir;
425            self.cache_path_source = source;
426        }
427        Ok(())
428    }
429}
430
431/// Resolve config directory: CLI/env override, then `DOCSRS_CLI_HOME/config`, then XDG.
432///
433/// Precedence:
434/// 1. Explicit override (`--config-dir` / `DOCSRS_CLI_CONFIG_DIR`)
435/// 2. `{DOCSRS_CLI_HOME}/config` when `DOCSRS_CLI_HOME` is set (sandbox / tests)
436/// 3. `directories::ProjectDirs` config dir (platform XDG / AppData / Library)
437pub fn resolve_config_dir(override_dir: Option<PathBuf>) -> Option<PathBuf> {
438    resolve_config_dir_with_source(override_dir).0
439}
440
441/// Resolve config directory and report which layer won.
442pub fn resolve_config_dir_with_source(override_dir: Option<PathBuf>) -> (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
608    /// Wall-clock timeout duration (at least one second).
609    pub fn timeout(&self) -> Duration {
610        Duration::from_secs(self.timeout_secs.max(1))
611    }
612
613    /// TCP connect timeout duration (at least one second).
614    pub fn connect_timeout(&self) -> Duration {
615        Duration::from_secs(self.connect_timeout_secs.max(1))
616    }
617
618    /// Per-host rate-limit delay duration.
619    pub fn rate_limit_delay(&self) -> Duration {
620        Duration::from_millis(self.rate_limit_delay_ms)
621    }
622
623    /// TTL for disk cache entries.
624    pub fn cache_ttl(&self) -> Duration {
625        Duration::from_secs(self.cache_ttl_secs)
626    }
627
628    /// Whether disk cache should be used for HTTP GET bodies.
629    pub fn cache_enabled(&self) -> bool {
630        !self.no_cache && self.cache_dir.is_some()
631    }
632}
633
634/// Validate crate name (compat wrapper over [`crate::domain::CrateName::parse`]).
635///
636/// # Errors
637///
638/// Propagates [`ErrorKind::InvalidInput`] from [`crate::domain::CrateName::parse`].
639pub fn validate_crate_name(name: &str) -> AppResult<()> {
640    crate::domain::CrateName::parse(name).map(|_| ())
641}
642
643/// True for Rust standard library crates documented on `doc.rust-lang.org`.
644pub fn is_stdlib_crate(name: &str) -> bool {
645    matches!(name, "std" | "core" | "alloc")
646}
647
648/// Resolve docs origin for a crate: stdlib → doc.rust-lang.org, else configured docs.rs origin.
649pub fn docs_origin_for_crate(cfg: &Config, crate_name: &str) -> String {
650    if is_stdlib_crate(crate_name) {
651        format!("https://{HOST_DOC_RUST_LANG_ORG}")
652    } else {
653        cfg.docs_rs_origin.clone()
654    }
655}
656
657/// Map CLI version token to a rustdoc channel for stdlib paths.
658///
659/// `latest` → `stable`. Accepts `stable` / `beta` / `nightly` and other path-safe tokens.
660pub fn stdlib_channel(version: &str) -> &str {
661    match version {
662        "latest" => "stable",
663        other => other,
664    }
665}
666
667/// Validate search query (compat wrapper over [`crate::domain::SearchQuery::parse`]).
668///
669/// # Errors
670///
671/// Propagates [`ErrorKind::InvalidInput`] from [`crate::domain::SearchQuery::parse`].
672pub fn validate_query(query: &str, allow_empty: bool) -> AppResult<()> {
673    crate::domain::SearchQuery::parse(query, allow_empty).map(|_| ())
674}
675
676/// Validate item path (compat wrapper over [`crate::domain::ItemPath::parse`]).
677///
678/// # Errors
679///
680/// Propagates [`ErrorKind::InvalidInput`] from [`crate::domain::ItemPath::parse`].
681pub fn validate_item_path(path: &str) -> AppResult<Vec<String>> {
682    crate::domain::ItemPath::parse(path).map(|p| p.into_segments())
683}
684
685/// Resolve version argument: `latest` or SemVer without `v` prefix / build metadata.
686///
687/// # Errors
688///
689/// Propagates [`ErrorKind::InvalidInput`] from [`crate::domain::VersionArg::parse_opt`].
690pub fn resolve_version_arg(raw: Option<&str>) -> AppResult<String> {
691    crate::domain::VersionArg::parse_opt(raw).map(|v| v.as_str().to_string())
692}
693
694#[cfg(test)]
695mod tests {
696    use super::*;
697    use std::fs;
698    use std::io::Write;
699
700    #[test]
701    fn crate_name_rules() {
702        assert!(validate_crate_name("serde").is_ok());
703        assert!(validate_crate_name("async-trait").is_ok());
704        // std/core/alloc are valid; docs are fetched from doc.rust-lang.org.
705        assert!(validate_crate_name("std").is_ok());
706        assert!(validate_crate_name("core").is_ok());
707        assert!(validate_crate_name("alloc").is_ok());
708        assert!(is_stdlib_crate("std"));
709        assert!(!is_stdlib_crate("serde"));
710        assert!(validate_crate_name("").is_err());
711        assert!(validate_crate_name("1bad").is_err());
712        assert!(validate_crate_name(&"a".repeat(MAX_CRATE_NAME_CHARS + 1)).is_err());
713    }
714
715    #[test]
716    fn version_policy() {
717        assert_eq!(resolve_version_arg(None).unwrap(), "latest");
718        assert_eq!(resolve_version_arg(Some("")).unwrap(), "latest");
719        assert_eq!(resolve_version_arg(Some("1.0.0")).unwrap(), "1.0.0");
720        assert_eq!(
721            resolve_version_arg(Some("1.0.0-rc.1")).unwrap(),
722            "1.0.0-rc.1"
723        );
724        assert!(resolve_version_arg(Some("v1.0.0")).is_err());
725        assert!(resolve_version_arg(Some("1.0.0+build")).is_err());
726        assert!(resolve_version_arg(Some("not-a-version")).is_err());
727    }
728
729    #[test]
730    fn query_and_path_rules() {
731        assert!(validate_query("serde", false).is_ok());
732        assert!(validate_query("", false).is_err());
733        assert!(validate_query("", true).is_ok());
734        assert!(validate_query(&"q".repeat(MAX_QUERY_CHARS + 1), true).is_err());
735        let segs = validate_item_path("clap::Parser").unwrap();
736        assert_eq!(segs, vec!["clap", "Parser"]);
737        assert!(validate_item_path("::").is_err());
738        assert!(validate_item_path("").is_err());
739        assert!(validate_item_path(&format!("a::{}", "b".repeat(MAX_ITEM_PATH_CHARS))).is_err());
740    }
741
742    #[test]
743    fn item_path_accepts_slash_and_rejects_bad_segments() {
744        let segs = validate_item_path("runtime/Runtime").unwrap();
745        assert_eq!(segs, vec!["runtime", "Runtime"]);
746        let mixed = validate_item_path("tokio::runtime/Runtime").unwrap();
747        assert_eq!(mixed, vec!["tokio", "runtime", "Runtime"]);
748        assert_eq!(
749            validate_item_path("async_trait").unwrap(),
750            vec!["async_trait"]
751        );
752        assert!(validate_item_path("has space").is_err());
753        assert!(validate_item_path("foo.bar").is_err());
754        assert!(validate_item_path("..").is_err());
755        assert!(validate_item_path("a/../b").is_err());
756        assert!(validate_item_path("/").is_err());
757    }
758
759    #[test]
760    fn default_user_agent_variants() {
761        let ua = default_user_agent(None);
762        assert!(ua.contains(APP_NAME));
763        let ua2 = default_user_agent(Some("dev@example.com"));
764        assert!(ua2.contains("dev@example.com"));
765        let ua3 = default_user_agent(Some("https://example.com"));
766        assert!(ua3.contains("+https://example.com"));
767    }
768
769    #[test]
770    fn config_load_toml_and_durations() {
771        let dir = tempfile::tempdir().unwrap();
772        let path = dir.path().join("config.toml");
773        let mut f = fs::File::create(&path).unwrap();
774        writeln!(
775            f,
776            "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"
777        )
778        .unwrap();
779        let cache_dir = dir.path().join("cache");
780        let cfg =
781            Config::load_with_cache_dir(Some(dir.path().to_path_buf()), Some(cache_dir.clone()))
782                .unwrap();
783        assert_eq!(cfg.timeout_secs, 12);
784        assert_eq!(cfg.rate_limit_delay_ms, 50);
785        assert!(cfg.user_agent.contains("a@b.c"));
786        assert_eq!(cfg.timeout(), Duration::from_secs(12));
787        assert_eq!(cfg.rate_limit_delay(), Duration::from_millis(50));
788        assert!(cfg.connect_timeout() >= Duration::from_secs(1));
789        assert_eq!(cfg.crates_io_origin, "http://127.0.0.1:9");
790        assert_eq!(cfg.docs_rs_origin, "http://127.0.0.1:9");
791        assert_eq!(cfg.lang.as_deref(), Some("pt-BR"));
792        assert_eq!(cfg.max_retries, 2);
793        assert_eq!(cfg.max_body_bytes, 1000);
794        assert_eq!(cfg.max_output_bytes, 2000);
795        assert_eq!(cfg.cache_ttl_secs, 3600);
796        assert_eq!(cfg.cache_dir.as_deref(), Some(cache_dir.as_path()));
797        assert!(cfg.cache_enabled());
798    }
799
800    #[test]
801    fn config_invalid_toml_errors() {
802        let dir = tempfile::tempdir().unwrap();
803        fs::write(dir.path().join("config.toml"), "timeout_secs = [\n").unwrap();
804        let err = Config::load(Some(dir.path().to_path_buf())).unwrap_err();
805        assert_eq!(err.kind(), ErrorKind::Config);
806    }
807
808    #[test]
809    fn normalize_origin_trims_slash() {
810        assert_eq!(normalize_origin(" https://docs.rs/ "), "https://docs.rs");
811    }
812
813    #[test]
814    fn resolve_config_dir_prefers_explicit_override() {
815        let explicit = PathBuf::from("/tmp/docsrs-cli-explicit-config");
816        let got = resolve_config_dir(Some(explicit.clone()));
817        assert_eq!(got.as_deref(), Some(explicit.as_path()));
818    }
819
820    #[test]
821    fn resolve_cache_dir_home_layout() {
822        // Pure path join contract (no env mutation): HOME root + "cache".
823        let home = PathBuf::from("/tmp/docsrs-cli-home-sandbox");
824        let cache = home.join("cache");
825        assert_eq!(cache.file_name().and_then(|s| s.to_str()), Some("cache"));
826        // resolve_cache_dir with explicit override must win over env/XDG.
827        let got = crate::cache::resolve_cache_dir(Some(cache.clone()));
828        assert_eq!(got.as_deref(), Some(cache.as_path()));
829    }
830
831    #[test]
832    fn config_defaults_positive() {
833        let cfg = Config::default();
834        assert!(cfg.timeout_secs >= 1);
835        assert!(cfg.max_body_bytes > 0);
836        assert!(cfg.user_agent.contains(APP_NAME));
837    }
838
839    #[test]
840    fn clamp_resource_limits_caps_body_and_output() {
841        let mut cfg = Config {
842            max_body_bytes: HARD_MAX_BODY_BYTES.saturating_mul(8),
843            max_output_bytes: HARD_MAX_OUTPUT_BYTES.saturating_mul(8),
844            ..Config::default()
845        };
846        cfg.clamp_resource_limits();
847        assert_eq!(cfg.max_body_bytes, HARD_MAX_BODY_BYTES);
848        assert_eq!(cfg.max_output_bytes, HARD_MAX_OUTPUT_BYTES);
849        // Lowering remains allowed (tests / tight budgets).
850        cfg.max_body_bytes = 64;
851        cfg.max_output_bytes = 32;
852        cfg.clamp_resource_limits();
853        assert_eq!(cfg.max_body_bytes, 64);
854        assert_eq!(cfg.max_output_bytes, 32);
855    }
856
857    #[test]
858    fn toml_cannot_raise_max_body_above_hard_ceiling() {
859        let dir = tempfile::tempdir().unwrap();
860        let path = dir.path().join("config.toml");
861        let huge_body = HARD_MAX_BODY_BYTES.saturating_mul(10);
862        let huge_out = HARD_MAX_OUTPUT_BYTES.saturating_mul(10);
863        fs::write(
864            &path,
865            format!("max_body_bytes = {huge_body}\nmax_output_bytes = {huge_out}\n"),
866        )
867        .unwrap();
868        let cfg = Config::load(Some(dir.path().to_path_buf())).unwrap();
869        assert_eq!(cfg.max_body_bytes, HARD_MAX_BODY_BYTES);
870        assert_eq!(cfg.max_output_bytes, HARD_MAX_OUTPUT_BYTES);
871    }
872
873    #[test]
874    fn hard_ceilings_equal_defaults() {
875        // Product policy: operators may only lower body/output caps, never raise.
876        assert_eq!(HARD_MAX_BODY_BYTES, DEFAULT_MAX_BODY_BYTES);
877        assert_eq!(HARD_MAX_OUTPUT_BYTES, DEFAULT_MAX_OUTPUT_BYTES);
878        assert_eq!(Config::default().max_body_bytes, HARD_MAX_BODY_BYTES);
879        assert_eq!(Config::default().max_output_bytes, HARD_MAX_OUTPUT_BYTES);
880    }
881
882    #[test]
883    fn path_source_tokens_are_stable() {
884        assert_eq!(PathSource::CliOrEnv.as_str(), "cli-or-env");
885        assert_eq!(PathSource::HomeSandbox.as_str(), "home-sandbox");
886        assert_eq!(PathSource::Xdg.as_str(), "xdg");
887        assert_eq!(PathSource::Unresolved.as_str(), "unresolved");
888    }
889
890    #[test]
891    fn resolve_config_dir_with_source_reports_cli() {
892        let explicit = PathBuf::from("/tmp/docsrs-cli-src-explicit");
893        let (got, source) = resolve_config_dir_with_source(Some(explicit.clone()));
894        assert_eq!(got.as_deref(), Some(explicit.as_path()));
895        assert_eq!(source, PathSource::CliOrEnv);
896    }
897
898    #[test]
899    fn init_config_toml_creates_and_refuses_without_force() {
900        let dir = tempfile::tempdir().unwrap();
901        let r1 = init_config_toml(Some(dir.path().to_path_buf()), false).unwrap();
902        assert!(r1.created);
903        assert!(!r1.overwritten);
904        assert!(Path::new(&r1.path).is_file());
905        let text = fs::read_to_string(&r1.path).unwrap();
906        assert!(text.contains("docsrs-cli XDG configuration"));
907        assert!(text.contains("No .env file is required"));
908        #[cfg(unix)]
909        {
910            use std::os::unix::fs::PermissionsExt;
911            let mode = fs::metadata(&r1.path).unwrap().permissions().mode() & 0o777;
912            assert_eq!(mode, 0o600);
913        }
914        let err = init_config_toml(Some(dir.path().to_path_buf()), false).unwrap_err();
915        assert_eq!(err.kind(), ErrorKind::Config);
916        let r2 = init_config_toml(Some(dir.path().to_path_buf()), true).unwrap();
917        assert!(r2.created);
918        assert!(r2.overwritten);
919    }
920
921    #[test]
922    fn config_load_marks_toml_loaded() {
923        let dir = tempfile::tempdir().unwrap();
924        fs::write(dir.path().join("config.toml"), "timeout_secs = 9\n").unwrap();
925        let cfg = Config::load(Some(dir.path().to_path_buf())).unwrap();
926        assert!(cfg.config_toml_loaded);
927        assert_eq!(cfg.timeout_secs, 9);
928        assert_eq!(cfg.config_path_source, PathSource::CliOrEnv);
929        let inv = config_path_data(&cfg);
930        assert!(inv.config_file_exists);
931        assert!(!inv.dotenv_runtime);
932    }
933
934    #[test]
935    fn config_load_without_toml_is_not_loaded() {
936        let dir = tempfile::tempdir().unwrap();
937        let cfg = Config::load(Some(dir.path().to_path_buf())).unwrap();
938        assert!(!cfg.config_toml_loaded);
939        assert!(!config_path_data(&cfg).config_file_exists);
940    }
941}