tokio_socket 0.1.0

Composable tokio-based UDP/TCP sockets
Documentation
// tokio_socket/src/socket/uds_lock.rs

use anyhow::Result;
use std::path::Path;

use crate::SocketAddr;
use crate::uds_compat::UnixListener;

/// A cross-platform UDS-based lock mechanism that uses a Unix domain socket
/// as an exclusive lock. This works on both Unix and Windows platforms.
///
/// The lock is held as long as the `UdsLock` instance exists. When dropped,
/// the socket is closed and the lock is released.
///
/// Note: This uses tokio_socket's UnixListener which on Unix requires tokio runtime
/// for abstract socket support. On Windows it uses uds_windows.
///
/// # Examples
///
/// ```no_run
/// use tokio_socket::UdsLock;
///
/// // Try to acquire a file-based lock
/// if let Ok(lock) = UdsLock::try_acquire_file("/tmp/my-app.lock") {
///     println!("Lock acquired!");
///     // Lock is held until `lock` is dropped
/// } else {
///     println!("Another instance is running");
/// }
///
/// // Try to acquire an abstract socket lock (no filesystem cleanup needed)
/// if let Ok(lock) = UdsLock::try_acquire_abstract("my-app-lock") {
///     println!("Lock acquired!");
/// }
/// ```
pub struct UdsLock {
    _listener: UnixListener,
    addr: SocketAddr,
}

impl UdsLock {
    /// Try to acquire a lock using a file-based Unix domain socket.
    ///
    /// Returns `Ok(UdsLock)` if the lock was successfully acquired,
    /// or `Err` if the lock is already held by another process.
    pub fn try_acquire_file(path: impl AsRef<Path>) -> Result<Self> {
        let addr = SocketAddr::file(path);
        Self::try_acquire(addr)
    }

    /// Try to acquire a lock using an abstract Unix domain socket.
    ///
    /// Abstract sockets don't create files on the filesystem and are
    /// automatically cleaned up when the process exits. This is preferred
    /// for temporary locks that don't need persistence.
    ///
    /// Returns `Ok(UdsLock)` if the lock was successfully acquired,
    /// or `Err` if the lock is already held by another process.
    pub fn try_acquire_abstract(name: impl AsRef<str>) -> Result<Self> {
        let addr = SocketAddr::abstract_uds(name);
        Self::try_acquire(addr)
    }

    /// Try to acquire a lock using the specified socket address.
    ///
    /// Returns `Ok(UdsLock)` if the lock was successfully acquired,
    /// or `Err` if the lock is already held.
    pub fn try_acquire(addr: SocketAddr) -> Result<Self> {
        if !addr.is_uds_address() {
            anyhow::bail!("UdsLock requires a Unix domain socket address");
        }

        // Try to bind to the socket address
        // This will fail if another process already has it bound
        // Use tokio_socket's UnixListener which supports abstract sockets
        let listener = UnixListener::bind(&addr)
            .map_err(|e| anyhow::anyhow!("Failed to acquire lock on {:?}: {}", addr, e))?;

        Ok(Self {
            _listener: listener,
            addr,
        })
    }

    /// Check if a lock is currently held at the specified file path.
    ///
    /// Returns `true` if the lock is held, `false` if it's available.
    pub fn is_locked_file(path: impl AsRef<Path>) -> bool {
        Self::try_acquire_file(path).is_err()
    }

    /// Check if a lock is currently held at the specified abstract socket name.
    ///
    /// Returns `true` if the lock is held, `false` if it's available.
    pub fn is_locked_abstract(name: impl AsRef<str>) -> bool {
        Self::try_acquire_abstract(name).is_err()
    }

    /// Get the socket address this lock is bound to.
    pub fn addr(&self) -> &SocketAddr {
        &self.addr
    }
}

impl std::fmt::Debug for UdsLock {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("UdsLock")
            .field("addr", &self.addr)
            .finish()
    }
}

impl std::fmt::Display for UdsLock {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "UdsLock({})", self.addr)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_abstract_lock() {
        let lock_name = format!("test-lock-{}", uuid::Uuid::new_v4());

        // First lock should succeed
        let lock1 = UdsLock::try_acquire_abstract(&lock_name);
        if let Err(e) = &lock1 {
            eprintln!("Failed to acquire abstract lock: {}", e);
        }
        assert!(lock1.is_ok());

        // Second lock should fail while first is held
        let lock2 = UdsLock::try_acquire_abstract(&lock_name);
        assert!(lock2.is_err());

        // Drop first lock
        drop(lock1);

        // Now we should be able to acquire it again
        let lock3 = UdsLock::try_acquire_abstract(&lock_name);
        assert!(lock3.is_ok());
    }

    #[tokio::test]
    async fn test_file_lock() {
        let temp_dir = tempfile::tempdir().unwrap();
        let lock_path = temp_dir.path().join("test.lock");

        // First lock should succeed
        let lock1 = UdsLock::try_acquire_file(&lock_path);
        assert!(lock1.is_ok());

        // Check that it's locked
        assert!(UdsLock::is_locked_file(&lock_path));

        // Second lock should fail
        let lock2 = UdsLock::try_acquire_file(&lock_path);
        assert!(lock2.is_err());

        // Drop first lock
        drop(lock1);

        // For file-based sockets, the file remains after close
        // We need to remove it manually to test re-acquisition
        let _ = std::fs::remove_file(&lock_path);

        // Now we should be able to acquire it again
        let lock3 = UdsLock::try_acquire_file(&lock_path);
        assert!(lock3.is_ok());
    }
}