config-resolver 0.2.1

A modular configuration resolver for auto-detecting and resolving runtime values (IPs, ports, peer IDs)
Documentation

Config Resolver

A modular, lightweight, and extensible configuration resolver for Rust that allows auto-detecting and resolving configuration values (such as IP addresses, port numbers, peer IDs, and socket addresses) at runtime.

This is particularly useful for containerized applications, cloud environments (AWS, DigitalOcean), or P2P/distributed systems where static configuration files are insufficient, and bindings must adapt dynamically to the environment.

Crates.io Documentation License


Features

  • Recursive Parsing & Resolution:
    • Static values: Supports standard Rust parser values like 127.0.0.1, 3000, or 127.0.0.1:8080.
    • Dynamic Lookups: Resolves variables like DO_PUBLIC_IP or AWS_PRIVATE_IP by querying metadata services.
    • Combined Addresses: Construct complex Socket addresses dynamically, e.g., DO_PUBLIC_IP:3000 or IPIFY:8080.
    • Offset Calculations: Performs mathematical calculations directly on IP addresses (converting IPv4 to a unique u64 base and adding an offset), e.g., CALC(DO_PUBLIC_IP+10000). Useful for generating unique Peer IDs in distributed protocols.
  • Type-Safe: Clean parsing into standard library types like IpAddr, SocketAddr, u32, and u64 via the ConfigUnit trait.
  • Feature-Gated Providers: AWS, DigitalOcean, and Ipify HTTP-based lookups can be compiled conditionally, keeping the crate extremely lightweight when only static resolution or custom providers are needed.
  • Extensible: Define your own custom provider by implementing the ConfigProvider trait and registering it with the ConfigRegistry.

Installation

Add config-resolver to your Cargo.toml:

[dependencies]
config-resolver = "0.2"

If you only need static resolution or custom providers (no remote metadata calls over HTTP), disable the default features to eliminate the dependency on reqwest and TLS:

[dependencies]
config-resolver = { version = "0.2", default-features = false }

Cargo Features

By default, all cloud metadata and external providers are enabled. You can disable them or select only what you need:

Feature Description Dependencies Enabled by Default
aws AWS EC2 Instance Metadata Service (IMDSv2) provider (AWS_PUBLIC_IP, AWS_PRIVATE_IP) reqwest Yes
digital-ocean DigitalOcean Droplet metadata provider (DO_PUBLIC_IP, DO_PRIVATE_IP) reqwest Yes
ipify Public IP lookup via api.ipify.org (IPIFY) reqwest Yes

Supported Expressions

The config resolver parses and resolves configuration specification strings into standard Rust types dynamically at runtime. The table below lists all supported syntax patterns and expressions:

Expression Type Syntax Pattern / Examples Target Rust Type Description
Static Value 127.0.0.1::1 IpAddr Standard static IPv4 or IPv6 address.
Static Value 80803000 u32 / u64 Standard unsigned integers.
Static Value 127.0.0.1:8080 SocketAddr Standard static socket address (IP + Port).
Dynamic Lookup IPIFY IpAddr Queries the public IP address via api.ipify.org.
Dynamic Lookup AWS_PUBLIC_IPAWS_PRIVATE_IP IpAddr Queries AWS IMDSv2 metadata service for the public or private IPv4.
Dynamic Lookup DO_PUBLIC_IPDO_PRIVATE_IP IpAddr Queries DigitalOcean droplet metadata service for the public or private IPv4.
Combined Socket <IP_EXPR>:<PORT_EXPR>Example: DO_PUBLIC_IP:3000Example: IPIFY:8080Example: AWS_PRIVATE_IP:CONSUL_PORT SocketAddr Combines any IP specification (static or dynamic) with a port specification (static or dynamic).
Offset Calculation CALC(<IP_EXPR>+<OFFSET>)Example: CALC(127.0.0.1+100)Example: CALC(DO_PUBLIC_IP+10000) u64 Resolves the IP expression, converts it into its u32 integer equivalent, adds the specified offset, and returns the result as u64. Perfect for generating unique Peer IDs in distributed protocols.

