Skip to content
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

error-chain -> thiserror port #131

Draft
wants to merge 3 commits into
base: async
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion aerospike-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ base64 = "0.11"
crossbeam-queue = "0.2"
rand = "0.7"
lazy_static = "1.4"
error-chain = "0.12"
# error-chain = "0.12"
thiserror = "1.0.40"
pwhash = "0.3"
serde = { version = "1.0", features = ["derive"], optional = true }
aerospike-rt = {path = "../aerospike-rt"}
Expand Down
35 changes: 20 additions & 15 deletions aerospike-core/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ use crate::commands::{
DeleteCommand, ExecuteUDFCommand, ExistsCommand, OperateCommand, QueryCommand, ReadCommand,
ScanCommand, TouchCommand, WriteCommand,
};
use crate::errors::{ErrorKind, Result, ResultExt};
use crate::errors::{Error, Result};
use crate::net::ToHosts;
use crate::operations::{Operation, OperationType};
use crate::policy::{BatchPolicy, ClientPolicy, QueryPolicy, ReadPolicy, ScanPolicy, WritePolicy};
Expand Down Expand Up @@ -148,7 +148,7 @@ impl Client {
/// match client.get(&ReadPolicy::default(), &key, ["a", "b"]).await {
/// Ok(record)
/// => println!("a={:?}", record.bins.get("a")),
/// Err(Error(ErrorKind::ServerError(ResultCode::KeyNotFoundError), _))
/// Err(Error::ServerError(ResultCode::KeyNotFoundError))
/// => println!("No such record: {}", key),
/// Err(err)
/// => println!("Error fetching record: {}", err),
Expand All @@ -170,7 +170,7 @@ impl Client {
/// Some(duration) => println!("ttl: {} secs", duration.as_secs()),
/// }
/// },
/// Err(Error(ErrorKind::ServerError(ResultCode::KeyNotFoundError), _))
/// Err(Error::ServerError(ResultCode::KeyNotFoundError))
/// => println!("No such record: {}", key),
/// Err(err)
/// => println!("Error fetching record: {}", err),
Expand Down Expand Up @@ -495,13 +495,13 @@ impl Client {
if let Some(msg) = response.get("error") {
let msg = base64::decode(msg)?;
let msg = str::from_utf8(&msg)?;
bail!(
return Err(Error::UdfBadResponse(format!(
"UDF Registration failed: {}, file: {}, line: {}, message: {}",
response.get("error").unwrap_or(&"-".to_string()),
response.get("file").unwrap_or(&"-".to_string()),
response.get("line").unwrap_or(&"-".to_string()),
msg
);
)));
}

Ok(RegisterTask::new(
Expand Down Expand Up @@ -539,7 +539,12 @@ impl Client {

match response.get(&cmd).map(String::as_str) {
Some("ok") => Ok(()),
_ => bail!("UDF Remove failed: {:?}", response),
_ => {
return Err(Error::UdfBadResponse(format!(
"UDF Remove failed: {:?}",
response
)))
}
}
}

Expand Down Expand Up @@ -578,11 +583,11 @@ impl Client {
if key.contains("SUCCESS") {
return Ok(Some(value.clone()));
} else if key.contains("FAILURE") {
bail!("{:?}", value);
return Err(Error::UdfBadResponse(value.to_string()));
}
}

Err("Invalid UDF return value".into())
Err(Error::UdfBadResponse("Invalid UDF return value".into()))
}

/// Read all records in the specified namespace and set and return a record iterator. The scan
Expand Down Expand Up @@ -808,7 +813,7 @@ impl Client {

self.send_info_cmd(&cmd)
.await
.chain_err(|| "Error truncating ns/set")
.map_err(|e| e.chain_error("Error truncating ns/set"))
}

/// Create a secondary index on a bin containing scalar values. This asynchronous server call
Expand Down Expand Up @@ -879,7 +884,7 @@ impl Client {
);
self.send_info_cmd(&cmd)
.await
.chain_err(|| "Error creating index")
.map_err(|e| e.chain_error("Error creating index"))
}

/// Delete secondary index.
Expand All @@ -900,7 +905,7 @@ impl Client {
);
self.send_info_cmd(&cmd)
.await
.chain_err(|| "Error dropping index")
.map_err(|e| e.chain_error("Error dropping index"))
}

async fn send_info_cmd(&self, cmd: &str) -> Result<()> {
Expand All @@ -912,12 +917,12 @@ impl Client {
return Ok(());
} else if v.starts_with("FAIL:") {
let result = v.split(':').nth(1).unwrap().parse::<u8>()?;
bail!(ErrorKind::ServerError(ResultCode::from(result)));
return Err(Error::ServerError(ResultCode::from(result)));
}
}

bail!(ErrorKind::BadResponse(
"Unexpected sindex info command response".to_string()
))
return Err(Error::BadResponse(
"Unexpected sindex info command response".to_string(),
));
}
}
18 changes: 10 additions & 8 deletions aerospike-core/src/cluster/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ use self::node_validator::NodeValidator;
use self::partition::Partition;
use self::partition_tokenizer::PartitionTokenizer;

