DistributedLock

Trait DistributedLock 

Source
pub trait DistributedLock: Send + Sync {
    type Handle: LockHandle + Send;

    // Required methods
    fn name(&self) -> &str;
    fn acquire(
        &self,
        timeout: Option<Duration>,
    ) -> impl Future<Output = Result<Self::Handle, LockError>> + Send;
    fn try_acquire(
        &self,
    ) -> impl Future<Output = Result<Option<Self::Handle>, LockError>> + Send;
}
Expand description

A distributed mutual exclusion lock.

Provides exclusive access to a resource identified by name across processes and machines. The specific backend (PostgreSQL, Redis, file system, etc.) determines how the lock is implemented.

§Example

use distributed_lock_core::DistributedLock;

async fn protected_operation(lock: &impl DistributedLock) -> Result<(), Error> {
    // Acquire with 5 second timeout
    let handle = lock.acquire(Some(Duration::from_secs(5))).await?;
     
    // We have exclusive access
    perform_critical_section().await?;
     
    // Release (also happens on drop)
    handle.release().await?;
    Ok(())
}

Required Associated Types§

Source

type Handle: LockHandle + Send

The handle type returned when the lock is acquired.

Required Methods§

Source

fn name(&self) -> &str

Returns the unique name identifying this lock.

Source

fn acquire( &self, timeout: Option<Duration>, ) -> impl Future<Output = Result<Self::Handle, LockError>> + Send

Acquires the lock, waiting up to timeout.

§Arguments
  • timeout - Maximum time to wait. None means wait indefinitely.
§Returns
  • Ok(handle) - Lock acquired successfully
  • Err(LockError::Timeout) - Timeout expired before lock acquired
  • Err(LockError::Cancelled) - Operation was cancelled
  • Err(LockError::Connection) - Backend connection failed
§Cancellation

This operation can be cancelled by dropping the returned future or using tokio::select! with a cancellation branch. Backends should check for cancellation periodically during the wait.

Source

fn try_acquire( &self, ) -> impl Future<Output = Result<Option<Self::Handle>, LockError>> + Send

Attempts to acquire the lock without waiting.

§Returns
  • Ok(Some(handle)) - Lock acquired successfully
  • Ok(None) - Lock is held by another process
  • Err(...) - Error occurred during attempt

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementations on Foreign Types§

Source§

impl DistributedLock for PostgresDistributedLock

Implementors§