1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2024-11-10 19:01:05 +00:00

chore: disallow e bindings

This commit is contained in:
Rob Ede 2024-08-10 05:15:49 +01:00
parent 70e3758ecc
commit 538c1bea34
No known key found for this signature in database
GPG key ID: 97C636207D3EF933
22 changed files with 96 additions and 87 deletions

7
.clippy.toml Normal file
View file

@ -0,0 +1,7 @@
disallowed-names = [
"e", # no single letter error bindings
]
disallowed-methods = [
"std::cell::RefCell::default()",
"std::rc::Rc::default()",
]

View file

@ -79,7 +79,7 @@ impl FilesService {
let (req, _) = req.into_parts(); let (req, _) = req.into_parts();
(self.renderer)(&dir, &req).unwrap_or_else(|e| ServiceResponse::from_err(e, req)) (self.renderer)(&dir, &req).unwrap_or_else(|err| ServiceResponse::from_err(err, req))
} }
} }

View file

@ -106,7 +106,7 @@ pub async fn test_server_with_addr<F: ServerServiceFactory<TcpStream>>(
builder.set_verify(SslVerifyMode::NONE); builder.set_verify(SslVerifyMode::NONE);
let _ = builder let _ = builder
.set_alpn_protos(b"\x02h2\x08http/1.1") .set_alpn_protos(b"\x02h2\x08http/1.1")
.map_err(|e| log::error!("Can not set alpn protocol: {:?}", e)); .map_err(|err| log::error!("Can not set ALPN protocol: {err}"));
Connector::new() Connector::new()
.conn_lifetime(Duration::from_secs(0)) .conn_lifetime(Duration::from_secs(0))

View file

@ -313,7 +313,7 @@ impl MessageType for RequestHeadType {
_ => return Err(io::Error::new(io::ErrorKind::Other, "unsupported version")), _ => return Err(io::Error::new(io::ErrorKind::Other, "unsupported version")),
} }
) )
.map_err(|e| io::Error::new(io::ErrorKind::Other, e)) .map_err(|err| io::Error::new(io::ErrorKind::Other, err))
} }
} }
@ -433,7 +433,7 @@ impl TransferEncoding {
buf.extend_from_slice(b"0\r\n\r\n"); buf.extend_from_slice(b"0\r\n\r\n");
} else { } else {
writeln!(helpers::MutWriter(buf), "{:X}\r", msg.len()) writeln!(helpers::MutWriter(buf), "{:X}\r", msg.len())
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))?; .map_err(|err| io::Error::new(io::ErrorKind::Other, err))?;
buf.reserve(msg.len() + 2); buf.reserve(msg.len() + 2);
buf.extend_from_slice(msg); buf.extend_from_slice(msg);

View file