use crate::errors::{ErrorKind, Result};
use crate::errors::{Error, Result};
use crate::net::Host;
use crate::policy::ClientPolicy;
use aerospike_rt::RwLock;
Expand Down Expand Up @@ -84,11 +84,11 @@ impl Cluster {

// apply policy rules
if cluster.client_policy.fail_if_not_connected && !cluster.is_connected().await {
bail!(ErrorKind::Connection(
return Err(Error::Connection(
"Failed to connect to host(s). The network \
connection(s) to cluster nodes may have timed out, or \
the cluster may be in a state of flux."
.to_string()
.to_string(),
));
}

Expand Down Expand Up @@ -201,9 +201,9 @@ impl Cluster {
});

#[cfg(all(feature = "rt-tokio", not(feature = "rt-async-std")))]
return handle
.await
.map_err(|err| format!("Error during initial cluster tend: {:?}", err).into());
return handle.await.map_err(|err| {
Error::InvalidArgument(format!("Error during initial cluster tend: {:?}", err).into())
});
#[cfg(all(feature = "rt-async-std", not(feature = "rt-tokio")))]
return {
handle.await;
Expand Down Expand Up @@ -518,7 +518,7 @@ impl Cluster {
}
}

bail!("No active node")
return Err(Error::Connection("No active node".into()));
}

pub async fn get_node_by_name(&self, node_name: &str) -> Result<Arc<Node>> {
Expand All @@ -530,7 +530,9 @@ impl Cluster {
}
}

bail!("Requested node `{}` not found.", node_name)
return Err(Error::InvalidNode(format!(
"Requested node `{node_name}` not found."
)));
}

