Skip to content

Commit

Permalink
rename AtError => Error (actix#275)
Browse files Browse the repository at this point in the history
* refactor(settings)!: rename AtError => Error

and remove AtResult from public API

* update changelog

* recover from file metadata errors
  • Loading branch information
robjtede committed Aug 10, 2022
1 parent a325f5d commit e61dbae
Show file tree
Hide file tree
Showing 12 changed files with 72 additions and 67 deletions.
4 changes: 4 additions & 0 deletions actix-settings/CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,15 @@

## Unreleased - 2022-xx-xx

- Rename `AtError => Error`.
- Remove `AtResult` type alias.

## 0.6.0 - 2022-07-31

- Update Actix Web dependencies to v4 ecosystem.
- Rename `actix.ssl` settings object to `actix.tls`.
- `NoSettings` is now marked `#[non_exhaustive]`.

## 0.5.2 - 2022-07-31

- Adopted into @actix org from <https://github.com/jjpe/actix-settings>.
39 changes: 18 additions & 21 deletions actix-settings/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,9 @@ use std::{env::VarError, io, num::ParseIntError, path::PathBuf, str::ParseBoolEr

use toml::de::Error as TomlError;

/// Convenience type alias for `Result<T, AtError>`.
pub type AtResult<T> = std::result::Result<T, AtError>;

/// Errors that can be returned from methods in this crate.
#[derive(Debug, Clone)]
pub enum AtError {
pub enum Error {
/// Environment variable does not exists or is invalid.
EnvVarError(VarError),

Expand Down Expand Up @@ -42,7 +39,7 @@ pub enum AtError {

macro_rules! InvalidValue {
(expected: $expected:expr, got: $got:expr,) => {
crate::AtError::InvalidValue {
crate::Error::InvalidValue {
expected: $expected,
got: $got.to_string(),
file: file!(),
Expand All @@ -52,56 +49,56 @@ macro_rules! InvalidValue {
};
}

impl From<io::Error> for AtError {
impl From<io::Error> for Error {
fn from(err: io::Error) -> Self {
Self::IoError(ioe::IoError::from(err))
}
}

impl From<ioe::IoError> for AtError {
impl From<ioe::IoError> for Error {
fn from(err: ioe::IoError) -> Self {
Self::IoError(err)
}
}

impl From<ParseBoolError> for AtError {
impl From<ParseBoolError> for Error {
fn from(err: ParseBoolError) -> Self {
Self::ParseBoolError(err)
}
}

impl From<ParseIntError> for AtError {
impl From<ParseIntError> for Error {
fn from(err: ParseIntError) -> Self {
Self::ParseIntError(err)
}
}

impl From<TomlError> for AtError {
impl From<TomlError> for Error {
fn from(err: TomlError) -> Self {
Self::TomlError(err)
}
}

impl From<VarError> for AtError {
impl From<VarError> for Error {
fn from(err: VarError) -> Self {
Self::EnvVarError(err)
}
}

impl From<AtError> for io::Error {
fn from(err: AtError) -> Self {
impl From<Error> for io::Error {
fn from(err: Error) -> Self {
match err {
AtError::EnvVarError(var_error) => {
Error::EnvVarError(var_error) => {
let msg = format!("Env var error: {}", var_error);
io::Error::new(io::ErrorKind::InvalidInput, msg)
}

AtError::FileExists(path_buf) => {
Error::FileExists(path_buf) => {
let msg = format!("File exists: {}", path_buf.display());
io::Error::new(io::ErrorKind::AlreadyExists, msg)
}

AtError::InvalidValue {
Error::InvalidValue {
expected,
ref got,
file,
Expand All @@ -115,24 +112,24 @@ impl From<AtError> for io::Error {
io::Error::new(io::ErrorKind::InvalidInput, msg)
}

AtError::IoError(io_error) => io_error.into(),
Error::IoError(io_error) => io_error.into(),

AtError::ParseBoolError(parse_bool_error) => {
Error::ParseBoolError(parse_bool_error) => {
let msg = format!("Failed to parse boolean: {}", parse_bool_error);
io::Error::new(io::ErrorKind::InvalidInput, msg)
}

AtError::ParseIntError(parse_int_error) => {
Error::ParseIntError(parse_int_error) => {
let msg = format!("Failed to parse integer: {}", parse_int_error);
io::Error::new(io::ErrorKind::InvalidInput, msg)
}

AtError::ParseAddressError(string) => {
Error::ParseAddressError(string) => {
let msg = format!("Failed to parse address: {}", string);
io::Error::new(io::ErrorKind::InvalidInput, msg)
}

AtError::TomlError(toml_error) => {
Error::TomlError(toml_error) => {
let msg = format!("TOML error: {}", toml_error);
io::Error::new(io::ErrorKind::InvalidInput, msg)
}
Expand Down
30 changes: 17 additions & 13 deletions actix-settings/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,13 +89,16 @@ mod error;
mod parse;
mod settings;

pub use self::error::{AtError, AtResult};
pub use self::error::Error;
pub use self::parse::Parse;
pub use self::settings::{
ActixSettings, Address, Backlog, KeepAlive, MaxConnectionRate, MaxConnections, Mode,
NumWorkers, Timeout, Tls,
};

/// Convenience type alias for `Result<T, AtError>`.
type AsResult<T> = std::result::Result<T, Error>;

/// Wrapper for server and application-specific settings.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize)]
#[serde(bound = "A: Deserialize<'de>")]
Expand Down Expand Up @@ -129,7 +132,7 @@ where
///
/// If the file doesn't exist, it is generated from the default TOML template, after which the
/// newly generated file is read in and parsed.
pub fn parse_toml<P>(filepath: P) -> AtResult<Self>
pub fn parse_toml<P>(filepath: P) -> AsResult<Self>
where
P: AsRef<Path>,
{
Expand All @@ -140,8 +143,9 @@ where
}

let mut f = File::open(filepath)?;
// TODO: don't bail on metadata fail
let mut contents = String::with_capacity(f.metadata()?.len() as usize);
let len_guess = f.metadata().map(|md| md.len()).unwrap_or(128);

let mut contents = String::with_capacity(len_guess as usize);
f.read_to_string(&mut contents)?;

Ok(toml::from_str::<Self>(&contents)?)
Expand All @@ -150,13 +154,13 @@ where
/// Parse an instance of `Self` straight from the default TOML template.
// TODO: make infallible
// TODO: consider "template" rename
pub fn from_default_template() -> AtResult<Self> {
pub fn from_default_template() -> AsResult<Self> {
Self::from_template(Self::DEFAULT_TOML_TEMPLATE)
}

/// Parse an instance of `Self` straight from the default TOML template.
// TODO: consider "template" rename
pub fn from_template(template: &str) -> AtResult<Self> {
pub fn from_template(template: &str) -> AsResult<Self> {
Ok(toml::from_str(template)?)
}

Expand All @@ -165,14 +169,14 @@ where
/// # Errors
/// Returns a [`FileExists`](crate::AtError::FileExists) error if a file already exists at that
/// location.
pub fn write_toml_file<P>(filepath: P) -> AtResult<()>
pub fn write_toml_file<P>(filepath: P) -> AsResult<()>
where
P: AsRef<Path>,
{
let filepath = filepath.as_ref();

if filepath.exists() {
return Err(AtError::FileExists(filepath.to_path_buf()));
return Err(Error::FileExists(filepath.to_path_buf()));
}

let mut file = File::create(filepath)?;
Expand All @@ -188,15 +192,15 @@ where
/// ```
/// use actix_settings::{Settings, Mode};
///
/// # fn inner() -> actix_settings::AtResult<()> {
/// # fn inner() -> Result<(), actix_settings::Error> {
/// let mut settings = Settings::from_default_template()?;
/// assert_eq!(settings.actix.mode, Mode::Development);
///
/// Settings::override_field(&mut settings.actix.mode, "production")?;
/// assert_eq!(settings.actix.mode, Mode::Production);
/// # Ok(()) }
/// ```
pub fn override_field<F, V>(field: &mut F, value: V) -> AtResult<()>
pub fn override_field<F, V>(field: &mut F, value: V) -> AsResult<()>
where
F: Parse,
V: AsRef<str>,
Expand All @@ -213,22 +217,22 @@ where
///
/// std::env::set_var("OVERRIDE__MODE", "production");
///
/// # fn inner() -> actix_settings::AtResult<()> {
/// # fn inner() -> Result<(), actix_settings::Error> {
/// let mut settings = Settings::from_default_template()?;
/// assert_eq!(settings.actix.mode, Mode::Development);
///
/// Settings::override_field_with_env_var(&mut settings.actix.mode, "OVERRIDE__MODE")?;
/// assert_eq!(settings.actix.mode, Mode::Production);
/// # Ok(()) }
/// ```
pub fn override_field_with_env_var<F, N>(field: &mut F, var_name: N) -> AtResult<()>
pub fn override_field_with_env_var<F, N>(field: &mut F, var_name: N) -> AsResult<()>
where
F: Parse,
N: AsRef<str>,
{
match env::var(var_name.as_ref()) {
Err(env::VarError::NotPresent) => Ok((/*NOP*/)),
Err(var_error) => Err(AtError::from(var_error)),
Err(var_error) => Err(Error::from(var_error)),
Ok(value) => Self::override_field(field, value),
}
}
Expand Down
16 changes: 8 additions & 8 deletions actix-settings/src/parse.rs
Original file line number Diff line number Diff line change
@@ -1,25 +1,25 @@
use std::{path::PathBuf, str::FromStr};

use crate::AtError;
use crate::Error;

/// A specialized `FromStr` trait that returns [`AtError`] errors
pub trait Parse: Sized {
/// Parse `Self` from `string`.
fn parse(string: &str) -> Result<Self, AtError>;
fn parse(string: &str) -> Result<Self, Error>;
}

impl Parse for bool {
fn parse(string: &str) -> Result<Self, AtError> {
Self::from_str(string).map_err(AtError::from)
fn parse(string: &str) -> Result<Self, Error> {
Self::from_str(string).map_err(Error::from)
}
}

macro_rules! impl_parse_for_int_type {
($($int_type:ty),+ $(,)?) => {
$(
impl Parse for $int_type {
fn parse(string: &str) -> Result<Self, AtError> {
Self::from_str(string).map_err(AtError::from)
fn parse(string: &str) -> Result<Self, Error> {
Self::from_str(string).map_err(Error::from)
}
}
)+
Expand All @@ -28,13 +28,13 @@ macro_rules! impl_parse_for_int_type {
impl_parse_for_int_type![i8, i16, i32, i64, i128, u8, u16, u32, u64, u128];

impl Parse for String {
fn parse(string: &str) -> Result<Self, AtError> {
fn parse(string: &str) -> Result<Self, Error> {
Ok(string.to_string())
}
}

impl Parse for PathBuf {
fn parse(string: &str) -> Result<Self, AtError> {
fn parse(string: &str) -> Result<Self, Error> {
Ok(PathBuf::from(string))
}
}
10 changes: 5 additions & 5 deletions actix-settings/src/settings/address.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use once_cell::sync::Lazy;
use regex::Regex;
use serde::Deserialize;

use crate::{AtError, Parse};
use crate::{Error, Parse};

static ADDR_REGEX: Lazy<Regex> = Lazy::new(|| {
Regex::new(
Expand Down Expand Up @@ -48,14 +48,14 @@ pub struct Address {
}

impl Parse for Address {
fn parse(string: &str) -> Result<Self, AtError> {
fn parse(string: &str) -> Result<Self, Error> {
let mut items = string
.trim()
.trim_start_matches('[')
.trim_end_matches(']')
.split(',');

let parse_error = || AtError::ParseAddressError(string.to_string());
let parse_error = || Error::ParseAddressError(string.to_string());

if !ADDR_REGEX.is_match(string) {
return Err(parse_error());
Expand All @@ -69,8 +69,8 @@ impl Parse for Address {
}

impl Parse for Vec<Address> {
fn parse(string: &str) -> Result<Self, AtError> {
let parse_error = || AtError::ParseAddressError(string.to_string());
fn parse(string: &str) -> Result<Self, Error> {
let parse_error = || Error::ParseAddressError(string.to_string());

if !ADDR_LIST_REGEX.is_match(string) {
return Err(parse_error());
Expand Down
6 changes: 3 additions & 3 deletions actix-settings/src/settings/backlog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::fmt;

use serde::de;

use crate::{AtError, AtResult, Parse};
use crate::{AsResult, Error, Parse};

/// The maximum number of pending connections.
///
Expand All @@ -22,7 +22,7 @@ pub enum Backlog {
}

impl Parse for Backlog {
fn parse(string: &str) -> AtResult<Self> {
fn parse(string: &str) -> AsResult<Self> {
match string {
"default" => Ok(Backlog::Default),
string => match string.parse::<usize>() {
Expand Down Expand Up @@ -57,7 +57,7 @@ impl<'de> de::Deserialize<'de> for Backlog {
{
match Backlog::parse(value) {
Ok(backlog) => Ok(backlog),
Err(AtError::InvalidValue { expected, got, .. }) => Err(
Err(Error::InvalidValue { expected, got, .. }) => Err(
de::Error::invalid_value(de::Unexpected::Str(&got), &expected),
),
Err(_) => unreachable!(),
Expand Down
6 changes: 3 additions & 3 deletions actix-settings/src/settings/keep_alive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use once_cell::sync::Lazy;
use regex::Regex;
use serde::de;

use crate::{AtError, AtResult, Parse};
use crate::{AsResult, Error, Parse};

/// The server keep-alive preference.
///
Expand All @@ -28,7 +28,7 @@ pub enum KeepAlive {
}

impl Parse for KeepAlive {
fn parse(string: &str) -> AtResult<Self> {
fn parse(string: &str) -> AsResult<Self> {
pub(crate) static FMT: Lazy<Regex> =
Lazy::new(|| Regex::new(r"^\d+ seconds$").expect("Failed to compile regex: FMT"));

Expand Down Expand Up @@ -82,7 +82,7 @@ impl<'de> de::Deserialize<'de> for KeepAlive {
{
match KeepAlive::parse(value) {
Ok(keep_alive) => Ok(keep_alive),
Err(AtError::InvalidValue { expected, got, .. }) => Err(
Err(Error::InvalidValue { expected, got, .. }) => Err(
de::Error::invalid_value(de::Unexpected::Str(&got), &expected),
),
Err(_) => unreachable!(),
Expand Down
Loading

0 comments on commit e61dbae

Please sign in to comment.