Usage

1. Basic Resolution

use std::net::{IpAddr, SocketAddr};
use config_resolver::create_default_registry;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Create the default registry populated with standard providers
    let registry = create_default_registry();

    // 1. Resolve a static IP address
    let local_ip: IpAddr = registry.resolve("127.0.0.1").await?;
    println!("Resolved IP: {}", local_ip);

    // 2. Resolve a SocketAddr with an environment/external provider and a static port
    // This dynamically queries api.ipify.org for your public IP and combines it with port 3003
    let public_socket: SocketAddr = registry.resolve("IPIFY:3003").await?;
    println!("Resolved SocketAddr: {}", public_socket);

    // 3. Perform a Peer ID calculation
    // Converts the public IP to a u64 integer and adds 10000
    let peer_id: u64 = registry.resolve("CALC(IPIFY+10000)").await?;
    println!("Resolved unique Peer ID: {}", peer_id);

    Ok(())
}

1b. Synchronous Resolution

If you do not have an asynchronous runtime or want to resolve configuration values synchronously (e.g. at the start of your program), you can use the synchronous .resolve_sync() method:

use std::net::{IpAddr, SocketAddr};
use config_resolver::create_default_registry;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let registry = create_default_registry();

    // Resolves synchronously (including blocking HTTP requests for DO/AWS/Ipify if features are enabled)
    let local_ip: IpAddr = registry.resolve_sync("127.0.0.1")?;
    println!("Resolved IP: {}", local_ip);

    let public_socket: SocketAddr = registry.resolve_sync("IPIFY:3003")?;
    println!("Resolved SocketAddr: {}", public_socket);

    Ok(())
}

2. Integration with clap

You can integrate config-resolver with clap to automatically resolve configuration specifications at parse time, allowing your parsed struct fields to have native types (such as u32, u64, IpAddr, or SocketAddr) directly without any wrappers:

use clap::Parser;
use std::net::{IpAddr, SocketAddr};
use config_resolver::clap_value_parser;

#[derive(Parser)]
struct Args {
    /// Resolved directly at parse time (type is u64)
    #[arg(long, env, default_value = "1000", value_parser = clap_value_parser::<u64>)]
    peer_id: u64,

    /// Resolved directly at parse time (type is SocketAddr)
    #[arg(long, env, default_value = "127.0.0.1:3000", value_parser = clap_value_parser::<SocketAddr>)]
    listen_address: SocketAddr,
}

fn main() {
    // Parsing is completely synchronous, resolving everything under the hood
    let args = Args::parse();

    // Fields are natively typed and already resolved! No manual resolve calls needed.
    println!("Listening on: {}", args.listen_address);
    println!("Peer ID: {}", args.peer_id);
}

[!NOTE] clap_value_parser utilizes a global registry. If you want to use custom providers, register them using config_resolver::init_global_registry(my_registry) at the start of your program before calling Args::parse().

3. Custom Providers

You can easily register your own resolution providers:

use async_trait::async_trait;
use config_resolver::{ConfigRegistry, ConfigProvider, ResolvedValue, Error};
use std::net::IpAddr;

struct ConsulIpProvider;

#[async_trait]
impl ConfigProvider for ConsulIpProvider {
    fn name(&self) -> &str {
        "CONSUL_IP"
    }

    async fn resolve(&self) -> Result<ResolvedValue, Error> {
        // Implement your custom resolution logic here (e.g., query Consul, read a file, etc.)
        let ip: IpAddr = "10.0.0.50".parse().unwrap();
        Ok(ResolvedValue::Ip(ip))
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut registry = ConfigRegistry::default();
    registry.register(Box::new(ConsulIpProvider));

    let addr: SocketAddr = registry.resolve("CONSUL_IP:8080").await?;
    assert_eq!(addr.to_string(), "10.0.0.50:8080");
    Ok(())
}

License

Licensed under either of:

at your option.