Skip to content

Commit

Permalink
Remove BuildError::Config variant
Browse files Browse the repository at this point in the history
That variant was added back by accident when merging the
arangodb PR.
  • Loading branch information
bikeshedder committed Nov 3, 2021
1 parent 638e85a commit 0c784fc
Show file tree
Hide file tree
Showing 5 changed files with 86 additions and 45 deletions.
2 changes: 1 addition & 1 deletion arangodb/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ rt_async-std_1 = ["deadpool/rt_async-std_1", "arangors/surf_async"]
serde = ["deadpool/serde", "serde_1"]

[dependencies]
deadpool = { path = "../", version = "0.9.0-pre", default-features = false, features = ["managed"] }
deadpool = { path = "../", version = "0.9.0", default-features = false, features = ["managed"] }
arangors = { git = "https://github.com/fMeow/arangors", rev = "2c31587", default-features = false, features = ["rocksdb"] }
serde_1 = { package = "serde", version = "1.0", features = ["derive"], optional = true }
url = "2.2"
Expand Down
79 changes: 61 additions & 18 deletions arangodb/src/config.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
use deadpool::{managed::BuildError, Runtime};
use std::fmt;

use deadpool::Runtime;
#[cfg(feature = "serde")]
use serde_1::Deserialize;
use url::Url;

use crate::{Pool, PoolConfig};
use crate::{CreatePoolError, Pool, PoolConfig};

/// Configuration object.
///
Expand Down Expand Up @@ -67,51 +69,51 @@ impl Config {
/// Creates a new [`Config`] from the given URL.
///
/// Url format is: `http://username:password@localhost:8529/?use_jwt=true`. If `use_jwt` is missing, then it defaults to `true`.
pub fn from_url<U: Into<String>>(url: U) -> Result<Self, BuildError<()>> {
pub fn from_url<U: Into<String>>(url: U) -> Result<Self, ConfigError> {
let url = url.into();
let url = Url::parse(&url)
.map_err(|e| BuildError::Config(format!("Could not extract a valid config from url: `{}` - Error: {}", url, e)))?;
let url = Url::parse(&url).map_err(|e| ConfigError::InvalidUrl(url, e))?;

let use_jwt = url.query_pairs()
let use_jwt = url
.query_pairs()
.filter(|(name, _)| name == "use_jwt")
.map(|(_, value)| value.to_string())
.next();
let use_jwt = match use_jwt {
Some(use_jwt) => use_jwt.parse()
.map_err(|e| BuildError::Config(format!("Could not parse `use_jwt` value: `{}` - Error: {}", use_jwt, e)))?,
Some(use_jwt) => use_jwt
.parse()
.map_err(|e| ConfigError::InvalidUseJwt(use_jwt, e))?,
None => true,
};

Ok(Config {
url: Some(format!("{}://{}:{}", url.scheme(), url.host_str().unwrap(), url.port_or_known_default().unwrap())),
url: Some(format!(
"{}://{}:{}",
url.scheme(),
url.host_str().unwrap(),
url.port_or_known_default().unwrap()
)),
username: Some(url.username().to_string()),
password: url.password().map(ToString::to_string),
use_jwt,
pool: None,
})
}


/// Creates a new [`Pool`] using this [`Config`].
///
/// # Errors
///
/// See [`BuildError`] and [`ClientError`] for details.
///
/// [`ClientError`]: arangors::ClientError
pub fn create_pool(&self, runtime: Runtime) -> Result<Pool, BuildError<arangors::ClientError>> {
let manager = match (&self.url, &self.username, &self.password) {
(Some(_), Some(_), Some(_)) => crate::Manager::from_config(self.clone())?,
_ => {
return Err(BuildError::Config("url, username and password must be specified.".into()))
}
};

pub fn create_pool(&self, runtime: Runtime) -> Result<Pool, CreatePoolError> {
let manager = crate::Manager::from_config(self.clone())?;
let pool_config = self.get_pool_config();
Pool::builder(manager)
.config(pool_config)
.runtime(runtime)
.build()
.map_err(CreatePoolError::Build)
}

/// Returns [`deadpool::managed::PoolConfig`] which can be used to construct
Expand All @@ -133,3 +135,44 @@ impl Default for Config {
}
}
}

/// This error is returned if the configuration contains an error
#[derive(Debug)]
pub enum ConfigError {
/// The `url` is invalid
InvalidUrl(String, url::ParseError),
/// The `use_jwt` part of the URL is invalid
InvalidUseJwt(String, std::str::ParseBoolError),
/// The `use` is `None`
MissingUrl,
/// The `username` is `None`
MissingUsername,
/// The `password` is None
MissingPassword,
}

impl fmt::Display for ConfigError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidUrl(url, e) => write!(f, "InvalidUrl: {} - Error: {}", url, e),
Self::InvalidUseJwt(use_jwt, e) => write!(
f,
"Could not parse `use_jwt` value: `{}` - Error: {}",
use_jwt, e
),
Self::MissingUrl => write!(f, "Missing URL"),
Self::MissingUsername => write!(f, "Missing username"),
Self::MissingPassword => write!(f, "Missing password"),
}
}
}

