Skip to content

Commit

Permalink
refactor: add a syntactic sugar method
Browse files Browse the repository at this point in the history
Signed-off-by: Phoeniix Zhao <Phoenix500526@163.com>
  • Loading branch information
Phoenix500526 committed Jun 11, 2024
1 parent e104226 commit 7decae5
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 13 deletions.
6 changes: 2 additions & 4 deletions crates/curp/src/server/storage/wal/segment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,14 @@ use tokio::{
};
use tokio_stream::StreamExt;

use crate::log_entry::LogEntry;

use super::{
codec::{DataFrame, DataFrameOwned, WAL},
error::{CorruptType, WALError},
framed::{Decoder, Encoder},
util::{get_checksum, parse_u64, validate_data, LockedFile},
WAL_FILE_EXT, WAL_MAGIC, WAL_VERSION,
};
use crate::log_entry::LogEntry;

/// The size of wal file header in bytes
const WAL_HEADER_SIZE: usize = 56;
Expand Down Expand Up @@ -307,9 +306,8 @@ mod tests {

use curp_test_utils::test_cmd::TestCommand;

use crate::log_entry::EntryData;

use super::*;
use crate::log_entry::EntryData;

#[test]
fn gen_parse_header_is_correct() {
Expand Down
28 changes: 19 additions & 9 deletions crates/xline-client/examples/lock.rs
Original file line number Diff line number Diff line change
@@ -1,23 +1,33 @@
use anyhow::Result;
use xline_client::{clients::Xutex, Client, ClientOptions};
use xline_client::{
clients::Xutex,
types::kv::{Compare, CompareResult, PutRequest, TxnOp},
Client, ClientOptions,
};

#[tokio::main]
async fn main() -> Result<()> {
// the name and address of all curp members
let curp_members = ["10.0.0.1:2379", "10.0.0.2:2379", "10.0.0.3:2379"];

let client = Client::connect(curp_members, ClientOptions::default())
.await?
.lock_client();
let client = Client::connect(curp_members, ClientOptions::default()).await?;

let mut xutex = Xutex::new(client, "lock-test", None, None).await?;
let lock_client = client.lock_client();
let kv_client = client.kv_client();

let mut xutex = Xutex::new(lock_client, "lock-test", None, None).await?;
// when the `xutex_guard` drop, the lock will be unlocked.
let xutex_guard = xutex.lock().await?;

println!(
"lock key: {:?}",
String::from_utf8_lossy(xutex_guard.key().as_bytes())
);
let txn_req = xutex_guard
.txn_check_locked_key()
.when([Compare::value("key2", CompareResult::Equal, "value2")])
.and_then([TxnOp::put(
PutRequest::new("key2", "value3").with_prev_kv(true),
)])
.or_else(&[]);

let _resp = kv_client.txn(txn_req).await?;

Ok(())
}
29 changes: 29 additions & 0 deletions crates/xline-client/src/clients/lock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ use crate::{
error::{Result, XlineClientError},
lease_gen::LeaseIdGenerator,
types::{
kv::TxnRequest as KvTxnRequest,
lease::{LeaseGrantRequest, LeaseKeepAliveRequest},
watch::WatchRequest,
},
Expand Down Expand Up @@ -82,6 +83,24 @@ impl XutexGuard {
pub fn key(&self) -> &str {
self.key.as_str()
}

/// Return a `TxnRequest` which will perform the success ops when the locked key is exist.
/// This method is syntactic sugar
#[inline]
#[must_use]
pub fn txn_check_locked_key(&self) -> KvTxnRequest {
let mut txn_request = KvTxnRequest::new();
#[allow(clippy::as_conversions)]
let cmp = Compare {
result: CompareResult::Greater as i32,
target: CompareTarget::Create as i32,
key: self.key().into(),
range_end: Vec::new(),
target_union: Some(TargetUnion::CreateRevision(0)),
};
txn_request.inner.compare.push(cmp);
txn_request
}
}

#[async_trait]
Expand Down Expand Up @@ -263,6 +282,16 @@ impl Xutex {
/// ```
#[inline]
pub async fn lock(&mut self) -> Result<AsyncDropper<XutexGuard>> {
if self
.session
.keep_alive
.as_ref()
.is_some_and(JoinHandle::is_finished)
{
return Err(XlineClientError::LeaseError(String::from(
"Lock renew task exists unexpectedly",
)));
}
let resp = self.try_acquire().await?;
#[allow(clippy::indexing_slicing)]
if let Some(Response::ResponseRange(ref lock_owner)) = resp.responses[1].response {
Expand Down

0 comments on commit 7decae5

Please sign in to comment.