servlet 1.0.0

A small application runtime with an explicit operational contract
Documentation
//! Parse explicit TCP endpoints without native environment or password-file discovery.

use super::PgError;

#[derive(Clone)]
pub(super) struct Endpoint {
    pub host: String,
    pub port: u16,
    pub username: String,
    pub password: String,
    pub database: String,
}
impl Endpoint {
    pub(super) fn parse(input: &str) -> Result<Self, PgError> {
        if input.len() > 8192 || input.chars().any(char::is_control) {
            return Err(PgError::Configuration);
        }
        let url = url::Url::parse(input).map_err(|_| PgError::Configuration)?;
        if !matches!(url.scheme(), "postgres" | "postgresql")
            || url.query().is_some()
            || url.fragment().is_some()
        {
            return Err(PgError::Configuration);
        }
        let host = match url.host().ok_or(PgError::Configuration)? {
            url::Host::Domain(host) => host.to_owned(),
            url::Host::Ipv4(host) => host.to_string(),
            url::Host::Ipv6(host) => host.to_string(),
        };
        if host.len() > 253
            || !host.bytes().all(|byte| {
                byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b'_' | b':')
            })
        {
            return Err(PgError::Configuration);
        }
        let username = decode(url.username(), 128)?;
        let password = decode(url.password().unwrap_or(""), 4096)?;
        let database = decode(url.path().strip_prefix('/').unwrap_or(""), 128)?;
        let port = url.port().unwrap_or(5432);
        if username.is_empty() || database.is_empty() || port == 0 {
            return Err(PgError::Configuration);
        }
        Ok(Self {
            host,
            port,
            username,
            password,
            database,
        })
    }
    pub(super) fn loopback(&self) -> bool {
        self.host
            .parse::<std::net::IpAddr>()
            .is_ok_and(|host| host.is_loopback())
    }
}
fn decode(value: &str, limit: usize) -> Result<String, PgError> {
    let value = percent_encoding::percent_decode_str(value)
        .decode_utf8()
        .map_err(|_| PgError::Configuration)?;
    if value.len() > limit || value.chars().any(char::is_control) {
        return Err(PgError::Configuration);
    }
    Ok(value.into_owned())
}