impl std::error::Error for ConfigError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::InvalidUrl(_, e) => Some(e),
Self::InvalidUseJwt(_, e) => Some(e),
_ => None,
}
}
}
31 changes: 18 additions & 13 deletions arangodb/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,26 +22,26 @@

mod config;

use std::{convert::Infallible, ops::{Deref, DerefMut}};

use arangors::{
Connection as ArangoConnection,
ClientError, uclient::ClientExt,
use std::{
convert::Infallible,
ops::{Deref, DerefMut},
};

use arangors::{uclient::ClientExt, ClientError, Connection as ArangoConnection};
use deadpool::{async_trait, managed};
use url::Url;

pub use arangors;

pub use self::config::{Config};
pub use self::config::{Config, ConfigError};

pub use deadpool::managed::reexports::*;
deadpool::managed_reexports!(
"arangors",
Manager,
deadpool::managed::Object<Manager>,
ClientError,
Infallible
ConfigError
);

/// Type alias for using [`deadpool::managed::RecycleResult`] with [`arangors`].
Expand Down Expand Up @@ -121,11 +121,17 @@ impl Manager {
}

/// Creates a new [`Manager`] with the given params.
pub fn from_config(config: Config) -> Result<Self, BuildError> {
pub fn from_config(config: Config) -> Result<Self, CreatePoolError> {
Ok(Self {
url: config.url.ok_or(BuildError::Config("url must be specified.".into()))?,
username: config.username.ok_or(BuildError::Config("username must be specified.".into()))?,
password: config.password.ok_or(BuildError::Config("password must be specified.".into()))?,
url: config
.url
.ok_or(CreatePoolError::Config(ConfigError::MissingUrl))?,
username: config
.username
.ok_or(CreatePoolError::Config(ConfigError::MissingUsername))?,
password: config
.password
.ok_or(CreatePoolError::Config(ConfigError::MissingPassword))?,
use_jwt: config.use_jwt,
})
}
Expand All @@ -138,8 +144,7 @@ impl managed::Manager for Manager {

async fn create(&self) -> Result<Self::Type, Self::Error> {
let conn = if self.use_jwt {
ArangoConnection::establish_jwt(&self.url, &self.username, &self.password)
.await?
ArangoConnection::establish_jwt(&self.url, &self.username, &self.password).await?
} else {
ArangoConnection::establish_basic_auth(&self.url, &self.username, &self.password)
.await?
Expand Down
10 changes: 5 additions & 5 deletions arangodb/tests/arangodb.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,17 @@
use serde_1::Deserialize;

use deadpool_arangodb::{Pool, Runtime};

use deadpool_arangodb::Runtime;

fn default_dbname() -> String {
"deadpool".to_string()
}


#[derive(Debug, Default, Deserialize)]
#[serde(crate = "serde_1")]
struct Config {
#[serde(default)]
arango: deadpool_arangodb::Config,
#[serde(default="default_dbname")]
#[serde(default = "default_dbname")]
dbname: String,
}

Expand All @@ -23,7 +21,9 @@ impl Config {
cfg.merge(config::Environment::new().separator("__"))
.unwrap();
let mut cfg = cfg.try_into::<Self>().unwrap();
cfg.arango.url.get_or_insert("http://localhost:8529".to_string());
cfg.arango
.url
.get_or_insert("http://localhost:8529".to_string());
cfg
}
}
Expand Down
9 changes: 1 addition & 8 deletions src/managed/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,6 @@ use super::{
/// [`Pool`].
#[derive(Debug)]
pub enum BuildError<E> {
/// Something is wrong with the configuration.
/// See message string for details.
Config(String),

/// Backend reported an error when creating a [`Pool`].
Backend(E),

Expand All @@ -25,9 +21,6 @@ pub enum BuildError<E> {
impl<E: std::fmt::Display> fmt::Display for BuildError<E> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Config(msg) => {
write!(f, "Error occurred while building the pool: Config: {}", msg)
}
Self::Backend(e) => write!(f, "Error occurred while building the pool: Backend: {}", e),
Self::NoRuntimeSpecified(msg) => write!(
f,
Expand All @@ -42,7 +35,7 @@ impl<E: std::error::Error + 'static> std::error::Error for BuildError<E> {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Backend(e) => Some(e),
Self::Config(_) | Self::NoRuntimeSpecified(_) => None,
Self::NoRuntimeSpecified(_) => None,
}
}
}
Expand Down

0 comments on commit 0c784fc

Please sign in to comment.