artifactize-provider 0.27.2

Managed credentials, model discovery and direct HTTP turns for Artifactize.
Documentation
//! Native edges for provider-owned, atomically replaced credential files.

use std::{
    fs::{File, OpenOptions},
    io,
    path::Path,
    time::Duration,
};

use super::{create_private_file, is_private_file, open_no_follow, open_regular};

/// Wait briefly between attempts when another process has an exclusive native lock.
const LOCK_RETRY_INTERVAL: Duration = Duration::from_millis(25);

fn open_existing(path: &Path) -> io::Result<File> {
    open_no_follow(OpenOptions::new().read(true).write(true), path)
}

fn private_lock(path: &Path) -> io::Result<File> {
    // The file is private from its creation; an existing lock is checked on its handle.
    let file = match create_private_file(path) {
        Err(error) if error.kind() == io::ErrorKind::AlreadyExists => open_existing(path)?,
        result => result?,
    };
    if !is_private_file(&file)? {
        return Err(io::ErrorKind::PermissionDenied.into());
    }
    Ok(file)
}

pub(crate) async fn lock(path: &Path) -> io::Result<File> {
    let file = private_lock(path)?;
    loop {
        match file.try_lock() {
            Ok(()) => return Ok(file),
            Err(std::fs::TryLockError::WouldBlock) => tokio::time::sleep(LOCK_RETRY_INTERVAL).await,
            Err(std::fs::TryLockError::Error(error)) => return Err(error),
        }
    }
}

pub(crate) fn replace(
    directory: &Path,
    destination: &Path,
    write: impl FnOnce(&mut File) -> Result<(), String>,
) -> Result<(), String> {
    let stage =
        artifactize_foundation::platform::private::private_tempdir_in("credentials-", directory)
            .map_err(|error| error.to_string())?;
    let path = stage.path().join("new");
    let mut file = create_private_file(&path).map_err(|error| error.to_string())?;
    write(&mut file)?;
    file.sync_all().map_err(|error| error.to_string())?;
    // Don't carry our own open handle into rename, even when it shares delete access.
    drop(file);
    with_delete_sharing(|| std::fs::rename(&path, destination)).map_err(|error| error.to_string())
}

pub(crate) fn remove(path: &Path) -> io::Result<()> {
    with_delete_sharing(|| {
        let file = open_regular(path)?;
        if !is_private_file(&file)? {
            return Err(io::ErrorKind::PermissionDenied.into());
        }
        drop(file);
        std::fs::remove_file(path)
    })
}

#[cfg(unix)]
fn with_delete_sharing(operation: impl FnOnce() -> io::Result<()>) -> io::Result<()> {
    operation()
}

#[cfg(windows)]
fn with_delete_sharing(mut operation: impl FnMut() -> io::Result<()>) -> io::Result<()> {
    use windows_sys::Win32::Foundation::{ERROR_LOCK_VIOLATION, ERROR_SHARING_VIOLATION};

    // Short readers may omit FILE_SHARE_DELETE. A persistent conflict is reported rather
    // than waiting indefinitely or moving credentials elsewhere and leaving a stale copy.
    const DELETE_SHARING_BUDGET: Duration = Duration::from_secs(2);
    let started = std::time::Instant::now();
    loop {
        match operation() {
            Err(error)
                if error.raw_os_error().is_some_and(|code| {
                    code == ERROR_SHARING_VIOLATION as i32 || code == ERROR_LOCK_VIOLATION as i32
                }) && started.elapsed() < DELETE_SHARING_BUDGET =>
            {
                std::thread::sleep(LOCK_RETRY_INTERVAL)
            }
            result => return result,
        }
    }
}

pub(crate) fn exclusive(path: &Path) -> io::Result<File> {
    let file = private_lock(path)?;
    file.lock()?;
    Ok(file)
}

pub(crate) fn held(path: &Path) -> io::Result<bool> {
    let file = open_existing(path)?;
    match file.try_lock() {
        Ok(()) => Ok(false),
        Err(std::fs::TryLockError::WouldBlock) => Ok(true),
        Err(std::fs::TryLockError::Error(error)) => Err(error),
    }
}