footing 0.1.19

Feature-gated foundations for Rust backend services
Documentation
//! PostgreSQL identifiers and redacted URL helpers shared by configuration and runtime code.

use std::str::FromStr;

use sqlx::postgres::PgConnectOptions;

#[must_use]
/// Extracts the database name from a PostgreSQL URL.
pub fn database_name(database_url: &str) -> Option<String> {
    PgConnectOptions::from_str(database_url)
        .ok()
        .and_then(|options| options.get_database().map(ToOwned::to_owned))
        .filter(|database| !database.trim().is_empty())
}

#[must_use]
/// Returns a redacted representation of database URL.
pub fn redact_database_url(database_url: &str) -> String {
    let Some((scheme, rest)) = database_url.split_once("://") else {
        return "<invalid-postgres-url>".to_owned();
    };

    let authority_end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
    let (authority, suffix) = rest.split_at(authority_end);
    let redacted_authority = match authority.rsplit_once('@') {
        Some((userinfo, host)) => {
            let redacted_userinfo = userinfo
                .split_once(':')
                .map(|(user, _)| format!("{user}:****"))
                .unwrap_or_else(|| "****".to_owned());
            format!("{redacted_userinfo}@{host}")
        }
        None => authority.to_owned(),
    };

    format!(
        "{scheme}://{redacted_authority}{}",
        redact_database_url_suffix(suffix)
    )
}

fn redact_database_url_suffix(suffix: &str) -> String {
    let (without_fragment, fragment) = suffix
        .split_once('#')
        .map_or((suffix, None), |(value, _)| (value, Some("#****")));
    let Some((path, query)) = without_fragment.split_once('?') else {
        return format!("{without_fragment}{}", fragment.unwrap_or_default());
    };

    let redacted_query = query
        .split('&')
        .map(|parameter| {
            parameter
                .split_once('=')
                .map_or_else(|| parameter.to_owned(), |(key, _)| format!("{key}=****"))
        })
        .collect::<Vec<_>>()
        .join("&");
    format!("{path}?{redacted_query}{}", fragment.unwrap_or_default())
}

#[must_use]
/// Derives a stable advisory-lock key from a namespace and name.
pub fn advisory_lock_key(namespace: &str, name: &str) -> i64 {
    const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
    const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;

    let mut hash = FNV_OFFSET;
    for byte in namespace
        .trim()
        .bytes()
        .chain([0])
        .chain(name.trim().bytes())
    {
        hash ^= u64::from(byte);
        hash = hash.wrapping_mul(FNV_PRIME);
    }

    i64::from_ne_bytes(hash.to_ne_bytes())
}

#[must_use]
/// Derives the database-scoped lock used by every schema maintenance operation.
///
/// Migrations and destructive resets deliberately share this key so they can
/// never mutate the same database schema concurrently.
pub fn schema_maintenance_advisory_lock_key(database_name: &str) -> i64 {
    advisory_lock_key("footing.postgres.schema-maintenance", database_name)
}