diff --git a/actix-settings/CHANGES.md b/actix-settings/CHANGES.md index 25e45859d..2fb8293f3 100644 --- a/actix-settings/CHANGES.md +++ b/actix-settings/CHANGES.md @@ -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 . diff --git a/actix-settings/src/error.rs b/actix-settings/src/error.rs index 009962b18..f3834cf45 100644 --- a/actix-settings/src/error.rs +++ b/actix-settings/src/error.rs @@ -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`. -pub type AtResult = std::result::Result; - /// 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), @@ -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!(), @@ -52,56 +49,56 @@ macro_rules! InvalidValue { }; } -impl From for AtError { +impl From for Error { fn from(err: io::Error) -> Self { Self::IoError(ioe::IoError::from(err)) } } -impl From for AtError { +impl From for Error { fn from(err: ioe::IoError) -> Self { Self::IoError(err) } } -impl From for AtError { +impl From for Error { fn from(err: ParseBoolError) -> Self { Self::ParseBoolError(err) } } -impl From for AtError { +impl From for Error { fn from(err: ParseIntError) -> Self { Self::ParseIntError(err) } } -impl From for AtError { +impl From for Error { fn from(err: TomlError) -> Self { Self::TomlError(err) } } -impl From for AtError { +impl From for Error { fn from(err: VarError) -> Self { Self::EnvVarError(err) } } -impl From for io::Error { - fn from(err: AtError) -> Self { +impl From 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, @@ -115,24 +112,24 @@ impl From 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) } diff --git a/actix-settings/src/lib.rs b/actix-settings/src/lib.rs index 857200c84..ed8b4bc84 100644 --- a/actix-settings/src/lib.rs +++ b/actix-settings/src/lib.rs @@ -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`. +type AsResult = std::result::Result; + /// Wrapper for server and application-specific settings. #[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize)] #[serde(bound = "A: Deserialize<'de>")] @@ -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

(filepath: P) -> AtResult + pub fn parse_toml

