pub struct Lock { /* private fields */ }Expand description
A distributed lock and its client-unique data.
Lock instances purposefully expose very little “raw” functionality. This is to prevent clients from using incorrect locking behaviour patterns, such as:
- Check-and-set (seeing that the lock is locked by you and assuming that trying to refresh the lock will succeed)
- Check-and-critical (seeing that the lock is locked by you and assuming it will stay locked long enough to perform critical work)
Any functionality you want to implement while a lock is held should be achievable using the Lock::locked method.
Implementations§
Source§impl Lock
impl Lock
Sourcepub fn builder<L: IntoLockID>(lock_id: L) -> LockBuilder
pub fn builder<L: IntoLockID>(lock_id: L) -> LockBuilder
Create a LockBuilder to configure a Lock.
This is the same as LockBuilder::new.
Sourcepub async fn locked<Fut, F, T>(self, f: F) -> Result<T, Error>
pub async fn locked<Fut, F, T>(self, f: F) -> Result<T, Error>
Evaluate a function while this client holds this lock
The CancellationToken provided to the argument function will be cancelled when the lock is no longer guaranteed to be held. This means that the lock may still be held when the cancellation is issued (and so no other client can grab the lock), but that such a state cannot be guaranteed.
If the lock is already locked by another client, this method will attempt to obtain the lock indefinitely. It will return an Error only if an error is encountered while trying to obtain the lock. Once the lock it obtained, the method will attempt to keep the lock locked (refreshed) as long as the argument function continues to run. At that point, it will only return when the argument function returns.
// attempt to do some long-running work, but only while locked
loop {
let result = lock.clone().locked(|cancellation_token| async move {
eprintln!("Resuming work");
perform_work_or_cancel(cancellation_token).await
}).await;
match result {
Ok(Ok(_)) => break,
Ok(Err(_)) => eprintln!("Work interrupted"),
Err(error) => match error {
Error::Data(message) => panic!("Problem with the lock configuration: {message:?}"),
Error::Reqwest(error) => eprintln!("Failure while trying to obtain the lock: {error:?}"),
},
}
}