-
Notifications
You must be signed in to change notification settings - Fork 305
Add a value-based lock in the CryptoStore
s
#2049
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
bnjbvr
merged 13 commits into
matrix-org:main
from
bnjbvr:insert-custom-value-if-missing
Jun 16, 2023
Merged
Changes from 11 commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
5dd2e96
feat: add `insert_custom_value_if_missing` in the crypto store
bnjbvr 75ed722
feat: add `remove_custom_value` in the crypto store
bnjbvr 49e5f10
tests: add some tests for the two new methods
bnjbvr 635f9a8
chore: add a new module for the database lock
bnjbvr fb8c3bc
labs: add experimental sqlite lock program
bnjbvr 1418575
feat: add more parameters to the lock's creation + handle interrupted…
bnjbvr 9087d51
chore: fmt grr
bnjbvr 094ded7
Add comments around the backoff sentinel value
bnjbvr 523b6ec
Get rid of the `CryptoStoreLockGuard` that has a racy Drop
bnjbvr 047e654
labs: simplify the locking test program
bnjbvr 1a6e382
chore: fmt
bnjbvr ab713ce
docs
bnjbvr 38dfb91
add a small enum helper for handling waiting times
bnjbvr File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,178 @@ | ||
// Copyright 2023 The Matrix.org Foundation C.I.C. | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
//! Collection of small helpers that implement store-based locks. | ||
//! | ||
//! Those locks are implemented as one value in the key-value crypto store, that | ||
//! exists if and only if the lock has been taken. For this to work correctly, | ||
//! we rely on multiple assumptions: | ||
//! | ||
//! - the store must allow concurrent reads and writes from multiple processes. | ||
//! For instance, for | ||
//! sqlite, this means that it is running in [WAL](https://www.sqlite.org/wal.html) mode. | ||
//! - the two operations used in the store implementation, | ||
//! `insert_custom_value_if_missing` and | ||
//! `remove_custom_value`, must be atomic / implemented in a transaction. | ||
|
||
use std::{sync::Arc, time::Duration}; | ||
|
||
use tokio::time::sleep; | ||
|
||
use super::DynCryptoStore; | ||
use crate::CryptoStoreError; | ||
|
||
/// A store-based lock for the `CryptoStore`. | ||
#[derive(Debug, Clone)] | ||
pub struct CryptoStoreLock { | ||
/// The store we're using to lock. | ||
store: Arc<DynCryptoStore>, | ||
|
||
/// The key used in the key/value mapping for the lock entry. | ||
lock_key: String, | ||
|
||
/// A specific value to identify the lock's holder. | ||
lock_holder: String, | ||
|
||
/// Backoff time, in milliseconds. | ||
backoff: u32, | ||
|
||
/// Maximum backoff time, between two attempts. | ||
max_backoff: u32, | ||
} | ||
|
||
impl CryptoStoreLock { | ||
/// Initial backoff, in milliseconds. This is the time we wait the first | ||
/// time, if taking the lock initially failed. | ||
const INITIAL_BACKOFF_MS: u32 = 10; | ||
|
||
/// Maximal backoff, in milliseconds. This is the maximum amount of time | ||
/// we'll wait for the lock, *between two attempts*. | ||
const MAX_BACKOFF_MS: u32 = 1000; | ||
|
||
/// Create a new store-based lock implemented as a value in the | ||
/// crypto-store. | ||
/// | ||
/// # Parameters | ||
/// | ||
/// - `lock_key`: key in the key-value store to store the lock's state. | ||
/// - `lock_holder`: identify the lock's holder with this given value. | ||
/// - `max_backoff`: maximum time (in milliseconds) that should be waited | ||
/// for, between two | ||
/// attempts. When that time is reached a second time, the lock will stop | ||
/// attempting to get the lock and will return a timeout error upon | ||
/// locking. If not provided, will wait for [`Self::MAX_BACKOFF_MS`]. | ||
pub fn new( | ||
store: Arc<DynCryptoStore>, | ||
lock_key: String, | ||
lock_holder: String, | ||
max_backoff: Option<u32>, | ||
) -> Self { | ||
let max_backoff = max_backoff.unwrap_or(Self::MAX_BACKOFF_MS); | ||
Self { store, lock_key, lock_holder, max_backoff, backoff: Self::INITIAL_BACKOFF_MS } | ||
} | ||
|
||
/// Attempt to take the lock, with exponential backoff if the lock has | ||
/// already been taken before. | ||
pub async fn lock(&mut self) -> Result<(), CryptoStoreError> { | ||
loop { | ||
let inserted = self | ||
.store | ||
.insert_custom_value_if_missing( | ||
&self.lock_key, | ||
self.lock_holder.as_bytes().to_vec(), | ||
) | ||
.await?; | ||
|
||
if inserted { | ||
// Reset backoff before returning, for the next attempt to lock. | ||
self.backoff = Self::INITIAL_BACKOFF_MS; | ||
return Ok(()); | ||
} | ||
|
||
// Double-check that we were not interrupted last time we tried to take the | ||
// lock, and forgot to release it; in that case, we *still* hold it. | ||
let previous = self.store.get_custom_value(&self.lock_key).await?; | ||
if previous.as_deref() == Some(self.lock_holder.as_bytes()) { | ||
// At this point, the only possible value for backoff is the initial one, but | ||
// better be safe than sorry. | ||
tracing::warn!( | ||
"Crypto-store lock {} was already taken by {}; let's pretend we just acquired it.", | ||
self.lock_key, | ||
self.lock_holder | ||
); | ||
self.backoff = Self::INITIAL_BACKOFF_MS; | ||
return Ok(()); | ||
} | ||
|
||
// Exponential backoff! Multiply by 2 the time we've waited before, cap it to | ||
// max_backoff. | ||
let wait = self.backoff; | ||
|
||
// If we've set the sentinel value before, that means this wait would be longer | ||
// than the max backoff, so abort. | ||
if wait == u32::MAX { | ||
// We've reached the maximum backoff, abandon. | ||
return Err(LockStoreError::LockTimeout.into()); | ||
} | ||
|
||
self.backoff = self.backoff.saturating_mul(2); | ||
if self.backoff >= self.max_backoff { | ||
// Set the sentinel value that indicates that we should timeout, were we to wait | ||
// more. | ||
self.backoff = u32::MAX; | ||
} | ||
|
||
sleep(Duration::from_millis(wait.into())).await; | ||
} | ||
} | ||
|
||
/// Release the lock taken previously with [`lock()`]. | ||
/// | ||
/// Will return an error if the lock wasn't taken. | ||
pub async fn unlock(&mut self) -> Result<(), CryptoStoreError> { | ||
let read = self | ||
.store | ||
.get_custom_value(&self.lock_key) | ||
.await? | ||
.ok_or(CryptoStoreError::from(LockStoreError::MissingLockValue))?; | ||
|
||
if read != self.lock_holder.as_bytes() { | ||
return Err(LockStoreError::IncorrectLockValue.into()); | ||
} | ||
|
||
let removed = self.store.remove_custom_value(&self.lock_key).await?; | ||
if removed { | ||
Ok(()) | ||
} else { | ||
Err(LockStoreError::MissingLockValue.into()) | ||
} | ||
} | ||
} | ||
|
||
/// Error related to the locking API of the crypto store. | ||
#[derive(Debug, thiserror::Error)] | ||
pub enum LockStoreError { | ||
/// A lock value was to be removed, but it didn't contain the expected lock | ||
/// value. | ||
#[error("a lock value was to be removed, but it didn't contain the expected lock value")] | ||
IncorrectLockValue, | ||
|
||
/// A lock value was to be removed, but it was missing in the database. | ||
#[error("a lock value was to be removed, but it was missing in the database")] | ||
MissingLockValue, | ||
|
||
/// Spent too long waiting for a database lock. | ||
#[error("a lock timed out")] | ||
LockTimeout, | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -80,6 +80,7 @@ use crate::{ | |
|
||
pub mod caches; | ||
mod error; | ||
pub mod locks; | ||
mod memorystore; | ||
mod traits; | ||
|
||
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.