(filepath: P) -> AsResult where P: AsRef, { @@ -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::(&contents)?) @@ -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 { + pub fn from_default_template() -> AsResult { 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 { + pub fn from_template(template: &str) -> AsResult { Ok(toml::from_str(template)?) } @@ -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

(filepath: P) -> AtResult<()> + pub fn write_toml_file

(filepath: P) -> AsResult<()> where P: AsRef, { 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)?; @@ -188,7 +192,7 @@ 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); /// @@ -196,7 +200,7 @@ where /// assert_eq!(settings.actix.mode, Mode::Production); /// # Ok(()) } /// ``` - pub fn override_field(field: &mut F, value: V) -> AtResult<()> + pub fn override_field(field: &mut F, value: V) -> AsResult<()> where F: Parse, V: AsRef, @@ -213,7 +217,7 @@ 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); /// @@ -221,14 +225,14 @@ where /// assert_eq!(settings.actix.mode, Mode::Production); /// # Ok(()) } /// ``` - pub fn override_field_with_env_var(field: &mut F, var_name: N) -> AtResult<()> + pub fn override_field_with_env_var(field: &mut F, var_name: N) -> AsResult<()> where F: Parse, N: AsRef, { 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), } } diff --git a/actix-settings/src/parse.rs b/actix-settings/src/parse.rs index 9a6c7f59c..e88a64a3c 100644 --- a/actix-settings/src/parse.rs +++ b/actix-settings/src/parse.rs @@ -1,16 +1,16 @@ 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; + fn parse(string: &str) -> Result; } impl Parse for bool { - fn parse(string: &str) -> Result { - Self::from_str(string).map_err(AtError::from) + fn parse(string: &str) -> Result { + Self::from_str(string).map_err(Error::from) } } @@ -18,8 +18,8 @@ macro_rules! impl_parse_for_int_type { ($($int_type:ty),+ $(,)?) => { $( impl Parse for $int_type { - fn parse(string: &str) -> Result { - Self::from_str(string).map_err(AtError::from) + fn parse(string: &str) -> Result { + Self::from_str(string).map_err(Error::from) } } )+ @@ -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 { + fn parse(string: &str) -> Result { Ok(string.to_string()) } } impl Parse for PathBuf { - fn parse(string: &str) -> Result { + fn parse(string: &str) -> Result { Ok(PathBuf::from(string)) } } diff --git a/actix-settings/src/settings/address.rs b/actix-settings/src/settings/address.rs index c07fff1b6..5f541cac2 100644 --- a/actix-settings/src/settings/address.rs +++ b/actix-settings/src/settings/address.rs @@ -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 = Lazy::new(|| { Regex::new( @@ -48,14 +48,14 @@ pub struct Address { } impl Parse for Address { - fn parse(string: &str) -> Result { + fn parse(string: &str) -> Result { 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()); @@ -69,8 +69,8 @@ impl Parse for Address { } impl Parse for Vec

{ - fn parse(string: &str) -> Result { - let parse_error = || AtError::ParseAddressError(string.to_string()); + fn parse(string: &str) -> Result { + let parse_error = || Error::ParseAddressError(string.to_string()); if !ADDR_LIST_REGEX.is_match(string) { return Err(parse_error()); diff --git a/actix-settings/src/settings/backlog.rs b/actix-settings/src/settings/backlog.rs index 500c20f13..668183d9d 100644 --- a/actix-settings/src/settings/backlog.rs +++ b/actix-settings/src/settings/backlog.rs @@ -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. /// @@ -22,7 +22,7 @@ pub enum Backlog { } impl Parse for Backlog { - fn parse(string: &str) -> AtResult { + fn parse(string: &str) -> AsResult { match string { "default" => Ok(Backlog::Default), string => match string.parse::() { @@ -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!(), diff --git a/actix-settings/src/settings/keep_alive.rs b/actix-settings/src/settings/keep_alive.rs index 96e1ed476..1395984ab 100644 --- a/actix-settings/src/settings/keep_alive.rs +++ b/actix-settings/src/settings/keep_alive.rs @@ -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. /// @@ -28,7 +28,7 @@ pub enum KeepAlive { } impl Parse for KeepAlive { - fn parse(string: &str) -> AtResult { + fn parse(string: &str) -> AsResult { pub(crate) static FMT: Lazy = Lazy::new(|| Regex::new(r"^\d+ seconds$").expect("Failed to compile regex: FMT")); @@ -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!(), diff --git a/actix-settings/src/settings/max_connection_rate.rs b/actix-settings/src/settings/max_connection_rate.rs index d6706783a..702f093b5 100644 --- a/actix-settings/src/settings/max_connection_rate.rs +++ b/actix-settings/src/settings/max_connection_rate.rs @@ -2,7 +2,7 @@ use std::fmt; use serde::de; -use crate::{AtError, AtResult, Parse}; +use crate::{AsResult, Error, Parse}; /// The maximum per-worker concurrent TLS connection limit. /// @@ -19,7 +19,7 @@ pub enum MaxConnectionRate { } impl Parse for MaxConnectionRate { - fn parse(string: &str) -> AtResult { + fn parse(string: &str) -> AsResult { match string { "default" => Ok(MaxConnectionRate::Default), string => match string.parse::() { @@ -54,7 +54,7 @@ impl<'de> de::Deserialize<'de> for MaxConnectionRate { { match MaxConnectionRate::parse(value) { Ok(max_connection_rate) => Ok(max_connection_rate), - Err(AtError::InvalidValue { expected, got, .. }) => Err( + Err(Error::InvalidValue { expected, got, .. }) => Err( de::Error::invalid_value(de::Unexpected::Str(&got), &expected), ), Err(_) => unreachable!(), diff --git a/actix-settings/src/settings/max_connections.rs b/actix-settings/src/settings/max_connections.rs index f0ffdcdf3..1bb3dd04e 100644 --- a/actix-settings/src/settings/max_connections.rs +++ b/actix-settings/src/settings/max_connections.rs @@ -2,7 +2,7 @@ use std::fmt; use serde::de; -use crate::{AtError, AtResult, Parse}; +use crate::{AsResult, Error, Parse}; /// The maximum per-worker number of concurrent connections. /// @@ -19,7 +19,7 @@ pub enum MaxConnections { } impl Parse for MaxConnections { - fn parse(string: &str) -> AtResult { + fn parse(string: &str) -> AsResult { match string { "default" => Ok(MaxConnections::Default), string => match string.parse::() { @@ -54,7 +54,7 @@ impl<'de> de::Deserialize<'de> for MaxConnections { { match MaxConnections::parse(value) { Ok(max_connections) => Ok(max_connections), - Err(AtError::InvalidValue { expected, got, .. }) => Err( + Err(Error::InvalidValue { expected, got, .. }) => Err( de::Error::invalid_value(de::Unexpected::Str(&got), &expected), ), Err(_) => unreachable!(), diff --git a/actix-settings/src/settings/mode.rs b/actix-settings/src/settings/mode.rs index 3833da38a..6eb1ef587 100644 --- a/actix-settings/src/settings/mode.rs +++ b/actix-settings/src/settings/mode.rs @@ -1,6 +1,6 @@ use serde::Deserialize; -use crate::{AtResult, Parse}; +use crate::{AsResult, Parse}; /// Marker of intended deployment environment. #[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize)] @@ -14,7 +14,7 @@ pub enum Mode { } impl Parse for Mode { - fn parse(string: &str) -> AtResult { + fn parse(string: &str) -> AsResult { match string { "development" => Ok(Self::Development), "production" => Ok(Self::Production), diff --git a/actix-settings/src/settings/num_workers.rs b/actix-settings/src/settings/num_workers.rs index ff8d00b8b..39c1bc32b 100644 --- a/actix-settings/src/settings/num_workers.rs +++ b/actix-settings/src/settings/num_workers.rs @@ -2,7 +2,7 @@ use std::fmt; use serde::de; -use crate::{AtError, AtResult, Parse}; +use crate::{AsResult, Error, Parse}; /// The number of workers that the server should start. /// @@ -18,7 +18,7 @@ pub enum NumWorkers { } impl Parse for NumWorkers { - fn parse(string: &str) -> AtResult { + fn parse(string: &str) -> AsResult { match string { "default" => Ok(NumWorkers::Default), string => match string.parse::() { @@ -53,7 +53,7 @@ impl<'de> de::Deserialize<'de> for NumWorkers { { match NumWorkers::parse(value) { Ok(num_workers) => Ok(num_workers), - Err(AtError::InvalidValue { expected, got, .. }) => Err( + Err(Error::InvalidValue { expected, got, .. }) => Err( de::Error::invalid_value(de::Unexpected::Str(&got), &expected), ), Err(_) => unreachable!(), diff --git a/actix-settings/src/settings/timeout.rs b/actix-settings/src/settings/timeout.rs index 1bed71396..dff3899d5 100644 --- a/actix-settings/src/settings/timeout.rs +++ b/actix-settings/src/settings/timeout.rs @@ -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}; /// A timeout duration in milliseconds or seconds. #[derive(Debug, Clone, PartialEq, Eq, Hash)] @@ -20,7 +20,7 @@ pub enum Timeout { } impl Parse for Timeout { - fn parse(string: &str) -> AtResult { + fn parse(string: &str) -> AsResult { pub static FMT: Lazy = Lazy::new(|| { Regex::new(r"^\d+ (milliseconds|seconds)$").expect("Failed to compile regex: FMT") }); @@ -85,7 +85,7 @@ impl<'de> de::Deserialize<'de> for Timeout { { match Timeout::parse(value) { Ok(num_workers) => Ok(num_workers), - Err(AtError::InvalidValue { expected, got, .. }) => Err( + Err(Error::InvalidValue { expected, got, .. }) => Err( de::Error::invalid_value(de::Unexpected::Str(&got), &expected), ), Err(_) => unreachable!(),