config-resolver 0.2.1

A modular configuration resolver for auto-detecting and resolving runtime values (IPs, ports, peer IDs)
Documentation
use crate::error::Error;
use crate::providers::ConfigProvider;
use crate::types::ResolvedValue;
use async_trait::async_trait;
use std::net::IpAddr;

/// A provider that resolves the DigitalOcean droplet's public IPv4 address using the metadata service.
pub struct DOPublicIpProvider;

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

    async fn resolve(&self) -> Result<ResolvedValue, Error> {
        let res =
            reqwest::get("http://169.254.169.254/metadata/v1/interfaces/public/0/ipv4/address")
                .await?
                .text()
                .await?;
        let ip = res
            .trim()
            .parse::<IpAddr>()
            .map_err(|e| Error::ParseError(e.to_string()))?;
        Ok(ResolvedValue::Ip(ip))
    }

    fn resolve_sync(&self) -> Result<ResolvedValue, Error> {
        let res = reqwest::blocking::get(
            "http://169.254.169.254/metadata/v1/interfaces/public/0/ipv4/address",
        )?
        .text()?;
        let ip = res
            .trim()
            .parse::<IpAddr>()
            .map_err(|e| Error::ParseError(e.to_string()))?;
        Ok(ResolvedValue::Ip(ip))
    }
}

/// A provider that resolves the DigitalOcean droplet's private IPv4 address using the metadata service.
pub struct DOPrivateIpProvider;

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

    async fn resolve(&self) -> Result<ResolvedValue, Error> {
        let res =
            reqwest::get("http://169.254.169.254/metadata/v1/interfaces/private/0/ipv4/address")
                .await?
                .text()
                .await?;
        let ip = res
            .trim()
            .parse::<IpAddr>()
            .map_err(|e| Error::ParseError(e.to_string()))?;
        Ok(ResolvedValue::Ip(ip))
    }

    fn resolve_sync(&self) -> Result<ResolvedValue, Error> {
        let res = reqwest::blocking::get(
            "http://169.254.169.254/metadata/v1/interfaces/private/0/ipv4/address",
        )?
        .text()?;
        let ip = res
            .trim()
            .parse::<IpAddr>()
            .map_err(|e| Error::ParseError(e.to_string()))?;
        Ok(ResolvedValue::Ip(ip))
    }
}