@ -480,15 +480,15 @@ where
let cfg = self.cfg.clone(); let cfg = self.cfg.clone();
Box::pin(async move { Box::pin(async move {
let expect = expect let expect = expect.await.map_err(|err| {
.await tracing::error!("Initialization of HTTP expect service error: {err:?}");
.map_err(|e| error!("Init http expect service error: {:?}", e))?; })?;
let upgrade = match upgrade { let upgrade = match upgrade {
Some(upgrade) => { Some(upgrade) => {
let upgrade = upgrade let upgrade = upgrade.await.map_err(|err| {
.await tracing::error!("Initialization of HTTP upgrade service error: {err:?}");
.map_err(|e| error!("Init http upgrade service error: {:?}", e))?; })?;
Some(upgrade) Some(upgrade)
} }
None => None, None => None,
@ -496,7 +496,7 @@ where
let service = service let service = service
.await .await
.map_err(|e| error!("Init http service error: {:?}", e))?; .map_err(|err| error!("Initialization of HTTP service error: {err:?}"))?;
Ok(H1ServiceHandler::new( Ok(H1ServiceHandler::new(
cfg, cfg,

View file

@ -775,23 +775,23 @@ where
let cfg = self.cfg.clone(); let cfg = self.cfg.clone();
Box::pin(async move { Box::pin(async move {
let expect = expect let expect = expect.await.map_err(|err| {
.await tracing::error!("Initialization of HTTP expect service error: {err:?}");
.map_err(|e| error!("Init http expect service error: {:?}", e))?; })?;
let upgrade = match upgrade { let upgrade = match upgrade {
Some(upgrade) => { Some(upgrade) => {
let upgrade = upgrade let upgrade = upgrade.await.map_err(|err| {
.await tracing::error!("Initialization of HTTP upgrade service error: {err:?}");
.map_err(|e| error!("Init http upgrade service error: {:?}", e))?; })?;
Some(upgrade) Some(upgrade)
} }
None => None, None => None,
}; };
let service = service let service = service.await.map_err(|err| {
.await tracing::error!("Initialization of HTTP service error: {err:?}");
.map_err(|e| error!("Init http service error: {:?}", e))?; })?;
Ok(HttpServiceHandler::new( Ok(HttpServiceHandler::new(
cfg, cfg,

View file

@ -114,14 +114,14 @@ mod inner {
{ {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self { match *self {
DispatcherError::Service(ref e) => { DispatcherError::Service(ref err) => {
write!(fmt, "DispatcherError::Service({:?})", e) write!(fmt, "DispatcherError::Service({err:?})")
} }
DispatcherError::Encoder(ref e) => { DispatcherError::Encoder(ref err) => {
write!(fmt, "DispatcherError::Encoder({:?})", e) write!(fmt, "DispatcherError::Encoder({err:?})")
} }
DispatcherError::Decoder(ref e) => { DispatcherError::Decoder(ref err) => {
write!(fmt, "DispatcherError::Decoder({:?})", e) write!(fmt, "DispatcherError::Decoder({err:?})")
} }
} }
} }
@ -136,9 +136,9 @@ mod inner {
{ {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self { match *self {
DispatcherError::Service(ref e) => write!(fmt, "{}", e), DispatcherError::Service(ref err) => write!(fmt, "{err}"),
DispatcherError::Encoder(ref e) => write!(fmt, "{:?}", e), DispatcherError::Encoder(ref err) => write!(fmt, "{err:?}"),
DispatcherError::Decoder(ref e) => write!(fmt, "{:?}", e), DispatcherError::Decoder(ref err) => write!(fmt, "{err:?}"),
} }
} }
} }

View file

@ -5,6 +5,7 @@
#![doc(html_logo_url = "https://actix.rs/img/logo.png")] #![doc(html_logo_url = "https://actix.rs/img/logo.png")]
#![doc(html_favicon_url = "https://actix.rs/favicon.ico")] #![doc(html_favicon_url = "https://actix.rs/favicon.ico")]
#![cfg_attr(docsrs, feature(doc_auto_cfg))] #![cfg_attr(docsrs, feature(doc_auto_cfg))]
#![allow(clippy::disallowed_names)] // false positives in some macro expansions
use std::collections::HashSet; use std::collections::HashSet;
@ -35,6 +36,7 @@ struct MultipartFormAttrs {
duplicate_field: DuplicateField, duplicate_field: DuplicateField,
} }
#[allow(clippy::disallowed_names)] // false positive in macro expansion
#[derive(FromField, Default)] #[derive(FromField, Default)]
#[darling(attributes(multipart), default)] #[darling(attributes(multipart), default)]
struct FieldAttrs { struct FieldAttrs {

View file

@ -143,9 +143,9 @@ impl<T: ResourcePath> Path<T> {
for (seg_name, val) in self.segments.iter() { for (seg_name, val) in self.segments.iter() {
if name == seg_name { if name == seg_name {
return match val { return match val {
PathItem::Static(ref s) => Some(s), PathItem::Static(ref seg) => Some(seg),
PathItem::Segment(s, e) => { PathItem::Segment(start, end) => {
Some(&self.path.path()[(*s as usize)..(*e as usize)]) Some(&self.path.path()[(*start as usize)..(*end as usize)])
} }
}; };
} }
@ -193,8 +193,10 @@ impl<'a, T: ResourcePath> Iterator for PathIter<'a, T> {
if self.idx < self.params.segment_count() { if self.idx < self.params.segment_count() {
let idx = self.idx; let idx = self.idx;
let res = match self.params.segments[idx].1 { let res = match self.params.segments[idx].1 {
PathItem::Static(ref s) => s, PathItem::Static(ref seg) => seg,
PathItem::Segment(s, e) => &self.params.path.path()[(s as usize)..(e as usize)], PathItem::Segment(start, end) => {
&self.params.path.path()[(start as usize)..(end as usize)]
}
}; };
self.idx += 1; self.idx += 1;
return Some((&self.params.segments[idx].0, res)); return Some((&self.params.segments[idx].0, res));
@ -217,8 +219,8 @@ impl<T: ResourcePath> Index<usize> for Path<T> {
fn index(&self, idx: usize) -> &str { fn index(&self, idx: usize) -> &str {
match self.segments[idx].1 { match self.segments[idx].1 {
PathItem::Static(ref s) => s, PathItem::Static(ref seg) => seg,
PathItem::Segment(s, e) => &self.path.path()[(s as usize)..(e as usize)], PathItem::Segment(start, end) => &self.path.path()[(start as usize)..(end as usize)],
} }
} }
} }

View file

@ -796,11 +796,8 @@ where
Some(frm) => { Some(frm) => {
let msg = match frm { let msg = match frm {
Frame::Text(data) => { Frame::Text(data) => {
Message::Text(ByteString::try_from(data).map_err(|e| { Message::Text(ByteString::try_from(data).map_err(|err| {
ProtocolError::Io(io::Error::new( ProtocolError::Io(io::Error::new(io::ErrorKind::Other, err))
io::ErrorKind::Other,
format!("{}", e),
))
})?) })?)
} }
Frame::Binary(data) => Message::Binary(data), Frame::Binary(data) => Message::Binary(data),

View file

@ -269,9 +269,9 @@ where
+ 'static, + 'static,
U::InitError: fmt::Debug, U::InitError: fmt::Debug,
{ {
let svc = svc let svc = svc.into_factory().map_init_err(|err| {
.into_factory() log::error!("Can not construct default service: {err:?}");
.map_init_err(|e| log::error!("Can not construct default service: {:?}", e)); });
self.default = Some(Rc::new(boxed::factory(svc))); self.default = Some(Rc::new(boxed::factory(svc)));

View file

@ -358,10 +358,9 @@ where
U::InitError: fmt::Debug, U::InitError: fmt::Debug,
{ {
// create and configure default resource // create and configure default resource
self.default = boxed::factory( self.default = boxed::factory(f.into_factory().map_init_err(|err| {
f.into_factory() log::error!("Can not construct default service: {err:?}");
.map_init_err(|e| log::error!("Can not construct default service: {:?}", e)), }));
);
self self
} }

View file

@ -278,7 +278,9 @@ where
{ {
// create and configure default resource // create and configure default resource
self.default = Some(Rc::new(boxed::factory(f.into_factory().map_init_err( self.default = Some(Rc::new(boxed::factory(f.into_factory().map_init_err(
|e| log::error!("Can not construct default service: {:?}", e), |err| {
log::error!("Can not construct default service: {err:?}");
},
)))); ))));
self self

View file

@ -398,7 +398,7 @@ impl<T: DeserializeOwned> JsonBody<T> {
_res: PhantomData, _res: PhantomData,
} }
} }
JsonBody::Error(e) => JsonBody::Error(e), JsonBody::Error(err) => JsonBody::Error(err),
} }
} }
} }
@ -434,7 +434,7 @@ impl<T: DeserializeOwned> Future for JsonBody<T> {
} }
} }
}, },
JsonBody::Error(e) => Poll::Ready(Err(e.take().unwrap())), JsonBody::Error(err) => Poll::Ready(Err(err.take().unwrap())),
} }
} }
} }

View file

@ -89,8 +89,8 @@ where
); );
if let Some(error_handler) = error_handler { if let Some(error_handler) = error_handler {
let e = PathError::Deserialize(err); let err = PathError::Deserialize(err);
(error_handler)(e, req) (error_handler)(err, req)
} else { } else {
ErrorNotFound(err) ErrorNotFound(err)
} }

View file

@ -2,7 +2,7 @@
use std::{fmt, ops, sync::Arc}; use std::{fmt, ops, sync::Arc};
use actix_utils::future::{err, ok, Ready}; use actix_utils::future::{ok, ready, Ready};
use serde::de::DeserializeOwned; use serde::de::DeserializeOwned;
use crate::{dev::Payload, error::QueryPayloadError, Error, FromRequest, HttpRequest}; use crate::{dev::Payload, error::QueryPayloadError, Error, FromRequest, HttpRequest};
@ -118,8 +118,8 @@ impl<T: DeserializeOwned> FromRequest for Query<T> {
serde_urlencoded::from_str::<T>(req.query_string()) serde_urlencoded::from_str::<T>(req.query_string())
.map(|val| ok(Query(val))) .map(|val| ok(Query(val)))
.unwrap_or_else(move |e| { .unwrap_or_else(move |err| {
let e = QueryPayloadError::Deserialize(e); let err = QueryPayloadError::Deserialize(err);
log::debug!( log::debug!(
"Failed during Query extractor deserialization. \ "Failed during Query extractor deserialization. \
@ -127,13 +127,13 @@ impl<T: DeserializeOwned> FromRequest for Query<T> {
req.path() req.path()
); );
let e = if let Some(error_handler) = error_handler { let err = if let Some(error_handler) = error_handler {
(error_handler)(e, req) (error_handler)(err, req)
} else { } else {
e.into() err.into()
}; };
err(e) ready(Err(err))
}) })
} }
} }

View file

@ -54,11 +54,11 @@ impl std::error::Error for ConnectError {}
impl From<actix_tls::connect::ConnectError> for ConnectError { impl From<actix_tls::connect::ConnectError> for ConnectError {
fn from(err: actix_tls::connect::ConnectError) -> ConnectError { fn from(err: actix_tls::connect::ConnectError) -> ConnectError {
match err { match err {
actix_tls::connect::ConnectError::Resolver(e) => ConnectError::Resolver(e), actix_tls::connect::ConnectError::Resolver(err) => ConnectError::Resolver(err),
actix_tls::connect::ConnectError::NoRecords => ConnectError::NoRecords, actix_tls::connect::ConnectError::NoRecords => ConnectError::NoRecords,
actix_tls::connect::ConnectError::InvalidInput => panic!(), actix_tls::connect::ConnectError::InvalidInput => panic!(),
actix_tls::connect::ConnectError::Unresolved => ConnectError::Unresolved, actix_tls::connect::ConnectError::Unresolved => ConnectError::Unresolved,
actix_tls::connect::ConnectError::Io(e) => ConnectError::Io(e), actix_tls::connect::ConnectError::Io(err) => ConnectError::Io(err),
} }
} }
} }

View file

@ -31,7 +31,7 @@ use super::{
Connect, Connect,
}; };
#[derive(Hash, Eq, PartialEq, Clone, Debug)] #[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Key { pub struct Key {
authority: Authority, authority: Authority,
} }
@ -42,8 +42,8 @@ impl From<Authority> for Key {
} }
} }
/// Connections pool to reuse I/O per [`Authority`].
#[doc(hidden)] #[doc(hidden)]
/// Connections pool for reuse Io type for certain [`http::uri::Authority`] as key.
pub struct ConnectionPool<S, Io> pub struct ConnectionPool<S, Io>
where where
Io: AsyncWrite + Unpin + 'static, Io: AsyncWrite + Unpin + 'static,
@ -52,7 +52,7 @@ where
inner: ConnectionPoolInner<Io>, inner: ConnectionPoolInner<Io>,
} }
/// wrapper type for check the ref count of Rc. /// Wrapper type for check the ref count of Rc.
pub struct ConnectionPoolInner<Io>(Rc<ConnectionPoolInnerPriv<Io>>) pub struct ConnectionPoolInner<Io>(Rc<ConnectionPoolInnerPriv<Io>>)
where where
Io: AsyncWrite + Unpin + 'static; Io: AsyncWrite + Unpin + 'static;
@ -63,7 +63,7 @@ where
{ {
fn new(config: ConnectorConfig) -> Self { fn new(config: ConnectorConfig) -> Self {
let permits = Arc::new(Semaphore::new(config.limit)); let permits = Arc::new(Semaphore::new(config.limit));
let available = RefCell::new(HashMap::default()); let available = RefCell::new(HashMap::new());
Self(Rc::new(ConnectionPoolInnerPriv { Self(Rc::new(ConnectionPoolInnerPriv {
config, config,
@ -72,7 +72,7 @@ where
})) }))
} }
/// spawn a async for graceful shutdown h1 Io type with a timeout. /// Spawns a graceful shutdown task for the underlying I/O with a timeout.
fn close(&self, conn: ConnectionInnerType<Io>) { fn close(&self, conn: ConnectionInnerType<Io>) {
if let Some(timeout) = self.config.disconnect_timeout { if let Some(timeout) = self.config.disconnect_timeout {
if let ConnectionInnerType::H1(io) = conn { if let ConnectionInnerType::H1(io) = conn {

View file

@ -147,8 +147,8 @@ impl FrozenSendBuilder {
/// Complete request construction and send a body. /// Complete request construction and send a body.
pub fn send_body(self, body: impl MessageBody + 'static) -> SendClientRequest { pub fn send_body(self, body: impl MessageBody + 'static) -> SendClientRequest {
if let Some(e) = self.err { if let Some(err) = self.err {
return e.into(); return err.into();
} }
RequestSender::Rc(self.req.head, Some(self.extra_headers)).send_body( RequestSender::Rc(self.req.head, Some(self.extra_headers)).send_body(
@ -177,8 +177,8 @@ impl FrozenSendBuilder {
/// Complete request construction and send an urlencoded body. /// Complete request construction and send an urlencoded body.
pub fn send_form(self, value: impl Serialize) -> SendClientRequest { pub fn send_form(self, value: impl Serialize) -> SendClientRequest {
if let Some(e) = self.err { if let Some(err) = self.err {
return e.into(); return err.into();
} }
RequestSender::Rc(self.req.head, Some(self.extra_headers)).send_form( RequestSender::Rc(self.req.head, Some(self.extra_headers)).send_form(
@ -196,8 +196,8 @@ impl FrozenSendBuilder {
S: Stream<Item = Result<Bytes, E>> + 'static, S: Stream<Item = Result<Bytes, E>> + 'static,
E: Into<BoxError> + 'static, E: Into<BoxError> + 'static,
{ {
if let Some(e) = self.err { if let Some(err) = self.err {
return e.into(); return err.into();
} }
RequestSender::Rc(self.req.head, Some(self.extra_headers)).send_stream( RequestSender::Rc(self.req.head, Some(self.extra_headers)).send_stream(
@ -211,8 +211,8 @@ impl FrozenSendBuilder {
/// Complete request construction and send an empty body. /// Complete request construction and send an empty body.
pub fn send(self) -> SendClientRequest { pub fn send(self) -> SendClientRequest {
if let Some(e) = self.err { if let Some(err) = self.err {
return e.into(); return err.into();
} }
RequestSender::Rc(self.req.head, Some(self.extra_headers)).send( RequestSender::Rc(self.req.head, Some(self.extra_headers)).send(

View file

@ -415,8 +415,8 @@ impl ClientRequest {
// allow unused mut when cookies feature is disabled // allow unused mut when cookies feature is disabled
fn prep_for_sending(#[allow(unused_mut)] mut self) -> Result<Self, PrepForSendingError> { fn prep_for_sending(#[allow(unused_mut)] mut self) -> Result<Self, PrepForSendingError> {
if let Some(e) = self.err { if let Some(err) = self.err {
return Err(e.into()); return Err(err.into());
} }
// validate uri // validate uri

View file

@ -54,8 +54,8 @@ impl From<PrepForSendingError> for FreezeRequestError {
impl From<PrepForSendingError> for SendRequestError { impl From<PrepForSendingError> for SendRequestError {
fn from(err: PrepForSendingError) -> SendRequestError { fn from(err: PrepForSendingError) -> SendRequestError {
match err { match err {
PrepForSendingError::Url(e) => SendRequestError::Url(e), PrepForSendingError::Url(err) => SendRequestError::Url(err),
PrepForSendingError::Http(e) => SendRequestError::Http(e), PrepForSendingError::Http(err) => SendRequestError::Http(err),
PrepForSendingError::Json(err) => { PrepForSendingError::Json(err) => {
SendRequestError::Custom(Box::new(err), Box::new("json serialization error")) SendRequestError::Custom(Box::new(err), Box::new("json serialization error"))
} }
@ -156,20 +156,20 @@ impl Future for SendClientRequest {
} }
impl From<SendRequestError> for SendClientRequest { impl From<SendRequestError> for SendClientRequest {
fn from(e: SendRequestError) -> Self { fn from(err: SendRequestError) -> Self {
SendClientRequest::Err(Some(e)) SendClientRequest::Err(Some(err))
} }
} }
impl From<HttpError> for SendClientRequest { impl From<HttpError> for SendClientRequest {
fn from(e: HttpError) -> Self { fn from(err: HttpError) -> Self {
SendClientRequest::Err(Some(e.into())) SendClientRequest::Err(Some(err.into()))
} }
} }
impl From<PrepForSendingError> for SendClientRequest { impl From<PrepForSendingError> for SendClientRequest {
fn from(e: PrepForSendingError) -> Self { fn from(err: PrepForSendingError) -> Self {
SendClientRequest::Err(Some(e.into())) SendClientRequest::Err(Some(err.into()))
} }
} }

View file

@ -253,8 +253,8 @@ impl WebsocketsRequest {
pub async fn connect( pub async fn connect(
mut self, mut self,
) -> Result<(ClientResponse, Framed<BoxedSocket, Codec>), WsClientError> { ) -> Result<(ClientResponse, Framed<BoxedSocket, Codec>), WsClientError> {
if let Some(e) = self.err.take() { if let Some(err) = self.err.take() {
return Err(e.into()); return Err(err.into());
} }
// validate URI // validate URI