pub async fn close(&self) -> Result<()> {
Expand Down
28 changes: 15 additions & 13 deletions aerospike-core/src/cluster/node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use std::sync::Arc;

use crate::cluster::node_validator::NodeValidator;
use crate::commands::Message;
use crate::errors::{ErrorKind, Result, ResultExt};
use crate::errors::{Error, Result};
use crate::net::{ConnectionPool, Host, PooledConnection};
use crate::policy::ClientPolicy;
use aerospike_rt::RwLock;
Expand Down Expand Up @@ -129,15 +129,15 @@ impl Node {
let info_map = self
.info(&commands)
.await
.chain_err(|| "Info command failed")?;
.map_err(|e| e.chain_error("Info command failed"))?;
self.validate_node(&info_map)
.chain_err(|| "Failed to validate node")?;
.map_err(|e| e.chain_error("Failed to validate node"))?;
self.responded.store(true, Ordering::Relaxed);
let friends = self
.add_friends(current_aliases, &info_map)
.chain_err(|| "Failed to add friends")?;
.map_err(|e| e.chain_error("Failed to add friends"))?;
self.update_partitions(&info_map)
.chain_err(|| "Failed to update partitions")?;
.map_err(|e| e.chain_error("Failed to update partitions"))?;
self.reset_failures();
Ok(friends)
}
Expand All @@ -159,11 +159,11 @@ impl Node {

fn verify_node_name(&self, info_map: &HashMap<String, String>) -> Result<()> {
match info_map.get("node") {
None => Err(ErrorKind::InvalidNode("Missing node name".to_string()).into()),
None => Err(Error::InvalidNode("Missing node name".to_string()).into()),
Some(info_name) if info_name == &self.name => Ok(()),
Some(info_name) => {
self.inactivate();
Err(ErrorKind::InvalidNode(format!(
Err(Error::InvalidNode(format!(
"Node name has changed: '{}' => '{}'",
self.name, info_name
))
Expand All @@ -176,11 +176,11 @@ impl Node {
match self.client_policy.cluster_name {
None => Ok(()),
Some(ref expected) => match info_map.get("cluster-name") {
None => Err(ErrorKind::InvalidNode("Missing cluster name".to_string()).into()),
None => Err(Error::InvalidNode("Missing cluster name".to_string()).into()),
Some(info_name) if info_name == expected => Ok(()),
Some(info_name) => {
self.inactivate();
Err(ErrorKind::InvalidNode(format!(
Err(Error::InvalidNode(format!(
"Cluster name mismatch: expected={},
got={}",
expected, info_name
Expand All @@ -199,7 +199,7 @@ impl Node {
let mut friends: Vec<Host> = vec![];

let friend_string = match info_map.get(self.services_name()) {
None => bail!(ErrorKind::BadResponse("Missing services list".to_string())),
None => return Err(Error::BadResponse("Missing services list".to_string())),
Some(friend_string) if friend_string.is_empty() => return Ok(friends),
Some(friend_string) => friend_string,
};
Expand Down Expand Up @@ -237,9 +237,11 @@ impl Node {

fn update_partitions(&self, info_map: &HashMap<String, String>) -> Result<()> {
match info_map.get("partition-generation") {
None => bail!(ErrorKind::BadResponse(
"Missing partition generation".to_string()
)),
None => {
return Err(Error::BadResponse(
"Missing partition generation".to_string(),
))
}
Some(gen_string) => {
let gen = gen_string.parse::<isize>()?;
self.partition_generation.store(gen, Ordering::Relaxed);
Expand Down
20 changes: 11 additions & 9 deletions aerospike-core/src/cluster/node_validator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use std::vec::Vec;

use crate::cluster::Cluster;
use crate::commands::Message;
use crate::errors::{ErrorKind, Result, ResultExt};
use crate::errors::{Error, Result};
use crate::net::{Connection, Host};
use crate::policy::ClientPolicy;

Expand Down Expand Up @@ -55,7 +55,7 @@ impl NodeValidator {

pub async fn validate_node(&mut self, cluster: &Cluster, host: &Host) -> Result<()> {
self.resolve_aliases(host)
.chain_err(|| "Failed to resolve host aliases")?;
.map_err(|e| e.chain_error("Failed to resolve host aliases"))?;

let mut last_err = None;
for alias in &self.aliases() {
Expand Down Expand Up @@ -84,7 +84,7 @@ impl NodeValidator {
.collect();
debug!("Resolved aliases for host {}: {:?}", host, self.aliases);
if self.aliases.is_empty() {
Err(ErrorKind::Connection(format!("Failed to find addresses for {}", host)).into())
Err(Error::Connection(format!("Failed to find addresses for {}", host)).into())
} else {
Ok(())
}
Expand All @@ -95,19 +95,21 @@ impl NodeValidator {
let info_map = Message::info(&mut conn, &["node", "cluster-name", "features"]).await?;

match info_map.get("node") {
None => bail!(ErrorKind::InvalidNode(String::from("Missing node name"))),
None => return Err(Error::InvalidNode(String::from("Missing node name"))),
Some(node_name) => self.name = node_name.clone(),
}

if let Some(ref cluster_name) = *cluster.cluster_name() {
match info_map.get("cluster-name") {
None => bail!(ErrorKind::InvalidNode(String::from("Missing cluster name"))),
None => return Err(Error::InvalidNode(String::from("Missing cluster name"))),
Some(info_name) if info_name == cluster_name => {}
Some(info_name) => bail!(ErrorKind::InvalidNode(format!(
"Cluster name mismatch: expected={},
Some(info_name) => {
return Err(Error::InvalidNode(format!(
"Cluster name mismatch: expected={},
got={}",
cluster_name, info_name
))),
cluster_name, info_name
)))
}
}
}

Expand Down
6 changes: 3 additions & 3 deletions aerospike-core/src/cluster/partition_tokenizer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ use std::vec::Vec;
use crate::cluster::node;
use crate::cluster::Node;
use crate::commands::Message;
use crate::errors::{ErrorKind, Result};
use crate::errors::{Error, Result};
use crate::net::Connection;
use aerospike_rt::RwLock;

Expand All @@ -45,7 +45,7 @@ impl PartitionTokenizer {
offset: 0,
});
}
bail!(ErrorKind::BadResponse("Missing replicas info".to_string()))
return Err(Error::BadResponse("Missing replicas info".to_string()))
}

pub async fn update_partition(
Expand Down Expand Up @@ -76,7 +76,7 @@ impl PartitionTokenizer {
}
}
(None, None) => break,
_ => bail!(ErrorKind::BadResponse(
_ => return Err(Error::BadResponse(
"Error parsing partition info".to_string()
)),
}
Expand Down
6 changes: 3 additions & 3 deletions aerospike-core/src/commands/admin_command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ use std::str;
use pwhash::bcrypt::{self, BcryptSetup, BcryptVariant};

use crate::cluster::Cluster;
use crate::errors::{ErrorKind, Result};
use crate::errors::{Error, Result};
use crate::net::Connection;
use crate::net::PooledConnection;
use crate::ResultCode;
Expand Down Expand Up @@ -81,7 +81,7 @@ impl AdminCommand {
let result_code = conn.buffer.read_u8(Some(RESULT_CODE));
let result_code = ResultCode::from(result_code);
if result_code != ResultCode::Ok {
bail!(ErrorKind::ServerError(result_code));
return Err(Error::ServerError(result_code));
}

Ok(())
Expand All @@ -103,7 +103,7 @@ impl AdminCommand {
let result_code = conn.buffer.read_u8(Some(RESULT_CODE));
let result_code = ResultCode::from(result_code);
if ResultCode::SecurityNotEnabled != result_code && ResultCode::Ok != result_code {
bail!(ErrorKind::ServerError(result_code));
return Err(Error::ServerError(result_code));
}

// consume the rest of the buffer
Expand Down
Loading