text
stringlengths
0
4.1M
//! HTTP requests. use std::{ cell::{Ref, RefCell, RefMut}, fmt, mem, net, rc::Rc, str, }; use http::{header, Method, Uri, Version}; use crate::{ header::HeaderMap, BoxedPayloadStream, Extensions, HttpMessage, Message, Payload, RequestHead, }; /// An HTTP request. pub struct Request<P = BoxedPayloadStream> { pub(crate) payload: Payload<P>, pub(crate) head: Message<RequestHead>, pub(crate) conn_data: Option<Rc<Extensions>>, pub(crate) extensions: RefCell<Extensions>, } impl<P> HttpMessage for Request<P> { type Stream = P; #[inline] fn headers(&self) -> &HeaderMap { &self.head().headers } fn take_payload(&mut self) -> Payload<P> { mem::replace(&mut self.payload, Payload::None) } #[inline] fn extensions(&self) -> Ref<'_, Extensions> { self.extensions.borrow() } #[inline] fn extensions_mut(&self) -> RefMut<'_, Extensions> { self.extensions.borrow_mut() } } impl From<Message<RequestHead>> for Request<BoxedPayloadStream> { fn from(head: Message<RequestHead>) -> Self { Request { head, payload: Payload::None, extensions: RefCell::new(Extensions::default()), conn_data: None, } } } impl Request<BoxedPayloadStream> { /// Create new Request instance #[allow(clippy::new_without_default)] pub fn new() -> Request<BoxedPayloadStream> { Request { head: Message::new(), payload: Payload::None, extensions: RefCell::new(Extensions::default()), conn_data: None, } } } impl<P> Request<P> { /// Create new Request instance pub fn with_payload(payload: Payload<P>) -> Request<P> { Request { payload, head: Message::new(), extensions: RefCell::new(Extensions::default()), conn_data: None, } } /// Create new Request instance pub fn replace_payload<P1>(self, payload: Payload<P1>) -> (Request<P1>, Payload<P>) { let pl = self.payload; ( Request { payload, head: self.head, extensions: self.extensions, conn_data: self.conn_data, }, pl, ) } /// Get request's payload pub fn payload(&mut self) -> &mut Payload<P> { &mut self.payload } /// Get request's payload pub fn take_payload(&mut self) -> Payload<P> { mem::replace(&mut self.payload, Payload::None) } /// Split request into request head and payload pub fn into_parts(self) -> (Message<RequestHead>, Payload<P>) { (self.head, self.payload) } #[inline] /// Http message part of the request pub fn head(&self) -> &RequestHead { &self.head } #[inline] #[doc(hidden)] /// Mutable reference to a HTTP message part of the request pub fn head_mut(&mut self) -> &mut RequestHead { &mut self.head } /// Mutable reference to the message's headers. pub fn headers_mut(&mut self) -> &mut HeaderMap { &mut self.head.headers } /// Request's uri. #[inline] pub fn uri(&self) -> &Uri { &self.head().uri } /// Mutable reference to the request's uri. #[inline] pub fn uri_mut(&mut self) -> &mut Uri { &mut self.head.uri } /// Read the Request method. #[inline] pub fn method(&self) -> &Method { &self.head().method } /// Read the Request Version. #[inline] pub fn version(&self) -> Version { self.head().version } /// The target path of this Request. #[inline] pub fn path(&self) -> &str { self.head().uri.path() } /// Check if request requires connection upgrade #[inline] pub fn upgrade(&self) -> bool { if let Some(conn) = self.head().headers.get(header::CONNECTION) { if let Ok(s) = conn.to_str() { return s.to_lowercase().contains("upgrade"); } } self.head().method == Method::CONNECT } /// Peer socket address. /// /// Peer address is the directly connected peer's socket address. If a proxy is used in front of /// the Actix Web server, then it would be address of this proxy. /// /// Will only return None when called in unit tests unless set manually. #[inline] pub fn peer_addr(&self) -> Option<net::SocketAddr> { self.head().peer_addr } /// Returns a reference a piece of connection data set in an [on-connect] callback. /// /// ```ignore /// let opt_t = req.conn_data::<PeerCertificate>(); /// ``` /// /// [on-connect]: crate::HttpServiceBuilder::on_connect_ext pub fn conn_data<T: 'static>(&self) -> Option<&T> { self.conn_data .as_deref() .and_then(|container| container.get::<T>()) } /// Returns the connection-level data/extensions container if an [on-connect] callback was /// registered, leaving an empty one in its place. /// /// [on-connect]: crate::HttpServiceBuilder::on_connect_ext pub fn take_conn_data(&mut self) -> Option<Rc<Extensions>> { self.conn_data.take() } /// Returns the request-local data/extensions container, leaving an empty one in its place. pub fn take_req_data(&mut self) -> Extensions { mem::take(self.extensions.get_mut()) } } impl<P> fmt::Debug for Request<P> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { writeln!( f, "\nRequest {:?} {}:{}", self.version(), self.method(), self.path() )?; if let Some(q) = self.uri().query().as_ref() { writeln!(f, " query: ?{:?}", q)?; } writeln!(f, " headers:")?; for (key, val) in self.headers().iter() { writeln!(f, " {:?}: {:?}", key, val)?; } Ok(()) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_basics() { let msg = Message::new(); let mut req = Request::from(msg); req.headers_mut().insert( header::CONTENT_TYPE, header::HeaderValue::from_static("text/plain"), ); assert!(req.headers().contains_key(header::CONTENT_TYPE)); *req.uri_mut() = Uri::try_from("/index.html?q=1").unwrap(); assert_eq!(req.uri().path(), "/index.html"); assert_eq!(req.uri().query(), Some("q=1")); let s = format!("{:?}", req); assert!(s.contains("Request HTTP/1.1 GET:/index.html")); } }
//! HTTP response builder. use std::{cell::RefCell, fmt, str}; use crate::{ body::{EitherBody, MessageBody}, error::{Error, HttpError}, header::{self, TryIntoHeaderPair, TryIntoHeaderValue}, responses::{BoxedResponseHead, ResponseHead}, ConnectionType, Extensions, Response, StatusCode, }; /// An HTTP response builder. /// /// Used to construct an instance of `Response` using a builder pattern. Response builders are often /// created using [`Response::build`]. /// /// # Examples /// ``` /// use actix_http::{Response, ResponseBuilder, StatusCode, body, header}; /// /// # actix_rt::System::new().block_on(async { /// let mut res: Response<_> = Response::build(StatusCode::OK) /// .content_type(mime::APPLICATION_JSON) /// .insert_header((header::SERVER, "my-app/1.0")) /// .append_header((header::SET_COOKIE, "a=1")) /// .append_header((header::SET_COOKIE, "b=2")) /// .body("1234"); /// /// assert_eq!(res.status(), StatusCode::OK); /// /// assert!(res.headers().contains_key("server")); /// assert_eq!(res.headers().get_all("set-cookie").count(), 2); /// /// assert_eq!(body::to_bytes(res.into_body()).await.unwrap(), &b"1234"[..]); /// # }) /// ``` pub struct ResponseBuilder { head: Option<BoxedResponseHead>, err: Option<HttpError>, } impl ResponseBuilder { /// Create response builder /// /// # Examples /// ``` /// use actix_http::{Response, ResponseBuilder, StatusCode}; /// let res: Response<_> = ResponseBuilder::default().finish(); /// assert_eq!(res.status(), StatusCode::OK); /// ``` #[inline] pub fn new(status: StatusCode) -> Self { ResponseBuilder { head: Some(BoxedResponseHead::new(status)), err: None, } } /// Set HTTP status code of this response. /// /// # Examples /// ``` /// use actix_http::{ResponseBuilder, StatusCode}; /// let res = ResponseBuilder::default().status(StatusCode::NOT_FOUND).finish(); /// assert_eq!(res.status(), StatusCode::NOT_FOUND); /// ``` #[inline] pub fn status(&mut self, status: StatusCode) -> &mut Self { if let Some(parts) = self.inner() { parts.status = status; } self } /// Insert a header, replacing any that were set with an equivalent field name. /// /// # Examples /// ``` /// use actix_http::{ResponseBuilder, header}; /// /// let res = ResponseBuilder::default() /// .insert_header((header::CONTENT_TYPE, mime::APPLICATION_JSON)) /// .insert_header(("X-TEST", "value")) /// .finish(); /// /// assert!(res.headers().contains_key("content-type")); /// assert!(res.headers().contains_key("x-test")); /// ``` pub fn insert_header(&mut self, header: impl TryIntoHeaderPair) -> &mut Self { if let Some(parts) = self.inner() { match header.try_into_pair() { Ok((key, value)) => { parts.headers.insert(key, value); } Err(err) => self.err = Some(err.into()), }; } self } /// Append a header, keeping any that were set with an equivalent field name. /// /// # Examples /// ``` /// use actix_http::{ResponseBuilder, header}; /// /// let res = ResponseBuilder::default() /// .append_header((header::CONTENT_TYPE, mime::APPLICATION_JSON)) /// .append_header(("X-TEST", "value1")) /// .append_header(("X-TEST", "value2")) /// .finish(); /// /// assert_eq!(res.headers().get_all("content-type").count(), 1); /// assert_eq!(res.headers().get_all("x-test").count(), 2); /// ``` pub fn append_header(&mut self, header: impl TryIntoHeaderPair) -> &mut Self { if let Some(parts) = self.inner() { match header.try_into_pair() { Ok((key, value)) => parts.headers.append(key, value), Err(err) => self.err = Some(err.into()), }; } self } /// Set the custom reason for the response. #[inline] pub fn reason(&mut self, reason: &'static str) -> &mut Self { if let Some(parts) = self.inner() { parts.reason = Some(reason); } self } /// Set connection type to KeepAlive #[inline] pub fn keep_alive(&mut self) -> &mut Self { if let Some(parts) = self.inner() { parts.set_connection_type(ConnectionType::KeepAlive); } self } /// Set connection type to `Upgrade`. #[inline] pub fn upgrade<V>(&mut self, value: V) -> &mut Self where V: TryIntoHeaderValue, { if let Some(parts) = self.inner() { parts.set_connection_type(ConnectionType::Upgrade); } if let Ok(value) = value.try_into_value() { self.insert_header((header::UPGRADE, value)); } self } /// Force-close connection, even if it is marked as keep-alive. #[inline] pub fn force_close(&mut self) -> &mut Self { if let Some(parts) = self.inner() { parts.set_connection_type(ConnectionType::Close); } self } /// Disable chunked transfer encoding for HTTP/1.1 streaming responses. #[inline] pub fn no_chunking(&mut self, len: u64) -> &mut Self { let mut buf = itoa::Buffer::new(); self.insert_header((header::CONTENT_LENGTH, buf.format(len))); if let Some(parts) = self.inner() { parts.no_chunking(true); } self } /// Set response content type. #[inline] pub fn content_type<V>(&mut self, value: V) -> &mut Self where V: TryIntoHeaderValue, { if let Some(parts) = self.inner() { match value.try_into_value() { Ok(value) => { parts.headers.insert(header::CONTENT_TYPE, value); } Err(err) => self.err = Some(err.into()), }; } self } /// Generate response with a wrapped body. /// /// This `ResponseBuilder` will be left in a useless state. pub fn body<B>(&mut self, body: B) -> Response<EitherBody<B>> where B: MessageBody + 'static, { match self.message_body(body) { Ok(res) => res.map_body(|_, body| EitherBody::left(body)), Err(err) => Response::from(err).map_body(|_, body| EitherBody::right(body)), } } /// Generate response with a body. /// /// This `ResponseBuilder` will be left in a useless state. pub fn message_body<B>(&mut self, body: B) -> Result<Response<B>, Error> { if let Some(err) = self.err.take() { return Err(Error::new_http().with_cause(err)); } let head = self.head.take().expect("cannot reuse response builder"); Ok(Response { head, body, extensions: RefCell::new(Extensions::new()), }) } /// Generate response with an empty body. /// /// This `ResponseBuilder` will be left in a useless state. #[inline] pub fn finish(&mut self) -> Response<EitherBody<()>> { self.body(()) } /// Create an owned `ResponseBuilder`, leaving the original in a useless state. pub fn take(&mut self) -> ResponseBuilder { ResponseBuilder { head: self.head.take(), err: self.err.take(), } } /// Get access to the inner response head if there has been no error. fn inner(&mut self) -> Option<&mut ResponseHead> { if self.err.is_some() { return None; } self.head.as_deref_mut() } } impl Default for ResponseBuilder { fn default() -> Self { Self::new(StatusCode::OK) } } /// Convert `Response` to a `ResponseBuilder`. Body get dropped. impl<B> From<Response<B>> for ResponseBuilder { fn from(res: Response<B>) -> ResponseBuilder { ResponseBuilder { head: Some(res.head), err: None, } } } /// Convert `ResponseHead` to a `ResponseBuilder` impl<'a> From<&'a ResponseHead> for ResponseBuilder { fn from(head: &'a ResponseHead) -> ResponseBuilder { let mut msg = BoxedResponseHead::new(head.status); msg.version = head.version; msg.reason = head.reason; for (k, v) in head.headers.iter() { msg.headers.append(k.clone(), v.clone()); } msg.no_chunking(!head.chunked()); ResponseBuilder { head: Some(msg), err: None, } } } impl fmt::Debug for ResponseBuilder { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let head = self.head.as_ref().unwrap(); let res = writeln!( f, "\nResponseBuilder {:?} {}{}", head.version, head.status, head.reason.unwrap_or(""), ); let _ = writeln!(f, " headers:"); for (key, val) in head.headers.iter() { let _ = writeln!(f, " {:?}: {:?}", key, val); } res } } #[cfg(test)] mod tests { use bytes::Bytes; use super::*; use crate::header::{HeaderName, HeaderValue, CONTENT_TYPE}; #[test] fn test_basic_builder() { let resp = Response::build(StatusCode::OK) .insert_header(("X-TEST", "value")) .finish(); assert_eq!(resp.status(), StatusCode::OK); } #[test] fn test_upgrade() { let resp = Response::build(StatusCode::OK) .upgrade("websocket") .finish(); assert!(resp.upgrade()); assert_eq!( resp.headers().get(header::UPGRADE).unwrap(), HeaderValue::from_static("websocket") ); } #[test] fn test_force_close() { let resp = Response::build(StatusCode::OK).force_close().finish(); assert!(!resp.keep_alive()); } #[test] fn test_content_type() { let resp = Response::build(StatusCode::OK) .content_type("text/plain") .body(Bytes::new()); assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "text/plain"); let resp = Response::build(StatusCode::OK) .content_type(mime::TEXT_JAVASCRIPT) .body(Bytes::new()); assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "text/javascript"); } #[test] fn test_into_builder() { let mut resp: Response<_> = "test".into(); assert_eq!(resp.status(), StatusCode::OK); resp.headers_mut().insert( HeaderName::from_static("cookie"), HeaderValue::from_static("cookie1=val100"), ); let mut builder: ResponseBuilder = resp.into(); let resp = builder.status(StatusCode::BAD_REQUEST).finish(); assert_eq!(resp.status(), StatusCode::BAD_REQUEST); let cookie = resp.headers().get_all("Cookie").next().unwrap(); assert_eq!(cookie.to_str().unwrap(), "cookie1=val100"); } #[test] fn response_builder_header_insert_kv() { let mut res = Response::build(StatusCode::OK); res.insert_header(("Content-Type", "application/octet-stream")); let res = res.finish(); assert_eq!( res.headers().get("Content-Type"), Some(&HeaderValue::from_static("application/octet-stream")) ); } #[test] fn response_builder_header_insert_typed() { let mut res = Response::build(StatusCode::OK); res.insert_header((header::CONTENT_TYPE, mime::APPLICATION_OCTET_STREAM)); let res = res.finish(); assert_eq!( res.headers().get("Content-Type"), Some(&HeaderValue::from_static("application/octet-stream")) ); } #[test] fn response_builder_header_append_kv() { let mut res = Response::build(StatusCode::OK); res.append_header(("Content-Type", "application/octet-stream")); res.append_header(("Content-Type", "application/json")); let res = res.finish(); let headers: Vec<_> = res.headers().get_all("Content-Type").cloned().collect(); assert_eq!(headers.len(), 2); assert!(headers.contains(&HeaderValue::from_static("application/octet-stream"))); assert!(headers.contains(&HeaderValue::from_static("application/json"))); } #[test] fn response_builder_header_append_typed() { let mut res = Response::build(StatusCode::OK); res.append_header((header::CONTENT_TYPE, mime::APPLICATION_OCTET_STREAM)); res.append_header((header::CONTENT_TYPE, mime::APPLICATION_JSON)); let res = res.finish(); let headers: Vec<_> = res.headers().get_all("Content-Type").cloned().collect(); assert_eq!(headers.len(), 2); assert!(headers.contains(&HeaderValue::from_static("application/octet-stream"))); assert!(headers.contains(&HeaderValue::from_static("application/json"))); } }
//! Response head type and caching pool. use std::{cell::RefCell, ops}; use crate::{header::HeaderMap, message::Flags, ConnectionType, StatusCode, Version}; thread_local! { static RESPONSE_POOL: BoxedResponsePool = BoxedResponsePool::create(); } #[derive(Debug, Clone)] pub struct ResponseHead { pub version: Version, pub status: StatusCode, pub headers: HeaderMap, pub reason: Option<&'static str>, pub(crate) flags: Flags, } impl ResponseHead { /// Create new instance of `ResponseHead` type #[inline] pub fn new(status: StatusCode) -> ResponseHead { ResponseHead { status, version: Version::HTTP_11, headers: HeaderMap::with_capacity(12), reason: None, flags: Flags::empty(), } } /// Read the message headers. #[inline] pub fn headers(&self) -> &HeaderMap { &self.headers } /// Mutable reference to the message headers. #[inline] pub fn headers_mut(&mut self) -> &mut HeaderMap { &mut self.headers } /// Sets the flag that controls whether to send headers formatted as Camel-Case. /// /// Only applicable to HTTP/1.x responses; HTTP/2 header names are always lowercase. #[inline] pub fn set_camel_case_headers(&mut self, camel_case: bool) { if camel_case { self.flags.insert(Flags::CAMEL_CASE); } else { self.flags.remove(Flags::CAMEL_CASE); } } /// Set connection type of the message #[inline] pub fn set_connection_type(&mut self, ctype: ConnectionType) { match ctype { ConnectionType::Close => self.flags.insert(Flags::CLOSE), ConnectionType::KeepAlive => self.flags.insert(Flags::KEEP_ALIVE), ConnectionType::Upgrade => self.flags.insert(Flags::UPGRADE), } } #[inline] pub fn connection_type(&self) -> ConnectionType { if self.flags.contains(Flags::CLOSE) { ConnectionType::Close } else if self.flags.contains(Flags::KEEP_ALIVE) { ConnectionType::KeepAlive } else if self.flags.contains(Flags::UPGRADE) { ConnectionType::Upgrade } else if self.version < Version::HTTP_11 { ConnectionType::Close } else { ConnectionType::KeepAlive } } /// Check if keep-alive is enabled #[inline] pub fn keep_alive(&self) -> bool { self.connection_type() == ConnectionType::KeepAlive } /// Check upgrade status of this message #[inline] pub fn upgrade(&self) -> bool { self.connection_type() == ConnectionType::Upgrade } /// Get custom reason for the response #[inline] pub fn reason(&self) -> &str { self.reason.unwrap_or_else(|| { self.status .canonical_reason() .unwrap_or("<unknown status code>") }) } #[inline] pub(crate) fn conn_type(&self) -> Option<ConnectionType> { if self.flags.contains(Flags::CLOSE) { Some(ConnectionType::Close) } else if self.flags.contains(Flags::KEEP_ALIVE) { Some(ConnectionType::KeepAlive) } else if self.flags.contains(Flags::UPGRADE) { Some(ConnectionType::Upgrade) } else { None } } /// Get response body chunking state #[inline] pub fn chunked(&self) -> bool { !self.flags.contains(Flags::NO_CHUNKING) } /// Set no chunking for payload #[inline] pub fn no_chunking(&mut self, val: bool) { if val { self.flags.insert(Flags::NO_CHUNKING); } else { self.flags.remove(Flags::NO_CHUNKING); } } } pub(crate) struct BoxedResponseHead { head: Option<Box<ResponseHead>>, } impl BoxedResponseHead { /// Get new message from the pool of objects pub fn new(status: StatusCode) -> Self { RESPONSE_POOL.with(|p| p.get_message(status)) } } impl ops::Deref for BoxedResponseHead { type Target = ResponseHead; fn deref(&self) -> &Self::Target { self.head.as_ref().unwrap() } } impl ops::DerefMut for BoxedResponseHead { fn deref_mut(&mut self) -> &mut Self::Target { self.head.as_mut().unwrap() } } impl Drop for BoxedResponseHead { fn drop(&mut self) { if let Some(head) = self.head.take() { RESPONSE_POOL.with(move |p| p.release(head)) } } } /// Response head object pool. #[doc(hidden)] pub struct BoxedResponsePool(#[allow(clippy::vec_box)] RefCell<Vec<Box<ResponseHead>>>); impl BoxedResponsePool { fn create() -> BoxedResponsePool { BoxedResponsePool(RefCell::new(Vec::with_capacity(128))) } /// Get message from the pool. #[inline] fn get_message(&self, status: StatusCode) -> BoxedResponseHead { if let Some(mut head) = self.0.borrow_mut().pop() { head.reason = None; head.status = status; head.headers.clear(); head.flags = Flags::empty(); BoxedResponseHead { head: Some(head) } } else { BoxedResponseHead { head: Some(Box::new(ResponseHead::new(status))), } } } /// Release request instance. #[inline] fn release(&self, msg: Box<ResponseHead>) { let pool = &mut self.0.borrow_mut(); if pool.len() < 128 { pool.push(msg); } } } #[cfg(test)] mod tests { use std::{ io::{Read as _, Write as _}, net, }; use memchr::memmem; use crate::{ h1::H1Service, header::{HeaderName, HeaderValue}, Error, Request, Response, ServiceConfig, }; #[actix_rt::test] async fn camel_case_headers() { let mut srv = actix_http_test::test_server(|| { H1Service::with_config(ServiceConfig::default(), |req: Request| async move { let mut res = Response::ok(); if req.path().contains("camel") { res.head_mut().set_camel_case_headers(true); } res.headers_mut().insert( HeaderName::from_static("foo-bar"), HeaderValue::from_static("baz"), ); Ok::<_, Error>(res) }) .tcp() }) .await; let mut stream = net::TcpStream::connect(srv.addr()).unwrap(); stream .write_all(b"GET /camel HTTP/1.1\r\nConnection: Close\r\n\r\n") .unwrap(); let mut data = vec![]; let _ = stream.read_to_end(&mut data).unwrap(); assert_eq!(&data[..17], b"HTTP/1.1 200 OK\r\n"); assert!(memmem::find(&data, b"Foo-Bar").is_some()); assert!(memmem::find(&data, b"foo-bar").is_none()); assert!(memmem::find(&data, b"Date").is_some()); assert!(memmem::find(&data, b"date").is_none()); assert!(memmem::find(&data, b"Content-Length").is_some()); assert!(memmem::find(&data, b"content-length").is_none()); let mut stream = net::TcpStream::connect(srv.addr()).unwrap(); stream .write_all(b"GET /lower HTTP/1.1\r\nConnection: Close\r\n\r\n") .unwrap(); let mut data = vec![]; let _ = stream.read_to_end(&mut data).unwrap(); assert_eq!(&data[..17], b"HTTP/1.1 200 OK\r\n"); assert!(memmem::find(&data, b"Foo-Bar").is_none()); assert!(memmem::find(&data, b"foo-bar").is_some()); assert!(memmem::find(&data, b"Date").is_none()); assert!(memmem::find(&data, b"date").is_some()); assert!(memmem::find(&data, b"Content-Length").is_none()); assert!(memmem::find(&data, b"content-length").is_some()); srv.stop().await; } }
//! HTTP response. mod builder; mod head; #[allow(clippy::module_inception)] mod response; pub(crate) use self::head::BoxedResponseHead; pub use self::{builder::ResponseBuilder, head::ResponseHead, response::Response};
//! HTTP response. use std::{ cell::{Ref, RefCell, RefMut}, fmt, str, }; use bytes::{Bytes, BytesMut}; use bytestring::ByteString; use crate::{ body::{BoxBody, EitherBody, MessageBody}, header::{self, HeaderMap, TryIntoHeaderValue}, responses::BoxedResponseHead, Error, Extensions, ResponseBuilder, ResponseHead, StatusCode, }; /// An HTTP response. pub struct Response<B> { pub(crate) head: BoxedResponseHead, pub(crate) body: B, pub(crate) extensions: RefCell<Extensions>, } impl Response<BoxBody> { /// Constructs a new response with default body. #[inline] pub fn new(status: StatusCode) -> Self { Response { head: BoxedResponseHead::new(status), body: BoxBody::new(()), extensions: RefCell::new(Extensions::new()), } } /// Constructs a new response builder. #[inline] pub fn build(status: StatusCode) -> ResponseBuilder { ResponseBuilder::new(status) } // just a couple frequently used shortcuts // this list should not grow larger than a few /// Constructs a new response with status 200 OK. #[inline] pub fn ok() -> Self { Response::new(StatusCode::OK) } /// Constructs a new response with status 400 Bad Request. #[inline] pub fn bad_request() -> Self { Response::new(StatusCode::BAD_REQUEST) } /// Constructs a new response with status 404 Not Found. #[inline] pub fn not_found() -> Self { Response::new(StatusCode::NOT_FOUND) } /// Constructs a new response with status 500 Internal Server Error. #[inline] pub fn internal_server_error() -> Self { Response::new(StatusCode::INTERNAL_SERVER_ERROR) } // end shortcuts } impl<B> Response<B> { /// Constructs a new response with given body. #[inline] pub fn with_body(status: StatusCode, body: B) -> Response<B> { Response { head: BoxedResponseHead::new(status), body, extensions: RefCell::new(Extensions::new()), } } /// Returns a reference to the head of this response. #[inline] pub fn head(&self) -> &ResponseHead { &self.head } /// Returns a mutable reference to the head of this response. #[inline] pub fn head_mut(&mut self) -> &mut ResponseHead { &mut self.head } /// Returns the status code of this response. #[inline] pub fn status(&self) -> StatusCode { self.head.status } /// Returns a mutable reference the status code of this response. #[inline] pub fn status_mut(&mut self) -> &mut StatusCode { &mut self.head.status } /// Returns a reference to response headers. #[inline] pub fn headers(&self) -> &HeaderMap { &self.head.headers } /// Returns a mutable reference to response headers. #[inline] pub fn headers_mut(&mut self) -> &mut HeaderMap { &mut self.head.headers } /// Returns true if connection upgrade is enabled. #[inline] pub fn upgrade(&self) -> bool { self.head.upgrade() } /// Returns true if keep-alive is enabled. #[inline] pub fn keep_alive(&self) -> bool { self.head.keep_alive() } /// Returns a reference to the request-local data/extensions container. #[inline] pub fn extensions(&self) -> Ref<'_, Extensions> { self.extensions.borrow() } /// Returns a mutable reference to the request-local data/extensions container. #[inline] pub fn extensions_mut(&mut self) -> RefMut<'_, Extensions> { self.extensions.borrow_mut() } /// Returns a reference to the body of this response. #[inline] pub fn body(&self) -> &B { &self.body } /// Sets new body. #[inline] pub fn set_body<B2>(self, body: B2) -> Response<B2> { Response { head: self.head, body, extensions: self.extensions, } } /// Drops body and returns new response. #[inline] pub fn drop_body(self) -> Response<()> { self.set_body(()) } /// Sets new body, returning new response and previous body value. #[inline] pub(crate) fn replace_body<B2>(self, body: B2) -> (Response<B2>, B) { ( Response { head: self.head, body, extensions: self.extensions, }, self.body, ) } /// Returns split head and body. /// /// # Implementation Notes /// Due to internal performance optimizations, the first element of the returned tuple is a /// `Response` as well but only contains the head of the response this was called on. #[inline] pub fn into_parts(self) -> (Response<()>, B) { self.replace_body(()) } /// Map the current body type to another using a closure, returning a new response. /// /// Closure receives the response head and the current body type. #[inline] pub fn map_body<F, B2>(mut self, f: F) -> Response<B2> where F: FnOnce(&mut ResponseHead, B) -> B2, { let body = f(&mut self.head, self.body); Response { head: self.head, body, extensions: self.extensions, } } /// Map the current body to a type-erased `BoxBody`. #[inline] pub fn map_into_boxed_body(self) -> Response<BoxBody> where B: MessageBody + 'static, { self.map_body(|_, body| body.boxed()) } /// Returns the response body, dropping all other parts. #[inline] pub fn into_body(self) -> B { self.body } } impl<B> fmt::Debug for Response<B> where B: MessageBody, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let res = writeln!( f, "\nResponse {:?} {}{}", self.head.version, self.head.status, self.head.reason.unwrap_or(""), ); let _ = writeln!(f, " headers:"); for (key, val) in self.head.headers.iter() { let _ = writeln!(f, " {:?}: {:?}", key, val); } let _ = writeln!(f, " body: {:?}", self.body.size()); res } } impl<B: Default> Default for Response<B> { #[inline] fn default() -> Response<B> { Response::with_body(StatusCode::default(), B::default()) } } impl<I: Into<Response<BoxBody>>, E: Into<Error>> From<Result<I, E>> for Response<BoxBody> { fn from(res: Result<I, E>) -> Self { match res { Ok(val) => val.into(), Err(err) => Response::from(err.into()), } } } impl From<ResponseBuilder> for Response<EitherBody<()>> { fn from(mut builder: ResponseBuilder) -> Self { builder.finish() } } impl From<std::convert::Infallible> for Response<BoxBody> { fn from(val: std::convert::Infallible) -> Self { match val {} } } impl From<&'static str> for Response<&'static str> { fn from(val: &'static str) -> Self { let mut res = Response::with_body(StatusCode::OK, val); let mime = mime::TEXT_PLAIN_UTF_8.try_into_value().unwrap(); res.headers_mut().insert(header::CONTENT_TYPE, mime); res } } impl From<&'static [u8]> for Response<&'static [u8]> { fn from(val: &'static [u8]) -> Self { let mut res = Response::with_body(StatusCode::OK, val); let mime = mime::APPLICATION_OCTET_STREAM.try_into_value().unwrap(); res.headers_mut().insert(header::CONTENT_TYPE, mime); res } } impl From<Vec<u8>> for Response<Vec<u8>> { fn from(val: Vec<u8>) -> Self { let mut res = Response::with_body(StatusCode::OK, val); let mime = mime::APPLICATION_OCTET_STREAM.try_into_value().unwrap(); res.headers_mut().insert(header::CONTENT_TYPE, mime); res } } impl From<&Vec<u8>> for Response<Vec<u8>> { fn from(val: &Vec<u8>) -> Self { let mut res = Response::with_body(StatusCode::OK, val.clone()); let mime = mime::APPLICATION_OCTET_STREAM.try_into_value().unwrap(); res.headers_mut().insert(header::CONTENT_TYPE, mime); res } } impl From<String> for Response<String> { fn from(val: String) -> Self { let mut res = Response::with_body(StatusCode::OK, val); let mime = mime::TEXT_PLAIN_UTF_8.try_into_value().unwrap(); res.headers_mut().insert(header::CONTENT_TYPE, mime); res } } impl From<&String> for Response<String> { fn from(val: &String) -> Self { let mut res = Response::with_body(StatusCode::OK, val.clone()); let mime = mime::TEXT_PLAIN_UTF_8.try_into_value().unwrap(); res.headers_mut().insert(header::CONTENT_TYPE, mime); res } } impl From<Bytes> for Response<Bytes> { fn from(val: Bytes) -> Self { let mut res = Response::with_body(StatusCode::OK, val); let mime = mime::APPLICATION_OCTET_STREAM.try_into_value().unwrap(); res.headers_mut().insert(header::CONTENT_TYPE, mime); res } } impl From<BytesMut> for Response<BytesMut> { fn from(val: BytesMut) -> Self { let mut res = Response::with_body(StatusCode::OK, val); let mime = mime::APPLICATION_OCTET_STREAM.try_into_value().unwrap(); res.headers_mut().insert(header::CONTENT_TYPE, mime); res } } impl From<ByteString> for Response<ByteString> { fn from(val: ByteString) -> Self { let mut res = Response::with_body(StatusCode::OK, val); let mime = mime::TEXT_PLAIN_UTF_8.try_into_value().unwrap(); res.headers_mut().insert(header::CONTENT_TYPE, mime); res } } #[cfg(test)] mod tests { use super::*; use crate::{ body::to_bytes, header::{HeaderValue, CONTENT_TYPE, COOKIE}, }; #[test] fn test_debug() { let resp = Response::build(StatusCode::OK) .append_header((COOKIE, HeaderValue::from_static("cookie1=value1; "))) .append_header((COOKIE, HeaderValue::from_static("cookie2=value2; "))) .finish(); let dbg = format!("{:?}", resp); assert!(dbg.contains("Response")); } #[actix_rt::test] async fn test_into_response() { let res = Response::from("test"); assert_eq!(res.status(), StatusCode::OK); assert_eq!( res.headers().get(CONTENT_TYPE).unwrap(), HeaderValue::from_static("text/plain; charset=utf-8") ); assert_eq!(res.status(), StatusCode::OK); assert_eq!(to_bytes(res.into_body()).await.unwrap(), &b"test"[..]); let res = Response::from(b"test".as_ref()); assert_eq!(res.status(), StatusCode::OK); assert_eq!( res.headers().get(CONTENT_TYPE).unwrap(), HeaderValue::from_static("application/octet-stream") ); assert_eq!(res.status(), StatusCode::OK); assert_eq!(to_bytes(res.into_body()).await.unwrap(), &b"test"[..]); let res = Response::from("test".to_owned()); assert_eq!(res.status(), StatusCode::OK); assert_eq!( res.headers().get(CONTENT_TYPE).unwrap(), HeaderValue::from_static("text/plain; charset=utf-8") ); assert_eq!(res.status(), StatusCode::OK); assert_eq!(to_bytes(res.into_body()).await.unwrap(), &b"test"[..]); let res = Response::from("test".to_owned()); assert_eq!(res.status(), StatusCode::OK); assert_eq!( res.headers().get(CONTENT_TYPE).unwrap(), HeaderValue::from_static("text/plain; charset=utf-8") ); assert_eq!(res.status(), StatusCode::OK); assert_eq!(to_bytes(res.into_body()).await.unwrap(), &b"test"[..]); let b = Bytes::from_static(b"test"); let res = Response::from(b); assert_eq!(res.status(), StatusCode::OK); assert_eq!( res.headers().get(CONTENT_TYPE).unwrap(), HeaderValue::from_static("application/octet-stream") ); assert_eq!(res.status(), StatusCode::OK); assert_eq!(to_bytes(res.into_body()).await.unwrap(), &b"test"[..]); let b = Bytes::from_static(b"test"); let res = Response::from(b); assert_eq!(res.status(), StatusCode::OK); assert_eq!( res.headers().get(CONTENT_TYPE).unwrap(), HeaderValue::from_static("application/octet-stream") ); assert_eq!(res.status(), StatusCode::OK); assert_eq!(to_bytes(res.into_body()).await.unwrap(), &b"test"[..]); let b = BytesMut::from("test"); let res = Response::from(b); assert_eq!(res.status(), StatusCode::OK); assert_eq!( res.headers().get(CONTENT_TYPE).unwrap(), HeaderValue::from_static("application/octet-stream") ); assert_eq!(res.status(), StatusCode::OK); assert_eq!(to_bytes(res.into_body()).await.unwrap(), &b"test"[..]); } }
use std::{ fmt, future::Future, marker::PhantomData, net, pin::Pin, rc::Rc, task::{Context, Poll}, }; use actix_codec::{AsyncRead, AsyncWrite, Framed}; use actix_rt::net::TcpStream; use actix_service::{ fn_service, IntoServiceFactory, Service, ServiceFactory, ServiceFactoryExt as _, }; use futures_core::{future::LocalBoxFuture, ready}; use pin_project_lite::pin_project; use tracing::error; use crate::{ body::{BoxBody, MessageBody}, builder::HttpServiceBuilder, error::DispatchError, h1, ConnectCallback, OnConnectData, Protocol, Request, Response, ServiceConfig, }; /// A [`ServiceFactory`] for HTTP/1.1 and HTTP/2 connections. /// /// Use [`build`](Self::build) to begin constructing service. Also see [`HttpServiceBuilder`]. /// /// # Automatic HTTP Version Selection /// There are two ways to select the HTTP version of an incoming connection: /// - One is to rely on the ALPN information that is provided when using TLS (HTTPS); both versions /// are supported automatically when using either of the `.rustls()` or `.openssl()` finalizing /// methods. /// - The other is to read the first few bytes of the TCP stream. This is the only viable approach /// for supporting H2C, which allows the HTTP/2 protocol to work over plaintext connections. Use /// the `.tcp_auto_h2c()` finalizing method to enable this behavior. /// /// # Examples /// ``` /// # use std::convert::Infallible; /// use actix_http::{HttpService, Request, Response, StatusCode}; /// /// // this service would constructed in an actix_server::Server /// /// # actix_rt::System::new().block_on(async { /// HttpService::build() /// // the builder finalizing method, other finalizers would not return an `HttpService` /// .finish(|_req: Request| async move { /// Ok::<_, Infallible>( /// Response::build(StatusCode::OK).body("Hello!") /// ) /// }) /// // the service finalizing method method /// // you can use `.tcp_auto_h2c()`, `.rustls()`, or `.openssl()` instead of `.tcp()` /// .tcp(); /// # }) /// ``` pub struct HttpService<T, S, B, X = h1::ExpectHandler, U = h1::UpgradeHandler> { srv: S, cfg: ServiceConfig, expect: X, upgrade: Option<U>, on_connect_ext: Option<Rc<ConnectCallback<T>>>, _phantom: PhantomData<B>, } impl<T, S, B> HttpService<T, S, B> where S: ServiceFactory<Request, Config = ()>, S::Error: Into<Response<BoxBody>> + 'static, S::InitError: fmt::Debug, S::Response: Into<Response<B>> + 'static, <S::Service as Service<Request>>::Future: 'static, B: MessageBody + 'static, { /// Constructs builder for `HttpService` instance. pub fn build() -> HttpServiceBuilder<T, S> { HttpServiceBuilder::default() } } impl<T, S, B> HttpService<T, S, B> where S: ServiceFactory<Request, Config = ()>, S::Error: Into<Response<BoxBody>> + 'static, S::InitError: fmt::Debug, S::Response: Into<Response<B>> + 'static, <S::Service as Service<Request>>::Future: 'static, B: MessageBody + 'static, { /// Constructs new `HttpService` instance from service with default config. pub fn new<F: IntoServiceFactory<S, Request>>(service: F) -> Self { HttpService { cfg: ServiceConfig::default(), srv: service.into_factory(), expect: h1::ExpectHandler, upgrade: None, on_connect_ext: None, _phantom: PhantomData, } } /// Constructs new `HttpService` instance from config and service. pub(crate) fn with_config<F: IntoServiceFactory<S, Request>>( cfg: ServiceConfig, service: F, ) -> Self { HttpService { cfg, srv: service.into_factory(), expect: h1::ExpectHandler, upgrade: None, on_connect_ext: None, _phantom: PhantomData, } } } impl<T, S, B, X, U> HttpService<T, S, B, X, U> where S: ServiceFactory<Request, Config = ()>, S::Error: Into<Response<BoxBody>> + 'static, S::InitError: fmt::Debug, S::Response: Into<Response<B>> + 'static, <S::Service as Service<Request>>::Future: 'static, B: MessageBody, { /// Sets service for `Expect: 100-Continue` handling. /// /// An expect service is called with requests that contain an `Expect` header. A successful /// response type is also a request which will be forwarded to the main service. pub fn expect<X1>(self, expect: X1) -> HttpService<T, S, B, X1, U> where X1: ServiceFactory<Request, Config = (), Response = Request>, X1::Error: Into<Response<BoxBody>>, X1::InitError: fmt::Debug, { HttpService { expect, cfg: self.cfg, srv: self.srv, upgrade: self.upgrade, on_connect_ext: self.on_connect_ext, _phantom: PhantomData, } } /// Sets service for custom `Connection: Upgrade` handling. /// /// If service is provided then normal requests handling get halted and this service get called /// with original request and framed object. pub fn upgrade<U1>(self, upgrade: Option<U1>) -> HttpService<T, S, B, X, U1> where U1: ServiceFactory<(Request, Framed<T, h1::Codec>), Config = (), Response = ()>, U1::Error: fmt::Display, U1::InitError: fmt::Debug, { HttpService { upgrade, cfg: self.cfg, srv: self.srv, expect: self.expect, on_connect_ext: self.on_connect_ext, _phantom: PhantomData, } } /// Set connect callback with mutable access to request data container. pub(crate) fn on_connect_ext(mut self, f: Option<Rc<ConnectCallback<T>>>) -> Self { self.on_connect_ext = f; self } } impl<S, B, X, U> HttpService<TcpStream, S, B, X, U> where S: ServiceFactory<Request, Config = ()>, S::Future: 'static, S::Error: Into<Response<BoxBody>> + 'static, S::InitError: fmt::Debug, S::Response: Into<Response<B>> + 'static, <S::Service as Service<Request>>::Future: 'static, B: MessageBody + 'static, X: ServiceFactory<Request, Config = (), Response = Request>, X::Future: 'static, X::Error: Into<Response<BoxBody>>, X::InitError: fmt::Debug, U: ServiceFactory<(Request, Framed<TcpStream, h1::Codec>), Config = (), Response = ()>, U::Future: 'static, U::Error: fmt::Display + Into<Response<BoxBody>>, U::InitError: fmt::Debug, { /// Creates TCP stream service from HTTP service. /// /// The resulting service only supports HTTP/1.x. pub fn tcp( self, ) -> impl ServiceFactory<TcpStream, Config = (), Response = (), Error = DispatchError, InitError = ()> { fn_service(|io: TcpStream| async { let peer_addr = io.peer_addr().ok(); Ok((io, Protocol::Http1, peer_addr)) }) .and_then(self) } /// Creates TCP stream service from HTTP service that automatically selects HTTP/1.x or HTTP/2 /// on plaintext connections. #[cfg(feature = "http2")] pub fn tcp_auto_h2c( self, ) -> impl ServiceFactory<TcpStream, Config = (), Response = (), Error = DispatchError, InitError = ()> { fn_service(move |io: TcpStream| async move { // subset of HTTP/2 preface defined by RFC 9113 §3.4 // this subset was chosen to maximize likelihood that peeking only once will allow us to // reliably determine version or else it should fallback to h1 and fail quickly if data // on the wire is junk const H2_PREFACE: &[u8] = b"PRI * HTTP/2"; let mut buf = [0; 12]; io.peek(&mut buf).await?; let proto = if buf == H2_PREFACE { Protocol::Http2 } else { Protocol::Http1 }; let peer_addr = io.peer_addr().ok(); Ok((io, proto, peer_addr)) }) .and_then(self) } } /// Configuration options used when accepting TLS connection. #[cfg(feature = "__tls")] #[derive(Debug, Default)] pub struct TlsAcceptorConfig { pub(crate) handshake_timeout: Option<std::time::Duration>, } #[cfg(feature = "__tls")] impl TlsAcceptorConfig { /// Set TLS handshake timeout duration. pub fn handshake_timeout(self, dur: std::time::Duration) -> Self { Self { handshake_timeout: Some(dur), // ..self } } } #[cfg(feature = "openssl")] mod openssl { use actix_service::ServiceFactoryExt as _; use actix_tls::accept::{ openssl::{ reexports::{Error as SslError, SslAcceptor}, Acceptor, TlsStream, }, TlsError, }; use super::*; impl<S, B, X, U> HttpService<TlsStream<TcpStream>, S, B, X, U> where S: ServiceFactory<Request, Config = ()>, S::Future: 'static, S::Error: Into<Response<BoxBody>> + 'static, S::InitError: fmt::Debug, S::Response: Into<Response<B>> + 'static, <S::Service as Service<Request>>::Future: 'static, B: MessageBody + 'static, X: ServiceFactory<Request, Config = (), Response = Request>, X::Future: 'static, X::Error: Into<Response<BoxBody>>, X::InitError: fmt::Debug, U: ServiceFactory< (Request, Framed<TlsStream<TcpStream>, h1::Codec>), Config = (), Response = (), >, U::Future: 'static, U::Error: fmt::Display + Into<Response<BoxBody>>, U::InitError: fmt::Debug, { /// Create OpenSSL based service. pub fn openssl( self, acceptor: SslAcceptor, ) -> impl ServiceFactory< TcpStream, Config = (), Response = (), Error = TlsError<SslError, DispatchError>, InitError = (), > { self.openssl_with_config(acceptor, TlsAcceptorConfig::default()) } /// Create OpenSSL based service with custom TLS acceptor configuration. pub fn openssl_with_config( self, acceptor: SslAcceptor, tls_acceptor_config: TlsAcceptorConfig, ) -> impl ServiceFactory< TcpStream, Config = (), Response = (), Error = TlsError<SslError, DispatchError>, InitError = (), > { let mut acceptor = Acceptor::new(acceptor); if let Some(handshake_timeout) = tls_acceptor_config.handshake_timeout { acceptor.set_handshake_timeout(handshake_timeout); } acceptor .map_init_err(|_| { unreachable!("TLS acceptor service factory does not error on init") }) .map_err(TlsError::into_service_error) .map(|io: TlsStream<TcpStream>| { let proto = if let Some(protos) = io.ssl().selected_alpn_protocol() { if protos.windows(2).any(|window| window == b"h2") { Protocol::Http2 } else { Protocol::Http1 } } else { Protocol::Http1 }; let peer_addr = io.get_ref().peer_addr().ok(); (io, proto, peer_addr) }) .and_then(self.map_err(TlsError::Service)) } } } #[cfg(feature = "rustls-0_20")] mod rustls_0_20 { use std::io; use actix_service::ServiceFactoryExt as _; use actix_tls::accept::{ rustls_0_20::{reexports::ServerConfig, Acceptor, TlsStream}, TlsError, }; use super::*; impl<S, B, X, U> HttpService<TlsStream<TcpStream>, S, B, X, U> where S: ServiceFactory<Request, Config = ()>, S::Future: 'static, S::Error: Into<Response<BoxBody>> + 'static, S::InitError: fmt::Debug, S::Response: Into<Response<B>> + 'static, <S::Service as Service<Request>>::Future: 'static, B: MessageBody + 'static, X: ServiceFactory<Request, Config = (), Response = Request>, X::Future: 'static, X::Error: Into<Response<BoxBody>>, X::InitError: fmt::Debug, U: ServiceFactory< (Request, Framed<TlsStream<TcpStream>, h1::Codec>), Config = (), Response = (), >, U::Future: 'static, U::Error: fmt::Display + Into<Response<BoxBody>>, U::InitError: fmt::Debug, { /// Create Rustls v0.20 based service. pub fn rustls( self, config: ServerConfig, ) -> impl ServiceFactory< TcpStream, Config = (), Response = (), Error = TlsError<io::Error, DispatchError>, InitError = (), > { self.rustls_with_config(config, TlsAcceptorConfig::default()) } /// Create Rustls v0.20 based service with custom TLS acceptor configuration. pub fn rustls_with_config( self, mut config: ServerConfig, tls_acceptor_config: TlsAcceptorConfig, ) -> impl ServiceFactory< TcpStream, Config = (), Response = (), Error = TlsError<io::Error, DispatchError>, InitError = (), > { let mut protos = vec![b"h2".to_vec(), b"http/1.1".to_vec()]; protos.extend_from_slice(&config.alpn_protocols); config.alpn_protocols = protos; let mut acceptor = Acceptor::new(config); if let Some(handshake_timeout) = tls_acceptor_config.handshake_timeout { acceptor.set_handshake_timeout(handshake_timeout); } acceptor .map_init_err(|_| { unreachable!("TLS acceptor service factory does not error on init") }) .map_err(TlsError::into_service_error) .and_then(|io: TlsStream<TcpStream>| async { let proto = if let Some(protos) = io.get_ref().1.alpn_protocol() { if protos.windows(2).any(|window| window == b"h2") { Protocol::Http2 } else { Protocol::Http1 } } else { Protocol::Http1 }; let peer_addr = io.get_ref().0.peer_addr().ok(); Ok((io, proto, peer_addr)) }) .and_then(self.map_err(TlsError::Service)) } } } #[cfg(feature = "rustls-0_21")] mod rustls_0_21 { use std::io; use actix_service::ServiceFactoryExt as _; use actix_tls::accept::{ rustls_0_21::{reexports::ServerConfig, Acceptor, TlsStream}, TlsError, }; use super::*; impl<S, B, X, U> HttpService<TlsStream<TcpStream>, S, B, X, U> where S: ServiceFactory<Request, Config = ()>, S::Future: 'static, S::Error: Into<Response<BoxBody>> + 'static, S::InitError: fmt::Debug, S::Response: Into<Response<B>> + 'static, <S::Service as Service<Request>>::Future: 'static, B: MessageBody + 'static, X: ServiceFactory<Request, Config = (), Response = Request>, X::Future: 'static, X::Error: Into<Response<BoxBody>>, X::InitError: fmt::Debug, U: ServiceFactory< (Request, Framed<TlsStream<TcpStream>, h1::Codec>), Config = (), Response = (), >, U::Future: 'static, U::Error: fmt::Display + Into<Response<BoxBody>>, U::InitError: fmt::Debug, { /// Create Rustls v0.21 based service. pub fn rustls_021( self, config: ServerConfig, ) -> impl ServiceFactory< TcpStream, Config = (), Response = (), Error = TlsError<io::Error, DispatchError>, InitError = (), > { self.rustls_021_with_config(config, TlsAcceptorConfig::default()) } /// Create Rustls v0.21 based service with custom TLS acceptor configuration. pub fn rustls_021_with_config( self, mut config: ServerConfig, tls_acceptor_config: TlsAcceptorConfig, ) -> impl ServiceFactory< TcpStream, Config = (), Response = (), Error = TlsError<io::Error, DispatchError>, InitError = (), > { let mut protos = vec![b"h2".to_vec(), b"http/1.1".to_vec()]; protos.extend_from_slice(&config.alpn_protocols); config.alpn_protocols = protos; let mut acceptor = Acceptor::new(config); if let Some(handshake_timeout) = tls_acceptor_config.handshake_timeout { acceptor.set_handshake_timeout(handshake_timeout); } acceptor .map_init_err(|_| { unreachable!("TLS acceptor service factory does not error on init") }) .map_err(TlsError::into_service_error) .and_then(|io: TlsStream<TcpStream>| async { let proto = if let Some(protos) = io.get_ref().1.alpn_protocol() { if protos.windows(2).any(|window| window == b"h2") { Protocol::Http2 } else { Protocol::Http1 } } else { Protocol::Http1 }; let peer_addr = io.get_ref().0.peer_addr().ok(); Ok((io, proto, peer_addr)) }) .and_then(self.map_err(TlsError::Service)) } } } #[cfg(feature = "rustls-0_22")] mod rustls_0_22 { use std::io; use actix_service::ServiceFactoryExt as _; use actix_tls::accept::{ rustls_0_22::{reexports::ServerConfig, Acceptor, TlsStream}, TlsError, }; use super::*; impl<S, B, X, U> HttpService<TlsStream<TcpStream>, S, B, X, U> where S: ServiceFactory<Request, Config = ()>, S::Future: 'static, S::Error: Into<Response<BoxBody>> + 'static, S::InitError: fmt::Debug, S::Response: Into<Response<B>> + 'static, <S::Service as Service<Request>>::Future: 'static, B: MessageBody + 'static, X: ServiceFactory<Request, Config = (), Response = Request>, X::Future: 'static, X::Error: Into<Response<BoxBody>>, X::InitError: fmt::Debug, U: ServiceFactory< (Request, Framed<TlsStream<TcpStream>, h1::Codec>), Config = (), Response = (), >, U::Future: 'static, U::Error: fmt::Display + Into<Response<BoxBody>>, U::InitError: fmt::Debug, { /// Create Rustls v0.22 based service. pub fn rustls_0_22( self, config: ServerConfig, ) -> impl ServiceFactory< TcpStream, Config = (), Response = (), Error = TlsError<io::Error, DispatchError>, InitError = (), > { self.rustls_0_22_with_config(config, TlsAcceptorConfig::default()) } /// Create Rustls v0.22 based service with custom TLS acceptor configuration. pub fn rustls_0_22_with_config( self, mut config: ServerConfig, tls_acceptor_config: TlsAcceptorConfig, ) -> impl ServiceFactory< TcpStream, Config = (), Response = (), Error = TlsError<io::Error, DispatchError>, InitError = (), > { let mut protos = vec![b"h2".to_vec(), b"http/1.1".to_vec()]; protos.extend_from_slice(&config.alpn_protocols); config.alpn_protocols = protos; let mut acceptor = Acceptor::new(config); if let Some(handshake_timeout) = tls_acceptor_config.handshake_timeout { acceptor.set_handshake_timeout(handshake_timeout); } acceptor .map_init_err(|_| { unreachable!("TLS acceptor service factory does not error on init") }) .map_err(TlsError::into_service_error) .and_then(|io: TlsStream<TcpStream>| async { let proto = if let Some(protos) = io.get_ref().1.alpn_protocol() { if protos.windows(2).any(|window| window == b"h2") { Protocol::Http2 } else { Protocol::Http1 } } else { Protocol::Http1 }; let peer_addr = io.get_ref().0.peer_addr().ok(); Ok((io, proto, peer_addr)) }) .and_then(self.map_err(TlsError::Service)) } } } #[cfg(feature = "rustls-0_23")] mod rustls_0_23 { use std::io; use actix_service::ServiceFactoryExt as _; use actix_tls::accept::{ rustls_0_23::{reexports::ServerConfig, Acceptor, TlsStream}, TlsError, }; use super::*; impl<S, B, X, U> HttpService<TlsStream<TcpStream>, S, B, X, U> where S: ServiceFactory<Request, Config = ()>, S::Future: 'static, S::Error: Into<Response<BoxBody>> + 'static, S::InitError: fmt::Debug, S::Response: Into<Response<B>> + 'static, <S::Service as Service<Request>>::Future: 'static, B: MessageBody + 'static, X: ServiceFactory<Request, Config = (), Response = Request>, X::Future: 'static, X::Error: Into<Response<BoxBody>>, X::InitError: fmt::Debug, U: ServiceFactory< (Request, Framed<TlsStream<TcpStream>, h1::Codec>), Config = (), Response = (), >, U::Future: 'static, U::Error: fmt::Display + Into<Response<BoxBody>>, U::InitError: fmt::Debug, { /// Create Rustls v0.23 based service. pub fn rustls_0_23( self, config: ServerConfig, ) -> impl ServiceFactory< TcpStream, Config = (), Response = (), Error = TlsError<io::Error, DispatchError>, InitError = (), > { self.rustls_0_23_with_config(config, TlsAcceptorConfig::default()) } /// Create Rustls v0.23 based service with custom TLS acceptor configuration. pub fn rustls_0_23_with_config( self, mut config: ServerConfig, tls_acceptor_config: TlsAcceptorConfig, ) -> impl ServiceFactory< TcpStream, Config = (), Response = (), Error = TlsError<io::Error, DispatchError>, InitError = (), > { let mut protos = vec![b"h2".to_vec(), b"http/1.1".to_vec()]; protos.extend_from_slice(&config.alpn_protocols); config.alpn_protocols = protos; let mut acceptor = Acceptor::new(config); if let Some(handshake_timeout) = tls_acceptor_config.handshake_timeout { acceptor.set_handshake_timeout(handshake_timeout); } acceptor .map_init_err(|_| { unreachable!("TLS acceptor service factory does not error on init") }) .map_err(TlsError::into_service_error) .and_then(|io: TlsStream<TcpStream>| async { let proto = if let Some(protos) = io.get_ref().1.alpn_protocol() { if protos.windows(2).any(|window| window == b"h2") { Protocol::Http2 } else { Protocol::Http1 } } else { Protocol::Http1 }; let peer_addr = io.get_ref().0.peer_addr().ok(); Ok((io, proto, peer_addr)) }) .and_then(self.map_err(TlsError::Service)) } } } impl<T, S, B, X, U> ServiceFactory<(T, Protocol, Option<net::SocketAddr>)> for HttpService<T, S, B, X, U> where T: AsyncRead + AsyncWrite + Unpin + 'static, S: ServiceFactory<Request, Config = ()>, S::Future: 'static, S::Error: Into<Response<BoxBody>> + 'static, S::InitError: fmt::Debug, S::Response: Into<Response<B>> + 'static, <S::Service as Service<Request>>::Future: 'static, B: MessageBody + 'static, X: ServiceFactory<Request, Config = (), Response = Request>, X::Future: 'static, X::Error: Into<Response<BoxBody>>, X::InitError: fmt::Debug, U: ServiceFactory<(Request, Framed<T, h1::Codec>), Config = (), Response = ()>, U::Future: 'static, U::Error: fmt::Display + Into<Response<BoxBody>>, U::InitError: fmt::Debug, { type Response = (); type Error = DispatchError; type Config = (); type Service = HttpServiceHandler<T, S::Service, B, X::Service, U::Service>; type InitError = (); type Future = LocalBoxFuture<'static, Result<Self::Service, Self::InitError>>; fn new_service(&self, _: ()) -> Self::Future { let service = self.srv.new_service(()); let expect = self.expect.new_service(()); let upgrade = self.upgrade.as_ref().map(|s| s.new_service(())); let on_connect_ext = self.on_connect_ext.clone(); let cfg = self.cfg.clone(); Box::pin(async move { let expect = expect.await.map_err(|err| { tracing::error!("Initialization of HTTP expect service error: {err:?}"); })?; let upgrade = match upgrade { Some(upgrade) => { let upgrade = upgrade.await.map_err(|err| { tracing::error!("Initialization of HTTP upgrade service error: {err:?}"); })?; Some(upgrade) } None => None, }; let service = service.await.map_err(|err| { tracing::error!("Initialization of HTTP service error: {err:?}"); })?; Ok(HttpServiceHandler::new( cfg, service, expect, upgrade, on_connect_ext, )) }) } } /// `Service` implementation for HTTP/1 and HTTP/2 transport pub struct HttpServiceHandler<T, S, B, X, U> where S: Service<Request>, X: Service<Request>, U: Service<(Request, Framed<T, h1::Codec>)>, { pub(super) flow: Rc<HttpFlow<S, X, U>>, pub(super) cfg: ServiceConfig, pub(super) on_connect_ext: Option<Rc<ConnectCallback<T>>>, _phantom: PhantomData<B>, } impl<T, S, B, X, U> HttpServiceHandler<T, S, B, X, U> where S: Service<Request>, S::Error: Into<Response<BoxBody>>, X: Service<Request>, X::Error: Into<Response<BoxBody>>, U: Service<(Request, Framed<T, h1::Codec>)>, U::Error: Into<Response<BoxBody>>, { pub(super) fn new( cfg: ServiceConfig, service: S, expect: X, upgrade: Option<U>, on_connect_ext: Option<Rc<ConnectCallback<T>>>, ) -> HttpServiceHandler<T, S, B, X, U> { HttpServiceHandler { cfg, on_connect_ext, flow: HttpFlow::new(service, expect, upgrade), _phantom: PhantomData, } } pub(super) fn _poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Response<BoxBody>>> { ready!(self.flow.expect.poll_ready(cx).map_err(Into::into))?; ready!(self.flow.service.poll_ready(cx).map_err(Into::into))?; if let Some(ref upg) = self.flow.upgrade { ready!(upg.poll_ready(cx).map_err(Into::into))?; }; Poll::Ready(Ok(())) } } /// A collection of services that describe an HTTP request flow. pub(super) struct HttpFlow<S, X, U> { pub(super) service: S, pub(super) expect: X, pub(super) upgrade: Option<U>, } impl<S, X, U> HttpFlow<S, X, U> { pub(super) fn new(service: S, expect: X, upgrade: Option<U>) -> Rc<Self> { Rc::new(Self { service, expect, upgrade, }) } } impl<T, S, B, X, U> Service<(T, Protocol, Option<net::SocketAddr>)> for HttpServiceHandler<T, S, B, X, U> where T: AsyncRead + AsyncWrite + Unpin, S: Service<Request>, S::Error: Into<Response<BoxBody>> + 'static, S::Future: 'static, S::Response: Into<Response<B>> + 'static, B: MessageBody + 'static, X: Service<Request, Response = Request>, X::Error: Into<Response<BoxBody>>, U: Service<(Request, Framed<T, h1::Codec>), Response = ()>, U::Error: fmt::Display + Into<Response<BoxBody>>, { type Response = (); type Error = DispatchError; type Future = HttpServiceHandlerResponse<T, S, B, X, U>; fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { self._poll_ready(cx).map_err(|err| { error!("HTTP service readiness error: {:?}", err); DispatchError::Service(err) }) } fn call(&self, (io, proto, peer_addr): (T, Protocol, Option<net::SocketAddr>)) -> Self::Future { let conn_data = OnConnectData::from_io(&io, self.on_connect_ext.as_deref()); match proto { #[cfg(feature = "http2")] Protocol::Http2 => HttpServiceHandlerResponse { state: State::H2Handshake { handshake: Some(( crate::h2::handshake_with_timeout(io, &self.cfg), self.cfg.clone(), Rc::clone(&self.flow), conn_data, peer_addr, )), }, }, #[cfg(not(feature = "http2"))] Protocol::Http2 => { panic!("HTTP/2 support is disabled (enable with the `http2` feature flag)") } Protocol::Http1 => HttpServiceHandlerResponse { state: State::H1 { dispatcher: h1::Dispatcher::new( io, Rc::clone(&self.flow), self.cfg.clone(), peer_addr, conn_data, ), }, }, proto => unimplemented!("Unsupported HTTP version: {:?}.", proto), } } } #[cfg(not(feature = "http2"))] pin_project! { #[project = StateProj] enum State<T, S, B, X, U> where T: AsyncRead, T: AsyncWrite, T: Unpin, S: Service<Request>, S::Future: 'static, S::Error: Into<Response<BoxBody>>, B: MessageBody, X: Service<Request, Response = Request>, X::Error: Into<Response<BoxBody>>, U: Service<(Request, Framed<T, h1::Codec>), Response = ()>, U::Error: fmt::Display, { H1 { #[pin] dispatcher: h1::Dispatcher<T, S, B, X, U> }, } } #[cfg(feature = "http2")] pin_project! { #[project = StateProj] enum State<T, S, B, X, U> where T: AsyncRead, T: AsyncWrite, T: Unpin, S: Service<Request>, S::Future: 'static, S::Error: Into<Response<BoxBody>>, B: MessageBody, X: Service<Request, Response = Request>, X::Error: Into<Response<BoxBody>>, U: Service<(Request, Framed<T, h1::Codec>), Response = ()>, U::Error: fmt::Display, { H1 { #[pin] dispatcher: h1::Dispatcher<T, S, B, X, U> }, H2 { #[pin] dispatcher: crate::h2::Dispatcher<T, S, B, X, U> }, H2Handshake { handshake: Option<( crate::h2::HandshakeWithTimeout<T>, ServiceConfig, Rc<HttpFlow<S, X, U>>, OnConnectData, Option<net::SocketAddr>, )>, }, } } pin_project! { pub struct HttpServiceHandlerResponse<T, S, B, X, U> where T: AsyncRead, T: AsyncWrite, T: Unpin, S: Service<Request>, S::Error: Into<Response<BoxBody>>, S::Error: 'static, S::Future: 'static, S::Response: Into<Response<B>>, S::Response: 'static, B: MessageBody, X: Service<Request, Response = Request>, X::Error: Into<Response<BoxBody>>, U: Service<(Request, Framed<T, h1::Codec>), Response = ()>, U::Error: fmt::Display, { #[pin] state: State<T, S, B, X, U>, } } impl<T, S, B, X, U> Future for HttpServiceHandlerResponse<T, S, B, X, U> where T: AsyncRead + AsyncWrite + Unpin, S: Service<Request>, S::Error: Into<Response<BoxBody>> + 'static, S::Future: 'static, S::Response: Into<Response<B>> + 'static, B: MessageBody + 'static, X: Service<Request, Response = Request>, X::Error: Into<Response<BoxBody>>, U: Service<(Request, Framed<T, h1::Codec>), Response = ()>, U::Error: fmt::Display, { type Output = Result<(), DispatchError>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { match self.as_mut().project().state.project() { StateProj::H1 { dispatcher } => dispatcher.poll(cx), #[cfg(feature = "http2")] StateProj::H2 { dispatcher } => dispatcher.poll(cx), #[cfg(feature = "http2")] StateProj::H2Handshake { handshake: data } => { match ready!(Pin::new(&mut data.as_mut().unwrap().0).poll(cx)) { Ok((conn, timer)) => { let (_, config, flow, conn_data, peer_addr) = data.take().unwrap(); self.as_mut().project().state.set(State::H2 { dispatcher: crate::h2::Dispatcher::new( conn, flow, config, peer_addr, conn_data, timer, ), }); self.poll(cx) } Err(err) => { tracing::trace!("H2 handshake error: {}", err); Poll::Ready(Err(err)) } } } } } }
//! Various testing helpers for use in internal and app tests. use std::{ cell::{Ref, RefCell, RefMut}, io::{self, Read, Write}, pin::Pin, rc::Rc, str::FromStr, task::{Context, Poll}, }; use actix_codec::{AsyncRead, AsyncWrite, ReadBuf}; use bytes::{Bytes, BytesMut}; use http::{Method, Uri, Version}; use crate::{ header::{HeaderMap, TryIntoHeaderPair}, payload::Payload, Request, }; /// Test `Request` builder. pub struct TestRequest(Option<Inner>); struct Inner { version: Version, method: Method, uri: Uri, headers: HeaderMap, payload: Option<Payload>, } impl Default for TestRequest { fn default() -> TestRequest { TestRequest(Some(Inner { method: Method::GET, uri: Uri::from_str("/").unwrap(), version: Version::HTTP_11, headers: HeaderMap::new(), payload: None, })) } } impl TestRequest { /// Create a default TestRequest and then set its URI. pub fn with_uri(path: &str) -> TestRequest { TestRequest::default().uri(path).take() } /// Set HTTP version of this request. pub fn version(&mut self, ver: Version) -> &mut Self { parts(&mut self.0).version = ver; self } /// Set HTTP method of this request. pub fn method(&mut self, meth: Method) -> &mut Self { parts(&mut self.0).method = meth; self } /// Set URI of this request. /// /// # Panics /// If provided URI is invalid. pub fn uri(&mut self, path: &str) -> &mut Self { parts(&mut self.0).uri = Uri::from_str(path).unwrap(); self } /// Insert a header, replacing any that were set with an equivalent field name. pub fn insert_header(&mut self, header: impl TryIntoHeaderPair) -> &mut Self { match header.try_into_pair() { Ok((key, value)) => { parts(&mut self.0).headers.insert(key, value); } Err(err) => { panic!("Error inserting test header: {}.", err.into()); } } self } /// Append a header, keeping any that were set with an equivalent field name. pub fn append_header(&mut self, header: impl TryIntoHeaderPair) -> &mut Self { match header.try_into_pair() { Ok((key, value)) => { parts(&mut self.0).headers.append(key, value); } Err(err) => { panic!("Error inserting test header: {}.", err.into()); } } self } /// Set request payload. pub fn set_payload(&mut self, data: impl Into<Bytes>) -> &mut Self { let mut payload = crate::h1::Payload::empty(); payload.unread_data(data.into()); parts(&mut self.0).payload = Some(payload.into()); self } pub fn take(&mut self) -> TestRequest { TestRequest(self.0.take()) } /// Complete request creation and generate `Request` instance. pub fn finish(&mut self) -> Request { let inner = self.0.take().expect("cannot reuse test request builder"); let mut req = if let Some(pl) = inner.payload { Request::with_payload(pl) } else { Request::with_payload(crate::h1::Payload::empty().into()) }; let head = req.head_mut(); head.uri = inner.uri; head.method = inner.method; head.version = inner.version; head.headers = inner.headers; req } } #[inline] fn parts(parts: &mut Option<Inner>) -> &mut Inner { parts.as_mut().expect("cannot reuse test request builder") } /// Async I/O test buffer. #[derive(Debug)] pub struct TestBuffer { pub read_buf: Rc<RefCell<BytesMut>>, pub write_buf: Rc<RefCell<BytesMut>>, pub err: Option<Rc<io::Error>>, } impl TestBuffer { /// Create new `TestBuffer` instance with initial read buffer. pub fn new<T>(data: T) -> Self where T: Into<BytesMut>, { Self { read_buf: Rc::new(RefCell::new(data.into())), write_buf: Rc::new(RefCell::new(BytesMut::new())), err: None, } } // intentionally not using Clone trait #[allow(dead_code)] pub(crate) fn clone(&self) -> Self { Self { read_buf: Rc::clone(&self.read_buf), write_buf: Rc::clone(&self.write_buf), err: self.err.clone(), } } /// Create new empty `TestBuffer` instance. pub fn empty() -> Self { Self::new("") } #[allow(dead_code)] pub(crate) fn read_buf_slice(&self) -> Ref<'_, [u8]> { Ref::map(self.read_buf.borrow(), |b| b.as_ref()) } #[allow(dead_code)] pub(crate) fn read_buf_slice_mut(&self) -> RefMut<'_, [u8]> { RefMut::map(self.read_buf.borrow_mut(), |b| b.as_mut()) } #[allow(dead_code)] pub(crate) fn write_buf_slice(&self) -> Ref<'_, [u8]> { Ref::map(self.write_buf.borrow(), |b| b.as_ref()) } #[allow(dead_code)] pub(crate) fn write_buf_slice_mut(&self) -> RefMut<'_, [u8]> { RefMut::map(self.write_buf.borrow_mut(), |b| b.as_mut()) } #[allow(dead_code)] pub(crate) fn take_write_buf(&self) -> Bytes { self.write_buf.borrow_mut().split().freeze() } /// Add data to read buffer. pub fn extend_read_buf<T: AsRef<[u8]>>(&mut self, data: T) { self.read_buf.borrow_mut().extend_from_slice(data.as_ref()) } } impl io::Read for TestBuffer { fn read(&mut self, dst: &mut [u8]) -> Result<usize, io::Error> { if self.read_buf.borrow().is_empty() { if self.err.is_some() { Err(Rc::try_unwrap(self.err.take().unwrap()).unwrap()) } else { Err(io::Error::new(io::ErrorKind::WouldBlock, "")) } } else { let size = std::cmp::min(self.read_buf.borrow().len(), dst.len()); let b = self.read_buf.borrow_mut().split_to(size); dst[..size].copy_from_slice(&b); Ok(size) } } } impl io::Write for TestBuffer { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.write_buf.borrow_mut().extend(buf); Ok(buf.len()) } fn flush(&mut self) -> io::Result<()> { Ok(()) } } impl AsyncRead for TestBuffer { fn poll_read( self: Pin<&mut Self>, _: &mut Context<'_>, buf: &mut ReadBuf<'_>, ) -> Poll<io::Result<()>> { let dst = buf.initialize_unfilled(); let res = self.get_mut().read(dst).map(|n| buf.advance(n)); Poll::Ready(res) } } impl AsyncWrite for TestBuffer { fn poll_write( self: Pin<&mut Self>, _: &mut Context<'_>, buf: &[u8], ) -> Poll<io::Result<usize>> { Poll::Ready(self.get_mut().write(buf)) } fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> { Poll::Ready(Ok(())) } fn poll_shutdown(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> { Poll::Ready(Ok(())) } } /// Async I/O test buffer with ability to incrementally add to the read buffer. #[derive(Clone)] pub struct TestSeqBuffer(Rc<RefCell<TestSeqInner>>); impl TestSeqBuffer { /// Create new `TestBuffer` instance with initial read buffer. pub fn new<T>(data: T) -> Self where T: Into<BytesMut>, { Self(Rc::new(RefCell::new(TestSeqInner { read_buf: data.into(), write_buf: BytesMut::new(), err: None, }))) } /// Create new empty `TestBuffer` instance. pub fn empty() -> Self { Self::new(BytesMut::new()) } pub fn read_buf(&self) -> Ref<'_, BytesMut> { Ref::map(self.0.borrow(), |inner| &inner.read_buf) } pub fn write_buf(&self) -> Ref<'_, BytesMut> { Ref::map(self.0.borrow(), |inner| &inner.write_buf) } pub fn err(&self) -> Ref<'_, Option<io::Error>> { Ref::map(self.0.borrow(), |inner| &inner.err) } /// Add data to read buffer. pub fn extend_read_buf<T: AsRef<[u8]>>(&mut self, data: T) { self.0 .borrow_mut() .read_buf .extend_from_slice(data.as_ref()) } } pub struct TestSeqInner { read_buf: BytesMut, write_buf: BytesMut, err: Option<io::Error>, } impl io::Read for TestSeqBuffer { fn read(&mut self, dst: &mut [u8]) -> Result<usize, io::Error> { if self.0.borrow().read_buf.is_empty() { if self.0.borrow().err.is_some() { Err(self.0.borrow_mut().err.take().unwrap()) } else { Err(io::Error::new(io::ErrorKind::WouldBlock, "")) } } else { let size = std::cmp::min(self.0.borrow().read_buf.len(), dst.len()); let b = self.0.borrow_mut().read_buf.split_to(size); dst[..size].copy_from_slice(&b); Ok(size) } } } impl io::Write for TestSeqBuffer { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.borrow_mut().write_buf.extend(buf); Ok(buf.len()) } fn flush(&mut self) -> io::Result<()> { Ok(()) } } impl AsyncRead for TestSeqBuffer { fn poll_read( self: Pin<&mut Self>, _: &mut Context<'_>, buf: &mut ReadBuf<'_>, ) -> Poll<io::Result<()>> { let dst = buf.initialize_unfilled(); let r = self.get_mut().read(dst); match r { Ok(n) => { buf.advance(n); Poll::Ready(Ok(())) } Err(err) if err.kind() == io::ErrorKind::WouldBlock => Poll::Pending, Err(err) => Poll::Ready(Err(err)), } } } impl AsyncWrite for TestSeqBuffer { fn poll_write( self: Pin<&mut Self>, _: &mut Context<'_>, buf: &[u8], ) -> Poll<io::Result<usize>> { Poll::Ready(self.get_mut().write(buf)) } fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> { Poll::Ready(Ok(())) } fn poll_shutdown(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> { Poll::Ready(Ok(())) } }
use bitflags::bitflags; use bytes::{Bytes, BytesMut}; use bytestring::ByteString; use tokio_util::codec::{Decoder, Encoder}; use tracing::error; use super::{ frame::Parser, proto::{CloseReason, OpCode}, ProtocolError, }; /// A WebSocket message. #[derive(Debug, PartialEq, Eq)] pub enum Message { /// Text message. Text(ByteString), /// Binary message. Binary(Bytes), /// Continuation. Continuation(Item), /// Ping message. Ping(Bytes), /// Pong message. Pong(Bytes), /// Close message with optional reason. Close(Option<CloseReason>), /// No-op. Useful for low-level services. Nop, } /// A WebSocket frame. #[derive(Debug, PartialEq, Eq)] pub enum Frame { /// Text frame. Note that the codec does not validate UTF-8 encoding. Text(Bytes), /// Binary frame. Binary(Bytes), /// Continuation. Continuation(Item), /// Ping message. Ping(Bytes), /// Pong message. Pong(Bytes), /// Close message with optional reason. Close(Option<CloseReason>), } /// A WebSocket continuation item. #[derive(Debug, PartialEq, Eq)] pub enum Item { FirstText(Bytes), FirstBinary(Bytes), Continue(Bytes), Last(Bytes), } /// WebSocket protocol codec. #[derive(Debug, Clone)] pub struct Codec { flags: Flags, max_size: usize, } bitflags! { #[derive(Debug, Clone, Copy)] struct Flags: u8 { const SERVER = 0b0000_0001; const CONTINUATION = 0b0000_0010; const W_CONTINUATION = 0b0000_0100; } } impl Codec { /// Create new WebSocket frames decoder. pub const fn new() -> Codec { Codec { max_size: 65_536, flags: Flags::SERVER, } } /// Set max frame size. /// /// By default max size is set to 64KiB. #[must_use = "This returns the a new Codec, without modifying the original."] pub fn max_size(mut self, size: usize) -> Self { self.max_size = size; self } /// Set decoder to client mode. /// /// By default decoder works in server mode. #[must_use = "This returns the a new Codec, without modifying the original."] pub fn client_mode(mut self) -> Self { self.flags.remove(Flags::SERVER); self } } impl Default for Codec { fn default() -> Self { Self::new() } } impl Encoder<Message> for Codec { type Error = ProtocolError; fn encode(&mut self, item: Message, dst: &mut BytesMut) -> Result<(), Self::Error> { match item { Message::Text(txt) => Parser::write_message( dst, txt, OpCode::Text, true, !self.flags.contains(Flags::SERVER), ), Message::Binary(bin) => Parser::write_message( dst, bin, OpCode::Binary, true, !self.flags.contains(Flags::SERVER), ), Message::Ping(txt) => Parser::write_message( dst, txt, OpCode::Ping, true, !self.flags.contains(Flags::SERVER), ), Message::Pong(txt) => Parser::write_message( dst, txt, OpCode::Pong, true, !self.flags.contains(Flags::SERVER), ), Message::Close(reason) => { Parser::write_close(dst, reason, !self.flags.contains(Flags::SERVER)) } Message::Continuation(cont) => match cont { Item::FirstText(data) => { if self.flags.contains(Flags::W_CONTINUATION) { return Err(ProtocolError::ContinuationStarted); } else { self.flags.insert(Flags::W_CONTINUATION); Parser::write_message( dst, &data[..], OpCode::Text, false, !self.flags.contains(Flags::SERVER), ) } } Item::FirstBinary(data) => { if self.flags.contains(Flags::W_CONTINUATION) { return Err(ProtocolError::ContinuationStarted); } else { self.flags.insert(Flags::W_CONTINUATION); Parser::write_message( dst, &data[..], OpCode::Binary, false, !self.flags.contains(Flags::SERVER), ) } } Item::Continue(data) => { if self.flags.contains(Flags::W_CONTINUATION) { Parser::write_message( dst, &data[..], OpCode::Continue, false, !self.flags.contains(Flags::SERVER), ) } else { return Err(ProtocolError::ContinuationNotStarted); } } Item::Last(data) => { if self.flags.contains(Flags::W_CONTINUATION) { self.flags.remove(Flags::W_CONTINUATION); Parser::write_message( dst, &data[..], OpCode::Continue, true, !self.flags.contains(Flags::SERVER), ) } else { return Err(ProtocolError::ContinuationNotStarted); } } }, Message::Nop => {} } Ok(()) } } impl Decoder for Codec { type Item = Frame; type Error = ProtocolError; fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> { match Parser::parse(src, self.flags.contains(Flags::SERVER), self.max_size) { Ok(Some((finished, opcode, payload))) => { // continuation is not supported if !finished { return match opcode { OpCode::Continue => { if self.flags.contains(Flags::CONTINUATION) { Ok(Some(Frame::Continuation(Item::Continue( payload.map(|pl| pl.freeze()).unwrap_or_else(Bytes::new), )))) } else { Err(ProtocolError::ContinuationNotStarted) } } OpCode::Binary => { if !self.flags.contains(Flags::CONTINUATION) { self.flags.insert(Flags::CONTINUATION); Ok(Some(Frame::Continuation(Item::FirstBinary( payload.map(|pl| pl.freeze()).unwrap_or_else(Bytes::new), )))) } else { Err(ProtocolError::ContinuationStarted) } } OpCode::Text => { if !self.flags.contains(Flags::CONTINUATION) { self.flags.insert(Flags::CONTINUATION); Ok(Some(Frame::Continuation(Item::FirstText( payload.map(|pl| pl.freeze()).unwrap_or_else(Bytes::new), )))) } else { Err(ProtocolError::ContinuationStarted) } } _ => { error!("Unfinished fragment {:?}", opcode); Err(ProtocolError::ContinuationFragment(opcode)) } }; } match opcode { OpCode::Continue => { if self.flags.contains(Flags::CONTINUATION) { self.flags.remove(Flags::CONTINUATION); Ok(Some(Frame::Continuation(Item::Last( payload.map(|pl| pl.freeze()).unwrap_or_else(Bytes::new), )))) } else { Err(ProtocolError::ContinuationNotStarted) } } OpCode::Bad => Err(ProtocolError::BadOpCode), OpCode::Close => { if let Some(ref pl) = payload { let close_reason = Parser::parse_close_payload(pl); Ok(Some(Frame::Close(close_reason))) } else { Ok(Some(Frame::Close(None))) } } OpCode::Ping => Ok(Some(Frame::Ping( payload.map(|pl| pl.freeze()).unwrap_or_else(Bytes::new), ))), OpCode::Pong => Ok(Some(Frame::Pong( payload.map(|pl| pl.freeze()).unwrap_or_else(Bytes::new), ))), OpCode::Binary => Ok(Some(Frame::Binary( payload.map(|pl| pl.freeze()).unwrap_or_else(Bytes::new), ))), OpCode::Text => Ok(Some(Frame::Text( payload.map(|pl| pl.freeze()).unwrap_or_else(Bytes::new), ))), } } Ok(None) => Ok(None), Err(err) => Err(err), } } }
use std::{ future::Future, pin::Pin, task::{Context, Poll}, }; use actix_codec::{AsyncRead, AsyncWrite, Framed}; use actix_service::{IntoService, Service}; use pin_project_lite::pin_project; use super::{Codec, Frame, Message}; pin_project! { pub struct Dispatcher<S, T> where S: Service<Frame, Response = Message>, S: 'static, T: AsyncRead, T: AsyncWrite, { #[pin] inner: inner::Dispatcher<S, T, Codec, Message>, } } impl<S, T> Dispatcher<S, T> where T: AsyncRead + AsyncWrite, S: Service<Frame, Response = Message>, S::Future: 'static, S::Error: 'static, { pub fn new<F: IntoService<S, Frame>>(io: T, service: F) -> Self { Dispatcher { inner: inner::Dispatcher::new(Framed::new(io, Codec::new()), service), } } pub fn with<F: IntoService<S, Frame>>(framed: Framed<T, Codec>, service: F) -> Self { Dispatcher { inner: inner::Dispatcher::new(framed, service), } } } impl<S, T> Future for Dispatcher<S, T> where T: AsyncRead + AsyncWrite, S: Service<Frame, Response = Message>, S::Future: 'static, S::Error: 'static, { type Output = Result<(), inner::DispatcherError<S::Error, Codec, Message>>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { self.project().inner.poll(cx) } } /// Framed dispatcher service and related utilities. mod inner { // allow dead code since this mod was ripped from actix-utils #![allow(dead_code)] use core::{ fmt, future::Future, mem, pin::Pin, task::{Context, Poll}, }; use actix_codec::Framed; use actix_service::{IntoService, Service}; use futures_core::stream::Stream; use local_channel::mpsc; use pin_project_lite::pin_project; use tokio::io::{AsyncRead, AsyncWrite}; use tokio_util::codec::{Decoder, Encoder}; use tracing::debug; use crate::{body::BoxBody, Response}; /// Framed transport errors pub enum DispatcherError<E, U, I> where U: Encoder<I> + Decoder, { /// Inner service error. Service(E), /// Frame encoding error. Encoder(<U as Encoder<I>>::Error), /// Frame decoding error. Decoder(<U as Decoder>::Error), } impl<E, U, I> From<E> for DispatcherError<E, U, I> where U: Encoder<I> + Decoder, { fn from(err: E) -> Self { DispatcherError::Service(err) } } impl<E, U, I> fmt::Debug for DispatcherError<E, U, I> where E: fmt::Debug, U: Encoder<I> + Decoder, <U as Encoder<I>>::Error: fmt::Debug, <U as Decoder>::Error: fmt::Debug, { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { DispatcherError::Service(ref err) => { write!(fmt, "DispatcherError::Service({err:?})") } DispatcherError::Encoder(ref err) => { write!(fmt, "DispatcherError::Encoder({err:?})") } DispatcherError::Decoder(ref err) => { write!(fmt, "DispatcherError::Decoder({err:?})") } } } } impl<E, U, I> fmt::Display for DispatcherError<E, U, I> where E: fmt::Display, U: Encoder<I> + Decoder, <U as Encoder<I>>::Error: fmt::Debug, <U as Decoder>::Error: fmt::Debug, { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { DispatcherError::Service(ref err) => write!(fmt, "{err}"), DispatcherError::Encoder(ref err) => write!(fmt, "{err:?}"), DispatcherError::Decoder(ref err) => write!(fmt, "{err:?}"), } } } impl<E, U, I> From<DispatcherError<E, U, I>> for Response<BoxBody> where E: fmt::Debug + fmt::Display, U: Encoder<I> + Decoder, <U as Encoder<I>>::Error: fmt::Debug, <U as Decoder>::Error: fmt::Debug, { fn from(err: DispatcherError<E, U, I>) -> Self { Response::internal_server_error().set_body(BoxBody::new(err.to_string())) } } /// Message type wrapper for signalling end of message stream. pub enum Message<T> { /// Message item. Item(T), /// Signal from service to flush all messages and stop processing. Close, } pin_project! { /// A future that reads frames from a [`Framed`] object and passes them to a [`Service`]. pub struct Dispatcher<S, T, U, I> where S: Service<<U as Decoder>::Item, Response = I>, S::Error: 'static, S::Future: 'static, T: AsyncRead, T: AsyncWrite, U: Encoder<I>, U: Decoder, I: 'static, <U as Encoder<I>>::Error: fmt::Debug, { service: S, state: State<S, U, I>, #[pin] framed: Framed<T, U>, rx: mpsc::Receiver<Result<Message<I>, S::Error>>, tx: mpsc::Sender<Result<Message<I>, S::Error>>, } } enum State<S, U, I> where S: Service<<U as Decoder>::Item>, U: Encoder<I> + Decoder, { Processing, Error(DispatcherError<S::Error, U, I>), FramedError(DispatcherError<S::Error, U, I>), FlushAndStop, Stopping, } impl<S, U, I> State<S, U, I> where S: Service<<U as Decoder>::Item>, U: Encoder<I> + Decoder, { fn take_error(&mut self) -> DispatcherError<S::Error, U, I> { match mem::replace(self, State::Processing) { State::Error(err) => err, _ => panic!(), } } fn take_framed_error(&mut self) -> DispatcherError<S::Error, U, I> { match mem::replace(self, State::Processing) { State::FramedError(err) => err, _ => panic!(), } } } impl<S, T, U, I> Dispatcher<S, T, U, I> where S: Service<<U as Decoder>::Item, Response = I>, S::Error: 'static, S::Future: 'static, T: AsyncRead + AsyncWrite, U: Decoder + Encoder<I>, I: 'static, <U as Decoder>::Error: fmt::Debug, <U as Encoder<I>>::Error: fmt::Debug, { /// Create new `Dispatcher`. pub fn new<F>(framed: Framed<T, U>, service: F) -> Self where F: IntoService<S, <U as Decoder>::Item>, { let (tx, rx) = mpsc::channel(); Dispatcher { framed, rx, tx, service: service.into_service(), state: State::Processing, } } /// Construct new `Dispatcher` instance with customer `mpsc::Receiver` pub fn with_rx<F>( framed: Framed<T, U>, service: F, rx: mpsc::Receiver<Result<Message<I>, S::Error>>, ) -> Self where F: IntoService<S, <U as Decoder>::Item>, { let tx = rx.sender(); Dispatcher { framed, rx, tx, service: service.into_service(), state: State::Processing, } } /// Get sender handle. pub fn tx(&self) -> mpsc::Sender<Result<Message<I>, S::Error>> { self.tx.clone() } /// Get reference to a service wrapped by `Dispatcher` instance. pub fn service(&self) -> &S { &self.service } /// Get mutable reference to a service wrapped by `Dispatcher` instance. pub fn service_mut(&mut self) -> &mut S { &mut self.service } /// Get reference to a framed instance wrapped by `Dispatcher` instance. pub fn framed(&self) -> &Framed<T, U> { &self.framed } /// Get mutable reference to a framed instance wrapped by `Dispatcher` instance. pub fn framed_mut(&mut self) -> &mut Framed<T, U> { &mut self.framed } /// Read from framed object. fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> bool where S: Service<<U as Decoder>::Item, Response = I>, S::Error: 'static, S::Future: 'static, T: AsyncRead + AsyncWrite, U: Decoder + Encoder<I>, I: 'static, <U as Encoder<I>>::Error: fmt::Debug, { loop { let this = self.as_mut().project(); match this.service.poll_ready(cx) { Poll::Ready(Ok(_)) => { let item = match this.framed.next_item(cx) { Poll::Ready(Some(Ok(el))) => el, Poll::Ready(Some(Err(err))) => { *this.state = State::FramedError(DispatcherError::Decoder(err)); return true; } Poll::Pending => return false, Poll::Ready(None) => { *this.state = State::Stopping; return true; } }; let tx = this.tx.clone(); let fut = this.service.call(item); actix_rt::spawn(async move { let item = fut.await; let _ = tx.send(item.map(Message::Item)); }); } Poll::Pending => return false, Poll::Ready(Err(err)) => { *this.state = State::Error(DispatcherError::Service(err)); return true; } } } } /// Write to framed object. fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> bool where S: Service<<U as Decoder>::Item, Response = I>, S::Error: 'static, S::Future: 'static, T: AsyncRead + AsyncWrite, U: Decoder + Encoder<I>, I: 'static, <U as Encoder<I>>::Error: fmt::Debug, { loop { let mut this = self.as_mut().project(); while !this.framed.is_write_buf_full() { match Pin::new(&mut this.rx).poll_next(cx) { Poll::Ready(Some(Ok(Message::Item(msg)))) => { if let Err(err) = this.framed.as_mut().write(msg) { *this.state = State::FramedError(DispatcherError::Encoder(err)); return true; } } Poll::Ready(Some(Ok(Message::Close))) => { *this.state = State::FlushAndStop; return true; } Poll::Ready(Some(Err(err))) => { *this.state = State::Error(DispatcherError::Service(err)); return true; } Poll::Ready(None) | Poll::Pending => break, } } if !this.framed.is_write_buf_empty() { match this.framed.flush(cx) { Poll::Pending => break, Poll::Ready(Ok(_)) => {} Poll::Ready(Err(err)) => { debug!("Error sending data: {:?}", err); *this.state = State::FramedError(DispatcherError::Encoder(err)); return true; } } } else { break; } } false } } impl<S, T, U, I> Future for Dispatcher<S, T, U, I> where S: Service<<U as Decoder>::Item, Response = I>, S::Error: 'static, S::Future: 'static, T: AsyncRead + AsyncWrite, U: Decoder + Encoder<I>, I: 'static, <U as Encoder<I>>::Error: fmt::Debug, <U as Decoder>::Error: fmt::Debug, { type Output = Result<(), DispatcherError<S::Error, U, I>>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { loop { let this = self.as_mut().project(); return match this.state { State::Processing => { if self.as_mut().poll_read(cx) || self.as_mut().poll_write(cx) { continue; } else { Poll::Pending } } State::Error(_) => { // flush write buffer if !this.framed.is_write_buf_empty() && this.framed.flush(cx).is_pending() { return Poll::Pending; } Poll::Ready(Err(this.state.take_error())) } State::FlushAndStop => { if !this.framed.is_write_buf_empty() { this.framed.flush(cx).map(|res| { if let Err(err) = res { debug!("Error sending data: {:?}", err); } Ok(()) }) } else { Poll::Ready(Ok(())) } } State::FramedError(_) => Poll::Ready(Err(this.state.take_framed_error())), State::Stopping => Poll::Ready(Ok(())), }; } } } }
use std::cmp::min; use bytes::{Buf, BufMut, BytesMut}; use tracing::debug; use super::{ mask::apply_mask, proto::{CloseCode, CloseReason, OpCode}, ProtocolError, }; /// A struct representing a WebSocket frame. #[derive(Debug)] pub struct Parser; impl Parser { fn parse_metadata( src: &[u8], server: bool, ) -> Result<Option<(usize, bool, OpCode, usize, Option<[u8; 4]>)>, ProtocolError> { let chunk_len = src.len(); let mut idx = 2; if chunk_len < 2 { return Ok(None); } let first = src[0]; let second = src[1]; let finished = first & 0x80 != 0; // check masking let masked = second & 0x80 != 0; if !masked && server { return Err(ProtocolError::UnmaskedFrame); } else if masked && !server { return Err(ProtocolError::MaskedFrame); } // Op code let opcode = OpCode::from(first & 0x0F); if let OpCode::Bad = opcode { return Err(ProtocolError::InvalidOpcode(first & 0x0F)); } let len = second & 0x7F; let length = if len == 126 { if chunk_len < 4 { return Ok(None); } let len = usize::from(u16::from_be_bytes( TryFrom::try_from(&src[idx..idx + 2]).unwrap(), )); idx += 2; len } else if len == 127 { if chunk_len < 10 { return Ok(None); } let len = u64::from_be_bytes(TryFrom::try_from(&src[idx..idx + 8]).unwrap()); idx += 8; len as usize } else { len as usize }; let mask = if server { if chunk_len < idx + 4 { return Ok(None); } let mask = TryFrom::try_from(&src[idx..idx + 4]).unwrap(); idx += 4; Some(mask) } else { None }; Ok(Some((idx, finished, opcode, length, mask))) } /// Parse the input stream into a frame. pub fn parse( src: &mut BytesMut, server: bool, max_size: usize, ) -> Result<Option<(bool, OpCode, Option<BytesMut>)>, ProtocolError> { // try to parse ws frame metadata let (idx, finished, opcode, length, mask) = match Parser::parse_metadata(src, server)? { None => return Ok(None), Some(res) => res, }; // not enough data if src.len() < idx + length { let min_length = min(length, max_size); if src.capacity() < idx + min_length { src.reserve(idx + min_length - src.capacity()); } return Ok(None); } // remove prefix src.advance(idx); // check for max allowed size if length > max_size { // drop the payload src.advance(length); return Err(ProtocolError::Overflow); } // no need for body if length == 0 { return Ok(Some((finished, opcode, None))); } let mut data = src.split_to(length); // control frames must have length <= 125 match opcode { OpCode::Ping | OpCode::Pong if length > 125 => { return Err(ProtocolError::InvalidLength(length)); } OpCode::Close if length > 125 => { debug!("Received close frame with payload length exceeding 125. Morphing to protocol close frame."); return Ok(Some((true, OpCode::Close, None))); } _ => {} } // unmask if let Some(mask) = mask { apply_mask(&mut data, mask); } Ok(Some((finished, opcode, Some(data)))) } /// Parse the payload of a close frame. pub fn parse_close_payload(payload: &[u8]) -> Option<CloseReason> { if payload.len() >= 2 { let raw_code = u16::from_be_bytes(TryFrom::try_from(&payload[..2]).unwrap()); let code = CloseCode::from(raw_code); let description = if payload.len() > 2 { Some(String::from_utf8_lossy(&payload[2..]).into()) } else { None }; Some(CloseReason { code, description }) } else { None } } /// Generate binary representation pub fn write_message<B: AsRef<[u8]>>( dst: &mut BytesMut, pl: B, op: OpCode, fin: bool, mask: bool, ) { let payload = pl.as_ref(); let one: u8 = if fin { 0x80 | Into::<u8>::into(op) } else { op.into() }; let payload_len = payload.len(); let (two, p_len) = if mask { (0x80, payload_len + 4) } else { (0, payload_len) }; if payload_len < 126 { dst.reserve(p_len + 2); dst.put_slice(&[one, two | payload_len as u8]); } else if payload_len <= 65_535 { dst.reserve(p_len + 4); dst.put_slice(&[one, two | 126]); dst.put_u16(payload_len as u16); } else { dst.reserve(p_len + 10); dst.put_slice(&[one, two | 127]); dst.put_u64(payload_len as u64); }; if mask { let mask = rand::random::<[u8; 4]>(); dst.put_slice(mask.as_ref()); dst.put_slice(payload.as_ref()); let pos = dst.len() - payload_len; apply_mask(&mut dst[pos..], mask); } else { dst.put_slice(payload.as_ref()); } } /// Create a new Close control frame. #[inline] pub fn write_close(dst: &mut BytesMut, reason: Option<CloseReason>, mask: bool) { let payload = match reason { None => Vec::new(), Some(reason) => { let mut payload = Into::<u16>::into(reason.code).to_be_bytes().to_vec(); if let Some(description) = reason.description { payload.extend(description.as_bytes()); } payload } }; Parser::write_message(dst, payload, OpCode::Close, true, mask) } } #[cfg(test)] mod tests { use bytes::Bytes; use super::*; struct F { finished: bool, opcode: OpCode, payload: Bytes, } fn is_none(frm: &Result<Option<(bool, OpCode, Option<BytesMut>)>, ProtocolError>) -> bool { matches!(*frm, Ok(None)) } fn extract(frm: Result<Option<(bool, OpCode, Option<BytesMut>)>, ProtocolError>) -> F { match frm { Ok(Some((finished, opcode, payload))) => F { finished, opcode, payload: payload .map(|b| b.freeze()) .unwrap_or_else(|| Bytes::from("")), }, _ => unreachable!("error"), } } #[test] fn test_parse() { let mut buf = BytesMut::from(&[0b0000_0001u8, 0b0000_0001u8][..]); assert!(is_none(&Parser::parse(&mut buf, false, 1024))); let mut buf = BytesMut::from(&[0b0000_0001u8, 0b0000_0001u8][..]); buf.extend(b"1"); let frame = extract(Parser::parse(&mut buf, false, 1024)); assert!(!frame.finished); assert_eq!(frame.opcode, OpCode::Text); assert_eq!(frame.payload.as_ref(), &b"1"[..]); } #[test] fn test_parse_length0() { let mut buf = BytesMut::from(&[0b0000_0001u8, 0b0000_0000u8][..]); let frame = extract(Parser::parse(&mut buf, false, 1024)); assert!(!frame.finished); assert_eq!(frame.opcode, OpCode::Text); assert!(frame.payload.is_empty()); } #[test] fn test_parse_length2() { let mut buf = BytesMut::from(&[0b0000_0001u8, 126u8][..]); assert!(is_none(&Parser::parse(&mut buf, false, 1024))); let mut buf = BytesMut::from(&[0b0000_0001u8, 126u8][..]); buf.extend(&[0u8, 4u8][..]); buf.extend(b"1234"); let frame = extract(Parser::parse(&mut buf, false, 1024)); assert!(!frame.finished); assert_eq!(frame.opcode, OpCode::Text); assert_eq!(frame.payload.as_ref(), &b"1234"[..]); } #[test] fn test_parse_length4() { let mut buf = BytesMut::from(&[0b0000_0001u8, 127u8][..]); assert!(is_none(&Parser::parse(&mut buf, false, 1024))); let mut buf = BytesMut::from(&[0b0000_0001u8, 127u8][..]); buf.extend(&[0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 4u8][..]); buf.extend(b"1234"); let frame = extract(Parser::parse(&mut buf, false, 1024)); assert!(!frame.finished); assert_eq!(frame.opcode, OpCode::Text); assert_eq!(frame.payload.as_ref(), &b"1234"[..]); } #[test] fn test_parse_frame_mask() { let mut buf = BytesMut::from(&[0b0000_0001u8, 0b1000_0001u8][..]); buf.extend(b"0001"); buf.extend(b"1"); assert!(Parser::parse(&mut buf, false, 1024).is_err()); let frame = extract(Parser::parse(&mut buf, true, 1024)); assert!(!frame.finished); assert_eq!(frame.opcode, OpCode::Text); assert_eq!(frame.payload, Bytes::from(vec![1u8])); } #[test] fn test_parse_frame_no_mask() { let mut buf = BytesMut::from(&[0b0000_0001u8, 0b0000_0001u8][..]); buf.extend([1u8]); assert!(Parser::parse(&mut buf, true, 1024).is_err()); let frame = extract(Parser::parse(&mut buf, false, 1024)); assert!(!frame.finished); assert_eq!(frame.opcode, OpCode::Text); assert_eq!(frame.payload, Bytes::from(vec![1u8])); } #[test] fn test_parse_frame_max_size() { let mut buf = BytesMut::from(&[0b0000_0001u8, 0b0000_0010u8][..]); buf.extend([1u8, 1u8]); assert!(Parser::parse(&mut buf, true, 1).is_err()); if let Err(ProtocolError::Overflow) = Parser::parse(&mut buf, false, 0) { } else { unreachable!("error"); } } #[test] fn test_parse_frame_max_size_recoverability() { let mut buf = BytesMut::new(); // The first text frame with length == 2, payload doesn't matter. buf.extend([0b0000_0001u8, 0b0000_0010u8, 0b0000_0000u8, 0b0000_0000u8]); // Next binary frame with length == 2 and payload == `[0x1111_1111u8, 0x1111_1111u8]`. buf.extend([0b0000_0010u8, 0b0000_0010u8, 0b1111_1111u8, 0b1111_1111u8]); assert_eq!(buf.len(), 8); assert!(matches!( Parser::parse(&mut buf, false, 1), Err(ProtocolError::Overflow) )); assert_eq!(buf.len(), 4); let frame = extract(Parser::parse(&mut buf, false, 2)); assert!(!frame.finished); assert_eq!(frame.opcode, OpCode::Binary); assert_eq!( frame.payload, Bytes::from(vec![0b1111_1111u8, 0b1111_1111u8]) ); assert_eq!(buf.len(), 0); } #[test] fn test_ping_frame() { let mut buf = BytesMut::new(); Parser::write_message(&mut buf, Vec::from("data"), OpCode::Ping, true, false); let mut v = vec![137u8, 4u8]; v.extend(b"data"); assert_eq!(&buf[..], &v[..]); } #[test] fn test_pong_frame() { let mut buf = BytesMut::new(); Parser::write_message(&mut buf, Vec::from("data"), OpCode::Pong, true, false); let mut v = vec![138u8, 4u8]; v.extend(b"data"); assert_eq!(&buf[..], &v[..]); } #[test] fn test_close_frame() { let mut buf = BytesMut::new(); let reason = (CloseCode::Normal, "data"); Parser::write_close(&mut buf, Some(reason.into()), false); let mut v = vec![136u8, 6u8, 3u8, 232u8]; v.extend(b"data"); assert_eq!(&buf[..], &v[..]); } #[test] fn test_empty_close_frame() { let mut buf = BytesMut::new(); Parser::write_close(&mut buf, None, false); assert_eq!(&buf[..], &vec![0x88, 0x00][..]); } }
//! This is code from [Tungstenite project](https://github.com/snapview/tungstenite-rs) /// Mask/unmask a frame. #[inline] pub fn apply_mask(buf: &mut [u8], mask: [u8; 4]) { apply_mask_fast32(buf, mask) } /// A safe unoptimized mask application. #[inline] fn apply_mask_fallback(buf: &mut [u8], mask: [u8; 4]) { for (i, byte) in buf.iter_mut().enumerate() { *byte ^= mask[i & 3]; } } /// Faster version of `apply_mask()` which operates on 4-byte blocks. #[inline] pub fn apply_mask_fast32(buf: &mut [u8], mask: [u8; 4]) { let mask_u32 = u32::from_ne_bytes(mask); // SAFETY: // // buf is a valid slice borrowed mutably from bytes::BytesMut. // // un aligned prefix and suffix would be mask/unmask per byte. // proper aligned middle slice goes into fast path and operates on 4-byte blocks. let (prefix, words, suffix) = unsafe { buf.align_to_mut::<u32>() }; apply_mask_fallback(prefix, mask); let head = prefix.len() & 3; let mask_u32 = if head > 0 { if cfg!(target_endian = "big") { mask_u32.rotate_left(8 * head as u32) } else { mask_u32.rotate_right(8 * head as u32) } } else { mask_u32 }; for word in words.iter_mut() { *word ^= mask_u32; } apply_mask_fallback(suffix, mask_u32.to_ne_bytes()); } #[cfg(test)] mod tests { use super::*; #[test] fn test_apply_mask() { let mask = [0x6d, 0xb6, 0xb2, 0x80]; let unmasked = [ 0xf3, 0x00, 0x01, 0x02, 0x03, 0x80, 0x81, 0x82, 0xff, 0xfe, 0x00, 0x17, 0x74, 0xf9, 0x12, 0x03, ]; for data_len in 0..=unmasked.len() { let unmasked = &unmasked[0..data_len]; // Check masking with different alignment. for off in 0..=3 { if unmasked.len() < off { continue; } let mut masked = unmasked.to_vec(); apply_mask_fallback(&mut masked[off..], mask); let mut masked_fast = unmasked.to_vec(); apply_mask_fast32(&mut masked_fast[off..], mask); assert_eq!(masked, masked_fast); } } } }
//! WebSocket protocol implementation. //! //! To setup a WebSocket, first perform the WebSocket handshake then on success convert `Payload` into a //! `WsStream` stream and then use `WsWriter` to communicate with the peer. use std::io; use derive_more::{Display, Error, From}; use http::{header, Method, StatusCode}; use crate::{body::BoxBody, header::HeaderValue, RequestHead, Response, ResponseBuilder}; mod codec; mod dispatcher; mod frame; mod mask; mod proto; pub use self::{ codec::{Codec, Frame, Item, Message}, dispatcher::Dispatcher, frame::Parser, proto::{hash_key, CloseCode, CloseReason, OpCode}, }; /// WebSocket protocol errors. #[derive(Debug, Display, Error, From)] pub enum ProtocolError { /// Received an unmasked frame from client. #[display("received an unmasked frame from client")] UnmaskedFrame, /// Received a masked frame from server. #[display("received a masked frame from server")] MaskedFrame, /// Encountered invalid opcode. #[display("invalid opcode ({})", _0)] InvalidOpcode(#[error(not(source))] u8), /// Invalid control frame length #[display("invalid control frame length ({})", _0)] InvalidLength(#[error(not(source))] usize), /// Bad opcode. #[display("bad opcode")] BadOpCode, /// A payload reached size limit. #[display("payload reached size limit")] Overflow, /// Continuation has not started. #[display("continuation has not started")] ContinuationNotStarted, /// Received new continuation but it is already started. #[display("received new continuation but it has already started")] ContinuationStarted, /// Unknown continuation fragment. #[display("unknown continuation fragment: {}", _0)] ContinuationFragment(#[error(not(source))] OpCode), /// I/O error. #[display("I/O error: {}", _0)] Io(io::Error), } /// WebSocket handshake errors #[derive(Debug, Clone, Copy, PartialEq, Eq, Display, Error)] pub enum HandshakeError { /// Only get method is allowed. #[display("method not allowed")] GetMethodRequired, /// Upgrade header if not set to WebSocket. #[display("WebSocket upgrade is expected")] NoWebsocketUpgrade, /// Connection header is not set to upgrade. #[display("connection upgrade is expected")] NoConnectionUpgrade, /// WebSocket version header is not set. #[display("WebSocket version header is required")] NoVersionHeader, /// Unsupported WebSocket version. #[display("unsupported WebSocket version")] UnsupportedVersion, /// WebSocket key is not set or wrong. #[display("unknown WebSocket key")] BadWebsocketKey, } impl From<HandshakeError> for Response<BoxBody> { fn from(err: HandshakeError) -> Self { match err { HandshakeError::GetMethodRequired => { let mut res = Response::new(StatusCode::METHOD_NOT_ALLOWED); #[allow(clippy::declare_interior_mutable_const)] const HV_GET: HeaderValue = HeaderValue::from_static("GET"); res.headers_mut().insert(header::ALLOW, HV_GET); res } HandshakeError::NoWebsocketUpgrade => { let mut res = Response::bad_request(); res.head_mut().reason = Some("No WebSocket Upgrade header found"); res } HandshakeError::NoConnectionUpgrade => { let mut res = Response::bad_request(); res.head_mut().reason = Some("No Connection upgrade"); res } HandshakeError::NoVersionHeader => { let mut res = Response::bad_request(); res.head_mut().reason = Some("WebSocket version header is required"); res } HandshakeError::UnsupportedVersion => { let mut res = Response::bad_request(); res.head_mut().reason = Some("Unsupported WebSocket version"); res } HandshakeError::BadWebsocketKey => { let mut res = Response::bad_request(); res.head_mut().reason = Some("Handshake error"); res } } } } impl From<&HandshakeError> for Response<BoxBody> { fn from(err: &HandshakeError) -> Self { (*err).into() } } /// Verify WebSocket handshake request and create handshake response. pub fn handshake(req: &RequestHead) -> Result<ResponseBuilder, HandshakeError> { verify_handshake(req)?; Ok(handshake_response(req)) } /// Verify WebSocket handshake request. pub fn verify_handshake(req: &RequestHead) -> Result<(), HandshakeError> { // WebSocket accepts only GET if req.method != Method::GET { return Err(HandshakeError::GetMethodRequired); } // Check for "UPGRADE" to WebSocket header let has_hdr = if let Some(hdr) = req.headers().get(header::UPGRADE) { if let Ok(s) = hdr.to_str() { s.to_ascii_lowercase().contains("websocket") } else { false } } else { false }; if !has_hdr { return Err(HandshakeError::NoWebsocketUpgrade); } // Upgrade connection if !req.upgrade() { return Err(HandshakeError::NoConnectionUpgrade); } // check supported version if !req.headers().contains_key(header::SEC_WEBSOCKET_VERSION) { return Err(HandshakeError::NoVersionHeader); } let supported_ver = { if let Some(hdr) = req.headers().get(header::SEC_WEBSOCKET_VERSION) { hdr == "13" || hdr == "8" || hdr == "7" } else { false } }; if !supported_ver { return Err(HandshakeError::UnsupportedVersion); } // check client handshake for validity if !req.headers().contains_key(header::SEC_WEBSOCKET_KEY) { return Err(HandshakeError::BadWebsocketKey); } Ok(()) } /// Create WebSocket handshake response. /// /// This function returns handshake `Response`, ready to send to peer. pub fn handshake_response(req: &RequestHead) -> ResponseBuilder { let key = { let key = req.headers().get(header::SEC_WEBSOCKET_KEY).unwrap(); proto::hash_key(key.as_ref()) }; Response::build(StatusCode::SWITCHING_PROTOCOLS) .upgrade("websocket") .insert_header(( header::SEC_WEBSOCKET_ACCEPT, // key is known to be header value safe ascii HeaderValue::from_bytes(&key).unwrap(), )) .take() } #[cfg(test)] mod tests { use super::*; use crate::{header, test::TestRequest}; #[test] fn test_handshake() { let req = TestRequest::default().method(Method::POST).finish(); assert_eq!( HandshakeError::GetMethodRequired, verify_handshake(req.head()).unwrap_err(), ); let req = TestRequest::default().finish(); assert_eq!( HandshakeError::NoWebsocketUpgrade, verify_handshake(req.head()).unwrap_err(), ); let req = TestRequest::default() .insert_header((header::UPGRADE, header::HeaderValue::from_static("test"))) .finish(); assert_eq!( HandshakeError::NoWebsocketUpgrade, verify_handshake(req.head()).unwrap_err(), ); let req = TestRequest::default() .insert_header(( header::UPGRADE, header::HeaderValue::from_static("websocket"), )) .finish(); assert_eq!( HandshakeError::NoConnectionUpgrade, verify_handshake(req.head()).unwrap_err(), ); let req = TestRequest::default() .insert_header(( header::UPGRADE, header::HeaderValue::from_static("websocket"), )) .insert_header(( header::CONNECTION, header::HeaderValue::from_static("upgrade"), )) .finish(); assert_eq!( HandshakeError::NoVersionHeader, verify_handshake(req.head()).unwrap_err(), ); let req = TestRequest::default() .insert_header(( header::UPGRADE, header::HeaderValue::from_static("websocket"), )) .insert_header(( header::CONNECTION, header::HeaderValue::from_static("upgrade"), )) .insert_header(( header::SEC_WEBSOCKET_VERSION, header::HeaderValue::from_static("5"), )) .finish(); assert_eq!( HandshakeError::UnsupportedVersion, verify_handshake(req.head()).unwrap_err(), ); let req = TestRequest::default() .insert_header(( header::UPGRADE, header::HeaderValue::from_static("websocket"), )) .insert_header(( header::CONNECTION, header::HeaderValue::from_static("upgrade"), )) .insert_header(( header::SEC_WEBSOCKET_VERSION, header::HeaderValue::from_static("13"), )) .finish(); assert_eq!( HandshakeError::BadWebsocketKey, verify_handshake(req.head()).unwrap_err(), ); let req = TestRequest::default() .insert_header(( header::UPGRADE, header::HeaderValue::from_static("websocket"), )) .insert_header(( header::CONNECTION, header::HeaderValue::from_static("upgrade"), )) .insert_header(( header::SEC_WEBSOCKET_VERSION, header::HeaderValue::from_static("13"), )) .insert_header(( header::SEC_WEBSOCKET_KEY, header::HeaderValue::from_static("13"), )) .finish(); assert_eq!( StatusCode::SWITCHING_PROTOCOLS, handshake_response(req.head()).finish().status() ); } #[test] fn test_ws_error_http_response() { let resp: Response<BoxBody> = HandshakeError::GetMethodRequired.into(); assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED); let resp: Response<BoxBody> = HandshakeError::NoWebsocketUpgrade.into(); assert_eq!(resp.status(), StatusCode::BAD_REQUEST); let resp: Response<BoxBody> = HandshakeError::NoConnectionUpgrade.into(); assert_eq!(resp.status(), StatusCode::BAD_REQUEST); let resp: Response<BoxBody> = HandshakeError::NoVersionHeader.into(); assert_eq!(resp.status(), StatusCode::BAD_REQUEST); let resp: Response<BoxBody> = HandshakeError::UnsupportedVersion.into(); assert_eq!(resp.status(), StatusCode::BAD_REQUEST); let resp: Response<BoxBody> = HandshakeError::BadWebsocketKey.into(); assert_eq!(resp.status(), StatusCode::BAD_REQUEST); } }
use std::fmt; use base64::prelude::*; use tracing::error; /// Operation codes defined in [RFC 6455 §11.8]. /// /// [RFC 6455]: https://datatracker.ietf.org/doc/html/rfc6455#section-11.8 #[derive(Debug, Eq, PartialEq, Clone, Copy)] pub enum OpCode { /// Indicates a continuation frame of a fragmented message. Continue, /// Indicates a text data frame. Text, /// Indicates a binary data frame. Binary, /// Indicates a close control frame. Close, /// Indicates a ping control frame. Ping, /// Indicates a pong control frame. Pong, /// Indicates an invalid opcode was received. Bad, } impl fmt::Display for OpCode { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { use OpCode::*; match self { Continue => write!(f, "CONTINUE"), Text => write!(f, "TEXT"), Binary => write!(f, "BINARY"), Close => write!(f, "CLOSE"), Ping => write!(f, "PING"), Pong => write!(f, "PONG"), Bad => write!(f, "BAD"), } } } impl From<OpCode> for u8 { fn from(op: OpCode) -> u8 { use self::OpCode::*; match op { Continue => 0, Text => 1, Binary => 2, Close => 8, Ping => 9, Pong => 10, Bad => { error!("Attempted to convert invalid opcode to u8. This is a bug."); 8 // if this somehow happens, a close frame will help us tear down quickly } } } } impl From<u8> for OpCode { fn from(byte: u8) -> OpCode { use self::OpCode::*; match byte { 0 => Continue, 1 => Text, 2 => Binary, 8 => Close, 9 => Ping, 10 => Pong, _ => Bad, } } } /// Status code used to indicate why an endpoint is closing the WebSocket connection. #[derive(Debug, Eq, PartialEq, Clone, Copy)] pub enum CloseCode { /// Indicates a normal closure, meaning that the purpose for which the connection was /// established has been fulfilled. Normal, /// Indicates that an endpoint is "going away", such as a server going down or a browser having /// navigated away from a page. Away, /// Indicates that an endpoint is terminating the connection due to a protocol error. Protocol, /// Indicates that an endpoint is terminating the connection because it has received a type of /// data it cannot accept (e.g., an endpoint that understands only text data MAY send this if it /// receives a binary message). Unsupported, /// Indicates an abnormal closure. If the abnormal closure was due to an error, this close code /// will not be used. Instead, the `on_error` method of the handler will be called with /// the error. However, if the connection is simply dropped, without an error, this close code /// will be sent to the handler. Abnormal, /// Indicates that an endpoint is terminating the connection because it has received data within /// a message that was not consistent with the type of the message (e.g., non-UTF-8 \[RFC 3629\] /// data within a text message). Invalid, /// Indicates that an endpoint is terminating the connection because it has received a message /// that violates its policy. This is a generic status code that can be returned when there is /// no other more suitable status code (e.g., Unsupported or Size) or if there is a need to hide /// specific details about the policy. Policy, /// Indicates that an endpoint is terminating the connection because it has received a message /// that is too big for it to process. Size, /// Indicates that an endpoint (client) is terminating the connection because it has expected /// the server to negotiate one or more extension, but the server didn't return them in the /// response message of the WebSocket handshake. The list of extensions that are needed should /// be given as the reason for closing. Note that this status code is not used by the server, /// because it can fail the WebSocket handshake instead. Extension, /// Indicates that a server is terminating the connection because it encountered an unexpected /// condition that prevented it from fulfilling the request. Error, /// Indicates that the server is restarting. A client may choose to reconnect, and if it does, /// it should use a randomized delay of 5-30 seconds between attempts. Restart, /// Indicates that the server is overloaded and the client should either connect to a different /// IP (when multiple targets exist), or reconnect to the same IP when a user has performed /// an action. Again, #[doc(hidden)] Tls, #[doc(hidden)] Other(u16), } impl From<CloseCode> for u16 { fn from(code: CloseCode) -> u16 { use self::CloseCode::*; match code { Normal => 1000, Away => 1001, Protocol => 1002, Unsupported => 1003, Abnormal => 1006, Invalid => 1007, Policy => 1008, Size => 1009, Extension => 1010, Error => 1011, Restart => 1012, Again => 1013, Tls => 1015, Other(code) => code, } } } impl From<u16> for CloseCode { fn from(code: u16) -> CloseCode { use self::CloseCode::*; match code { 1000 => Normal, 1001 => Away, 1002 => Protocol, 1003 => Unsupported, 1006 => Abnormal, 1007 => Invalid, 1008 => Policy, 1009 => Size, 1010 => Extension, 1011 => Error, 1012 => Restart, 1013 => Again, 1015 => Tls, _ => Other(code), } } } #[derive(Debug, Eq, PartialEq, Clone)] /// Reason for closing the connection pub struct CloseReason { /// Exit code pub code: CloseCode, /// Optional description of the exit code pub description: Option<String>, } impl From<CloseCode> for CloseReason { fn from(code: CloseCode) -> Self { CloseReason { code, description: None, } } } impl<T: Into<String>> From<(CloseCode, T)> for CloseReason { fn from(info: (CloseCode, T)) -> Self { CloseReason { code: info.0, description: Some(info.1.into()), } } } /// The WebSocket GUID as stated in the spec. /// See <https://datatracker.ietf.org/doc/html/rfc6455#section-1.3>. static WS_GUID: &[u8] = b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; /// Hashes the `Sec-WebSocket-Key` header according to the WebSocket spec. /// /// Result is a Base64 encoded byte array. `base64(sha1(input))` is always 28 bytes. pub fn hash_key(key: &[u8]) -> [u8; 28] { let hash = { use sha1::Digest as _; let mut hasher = sha1::Sha1::new(); hasher.update(key); hasher.update(WS_GUID); hasher.finalize() }; let mut hash_b64 = [0; 28]; let n = BASE64_STANDARD.encode_slice(hash, &mut hash_b64).unwrap(); assert_eq!(n, 28); hash_b64 } #[cfg(test)] mod test { #![allow(unused_imports, unused_variables, dead_code)] use super::*; macro_rules! opcode_into { ($from:expr => $opcode:pat) => { match OpCode::from($from) { e @ $opcode => {} e => unreachable!("{:?}", e), } }; } macro_rules! opcode_from { ($from:expr => $opcode:pat) => { let res: u8 = $from.into(); match res { e @ $opcode => {} e => unreachable!("{:?}", e), } }; } #[test] fn test_to_opcode() { opcode_into!(0 => OpCode::Continue); opcode_into!(1 => OpCode::Text); opcode_into!(2 => OpCode::Binary); opcode_into!(8 => OpCode::Close); opcode_into!(9 => OpCode::Ping); opcode_into!(10 => OpCode::Pong); opcode_into!(99 => OpCode::Bad); } #[test] fn test_from_opcode() { opcode_from!(OpCode::Continue => 0); opcode_from!(OpCode::Text => 1); opcode_from!(OpCode::Binary => 2); opcode_from!(OpCode::Close => 8); opcode_from!(OpCode::Ping => 9); opcode_from!(OpCode::Pong => 10); } #[test] #[should_panic] fn test_from_opcode_debug() { opcode_from!(OpCode::Bad => 99); } #[test] fn test_from_opcode_display() { assert_eq!(format!("{}", OpCode::Continue), "CONTINUE"); assert_eq!(format!("{}", OpCode::Text), "TEXT"); assert_eq!(format!("{}", OpCode::Binary), "BINARY"); assert_eq!(format!("{}", OpCode::Close), "CLOSE"); assert_eq!(format!("{}", OpCode::Ping), "PING"); assert_eq!(format!("{}", OpCode::Pong), "PONG"); assert_eq!(format!("{}", OpCode::Bad), "BAD"); } #[test] fn test_hash_key() { let hash = hash_key(b"hello actix-web"); assert_eq!(&hash, b"cR1dlyUUJKp0s/Bel25u5TgvC3E="); } #[test] fn close_code_from_u16() { assert_eq!(CloseCode::from(1000u16), CloseCode::Normal); assert_eq!(CloseCode::from(1001u16), CloseCode::Away); assert_eq!(CloseCode::from(1002u16), CloseCode::Protocol); assert_eq!(CloseCode::from(1003u16), CloseCode::Unsupported); assert_eq!(CloseCode::from(1006u16), CloseCode::Abnormal); assert_eq!(CloseCode::from(1007u16), CloseCode::Invalid); assert_eq!(CloseCode::from(1008u16), CloseCode::Policy); assert_eq!(CloseCode::from(1009u16), CloseCode::Size); assert_eq!(CloseCode::from(1010u16), CloseCode::Extension); assert_eq!(CloseCode::from(1011u16), CloseCode::Error); assert_eq!(CloseCode::from(1012u16), CloseCode::Restart); assert_eq!(CloseCode::from(1013u16), CloseCode::Again); assert_eq!(CloseCode::from(1015u16), CloseCode::Tls); assert_eq!(CloseCode::from(2000u16), CloseCode::Other(2000)); } #[test] fn close_code_into_u16() { assert_eq!(1000u16, Into::<u16>::into(CloseCode::Normal)); assert_eq!(1001u16, Into::<u16>::into(CloseCode::Away)); assert_eq!(1002u16, Into::<u16>::into(CloseCode::Protocol)); assert_eq!(1003u16, Into::<u16>::into(CloseCode::Unsupported)); assert_eq!(1006u16, Into::<u16>::into(CloseCode::Abnormal)); assert_eq!(1007u16, Into::<u16>::into(CloseCode::Invalid)); assert_eq!(1008u16, Into::<u16>::into(CloseCode::Policy)); assert_eq!(1009u16, Into::<u16>::into(CloseCode::Size)); assert_eq!(1010u16, Into::<u16>::into(CloseCode::Extension)); assert_eq!(1011u16, Into::<u16>::into(CloseCode::Error)); assert_eq!(1012u16, Into::<u16>::into(CloseCode::Restart)); assert_eq!(1013u16, Into::<u16>::into(CloseCode::Again)); assert_eq!(1015u16, Into::<u16>::into(CloseCode::Tls)); assert_eq!(2000u16, Into::<u16>::into(CloseCode::Other(2000))); } }
use std::convert::Infallible; use actix_http::{body::BoxBody, HttpMessage, HttpService, Request, Response, StatusCode}; use actix_http_test::test_server; use actix_service::ServiceFactoryExt; use actix_utils::future; use bytes::Bytes; use derive_more::{Display, Error}; use futures_util::StreamExt as _; const STR: &str = "Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World"; #[actix_rt::test] async fn h1_v2() { let srv = test_server(move || { HttpService::build() .finish(|_| future::ok::<_, Infallible>(Response::ok().set_body(STR))) .tcp() }) .await; let response = srv.get("/").send().await.unwrap(); assert!(response.status().is_success()); let request = srv.get("/").insert_header(("x-test", "111")).send(); let mut response = request.await.unwrap(); assert!(response.status().is_success()); // read response let bytes = response.body().await.unwrap(); assert_eq!(bytes, Bytes::from_static(STR.as_ref())); let mut response = srv.post("/").send().await.unwrap(); assert!(response.status().is_success()); // read response let bytes = response.body().await.unwrap(); assert_eq!(bytes, Bytes::from_static(STR.as_ref())); } #[actix_rt::test] async fn connection_close() { let srv = test_server(move || { HttpService::build() .finish(|_| future::ok::<_, Infallible>(Response::ok().set_body(STR))) .tcp() .map(|_| ()) }) .await; let response = srv.get("/").force_close().send().await.unwrap(); assert!(response.status().is_success()); } #[actix_rt::test] async fn with_query_parameter() { let srv = test_server(move || { HttpService::build() .finish(|req: Request| async move { if req.uri().query().unwrap().contains("qp=") { Ok::<_, Infallible>(Response::ok()) } else { Ok(Response::bad_request()) } }) .tcp() .map(|_| ()) }) .await; let request = srv.request(http::Method::GET, srv.url("/?qp=5")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); } #[derive(Debug, Display, Error)] #[display("expect failed")] struct ExpectFailed; impl From<ExpectFailed> for Response<BoxBody> { fn from(_: ExpectFailed) -> Self { Response::new(StatusCode::EXPECTATION_FAILED) } } #[actix_rt::test] async fn h1_expect() { let srv = test_server(move || { HttpService::build() .expect(|req: Request| async { if req.headers().contains_key("AUTH") { Ok(req) } else { Err(ExpectFailed) } }) .h1(|req: Request| async move { let (_, mut body) = req.into_parts(); let mut buf = Vec::new(); while let Some(Ok(chunk)) = body.next().await { buf.extend_from_slice(&chunk); } let str = std::str::from_utf8(&buf).unwrap(); assert_eq!(str, "expect body"); Ok::<_, Infallible>(Response::ok()) }) .tcp() }) .await; // test expect without payload. let request = srv .request(http::Method::GET, srv.url("/")) .insert_header(("Expect", "100-continue")); let response = request.send().await; assert!(response.is_err()); // test expect would fail to continue let request = srv .request(http::Method::GET, srv.url("/")) .insert_header(("Expect", "100-continue")); let response = request.send_body("expect body").await.unwrap(); assert_eq!(response.status(), StatusCode::EXPECTATION_FAILED); // test expect would continue let request = srv .request(http::Method::GET, srv.url("/")) .insert_header(("Expect", "100-continue")) .insert_header(("AUTH", "996")); let response = request.send_body("expect body").await.unwrap(); assert!(response.status().is_success()); }
use std::{io, time::Duration}; use actix_http::{error::Error, HttpService, Response}; use actix_server::Server; use tokio::io::AsyncWriteExt; #[actix_rt::test] async fn h2_ping_pong() -> io::Result<()> { let (tx, rx) = std::sync::mpsc::sync_channel(1); let lst = std::net::TcpListener::bind("127.0.0.1:0")?; let addr = lst.local_addr().unwrap(); let join = std::thread::spawn(move || { actix_rt::System::new().block_on(async move { let srv = Server::build() .disable_signals() .workers(1) .listen("h2_ping_pong", lst, || { HttpService::build() .keep_alive(Duration::from_secs(3)) .h2(|_| async { Ok::<_, Error>(Response::ok()) }) .tcp() })? .run(); tx.send(srv.handle()).unwrap(); srv.await }) }); let handle = rx.recv().unwrap(); let (sync_tx, rx) = std::sync::mpsc::sync_channel(1); // use a separate thread for h2 client so it can be blocked. std::thread::spawn(move || { tokio::runtime::Builder::new_current_thread() .enable_all() .build() .unwrap() .block_on(async move { let stream = tokio::net::TcpStream::connect(addr).await.unwrap(); let (mut tx, conn) = h2::client::handshake(stream).await.unwrap(); tokio::spawn(async move { conn.await.unwrap() }); let (res, _) = tx.send_request(::http::Request::new(()), true).unwrap(); let res = res.await.unwrap(); assert_eq!(res.status().as_u16(), 200); sync_tx.send(()).unwrap(); // intentionally block the client thread so it can not answer ping pong. std::thread::sleep(std::time::Duration::from_secs(1000)); }) }); rx.recv().unwrap(); let now = std::time::Instant::now(); // stop server gracefully. this step would take up to 30 seconds. handle.stop(true).await; // join server thread. only when connection are all gone this step would finish. join.join().unwrap()?; // check the time used for join server thread so it's known that the server shutdown // is from keep alive and not server graceful shutdown timeout. assert!(now.elapsed() < std::time::Duration::from_secs(30)); Ok(()) } #[actix_rt::test] async fn h2_handshake_timeout() -> io::Result<()> { let (tx, rx) = std::sync::mpsc::sync_channel(1); let lst = std::net::TcpListener::bind("127.0.0.1:0")?; let addr = lst.local_addr().unwrap(); let join = std::thread::spawn(move || { actix_rt::System::new().block_on(async move { let srv = Server::build() .disable_signals() .workers(1) .listen("h2_ping_pong", lst, || { HttpService::build() .keep_alive(Duration::from_secs(30)) // set first request timeout to 5 seconds. // this is the timeout used for http2 handshake. .client_request_timeout(Duration::from_secs(5)) .h2(|_| async { Ok::<_, Error>(Response::ok()) }) .tcp() })? .run(); tx.send(srv.handle()).unwrap(); srv.await }) }); let handle = rx.recv().unwrap(); let (sync_tx, rx) = std::sync::mpsc::sync_channel(1); // use a separate thread for tcp client so it can be blocked. std::thread::spawn(move || { tokio::runtime::Builder::new_current_thread() .enable_all() .build() .unwrap() .block_on(async move { let mut stream = tokio::net::TcpStream::connect(addr).await.unwrap(); // do not send the last new line intentionally. // This should hang the server handshake let malicious_buf = b"PRI * HTTP/2.0\r\n\r\nSM\r\n"; stream.write_all(malicious_buf).await.unwrap(); stream.flush().await.unwrap(); sync_tx.send(()).unwrap(); // intentionally block the client thread so it sit idle and not do handshake. std::thread::sleep(std::time::Duration::from_secs(1000)); drop(stream) }) }); rx.recv().unwrap(); let now = std::time::Instant::now(); // stop server gracefully. this step would take up to 30 seconds. handle.stop(true).await; // join server thread. only when connection are all gone this step would finish. join.join().unwrap()?; // check the time used for join server thread so it's known that the server shutdown // is from handshake timeout and not server graceful shutdown timeout. assert!(now.elapsed() < std::time::Duration::from_secs(30)); Ok(()) }
#![cfg(feature = "openssl")] extern crate tls_openssl as openssl; use std::{convert::Infallible, io, time::Duration}; use actix_http::{ body::{BodyStream, BoxBody, SizedStream}, error::PayloadError, header::{self, HeaderValue}, Error, HttpService, Method, Request, Response, StatusCode, TlsAcceptorConfig, Version, }; use actix_http_test::test_server; use actix_service::{fn_service, ServiceFactoryExt}; use actix_utils::future::{err, ok, ready}; use bytes::{Bytes, BytesMut}; use derive_more::{Display, Error}; use futures_core::Stream; use futures_util::{stream::once, StreamExt as _}; use openssl::{ pkey::PKey, ssl::{SslAcceptor, SslMethod}, x509::X509, }; async fn load_body<S>(stream: S) -> Result<BytesMut, PayloadError> where S: Stream<Item = Result<Bytes, PayloadError>>, { let body = stream .map(|res| match res { Ok(chunk) => chunk, Err(_) => panic!(), }) .fold(BytesMut::new(), move |mut body, chunk| { body.extend_from_slice(&chunk); ready(body) }) .await; Ok(body) } fn tls_config() -> SslAcceptor { let rcgen::CertifiedKey { cert, key_pair } = rcgen::generate_simple_self_signed(["localhost".to_owned()]).unwrap(); let cert_file = cert.pem(); let key_file = key_pair.serialize_pem(); let cert = X509::from_pem(cert_file.as_bytes()).unwrap(); let key = PKey::private_key_from_pem(key_file.as_bytes()).unwrap(); let mut builder = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap(); builder.set_certificate(&cert).unwrap(); builder.set_private_key(&key).unwrap(); builder.set_alpn_select_callback(|_, protos| { const H2: &[u8] = b"\x02h2"; if protos.windows(3).any(|window| window == H2) { Ok(b"h2") } else { Err(openssl::ssl::AlpnError::NOACK) } }); builder.set_alpn_protos(b"\x02h2").unwrap(); builder.build() } #[actix_rt::test] async fn h2() -> io::Result<()> { let srv = test_server(move || { HttpService::build() .h2(|_| ok::<_, Error>(Response::ok())) .openssl(tls_config()) .map_err(|_| ()) }) .await; let response = srv.sget("/").send().await.unwrap(); assert!(response.status().is_success()); Ok(()) } #[actix_rt::test] async fn h2_1() -> io::Result<()> { let srv = test_server(move || { HttpService::build() .finish(|req: Request| { assert!(req.peer_addr().is_some()); assert_eq!(req.version(), Version::HTTP_2); ok::<_, Error>(Response::ok()) }) .openssl_with_config( tls_config(), TlsAcceptorConfig::default().handshake_timeout(Duration::from_secs(5)), ) .map_err(|_| ()) }) .await; let response = srv.sget("/").send().await.unwrap(); assert!(response.status().is_success()); Ok(()) } #[actix_rt::test] async fn h2_body() -> io::Result<()> { let data = "HELLOWORLD".to_owned().repeat(64 * 1024); // 640 KiB let mut srv = test_server(move || { HttpService::build() .h2(|mut req: Request<_>| async move { let body = load_body(req.take_payload()).await?; Ok::<_, Error>(Response::ok().set_body(body)) }) .openssl(tls_config()) .map_err(|_| ()) }) .await; let response = srv.sget("/").send_body(data.clone()).await.unwrap(); assert!(response.status().is_success()); let body = srv.load_body(response).await.unwrap(); assert_eq!(&body, data.as_bytes()); Ok(()) } #[actix_rt::test] async fn h2_content_length() { let srv = test_server(move || { HttpService::build() .h2(|req: Request| { let idx: usize = req.uri().path()[1..].parse().unwrap(); let statuses = [ StatusCode::CONTINUE, StatusCode::NO_CONTENT, StatusCode::OK, StatusCode::NOT_FOUND, ]; ok::<_, Infallible>(Response::new(statuses[idx])) }) .openssl(tls_config()) .map_err(|_| ()) }) .await; static VALUE: HeaderValue = HeaderValue::from_static("0"); { let req = srv.request(Method::HEAD, srv.surl("/0")).send(); req.await.expect_err("should timeout on recv 1xx frame"); let req = srv.request(Method::GET, srv.surl("/0")).send(); req.await.expect_err("should timeout on recv 1xx frame"); let req = srv.request(Method::GET, srv.surl("/1")).send(); let response = req.await.unwrap(); assert!(response.headers().get("content-length").is_none()); for &i in &[2, 3] { let req = srv .request(Method::GET, srv.surl(&format!("/{}", i))) .send(); let response = req.await.unwrap(); assert_eq!(response.headers().get("content-length"), Some(&VALUE)); } } } #[actix_rt::test] async fn h2_headers() { let data = STR.repeat(10); let data2 = data.clone(); let mut srv = test_server(move || { let data = data.clone(); HttpService::build() .h2(move |_| { let mut builder = Response::build(StatusCode::OK); for idx in 0..90 { builder.insert_header( (format!("X-TEST-{}", idx).as_str(), "TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \ TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \ TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \ TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \ TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \ TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \ TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \ TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \ TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \ TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \ TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \ TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \ TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST ", )); } ok::<_, Infallible>(builder.body(data.clone())) }) .openssl(tls_config()) .map_err(|_| ()) }) .await; let response = srv.sget("/").send().await.unwrap(); assert!(response.status().is_success()); // read response let bytes = srv.load_body(response).await.unwrap(); assert_eq!(bytes, Bytes::from(data2)); } const STR: &str = "Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World"; #[actix_rt::test] async fn h2_body2() { let mut srv = test_server(move || { HttpService::build() .h2(|_| ok::<_, Infallible>(Response::ok().set_body(STR))) .openssl(tls_config()) .map_err(|_| ()) }) .await; let response = srv.sget("/").send().await.unwrap(); assert!(response.status().is_success()); // read response let bytes = srv.load_body(response).await.unwrap(); assert_eq!(bytes, Bytes::from_static(STR.as_ref())); } #[actix_rt::test] async fn h2_head_empty() { let mut srv = test_server(move || { HttpService::build() .finish(|_| ok::<_, Infallible>(Response::ok().set_body(STR))) .openssl(tls_config()) .map_err(|_| ()) }) .await; let response = srv.shead("/").send().await.unwrap(); assert!(response.status().is_success()); assert_eq!(response.version(), Version::HTTP_2); { let len = response.headers().get(header::CONTENT_LENGTH).unwrap(); assert_eq!(format!("{}", STR.len()), len.to_str().unwrap()); } // read response let bytes = srv.load_body(response).await.unwrap(); assert!(bytes.is_empty()); } #[actix_rt::test] async fn h2_head_binary() { let mut srv = test_server(move || { HttpService::build() .h2(|_| ok::<_, Infallible>(Response::ok().set_body(STR))) .openssl(tls_config()) .map_err(|_| ()) }) .await; let response = srv.shead("/").send().await.unwrap(); assert!(response.status().is_success()); { let len = response.headers().get(header::CONTENT_LENGTH).unwrap(); assert_eq!(format!("{}", STR.len()), len.to_str().unwrap()); } // read response let bytes = srv.load_body(response).await.unwrap(); assert!(bytes.is_empty()); } #[actix_rt::test] async fn h2_head_binary2() { let srv = test_server(move || { HttpService::build() .h2(|_| ok::<_, Infallible>(Response::ok().set_body(STR))) .openssl(tls_config()) .map_err(|_| ()) }) .await; let response = srv.shead("/").send().await.unwrap(); assert!(response.status().is_success()); { let len = response.headers().get(header::CONTENT_LENGTH).unwrap(); assert_eq!(format!("{}", STR.len()), len.to_str().unwrap()); } } #[actix_rt::test] async fn h2_body_length() { let mut srv = test_server(move || { HttpService::build() .h2(|_| async { let body = once(async { Ok::<_, Infallible>(Bytes::from_static(STR.as_ref())) }); Ok::<_, Infallible>( Response::ok().set_body(SizedStream::new(STR.len() as u64, body)), ) }) .openssl(tls_config()) .map_err(|_| ()) }) .await; let response = srv.sget("/").send().await.unwrap(); assert!(response.status().is_success()); // read response let bytes = srv.load_body(response).await.unwrap(); assert_eq!(bytes, Bytes::from_static(STR.as_ref())); } #[actix_rt::test] async fn h2_body_chunked_explicit() { let mut srv = test_server(move || { HttpService::build() .h2(|_| { let body = once(ok::<_, Error>(Bytes::from_static(STR.as_ref()))); ok::<_, Infallible>( Response::build(StatusCode::OK) .insert_header((header::TRANSFER_ENCODING, "chunked")) .body(BodyStream::new(body)), ) }) .openssl(tls_config()) .map_err(|_| ()) }) .await; let response = srv.sget("/").send().await.unwrap(); assert!(response.status().is_success()); assert!(!response.headers().contains_key(header::TRANSFER_ENCODING)); // read response let bytes = srv.load_body(response).await.unwrap(); // decode assert_eq!(bytes, Bytes::from_static(STR.as_ref())); } #[actix_rt::test] async fn h2_response_http_error_handling() { let mut srv = test_server(move || { HttpService::build() .h2(fn_service(|_| { let broken_header = Bytes::from_static(b"\0\0\0"); ok::<_, Infallible>( Response::build(StatusCode::OK) .insert_header((header::CONTENT_TYPE, broken_header)) .body(STR), ) })) .openssl(tls_config()) .map_err(|_| ()) }) .await; let response = srv.sget("/").send().await.unwrap(); assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR); // read response let bytes = srv.load_body(response).await.unwrap(); assert_eq!( bytes, Bytes::from_static(b"error processing HTTP: failed to parse header value") ); } #[derive(Debug, Display, Error)] #[display("error")] struct BadRequest; impl From<BadRequest> for Response<BoxBody> { fn from(err: BadRequest) -> Self { Response::build(StatusCode::BAD_REQUEST) .body(err.to_string()) .map_into_boxed_body() } } #[actix_rt::test] async fn h2_service_error() { let mut srv = test_server(move || { HttpService::build() .h2(|_| err::<Response<BoxBody>, _>(BadRequest)) .openssl(tls_config()) .map_err(|_| ()) }) .await; let response = srv.sget("/").send().await.unwrap(); assert_eq!(response.status(), StatusCode::BAD_REQUEST); // read response let bytes = srv.load_body(response).await.unwrap(); assert_eq!(bytes, Bytes::from_static(b"error")); } #[actix_rt::test] async fn h2_on_connect() { let srv = test_server(move || { HttpService::build() .on_connect_ext(|_, data| { data.insert(20isize); }) .h2(|req: Request| { assert!(req.conn_data::<isize>().is_some()); ok::<_, Infallible>(Response::ok()) }) .openssl(tls_config()) .map_err(|_| ()) }) .await; let response = srv.sget("/").send().await.unwrap(); assert!(response.status().is_success()); }
#![cfg(feature = "rustls-0_23")] extern crate tls_rustls_023 as rustls; use std::{ convert::Infallible, io::{self, BufReader, Write}, net::{SocketAddr, TcpStream as StdTcpStream}, sync::Arc, task::Poll, time::Duration, }; use actix_http::{ body::{BodyStream, BoxBody, SizedStream}, error::PayloadError, header::{self, HeaderName, HeaderValue}, Error, HttpService, Method, Request, Response, StatusCode, TlsAcceptorConfig, Version, }; use actix_http_test::test_server; use actix_rt::pin; use actix_service::{fn_factory_with_config, fn_service}; use actix_tls::connect::rustls_0_23::webpki_roots_cert_store; use actix_utils::future::{err, ok, poll_fn}; use bytes::{Bytes, BytesMut}; use derive_more::{Display, Error}; use futures_core::{ready, Stream}; use futures_util::stream::once; use rustls::{pki_types::ServerName, ServerConfig as RustlsServerConfig}; use rustls_pemfile::{certs, pkcs8_private_keys}; async fn load_body<S>(stream: S) -> Result<BytesMut, PayloadError> where S: Stream<Item = Result<Bytes, PayloadError>>, { let mut buf = BytesMut::new(); pin!(stream); poll_fn(|cx| loop { let body = stream.as_mut(); match ready!(body.poll_next(cx)) { Some(Ok(bytes)) => buf.extend_from_slice(&bytes), None => return Poll::Ready(Ok(())), Some(Err(err)) => return Poll::Ready(Err(err)), } }) .await?; Ok(buf) } fn tls_config() -> RustlsServerConfig { let rcgen::CertifiedKey { cert, key_pair } = rcgen::generate_simple_self_signed(["localhost".to_owned()]).unwrap(); let cert_file = cert.pem(); let key_file = key_pair.serialize_pem(); let cert_file = &mut BufReader::new(cert_file.as_bytes()); let key_file = &mut BufReader::new(key_file.as_bytes()); let cert_chain = certs(cert_file).collect::<Result<Vec<_>, _>>().unwrap(); let mut keys = pkcs8_private_keys(key_file) .collect::<Result<Vec<_>, _>>() .unwrap(); let mut config = RustlsServerConfig::builder() .with_no_client_auth() .with_single_cert( cert_chain, rustls::pki_types::PrivateKeyDer::Pkcs8(keys.remove(0)), ) .unwrap(); config.alpn_protocols.push(HTTP1_1_ALPN_PROTOCOL.to_vec()); config.alpn_protocols.push(H2_ALPN_PROTOCOL.to_vec()); config } pub fn get_negotiated_alpn_protocol( addr: SocketAddr, client_alpn_protocol: &[u8], ) -> Option<Vec<u8>> { let mut config = rustls::ClientConfig::builder() .with_root_certificates(webpki_roots_cert_store()) .with_no_client_auth(); config.alpn_protocols.push(client_alpn_protocol.to_vec()); let mut sess = rustls::ClientConnection::new(Arc::new(config), ServerName::try_from("localhost").unwrap()) .unwrap(); let mut sock = StdTcpStream::connect(addr).unwrap(); let mut stream = rustls::Stream::new(&mut sess, &mut sock); // The handshake will fails because the client will not be able to verify the server // certificate, but it doesn't matter here as we are just interested in the negotiated ALPN // protocol let _ = stream.flush(); sess.alpn_protocol().map(|proto| proto.to_vec()) } #[actix_rt::test] async fn h1() -> io::Result<()> { let srv = test_server(move || { HttpService::build() .h1(|_| ok::<_, Error>(Response::ok())) .rustls_0_23(tls_config()) }) .await; let response = srv.sget("/").send().await.unwrap(); assert!(response.status().is_success()); Ok(()) } #[actix_rt::test] async fn h2() -> io::Result<()> { let srv = test_server(move || { HttpService::build() .h2(|_| ok::<_, Error>(Response::ok())) .rustls_0_23(tls_config()) }) .await; let response = srv.sget("/").send().await.unwrap(); assert!(response.status().is_success()); Ok(()) } #[actix_rt::test] async fn h1_1() -> io::Result<()> { let srv = test_server(move || { HttpService::build() .h1(|req: Request| { assert!(req.peer_addr().is_some()); assert_eq!(req.version(), Version::HTTP_11); ok::<_, Error>(Response::ok()) }) .rustls_0_23(tls_config()) }) .await; let response = srv.sget("/").send().await.unwrap(); assert!(response.status().is_success()); Ok(()) } #[actix_rt::test] async fn h2_1() -> io::Result<()> { let srv = test_server(move || { HttpService::build() .finish(|req: Request| { assert!(req.peer_addr().is_some()); assert_eq!(req.version(), Version::HTTP_2); ok::<_, Error>(Response::ok()) }) .rustls_0_23_with_config( tls_config(), TlsAcceptorConfig::default().handshake_timeout(Duration::from_secs(5)), ) }) .await; let response = srv.sget("/").send().await.unwrap(); assert!(response.status().is_success()); Ok(()) } #[actix_rt::test] async fn h2_body1() -> io::Result<()> { let data = "HELLOWORLD".to_owned().repeat(64 * 1024); let mut srv = test_server(move || { HttpService::build() .h2(|mut req: Request<_>| async move { let body = load_body(req.take_payload()).await?; Ok::<_, Error>(Response::ok().set_body(body)) }) .rustls_0_23(tls_config()) }) .await; let response = srv.sget("/").send_body(data.clone()).await.unwrap(); assert!(response.status().is_success()); let body = srv.load_body(response).await.unwrap(); assert_eq!(&body, data.as_bytes()); Ok(()) } #[actix_rt::test] async fn h2_content_length() { let srv = test_server(move || { HttpService::build() .h2(|req: Request| { let indx: usize = req.uri().path()[1..].parse().unwrap(); let statuses = [ StatusCode::CONTINUE, StatusCode::NO_CONTENT, StatusCode::OK, StatusCode::NOT_FOUND, ]; ok::<_, Infallible>(Response::new(statuses[indx])) }) .rustls_0_23(tls_config()) }) .await; let header = HeaderName::from_static("content-length"); let value = HeaderValue::from_static("0"); { #[allow(clippy::single_element_loop)] for &i in &[0] { let req = srv .request(Method::HEAD, srv.surl(&format!("/{}", i))) .send(); let _response = req.await.expect_err("should timeout on recv 1xx frame"); // assert_eq!(response.headers().get(&header), None); let req = srv .request(Method::GET, srv.surl(&format!("/{}", i))) .send(); let _response = req.await.expect_err("should timeout on recv 1xx frame"); // assert_eq!(response.headers().get(&header), None); } #[allow(clippy::single_element_loop)] for &i in &[1] { let req = srv .request(Method::GET, srv.surl(&format!("/{}", i))) .send(); let response = req.await.unwrap(); assert_eq!(response.headers().get(&header), None); } for &i in &[2, 3] { let req = srv .request(Method::GET, srv.surl(&format!("/{}", i))) .send(); let response = req.await.unwrap(); assert_eq!(response.headers().get(&header), Some(&value)); } } } #[actix_rt::test] async fn h2_headers() { let data = STR.repeat(10); let data2 = data.clone(); let mut srv = test_server(move || { let data = data.clone(); HttpService::build() .h2(move |_| { let mut config = Response::build(StatusCode::OK); for idx in 0..90 { config.insert_header(( format!("X-TEST-{}", idx).as_str(), "TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \ TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \ TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \ TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \ TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \ TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \ TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \ TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \ TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \ TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \ TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \ TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \ TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST ", )); } ok::<_, Infallible>(config.body(data.clone())) }) .rustls_0_23(tls_config()) }) .await; let response = srv.sget("/").send().await.unwrap(); assert!(response.status().is_success()); // read response let bytes = srv.load_body(response).await.unwrap(); assert_eq!(bytes, Bytes::from(data2)); } const STR: &str = "Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World"; #[actix_rt::test] async fn h2_body2() { let mut srv = test_server(move || { HttpService::build() .h2(|_| ok::<_, Infallible>(Response::ok().set_body(STR))) .rustls_0_23(tls_config()) }) .await; let response = srv.sget("/").send().await.unwrap(); assert!(response.status().is_success()); // read response let bytes = srv.load_body(response).await.unwrap(); assert_eq!(bytes, Bytes::from_static(STR.as_ref())); } #[actix_rt::test] async fn h2_head_empty() { let mut srv = test_server(move || { HttpService::build() .finish(|_| ok::<_, Infallible>(Response::ok().set_body(STR))) .rustls_0_23(tls_config()) }) .await; let response = srv.shead("/").send().await.unwrap(); assert!(response.status().is_success()); assert_eq!(response.version(), Version::HTTP_2); { let len = response .headers() .get(http::header::CONTENT_LENGTH) .unwrap(); assert_eq!(format!("{}", STR.len()), len.to_str().unwrap()); } // read response let bytes = srv.load_body(response).await.unwrap(); assert!(bytes.is_empty()); } #[actix_rt::test] async fn h2_head_binary() { let mut srv = test_server(move || { HttpService::build() .h2(|_| ok::<_, Infallible>(Response::ok().set_body(STR))) .rustls_0_23(tls_config()) }) .await; let response = srv.shead("/").send().await.unwrap(); assert!(response.status().is_success()); { let len = response .headers() .get(http::header::CONTENT_LENGTH) .unwrap(); assert_eq!(format!("{}", STR.len()), len.to_str().unwrap()); } // read response let bytes = srv.load_body(response).await.unwrap(); assert!(bytes.is_empty()); } #[actix_rt::test] async fn h2_head_binary2() { let srv = test_server(move || { HttpService::build() .h2(|_| ok::<_, Infallible>(Response::ok().set_body(STR))) .rustls_0_23(tls_config()) }) .await; let response = srv.shead("/").send().await.unwrap(); assert!(response.status().is_success()); { let len = response .headers() .get(http::header::CONTENT_LENGTH) .unwrap(); assert_eq!(format!("{}", STR.len()), len.to_str().unwrap()); } } #[actix_rt::test] async fn h2_body_length() { let mut srv = test_server(move || { HttpService::build() .h2(|_| { let body = once(ok::<_, Infallible>(Bytes::from_static(STR.as_ref()))); ok::<_, Infallible>( Response::ok().set_body(SizedStream::new(STR.len() as u64, body)), ) }) .rustls_0_23(tls_config()) }) .await; let response = srv.sget("/").send().await.unwrap(); assert!(response.status().is_success()); // read response let bytes = srv.load_body(response).await.unwrap(); assert_eq!(bytes, Bytes::from_static(STR.as_ref())); } #[actix_rt::test] async fn h2_body_chunked_explicit() { let mut srv = test_server(move || { HttpService::build() .h2(|_| { let body = once(ok::<_, Error>(Bytes::from_static(STR.as_ref()))); ok::<_, Infallible>( Response::build(StatusCode::OK) .insert_header((header::TRANSFER_ENCODING, "chunked")) .body(BodyStream::new(body)), ) }) .rustls_0_23(tls_config()) }) .await; let response = srv.sget("/").send().await.unwrap(); assert!(response.status().is_success()); assert!(!response.headers().contains_key(header::TRANSFER_ENCODING)); // read response let bytes = srv.load_body(response).await.unwrap(); // decode assert_eq!(bytes, Bytes::from_static(STR.as_ref())); } #[actix_rt::test] async fn h2_response_http_error_handling() { let mut srv = test_server(move || { HttpService::build() .h2(fn_factory_with_config(|_: ()| { ok::<_, Infallible>(fn_service(|_| { let broken_header = Bytes::from_static(b"\0\0\0"); ok::<_, Infallible>( Response::build(StatusCode::OK) .insert_header((http::header::CONTENT_TYPE, broken_header)) .body(STR), ) })) })) .rustls_0_23(tls_config()) }) .await; let response = srv.sget("/").send().await.unwrap(); assert_eq!(response.status(), http::StatusCode::INTERNAL_SERVER_ERROR); // read response let bytes = srv.load_body(response).await.unwrap(); assert_eq!( bytes, Bytes::from_static(b"error processing HTTP: failed to parse header value") ); } #[derive(Debug, Display, Error)] #[display("error")] struct BadRequest; impl From<BadRequest> for Response<BoxBody> { fn from(_: BadRequest) -> Self { Response::bad_request().set_body(BoxBody::new("error")) } } #[actix_rt::test] async fn h2_service_error() { let mut srv = test_server(move || { HttpService::build() .h2(|_| err::<Response<BoxBody>, _>(BadRequest)) .rustls_0_23(tls_config()) }) .await; let response = srv.sget("/").send().await.unwrap(); assert_eq!(response.status(), http::StatusCode::BAD_REQUEST); // read response let bytes = srv.load_body(response).await.unwrap(); assert_eq!(bytes, Bytes::from_static(b"error")); } #[actix_rt::test] async fn h1_service_error() { let mut srv = test_server(move || { HttpService::build() .h1(|_| err::<Response<BoxBody>, _>(BadRequest)) .rustls_0_23(tls_config()) }) .await; let response = srv.sget("/").send().await.unwrap(); assert_eq!(response.status(), http::StatusCode::BAD_REQUEST); // read response let bytes = srv.load_body(response).await.unwrap(); assert_eq!(bytes, Bytes::from_static(b"error")); } const H2_ALPN_PROTOCOL: &[u8] = b"h2"; const HTTP1_1_ALPN_PROTOCOL: &[u8] = b"http/1.1"; const CUSTOM_ALPN_PROTOCOL: &[u8] = b"custom"; #[actix_rt::test] async fn alpn_h1() -> io::Result<()> { let srv = test_server(move || { let mut config = tls_config(); config.alpn_protocols.push(CUSTOM_ALPN_PROTOCOL.to_vec()); HttpService::build() .h1(|_| ok::<_, Error>(Response::ok())) .rustls_0_23(config) }) .await; assert_eq!( get_negotiated_alpn_protocol(srv.addr(), CUSTOM_ALPN_PROTOCOL), Some(CUSTOM_ALPN_PROTOCOL.to_vec()) ); let response = srv.sget("/").send().await.unwrap(); assert!(response.status().is_success()); Ok(()) } #[actix_rt::test] async fn alpn_h2() -> io::Result<()> { let srv = test_server(move || { let mut config = tls_config(); config.alpn_protocols.push(CUSTOM_ALPN_PROTOCOL.to_vec()); HttpService::build() .h2(|_| ok::<_, Error>(Response::ok())) .rustls_0_23(config) }) .await; assert_eq!( get_negotiated_alpn_protocol(srv.addr(), H2_ALPN_PROTOCOL), Some(H2_ALPN_PROTOCOL.to_vec()) ); assert_eq!( get_negotiated_alpn_protocol(srv.addr(), CUSTOM_ALPN_PROTOCOL), Some(CUSTOM_ALPN_PROTOCOL.to_vec()) ); let response = srv.sget("/").send().await.unwrap(); assert!(response.status().is_success()); Ok(()) } #[actix_rt::test] async fn alpn_h2_1() -> io::Result<()> { let srv = test_server(move || { let mut config = tls_config(); config.alpn_protocols.push(CUSTOM_ALPN_PROTOCOL.to_vec()); HttpService::build() .finish(|_| ok::<_, Error>(Response::ok())) .rustls_0_23(config) }) .await; assert_eq!( get_negotiated_alpn_protocol(srv.addr(), H2_ALPN_PROTOCOL), Some(H2_ALPN_PROTOCOL.to_vec()) ); assert_eq!( get_negotiated_alpn_protocol(srv.addr(), HTTP1_1_ALPN_PROTOCOL), Some(HTTP1_1_ALPN_PROTOCOL.to_vec()) ); assert_eq!( get_negotiated_alpn_protocol(srv.addr(), CUSTOM_ALPN_PROTOCOL), Some(CUSTOM_ALPN_PROTOCOL.to_vec()) ); let response = srv.sget("/").send().await.unwrap(); assert!(response.status().is_success()); Ok(()) }
use std::{ convert::Infallible, io::{Read, Write}, net, thread, time::{Duration, Instant}, }; use actix_http::{ body::{self, BodyStream, BoxBody, SizedStream}, header, Error, HttpService, KeepAlive, Request, Response, StatusCode, Version, }; use actix_http_test::test_server; use actix_rt::{net::TcpStream, time::sleep}; use actix_service::fn_service; use actix_utils::future::{err, ok, ready}; use bytes::Bytes; use derive_more::{Display, Error}; use futures_util::{stream::once, FutureExt as _, StreamExt as _}; use rand::Rng as _; use regex::Regex; #[actix_rt::test] async fn h1_basic() { let mut srv = test_server(|| { HttpService::build() .keep_alive(KeepAlive::Disabled) .client_request_timeout(Duration::from_secs(1)) .client_disconnect_timeout(Duration::from_secs(1)) .h1(|req: Request| { assert!(req.peer_addr().is_some()); ok::<_, Infallible>(Response::ok()) }) .tcp() }) .await; let response = srv.get("/").send().await.unwrap(); assert!(response.status().is_success()); srv.stop().await; } #[actix_rt::test] async fn h1_2() { let mut srv = test_server(|| { HttpService::build() .keep_alive(KeepAlive::Disabled) .client_request_timeout(Duration::from_secs(1)) .client_disconnect_timeout(Duration::from_secs(1)) .finish(|req: Request| { assert!(req.peer_addr().is_some()); assert_eq!(req.version(), http::Version::HTTP_11); ok::<_, Infallible>(Response::ok()) }) .tcp() }) .await; let response = srv.get("/").send().await.unwrap(); assert!(response.status().is_success()); srv.stop().await; } #[derive(Debug, Display, Error)] #[display("expect failed")] struct ExpectFailed; impl From<ExpectFailed> for Response<BoxBody> { fn from(_: ExpectFailed) -> Self { Response::new(StatusCode::EXPECTATION_FAILED) } } #[actix_rt::test] async fn expect_continue() { let mut srv = test_server(|| { HttpService::build() .expect(fn_service(|req: Request| { if req.head().uri.query() == Some("yes=") { ok(req) } else { err(ExpectFailed) } })) .finish(|_| ok::<_, Infallible>(Response::ok())) .tcp() }) .await; let mut stream = net::TcpStream::connect(srv.addr()).unwrap(); let _ = stream.write_all(b"GET /test HTTP/1.1\r\nexpect: 100-continue\r\n\r\n"); let mut data = String::new(); let _ = stream.read_to_string(&mut data); assert!(data.starts_with("HTTP/1.1 417 Expectation Failed\r\ncontent-length")); let mut stream = net::TcpStream::connect(srv.addr()).unwrap(); let _ = stream.write_all(b"GET /test?yes= HTTP/1.1\r\nexpect: 100-continue\r\n\r\n"); let mut data = String::new(); let _ = stream.read_to_string(&mut data); assert!(data.starts_with("HTTP/1.1 100 Continue\r\n\r\nHTTP/1.1 200 OK\r\n")); srv.stop().await; } #[actix_rt::test] async fn expect_continue_h1() { let mut srv = test_server(|| { HttpService::build() .expect(fn_service(|req: Request| { sleep(Duration::from_millis(20)).then(move |_| { if req.head().uri.query() == Some("yes=") { ok(req) } else { err(ExpectFailed) } }) })) .h1(fn_service(|_| ok::<_, Infallible>(Response::ok()))) .tcp() }) .await; let mut stream = net::TcpStream::connect(srv.addr()).unwrap(); let _ = stream.write_all(b"GET /test HTTP/1.1\r\nexpect: 100-continue\r\n\r\n"); let mut data = String::new(); let _ = stream.read_to_string(&mut data); assert!(data.starts_with("HTTP/1.1 417 Expectation Failed\r\ncontent-length")); let mut stream = net::TcpStream::connect(srv.addr()).unwrap(); let _ = stream.write_all(b"GET /test?yes= HTTP/1.1\r\nexpect: 100-continue\r\n\r\n"); let mut data = String::new(); let _ = stream.read_to_string(&mut data); assert!(data.starts_with("HTTP/1.1 100 Continue\r\n\r\nHTTP/1.1 200 OK\r\n")); srv.stop().await; } #[actix_rt::test] async fn chunked_payload() { let chunk_sizes = [32768, 32, 32768]; let total_size: usize = chunk_sizes.iter().sum(); let mut srv = test_server(|| { HttpService::build() .h1(fn_service(|mut request: Request| { request .take_payload() .map(|res| match res { Ok(pl) => pl, Err(err) => panic!("Error reading payload: {err}"), }) .fold(0usize, |acc, chunk| ready(acc + chunk.len())) .map(|req_size| { Ok::<_, Error>(Response::ok().set_body(format!("size={}", req_size))) }) })) .tcp() }) .await; let returned_size = { let mut stream = net::TcpStream::connect(srv.addr()).unwrap(); let _ = stream.write_all(b"POST /test HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n"); for chunk_size in chunk_sizes.iter() { let mut bytes = Vec::new(); let random_bytes = rand::rng() .sample_iter(rand::distr::StandardUniform) .take(*chunk_size) .collect::<Vec<_>>(); bytes.extend(format!("{:X}\r\n", chunk_size).as_bytes()); bytes.extend(&random_bytes[..]); bytes.extend(b"\r\n"); let _ = stream.write_all(&bytes); } let _ = stream.write_all(b"0\r\n\r\n"); stream.shutdown(net::Shutdown::Write).unwrap(); let mut data = String::new(); let _ = stream.read_to_string(&mut data); let re = Regex::new(r"size=(\d+)").unwrap(); let size: usize = match re.captures(&data) { Some(caps) => caps.get(1).unwrap().as_str().parse().unwrap(), None => panic!("Failed to find size in HTTP Response: {}", data), }; size }; assert_eq!(returned_size, total_size); srv.stop().await; } #[actix_rt::test] async fn slow_request_408() { let mut srv = test_server(|| { HttpService::build() .client_request_timeout(Duration::from_millis(200)) .keep_alive(Duration::from_secs(2)) .finish(|_| ok::<_, Infallible>(Response::ok())) .tcp() }) .await; let start = Instant::now(); let mut stream = net::TcpStream::connect(srv.addr()).unwrap(); let _ = stream.write_all(b"GET /test HTTP/1.1\r\n"); let mut data = String::new(); let _ = stream.read_to_string(&mut data); assert!( data.starts_with("HTTP/1.1 408 Request Timeout"), "response was not 408: {}", data ); let diff = start.elapsed(); if diff < Duration::from_secs(1) { // test success } else if diff < Duration::from_secs(3) { panic!("request seems to have wrongly timed-out according to keep-alive"); } else { panic!("request took way too long to time out"); } srv.stop().await; } #[actix_rt::test] async fn http1_malformed_request() { let mut srv = test_server(|| { HttpService::build() .h1(|_| ok::<_, Infallible>(Response::ok())) .tcp() }) .await; let mut stream = net::TcpStream::connect(srv.addr()).unwrap(); let _ = stream.write_all(b"GET /test/tests/test HTTP1.1\r\n"); let mut data = String::new(); let _ = stream.read_to_string(&mut data); assert!(data.starts_with("HTTP/1.1 400 Bad Request")); srv.stop().await; } #[actix_rt::test] async fn http1_keepalive() { let mut srv = test_server(|| { HttpService::build() .h1(|_| ok::<_, Infallible>(Response::ok())) .tcp() }) .await; let mut stream = net::TcpStream::connect(srv.addr()).unwrap(); let _ = stream.write_all(b"GET /test/tests/test HTTP/1.1\r\n\r\n"); let mut data = vec![0; 1024]; let _ = stream.read(&mut data); assert_eq!(&data[..17], b"HTTP/1.1 200 OK\r\n"); let _ = stream.write_all(b"GET /test/tests/test HTTP/1.1\r\n\r\n"); let mut data = vec![0; 1024]; let _ = stream.read(&mut data); assert_eq!(&data[..17], b"HTTP/1.1 200 OK\r\n"); srv.stop().await; } #[actix_rt::test] async fn http1_keepalive_timeout() { let mut srv = test_server(|| { HttpService::build() .keep_alive(Duration::from_secs(1)) .h1(|_| ok::<_, Infallible>(Response::ok())) .tcp() }) .await; let mut stream = net::TcpStream::connect(srv.addr()).unwrap(); let _ = stream.write_all(b"GET /test HTTP/1.1\r\n\r\n"); let mut data = vec![0; 256]; let _ = stream.read(&mut data); assert_eq!(&data[..17], b"HTTP/1.1 200 OK\r\n"); thread::sleep(Duration::from_millis(1100)); let mut data = vec![0; 256]; let res = stream.read(&mut data).unwrap(); assert_eq!(res, 0); srv.stop().await; } #[actix_rt::test] async fn http1_keepalive_close() { let mut srv = test_server(|| { HttpService::build() .h1(|_| ok::<_, Infallible>(Response::ok())) .tcp() }) .await; let mut stream = net::TcpStream::connect(srv.addr()).unwrap(); let _ = stream.write_all(b"GET /test/tests/test HTTP/1.1\r\nconnection: close\r\n\r\n"); let mut data = vec![0; 1024]; let _ = stream.read(&mut data); assert_eq!(&data[..17], b"HTTP/1.1 200 OK\r\n"); let mut data = vec![0; 1024]; let res = stream.read(&mut data).unwrap(); assert_eq!(res, 0); srv.stop().await; } #[actix_rt::test] async fn http10_keepalive_default_close() { let mut srv = test_server(|| { HttpService::build() .h1(|_| ok::<_, Infallible>(Response::ok())) .tcp() }) .await; let mut stream = net::TcpStream::connect(srv.addr()).unwrap(); let _ = stream.write_all(b"GET /test/tests/test HTTP/1.0\r\n\r\n"); let mut data = vec![0; 1024]; let _ = stream.read(&mut data); assert_eq!(&data[..17], b"HTTP/1.0 200 OK\r\n"); let mut data = vec![0; 1024]; let res = stream.read(&mut data).unwrap(); assert_eq!(res, 0); srv.stop().await; } #[actix_rt::test] async fn http10_keepalive() { let mut srv = test_server(|| { HttpService::build() .h1(|_| ok::<_, Infallible>(Response::ok())) .tcp() }) .await; let mut stream = net::TcpStream::connect(srv.addr()).unwrap(); let _ = stream.write_all(b"GET /test/tests/test HTTP/1.0\r\nconnection: keep-alive\r\n\r\n"); let mut data = vec![0; 1024]; let _ = stream.read(&mut data); assert_eq!(&data[..17], b"HTTP/1.0 200 OK\r\n"); let mut stream = net::TcpStream::connect(srv.addr()).unwrap(); let _ = stream.write_all(b"GET /test/tests/test HTTP/1.0\r\n\r\n"); let mut data = vec![0; 1024]; let _ = stream.read(&mut data); assert_eq!(&data[..17], b"HTTP/1.0 200 OK\r\n"); let mut data = vec![0; 1024]; let res = stream.read(&mut data).unwrap(); assert_eq!(res, 0); srv.stop().await; } #[actix_rt::test] async fn http1_keepalive_disabled() { let mut srv = test_server(|| { HttpService::build() .keep_alive(KeepAlive::Disabled) .h1(|_| ok::<_, Infallible>(Response::ok())) .tcp() }) .await; let mut stream = net::TcpStream::connect(srv.addr()).unwrap(); let _ = stream.write_all(b"GET /test/tests/test HTTP/1.1\r\n\r\n"); let mut data = vec![0; 1024]; let _ = stream.read(&mut data); assert_eq!(&data[..17], b"HTTP/1.1 200 OK\r\n"); let mut data = vec![0; 1024]; let res = stream.read(&mut data).unwrap(); assert_eq!(res, 0); srv.stop().await; } #[actix_rt::test] async fn content_length() { use actix_http::{ header::{HeaderName, HeaderValue}, StatusCode, }; let mut srv = test_server(|| { HttpService::build() .h1(|req: Request| { let idx: usize = req.uri().path()[1..].parse().unwrap(); let statuses = [ StatusCode::NO_CONTENT, StatusCode::CONTINUE, StatusCode::SWITCHING_PROTOCOLS, StatusCode::PROCESSING, StatusCode::OK, StatusCode::NOT_FOUND, ]; ok::<_, Infallible>(Response::new(statuses[idx])) }) .tcp() }) .await; let header = HeaderName::from_static("content-length"); let value = HeaderValue::from_static("0"); { for i in 0..4 { let req = srv.request(http::Method::GET, srv.url(&format!("/{}", i))); let response = req.send().await.unwrap(); assert_eq!(response.headers().get(&header), None); let req = srv.request(http::Method::HEAD, srv.url(&format!("/{}", i))); let response = req.send().await.unwrap(); assert_eq!(response.headers().get(&header), None); } for i in 4..6 { let req = srv.request(http::Method::GET, srv.url(&format!("/{}", i))); let response = req.send().await.unwrap(); assert_eq!(response.headers().get(&header), Some(&value)); } } srv.stop().await; } #[actix_rt::test] async fn h1_headers() { let data = STR.repeat(10); let data2 = data.clone(); let mut srv = test_server(move || { let data = data.clone(); HttpService::build() .h1(move |_| { let mut builder = Response::build(StatusCode::OK); for idx in 0..90 { builder.insert_header(( format!("X-TEST-{}", idx).as_str(), "TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \ TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \ TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \ TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \ TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \ TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \ TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \ TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \ TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \ TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \ TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \ TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \ TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST ", )); } ok::<_, Infallible>(builder.body(data.clone())) }) .tcp() }) .await; let response = srv.get("/").send().await.unwrap(); assert!(response.status().is_success()); // read response let bytes = srv.load_body(response).await.unwrap(); assert_eq!(bytes, Bytes::from(data2)); srv.stop().await; } const STR: &str = "Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World"; #[actix_rt::test] async fn h1_body() { let mut srv = test_server(|| { HttpService::build() .h1(|_| ok::<_, Infallible>(Response::ok().set_body(STR))) .tcp() }) .await; let response = srv.get("/").send().await.unwrap(); assert!(response.status().is_success()); // read response let bytes = srv.load_body(response).await.unwrap(); assert_eq!(bytes, Bytes::from_static(STR.as_ref())); srv.stop().await; } #[actix_rt::test] async fn h1_head_empty() { let mut srv = test_server(|| { HttpService::build() .h1(|_| ok::<_, Infallible>(Response::ok().set_body(STR))) .tcp() }) .await; let response = srv.head("/").send().await.unwrap(); assert!(response.status().is_success()); { let len = response .headers() .get(http::header::CONTENT_LENGTH) .unwrap(); assert_eq!(format!("{}", STR.len()), len.to_str().unwrap()); } // read response let bytes = srv.load_body(response).await.unwrap(); assert!(bytes.is_empty()); srv.stop().await; } #[actix_rt::test] async fn h1_head_binary() { let mut srv = test_server(|| { HttpService::build() .h1(|_| ok::<_, Infallible>(Response::ok().set_body(STR))) .tcp() }) .await; let response = srv.head("/").send().await.unwrap(); assert!(response.status().is_success()); { let len = response .headers() .get(http::header::CONTENT_LENGTH) .unwrap(); assert_eq!(format!("{}", STR.len()), len.to_str().unwrap()); } // read response let bytes = srv.load_body(response).await.unwrap(); assert!(bytes.is_empty()); srv.stop().await; } #[actix_rt::test] async fn h1_head_binary2() { let mut srv = test_server(|| { HttpService::build() .h1(|_| ok::<_, Infallible>(Response::ok().set_body(STR))) .tcp() }) .await; let response = srv.head("/").send().await.unwrap(); assert!(response.status().is_success()); { let len = response .headers() .get(http::header::CONTENT_LENGTH) .unwrap(); assert_eq!(format!("{}", STR.len()), len.to_str().unwrap()); } srv.stop().await; } #[actix_rt::test] async fn h1_body_length() { let mut srv = test_server(|| { HttpService::build() .h1(|_| { let body = once(ok::<_, Infallible>(Bytes::from_static(STR.as_ref()))); ok::<_, Infallible>( Response::ok().set_body(SizedStream::new(STR.len() as u64, body)), ) }) .tcp() }) .await; let response = srv.get("/").send().await.unwrap(); assert!(response.status().is_success()); // read response let bytes = srv.load_body(response).await.unwrap(); assert_eq!(bytes, Bytes::from_static(STR.as_ref())); srv.stop().await; } #[actix_rt::test] async fn h1_body_chunked_explicit() { let mut srv = test_server(|| { HttpService::build() .h1(|_| { let body = once(ok::<_, Error>(Bytes::from_static(STR.as_ref()))); ok::<_, Infallible>( Response::build(StatusCode::OK) .insert_header((header::TRANSFER_ENCODING, "chunked")) .body(BodyStream::new(body)), ) }) .tcp() }) .await; let response = srv.get("/").send().await.unwrap(); assert!(response.status().is_success()); assert_eq!( response .headers() .get(header::TRANSFER_ENCODING) .unwrap() .to_str() .unwrap(), "chunked" ); // read response let bytes = srv.load_body(response).await.unwrap(); // decode assert_eq!(bytes, Bytes::from_static(STR.as_ref())); srv.stop().await; } #[actix_rt::test] async fn h1_body_chunked_implicit() { let mut srv = test_server(|| { HttpService::build() .h1(|_| { let body = once(ok::<_, Error>(Bytes::from_static(STR.as_ref()))); ok::<_, Infallible>(Response::build(StatusCode::OK).body(BodyStream::new(body))) }) .tcp() }) .await; let response = srv.get("/").send().await.unwrap(); assert!(response.status().is_success()); assert_eq!( response .headers() .get(header::TRANSFER_ENCODING) .unwrap() .to_str() .unwrap(), "chunked" ); // read response let bytes = srv.load_body(response).await.unwrap(); assert_eq!(bytes, Bytes::from_static(STR.as_ref())); srv.stop().await; } #[actix_rt::test] async fn h1_response_http_error_handling() { let mut srv = test_server(|| { HttpService::build() .h1(fn_service(|_| { let broken_header = Bytes::from_static(b"\0\0\0"); ok::<_, Infallible>( Response::build(StatusCode::OK) .insert_header((http::header::CONTENT_TYPE, broken_header)) .body(STR), ) })) .tcp() }) .await; let response = srv.get("/").send().await.unwrap(); assert_eq!(response.status(), http::StatusCode::INTERNAL_SERVER_ERROR); // read response let bytes = srv.load_body(response).await.unwrap(); assert_eq!( bytes, Bytes::from_static(b"error processing HTTP: failed to parse header value") ); srv.stop().await; } #[derive(Debug, Display, Error)] #[display("error")] struct BadRequest; impl From<BadRequest> for Response<BoxBody> { fn from(_: BadRequest) -> Self { Response::bad_request().set_body(BoxBody::new("error")) } } #[actix_rt::test] async fn h1_service_error() { let mut srv = test_server(|| { HttpService::build() .h1(|_| err::<Response<()>, _>(BadRequest)) .tcp() }) .await; let response = srv.get("/").send().await.unwrap(); assert_eq!(response.status(), http::StatusCode::BAD_REQUEST); // read response let bytes = srv.load_body(response).await.unwrap(); assert_eq!(bytes, Bytes::from_static(b"error")); srv.stop().await; } #[actix_rt::test] async fn h1_on_connect() { let mut srv = test_server(|| { HttpService::build() .on_connect_ext(|_, data| { data.insert(20isize); }) .h1(|req: Request| { assert!(req.conn_data::<isize>().is_some()); ok::<_, Infallible>(Response::ok()) }) .tcp() }) .await; let response = srv.get("/").send().await.unwrap(); assert!(response.status().is_success()); srv.stop().await; } /// Tests compliance with 304 Not Modified spec in RFC 7232 §4.1. /// https://datatracker.ietf.org/doc/html/rfc7232#section-4.1 #[actix_rt::test] async fn not_modified_spec_h1() { // TODO: this test needing a few seconds to complete reveals some weirdness with either the // dispatcher or the client, though similar hangs occur on other tests in this file, only // succeeding, it seems, because of the keepalive timer static CL: header::HeaderName = header::CONTENT_LENGTH; let mut srv = test_server(|| { HttpService::build() .h1(|req: Request| { let res: Response<BoxBody> = match req.path() { // with no content-length "/none" => Response::with_body(StatusCode::NOT_MODIFIED, body::None::new()) .map_into_boxed_body(), // with no content-length "/body" => { Response::with_body(StatusCode::NOT_MODIFIED, "1234").map_into_boxed_body() } // with manual content-length header and specific None body "/cl-none" => { let mut res = Response::with_body(StatusCode::NOT_MODIFIED, body::None::new()); res.headers_mut() .insert(CL.clone(), header::HeaderValue::from_static("24")); res.map_into_boxed_body() } // with manual content-length header and ignore-able body "/cl-body" => { let mut res = Response::with_body(StatusCode::NOT_MODIFIED, "1234"); res.headers_mut() .insert(CL.clone(), header::HeaderValue::from_static("4")); res.map_into_boxed_body() } _ => panic!("unknown route"), }; ok::<_, Infallible>(res) }) .tcp() }) .await; let res = srv.get("/none").send().await.unwrap(); assert_eq!(res.status(), http::StatusCode::NOT_MODIFIED); assert_eq!(res.headers().get(&CL), None); assert!(srv.load_body(res).await.unwrap().is_empty()); let res = srv.get("/body").send().await.unwrap(); assert_eq!(res.status(), http::StatusCode::NOT_MODIFIED); assert_eq!(res.headers().get(&CL), None); assert!(srv.load_body(res).await.unwrap().is_empty()); let res = srv.get("/cl-none").send().await.unwrap(); assert_eq!(res.status(), http::StatusCode::NOT_MODIFIED); assert_eq!( res.headers().get(&CL), Some(&header::HeaderValue::from_static("24")), ); assert!(srv.load_body(res).await.unwrap().is_empty()); let res = srv.get("/cl-body").send().await.unwrap(); assert_eq!(res.status(), http::StatusCode::NOT_MODIFIED); assert_eq!( res.headers().get(&CL), Some(&header::HeaderValue::from_static("4")), ); // server does not prevent payload from being sent but clients may choose not to read it // TODO: this is probably a bug in the client, especially since CL header can differ in length // from the body assert!(!srv.load_body(res).await.unwrap().is_empty()); // TODO: add stream response tests srv.stop().await; } #[actix_rt::test] async fn h2c_auto() { let mut srv = test_server(|| { HttpService::build() .keep_alive(KeepAlive::Disabled) .finish(|req: Request| { let body = match req.version() { Version::HTTP_11 => "h1", Version::HTTP_2 => "h2", _ => unreachable!(), }; ok::<_, Infallible>(Response::ok().set_body(body)) }) .tcp_auto_h2c() }) .await; let req = srv.get("/"); assert_eq!(req.get_version(), &Version::HTTP_11); let mut res = req.send().await.unwrap(); assert!(res.status().is_success()); assert_eq!(res.body().await.unwrap(), &b"h1"[..]); // awc doesn't support forcing the version to http/2 so use h2 manually let tcp = TcpStream::connect(srv.addr()).await.unwrap(); let (h2, connection) = h2::client::handshake(tcp).await.unwrap(); tokio::spawn(async move { connection.await.unwrap() }); let mut h2 = h2.ready().await.unwrap(); let request = ::http::Request::new(()); let (response, _) = h2.send_request(request, true).unwrap(); let (head, mut body) = response.await.unwrap().into_parts(); let body = body.data().await.unwrap().unwrap(); assert!(head.status.is_success()); assert_eq!(body, &b"h2"[..]); srv.stop().await; }
use std::{ cell::Cell, convert::Infallible, task::{Context, Poll}, }; use actix_codec::{AsyncRead, AsyncWrite, Framed}; use actix_http::{ body::{BodySize, BoxBody}, h1, ws::{self, CloseCode, Frame, Item, Message}, Error, HttpService, Request, Response, }; use actix_http_test::test_server; use actix_service::{fn_factory, Service}; use bytes::Bytes; use derive_more::{Display, Error, From}; use futures_core::future::LocalBoxFuture; use futures_util::{SinkExt as _, StreamExt as _}; #[derive(Clone)] struct WsService(Cell<bool>); impl WsService { fn new() -> Self { WsService(Cell::new(false)) } fn set_polled(&self) { self.0.set(true); } fn was_polled(&self) -> bool { self.0.get() } } #[derive(Debug, Display, Error, From)] enum WsServiceError { #[display("HTTP error")] Http(actix_http::Error), #[display("WS handshake error")] Ws(actix_http::ws::HandshakeError), #[display("I/O error")] Io(std::io::Error), #[display("dispatcher error")] Dispatcher, } impl From<WsServiceError> for Response<BoxBody> { fn from(err: WsServiceError) -> Self { match err { WsServiceError::Http(err) => err.into(), WsServiceError::Ws(err) => err.into(), WsServiceError::Io(_err) => unreachable!(), WsServiceError::Dispatcher => { Response::internal_server_error().set_body(BoxBody::new(format!("{}", err))) } } } } impl<T> Service<(Request, Framed<T, h1::Codec>)> for WsService where T: AsyncRead + AsyncWrite + Unpin + 'static, { type Response = (); type Error = WsServiceError; type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>; fn poll_ready(&self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { self.set_polled(); Poll::Ready(Ok(())) } fn call(&self, (req, mut framed): (Request, Framed<T, h1::Codec>)) -> Self::Future { assert!(self.was_polled()); Box::pin(async move { let res = ws::handshake(req.head())?.message_body(())?; framed.send((res, BodySize::None).into()).await?; let framed = framed.replace_codec(ws::Codec::new()); ws::Dispatcher::with(framed, service) .await .map_err(|_| WsServiceError::Dispatcher)?; Ok(()) }) } } async fn service(msg: Frame) -> Result<Message, Error> { let msg = match msg { Frame::Ping(msg) => Message::Pong(msg), Frame::Text(text) => Message::Text(String::from_utf8_lossy(&text).into_owned().into()), Frame::Binary(bin) => Message::Binary(bin), Frame::Continuation(item) => Message::Continuation(item), Frame::Close(reason) => Message::Close(reason), _ => return Err(ws::ProtocolError::BadOpCode.into()), }; Ok(msg) } #[actix_rt::test] async fn simple() { let mut srv = test_server(|| { HttpService::build() .upgrade(fn_factory(|| async { Ok::<_, Infallible>(WsService::new()) })) .finish(|_| async { Ok::<_, Infallible>(Response::not_found()) }) .tcp() }) .await; // client service let mut framed = srv.ws().await.unwrap(); framed.send(Message::Text("text".into())).await.unwrap(); let item = framed.next().await.unwrap().unwrap(); assert_eq!(item, Frame::Text(Bytes::from_static(b"text"))); framed.send(Message::Binary("text".into())).await.unwrap(); let item = framed.next().await.unwrap().unwrap(); assert_eq!(item, Frame::Binary(Bytes::from_static(&b"text"[..]))); framed.send(Message::Ping("text".into())).await.unwrap(); let item = framed.next().await.unwrap().unwrap(); assert_eq!(item, Frame::Pong("text".to_string().into())); framed .send(Message::Continuation(Item::FirstText("text".into()))) .await .unwrap(); let item = framed.next().await.unwrap().unwrap(); assert_eq!( item, Frame::Continuation(Item::FirstText(Bytes::from_static(b"text"))) ); assert!(framed .send(Message::Continuation(Item::FirstText("text".into()))) .await .is_err()); assert!(framed .send(Message::Continuation(Item::FirstBinary("text".into()))) .await .is_err()); framed .send(Message::Continuation(Item::Continue("text".into()))) .await .unwrap(); let item = framed.next().await.unwrap().unwrap(); assert_eq!( item, Frame::Continuation(Item::Continue(Bytes::from_static(b"text"))) ); framed .send(Message::Continuation(Item::Last("text".into()))) .await .unwrap(); let item = framed.next().await.unwrap().unwrap(); assert_eq!( item, Frame::Continuation(Item::Last(Bytes::from_static(b"text"))) ); assert!(framed .send(Message::Continuation(Item::Continue("text".into()))) .await .is_err()); assert!(framed .send(Message::Continuation(Item::Last("text".into()))) .await .is_err()); framed .send(Message::Close(Some(CloseCode::Normal.into()))) .await .unwrap(); let item = framed.next().await.unwrap().unwrap(); assert_eq!(item, Frame::Close(Some(CloseCode::Normal.into()))); }
//! Macros for Actix system and runtime. //! //! The [`actix-rt`](https://docs.rs/actix-rt) crate must be available for macro output to compile. //! //! # Entry-point //! See docs for the [`#[main]`](macro@main) macro. //! //! # Tests //! See docs for the [`#[test]`](macro@test) macro. #![deny(rust_2018_idioms, nonstandard_style)] #![warn(future_incompatible)] #![doc(html_logo_url = "https://actix.rs/img/logo.png")] #![doc(html_favicon_url = "https://actix.rs/favicon.ico")] use proc_macro::TokenStream; use quote::quote; use syn::parse::Parser as _; type AttributeArgs = syn::punctuated::Punctuated<syn::Meta, syn::Token![,]>; /// Marks async entry-point function to be executed by Actix system. /// /// # Examples /// ``` /// #[actix_rt::main] /// async fn main() { /// println!("Hello world"); /// } /// ``` // #[allow(clippy::needless_doctest_main)] // #[cfg(not(test))] // Work around for rust-lang/rust#62127 #[proc_macro_attribute] pub fn main(args: TokenStream, item: TokenStream) -> TokenStream { let mut input = match syn::parse::<syn::ItemFn>(item.clone()) { Ok(input) => input, // on parse err, make IDEs happy; see fn docs Err(err) => return input_and_compile_error(item, err), }; let parser = AttributeArgs::parse_terminated; let args = match parser.parse(args.clone()) { Ok(args) => args, Err(err) => return input_and_compile_error(args, err), }; let attrs = &input.attrs; let vis = &input.vis; let sig = &mut input.sig; let body = &input.block; if sig.asyncness.is_none() { return syn::Error::new_spanned( sig.fn_token, "the async keyword is missing from the function declaration", ) .to_compile_error() .into(); } let mut system = syn::parse_str::<syn::Path>("::actix_rt::System").unwrap(); for arg in &args { match arg { syn::Meta::NameValue(syn::MetaNameValue { path, value: syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Str(lit), .. }), .. }) => match path .get_ident() .map(|i| i.to_string().to_lowercase()) .as_deref() { Some("system") => match lit.parse() { Ok(path) => system = path, Err(_) => { return syn::Error::new_spanned(lit, "Expected path") .to_compile_error() .into(); } }, _ => { return syn::Error::new_spanned(arg, "Unknown attribute specified") .to_compile_error() .into(); } }, _ => { return syn::Error::new_spanned(arg, "Unknown attribute specified") .to_compile_error() .into(); } } } sig.asyncness = None; (quote! { #(#attrs)* #vis #sig { <#system>::new().block_on(async move { #body }) } }) .into() } /// Marks async test function to be executed in an Actix system. /// /// # Examples /// ``` /// #[actix_rt::test] /// async fn my_test() { /// assert!(true); /// } /// ``` #[proc_macro_attribute] pub fn test(args: TokenStream, item: TokenStream) -> TokenStream { let mut input = match syn::parse::<syn::ItemFn>(item.clone()) { Ok(input) => input, // on parse err, make IDEs happy; see fn docs Err(err) => return input_and_compile_error(item, err), }; let parser = AttributeArgs::parse_terminated; let args = match parser.parse(args.clone()) { Ok(args) => args, Err(err) => return input_and_compile_error(args, err), }; let attrs = &input.attrs; let vis = &input.vis; let sig = &mut input.sig; let body = &input.block; let mut has_test_attr = false; for attr in attrs { if attr.path().is_ident("test") { has_test_attr = true; } } if sig.asyncness.is_none() { return syn::Error::new_spanned( input.sig.fn_token, "the async keyword is missing from the function declaration", ) .to_compile_error() .into(); } sig.asyncness = None; let missing_test_attr = if has_test_attr { quote! {} } else { quote! { #[::core::prelude::v1::test] } }; let mut system = syn::parse_str::<syn::Path>("::actix_rt::System").unwrap(); for arg in &args { match arg { syn::Meta::NameValue(syn::MetaNameValue { path, value: syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Str(lit), .. }), .. }) => match path .get_ident() .map(|i| i.to_string().to_lowercase()) .as_deref() { Some("system") => match lit.parse() { Ok(path) => system = path, Err(_) => { return syn::Error::new_spanned(lit, "Expected path") .to_compile_error() .into(); } }, _ => { return syn::Error::new_spanned(arg, "Unknown attribute specified") .to_compile_error() .into(); } }, _ => { return syn::Error::new_spanned(arg, "Unknown attribute specified") .to_compile_error() .into(); } } } (quote! { #missing_test_attr #(#attrs)* #vis #sig { <#system>::new().block_on(async { #body }) } }) .into() } /// Converts the error to a token stream and appends it to the original input. /// /// Returning the original input in addition to the error is good for IDEs which can gracefully /// recover and show more precise errors within the macro body. /// /// See <https://github.com/rust-analyzer/rust-analyzer/issues/10468> for more info. fn input_and_compile_error(mut item: TokenStream, err: syn::Error) -> TokenStream { let compile_err = TokenStream::from(err.to_compile_error()); item.extend(compile_err); item }
#[actix_rt::main] async fn main() { println!("Hello world"); }
#[actix_rt::main] fn main() { futures_util::future::ready(()).await }
#[actix_rt::main] async fn main2(_param: bool) { futures_util::future::ready(()).await } fn main() {}
mod system { pub use actix_rt::System as MySystem; } #[actix_rt::main(system = "system::MySystem")] async fn main() { futures_util::future::ready(()).await }
#[actix_rt::main(system = "!@#*&")] async fn main2() {} fn main() {}
#[actix_rt::main(foo = "bar")] async fn async_main() {} #[actix_rt::main(bar::baz)] async fn async_main2() {} fn main() {}
#[actix_rt::test] async fn my_test() { assert!(true); } fn main() {}
#[actix_rt::test] #[should_panic] async fn my_test() { todo!() } fn main() {}
#[actix_rt::test] fn my_test() { futures_util::future::ready(()).await } fn main() {}
mod system { pub use actix_rt::System as MySystem; } #[actix_rt::test(system = "system::MySystem")] async fn my_test() { futures_util::future::ready(()).await } fn main() {}
#[actix_rt::test(system = "!@#*&")] async fn my_test() {} fn main() {}
#[actix_rt::test(foo = "bar")] async fn my_test_1() {} #[actix_rt::test(bar::baz)] async fn my_test_2() {} fn main() {}
#[rustversion::stable(1.65)] // MSRV #[test] fn compile_macros() { let t = trybuild::TestCases::new(); t.pass("tests/trybuild/main-01-basic.rs"); t.compile_fail("tests/trybuild/main-02-only-async.rs"); t.pass("tests/trybuild/main-03-fn-params.rs"); t.pass("tests/trybuild/main-04-system-path.rs"); t.compile_fail("tests/trybuild/main-05-system-expect-path.rs"); t.compile_fail("tests/trybuild/main-06-unknown-attr.rs"); t.pass("tests/trybuild/test-01-basic.rs"); t.pass("tests/trybuild/test-02-keep-attrs.rs"); t.compile_fail("tests/trybuild/test-03-only-async.rs"); t.pass("tests/trybuild/test-04-system-path.rs"); t.compile_fail("tests/trybuild/test-05-system-expect-path.rs"); t.compile_fail("tests/trybuild/test-06-unknown-attr.rs"); }
use std::{borrow::Cow, fmt::Write as _}; use criterion::{black_box, criterion_group, criterion_main, Criterion}; fn compare_quoters(c: &mut Criterion) { let mut group = c.benchmark_group("Compare Quoters"); let quoter = actix_router::Quoter::new(b"", b""); let path_quoted = (0..=0x7f).fold(String::new(), |mut buf, c| { write!(&mut buf, "%{:02X}", c).unwrap(); buf }); let path_unquoted = ('\u{00}'..='\u{7f}').collect::<String>(); group.bench_function("quoter_unquoted", |b| { b.iter(|| { for _ in 0..10 { black_box(quoter.requote(path_unquoted.as_bytes())); } }); }); group.bench_function("percent_encode_unquoted", |b| { b.iter(|| { for _ in 0..10 { let decode = percent_encoding::percent_decode(path_unquoted.as_bytes()); black_box(Into::<Cow<'_, [u8]>>::into(decode)); } }); }); group.bench_function("quoter_quoted", |b| { b.iter(|| { for _ in 0..10 { black_box(quoter.requote(path_quoted.as_bytes())); } }); }); group.bench_function("percent_encode_quoted", |b| { b.iter(|| { for _ in 0..10 { let decode = percent_encoding::percent_decode(path_quoted.as_bytes()); black_box(Into::<Cow<'_, [u8]>>::into(decode)); } }); }); group.finish(); } criterion_group!(benches, compare_quoters); criterion_main!(benches);
//! Based on https://github.com/ibraheemdev/matchit/blob/master/benches/bench.rs use criterion::{black_box, criterion_group, criterion_main, Criterion}; macro_rules! register { (colon) => {{ register!(finish => ":p1", ":p2", ":p3", ":p4") }}; (brackets) => {{ register!(finish => "{p1}", "{p2}", "{p3}", "{p4}") }}; (regex) => {{ register!(finish => "(.*)", "(.*)", "(.*)", "(.*)") }}; (finish => $p1:literal, $p2:literal, $p3:literal, $p4:literal) => {{ let arr = [ concat!("/authorizations"), concat!("/authorizations/", $p1), concat!("/applications/", $p1, "/tokens/", $p2), concat!("/events"), concat!("/repos/", $p1, "/", $p2, "/events"), concat!("/networks/", $p1, "/", $p2, "/events"), concat!("/orgs/", $p1, "/events"), concat!("/users/", $p1, "/received_events"), concat!("/users/", $p1, "/received_events/public"), concat!("/users/", $p1, "/events"), concat!("/users/", $p1, "/events/public"), concat!("/users/", $p1, "/events/orgs/", $p2), concat!("/feeds"), concat!("/notifications"), concat!("/repos/", $p1, "/", $p2, "/notifications"), concat!("/notifications/threads/", $p1), concat!("/notifications/threads/", $p1, "/subscription"), concat!("/repos/", $p1, "/", $p2, "/stargazers"), concat!("/users/", $p1, "/starred"), concat!("/user/starred"), concat!("/user/starred/", $p1, "/", $p2), concat!("/repos/", $p1, "/", $p2, "/subscribers"), concat!("/users/", $p1, "/subscriptions"), concat!("/user/subscriptions"), concat!("/repos/", $p1, "/", $p2, "/subscription"), concat!("/user/subscriptions/", $p1, "/", $p2), concat!("/users/", $p1, "/gists"), concat!("/gists"), concat!("/gists/", $p1), concat!("/gists/", $p1, "/star"), concat!("/repos/", $p1, "/", $p2, "/git/blobs/", $p3), concat!("/repos/", $p1, "/", $p2, "/git/commits/", $p3), concat!("/repos/", $p1, "/", $p2, "/git/refs"), concat!("/repos/", $p1, "/", $p2, "/git/tags/", $p3), concat!("/repos/", $p1, "/", $p2, "/git/trees/", $p3), concat!("/issues"), concat!("/user/issues"), concat!("/orgs/", $p1, "/issues"), concat!("/repos/", $p1, "/", $p2, "/issues"), concat!("/repos/", $p1, "/", $p2, "/issues/", $p3), concat!("/repos/", $p1, "/", $p2, "/assignees"), concat!("/repos/", $p1, "/", $p2, "/assignees/", $p3), concat!("/repos/", $p1, "/", $p2, "/issues/", $p3, "/comments"), concat!("/repos/", $p1, "/", $p2, "/issues/", $p3, "/events"), concat!("/repos/", $p1, "/", $p2, "/labels"), concat!("/repos/", $p1, "/", $p2, "/labels/", $p3), concat!("/repos/", $p1, "/", $p2, "/issues/", $p3, "/labels"), concat!("/repos/", $p1, "/", $p2, "/milestones/", $p3, "/labels"), concat!("/repos/", $p1, "/", $p2, "/milestones/"), concat!("/repos/", $p1, "/", $p2, "/milestones/", $p3), concat!("/emojis"), concat!("/gitignore/templates"), concat!("/gitignore/templates/", $p1), concat!("/meta"), concat!("/rate_limit"), concat!("/users/", $p1, "/orgs"), concat!("/user/orgs"), concat!("/orgs/", $p1), concat!("/orgs/", $p1, "/members"), concat!("/orgs/", $p1, "/members", $p2), concat!("/orgs/", $p1, "/public_members"), concat!("/orgs/", $p1, "/public_members/", $p2), concat!("/orgs/", $p1, "/teams"), concat!("/teams/", $p1), concat!("/teams/", $p1, "/members"), concat!("/teams/", $p1, "/members", $p2), concat!("/teams/", $p1, "/repos"), concat!("/teams/", $p1, "/repos/", $p2, "/", $p3), concat!("/user/teams"), concat!("/repos/", $p1, "/", $p2, "/pulls"), concat!("/repos/", $p1, "/", $p2, "/pulls/", $p3), concat!("/repos/", $p1, "/", $p2, "/pulls/", $p3, "/commits"), concat!("/repos/", $p1, "/", $p2, "/pulls/", $p3, "/files"), concat!("/repos/", $p1, "/", $p2, "/pulls/", $p3, "/merge"), concat!("/repos/", $p1, "/", $p2, "/pulls/", $p3, "/comments"), concat!("/user/repos"), concat!("/users/", $p1, "/repos"), concat!("/orgs/", $p1, "/repos"), concat!("/repositories"), concat!("/repos/", $p1, "/", $p2), concat!("/repos/", $p1, "/", $p2, "/contributors"), concat!("/repos/", $p1, "/", $p2, "/languages"), concat!("/repos/", $p1, "/", $p2, "/teams"), concat!("/repos/", $p1, "/", $p2, "/tags"), concat!("/repos/", $p1, "/", $p2, "/branches"), concat!("/repos/", $p1, "/", $p2, "/branches/", $p3), concat!("/repos/", $p1, "/", $p2, "/collaborators"), concat!("/repos/", $p1, "/", $p2, "/collaborators/", $p3), concat!("/repos/", $p1, "/", $p2, "/comments"), concat!("/repos/", $p1, "/", $p2, "/commits/", $p3, "/comments"), concat!("/repos/", $p1, "/", $p2, "/commits"), concat!("/repos/", $p1, "/", $p2, "/commits/", $p3), concat!("/repos/", $p1, "/", $p2, "/readme"), concat!("/repos/", $p1, "/", $p2, "/keys"), concat!("/repos/", $p1, "/", $p2, "/keys", $p3), concat!("/repos/", $p1, "/", $p2, "/downloads"), concat!("/repos/", $p1, "/", $p2, "/downloads", $p3), concat!("/repos/", $p1, "/", $p2, "/forks"), concat!("/repos/", $p1, "/", $p2, "/hooks"), concat!("/repos/", $p1, "/", $p2, "/hooks", $p3), concat!("/repos/", $p1, "/", $p2, "/releases"), concat!("/repos/", $p1, "/", $p2, "/releases/", $p3), concat!("/repos/", $p1, "/", $p2, "/releases/", $p3, "/assets"), concat!("/repos/", $p1, "/", $p2, "/stats/contributors"), concat!("/repos/", $p1, "/", $p2, "/stats/commit_activity"), concat!("/repos/", $p1, "/", $p2, "/stats/code_frequency"), concat!("/repos/", $p1, "/", $p2, "/stats/participation"), concat!("/repos/", $p1, "/", $p2, "/stats/punch_card"), concat!("/repos/", $p1, "/", $p2, "/statuses/", $p3), concat!("/search/repositories"), concat!("/search/code"), concat!("/search/issues"), concat!("/search/users"), concat!("/legacy/issues/search/", $p1, "/", $p2, "/", $p3, "/", $p4), concat!("/legacy/repos/search/", $p1), concat!("/legacy/user/search/", $p1), concat!("/legacy/user/email/", $p1), concat!("/users/", $p1), concat!("/user"), concat!("/users"), concat!("/user/emails"), concat!("/users/", $p1, "/followers"), concat!("/user/followers"), concat!("/users/", $p1, "/following"), concat!("/user/following"), concat!("/user/following/", $p1), concat!("/users/", $p1, "/following", $p2), concat!("/users/", $p1, "/keys"), concat!("/user/keys"), concat!("/user/keys/", $p1), ]; IntoIterator::into_iter(arr) }}; } fn call() -> impl Iterator<Item = &'static str> { let arr = [ "/authorizations", "/user/repos", "/repos/rust-lang/rust/stargazers", "/orgs/rust-lang/public_members/nikomatsakis", "/repos/rust-lang/rust/releases/1.51.0", ]; IntoIterator::into_iter(arr) } fn compare_routers(c: &mut Criterion) { let mut group = c.benchmark_group("Compare Routers"); let mut actix = actix_router::Router::<bool>::build(); for route in register!(brackets) { actix.path(route, true); } let actix = actix.finish(); group.bench_function("actix", |b| { b.iter(|| { for route in call() { let mut path = actix_router::Path::new(route); black_box(actix.recognize(&mut path).unwrap()); } }); }); let regex_set = regex::RegexSet::new(register!(regex)).unwrap(); group.bench_function("regex", |b| { b.iter(|| { for route in call() { black_box(regex_set.matches(route)); } }); }); group.finish(); } criterion_group!(benches, compare_routers); criterion_main!(benches);
use std::borrow::Cow; use serde::{ de::{self, Deserializer, Error as DeError, Visitor}, forward_to_deserialize_any, }; use crate::{ path::{Path, PathIter}, Quoter, ResourcePath, }; thread_local! { static FULL_QUOTER: Quoter = Quoter::new(b"", b""); } macro_rules! unsupported_type { ($trait_fn:ident, $name:expr) => { fn $trait_fn<V>(self, _: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { Err(de::Error::custom(concat!("unsupported type: ", $name))) } }; } macro_rules! parse_single_value { ($trait_fn:ident) => { fn $trait_fn<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { if self.path.segment_count() != 1 { Err(de::value::Error::custom( format!( "wrong number of parameters: {} expected 1", self.path.segment_count() ) .as_str(), )) } else { Value { value: &self.path[0], } .$trait_fn(visitor) } } }; } macro_rules! parse_value { ($trait_fn:ident, $visit_fn:ident, $tp:tt) => { fn $trait_fn<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { let decoded = FULL_QUOTER .with(|q| q.requote_str_lossy(self.value)) .map(Cow::Owned) .unwrap_or(Cow::Borrowed(self.value)); let v = decoded.parse().map_err(|_| { de::value::Error::custom(format!("can not parse {:?} to a {}", self.value, $tp)) })?; visitor.$visit_fn(v) } }; } pub struct PathDeserializer<'de, T: ResourcePath> { path: &'de Path<T>, } impl<'de, T: ResourcePath + 'de> PathDeserializer<'de, T> { pub fn new(path: &'de Path<T>) -> Self { PathDeserializer { path } } } impl<'de, T: ResourcePath + 'de> Deserializer<'de> for PathDeserializer<'de, T> { type Error = de::value::Error; fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { visitor.visit_map(ParamsDeserializer { params: self.path.iter(), current: None, }) } fn deserialize_struct<V>( self, _: &'static str, _: &'static [&'static str], visitor: V, ) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { self.deserialize_map(visitor) } fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { visitor.visit_unit() } fn deserialize_unit_struct<V>( self, _: &'static str, visitor: V, ) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { self.deserialize_unit(visitor) } fn deserialize_newtype_struct<V>( self, _: &'static str, visitor: V, ) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { visitor.visit_newtype_struct(self) } fn deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { if self.path.segment_count() < len { Err(de::value::Error::custom( format!( "wrong number of parameters: {} expected {}", self.path.segment_count(), len ) .as_str(), )) } else { visitor.visit_seq(ParamsSeq { params: self.path.iter(), }) } } fn deserialize_tuple_struct<V>( self, _: &'static str, len: usize, visitor: V, ) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { if self.path.segment_count() < len { Err(de::value::Error::custom( format!( "wrong number of parameters: {} expected {}", self.path.segment_count(), len ) .as_str(), )) } else { visitor.visit_seq(ParamsSeq { params: self.path.iter(), }) } } fn deserialize_enum<V>( self, _: &'static str, _: &'static [&'static str], visitor: V, ) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { if self.path.is_empty() { Err(de::value::Error::custom("expected at least one parameters")) } else { visitor.visit_enum(ValueEnum { value: &self.path[0], }) } } fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { visitor.visit_seq(ParamsSeq { params: self.path.iter(), }) } unsupported_type!(deserialize_any, "'any'"); unsupported_type!(deserialize_option, "Option<T>"); unsupported_type!(deserialize_identifier, "identifier"); unsupported_type!(deserialize_ignored_any, "ignored_any"); parse_single_value!(deserialize_bool); parse_single_value!(deserialize_i8); parse_single_value!(deserialize_i16); parse_single_value!(deserialize_i32); parse_single_value!(deserialize_i64); parse_single_value!(deserialize_u8); parse_single_value!(deserialize_u16); parse_single_value!(deserialize_u32); parse_single_value!(deserialize_u64); parse_single_value!(deserialize_f32); parse_single_value!(deserialize_f64); parse_single_value!(deserialize_str); parse_single_value!(deserialize_string); parse_single_value!(deserialize_bytes); parse_single_value!(deserialize_byte_buf); parse_single_value!(deserialize_char); } struct ParamsDeserializer<'de, T: ResourcePath> { params: PathIter<'de, T>, current: Option<(&'de str, &'de str)>, } impl<'de, T: ResourcePath> de::MapAccess<'de> for ParamsDeserializer<'de, T> { type Error = de::value::Error; fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error> where K: de::DeserializeSeed<'de>, { self.current = self.params.next().map(|ref item| (item.0, item.1)); match self.current { Some((key, _)) => Ok(Some(seed.deserialize(Key { key })?)), None => Ok(None), } } fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error> where V: de::DeserializeSeed<'de>, { if let Some((_, value)) = self.current.take() { seed.deserialize(Value { value }) } else { Err(de::value::Error::custom("unexpected item")) } } } struct Key<'de> { key: &'de str, } impl<'de> Deserializer<'de> for Key<'de> { type Error = de::value::Error; fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { visitor.visit_str(self.key) } fn deserialize_any<V>(self, _visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { Err(de::value::Error::custom("Unexpected")) } forward_to_deserialize_any! { bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct map struct enum ignored_any } } struct Value<'de> { value: &'de str, } impl<'de> Deserializer<'de> for Value<'de> { type Error = de::value::Error; parse_value!(deserialize_bool, visit_bool, "bool"); parse_value!(deserialize_i8, visit_i8, "i8"); parse_value!(deserialize_i16, visit_i16, "i16"); parse_value!(deserialize_i32, visit_i32, "i32"); parse_value!(deserialize_i64, visit_i64, "i64"); parse_value!(deserialize_u8, visit_u8, "u8"); parse_value!(deserialize_u16, visit_u16, "u16"); parse_value!(deserialize_u32, visit_u32, "u32"); parse_value!(deserialize_u64, visit_u64, "u64"); parse_value!(deserialize_f32, visit_f32, "f32"); parse_value!(deserialize_f64, visit_f64, "f64"); parse_value!(deserialize_char, visit_char, "char"); fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { visitor.visit_unit() } fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { visitor.visit_unit() } fn deserialize_unit_struct<V>( self, _: &'static str, visitor: V, ) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { visitor.visit_unit() } fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { match FULL_QUOTER.with(|q| q.requote_str_lossy(self.value)) { Some(s) => visitor.visit_string(s), None => visitor.visit_borrowed_str(self.value), } } fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { match FULL_QUOTER.with(|q| q.requote_str_lossy(self.value)) { Some(s) => visitor.visit_byte_buf(s.into()), None => visitor.visit_borrowed_bytes(self.value.as_bytes()), } } fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { self.deserialize_bytes(visitor) } fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { self.deserialize_str(visitor) } fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { visitor.visit_some(self) } fn deserialize_enum<V>( self, _: &'static str, _: &'static [&'static str], visitor: V, ) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { visitor.visit_enum(ValueEnum { value: self.value }) } fn deserialize_newtype_struct<V>( self, _: &'static str, visitor: V, ) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { visitor.visit_newtype_struct(self) } fn deserialize_tuple<V>(self, _: usize, _: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { Err(de::value::Error::custom("unsupported type: tuple")) } fn deserialize_struct<V>( self, _: &'static str, _: &'static [&'static str], _: V, ) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { Err(de::value::Error::custom("unsupported type: struct")) } fn deserialize_tuple_struct<V>( self, _: &'static str, _: usize, _: V, ) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { Err(de::value::Error::custom("unsupported type: tuple struct")) } unsupported_type!(deserialize_any, "any"); unsupported_type!(deserialize_seq, "seq"); unsupported_type!(deserialize_map, "map"); unsupported_type!(deserialize_identifier, "identifier"); } struct ParamsSeq<'de, T: ResourcePath> { params: PathIter<'de, T>, } impl<'de, T: ResourcePath> de::SeqAccess<'de> for ParamsSeq<'de, T> { type Error = de::value::Error; fn next_element_seed<U>(&mut self, seed: U) -> Result<Option<U::Value>, Self::Error> where U: de::DeserializeSeed<'de>, { match self.params.next() { Some(item) => Ok(Some(seed.deserialize(Value { value: item.1 })?)), None => Ok(None), } } } struct ValueEnum<'de> { value: &'de str, } impl<'de> de::EnumAccess<'de> for ValueEnum<'de> { type Error = de::value::Error; type Variant = UnitVariant; fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error> where V: de::DeserializeSeed<'de>, { Ok((seed.deserialize(Key { key: self.value })?, UnitVariant)) } } struct UnitVariant; impl<'de> de::VariantAccess<'de> for UnitVariant { type Error = de::value::Error; fn unit_variant(self) -> Result<(), Self::Error> { Ok(()) } fn newtype_variant_seed<T>(self, _seed: T) -> Result<T::Value, Self::Error> where T: de::DeserializeSeed<'de>, { Err(de::value::Error::custom("not supported")) } fn tuple_variant<V>(self, _len: usize, _visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { Err(de::value::Error::custom("not supported")) } fn struct_variant<V>(self, _: &'static [&'static str], _: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { Err(de::value::Error::custom("not supported")) } } #[cfg(test)] mod tests { use serde::Deserialize; use super::*; use crate::{router::Router, ResourceDef}; #[derive(Deserialize)] struct MyStruct { key: String, value: String, } #[derive(Deserialize)] struct Id { _id: String, } #[derive(Debug, Deserialize)] struct Test1(String, u32); #[derive(Debug, Deserialize)] struct Test2 { key: String, value: u32, } #[derive(Debug, Deserialize, PartialEq)] #[serde(rename_all = "lowercase")] enum TestEnum { Val1, Val2, } #[derive(Debug, Deserialize)] struct Test3 { val: TestEnum, } #[test] fn test_request_extract() { let mut router = Router::<()>::build(); router.path("/{key}/{value}/", ()); let router = router.finish(); let mut path = Path::new("/name/user1/"); assert!(router.recognize(&mut path).is_some()); let s: MyStruct = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap(); assert_eq!(s.key, "name"); assert_eq!(s.value, "user1"); let s: (String, String) = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap(); assert_eq!(s.0, "name"); assert_eq!(s.1, "user1"); let mut router = Router::<()>::build(); router.path("/{key}/{value}/", ()); let router = router.finish(); let mut path = Path::new("/name/32/"); assert!(router.recognize(&mut path).is_some()); let s: Test1 = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap(); assert_eq!(s.0, "name"); assert_eq!(s.1, 32); let s: Test2 = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap(); assert_eq!(s.key, "name"); assert_eq!(s.value, 32); let s: (String, u8) = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap(); assert_eq!(s.0, "name"); assert_eq!(s.1, 32); let res: Vec<String> = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap(); assert_eq!(res[0], "name".to_owned()); assert_eq!(res[1], "32".to_owned()); } #[test] fn test_extract_path_single() { let mut router = Router::<()>::build(); router.path("/{value}/", ()); let router = router.finish(); let mut path = Path::new("/32/"); assert!(router.recognize(&mut path).is_some()); let i: i8 = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap(); assert_eq!(i, 32); } #[test] fn test_extract_enum() { let mut router = Router::<()>::build(); router.path("/{val}/", ()); let router = router.finish(); let mut path = Path::new("/val1/"); assert!(router.recognize(&mut path).is_some()); let i: TestEnum = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap(); assert_eq!(i, TestEnum::Val1); let mut router = Router::<()>::build(); router.path("/{val1}/{val2}/", ()); let router = router.finish(); let mut path = Path::new("/val1/val2/"); assert!(router.recognize(&mut path).is_some()); let i: (TestEnum, TestEnum) = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap(); assert_eq!(i, (TestEnum::Val1, TestEnum::Val2)); } #[test] fn test_extract_enum_value() { let mut router = Router::<()>::build(); router.path("/{val}/", ()); let router = router.finish(); let mut path = Path::new("/val1/"); assert!(router.recognize(&mut path).is_some()); let i: Test3 = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap(); assert_eq!(i.val, TestEnum::Val1); let mut path = Path::new("/val3/"); assert!(router.recognize(&mut path).is_some()); let i: Result<Test3, de::value::Error> = de::Deserialize::deserialize(PathDeserializer::new(&path)); assert!(i.is_err()); assert!(format!("{:?}", i).contains("unknown variant")); } #[test] fn test_extract_errors() { let mut router = Router::<()>::build(); router.path("/{value}/", ()); let router = router.finish(); let mut path = Path::new("/name/"); assert!(router.recognize(&mut path).is_some()); let s: Result<Test1, de::value::Error> = de::Deserialize::deserialize(PathDeserializer::new(&path)); assert!(s.is_err()); assert!(format!("{:?}", s).contains("wrong number of parameters")); let s: Result<Test2, de::value::Error> = de::Deserialize::deserialize(PathDeserializer::new(&path)); assert!(s.is_err()); assert!(format!("{:?}", s).contains("can not parse")); let s: Result<(String, String), de::value::Error> = de::Deserialize::deserialize(PathDeserializer::new(&path)); assert!(s.is_err()); assert!(format!("{:?}", s).contains("wrong number of parameters")); let s: Result<u32, de::value::Error> = de::Deserialize::deserialize(PathDeserializer::new(&path)); assert!(s.is_err()); assert!(format!("{:?}", s).contains("can not parse")); } #[test] fn deserialize_path_decode_string() { let rdef = ResourceDef::new("/{key}"); let mut path = Path::new("/%25"); rdef.capture_match_info(&mut path); let de = PathDeserializer::new(&path); let segment: String = serde::Deserialize::deserialize(de).unwrap(); assert_eq!(segment, "%"); let mut path = Path::new("/%2F"); rdef.capture_match_info(&mut path); let de = PathDeserializer::new(&path); let segment: String = serde::Deserialize::deserialize(de).unwrap(); assert_eq!(segment, "/") } #[test] fn deserialize_path_decode_seq() { let rdef = ResourceDef::new("/{key}/{value}"); let mut path = Path::new("/%30%25/%30%2F"); rdef.capture_match_info(&mut path); let de = PathDeserializer::new(&path); let segment: (String, String) = serde::Deserialize::deserialize(de).unwrap(); assert_eq!(segment.0, "0%"); assert_eq!(segment.1, "0/"); } #[test] fn deserialize_path_decode_map() { #[derive(Deserialize)] struct Vals { key: String, value: String, } let rdef = ResourceDef::new("/{key}/{value}"); let mut path = Path::new("/%25/%2F"); rdef.capture_match_info(&mut path); let de = PathDeserializer::new(&path); let vals: Vals = serde::Deserialize::deserialize(de).unwrap(); assert_eq!(vals.key, "%"); assert_eq!(vals.value, "/"); } #[test] fn deserialize_borrowed() { #[derive(Debug, Deserialize)] struct Params<'a> { val: &'a str, } let rdef = ResourceDef::new("/{val}"); let mut path = Path::new("/X"); rdef.capture_match_info(&mut path); let de = PathDeserializer::new(&path); let params: Params<'_> = serde::Deserialize::deserialize(de).unwrap(); assert_eq!(params.val, "X"); let de = PathDeserializer::new(&path); let params: &str = serde::Deserialize::deserialize(de).unwrap(); assert_eq!(params, "X"); let mut path = Path::new("/%2F"); rdef.capture_match_info(&mut path); let de = PathDeserializer::new(&path); assert!(<Params<'_> as serde::Deserialize>::deserialize(de).is_err()); let de = PathDeserializer::new(&path); assert!(<&str as serde::Deserialize>::deserialize(de).is_err()); } // #[test] // fn test_extract_path_decode() { // let mut router = Router::<()>::default(); // router.register_resource(Resource::new(ResourceDef::new("/{value}/"))); // macro_rules! test_single_value { // ($value:expr, $expected:expr) => {{ // let req = TestRequest::with_uri($value).finish(); // let info = router.recognize(&req, &(), 0); // let req = req.with_route_info(info); // assert_eq!( // *Path::<String>::from_request(&req, &PathConfig::default()).unwrap(), // $expected // ); // }}; // } // test_single_value!("/%25/", "%"); // test_single_value!("/%40%C2%A3%24%25%5E%26%2B%3D/", "@£$%^&+="); // test_single_value!("/%2B/", "+"); // test_single_value!("/%252B/", "%2B"); // test_single_value!("/%2F/", "/"); // test_single_value!("/%252F/", "%2F"); // test_single_value!( // "/http%3A%2F%2Flocalhost%3A80%2Ffoo/", // "http://localhost:80/foo" // ); // test_single_value!("/%2Fvar%2Flog%2Fsyslog/", "/var/log/syslog"); // test_single_value!( // "/http%3A%2F%2Flocalhost%3A80%2Ffile%2F%252Fvar%252Flog%252Fsyslog/", // "http://localhost:80/file/%2Fvar%2Flog%2Fsyslog" // ); // let req = TestRequest::with_uri("/%25/7/?id=test").finish(); // let mut router = Router::<()>::default(); // router.register_resource(Resource::new(ResourceDef::new("/{key}/{value}/"))); // let info = router.recognize(&req, &(), 0); // let req = req.with_route_info(info); // let s = Path::<Test2>::from_request(&req, &PathConfig::default()).unwrap(); // assert_eq!(s.key, "%"); // assert_eq!(s.value, 7); // let s = Path::<(String, String)>::from_request(&req, &PathConfig::default()).unwrap(); // assert_eq!(s.0, "%"); // assert_eq!(s.1, "7"); // } // #[test] // fn test_extract_path_no_decode() { // let mut router = Router::<()>::default(); // router.register_resource(Resource::new(ResourceDef::new("/{value}/"))); // let req = TestRequest::with_uri("/%25/").finish(); // let info = router.recognize(&req, &(), 0); // let req = req.with_route_info(info); // assert_eq!( // *Path::<String>::from_request(&req, &&PathConfig::default().disable_decoding()) // .unwrap(), // "%25" // ); // } }
//! Resource path matching and router. #![deny(rust_2018_idioms, nonstandard_style)] #![warn(future_incompatible)] #![doc(html_logo_url = "https://actix.rs/img/logo.png")] #![doc(html_favicon_url = "https://actix.rs/favicon.ico")] #![cfg_attr(docsrs, feature(doc_auto_cfg))] mod de; mod path; mod pattern; mod quoter; mod regex_set; mod resource; mod resource_path; mod router; #[cfg(feature = "http")] mod url; #[cfg(feature = "http")] pub use self::url::Url; pub use self::{ de::PathDeserializer, path::Path, pattern::{IntoPatterns, Patterns}, quoter::Quoter, resource::ResourceDef, resource_path::{Resource, ResourcePath}, router::{ResourceId, Router, RouterBuilder}, };
use std::{ borrow::Cow, ops::{DerefMut, Index}, }; use serde::{de, Deserialize}; use crate::{de::PathDeserializer, Resource, ResourcePath}; #[derive(Debug, Clone)] pub(crate) enum PathItem { Static(Cow<'static, str>), Segment(u16, u16), } impl Default for PathItem { fn default() -> Self { Self::Static(Cow::Borrowed("")) } } /// Resource path match information. /// /// If resource path contains variable patterns, `Path` stores them. #[derive(Debug, Clone, Default)] pub struct Path<T> { /// Full path representation. path: T, /// Number of characters in `path` that have been processed into `segments`. pub(crate) skip: u16, /// List of processed dynamic segments; name->value pairs. pub(crate) segments: Vec<(Cow<'static, str>, PathItem)>, } impl<T: ResourcePath> Path<T> { pub fn new(path: T) -> Path<T> { Path { path, skip: 0, segments: Vec::new(), } } /// Returns reference to inner path instance. #[inline] pub fn get_ref(&self) -> &T { &self.path } /// Returns mutable reference to inner path instance. #[inline] pub fn get_mut(&mut self) -> &mut T { &mut self.path } /// Returns full path as a string. #[inline] pub fn as_str(&self) -> &str { self.path.path() } /// Returns unprocessed part of the path. /// /// Returns empty string if no more is to be processed. #[inline] pub fn unprocessed(&self) -> &str { // clamp skip to path length let skip = (self.skip as usize).min(self.as_str().len()); &self.path.path()[skip..] } /// Returns unprocessed part of the path. #[doc(hidden)] #[deprecated(since = "0.6.0", note = "Use `.as_str()` or `.unprocessed()`.")] #[inline] pub fn path(&self) -> &str { let skip = self.skip as usize; let path = self.path.path(); if skip <= path.len() { &path[skip..] } else { "" } } /// Set new path. #[inline] pub fn set(&mut self, path: T) { self.path = path; self.skip = 0; self.segments.clear(); } /// Reset state. #[inline] pub fn reset(&mut self) { self.skip = 0; self.segments.clear(); } /// Skip first `n` chars in path. #[inline] pub fn skip(&mut self, n: u16) { self.skip += n; } pub(crate) fn add(&mut self, name: impl Into<Cow<'static, str>>, value: PathItem) { match value { PathItem::Static(seg) => self.segments.push((name.into(), PathItem::Static(seg))), PathItem::Segment(begin, end) => self.segments.push(( name.into(), PathItem::Segment(self.skip + begin, self.skip + end), )), } } #[doc(hidden)] pub fn add_static( &mut self, name: impl Into<Cow<'static, str>>, value: impl Into<Cow<'static, str>>, ) { self.segments .push((name.into(), PathItem::Static(value.into()))); } /// Check if there are any matched patterns. #[inline] pub fn is_empty(&self) -> bool { self.segments.is_empty() } /// Returns number of interpolated segments. #[inline] pub fn segment_count(&self) -> usize { self.segments.len() } /// Get matched parameter by name without type conversion pub fn get(&self, name: &str) -> Option<&str> { for (seg_name, val) in self.segments.iter() { if name == seg_name { return match val { PathItem::Static(ref s) => Some(s), PathItem::Segment(s, e) => { Some(&self.path.path()[(*s as usize)..(*e as usize)]) } }; } } None } /// Returns matched parameter by name. /// /// If keyed parameter is not available empty string is used as default value. pub fn query(&self, key: &str) -> &str { self.get(key).unwrap_or_default() } /// Return iterator to items in parameter container. pub fn iter(&self) -> PathIter<'_, T> { PathIter { idx: 0, params: self, } } /// Deserializes matching parameters to a specified type `U`. /// /// # Errors /// /// Returns error when dynamic path segments cannot be deserialized into a `U` type. pub fn load<'de, U: Deserialize<'de>>(&'de self) -> Result<U, de::value::Error> { Deserialize::deserialize(PathDeserializer::new(self)) } } #[derive(Debug)] pub struct PathIter<'a, T> { idx: usize, params: &'a Path<T>, } impl<'a, T: ResourcePath> Iterator for PathIter<'a, T> { type Item = (&'a str, &'a str); #[inline] fn next(&mut self) -> Option<(&'a str, &'a str)> { if self.idx < self.params.segment_count() { let idx = self.idx; let res = match self.params.segments[idx].1 { PathItem::Static(ref s) => s, PathItem::Segment(s, e) => &self.params.path.path()[(s as usize)..(e as usize)], }; self.idx += 1; return Some((&self.params.segments[idx].0, res)); } None } } impl<'a, T: ResourcePath> Index<&'a str> for Path<T> { type Output = str; fn index(&self, name: &'a str) -> &str { self.get(name) .expect("Value for parameter is not available") } } impl<T: ResourcePath> Index<usize> for Path<T> { type Output = str; fn index(&self, idx: usize) -> &str { match self.segments[idx].1 { PathItem::Static(ref s) => s, PathItem::Segment(s, e) => &self.path.path()[(s as usize)..(e as usize)], } } } impl<T: ResourcePath> Resource for Path<T> { type Path = T; fn resource_path(&mut self) -> &mut Path<Self::Path> { self } } impl<T, P> Resource for T where T: DerefMut<Target = Path<P>>, P: ResourcePath, { type Path = P; fn resource_path(&mut self) -> &mut Path<Self::Path> { &mut *self } } #[cfg(test)] mod tests { use std::cell::RefCell; use super::*; #[allow(clippy::needless_borrow)] #[test] fn deref_impls() { let mut foo = Path::new("/foo"); let _ = (&mut foo).resource_path(); let foo = RefCell::new(foo); let _ = foo.borrow_mut().resource_path(); } }
/// One or many patterns. #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum Patterns { Single(String), List(Vec<String>), } impl Patterns { pub fn is_empty(&self) -> bool { match self { Patterns::Single(_) => false, Patterns::List(pats) => pats.is_empty(), } } } /// Helper trait for type that could be converted to one or more path patterns. pub trait IntoPatterns { fn patterns(&self) -> Patterns; } impl IntoPatterns for String { fn patterns(&self) -> Patterns { Patterns::Single(self.clone()) } } impl IntoPatterns for &String { fn patterns(&self) -> Patterns { (*self).patterns() } } impl IntoPatterns for str { fn patterns(&self) -> Patterns { Patterns::Single(self.to_owned()) } } impl IntoPatterns for &str { fn patterns(&self) -> Patterns { (*self).patterns() } } impl IntoPatterns for bytestring::ByteString { fn patterns(&self) -> Patterns { Patterns::Single(self.to_string()) } } impl IntoPatterns for Patterns { fn patterns(&self) -> Patterns { self.clone() } } impl<T: AsRef<str>> IntoPatterns for Vec<T> { fn patterns(&self) -> Patterns { let mut patterns = self.iter().map(|v| v.as_ref().to_owned()); match patterns.size_hint() { (1, _) => Patterns::Single(patterns.next().unwrap()), _ => Patterns::List(patterns.collect()), } } } macro_rules! array_patterns_single (($tp:ty) => { impl IntoPatterns for [$tp; 1] { fn patterns(&self) -> Patterns { Patterns::Single(self[0].to_owned()) } } }); macro_rules! array_patterns_multiple (($tp:ty, $str_fn:expr, $($num:tt) +) => { // for each array length specified in space-separated $num $( impl IntoPatterns for [$tp; $num] { fn patterns(&self) -> Patterns { Patterns::List(self.iter().map($str_fn).collect()) } } )+ }); array_patterns_single!(&str); array_patterns_multiple!(&str, |&v| v.to_owned(), 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16); array_patterns_single!(String); array_patterns_multiple!(String, |v| v.clone(), 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16);
/// Partial percent-decoding. /// /// Performs percent-decoding on a slice but can selectively skip decoding certain sequences. /// /// # Examples /// ``` /// # use actix_router::Quoter; /// // + is set as a protected character and will not be decoded... /// let q = Quoter::new(&[], b"+"); /// /// // ...but the other encoded characters (like the hyphen below) will. /// assert_eq!(q.requote(b"/a%2Db%2Bc").unwrap(), b"/a-b%2Bc"); /// ``` pub struct Quoter { /// Simple bit-map of protected values in the 0-127 ASCII range. protected_table: AsciiBitmap, } impl Quoter { /// Constructs a new `Quoter` instance given a set of protected ASCII bytes. /// /// The first argument is ignored but is kept for backward compatibility. /// /// # Panics /// Panics if any of the `protected` bytes are not in the 0-127 ASCII range. pub fn new(_: &[u8], protected: &[u8]) -> Quoter { let mut protected_table = AsciiBitmap::default(); // prepare protected table for &ch in protected { protected_table.set_bit(ch); } Quoter { protected_table } } /// Decodes the next escape sequence, if any, and advances `val`. #[inline(always)] fn decode_next<'a>(&self, val: &mut &'a [u8]) -> Option<(&'a [u8], u8)> { for i in 0..val.len() { if let (prev, [b'%', p1, p2, rem @ ..]) = val.split_at(i) { if let Some(ch) = hex_pair_to_char(*p1, *p2) // ignore protected ascii bytes .filter(|&ch| !(ch < 128 && self.protected_table.bit_at(ch))) { *val = rem; return Some((prev, ch)); } } } None } /// Partially percent-decodes the given bytes. /// /// Escape sequences of the protected set are *not* decoded. /// /// Returns `None` when no modification to the original bytes was required. /// /// Invalid/incomplete percent-encoding sequences are passed unmodified. pub fn requote(&self, val: &[u8]) -> Option<Vec<u8>> { let mut remaining = val; // early return indicates that no percent-encoded sequences exist and we can skip allocation let (pre, decoded_char) = self.decode_next(&mut remaining)?; // decoded output will always be shorter than the input let mut decoded = Vec::<u8>::with_capacity(val.len()); // push first segment and decoded char decoded.extend_from_slice(pre); decoded.push(decoded_char); // decode and push rest of segments and decoded chars while let Some((prev, ch)) = self.decode_next(&mut remaining) { // this ugly conditional achieves +50% perf in cases where this is a tight loop. if !prev.is_empty() { decoded.extend_from_slice(prev); } decoded.push(ch); } decoded.extend_from_slice(remaining); Some(decoded) } pub(crate) fn requote_str_lossy(&self, val: &str) -> Option<String> { self.requote(val.as_bytes()) .map(|data| String::from_utf8_lossy(&data).into_owned()) } } /// Decode a ASCII hex-encoded pair to an integer. /// /// Returns `None` if either portion of the decoded pair does not evaluate to a valid hex value. /// /// - `0x33 ('3'), 0x30 ('0') => 0x30 ('0')` /// - `0x34 ('4'), 0x31 ('1') => 0x41 ('A')` /// - `0x36 ('6'), 0x31 ('1') => 0x61 ('a')` #[inline(always)] fn hex_pair_to_char(d1: u8, d2: u8) -> Option<u8> { let d_high = char::from(d1).to_digit(16)?; let d_low = char::from(d2).to_digit(16)?; // left shift high nibble by 4 bits Some((d_high as u8) << 4 | (d_low as u8)) } #[derive(Debug, Default, Clone)] struct AsciiBitmap { array: [u8; 16], } impl AsciiBitmap { /// Sets bit in given bit-map to 1=true. /// /// # Panics /// Panics if `ch` index is out of bounds. fn set_bit(&mut self, ch: u8) { self.array[(ch >> 3) as usize] |= 0b1 << (ch & 0b111) } /// Returns true if bit to true in given bit-map. /// /// # Panics /// Panics if `ch` index is out of bounds. fn bit_at(&self, ch: u8) -> bool { self.array[(ch >> 3) as usize] & (0b1 << (ch & 0b111)) != 0 } } #[cfg(test)] mod tests { use super::*; #[test] fn custom_quoter() { let q = Quoter::new(b"", b"+"); assert_eq!(q.requote(b"/a%25c").unwrap(), b"/a%c"); assert_eq!(q.requote(b"/a%2Bc"), None); let q = Quoter::new(b"%+", b"/"); assert_eq!(q.requote(b"/a%25b%2Bc").unwrap(), b"/a%b+c"); assert_eq!(q.requote(b"/a%2fb"), None); assert_eq!(q.requote(b"/a%2Fb"), None); assert_eq!(q.requote(b"/a%0Ab").unwrap(), b"/a\nb"); assert_eq!(q.requote(b"/a%FE\xffb").unwrap(), b"/a\xfe\xffb"); assert_eq!(q.requote(b"/a\xfe\xffb"), None); } #[test] fn non_ascii() { let q = Quoter::new(b"%+", b"/"); assert_eq!(q.requote(b"/a%FE\xffb").unwrap(), b"/a\xfe\xffb"); assert_eq!(q.requote(b"/a\xfe\xffb"), None); } #[test] fn invalid_sequences() { let q = Quoter::new(b"%+", b"/"); assert_eq!(q.requote(b"/a%2x%2X%%"), None); assert_eq!(q.requote(b"/a%20%2X%%").unwrap(), b"/a %2X%%"); } #[test] fn quoter_no_modification() { let q = Quoter::new(b"", b""); assert_eq!(q.requote(b"/abc/../efg"), None); } }
//! Abstraction over `regex` and `regex-lite` depending on whether we have `unicode` crate feature //! enabled. use cfg_if::cfg_if; #[cfg(feature = "unicode")] pub(crate) use regex::{escape, Regex}; #[cfg(not(feature = "unicode"))] pub(crate) use regex_lite::{escape, Regex}; #[cfg(feature = "unicode")] #[derive(Debug, Clone)] pub(crate) struct RegexSet(regex::RegexSet); #[cfg(not(feature = "unicode"))] #[derive(Debug, Clone)] pub(crate) struct RegexSet(Vec<regex_lite::Regex>); impl RegexSet { /// Create a new regex set. /// /// # Panics /// /// Panics if any path patterns are malformed. pub(crate) fn new(re_set: Vec<String>) -> Self { cfg_if! { if #[cfg(feature = "unicode")] { Self(regex::RegexSet::new(re_set).unwrap()) } else { Self(re_set.iter().map(|re| Regex::new(re).unwrap()).collect()) } } } /// Create a new empty regex set. pub(crate) fn empty() -> Self { cfg_if! { if #[cfg(feature = "unicode")] { Self(regex::RegexSet::empty()) } else { Self(Vec::new()) } } } /// Returns true if regex set matches `path`. pub(crate) fn is_match(&self, path: &str) -> bool { cfg_if! { if #[cfg(feature = "unicode")] { self.0.is_match(path) } else { self.0.iter().any(|re| re.is_match(path)) } } } /// Returns index within `path` of first match. pub(crate) fn first_match_idx(&self, path: &str) -> Option<usize> { cfg_if! { if #[cfg(feature = "unicode")] { self.0.matches(path).into_iter().next() } else { Some(self.0.iter().enumerate().find(|(_, re)| re.is_match(path))?.0) } } } }
use std::{ borrow::{Borrow, Cow}, collections::HashMap, hash::{BuildHasher, Hash, Hasher}, mem, }; use tracing::error; use crate::{ path::PathItem, regex_set::{escape, Regex, RegexSet}, IntoPatterns, Patterns, Resource, ResourcePath, }; const MAX_DYNAMIC_SEGMENTS: usize = 16; /// Regex flags to allow '.' in regex to match '\n' /// /// See the docs under: https://docs.rs/regex/1/regex/#grouping-and-flags const REGEX_FLAGS: &str = "(?s-m)"; /// Describes the set of paths that match to a resource. /// /// `ResourceDef`s are effectively a way to transform the a custom resource pattern syntax into /// suitable regular expressions from which to check matches with paths and capture portions of a /// matched path into variables. Common cases are on a fast path that avoids going through the /// regex engine. /// /// /// # Pattern Format and Matching Behavior /// Resource pattern is defined as a string of zero or more _segments_ where each segment is /// preceded by a slash `/`. /// /// This means that pattern string __must__ either be empty or begin with a slash (`/`). This also /// implies that a trailing slash in pattern defines an empty segment. For example, the pattern /// `"/user/"` has two segments: `["user", ""]` /// /// A key point to understand is that `ResourceDef` matches segments, not strings. Segments are /// matched individually. For example, the pattern `/user/` is not considered a prefix for the path /// `/user/123/456`, because the second segment doesn't match: `["user", ""]` /// vs `["user", "123", "456"]`. /// /// This definition is consistent with the definition of absolute URL path in /// [RFC 3986 §3.3](https://datatracker.ietf.org/doc/html/rfc3986#section-3.3) /// /// /// # Static Resources /// A static resource is the most basic type of definition. Pass a pattern to [new][Self::new]. /// Conforming paths must match the pattern exactly. /// /// ## Examples /// ``` /// # use actix_router::ResourceDef; /// let resource = ResourceDef::new("/home"); /// /// assert!(resource.is_match("/home")); /// /// assert!(!resource.is_match("/home/")); /// assert!(!resource.is_match("/home/new")); /// assert!(!resource.is_match("/homes")); /// assert!(!resource.is_match("/search")); /// ``` /// /// # Dynamic Segments /// Also known as "path parameters". Resources can define sections of a pattern that be extracted /// from a conforming path, if it conforms to (one of) the resource pattern(s). /// /// The marker for a dynamic segment is curly braces wrapping an identifier. For example, /// `/user/{id}` would match paths like `/user/123` or `/user/james` and be able to extract the user /// IDs "123" and "james", respectively. /// /// However, this resource pattern (`/user/{id}`) would, not cover `/user/123/stars` (unless /// constructed as a prefix; see next section) since the default pattern for segments matches all /// characters until it finds a `/` character (or the end of the path). Custom segment patterns are /// covered further down. /// /// Dynamic segments do not need to be delimited by `/` characters, they can be defined within a /// path segment. For example, `/rust-is-{opinion}` can match the paths `/rust-is-cool` and /// `/rust-is-hard`. /// /// For information on capturing segment values from paths or other custom resource types, /// see [`capture_match_info`][Self::capture_match_info] /// and [`capture_match_info_fn`][Self::capture_match_info_fn]. /// /// A resource definition can contain at most 16 dynamic segments. /// /// ## Examples /// ``` /// use actix_router::{Path, ResourceDef}; /// /// let resource = ResourceDef::prefix("/user/{id}"); /// /// assert!(resource.is_match("/user/123")); /// assert!(!resource.is_match("/user")); /// assert!(!resource.is_match("/user/")); /// /// let mut path = Path::new("/user/123"); /// resource.capture_match_info(&mut path); /// assert_eq!(path.get("id").unwrap(), "123"); /// ``` /// /// # Prefix Resources /// A prefix resource is defined as pattern that can match just the start of a path, up to a /// segment boundary. /// /// Prefix patterns with a trailing slash may have an unexpected, though correct, behavior. /// They define and therefore require an empty segment in order to match. It is easier to understand /// this behavior after reading the [matching behavior section]. Examples are given below. /// /// The empty pattern (`""`), as a prefix, matches any path. /// /// Prefix resources can contain dynamic segments. /// /// ## Examples /// ``` /// # use actix_router::ResourceDef; /// let resource = ResourceDef::prefix("/home"); /// assert!(resource.is_match("/home")); /// assert!(resource.is_match("/home/new")); /// assert!(!resource.is_match("/homes")); /// /// // prefix pattern with a trailing slash /// let resource = ResourceDef::prefix("/user/{id}/"); /// assert!(resource.is_match("/user/123/")); /// assert!(resource.is_match("/user/123//stars")); /// assert!(!resource.is_match("/user/123/stars")); /// assert!(!resource.is_match("/user/123")); /// ``` /// /// # Custom Regex Segments /// Dynamic segments can be customised to only match a specific regular expression. It can be /// helpful to do this if resource definitions would otherwise conflict and cause one to /// be inaccessible. /// /// The regex used when capturing segment values can be specified explicitly using this syntax: /// `{name:regex}`. For example, `/user/{id:\d+}` will only match paths where the user ID /// is numeric. /// /// The regex could potentially match multiple segments. If this is not wanted, then care must be /// taken to avoid matching a slash `/`. It is guaranteed, however, that the match ends at a /// segment boundary; the pattern `r"(/|$)` is always appended to the regex. /// /// By default, dynamic segments use this regex: `[^/]+`. This shows why it is the case, as shown in /// the earlier section, that segments capture a slice of the path up to the next `/` character. /// /// Custom regex segments can be used in static and prefix resource definition variants. /// /// ## Examples /// ``` /// # use actix_router::ResourceDef; /// let resource = ResourceDef::new(r"/user/{id:\d+}"); /// assert!(resource.is_match("/user/123")); /// assert!(resource.is_match("/user/314159")); /// assert!(!resource.is_match("/user/abc")); /// ``` /// /// # Tail Segments /// As a shortcut to defining a custom regex for matching _all_ remaining characters (not just those /// up until a `/` character), there is a special pattern to match (and capture) the remaining /// path portion. /// /// To do this, use the segment pattern: `{name}*`. Since a tail segment also has a name, values are /// extracted in the same way as non-tail dynamic segments. /// /// ## Examples /// ``` /// # use actix_router::{Path, ResourceDef}; /// let resource = ResourceDef::new("/blob/{tail}*"); /// assert!(resource.is_match("/blob/HEAD/Cargo.toml")); /// assert!(resource.is_match("/blob/HEAD/README.md")); /// /// let mut path = Path::new("/blob/main/LICENSE"); /// resource.capture_match_info(&mut path); /// assert_eq!(path.get("tail").unwrap(), "main/LICENSE"); /// ``` /// /// # Multi-Pattern Resources /// For resources that can map to multiple distinct paths, it may be suitable to use /// multi-pattern resources by passing an array/vec to [`new`][Self::new]. They will be combined /// into a regex set which is usually quicker to check matches on than checking each /// pattern individually. /// /// Multi-pattern resources can contain dynamic segments just like single pattern ones. /// However, take care to use consistent and semantically-equivalent segment names; it could affect /// expectations in the router using these definitions and cause runtime panics. /// /// ## Examples /// ``` /// # use actix_router::ResourceDef; /// let resource = ResourceDef::new(["/home", "/index"]); /// assert!(resource.is_match("/home")); /// assert!(resource.is_match("/index")); /// ``` /// /// # Trailing Slashes /// It should be noted that this library takes no steps to normalize intra-path or trailing slashes. /// As such, all resource definitions implicitly expect a pre-processing step to normalize paths if /// you wish to accommodate "recoverable" path errors. Below are several examples of resource-path /// pairs that would not be compatible. /// /// ## Examples /// ``` /// # use actix_router::ResourceDef; /// assert!(!ResourceDef::new("/root").is_match("/root/")); /// assert!(!ResourceDef::new("/root/").is_match("/root")); /// assert!(!ResourceDef::prefix("/root/").is_match("/root")); /// ``` /// /// [matching behavior section]: #pattern-format-and-matching-behavior #[derive(Clone, Debug)] pub struct ResourceDef { id: u16, /// Optional name of resource. name: Option<String>, /// Pattern that generated the resource definition. patterns: Patterns, is_prefix: bool, /// Pattern type. pat_type: PatternType, /// List of segments that compose the pattern, in order. segments: Vec<PatternSegment>, } #[derive(Debug, Clone, PartialEq)] enum PatternSegment { /// Literal slice of pattern. Const(String), /// Name of dynamic segment. Var(String), } #[derive(Debug, Clone)] #[allow(clippy::large_enum_variant)] enum PatternType { /// Single constant/literal segment. Static(String), /// Single regular expression and list of dynamic segment names. Dynamic(Regex, Vec<&'static str>), /// Regular expression set and list of component expressions plus dynamic segment names. DynamicSet(RegexSet, Vec<(Regex, Vec<&'static str>)>), } impl ResourceDef { /// Constructs a new resource definition from patterns. /// /// Multi-pattern resources can be constructed by providing a slice (or vec) of patterns. /// /// # Panics /// Panics if any path patterns are malformed. /// /// # Examples /// ``` /// use actix_router::ResourceDef; /// /// let resource = ResourceDef::new("/user/{id}"); /// assert!(resource.is_match("/user/123")); /// assert!(!resource.is_match("/user/123/stars")); /// assert!(!resource.is_match("user/1234")); /// assert!(!resource.is_match("/foo")); /// /// let resource = ResourceDef::new(["/profile", "/user/{id}"]); /// assert!(resource.is_match("/profile")); /// assert!(resource.is_match("/user/123")); /// assert!(!resource.is_match("user/123")); /// assert!(!resource.is_match("/foo")); /// ``` pub fn new<T: IntoPatterns>(paths: T) -> Self { Self::construct(paths, false) } /// Constructs a new resource definition using a pattern that performs prefix matching. /// /// More specifically, the regular expressions generated for matching are different when using /// this method vs using `new`; they will not be appended with the `$` meta-character that /// matches the end of an input. /// /// Although it will compile and run correctly, it is meaningless to construct a prefix /// resource definition with a tail segment; use [`new`][Self::new] in this case. /// /// # Panics /// Panics if path pattern is malformed. /// /// # Examples /// ``` /// use actix_router::ResourceDef; /// /// let resource = ResourceDef::prefix("/user/{id}"); /// assert!(resource.is_match("/user/123")); /// assert!(resource.is_match("/user/123/stars")); /// assert!(!resource.is_match("user/123")); /// assert!(!resource.is_match("user/123/stars")); /// assert!(!resource.is_match("/foo")); /// ``` pub fn prefix<T: IntoPatterns>(paths: T) -> Self { ResourceDef::construct(paths, true) } /// Constructs a new resource definition using a string pattern that performs prefix matching, /// ensuring a leading `/` if pattern is not empty. /// /// # Panics /// Panics if path pattern is malformed. /// /// # Examples /// ``` /// use actix_router::ResourceDef; /// /// let resource = ResourceDef::root_prefix("user/{id}"); /// /// assert_eq!(&resource, &ResourceDef::prefix("/user/{id}")); /// assert_eq!(&resource, &ResourceDef::root_prefix("/user/{id}")); /// assert_ne!(&resource, &ResourceDef::new("user/{id}")); /// assert_ne!(&resource, &ResourceDef::new("/user/{id}")); /// /// assert!(resource.is_match("/user/123")); /// assert!(!resource.is_match("user/123")); /// ``` pub fn root_prefix(path: &str) -> Self { ResourceDef::prefix(insert_slash(path).into_owned()) } /// Returns a numeric resource ID. /// /// If not explicitly set using [`set_id`][Self::set_id], this will return `0`. /// /// # Examples /// ``` /// # use actix_router::ResourceDef; /// let mut resource = ResourceDef::new("/root"); /// assert_eq!(resource.id(), 0); /// /// resource.set_id(42); /// assert_eq!(resource.id(), 42); /// ``` pub fn id(&self) -> u16 { self.id } /// Set numeric resource ID. /// /// # Examples /// ``` /// # use actix_router::ResourceDef; /// let mut resource = ResourceDef::new("/root"); /// resource.set_id(42); /// assert_eq!(resource.id(), 42); /// ``` pub fn set_id(&mut self, id: u16) { self.id = id; } /// Returns resource definition name, if set. /// /// # Examples /// ``` /// # use actix_router::ResourceDef; /// let mut resource = ResourceDef::new("/root"); /// assert!(resource.name().is_none()); /// /// resource.set_name("root"); /// assert_eq!(resource.name().unwrap(), "root"); pub fn name(&self) -> Option<&str> { self.name.as_deref() } /// Assigns a new name to the resource. /// /// # Panics /// Panics if `name` is an empty string. /// /// # Examples /// ``` /// # use actix_router::ResourceDef; /// let mut resource = ResourceDef::new("/root"); /// resource.set_name("root"); /// assert_eq!(resource.name().unwrap(), "root"); /// ``` pub fn set_name(&mut self, name: impl Into<String>) { let name = name.into(); assert!(!name.is_empty(), "resource name should not be empty"); self.name = Some(name) } /// Returns `true` if pattern type is prefix. /// /// # Examples /// ``` /// # use actix_router::ResourceDef; /// assert!(ResourceDef::prefix("/user").is_prefix()); /// assert!(!ResourceDef::new("/user").is_prefix()); /// ``` pub fn is_prefix(&self) -> bool { self.is_prefix } /// Returns the pattern string that generated the resource definition. /// /// If definition is constructed with multiple patterns, the first pattern is returned. To get /// all patterns, use [`patterns_iter`][Self::pattern_iter]. If resource has 0 patterns, /// returns `None`. /// /// # Examples /// ``` /// # use actix_router::ResourceDef; /// let mut resource = ResourceDef::new("/user/{id}"); /// assert_eq!(resource.pattern().unwrap(), "/user/{id}"); /// /// let mut resource = ResourceDef::new(["/profile", "/user/{id}"]); /// assert_eq!(resource.pattern(), Some("/profile")); pub fn pattern(&self) -> Option<&str> { match &self.patterns { Patterns::Single(pattern) => Some(pattern.as_str()), Patterns::List(patterns) => patterns.first().map(AsRef::as_ref), } } /// Returns iterator of pattern strings that generated the resource definition. /// /// # Examples /// ``` /// # use actix_router::ResourceDef; /// let mut resource = ResourceDef::new("/root"); /// let mut iter = resource.pattern_iter(); /// assert_eq!(iter.next().unwrap(), "/root"); /// assert!(iter.next().is_none()); /// /// let mut resource = ResourceDef::new(["/root", "/backup"]); /// let mut iter = resource.pattern_iter(); /// assert_eq!(iter.next().unwrap(), "/root"); /// assert_eq!(iter.next().unwrap(), "/backup"); /// assert!(iter.next().is_none()); pub fn pattern_iter(&self) -> impl Iterator<Item = &str> { struct PatternIter<'a> { patterns: &'a Patterns, list_idx: usize, done: bool, } impl<'a> Iterator for PatternIter<'a> { type Item = &'a str; fn next(&mut self) -> Option<Self::Item> { match &self.patterns { Patterns::Single(pattern) => { if self.done { return None; } self.done = true; Some(pattern.as_str()) } Patterns::List(patterns) if patterns.is_empty() => None, Patterns::List(patterns) => match patterns.get(self.list_idx) { Some(pattern) => { self.list_idx += 1; Some(pattern.as_str()) } None => { // fast path future call self.done = true; None } }, } } fn size_hint(&self) -> (usize, Option<usize>) { match &self.patterns { Patterns::Single(_) => (1, Some(1)), Patterns::List(patterns) => (patterns.len(), Some(patterns.len())), } } } PatternIter { patterns: &self.patterns, list_idx: 0, done: false, } } /// Joins two resources. /// /// Resulting resource is prefix if `other` is prefix. /// /// # Examples /// ``` /// # use actix_router::ResourceDef; /// let joined = ResourceDef::prefix("/root").join(&ResourceDef::prefix("/seg")); /// assert_eq!(joined, ResourceDef::prefix("/root/seg")); /// ``` pub fn join(&self, other: &ResourceDef) -> ResourceDef { let patterns = self .pattern_iter() .flat_map(move |this| other.pattern_iter().map(move |other| (this, other))) .map(|(this, other)| { let mut pattern = String::with_capacity(this.len() + other.len()); pattern.push_str(this); pattern.push_str(other); pattern }) .collect::<Vec<_>>(); match patterns.len() { 1 => ResourceDef::construct(&patterns[0], other.is_prefix()), _ => ResourceDef::construct(patterns, other.is_prefix()), } } /// Returns `true` if `path` matches this resource. /// /// The behavior of this method depends on how the `ResourceDef` was constructed. For example, /// static resources will not be able to match as many paths as dynamic and prefix resources. /// See [`ResourceDef`] struct docs for details on resource definition types. /// /// This method will always agree with [`find_match`][Self::find_match] on whether the path /// matches or not. /// /// # Examples /// ``` /// use actix_router::ResourceDef; /// /// // static resource /// let resource = ResourceDef::new("/user"); /// assert!(resource.is_match("/user")); /// assert!(!resource.is_match("/users")); /// assert!(!resource.is_match("/user/123")); /// assert!(!resource.is_match("/foo")); /// /// // dynamic resource /// let resource = ResourceDef::new("/user/{user_id}"); /// assert!(resource.is_match("/user/123")); /// assert!(!resource.is_match("/user/123/stars")); /// /// // prefix resource /// let resource = ResourceDef::prefix("/root"); /// assert!(resource.is_match("/root")); /// assert!(resource.is_match("/root/leaf")); /// assert!(!resource.is_match("/roots")); /// /// // more examples are shown in the `ResourceDef` struct docs /// ``` #[inline] pub fn is_match(&self, path: &str) -> bool { // this function could be expressed as: // `self.find_match(path).is_some()` // but this skips some checks and uses potentially faster regex methods match &self.pat_type { PatternType::Static(pattern) => self.static_match(pattern, path).is_some(), PatternType::Dynamic(re, _) => re.is_match(path), PatternType::DynamicSet(re, _) => re.is_match(path), } } /// Tries to match `path` to this resource, returning the position in the path where the /// match ends. /// /// This method will always agree with [`is_match`][Self::is_match] on whether the path matches /// or not. /// /// # Examples /// ``` /// use actix_router::ResourceDef; /// /// // static resource /// let resource = ResourceDef::new("/user"); /// assert_eq!(resource.find_match("/user"), Some(5)); /// assert!(resource.find_match("/user/").is_none()); /// assert!(resource.find_match("/user/123").is_none()); /// assert!(resource.find_match("/foo").is_none()); /// /// // constant prefix resource /// let resource = ResourceDef::prefix("/user"); /// assert_eq!(resource.find_match("/user"), Some(5)); /// assert_eq!(resource.find_match("/user/"), Some(5)); /// assert_eq!(resource.find_match("/user/123"), Some(5)); /// /// // dynamic prefix resource /// let resource = ResourceDef::prefix("/user/{id}"); /// assert_eq!(resource.find_match("/user/123"), Some(9)); /// assert_eq!(resource.find_match("/user/1234/"), Some(10)); /// assert_eq!(resource.find_match("/user/12345/stars"), Some(11)); /// assert!(resource.find_match("/user/").is_none()); /// /// // multi-pattern resource /// let resource = ResourceDef::new(["/user/{id}", "/profile/{id}"]); /// assert_eq!(resource.find_match("/user/123"), Some(9)); /// assert_eq!(resource.find_match("/profile/1234"), Some(13)); /// ``` pub fn find_match(&self, path: &str) -> Option<usize> { match &self.pat_type { PatternType::Static(pattern) => self.static_match(pattern, path), PatternType::Dynamic(re, _) => Some(re.captures(path)?[1].len()), PatternType::DynamicSet(re, params) => { let idx = re.first_match_idx(path)?; let (ref pattern, _) = params[idx]; Some(pattern.captures(path)?[1].len()) } } } /// Collects dynamic segment values into `resource`. /// /// Returns `true` if `path` matches this resource. /// /// # Examples /// ``` /// use actix_router::{Path, ResourceDef}; /// /// let resource = ResourceDef::prefix("/user/{id}"); /// let mut path = Path::new("/user/123/stars"); /// assert!(resource.capture_match_info(&mut path)); /// assert_eq!(path.get("id").unwrap(), "123"); /// assert_eq!(path.unprocessed(), "/stars"); /// /// let resource = ResourceDef::new("/blob/{path}*"); /// let mut path = Path::new("/blob/HEAD/Cargo.toml"); /// assert!(resource.capture_match_info(&mut path)); /// assert_eq!(path.get("path").unwrap(), "HEAD/Cargo.toml"); /// assert_eq!(path.unprocessed(), ""); /// ``` pub fn capture_match_info<R: Resource>(&self, resource: &mut R) -> bool { self.capture_match_info_fn(resource, |_| true) } /// Collects dynamic segment values into `resource` after matching paths and executing /// check function. /// /// The check function is given a reference to the passed resource and optional arbitrary data. /// This is useful if you want to conditionally match on some non-path related aspect of the /// resource type. /// /// Returns `true` if resource path matches this resource definition _and_ satisfies the /// given check function. /// /// # Examples /// ``` /// use actix_router::{Path, ResourceDef}; /// /// fn try_match(resource: &ResourceDef, path: &mut Path<&str>) -> bool { /// let admin_allowed = std::env::var("ADMIN_ALLOWED").is_ok(); /// /// resource.capture_match_info_fn( /// path, /// // when env var is not set, reject when path contains "admin" /// |path| !(!admin_allowed && path.as_str().contains("admin")), /// ) /// } /// /// let resource = ResourceDef::prefix("/user/{id}"); /// /// // path matches; segment values are collected into path /// let mut path = Path::new("/user/james/stars"); /// assert!(try_match(&resource, &mut path)); /// assert_eq!(path.get("id").unwrap(), "james"); /// assert_eq!(path.unprocessed(), "/stars"); /// /// // path matches but fails check function; no segments are collected /// let mut path = Path::new("/user/admin/stars"); /// assert!(!try_match(&resource, &mut path)); /// assert_eq!(path.unprocessed(), "/user/admin/stars"); /// ``` pub fn capture_match_info_fn<R, F>(&self, resource: &mut R, check_fn: F) -> bool where R: Resource, F: FnOnce(&R) -> bool, { let mut segments = <[PathItem; MAX_DYNAMIC_SEGMENTS]>::default(); let path = resource.resource_path(); let path_str = path.unprocessed(); let (matched_len, matched_vars) = match &self.pat_type { PatternType::Static(pattern) => match self.static_match(pattern, path_str) { Some(len) => (len, None), None => return false, }, PatternType::Dynamic(re, names) => { let captures = match re.captures(path.unprocessed()) { Some(captures) => captures, _ => return false, }; for (no, name) in names.iter().enumerate() { if let Some(m) = captures.name(name) { segments[no] = PathItem::Segment(m.start() as u16, m.end() as u16); } else { error!("Dynamic path match but not all segments found: {}", name); return false; } } (captures[1].len(), Some(names)) } PatternType::DynamicSet(re, params) => { let path = path.unprocessed(); let (pattern, names) = match re.first_match_idx(path) { Some(idx) => &params[idx], _ => return false, }; let captures = match pattern.captures(path.path()) { Some(captures) => captures, _ => return false, }; for (no, name) in names.iter().enumerate() { if let Some(m) = captures.name(name) { segments[no] = PathItem::Segment(m.start() as u16, m.end() as u16); } else { error!("Dynamic path match but not all segments found: {}", name); return false; } } (captures[1].len(), Some(names)) } }; if !check_fn(resource) { return false; } // Modify `path` to skip matched part and store matched segments let path = resource.resource_path(); if let Some(vars) = matched_vars { for i in 0..vars.len() { path.add(vars[i], mem::take(&mut segments[i])); } } path.skip(matched_len as u16); true } /// Assembles resource path using a closure that maps variable segment names to values. fn build_resource_path<F, I>(&self, path: &mut String, mut vars: F) -> bool where F: FnMut(&str) -> Option<I>, I: AsRef<str>, { for segment in &self.segments { match segment { PatternSegment::Const(val) => path.push_str(val), PatternSegment::Var(name) => match vars(name) { Some(val) => path.push_str(val.as_ref()), _ => return false, }, } } true } /// Assembles full resource path from iterator of dynamic segment values. /// /// Returns `true` on success. /// /// For multi-pattern resources, the first pattern is used under the assumption that it would be /// equivalent to any other choice. /// /// # Examples /// ``` /// # use actix_router::ResourceDef; /// let mut s = String::new(); /// let resource = ResourceDef::new("/user/{id}/post/{title}"); /// /// assert!(resource.resource_path_from_iter(&mut s, &["123", "my-post"])); /// assert_eq!(s, "/user/123/post/my-post"); /// ``` pub fn resource_path_from_iter<I>(&self, path: &mut String, values: I) -> bool where I: IntoIterator, I::Item: AsRef<str>, { let mut iter = values.into_iter(); self.build_resource_path(path, |_| iter.next()) } /// Assembles resource path from map of dynamic segment values. /// /// Returns `true` on success. /// /// For multi-pattern resources, the first pattern is used under the assumption that it would be /// equivalent to any other choice. /// /// # Examples /// ``` /// # use std::collections::HashMap; /// # use actix_router::ResourceDef; /// let mut s = String::new(); /// let resource = ResourceDef::new("/user/{id}/post/{title}"); /// /// let mut map = HashMap::new(); /// map.insert("id", "123"); /// map.insert("title", "my-post"); /// /// assert!(resource.resource_path_from_map(&mut s, &map)); /// assert_eq!(s, "/user/123/post/my-post"); /// ``` pub fn resource_path_from_map<K, V, S>( &self, path: &mut String, values: &HashMap<K, V, S>, ) -> bool where K: Borrow<str> + Eq + Hash, V: AsRef<str>, S: BuildHasher, { self.build_resource_path(path, |name| values.get(name)) } /// Returns true if `prefix` acts as a proper prefix (i.e., separated by a slash) in `path`. fn static_match(&self, pattern: &str, path: &str) -> Option<usize> { let rem = path.strip_prefix(pattern)?; match self.is_prefix { // resource is not a prefix so an exact match is needed false if rem.is_empty() => Some(pattern.len()), // resource is a prefix so rem should start with a path delimiter true if rem.is_empty() || rem.starts_with('/') => Some(pattern.len()), // otherwise, no match _ => None, } } fn construct<T: IntoPatterns>(paths: T, is_prefix: bool) -> Self { let patterns = paths.patterns(); let (pat_type, segments) = match &patterns { Patterns::Single(pattern) => ResourceDef::parse(pattern, is_prefix, false), // since zero length pattern sets are possible // just return a useless `ResourceDef` Patterns::List(patterns) if patterns.is_empty() => ( PatternType::DynamicSet(RegexSet::empty(), Vec::new()), Vec::new(), ), Patterns::List(patterns) => { let mut re_set = Vec::with_capacity(patterns.len()); let mut pattern_data = Vec::new(); let mut segments = None; for pattern in patterns { match ResourceDef::parse(pattern, is_prefix, true) { (PatternType::Dynamic(re, names), segs) => { re_set.push(re.as_str().to_owned()); pattern_data.push((re, names)); segments.get_or_insert(segs); } _ => unreachable!(), } } let pattern_re_set = RegexSet::new(re_set); let segments = segments.unwrap_or_default(); ( PatternType::DynamicSet(pattern_re_set, pattern_data), segments, ) } }; ResourceDef { id: 0, name: None, patterns, is_prefix, pat_type, segments, } } /// Parses a dynamic segment definition from a pattern. /// /// The returned tuple includes: /// - the segment descriptor, either `Var` or `Tail` /// - the segment's regex to check values against /// - the remaining, unprocessed string slice /// - whether the parsed parameter represents a tail pattern /// /// # Panics /// Panics if given patterns does not contain a dynamic segment. fn parse_param(pattern: &str) -> (PatternSegment, String, &str, bool) { const DEFAULT_PATTERN: &str = "[^/]+"; const DEFAULT_PATTERN_TAIL: &str = ".*"; let mut params_nesting = 0usize; let close_idx = pattern .find(|c| match c { '{' => { params_nesting += 1; false } '}' => { params_nesting -= 1; params_nesting == 0 } _ => false, }) .unwrap_or_else(|| { panic!( r#"pattern "{}" contains malformed dynamic segment"#, pattern ) }); let (mut param, mut unprocessed) = pattern.split_at(close_idx + 1); // remove outer curly brackets param = &param[1..param.len() - 1]; let tail = unprocessed == "*"; let (name, pattern) = match param.find(':') { Some(idx) => { assert!(!tail, "custom regex is not supported for tail match"); let (name, pattern) = param.split_at(idx); (name, &pattern[1..]) } None => ( param, if tail { unprocessed = &unprocessed[1..]; DEFAULT_PATTERN_TAIL } else { DEFAULT_PATTERN }, ), }; let segment = PatternSegment::Var(name.to_string()); let regex = format!(r"(?P<{}>{})", &name, &pattern); (segment, regex, unprocessed, tail) } /// Parse `pattern` using `is_prefix` and `force_dynamic` flags. /// /// Parameters: /// - `is_prefix`: Use `true` if `pattern` should be treated as a prefix; i.e., a conforming /// path will be a match even if it has parts remaining to process /// - `force_dynamic`: Use `true` to disallow the return of static and prefix segments. /// /// The returned tuple includes: /// - the pattern type detected, either `Static`, `Prefix`, or `Dynamic` /// - a list of segment descriptors from the pattern fn parse( pattern: &str, is_prefix: bool, force_dynamic: bool, ) -> (PatternType, Vec<PatternSegment>) { if !force_dynamic && pattern.find('{').is_none() && !pattern.ends_with('*') { // pattern is static return ( PatternType::Static(pattern.to_owned()), vec![PatternSegment::Const(pattern.to_owned())], ); } let mut unprocessed = pattern; let mut segments = Vec::new(); let mut re = format!("{}^", REGEX_FLAGS); let mut dyn_segment_count = 0; let mut has_tail_segment = false; while let Some(idx) = unprocessed.find('{') { let (prefix, rem) = unprocessed.split_at(idx); segments.push(PatternSegment::Const(prefix.to_owned())); re.push_str(&escape(prefix)); let (param_pattern, re_part, rem, tail) = Self::parse_param(rem); if tail { has_tail_segment = true; } segments.push(param_pattern); re.push_str(&re_part); unprocessed = rem; dyn_segment_count += 1; } if is_prefix && has_tail_segment { // tail segments in prefixes have no defined semantics #[cfg(not(test))] tracing::warn!( "Prefix resources should not have tail segments. \ Use `ResourceDef::new` constructor. \ This may become a panic in the future." ); // panic in tests to make this case detectable #[cfg(test)] panic!("prefix resource definitions should not have tail segments"); } if unprocessed.ends_with('*') { // unnamed tail segment #[cfg(not(test))] tracing::warn!( "Tail segments must have names. \ Consider `.../{{tail}}*`. \ This may become a panic in the future." ); // panic in tests to make this case detectable #[cfg(test)] panic!("tail segments must have names"); } else if !has_tail_segment && !unprocessed.is_empty() { // prevent `Const("")` element from being added after last dynamic segment segments.push(PatternSegment::Const(unprocessed.to_owned())); re.push_str(&escape(unprocessed)); } assert!( dyn_segment_count <= MAX_DYNAMIC_SEGMENTS, "Only {} dynamic segments are allowed, provided: {}", MAX_DYNAMIC_SEGMENTS, dyn_segment_count ); // Store the pattern in capture group #1 to have context info outside it let mut re = format!("({})", re); // Ensure the match ends at a segment boundary if !has_tail_segment { if is_prefix { re.push_str(r"(/|$)"); } else { re.push('$'); } } let re = match Regex::new(&re) { Ok(re) => re, Err(err) => panic!("Wrong path pattern: \"{}\" {}", pattern, err), }; // `Bok::leak(Box::new(name))` is an intentional memory leak. In typical applications the // routing table is only constructed once (per worker) so leak is bounded. If you are // constructing `ResourceDef`s more than once in your application's lifecycle you would // expect a linear increase in leaked memory over time. let names = re .capture_names() .filter_map(|name| name.map(|name| Box::leak(Box::new(name.to_owned())).as_str())) .collect(); (PatternType::Dynamic(re, names), segments) } } impl Eq for ResourceDef {} impl PartialEq for ResourceDef { fn eq(&self, other: &ResourceDef) -> bool { self.patterns == other.patterns && self.is_prefix == other.is_prefix } } impl Hash for ResourceDef { fn hash<H: Hasher>(&self, state: &mut H) { self.patterns.hash(state); } } impl<'a> From<&'a str> for ResourceDef { fn from(path: &'a str) -> ResourceDef { ResourceDef::new(path) } } impl From<String> for ResourceDef { fn from(path: String) -> ResourceDef { ResourceDef::new(path) } } pub(crate) fn insert_slash(path: &str) -> Cow<'_, str> { if !path.is_empty() && !path.starts_with('/') { let mut new_path = String::with_capacity(path.len() + 1); new_path.push('/'); new_path.push_str(path); Cow::Owned(new_path) } else { Cow::Borrowed(path) } } #[cfg(test)] mod tests { use super::*; use crate::Path; #[test] fn equivalence() { assert_eq!( ResourceDef::root_prefix("/root"), ResourceDef::prefix("/root") ); assert_eq!( ResourceDef::root_prefix("root"), ResourceDef::prefix("/root") ); assert_eq!( ResourceDef::root_prefix("/{id}"), ResourceDef::prefix("/{id}") ); assert_eq!( ResourceDef::root_prefix("{id}"), ResourceDef::prefix("/{id}") ); assert_eq!(ResourceDef::new("/"), ResourceDef::new(["/"])); assert_eq!(ResourceDef::new("/"), ResourceDef::new(vec!["/"])); assert_ne!(ResourceDef::new(""), ResourceDef::prefix("")); assert_ne!(ResourceDef::new("/"), ResourceDef::prefix("/")); assert_ne!(ResourceDef::new("/{id}"), ResourceDef::prefix("/{id}")); } #[test] fn parse_static() { let re = ResourceDef::new(""); assert!(!re.is_prefix()); assert!(re.is_match("")); assert!(!re.is_match("/")); assert_eq!(re.find_match(""), Some(0)); assert_eq!(re.find_match("/"), None); let re = ResourceDef::new("/"); assert!(re.is_match("/")); assert!(!re.is_match("")); assert!(!re.is_match("/foo")); let re = ResourceDef::new("/name"); assert!(re.is_match("/name")); assert!(!re.is_match("/name1")); assert!(!re.is_match("/name/")); assert!(!re.is_match("/name~")); let mut path = Path::new("/name"); assert!(re.capture_match_info(&mut path)); assert_eq!(path.unprocessed(), ""); assert_eq!(re.find_match("/name"), Some(5)); assert_eq!(re.find_match("/name1"), None); assert_eq!(re.find_match("/name/"), None); assert_eq!(re.find_match("/name~"), None); let re = ResourceDef::new("/name/"); assert!(re.is_match("/name/")); assert!(!re.is_match("/name")); assert!(!re.is_match("/name/gs")); let re = ResourceDef::new("/user/profile"); assert!(re.is_match("/user/profile")); assert!(!re.is_match("/user/profile/profile")); let mut path = Path::new("/user/profile"); assert!(re.capture_match_info(&mut path)); assert_eq!(path.unprocessed(), ""); } #[test] fn parse_param() { let re = ResourceDef::new("/user/{id}"); assert!(re.is_match("/user/profile")); assert!(re.is_match("/user/2345")); assert!(!re.is_match("/user/2345/")); assert!(!re.is_match("/user/2345/sdg")); let mut path = Path::new("/user/profile"); assert!(re.capture_match_info(&mut path)); assert_eq!(path.get("id").unwrap(), "profile"); assert_eq!(path.unprocessed(), ""); let mut path = Path::new("/user/1245125"); assert!(re.capture_match_info(&mut path)); assert_eq!(path.get("id").unwrap(), "1245125"); assert_eq!(path.unprocessed(), ""); let re = ResourceDef::new("/v{version}/resource/{id}"); assert!(re.is_match("/v1/resource/320120")); assert!(!re.is_match("/v/resource/1")); assert!(!re.is_match("/resource")); let mut path = Path::new("/v151/resource/adage32"); assert!(re.capture_match_info(&mut path)); assert_eq!(path.get("version").unwrap(), "151"); assert_eq!(path.get("id").unwrap(), "adage32"); assert_eq!(path.unprocessed(), ""); let re = ResourceDef::new("/{id:[[:digit:]]{6}}"); assert!(re.is_match("/012345")); assert!(!re.is_match("/012")); assert!(!re.is_match("/01234567")); assert!(!re.is_match("/XXXXXX")); let mut path = Path::new("/012345"); assert!(re.capture_match_info(&mut path)); assert_eq!(path.get("id").unwrap(), "012345"); assert_eq!(path.unprocessed(), ""); } #[allow(clippy::cognitive_complexity)] #[test] fn dynamic_set() { let re = ResourceDef::new(vec![ "/user/{id}", "/v{version}/resource/{id}", "/{id:[[:digit:]]{6}}", "/static", ]); assert!(re.is_match("/user/profile")); assert!(re.is_match("/user/2345")); assert!(!re.is_match("/user/2345/")); assert!(!re.is_match("/user/2345/sdg")); let mut path = Path::new("/user/profile"); assert!(re.capture_match_info(&mut path)); assert_eq!(path.get("id").unwrap(), "profile"); assert_eq!(path.unprocessed(), ""); let mut path = Path::new("/user/1245125"); assert!(re.capture_match_info(&mut path)); assert_eq!(path.get("id").unwrap(), "1245125"); assert_eq!(path.unprocessed(), ""); assert!(re.is_match("/v1/resource/320120")); assert!(!re.is_match("/v/resource/1")); assert!(!re.is_match("/resource")); let mut path = Path::new("/v151/resource/adage32"); assert!(re.capture_match_info(&mut path)); assert_eq!(path.get("version").unwrap(), "151"); assert_eq!(path.get("id").unwrap(), "adage32"); assert!(re.is_match("/012345")); assert!(!re.is_match("/012")); assert!(!re.is_match("/01234567")); assert!(!re.is_match("/XXXXXX")); assert!(re.is_match("/static")); assert!(!re.is_match("/a/static")); assert!(!re.is_match("/static/a")); let mut path = Path::new("/012345"); assert!(re.capture_match_info(&mut path)); assert_eq!(path.get("id").unwrap(), "012345"); let re = ResourceDef::new([ "/user/{id}", "/v{version}/resource/{id}", "/{id:[[:digit:]]{6}}", ]); assert!(re.is_match("/user/profile")); assert!(re.is_match("/user/2345")); assert!(!re.is_match("/user/2345/")); assert!(!re.is_match("/user/2345/sdg")); let re = ResourceDef::new([ "/user/{id}".to_string(), "/v{version}/resource/{id}".to_string(), "/{id:[[:digit:]]{6}}".to_string(), ]); assert!(re.is_match("/user/profile")); assert!(re.is_match("/user/2345")); assert!(!re.is_match("/user/2345/")); assert!(!re.is_match("/user/2345/sdg")); } #[test] fn dynamic_set_prefix() { let re = ResourceDef::prefix(vec!["/u/{id}", "/{id:[[:digit:]]{3}}"]); assert_eq!(re.find_match("/u/abc"), Some(6)); assert_eq!(re.find_match("/u/abc/123"), Some(6)); assert_eq!(re.find_match("/s/user/profile"), None); assert_eq!(re.find_match("/123"), Some(4)); assert_eq!(re.find_match("/123/456"), Some(4)); assert_eq!(re.find_match("/12345"), None); let mut path = Path::new("/151/res"); assert!(re.capture_match_info(&mut path)); assert_eq!(path.get("id").unwrap(), "151"); assert_eq!(path.unprocessed(), "/res"); } #[test] fn parse_tail() { let re = ResourceDef::new("/user/-{id}*"); let mut path = Path::new("/user/-profile"); assert!(re.capture_match_info(&mut path)); assert_eq!(path.get("id").unwrap(), "profile"); let mut path = Path::new("/user/-2345"); assert!(re.capture_match_info(&mut path)); assert_eq!(path.get("id").unwrap(), "2345"); let mut path = Path::new("/user/-2345/"); assert!(re.capture_match_info(&mut path)); assert_eq!(path.get("id").unwrap(), "2345/"); let mut path = Path::new("/user/-2345/sdg"); assert!(re.capture_match_info(&mut path)); assert_eq!(path.get("id").unwrap(), "2345/sdg"); } #[test] fn static_tail() { let re = ResourceDef::new("/user{tail}*"); assert!(re.is_match("/users")); assert!(re.is_match("/user-foo")); assert!(re.is_match("/user/profile")); assert!(re.is_match("/user/2345")); assert!(re.is_match("/user/2345/")); assert!(re.is_match("/user/2345/sdg")); assert!(!re.is_match("/foo/profile")); let re = ResourceDef::new("/user/{tail}*"); assert!(re.is_match("/user/profile")); assert!(re.is_match("/user/2345")); assert!(re.is_match("/user/2345/")); assert!(re.is_match("/user/2345/sdg")); assert!(!re.is_match("/foo/profile")); } #[test] fn dynamic_tail() { let re = ResourceDef::new("/user/{id}/{tail}*"); assert!(!re.is_match("/user/2345")); let mut path = Path::new("/user/2345/sdg"); assert!(re.capture_match_info(&mut path)); assert_eq!(path.get("id").unwrap(), "2345"); assert_eq!(path.get("tail").unwrap(), "sdg"); assert_eq!(path.unprocessed(), ""); } #[test] fn newline_patterns_and_paths() { let re = ResourceDef::new("/user/a\nb"); assert!(re.is_match("/user/a\nb")); assert!(!re.is_match("/user/a\nb/profile")); let re = ResourceDef::new("/a{x}b/test/a{y}b"); let mut path = Path::new("/a\nb/test/a\nb"); assert!(re.capture_match_info(&mut path)); assert_eq!(path.get("x").unwrap(), "\n"); assert_eq!(path.get("y").unwrap(), "\n"); let re = ResourceDef::new("/user/{tail}*"); assert!(re.is_match("/user/a\nb/")); let re = ResourceDef::new("/user/{id}*"); let mut path = Path::new("/user/a\nb/a\nb"); assert!(re.capture_match_info(&mut path)); assert_eq!(path.get("id").unwrap(), "a\nb/a\nb"); let re = ResourceDef::new("/user/{id:.*}"); let mut path = Path::new("/user/a\nb/a\nb"); assert!(re.capture_match_info(&mut path)); assert_eq!(path.get("id").unwrap(), "a\nb/a\nb"); } #[cfg(feature = "http")] #[test] fn parse_urlencoded_param() { let re = ResourceDef::new("/user/{id}/test"); let mut path = Path::new("/user/2345/test"); assert!(re.capture_match_info(&mut path)); assert_eq!(path.get("id").unwrap(), "2345"); let mut path = Path::new("/user/qwe%25/test"); assert!(re.capture_match_info(&mut path)); assert_eq!(path.get("id").unwrap(), "qwe%25"); let uri = http::Uri::try_from("/user/qwe%25/test").unwrap(); let mut path = Path::new(uri); assert!(re.capture_match_info(&mut path)); assert_eq!(path.get("id").unwrap(), "qwe%25"); } #[test] fn prefix_static() { let re = ResourceDef::prefix("/name"); assert!(re.is_prefix()); assert!(re.is_match("/name")); assert!(re.is_match("/name/")); assert!(re.is_match("/name/test/test")); assert!(!re.is_match("/name1")); assert!(!re.is_match("/name~")); let mut path = Path::new("/name"); assert!(re.capture_match_info(&mut path)); assert_eq!(path.unprocessed(), ""); let mut path = Path::new("/name/test"); assert!(re.capture_match_info(&mut path)); assert_eq!(path.unprocessed(), "/test"); assert_eq!(re.find_match("/name"), Some(5)); assert_eq!(re.find_match("/name/"), Some(5)); assert_eq!(re.find_match("/name/test/test"), Some(5)); assert_eq!(re.find_match("/name1"), None); assert_eq!(re.find_match("/name~"), None); let re = ResourceDef::prefix("/name/"); assert!(re.is_match("/name/")); assert!(re.is_match("/name//gs")); assert!(!re.is_match("/name/gs")); assert!(!re.is_match("/name")); let mut path = Path::new("/name/gs"); assert!(!re.capture_match_info(&mut path)); let mut path = Path::new("/name//gs"); assert!(re.capture_match_info(&mut path)); assert_eq!(path.unprocessed(), "/gs"); let re = ResourceDef::root_prefix("name/"); assert!(re.is_match("/name/")); assert!(re.is_match("/name//gs")); assert!(!re.is_match("/name/gs")); assert!(!re.is_match("/name")); let mut path = Path::new("/name/gs"); assert!(!re.capture_match_info(&mut path)); } #[test] fn prefix_dynamic() { let re = ResourceDef::prefix("/{name}"); assert!(re.is_prefix()); assert!(re.is_match("/name/")); assert!(re.is_match("/name/gs")); assert!(re.is_match("/name")); assert_eq!(re.find_match("/name/"), Some(5)); assert_eq!(re.find_match("/name/gs"), Some(5)); assert_eq!(re.find_match("/name"), Some(5)); assert_eq!(re.find_match(""), None); let mut path = Path::new("/test2/"); assert!(re.capture_match_info(&mut path)); assert_eq!(&path["name"], "test2"); assert_eq!(&path[0], "test2"); assert_eq!(path.unprocessed(), "/"); let mut path = Path::new("/test2/subpath1/subpath2/index.html"); assert!(re.capture_match_info(&mut path)); assert_eq!(&path["name"], "test2"); assert_eq!(&path[0], "test2"); assert_eq!(path.unprocessed(), "/subpath1/subpath2/index.html"); let resource = ResourceDef::prefix("/user"); // input string shorter than prefix assert!(resource.find_match("/foo").is_none()); } #[test] fn prefix_empty() { let re = ResourceDef::prefix(""); assert!(re.is_prefix()); assert!(re.is_match("")); assert!(re.is_match("/")); assert!(re.is_match("/name/test/test")); } #[test] fn build_path_list() { let mut s = String::new(); let resource = ResourceDef::new("/user/{item1}/test"); assert!(resource.resource_path_from_iter(&mut s, &mut ["user1"].iter())); assert_eq!(s, "/user/user1/test"); let mut s = String::new(); let resource = ResourceDef::new("/user/{item1}/{item2}/test"); assert!(resource.resource_path_from_iter(&mut s, &mut ["item", "item2"].iter())); assert_eq!(s, "/user/item/item2/test"); let mut s = String::new(); let resource = ResourceDef::new("/user/{item1}/{item2}"); assert!(resource.resource_path_from_iter(&mut s, &mut ["item", "item2"].iter())); assert_eq!(s, "/user/item/item2"); let mut s = String::new(); let resource = ResourceDef::new("/user/{item1}/{item2}/"); assert!(resource.resource_path_from_iter(&mut s, &mut ["item", "item2"].iter())); assert_eq!(s, "/user/item/item2/"); let mut s = String::new(); assert!(!resource.resource_path_from_iter(&mut s, &mut ["item"].iter())); let mut s = String::new(); assert!(resource.resource_path_from_iter(&mut s, &mut ["item", "item2"].iter())); assert_eq!(s, "/user/item/item2/"); assert!(!resource.resource_path_from_iter(&mut s, &mut ["item"].iter())); let mut s = String::new(); assert!(resource.resource_path_from_iter( &mut s, #[allow(clippy::useless_vec)] &mut vec!["item", "item2"].iter() )); assert_eq!(s, "/user/item/item2/"); } #[test] fn multi_pattern_build_path() { let resource = ResourceDef::new(["/user/{id}", "/profile/{id}"]); let mut s = String::new(); assert!(resource.resource_path_from_iter(&mut s, &mut ["123"].iter())); assert_eq!(s, "/user/123"); } #[test] fn multi_pattern_capture_segment_values() { let resource = ResourceDef::new(["/user/{id}", "/profile/{id}"]); let mut path = Path::new("/user/123"); assert!(resource.capture_match_info(&mut path)); assert!(path.get("id").is_some()); let mut path = Path::new("/profile/123"); assert!(resource.capture_match_info(&mut path)); assert!(path.get("id").is_some()); let resource = ResourceDef::new(["/user/{id}", "/profile/{uid}"]); let mut path = Path::new("/user/123"); assert!(resource.capture_match_info(&mut path)); assert!(path.get("id").is_some()); assert!(path.get("uid").is_none()); let mut path = Path::new("/profile/123"); assert!(resource.capture_match_info(&mut path)); assert!(path.get("id").is_none()); assert!(path.get("uid").is_some()); } #[test] fn dynamic_prefix_proper_segmentation() { let resource = ResourceDef::prefix(r"/id/{id:\d{3}}"); assert!(resource.is_match("/id/123")); assert!(resource.is_match("/id/123/foo")); assert!(!resource.is_match("/id/1234")); assert!(!resource.is_match("/id/123a")); assert_eq!(resource.find_match("/id/123"), Some(7)); assert_eq!(resource.find_match("/id/123/foo"), Some(7)); assert_eq!(resource.find_match("/id/1234"), None); assert_eq!(resource.find_match("/id/123a"), None); } #[test] fn build_path_map() { let resource = ResourceDef::new("/user/{item1}/{item2}/"); let mut map = HashMap::new(); map.insert("item1", "item"); let mut s = String::new(); assert!(!resource.resource_path_from_map(&mut s, &map)); map.insert("item2", "item2"); let mut s = String::new(); assert!(resource.resource_path_from_map(&mut s, &map)); assert_eq!(s, "/user/item/item2/"); } #[test] fn build_path_tail() { let resource = ResourceDef::new("/user/{item1}*"); let mut s = String::new(); assert!(!resource.resource_path_from_iter(&mut s, &mut [""; 0].iter())); let mut s = String::new(); assert!(resource.resource_path_from_iter(&mut s, &mut ["user1"].iter())); assert_eq!(s, "/user/user1"); let mut s = String::new(); let mut map = HashMap::new(); map.insert("item1", "item"); assert!(resource.resource_path_from_map(&mut s, &map)); assert_eq!(s, "/user/item"); } #[test] fn prefix_trailing_slash() { // The prefix "/abc/" matches two segments: ["user", ""] // These are not prefixes let re = ResourceDef::prefix("/abc/"); assert_eq!(re.find_match("/abc/def"), None); assert_eq!(re.find_match("/abc//def"), Some(5)); let re = ResourceDef::prefix("/{id}/"); assert_eq!(re.find_match("/abc/def"), None); assert_eq!(re.find_match("/abc//def"), Some(5)); } #[test] fn join() { // test joined defs match the same paths as each component separately fn seq_find_match(re1: &ResourceDef, re2: &ResourceDef, path: &str) -> Option<usize> { let len1 = re1.find_match(path)?; let len2 = re2.find_match(&path[len1..])?; Some(len1 + len2) } macro_rules! join_test { ($pat1:expr, $pat2:expr => $($test:expr),+) => {{ let pat1 = $pat1; let pat2 = $pat2; $({ let _path = $test; let (re1, re2) = (ResourceDef::prefix(pat1), ResourceDef::new(pat2)); let _seq = seq_find_match(&re1, &re2, _path); let _join = re1.join(&re2).find_match(_path); assert_eq!( _seq, _join, "patterns: prefix {:?}, {:?}; mismatch on \"{}\"; seq={:?}; join={:?}", pat1, pat2, _path, _seq, _join ); assert!(!re1.join(&re2).is_prefix()); let (re1, re2) = (ResourceDef::prefix(pat1), ResourceDef::prefix(pat2)); let _seq = seq_find_match(&re1, &re2, _path); let _join = re1.join(&re2).find_match(_path); assert_eq!( _seq, _join, "patterns: prefix {:?}, prefix {:?}; mismatch on \"{}\"; seq={:?}; join={:?}", pat1, pat2, _path, _seq, _join ); assert!(re1.join(&re2).is_prefix()); })+ }} } join_test!("", "" => "", "/hello", "/"); join_test!("/user", "" => "", "/user", "/user/123", "/user11", "user", "user/123"); join_test!("", "/user" => "", "/user", "foo", "/user11", "user", "user/123"); join_test!("/user", "/xx" => "", "", "/", "/user", "/xx", "/userxx", "/user/xx"); join_test!(["/ver/{v}", "/v{v}"], ["/req/{req}", "/{req}"] => "/v1/abc", "/ver/1/abc", "/v1/req/abc", "/ver/1/req/abc", "/v1/abc/def", "/ver1/req/abc/def", "", "/", "/v1/"); } #[test] fn match_methods_agree() { macro_rules! match_methods_agree { ($pat:expr => $($test:expr),+) => {{ match_methods_agree!(finish $pat, ResourceDef::new($pat), $($test),+); }}; (prefix $pat:expr => $($test:expr),+) => {{ match_methods_agree!(finish $pat, ResourceDef::prefix($pat), $($test),+); }}; (finish $pat:expr, $re:expr, $($test:expr),+) => {{ let re = $re; $({ let _is = re.is_match($test); let _find = re.find_match($test).is_some(); assert_eq!( _is, _find, "pattern: {:?}; mismatch on \"{}\"; is={}; find={}", $pat, $test, _is, _find ); })+ }} } match_methods_agree!("" => "", "/", "/foo"); match_methods_agree!("/" => "", "/", "/foo"); match_methods_agree!("/user" => "user", "/user", "/users", "/user/123", "/foo"); match_methods_agree!("/v{v}" => "v", "/v", "/v1", "/v222", "/foo"); match_methods_agree!(["/v{v}", "/version/{v}"] => "/v", "/v1", "/version", "/version/1", "/foo"); match_methods_agree!("/path{tail}*" => "/path", "/path1", "/path/123"); match_methods_agree!("/path/{tail}*" => "/path", "/path1", "/path/123"); match_methods_agree!(prefix "" => "", "/", "/foo"); match_methods_agree!(prefix "/user" => "user", "/user", "/users", "/user/123", "/foo"); match_methods_agree!(prefix r"/id/{id:\d{3}}" => "/id/123", "/id/1234"); match_methods_agree!(["/v{v}", "/ver/{v}"] => "", "s/v", "/v1", "/v1/xx", "/ver/i3/5", "/ver/1"); } #[test] #[should_panic] fn duplicate_segment_name() { ResourceDef::new("/user/{id}/post/{id}"); } #[test] #[should_panic] fn invalid_dynamic_segment_delimiter() { ResourceDef::new("/user/{username"); } #[test] #[should_panic] fn invalid_dynamic_segment_name() { ResourceDef::new("/user/{}"); } #[test] #[should_panic] fn invalid_too_many_dynamic_segments() { // valid ResourceDef::new("/{a}/{b}/{c}/{d}/{e}/{f}/{g}/{h}/{i}/{j}/{k}/{l}/{m}/{n}/{o}/{p}"); // panics ResourceDef::new("/{a}/{b}/{c}/{d}/{e}/{f}/{g}/{h}/{i}/{j}/{k}/{l}/{m}/{n}/{o}/{p}/{q}"); } #[test] #[should_panic] fn invalid_custom_regex_for_tail() { ResourceDef::new(r"/{tail:\d+}*"); } #[test] #[should_panic] fn invalid_unnamed_tail_segment() { ResourceDef::new("/*"); } #[test] #[should_panic] fn prefix_plus_tail_match_disallowed() { ResourceDef::prefix("/user/{id}*"); } }
use crate::Path; // TODO: this trait is necessary, document it // see impl Resource for ServiceRequest pub trait Resource { /// Type of resource's path returned in `resource_path`. type Path: ResourcePath; fn resource_path(&mut self) -> &mut Path<Self::Path>; } pub trait ResourcePath { fn path(&self) -> &str; } impl ResourcePath for String { fn path(&self) -> &str { self.as_str() } } impl<'a> ResourcePath for &'a str { fn path(&self) -> &str { self } } impl ResourcePath for bytestring::ByteString { fn path(&self) -> &str { self } } #[cfg(feature = "http")] impl ResourcePath for http::Uri { fn path(&self) -> &str { self.path() } }
use crate::{IntoPatterns, Resource, ResourceDef}; #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub struct ResourceId(pub u16); /// Resource router. /// /// It matches a [routing resource](Resource) to an ordered list of _routes_. Each is defined by a /// single [`ResourceDef`] and contains two types of custom data: /// 1. The route _value_, of the generic type `T`. /// 1. Some _context_ data, of the generic type `U`, which is only provided to the check function in /// [`recognize_fn`](Self::recognize_fn). This parameter defaults to `()` and can be omitted if /// not required. pub struct Router<T, U = ()> { routes: Vec<(ResourceDef, T, U)>, } impl<T, U> Router<T, U> { /// Constructs new `RouterBuilder` with empty route list. pub fn build() -> RouterBuilder<T, U> { RouterBuilder { routes: Vec::new() } } /// Finds the value in the router that matches a given [routing resource](Resource). /// /// The match result, including the captured dynamic segments, in the `resource`. pub fn recognize<R>(&self, resource: &mut R) -> Option<(&T, ResourceId)> where R: Resource, { self.recognize_fn(resource, |_, _| true) } /// Same as [`recognize`](Self::recognize) but returns a mutable reference to the matched value. pub fn recognize_mut<R>(&mut self, resource: &mut R) -> Option<(&mut T, ResourceId)> where R: Resource, { self.recognize_mut_fn(resource, |_, _| true) } /// Finds the value in the router that matches a given [routing resource](Resource) and passes /// an additional predicate check using context data. /// /// Similar to [`recognize`](Self::recognize). However, before accepting the route as matched, /// the `check` closure is executed, passing the resource and each route's context data. If the /// closure returns true then the match result is stored into `resource` and a reference to /// the matched _value_ is returned. pub fn recognize_fn<R, F>(&self, resource: &mut R, mut check: F) -> Option<(&T, ResourceId)> where R: Resource, F: FnMut(&R, &U) -> bool, { for (rdef, val, ctx) in self.routes.iter() { if rdef.capture_match_info_fn(resource, |res| check(res, ctx)) { return Some((val, ResourceId(rdef.id()))); } } None } /// Same as [`recognize_fn`](Self::recognize_fn) but returns a mutable reference to the matched /// value. pub fn recognize_mut_fn<R, F>( &mut self, resource: &mut R, mut check: F, ) -> Option<(&mut T, ResourceId)> where R: Resource, F: FnMut(&R, &U) -> bool, { for (rdef, val, ctx) in self.routes.iter_mut() { if rdef.capture_match_info_fn(resource, |res| check(res, ctx)) { return Some((val, ResourceId(rdef.id()))); } } None } } /// Builder for an ordered [routing](Router) list. pub struct RouterBuilder<T, U = ()> { routes: Vec<(ResourceDef, T, U)>, } impl<T, U> RouterBuilder<T, U> { /// Adds a new route to the end of the routing list. /// /// Returns mutable references to elements of the new route. pub fn push( &mut self, rdef: ResourceDef, val: T, ctx: U, ) -> (&mut ResourceDef, &mut T, &mut U) { self.routes.push((rdef, val, ctx)); #[allow(clippy::map_identity)] // map is used to distribute &mut-ness to tuple elements self.routes .last_mut() .map(|(rdef, val, ctx)| (rdef, val, ctx)) .unwrap() } /// Finish configuration and create router instance. pub fn finish(self) -> Router<T, U> { Router { routes: self.routes, } } } /// Convenience methods provided when context data impls [`Default`] impl<T, U> RouterBuilder<T, U> where U: Default, { /// Registers resource for specified path. pub fn path(&mut self, path: impl IntoPatterns, val: T) -> (&mut ResourceDef, &mut T, &mut U) { self.push(ResourceDef::new(path), val, U::default()) } /// Registers resource for specified path prefix. pub fn prefix( &mut self, prefix: impl IntoPatterns, val: T, ) -> (&mut ResourceDef, &mut T, &mut U) { self.push(ResourceDef::prefix(prefix), val, U::default()) } /// Registers resource for [`ResourceDef`]. pub fn rdef(&mut self, rdef: ResourceDef, val: T) -> (&mut ResourceDef, &mut T, &mut U) { self.push(rdef, val, U::default()) } } #[cfg(test)] mod tests { use crate::{ path::Path, router::{ResourceId, Router}, }; #[allow(clippy::cognitive_complexity)] #[test] fn test_recognizer_1() { let mut router = Router::<usize>::build(); router.path("/name", 10).0.set_id(0); router.path("/name/{val}", 11).0.set_id(1); router.path("/name/{val}/index.html", 12).0.set_id(2); router.path("/file/{file}.{ext}", 13).0.set_id(3); router.path("/v{val}/{val2}/index.html", 14).0.set_id(4); router.path("/v/{tail:.*}", 15).0.set_id(5); router.path("/test2/{test}.html", 16).0.set_id(6); router.path("/{test}/index.html", 17).0.set_id(7); let mut router = router.finish(); let mut path = Path::new("/unknown"); assert!(router.recognize_mut(&mut path).is_none()); let mut path = Path::new("/name"); let (h, info) = router.recognize_mut(&mut path).unwrap(); assert_eq!(*h, 10); assert_eq!(info, ResourceId(0)); assert!(path.is_empty()); let mut path = Path::new("/name/value"); let (h, info) = router.recognize_mut(&mut path).unwrap(); assert_eq!(*h, 11); assert_eq!(info, ResourceId(1)); assert_eq!(path.get("val").unwrap(), "value"); assert_eq!(&path["val"], "value"); let mut path = Path::new("/name/value2/index.html"); let (h, info) = router.recognize_mut(&mut path).unwrap(); assert_eq!(*h, 12); assert_eq!(info, ResourceId(2)); assert_eq!(path.get("val").unwrap(), "value2"); let mut path = Path::new("/file/file.gz"); let (h, info) = router.recognize_mut(&mut path).unwrap(); assert_eq!(*h, 13); assert_eq!(info, ResourceId(3)); assert_eq!(path.get("file").unwrap(), "file"); assert_eq!(path.get("ext").unwrap(), "gz"); let mut path = Path::new("/v2/ttt/index.html"); let (h, info) = router.recognize_mut(&mut path).unwrap(); assert_eq!(*h, 14); assert_eq!(info, ResourceId(4)); assert_eq!(path.get("val").unwrap(), "2"); assert_eq!(path.get("val2").unwrap(), "ttt"); let mut path = Path::new("/v/blah-blah/index.html"); let (h, info) = router.recognize_mut(&mut path).unwrap(); assert_eq!(*h, 15); assert_eq!(info, ResourceId(5)); assert_eq!(path.get("tail").unwrap(), "blah-blah/index.html"); let mut path = Path::new("/test2/index.html"); let (h, info) = router.recognize_mut(&mut path).unwrap(); assert_eq!(*h, 16); assert_eq!(info, ResourceId(6)); assert_eq!(path.get("test").unwrap(), "index"); let mut path = Path::new("/bbb/index.html"); let (h, info) = router.recognize_mut(&mut path).unwrap(); assert_eq!(*h, 17); assert_eq!(info, ResourceId(7)); assert_eq!(path.get("test").unwrap(), "bbb"); } #[test] fn test_recognizer_2() { let mut router = Router::<usize>::build(); router.path("/index.json", 10); router.path("/{source}.json", 11); let mut router = router.finish(); let mut path = Path::new("/index.json"); let (h, _) = router.recognize_mut(&mut path).unwrap(); assert_eq!(*h, 10); let mut path = Path::new("/test.json"); let (h, _) = router.recognize_mut(&mut path).unwrap(); assert_eq!(*h, 11); } #[test] fn test_recognizer_with_prefix() { let mut router = Router::<usize>::build(); router.path("/name", 10).0.set_id(0); router.path("/name/{val}", 11).0.set_id(1); let mut router = router.finish(); let mut path = Path::new("/name"); path.skip(5); assert!(router.recognize_mut(&mut path).is_none()); let mut path = Path::new("/test/name"); path.skip(5); let (h, _) = router.recognize_mut(&mut path).unwrap(); assert_eq!(*h, 10); let mut path = Path::new("/test/name/value"); path.skip(5); let (h, id) = router.recognize_mut(&mut path).unwrap(); assert_eq!(*h, 11); assert_eq!(id, ResourceId(1)); assert_eq!(path.get("val").unwrap(), "value"); assert_eq!(&path["val"], "value"); // same patterns let mut router = Router::<usize>::build(); router.path("/name", 10); router.path("/name/{val}", 11); let mut router = router.finish(); // test skip beyond path length let mut path = Path::new("/name"); path.skip(6); assert!(router.recognize_mut(&mut path).is_none()); let mut path = Path::new("/test2/name"); path.skip(6); let (h, _) = router.recognize_mut(&mut path).unwrap(); assert_eq!(*h, 10); let mut path = Path::new("/test2/name-test"); path.skip(6); assert!(router.recognize_mut(&mut path).is_none()); let mut path = Path::new("/test2/name/ttt"); path.skip(6); let (h, _) = router.recognize_mut(&mut path).unwrap(); assert_eq!(*h, 11); assert_eq!(&path["val"], "ttt"); } }
use crate::{Quoter, ResourcePath}; thread_local! { static DEFAULT_QUOTER: Quoter = Quoter::new(b"", b"%/+"); } #[derive(Debug, Clone, Default)] pub struct Url { uri: http::Uri, path: Option<String>, } impl Url { #[inline] pub fn new(uri: http::Uri) -> Url { let path = DEFAULT_QUOTER.with(|q| q.requote_str_lossy(uri.path())); Url { uri, path } } #[inline] pub fn new_with_quoter(uri: http::Uri, quoter: &Quoter) -> Url { Url { path: quoter.requote_str_lossy(uri.path()), uri, } } /// Returns URI. #[inline] pub fn uri(&self) -> &http::Uri { &self.uri } /// Returns path. #[inline] pub fn path(&self) -> &str { match self.path { Some(ref path) => path, _ => self.uri.path(), } } #[inline] pub fn update(&mut self, uri: &http::Uri) { self.uri = uri.clone(); self.path = DEFAULT_QUOTER.with(|q| q.requote_str_lossy(uri.path())); } #[inline] pub fn update_with_quoter(&mut self, uri: &http::Uri, quoter: &Quoter) { self.uri = uri.clone(); self.path = quoter.requote_str_lossy(uri.path()); } } impl ResourcePath for Url { #[inline] fn path(&self) -> &str { self.path() } } #[cfg(test)] mod tests { use std::fmt::Write as _; use http::Uri; use super::*; use crate::{Path, ResourceDef}; const PROTECTED: &[u8] = b"%/+"; fn match_url(pattern: &'static str, url: impl AsRef<str>) -> Path<Url> { let re = ResourceDef::new(pattern); let uri = Uri::try_from(url.as_ref()).unwrap(); let mut path = Path::new(Url::new(uri)); assert!(re.capture_match_info(&mut path)); path } fn percent_encode(data: &[u8]) -> String { data.iter() .fold(String::with_capacity(data.len() * 3), |mut buf, c| { write!(&mut buf, "%{:02X}", c).unwrap(); buf }) } #[test] fn parse_url() { let re = "/user/{id}/test"; let path = match_url(re, "/user/2345/test"); assert_eq!(path.get("id").unwrap(), "2345"); } #[test] fn protected_chars() { let re = "/user/{id}/test"; let encoded = percent_encode(PROTECTED); let path = match_url(re, format!("/user/{}/test", encoded)); // characters in captured segment remain unencoded assert_eq!(path.get("id").unwrap(), &encoded); // "%25" should never be decoded into '%' to guarantee the output is a valid // percent-encoded format let path = match_url(re, "/user/qwe%25/test"); assert_eq!(path.get("id").unwrap(), "qwe%25"); let path = match_url(re, "/user/qwe%25rty/test"); assert_eq!(path.get("id").unwrap(), "qwe%25rty"); } #[test] fn non_protected_ascii() { let non_protected_ascii = ('\u{0}'..='\u{7F}') .filter(|&c| c.is_ascii() && !PROTECTED.contains(&(c as u8))) .collect::<String>(); let encoded = percent_encode(non_protected_ascii.as_bytes()); let path = match_url("/user/{id}/test", format!("/user/{}/test", encoded)); assert_eq!(path.get("id").unwrap(), &non_protected_ascii); } #[test] fn valid_utf8_multi_byte() { let test = ('\u{FF00}'..='\u{FFFF}').collect::<String>(); let encoded = percent_encode(test.as_bytes()); let path = match_url("/a/{id}/b", format!("/a/{}/b", &encoded)); assert_eq!(path.get("id").unwrap(), &test); } #[test] fn invalid_utf8() { let invalid_utf8 = percent_encode((0x80..=0xff).collect::<Vec<_>>().as_slice()); let uri = Uri::try_from(format!("/{}", invalid_utf8)).unwrap(); let path = Path::new(Url::new(uri)); // We should always get a valid utf8 string assert!(String::from_utf8(path.as_str().as_bytes().to_owned()).is_ok()); } }
//! An example on how to build a multi-thread tokio runtime for Actix System. //! Then spawn async task that can make use of work stealing of tokio runtime. use actix_rt::System; fn main() { System::with_tokio_rt(|| { // build system with a multi-thread tokio runtime. tokio::runtime::Builder::new_multi_thread() .worker_threads(2) .enable_all() .build() .unwrap() }) .block_on(async_main()); } // async main function that acts like #[actix_web::main] or #[tokio::main] async fn async_main() { let (tx, rx) = tokio::sync::oneshot::channel(); // get a handle to system arbiter and spawn async task on it System::current().arbiter().spawn(async { // use tokio::spawn to get inside the context of multi thread tokio runtime let h1 = tokio::spawn(async { println!("thread id is {:?}", std::thread::current().id()); std::thread::sleep(std::time::Duration::from_secs(2)); }); // work stealing occurs for this task spawn let h2 = tokio::spawn(async { println!("thread id is {:?}", std::thread::current().id()); }); h1.await.unwrap(); h2.await.unwrap(); let _ = tx.send(()); }); rx.await.unwrap(); let (tx, rx) = tokio::sync::oneshot::channel(); let now = std::time::Instant::now(); // without additional tokio::spawn, all spawned tasks run on single thread System::current().arbiter().spawn(async { println!("thread id is {:?}", std::thread::current().id()); std::thread::sleep(std::time::Duration::from_secs(2)); let _ = tx.send(()); }); // previous spawn task has blocked the system arbiter thread // so this task will wait for 2 seconds until it can be run System::current().arbiter().spawn(async move { println!("thread id is {:?}", std::thread::current().id()); assert!(now.elapsed() > std::time::Duration::from_secs(2)); }); rx.await.unwrap(); }
use std::{ cell::RefCell, fmt, future::Future, pin::Pin, sync::atomic::{AtomicUsize, Ordering}, task::{Context, Poll}, thread, }; use futures_core::ready; use tokio::sync::mpsc; use crate::system::{System, SystemCommand}; pub(crate) static COUNT: AtomicUsize = AtomicUsize::new(0); thread_local!( static HANDLE: RefCell<Option<ArbiterHandle>> = const { RefCell::new(None) }; ); pub(crate) enum ArbiterCommand { Stop, Execute(Pin<Box<dyn Future<Output = ()> + Send>>), } impl fmt::Debug for ArbiterCommand { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { ArbiterCommand::Stop => write!(f, "ArbiterCommand::Stop"), ArbiterCommand::Execute(_) => write!(f, "ArbiterCommand::Execute"), } } } /// A handle for sending spawn and stop messages to an [Arbiter]. #[derive(Debug, Clone)] pub struct ArbiterHandle { tx: mpsc::UnboundedSender<ArbiterCommand>, } impl ArbiterHandle { pub(crate) fn new(tx: mpsc::UnboundedSender<ArbiterCommand>) -> Self { Self { tx } } /// Send a future to the [Arbiter]'s thread and spawn it. /// /// If you require a result, include a response channel in the future. /// /// Returns true if future was sent successfully and false if the [Arbiter] has died. pub fn spawn<Fut>(&self, future: Fut) -> bool where Fut: Future<Output = ()> + Send + 'static, { self.tx .send(ArbiterCommand::Execute(Box::pin(future))) .is_ok() } /// Send a function to the [Arbiter]'s thread and execute it. /// /// Any result from the function is discarded. If you require a result, include a response /// channel in the function. /// /// Returns true if function was sent successfully and false if the [Arbiter] has died. pub fn spawn_fn<F>(&self, f: F) -> bool where F: FnOnce() + Send + 'static, { self.spawn(async { f() }) } /// Instruct [Arbiter] to stop processing it's event loop. /// /// Returns true if stop message was sent successfully and false if the [Arbiter] has /// been dropped. pub fn stop(&self) -> bool { self.tx.send(ArbiterCommand::Stop).is_ok() } } /// An Arbiter represents a thread that provides an asynchronous execution environment for futures /// and functions. /// /// When an arbiter is created, it spawns a new [OS thread](thread), and hosts an event loop. #[derive(Debug)] pub struct Arbiter { tx: mpsc::UnboundedSender<ArbiterCommand>, thread_handle: thread::JoinHandle<()>, } impl Arbiter { /// Spawn a new Arbiter thread and start its event loop. /// /// # Panics /// Panics if a [System] is not registered on the current thread. #[cfg(not(all(target_os = "linux", feature = "io-uring")))] #[allow(clippy::new_without_default)] pub fn new() -> Arbiter { Self::with_tokio_rt(|| { crate::runtime::default_tokio_runtime().expect("Cannot create new Arbiter's Runtime.") }) } /// Spawn a new Arbiter using the [Tokio Runtime](tokio-runtime) returned from a closure. /// /// [tokio-runtime]: tokio::runtime::Runtime #[cfg(not(all(target_os = "linux", feature = "io-uring")))] pub fn with_tokio_rt<F>(runtime_factory: F) -> Arbiter where F: FnOnce() -> tokio::runtime::Runtime + Send + 'static, { let sys = System::current(); let system_id = sys.id(); let arb_id = COUNT.fetch_add(1, Ordering::Relaxed); let name = format!("actix-rt|system:{}|arbiter:{}", system_id, arb_id); let (tx, rx) = mpsc::unbounded_channel(); let (ready_tx, ready_rx) = std::sync::mpsc::channel::<()>(); let thread_handle = thread::Builder::new() .name(name.clone()) .spawn({ let tx = tx.clone(); move || { let rt = crate::runtime::Runtime::from(runtime_factory()); let hnd = ArbiterHandle::new(tx); System::set_current(sys); HANDLE.with(|cell| *cell.borrow_mut() = Some(hnd.clone())); // register arbiter let _ = System::current() .tx() .send(SystemCommand::RegisterArbiter(arb_id, hnd)); ready_tx.send(()).unwrap(); // run arbiter event processing loop rt.block_on(ArbiterRunner { rx }); // deregister arbiter let _ = System::current() .tx() .send(SystemCommand::DeregisterArbiter(arb_id)); } }) .unwrap_or_else(|err| panic!("Cannot spawn Arbiter's thread: {name:?}: {err:?}")); ready_rx.recv().unwrap(); Arbiter { tx, thread_handle } } /// Spawn a new Arbiter thread and start its event loop with `tokio-uring` runtime. /// /// # Panics /// Panics if a [System] is not registered on the current thread. #[cfg(all(target_os = "linux", feature = "io-uring"))] #[allow(clippy::new_without_default)] pub fn new() -> Arbiter { let sys = System::current(); let system_id = sys.id(); let arb_id = COUNT.fetch_add(1, Ordering::Relaxed); let name = format!("actix-rt|system:{}|arbiter:{}", system_id, arb_id); let (tx, rx) = mpsc::unbounded_channel(); let (ready_tx, ready_rx) = std::sync::mpsc::channel::<()>(); let thread_handle = thread::Builder::new() .name(name.clone()) .spawn({ let tx = tx.clone(); move || { let hnd = ArbiterHandle::new(tx); System::set_current(sys); HANDLE.with(|cell| *cell.borrow_mut() = Some(hnd.clone())); // register arbiter let _ = System::current() .tx() .send(SystemCommand::RegisterArbiter(arb_id, hnd)); ready_tx.send(()).unwrap(); // run arbiter event processing loop tokio_uring::start(ArbiterRunner { rx }); // deregister arbiter let _ = System::current() .tx() .send(SystemCommand::DeregisterArbiter(arb_id)); } }) .unwrap_or_else(|err| panic!("Cannot spawn Arbiter's thread: {name:?}: {err:?}")); ready_rx.recv().unwrap(); Arbiter { tx, thread_handle } } /// Sets up an Arbiter runner in a new System using the environment's local set. pub(crate) fn in_new_system() -> ArbiterHandle { let (tx, rx) = mpsc::unbounded_channel(); let hnd = ArbiterHandle::new(tx); HANDLE.with(|cell| *cell.borrow_mut() = Some(hnd.clone())); crate::spawn(ArbiterRunner { rx }); hnd } /// Return a handle to the this Arbiter's message sender. pub fn handle(&self) -> ArbiterHandle { ArbiterHandle::new(self.tx.clone()) } /// Return a handle to the current thread's Arbiter's message sender. /// /// # Panics /// Panics if no Arbiter is running on the current thread. pub fn current() -> ArbiterHandle { HANDLE.with(|cell| match *cell.borrow() { Some(ref hnd) => hnd.clone(), None => panic!("Arbiter is not running."), }) } /// Try to get current running arbiter handle. /// /// Returns `None` if no Arbiter has been started. /// /// Unlike [`current`](Self::current), this never panics. pub fn try_current() -> Option<ArbiterHandle> { HANDLE.with(|cell| cell.borrow().clone()) } /// Stop Arbiter from continuing it's event loop. /// /// Returns true if stop message was sent successfully and false if the Arbiter has been dropped. pub fn stop(&self) -> bool { self.tx.send(ArbiterCommand::Stop).is_ok() } /// Send a future to the Arbiter's thread and spawn it. /// /// If you require a result, include a response channel in the future. /// /// Returns true if future was sent successfully and false if the Arbiter has died. #[track_caller] pub fn spawn<Fut>(&self, future: Fut) -> bool where Fut: Future<Output = ()> + Send + 'static, { self.tx .send(ArbiterCommand::Execute(Box::pin(future))) .is_ok() } /// Send a function to the Arbiter's thread and execute it. /// /// Any result from the function is discarded. If you require a result, include a response /// channel in the function. /// /// Returns true if function was sent successfully and false if the Arbiter has died. #[track_caller] pub fn spawn_fn<F>(&self, f: F) -> bool where F: FnOnce() + Send + 'static, { self.spawn(async { f() }) } /// Wait for Arbiter's event loop to complete. /// /// Joins the underlying OS thread handle. See [`JoinHandle::join`](thread::JoinHandle::join). pub fn join(self) -> thread::Result<()> { self.thread_handle.join() } } /// A persistent future that processes [Arbiter] commands. struct ArbiterRunner { rx: mpsc::UnboundedReceiver<ArbiterCommand>, } impl Future for ArbiterRunner { type Output = (); fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { // process all items currently buffered in channel loop { match ready!(self.rx.poll_recv(cx)) { // channel closed; no more messages can be received None => return Poll::Ready(()), // process arbiter command Some(item) => match item { ArbiterCommand::Stop => { return Poll::Ready(()); } ArbiterCommand::Execute(task_fut) => { tokio::task::spawn_local(task_fut); } }, } } } }
//! Tokio-based single-threaded async runtime for the Actix ecosystem. //! //! In most parts of the the Actix ecosystem, it has been chosen to use !Send futures. For this //! reason, a single-threaded runtime is appropriate since it is guaranteed that futures will not //! be moved between threads. This can result in small performance improvements over cases where //! atomics would otherwise be needed. //! //! To achieve similar performance to multi-threaded, work-stealing runtimes, applications //! using `actix-rt` will create multiple, mostly disconnected, single-threaded runtimes. //! This approach has good performance characteristics for workloads where the majority of tasks //! have similar runtime expense. //! //! The disadvantage is that idle threads will not steal work from very busy, stuck or otherwise //! backlogged threads. Tasks that are disproportionately expensive should be offloaded to the //! blocking task thread-pool using [`task::spawn_blocking`]. //! //! # Examples //! ```no_run //! use std::sync::mpsc; //! use actix_rt::{Arbiter, System}; //! //! let _ = System::new(); //! //! let (tx, rx) = mpsc::channel::<u32>(); //! //! let arbiter = Arbiter::new(); //! arbiter.spawn_fn(move || tx.send(42).unwrap()); //! //! let num = rx.recv().unwrap(); //! assert_eq!(num, 42); //! //! arbiter.stop(); //! arbiter.join().unwrap(); //! ``` //! //! # `io-uring` Support //! //! There is experimental support for using io-uring with this crate by enabling the //! `io-uring` feature. For now, it is semver exempt. //! //! Note that there are currently some unimplemented parts of using `actix-rt` with `io-uring`. //! In particular, when running a `System`, only `System::block_on` is supported. #![deny(rust_2018_idioms, nonstandard_style)] #![warn(future_incompatible, missing_docs)] #![allow(clippy::type_complexity)] #![doc(html_logo_url = "https://actix.rs/img/logo.png")] #![doc(html_favicon_url = "https://actix.rs/favicon.ico")] #[cfg(all(not(target_os = "linux"), feature = "io-uring"))] compile_error!("io_uring is a linux only feature."); use std::future::Future; // Cannot define a main macro when compiled into test harness. // Workaround for https://github.com/rust-lang/rust/issues/62127. #[cfg(all(feature = "macros", not(test)))] pub use actix_macros::main; #[cfg(feature = "macros")] pub use actix_macros::test; mod arbiter; mod runtime; mod system; pub use tokio::pin; use tokio::task::JoinHandle; pub use self::{ arbiter::{Arbiter, ArbiterHandle}, runtime::Runtime, system::{System, SystemRunner}, }; pub mod signal { //! Asynchronous signal handling (Tokio re-exports). #[cfg(unix)] pub mod unix { //! Unix specific signals (Tokio re-exports). pub use tokio::signal::unix::*; } pub use tokio::signal::ctrl_c; } pub mod net { //! TCP/UDP/Unix bindings (mostly Tokio re-exports). use std::{ future::Future, io, task::{Context, Poll}, }; use tokio::io::{AsyncRead, AsyncWrite, Interest}; #[cfg(unix)] pub use tokio::net::{UnixDatagram, UnixListener, UnixStream}; pub use tokio::{ io::Ready, net::{TcpListener, TcpSocket, TcpStream, UdpSocket}, }; /// Extension trait over async read+write types that can also signal readiness. #[doc(hidden)] pub trait ActixStream: AsyncRead + AsyncWrite + Unpin { /// Poll stream and check read readiness of Self. /// /// See [tokio::net::TcpStream::poll_read_ready] for detail on intended use. fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>>; /// Poll stream and check write readiness of Self. /// /// See [tokio::net::TcpStream::poll_write_ready] for detail on intended use. fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>>; } impl ActixStream for TcpStream { fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> { let ready = self.ready(Interest::READABLE); tokio::pin!(ready); ready.poll(cx) } fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> { let ready = self.ready(Interest::WRITABLE); tokio::pin!(ready); ready.poll(cx) } } #[cfg(unix)] impl ActixStream for UnixStream { fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> { let ready = self.ready(Interest::READABLE); tokio::pin!(ready); ready.poll(cx) } fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> { let ready = self.ready(Interest::WRITABLE); tokio::pin!(ready); ready.poll(cx) } } impl<Io: ActixStream + ?Sized> ActixStream for Box<Io> { fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> { (**self).poll_read_ready(cx) } fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> { (**self).poll_write_ready(cx) } } } pub mod time { //! Utilities for tracking time (Tokio re-exports). pub use tokio::time::{ interval, interval_at, sleep, sleep_until, timeout, Instant, Interval, Sleep, Timeout, }; } pub mod task { //! Task management (Tokio re-exports). pub use tokio::task::{spawn_blocking, yield_now, JoinError, JoinHandle}; } /// Spawns a future on the current thread as a new task. /// /// If not immediately awaited, the task can be cancelled using [`JoinHandle::abort`]. /// /// The provided future is spawned as a new task; therefore, panics are caught. /// /// # Panics /// Panics if Actix system is not running. /// /// # Examples /// ``` /// # use std::time::Duration; /// # actix_rt::Runtime::new().unwrap().block_on(async { /// // task resolves successfully /// assert_eq!(actix_rt::spawn(async { 1 }).await.unwrap(), 1); /// /// // task panics /// assert!(actix_rt::spawn(async { /// panic!("panic is caught at task boundary"); /// }) /// .await /// .unwrap_err() /// .is_panic()); /// /// // task is cancelled before completion /// let handle = actix_rt::spawn(actix_rt::time::sleep(Duration::from_secs(100))); /// handle.abort(); /// assert!(handle.await.unwrap_err().is_cancelled()); /// # }); /// ``` #[track_caller] #[inline] pub fn spawn<Fut>(f: Fut) -> JoinHandle<Fut::Output> where Fut: Future + 'static, Fut::Output: 'static, { tokio::task::spawn_local(f) }
use std::{future::Future, io}; use tokio::task::{JoinHandle, LocalSet}; /// A Tokio-based runtime proxy. /// /// All spawned futures will be executed on the current thread. Therefore, there is no `Send` bound /// on submitted futures. #[derive(Debug)] pub struct Runtime { local: LocalSet, rt: tokio::runtime::Runtime, } pub(crate) fn default_tokio_runtime() -> io::Result<tokio::runtime::Runtime> { tokio::runtime::Builder::new_current_thread() .enable_io() .enable_time() .build() } impl Runtime { /// Returns a new runtime initialized with default configuration values. #[allow(clippy::new_ret_no_self)] pub fn new() -> io::Result<Self> { let rt = default_tokio_runtime()?; Ok(Runtime { rt, local: LocalSet::new(), }) } /// Offload a future onto the single-threaded runtime. /// /// The returned join handle can be used to await the future's result. /// /// See [crate root][crate] documentation for more details. /// /// # Examples /// ``` /// let rt = actix_rt::Runtime::new().unwrap(); /// /// // Spawn a future onto the runtime /// let handle = rt.spawn(async { /// println!("running on the runtime"); /// 42 /// }); /// /// assert_eq!(rt.block_on(handle).unwrap(), 42); /// ``` /// /// # Panics /// This function panics if the spawn fails. Failure occurs if the executor is currently at /// capacity and is unable to spawn a new future. #[track_caller] pub fn spawn<F>(&self, future: F) -> JoinHandle<F::Output> where F: Future + 'static, { self.local.spawn_local(future) } /// Retrieves a reference to the underlying Tokio runtime associated with this instance. /// /// The Tokio runtime is responsible for executing asynchronous tasks and managing /// the event loop for an asynchronous Rust program. This method allows accessing /// the runtime to interact with its features directly. /// /// In a typical use case, you might need to share the same runtime between different /// modules of your project. For example, a module might require a `tokio::runtime::Handle` /// to spawn tasks on the same runtime, or the runtime itself to configure more complex /// behaviours. /// /// # Example /// /// ``` /// use actix_rt::Runtime; /// /// mod module_a { /// pub fn do_something(handle: tokio::runtime::Handle) { /// handle.spawn(async { /// // Some asynchronous task here /// }); /// } /// } /// /// mod module_b { /// pub fn do_something_else(rt: &tokio::runtime::Runtime) { /// rt.spawn(async { /// // Another asynchronous task here /// }); /// } /// } /// /// let actix_runtime = actix_rt::Runtime::new().unwrap(); /// let tokio_runtime = actix_runtime.tokio_runtime(); /// /// let handle = tokio_runtime.handle().clone(); /// /// module_a::do_something(handle); /// module_b::do_something_else(tokio_runtime); /// ``` /// /// # Returns /// /// An immutable reference to the `tokio::runtime::Runtime` instance associated with this /// `Runtime` instance. /// /// # Note /// /// While this method provides an immutable reference to the Tokio runtime, which is safe to share across threads, /// be aware that spawning blocking tasks on the Tokio runtime could potentially impact the execution /// of the Actix runtime. This is because Tokio is responsible for driving the Actix system, /// and blocking tasks could delay or deadlock other tasks in run loop. pub fn tokio_runtime(&self) -> &tokio::runtime::Runtime { &self.rt } /// Runs the provided future, blocking the current thread until the future completes. /// /// This function can be used to synchronously block the current thread until the provided /// `future` has resolved either successfully or with an error. The result of the future is /// then returned from this function call. /// /// Note that this function will also execute any spawned futures on the current thread, but /// will not block until these other spawned futures have completed. Once the function returns, /// any uncompleted futures remain pending in the `Runtime` instance. These futures will not run /// until `block_on` or `run` is called again. /// /// The caller is responsible for ensuring that other spawned futures complete execution by /// calling `block_on` or `run`. #[track_caller] pub fn block_on<F>(&self, f: F) -> F::Output where F: Future, { self.local.block_on(&self.rt, f) } } impl From<tokio::runtime::Runtime> for Runtime { fn from(rt: tokio::runtime::Runtime) -> Self { Self { local: LocalSet::new(), rt, } } }
use std::{ cell::RefCell, collections::HashMap, future::Future, io, pin::Pin, sync::atomic::{AtomicUsize, Ordering}, task::{Context, Poll}, }; use futures_core::ready; use tokio::sync::{mpsc, oneshot}; use crate::{arbiter::ArbiterHandle, Arbiter}; static SYSTEM_COUNT: AtomicUsize = AtomicUsize::new(0); thread_local!( static CURRENT: RefCell<Option<System>> = const { RefCell::new(None) }; ); /// A manager for a per-thread distributed async runtime. #[derive(Clone, Debug)] pub struct System { id: usize, sys_tx: mpsc::UnboundedSender<SystemCommand>, /// Handle to the first [Arbiter] that is created with the System. arbiter_handle: ArbiterHandle, } #[cfg(not(feature = "io-uring"))] impl System { /// Create a new system. /// /// # Panics /// Panics if underlying Tokio runtime can not be created. #[allow(clippy::new_ret_no_self)] pub fn new() -> SystemRunner { Self::with_tokio_rt(|| { crate::runtime::default_tokio_runtime() .expect("Default Actix (Tokio) runtime could not be created.") }) } /// Create a new System using the [Tokio Runtime](tokio-runtime) returned from a closure. /// /// [tokio-runtime]: tokio::runtime::Runtime pub fn with_tokio_rt<F>(runtime_factory: F) -> SystemRunner where F: FnOnce() -> tokio::runtime::Runtime, { let (stop_tx, stop_rx) = oneshot::channel(); let (sys_tx, sys_rx) = mpsc::unbounded_channel(); let rt = crate::runtime::Runtime::from(runtime_factory()); let sys_arbiter = rt.block_on(async { Arbiter::in_new_system() }); let system = System::construct(sys_tx, sys_arbiter.clone()); system .tx() .send(SystemCommand::RegisterArbiter(usize::MAX, sys_arbiter)) .unwrap(); // init background system arbiter let sys_ctrl = SystemController::new(sys_rx, stop_tx); rt.spawn(sys_ctrl); SystemRunner { rt, stop_rx } } } #[cfg(feature = "io-uring")] impl System { /// Create a new system. /// /// # Panics /// Panics if underlying Tokio runtime can not be created. #[allow(clippy::new_ret_no_self)] pub fn new() -> SystemRunner { SystemRunner } /// Create a new System using the [Tokio Runtime](tokio-runtime) returned from a closure. /// /// [tokio-runtime]: tokio::runtime::Runtime #[doc(hidden)] pub fn with_tokio_rt<F>(_: F) -> SystemRunner where F: FnOnce() -> tokio::runtime::Runtime, { unimplemented!("System::with_tokio_rt is not implemented for io-uring feature yet") } } impl System { /// Constructs new system and registers it on the current thread. pub(crate) fn construct( sys_tx: mpsc::UnboundedSender<SystemCommand>, arbiter_handle: ArbiterHandle, ) -> Self { let sys = System { sys_tx, arbiter_handle, id: SYSTEM_COUNT.fetch_add(1, Ordering::SeqCst), }; System::set_current(sys.clone()); sys } /// Get current running system. /// /// # Panics /// Panics if no system is registered on the current thread. pub fn current() -> System { CURRENT.with(|cell| match *cell.borrow() { Some(ref sys) => sys.clone(), None => panic!("System is not running"), }) } /// Try to get current running system. /// /// Returns `None` if no System has been started. /// /// Unlike [`current`](Self::current), this never panics. pub fn try_current() -> Option<System> { CURRENT.with(|cell| cell.borrow().clone()) } /// Get handle to a the System's initial [Arbiter]. pub fn arbiter(&self) -> &ArbiterHandle { &self.arbiter_handle } /// Check if there is a System registered on the current thread. pub fn is_registered() -> bool { CURRENT.with(|sys| sys.borrow().is_some()) } /// Register given system on current thread. #[doc(hidden)] pub fn set_current(sys: System) { CURRENT.with(|cell| { *cell.borrow_mut() = Some(sys); }) } /// Numeric system identifier. /// /// Useful when using multiple Systems. pub fn id(&self) -> usize { self.id } /// Stop the system (with code 0). pub fn stop(&self) { self.stop_with_code(0) } /// Stop the system with a given exit code. pub fn stop_with_code(&self, code: i32) { let _ = self.sys_tx.send(SystemCommand::Exit(code)); } pub(crate) fn tx(&self) -> &mpsc::UnboundedSender<SystemCommand> { &self.sys_tx } } /// Runner that keeps a [System]'s event loop alive until stop message is received. #[cfg(not(feature = "io-uring"))] #[must_use = "A SystemRunner does nothing unless `run` is called."] #[derive(Debug)] pub struct SystemRunner { rt: crate::runtime::Runtime, stop_rx: oneshot::Receiver<i32>, } #[cfg(not(feature = "io-uring"))] impl SystemRunner { /// Starts event loop and will return once [System] is [stopped](System::stop). pub fn run(self) -> io::Result<()> { let exit_code = self.run_with_code()?; match exit_code { 0 => Ok(()), nonzero => Err(io::Error::new( io::ErrorKind::Other, format!("Non-zero exit code: {}", nonzero), )), } } /// Runs the event loop until [stopped](System::stop_with_code), returning the exit code. pub fn run_with_code(self) -> io::Result<i32> { let SystemRunner { rt, stop_rx, .. } = self; // run loop rt.block_on(stop_rx) .map_err(|err| io::Error::new(io::ErrorKind::Other, err)) } /// Retrieves a reference to the underlying [Actix runtime](crate::Runtime) associated with this /// `SystemRunner` instance. /// /// The Actix runtime is responsible for managing the event loop for an Actix system and /// executing asynchronous tasks. This method provides access to the runtime, allowing direct /// interaction with its features. /// /// In a typical use case, you might need to share the same runtime between different /// parts of your project. For example, some components might require a [`Runtime`] to spawn /// tasks on the same runtime. /// /// Read more in the documentation for [`Runtime`]. /// /// # Examples /// /// ``` /// let system_runner = actix_rt::System::new(); /// let actix_runtime = system_runner.runtime(); /// /// // Use the runtime to spawn an async task or perform other operations /// ``` /// /// # Note /// /// While this method provides an immutable reference to the Actix runtime, which is safe to /// share across threads, be aware that spawning blocking tasks on the Actix runtime could /// potentially impact system performance. This is because the Actix runtime is responsible for /// driving the system, and blocking tasks could delay other tasks in the run loop. /// /// [`Runtime`]: crate::Runtime pub fn runtime(&self) -> &crate::runtime::Runtime { &self.rt } /// Runs the provided future, blocking the current thread until the future completes. #[track_caller] #[inline] pub fn block_on<F: Future>(&self, fut: F) -> F::Output { self.rt.block_on(fut) } } /// Runner that keeps a [System]'s event loop alive until stop message is received. #[cfg(feature = "io-uring")] #[must_use = "A SystemRunner does nothing unless `run` is called."] #[derive(Debug)] pub struct SystemRunner; #[cfg(feature = "io-uring")] impl SystemRunner { /// Starts event loop and will return once [System] is [stopped](System::stop). pub fn run(self) -> io::Result<()> { unimplemented!("SystemRunner::run is not implemented for io-uring feature yet"); } /// Runs the event loop until [stopped](System::stop_with_code), returning the exit code. pub fn run_with_code(self) -> io::Result<i32> { unimplemented!("SystemRunner::run_with_code is not implemented for io-uring feature yet"); } /// Runs the provided future, blocking the current thread until the future completes. #[inline] pub fn block_on<F: Future>(&self, fut: F) -> F::Output { tokio_uring::start(async move { let (stop_tx, stop_rx) = oneshot::channel(); let (sys_tx, sys_rx) = mpsc::unbounded_channel(); let sys_arbiter = Arbiter::in_new_system(); let system = System::construct(sys_tx, sys_arbiter.clone()); system .tx() .send(SystemCommand::RegisterArbiter(usize::MAX, sys_arbiter)) .unwrap(); // init background system arbiter let sys_ctrl = SystemController::new(sys_rx, stop_tx); tokio_uring::spawn(sys_ctrl); let res = fut.await; drop(stop_rx); res }) } } #[derive(Debug)] pub(crate) enum SystemCommand { Exit(i32), RegisterArbiter(usize, ArbiterHandle), DeregisterArbiter(usize), } /// There is one `SystemController` per [System]. It runs in the background, keeping track of /// [Arbiter]s and is able to distribute a system-wide stop command. #[derive(Debug)] pub(crate) struct SystemController { stop_tx: Option<oneshot::Sender<i32>>, cmd_rx: mpsc::UnboundedReceiver<SystemCommand>, arbiters: HashMap<usize, ArbiterHandle>, } impl SystemController { pub(crate) fn new( cmd_rx: mpsc::UnboundedReceiver<SystemCommand>, stop_tx: oneshot::Sender<i32>, ) -> Self { SystemController { cmd_rx, stop_tx: Some(stop_tx), arbiters: HashMap::with_capacity(4), } } } impl Future for SystemController { type Output = (); fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { // process all items currently buffered in channel loop { match ready!(self.cmd_rx.poll_recv(cx)) { // channel closed; no more messages can be received None => return Poll::Ready(()), // process system command Some(cmd) => match cmd { SystemCommand::Exit(code) => { // stop all arbiters for arb in self.arbiters.values() { arb.stop(); } // stop event loop // will only fire once if let Some(stop_tx) = self.stop_tx.take() { let _ = stop_tx.send(code); } } SystemCommand::RegisterArbiter(id, arb) => { self.arbiters.insert(id, arb); } SystemCommand::DeregisterArbiter(id) => { self.arbiters.remove(&id); } }, } } } }
//! Checks that test macro does not cause problems in the presence of imports named "test" that //! could be either a module with test items or the "test with runtime" macro itself. //! //! Before actix/actix-net#399 was implemented, this macro was running twice. The first run output //! `#[test]` and it got run again and since it was in scope. //! //! Prevented by using the fully-qualified test marker (`#[::core::prelude::v1::test]`). #![cfg(feature = "macros")] use actix_rt::time as test; #[actix_rt::test] async fn test_naming_conflict() { use test as time; time::sleep(std::time::Duration::from_millis(2)).await; }
use std::{ future::Future, time::{Duration, Instant}, }; use actix_rt::{task::JoinError, Arbiter, System}; #[cfg(not(feature = "io-uring"))] use { std::{sync::mpsc::channel, thread}, tokio::sync::oneshot, }; #[test] fn await_for_timer() { let time = Duration::from_secs(1); let instant = Instant::now(); System::new().block_on(async move { tokio::time::sleep(time).await; }); assert!( instant.elapsed() >= time, "Block on should poll awaited future to completion" ); } #[cfg(not(feature = "io-uring"))] #[test] fn run_with_code() { let sys = System::new(); System::current().stop_with_code(42); let exit_code = sys.run_with_code().expect("system stop should not error"); assert_eq!(exit_code, 42); } #[test] fn join_another_arbiter() { let time = Duration::from_secs(1); let instant = Instant::now(); System::new().block_on(async move { let arbiter = Arbiter::new(); arbiter.spawn(Box::pin(async move { tokio::time::sleep(time).await; Arbiter::current().stop(); })); arbiter.join().unwrap(); }); assert!( instant.elapsed() >= time, "Join on another arbiter should complete only when it calls stop" ); let instant = Instant::now(); System::new().block_on(async move { let arbiter = Arbiter::new(); arbiter.spawn_fn(move || { actix_rt::spawn(async move { tokio::time::sleep(time).await; Arbiter::current().stop(); }); }); arbiter.join().unwrap(); }); assert!( instant.elapsed() >= time, "Join on an arbiter that has used actix_rt::spawn should wait for said future" ); let instant = Instant::now(); System::new().block_on(async move { let arbiter = Arbiter::new(); arbiter.spawn(Box::pin(async move { tokio::time::sleep(time).await; Arbiter::current().stop(); })); arbiter.stop(); arbiter.join().unwrap(); }); assert!( instant.elapsed() < time, "Premature stop of arbiter should conclude regardless of it's current state" ); } #[test] fn non_static_block_on() { let string = String::from("test_str"); let string = string.as_str(); let sys = System::new(); sys.block_on(async { actix_rt::time::sleep(Duration::from_millis(1)).await; assert_eq!("test_str", string); }); let rt = actix_rt::Runtime::new().unwrap(); rt.block_on(async { actix_rt::time::sleep(Duration::from_millis(1)).await; assert_eq!("test_str", string); }); } #[test] fn wait_for_spawns() { let rt = actix_rt::Runtime::new().unwrap(); let handle = rt.spawn(async { println!("running on the runtime"); // panic is caught at task boundary panic!("intentional test panic"); }); assert!(rt.block_on(handle).is_err()); } // Temporary disabled tests for io-uring feature. // They should be enabled when possible. #[cfg(not(feature = "io-uring"))] #[test] fn arbiter_spawn_fn_runs() { let _ = System::new(); let (tx, rx) = channel::<u32>(); let arbiter = Arbiter::new(); arbiter.spawn_fn(move || tx.send(42).unwrap()); let num = rx.recv().unwrap(); assert_eq!(num, 42); arbiter.stop(); arbiter.join().unwrap(); } #[cfg(not(feature = "io-uring"))] #[test] fn arbiter_handle_spawn_fn_runs() { let sys = System::new(); let (tx, rx) = channel::<u32>(); let arbiter = Arbiter::new(); let handle = arbiter.handle(); drop(arbiter); handle.spawn_fn(move || { tx.send(42).unwrap(); System::current().stop() }); let num = rx.recv_timeout(Duration::from_secs(2)).unwrap(); assert_eq!(num, 42); handle.stop(); sys.run().unwrap(); } #[cfg(not(feature = "io-uring"))] #[test] fn arbiter_drop_no_panic_fn() { let _ = System::new(); let arbiter = Arbiter::new(); arbiter.spawn_fn(|| panic!("test")); arbiter.stop(); arbiter.join().unwrap(); } #[cfg(not(feature = "io-uring"))] #[test] fn arbiter_drop_no_panic_fut() { let _ = System::new(); let arbiter = Arbiter::new(); arbiter.spawn(async { panic!("test") }); arbiter.stop(); arbiter.join().unwrap(); } #[cfg(not(feature = "io-uring"))] #[test] fn system_arbiter_spawn() { let runner = System::new(); let (tx, rx) = oneshot::channel(); let sys = System::current(); thread::spawn(|| { // this thread will have no arbiter in it's thread local so call will panic Arbiter::current(); }) .join() .unwrap_err(); let thread = thread::spawn(|| { // this thread will have no arbiter in it's thread local so use the system handle instead System::set_current(sys); let sys = System::current(); let arb = sys.arbiter(); arb.spawn(async move { tx.send(42u32).unwrap(); System::current().stop(); }); }); assert_eq!(runner.block_on(rx).unwrap(), 42); thread.join().unwrap(); } #[cfg(not(feature = "io-uring"))] #[test] fn system_stop_stops_arbiters() { let sys = System::new(); let arb = Arbiter::new(); // arbiter should be alive to receive spawn msg assert!(Arbiter::current().spawn_fn(|| {})); assert!(arb.spawn_fn(|| {})); System::current().stop(); sys.run().unwrap(); // account for slightly slow thread de-spawns thread::sleep(Duration::from_millis(500)); // arbiter should be dead and return false assert!(!Arbiter::current().spawn_fn(|| {})); assert!(!arb.spawn_fn(|| {})); arb.join().unwrap(); } #[cfg(not(feature = "io-uring"))] #[test] fn new_system_with_tokio() { let (tx, rx) = channel(); let res = System::with_tokio_rt(move || { tokio::runtime::Builder::new_multi_thread() .enable_io() .enable_time() .thread_keep_alive(Duration::from_millis(1000)) .worker_threads(2) .max_blocking_threads(2) .on_thread_start(|| {}) .on_thread_stop(|| {}) .build() .unwrap() }) .block_on(async { actix_rt::time::sleep(Duration::from_millis(1)).await; tokio::task::spawn(async move { tx.send(42).unwrap(); }) .await .unwrap(); 123usize }); assert_eq!(res, 123); assert_eq!(rx.recv().unwrap(), 42); } #[cfg(not(feature = "io-uring"))] #[test] fn new_arbiter_with_tokio() { use std::sync::{ atomic::{AtomicBool, Ordering}, Arc, }; let _ = System::new(); let arb = Arbiter::with_tokio_rt(|| { tokio::runtime::Builder::new_current_thread() .enable_all() .build() .unwrap() }); let counter = Arc::new(AtomicBool::new(true)); let counter1 = counter.clone(); let did_spawn = arb.spawn(async move { actix_rt::time::sleep(Duration::from_millis(1)).await; counter1.store(false, Ordering::SeqCst); Arbiter::current().stop(); }); assert!(did_spawn); arb.join().unwrap(); assert!(!counter.load(Ordering::SeqCst)); } #[test] #[should_panic] fn no_system_current_panic() { System::current(); } #[test] #[should_panic] fn no_system_arbiter_new_panic() { Arbiter::new(); } #[test] fn try_current_no_system() { assert!(System::try_current().is_none()) } #[test] fn try_current_with_system() { System::new().block_on(async { assert!(System::try_current().is_some()) }); } #[allow(clippy::unit_cmp)] #[test] fn spawn_local() { System::new().block_on(async { // demonstrate that spawn -> R is strictly more capable than spawn -> () assert_eq!(actix_rt::spawn(async {}).await.unwrap(), ()); assert_eq!(actix_rt::spawn(async { 1 }).await.unwrap(), 1); assert!(actix_rt::spawn(async { panic!("") }).await.is_err()); actix_rt::spawn(async { tokio::time::sleep(Duration::from_millis(50)).await }) .await .unwrap(); fn g<F: Future<Output = Result<(), JoinError>>>(_f: F) {} g(actix_rt::spawn(async {})); // g(actix_rt::spawn(async { 1 })); // compile err fn h<F: Future<Output = Result<R, JoinError>>, R>(_f: F) {} h(actix_rt::spawn(async {})); h(actix_rt::spawn(async { 1 })); }) } #[cfg(all(target_os = "linux", feature = "io-uring"))] #[test] fn tokio_uring_arbiter() { System::new().block_on(async { let (tx, rx) = std::sync::mpsc::channel(); Arbiter::new().spawn(async move { let handle = actix_rt::spawn(async move { let f = tokio_uring::fs::File::create("test.txt").await.unwrap(); let buf = b"Hello World!"; let (res, _) = f.write_all_at(&buf[..], 0).await; assert!(res.is_ok()); f.sync_all().await.unwrap(); f.close().await.unwrap(); std::fs::remove_file("test.txt").unwrap(); }); handle.await.unwrap(); tx.send(true).unwrap(); }); assert!(rx.recv().unwrap()); }) }
//! Simple file-reader TCP server with framed stream. //! //! Using the following command: //! //! ```sh //! nc 127.0.0.1 8080 //! ``` //! //! Follow the prompt and enter a file path, relative or absolute. #![allow(missing_docs)] use std::io; use actix_codec::{Framed, LinesCodec}; use actix_rt::net::TcpStream; use actix_server::Server; use actix_service::{fn_service, ServiceFactoryExt as _}; use futures_util::{SinkExt as _, StreamExt as _}; use tokio::{fs::File, io::AsyncReadExt as _}; async fn run() -> io::Result<()> { pretty_env_logger::formatted_timed_builder() .parse_env(pretty_env_logger::env_logger::Env::default().default_filter_or("info")); let addr = ("127.0.0.1", 8080); tracing::info!("starting server on port: {}", &addr.0); // Bind socket address and start worker(s). By default, the server uses the number of physical // CPU cores as the worker count. For this reason, the closure passed to bind needs to return // a service *factory*; so it can be created once per worker. Server::build() .bind("file-reader", addr, move || { fn_service(move |stream: TcpStream| async move { // set up codec to use with I/O resource let mut framed = Framed::new(stream, LinesCodec::default()); loop { // prompt for file name framed.send("Type file name to return:").await?; // wait for next line match framed.next().await { Some(Ok(line)) => { match File::open(&line).await { Ok(mut file) => { tracing::info!("reading file: {}", &line); // read file into String buffer let mut buf = String::new(); file.read_to_string(&mut buf).await?; // send String into framed object framed.send(buf).await?; // break out of loop and break; } Err(err) => { tracing::error!("{}", err); framed .send("File not found or not readable. Try again.") .await?; continue; } }; } // not being able to read a line from the stream is unrecoverable Some(Err(err)) => return Err(err), // This EOF won't be hit. None => continue, } } // close connection after file has been copied to TCP stream Ok(()) }) .map_err(|err| tracing::error!("service error: {:?}", err)) })? .workers(2) .run() .await } #[tokio::main] async fn main() -> io::Result<()> { run().await?; Ok(()) } // alternatively: // #[actix_rt::main] // async fn main() -> io::Result<()> { // run().await?; // Ok(()) // }
//! Simple composite-service TCP echo server. //! //! Using the following command: //! //! ```sh //! nc 127.0.0.1 8080 //! ``` //! //! Start typing. When you press enter the typed line will be echoed back. The server will log //! the length of each line it echos and the total size of data sent when the connection is closed. use std::{ io, sync::{ atomic::{AtomicUsize, Ordering}, Arc, }, }; use actix_rt::net::TcpStream; use actix_server::Server; use actix_service::{fn_service, ServiceFactoryExt as _}; use bytes::BytesMut; use futures_util::future::ok; use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _}; async fn run() -> io::Result<()> { pretty_env_logger::formatted_timed_builder() .parse_env(pretty_env_logger::env_logger::Env::default().default_filter_or("info")); let count = Arc::new(AtomicUsize::new(0)); let addr = ("127.0.0.1", 8080); tracing::info!("starting server on port: {}", &addr.0); // Bind socket address and start worker(s). By default, the server uses the number of physical // CPU cores as the worker count. For this reason, the closure passed to bind needs to return // a service *factory*; so it can be created once per worker. Server::build() .bind("echo", addr, move || { let count = Arc::clone(&count); let num2 = Arc::clone(&count); fn_service(move |mut stream: TcpStream| { let count = Arc::clone(&count); async move { let num = count.fetch_add(1, Ordering::SeqCst); let num = num + 1; let mut size = 0; let mut buf = BytesMut::new(); loop { match stream.read_buf(&mut buf).await { // end of stream; bail from loop Ok(0) => break, // more bytes to process Ok(bytes_read) => { tracing::info!("[{}] read {} bytes", num, bytes_read); stream.write_all(&buf[size..]).await.unwrap(); size += bytes_read; } // stream error; bail from loop with error Err(err) => { tracing::error!("stream error: {:?}", err); return Err(()); } } } // send data down service pipeline Ok((buf.freeze(), size)) } }) .map_err(|err| tracing::error!("service error: {:?}", err)) .and_then(move |(_, size)| { let num = num2.load(Ordering::SeqCst); tracing::info!("[{}] total bytes read: {}", num, size); ok(size) }) })? .workers(2) .run() .await } #[tokio::main] async fn main() -> io::Result<()> { run().await?; Ok(()) } // alternatively: // #[actix_rt::main] // async fn main() -> io::Result<()> { // run().await?; // Ok(()) // }
use std::{io, thread, time::Duration}; use actix_rt::time::Instant; use mio::{Interest, Poll, Token as MioToken}; use tracing::{debug, error, info}; use crate::{ availability::Availability, socket::MioListener, waker_queue::{WakerInterest, WakerQueue, WAKER_TOKEN}, worker::{Conn, ServerWorker, WorkerHandleAccept, WorkerHandleServer}, ServerBuilder, ServerHandle, }; const TIMEOUT_DURATION_ON_ERROR: Duration = Duration::from_millis(510); struct ServerSocketInfo { token: usize, lst: MioListener, /// Timeout is used to mark the deadline when this socket's listener should be registered again /// after an error. timeout: Option<actix_rt::time::Instant>, } /// Poll instance of the server. pub(crate) struct Accept { poll: Poll, waker_queue: WakerQueue, handles: Vec<WorkerHandleAccept>, srv: ServerHandle, next: usize, avail: Availability, /// use the smallest duration from sockets timeout. timeout: Option<Duration>, paused: bool, } impl Accept { pub(crate) fn start( sockets: Vec<(usize, MioListener)>, builder: &ServerBuilder, ) -> io::Result<(WakerQueue, Vec<WorkerHandleServer>, thread::JoinHandle<()>)> { let handle_server = ServerHandle::new(builder.cmd_tx.clone()); // construct poll instance and its waker let poll = Poll::new()?; let waker_queue = WakerQueue::new(poll.registry())?; // start workers and collect handles let (handles_accept, handles_server) = (0..builder.threads) .map(|idx| { // clone service factories let factories = builder .factories .iter() .map(|f| f.clone_factory()) .collect::<Vec<_>>(); // start worker using service factories ServerWorker::start(idx, factories, waker_queue.clone(), builder.worker_config) }) .collect::<io::Result<Vec<_>>>()? .into_iter() .unzip(); let (mut accept, mut sockets) = Accept::new_with_sockets( poll, waker_queue.clone(), sockets, handles_accept, handle_server, )?; let accept_handle = thread::Builder::new() .name("actix-server acceptor".to_owned()) .spawn(move || accept.poll_with(&mut sockets)) .map_err(|err| io::Error::new(io::ErrorKind::Other, err))?; Ok((waker_queue, handles_server, accept_handle)) } fn new_with_sockets( poll: Poll, waker_queue: WakerQueue, sockets: Vec<(usize, MioListener)>, accept_handles: Vec<WorkerHandleAccept>, server_handle: ServerHandle, ) -> io::Result<(Accept, Box<[ServerSocketInfo]>)> { let sockets = sockets .into_iter() .map(|(token, mut lst)| { // Start listening for incoming connections poll.registry() .register(&mut lst, MioToken(token), Interest::READABLE)?; Ok(ServerSocketInfo { token, lst, timeout: None, }) }) .collect::<io::Result<_>>()?; let mut avail = Availability::default(); // Assume all handles are avail at construct time. avail.set_available_all(&accept_handles); let accept = Accept { poll, waker_queue, handles: accept_handles, srv: server_handle, next: 0, avail, timeout: None, paused: false, }; Ok((accept, sockets)) } /// blocking wait for readiness events triggered by mio fn poll_with(&mut self, sockets: &mut [ServerSocketInfo]) { let mut events = mio::Events::with_capacity(256); loop { if let Err(err) = self.poll.poll(&mut events, self.timeout) { match err.kind() { io::ErrorKind::Interrupted => {} _ => panic!("Poll error: {}", err), } } for event in events.iter() { let token = event.token(); match token { WAKER_TOKEN => { let exit = self.handle_waker(sockets); if exit { info!("accept thread stopped"); return; } } _ => { let token = usize::from(token); self.accept(sockets, token); } } } // check for timeout and re-register sockets self.process_timeout(sockets); } } fn handle_waker(&mut self, sockets: &mut [ServerSocketInfo]) -> bool { // This is a loop because interests for command from previous version was // a loop that would try to drain the command channel. It's yet unknown // if it's necessary/good practice to actively drain the waker queue. loop { // Take guard with every iteration so no new interests can be added until the current // task is done. Take care not to take the guard again inside this loop. let mut guard = self.waker_queue.guard(); #[allow(clippy::significant_drop_in_scrutinee)] match guard.pop_front() { // Worker notified it became available. Some(WakerInterest::WorkerAvailable(idx)) => { drop(guard); self.avail.set_available(idx, true); if !self.paused { self.accept_all(sockets); } } // A new worker thread has been created so store its handle. Some(WakerInterest::Worker(handle)) => { drop(guard); self.avail.set_available(handle.idx(), true); self.handles.push(handle); if !self.paused { self.accept_all(sockets); } } Some(WakerInterest::Pause) => { drop(guard); if !self.paused { self.paused = true; self.deregister_all(sockets); } } Some(WakerInterest::Resume) => { drop(guard); if self.paused { self.paused = false; sockets.iter_mut().for_each(|info| { self.register_logged(info); }); self.accept_all(sockets); } } Some(WakerInterest::Stop) => { if !self.paused { self.deregister_all(sockets); } return true; } // waker queue is drained None => { // Reset the WakerQueue before break so it does not grow infinitely WakerQueue::reset(&mut guard); return false; } } } } fn process_timeout(&mut self, sockets: &mut [ServerSocketInfo]) { // always remove old timeouts if self.timeout.take().is_some() { let now = Instant::now(); sockets .iter_mut() // Only sockets that had an associated timeout were deregistered. .filter(|info| info.timeout.is_some()) .for_each(|info| { let inst = info.timeout.take().unwrap(); if now < inst { // still timed out; try to set new timeout info.timeout = Some(inst); self.set_timeout(inst - now); } else if !self.paused { // timeout expired; register socket again self.register_logged(info); } // Drop the timeout if server is paused and socket timeout is expired. // When server recovers from pause it will register all sockets without // a timeout value so this socket register will be delayed till then. }); } } /// Update accept timeout with `duration` if it is shorter than current timeout. fn set_timeout(&mut self, duration: Duration) { match self.timeout { Some(ref mut timeout) => { if *timeout > duration { *timeout = duration; } } None => self.timeout = Some(duration), } } #[cfg(not(target_os = "windows"))] fn register(&self, info: &mut ServerSocketInfo) -> io::Result<()> { let token = MioToken(info.token); self.poll .registry() .register(&mut info.lst, token, Interest::READABLE) } #[cfg(target_os = "windows")] fn register(&self, info: &mut ServerSocketInfo) -> io::Result<()> { // On windows, calling register without deregister cause an error. // See https://github.com/actix/actix-web/issues/905 // Calling reregister seems to fix the issue. let token = MioToken(info.token); self.poll .registry() .register(&mut info.lst, token, Interest::READABLE) .or_else(|_| { self.poll .registry() .reregister(&mut info.lst, token, Interest::READABLE) }) } fn register_logged(&self, info: &mut ServerSocketInfo) { match self.register(info) { Ok(_) => debug!("resume accepting connections on {}", info.lst.local_addr()), Err(err) => error!("can not register server socket {}", err), } } fn deregister_logged(&self, info: &mut ServerSocketInfo) { match self.poll.registry().deregister(&mut info.lst) { Ok(_) => debug!("paused accepting connections on {}", info.lst.local_addr()), Err(err) => { error!("can not deregister server socket {}", err) } } } fn deregister_all(&self, sockets: &mut [ServerSocketInfo]) { // This is a best effort implementation with following limitation: // // Every ServerSocketInfo with associated timeout will be skipped and it's timeout is // removed in the process. // // Therefore WakerInterest::Pause followed by WakerInterest::Resume in a very short gap // (less than 500ms) would cause all timing out ServerSocketInfos be re-registered before // expected timing. sockets .iter_mut() // Take all timeout. // This is to prevent Accept::process_timer method re-register a socket afterwards. .map(|info| (info.timeout.take(), info)) // Socket info with a timeout is already deregistered so skip them. .filter(|(timeout, _)| timeout.is_none()) .for_each(|(_, info)| self.deregister_logged(info)); } // Send connection to worker and handle error. fn send_connection(&mut self, conn: Conn) -> Result<(), Conn> { let next = self.next(); match next.send(conn) { Ok(_) => { // Increment counter of WorkerHandle. // Set worker to unavailable with it hit max (Return false). if !next.inc_counter() { let idx = next.idx(); self.avail.set_available(idx, false); } self.set_next(); Ok(()) } Err(conn) => { // Worker thread is error and could be gone. // Remove worker handle and notify `ServerBuilder`. self.remove_next(); if self.handles.is_empty() { error!("no workers"); // All workers are gone and Conn is nowhere to be sent. // Treat this situation as Ok and drop Conn. return Ok(()); } else if self.handles.len() <= self.next { self.next = 0; } Err(conn) } } } fn accept_one(&mut self, mut conn: Conn) { loop { let next = self.next(); let idx = next.idx(); if self.avail.get_available(idx) { match self.send_connection(conn) { Ok(_) => return, Err(c) => conn = c, } } else { self.avail.set_available(idx, false); self.set_next(); if !self.avail.available() { while let Err(c) = self.send_connection(conn) { conn = c; } return; } } } } fn accept(&mut self, sockets: &mut [ServerSocketInfo], token: usize) { while self.avail.available() { let info = &mut sockets[token]; match info.lst.accept() { Ok(io) => { let conn = Conn { io, token }; self.accept_one(conn); } Err(ref err) if err.kind() == io::ErrorKind::WouldBlock => return, Err(ref err) if connection_error(err) => continue, Err(err) => { error!("error accepting connection: {}", err); // deregister listener temporary self.deregister_logged(info); // sleep after error. write the timeout to socket info as later // the poll would need it mark which socket and when it's // listener should be registered info.timeout = Some(Instant::now() + Duration::from_millis(500)); self.set_timeout(TIMEOUT_DURATION_ON_ERROR); return; } }; } } fn accept_all(&mut self, sockets: &mut [ServerSocketInfo]) { sockets .iter_mut() .map(|info| info.token) .collect::<Vec<_>>() .into_iter() .for_each(|idx| self.accept(sockets, idx)) } #[inline(always)] fn next(&self) -> &WorkerHandleAccept { &self.handles[self.next] } /// Set next worker handle that would accept connection. #[inline(always)] fn set_next(&mut self) { self.next = (self.next + 1) % self.handles.len(); } /// Remove next worker handle that fail to accept connection. fn remove_next(&mut self) { let handle = self.handles.swap_remove(self.next); let idx = handle.idx(); // A message is sent to `ServerBuilder` future to notify it a new worker // should be made. self.srv.worker_faulted(idx); self.avail.set_available(idx, false); } } /// This function defines errors that are per-connection; if we get this error from the `accept()` /// system call it means the next connection might be ready to be accepted. /// /// All other errors will incur a timeout before next `accept()` call is attempted. The timeout is /// useful to handle resource exhaustion errors like `ENFILE` and `EMFILE`. Otherwise, it could /// enter into a temporary spin loop. fn connection_error(e: &io::Error) -> bool { e.kind() == io::ErrorKind::ConnectionRefused || e.kind() == io::ErrorKind::ConnectionAborted || e.kind() == io::ErrorKind::ConnectionReset }
use crate::worker::WorkerHandleAccept; /// Array of u128 with every bit as marker for a worker handle's availability. #[derive(Debug, Default)] pub(crate) struct Availability([u128; 4]); impl Availability { /// Check if any worker handle is available #[inline(always)] pub(crate) fn available(&self) -> bool { self.0.iter().any(|a| *a != 0) } /// Check if worker handle is available by index #[inline(always)] pub(crate) fn get_available(&self, idx: usize) -> bool { let (offset, idx) = Self::offset(idx); self.0[offset] & (1 << idx as u128) != 0 } /// Set worker handle available state by index. pub(crate) fn set_available(&mut self, idx: usize, avail: bool) { let (offset, idx) = Self::offset(idx); let off = 1 << idx as u128; if avail { self.0[offset] |= off; } else { self.0[offset] &= !off } } /// Set all worker handle to available state. /// This would result in a re-check on all workers' availability. pub(crate) fn set_available_all(&mut self, handles: &[WorkerHandleAccept]) { handles.iter().for_each(|handle| { self.set_available(handle.idx(), true); }) } /// Get offset and adjusted index of given worker handle index. pub(crate) fn offset(idx: usize) -> (usize, usize) { if idx < 128 { (0, idx) } else if idx < 128 * 2 { (1, idx - 128) } else if idx < 128 * 3 { (2, idx - 128 * 2) } else if idx < 128 * 4 { (3, idx - 128 * 3) } else { panic!("Max WorkerHandle count is 512") } } } #[cfg(test)] mod tests { use super::*; fn single(aval: &mut Availability, idx: usize) { aval.set_available(idx, true); assert!(aval.available()); aval.set_available(idx, true); aval.set_available(idx, false); assert!(!aval.available()); aval.set_available(idx, false); assert!(!aval.available()); } fn multi(aval: &mut Availability, mut idx: Vec<usize>) { idx.iter().for_each(|idx| aval.set_available(*idx, true)); assert!(aval.available()); while let Some(idx) = idx.pop() { assert!(aval.available()); aval.set_available(idx, false); } assert!(!aval.available()); } #[test] fn availability() { let mut aval = Availability::default(); single(&mut aval, 1); single(&mut aval, 128); single(&mut aval, 256); single(&mut aval, 511); let idx = (0..511).filter(|i| i % 3 == 0 && i % 5 == 0).collect(); multi(&mut aval, idx); multi(&mut aval, (0..511).collect()) } #[test] #[should_panic] fn overflow() { let mut aval = Availability::default(); single(&mut aval, 512); } #[test] fn pin_point() { let mut aval = Availability::default(); aval.set_available(438, true); aval.set_available(479, true); assert_eq!(aval.0[3], 1 << (438 - 384) | 1 << (479 - 384)); } }
use std::{io, num::NonZeroUsize, time::Duration}; use actix_rt::net::TcpStream; use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender}; use crate::{ server::ServerCommand, service::{InternalServiceFactory, ServerServiceFactory, StreamNewService}, socket::{create_mio_tcp_listener, MioListener, MioTcpListener, StdTcpListener, ToSocketAddrs}, worker::ServerWorkerConfig, Server, }; /// Multipath TCP (MPTCP) preference. /// /// Currently only useful on Linux. /// #[cfg_attr(target_os = "linux", doc = "Also see [`ServerBuilder::mptcp()`].")] #[derive(Debug, Clone)] pub enum MpTcp { /// MPTCP will not be used when binding sockets. Disabled, /// MPTCP will be attempted when binding sockets. If errors occur, regular TCP will be /// attempted, too. TcpFallback, /// MPTCP will be used when binding sockets (with no fallback). NoFallback, } /// [Server] builder. pub struct ServerBuilder { pub(crate) threads: usize, pub(crate) token: usize, pub(crate) backlog: u32, pub(crate) factories: Vec<Box<dyn InternalServiceFactory>>, pub(crate) sockets: Vec<(usize, String, MioListener)>, pub(crate) mptcp: MpTcp, pub(crate) exit: bool, pub(crate) listen_os_signals: bool, pub(crate) cmd_tx: UnboundedSender<ServerCommand>, pub(crate) cmd_rx: UnboundedReceiver<ServerCommand>, pub(crate) worker_config: ServerWorkerConfig, } impl Default for ServerBuilder { fn default() -> Self { Self::new() } } impl ServerBuilder { /// Create new Server builder instance pub fn new() -> ServerBuilder { let (cmd_tx, cmd_rx) = unbounded_channel(); ServerBuilder { threads: std::thread::available_parallelism().map_or(2, NonZeroUsize::get), token: 0, factories: Vec::new(), sockets: Vec::new(), backlog: 2048, mptcp: MpTcp::Disabled, exit: false, listen_os_signals: true, cmd_tx, cmd_rx, worker_config: ServerWorkerConfig::default(), } } /// Sets number of workers to start. /// /// See [`bind()`](Self::bind()) for more details on how worker count affects the number of /// server factory instantiations. /// /// The default worker count is the determined by [`std::thread::available_parallelism()`]. See /// its documentation to determine what behavior you should expect when server is run. /// /// `num` must be greater than 0. /// /// # Panics /// /// Panics if `num` is 0. pub fn workers(mut self, num: usize) -> Self { assert_ne!(num, 0, "workers must be greater than 0"); self.threads = num; self } /// Set max number of threads for each worker's blocking task thread pool. /// /// One thread pool is set up **per worker**; not shared across workers. /// /// # Examples: /// ``` /// # use actix_server::ServerBuilder; /// let builder = ServerBuilder::new() /// .workers(4) // server has 4 worker thread. /// .worker_max_blocking_threads(4); // every worker has 4 max blocking threads. /// ``` /// /// See [tokio::runtime::Builder::max_blocking_threads] for behavior reference. pub fn worker_max_blocking_threads(mut self, num: usize) -> Self { self.worker_config.max_blocking_threads(num); self } /// Set the maximum number of pending connections. /// /// This refers to the number of clients that can be waiting to be served. Exceeding this number /// results in the client getting an error when attempting to connect. It should only affect /// servers under significant load. /// /// Generally set in the 64-2048 range. Default value is 2048. /// /// This method should be called before `bind()` method call. pub fn backlog(mut self, num: u32) -> Self { self.backlog = num; self } /// Sets MultiPath TCP (MPTCP) preference on bound sockets. /// /// Multipath TCP (MPTCP) builds on top of TCP to improve connection redundancy and performance /// by sharing a network data stream across multiple underlying TCP sessions. See [mptcp.dev] /// for more info about MPTCP itself. /// /// MPTCP is available on Linux kernel version 5.6 and higher. In addition, you'll also need to /// ensure the kernel option is enabled using `sysctl net.mptcp.enabled=1`. /// /// This method will have no effect if called after a `bind()`. /// /// [mptcp.dev]: https://www.mptcp.dev #[cfg(target_os = "linux")] pub fn mptcp(mut self, mptcp_enabled: MpTcp) -> Self { self.mptcp = mptcp_enabled; self } /// Sets the maximum per-worker number of concurrent connections. /// /// All socket listeners will stop accepting connections when this limit is reached for /// each worker. /// /// By default max connections is set to a 25k per worker. pub fn max_concurrent_connections(mut self, num: usize) -> Self { self.worker_config.max_concurrent_connections(num); self } #[doc(hidden)] #[deprecated(since = "2.0.0", note = "Renamed to `max_concurrent_connections`.")] pub fn maxconn(self, num: usize) -> Self { self.max_concurrent_connections(num) } /// Sets flag to stop Actix `System` after server shutdown. /// /// This has no effect when server is running in a Tokio-only runtime. pub fn system_exit(mut self) -> Self { self.exit = true; self } /// Disables OS signal handling. pub fn disable_signals(mut self) -> Self { self.listen_os_signals = false; self } /// Timeout for graceful workers shutdown in seconds. /// /// After receiving a stop signal, workers have this much time to finish serving requests. /// Workers still alive after the timeout are force dropped. /// /// By default shutdown timeout sets to 30 seconds. pub fn shutdown_timeout(mut self, sec: u64) -> Self { self.worker_config .shutdown_timeout(Duration::from_secs(sec)); self } /// Adds new service to the server. /// /// Note that, if a DNS lookup is required, resolving hostnames is a blocking operation. /// /// # Worker Count /// /// The `factory` will be instantiated multiple times in most scenarios. The number of /// instantiations is number of [`workers`](Self::workers()) × number of sockets resolved by /// `addrs`. /// /// For example, if you've manually set [`workers`](Self::workers()) to 2, and use `127.0.0.1` /// as the bind `addrs`, then `factory` will be instantiated twice. However, using `localhost` /// as the bind `addrs` can often resolve to both `127.0.0.1` (IPv4) _and_ `::1` (IPv6), causing /// the `factory` to be instantiated 4 times (2 workers × 2 bind addresses). /// /// Using a bind address of `0.0.0.0`, which signals to use all interfaces, may also multiple /// the number of instantiations in a similar way. /// /// # Errors /// /// Returns an `io::Error` if: /// - `addrs` cannot be resolved into one or more socket addresses; /// - all the resolved socket addresses are already bound. pub fn bind<F, U, N>(mut self, name: N, addrs: U, factory: F) -> io::Result<Self> where F: ServerServiceFactory<TcpStream>, U: ToSocketAddrs, N: AsRef<str>, { let sockets = bind_addr(addrs, self.backlog, &self.mptcp)?; tracing::trace!("binding server to: {sockets:?}"); for lst in sockets { let token = self.next_token(); self.factories.push(StreamNewService::create( name.as_ref().to_string(), token, factory.clone(), lst.local_addr()?, )); self.sockets .push((token, name.as_ref().to_string(), MioListener::Tcp(lst))); } Ok(self) } /// Adds service to the server using a socket listener already bound. /// /// # Worker Count /// /// The `factory` will be instantiated multiple times in most scenarios. The number of /// instantiations is: number of [`workers`](Self::workers()). pub fn listen<F, N: AsRef<str>>( mut self, name: N, lst: StdTcpListener, factory: F, ) -> io::Result<Self> where F: ServerServiceFactory<TcpStream>, { lst.set_nonblocking(true)?; let addr = lst.local_addr()?; let token = self.next_token(); self.factories.push(StreamNewService::create( name.as_ref().to_string(), token, factory, addr, )); self.sockets .push((token, name.as_ref().to_string(), MioListener::from(lst))); Ok(self) } /// Starts processing incoming connections and return server controller. pub fn run(self) -> Server { if self.sockets.is_empty() { panic!("Server should have at least one bound socket"); } else { tracing::info!("starting {} workers", self.threads); Server::new(self) } } fn next_token(&mut self) -> usize { let token = self.token; self.token += 1; token } } #[cfg(unix)] impl ServerBuilder { /// Adds new service to the server using a UDS (unix domain socket) address. /// /// # Worker Count /// /// The `factory` will be instantiated multiple times in most scenarios. The number of /// instantiations is: number of [`workers`](Self::workers()). pub fn bind_uds<F, U, N>(self, name: N, addr: U, factory: F) -> io::Result<Self> where F: ServerServiceFactory<actix_rt::net::UnixStream>, N: AsRef<str>, U: AsRef<std::path::Path>, { // The path must not exist when we try to bind. // Try to remove it to avoid bind error. if let Err(err) = std::fs::remove_file(addr.as_ref()) { // NotFound is expected and not an issue. Anything else is. if err.kind() != std::io::ErrorKind::NotFound { return Err(err); } } let lst = crate::socket::StdUnixListener::bind(addr)?; self.listen_uds(name, lst, factory) } /// Adds new service to the server using a UDS (unix domain socket) listener already bound. /// /// Useful when running as a systemd service and a socket FD is acquired externally. /// /// # Worker Count /// /// The `factory` will be instantiated multiple times in most scenarios. The number of /// instantiations is: number of [`workers`](Self::workers()). pub fn listen_uds<F, N: AsRef<str>>( mut self, name: N, lst: crate::socket::StdUnixListener, factory: F, ) -> io::Result<Self> where F: ServerServiceFactory<actix_rt::net::UnixStream>, { use std::net::{IpAddr, Ipv4Addr}; lst.set_nonblocking(true)?; let token = self.next_token(); let addr = crate::socket::StdSocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080); self.factories.push(StreamNewService::create( name.as_ref().to_string(), token, factory, addr, )); self.sockets .push((token, name.as_ref().to_string(), MioListener::from(lst))); Ok(self) } } pub(super) fn bind_addr<S: ToSocketAddrs>( addr: S, backlog: u32, mptcp: &MpTcp, ) -> io::Result<Vec<MioTcpListener>> { let mut opt_err = None; let mut success = false; let mut sockets = Vec::new(); for addr in addr.to_socket_addrs()? { match create_mio_tcp_listener(addr, backlog, mptcp) { Ok(lst) => { success = true; sockets.push(lst); } Err(err) => opt_err = Some(err), } } if success { Ok(sockets) } else if let Some(err) = opt_err.take() { Err(err) } else { Err(io::Error::new( io::ErrorKind::Other, "Can not bind to address.", )) } }
use std::future::Future; use tokio::sync::{mpsc::UnboundedSender, oneshot}; use crate::server::ServerCommand; /// Server handle. #[derive(Debug, Clone)] pub struct ServerHandle { cmd_tx: UnboundedSender<ServerCommand>, } impl ServerHandle { pub(crate) fn new(cmd_tx: UnboundedSender<ServerCommand>) -> Self { ServerHandle { cmd_tx } } pub(crate) fn worker_faulted(&self, idx: usize) { let _ = self.cmd_tx.send(ServerCommand::WorkerFaulted(idx)); } /// Pause accepting incoming connections. /// /// May drop socket pending connection. All open connections remain active. pub fn pause(&self) -> impl Future<Output = ()> { let (tx, rx) = oneshot::channel(); let _ = self.cmd_tx.send(ServerCommand::Pause(tx)); async { let _ = rx.await; } } /// Resume accepting incoming connections. pub fn resume(&self) -> impl Future<Output = ()> { let (tx, rx) = oneshot::channel(); let _ = self.cmd_tx.send(ServerCommand::Resume(tx)); async { let _ = rx.await; } } /// Stop incoming connection processing, stop all workers and exit. pub fn stop(&self, graceful: bool) -> impl Future<Output = ()> { let (tx, rx) = oneshot::channel(); let _ = self.cmd_tx.send(ServerCommand::Stop { graceful, completion: Some(tx), force_system_stop: false, }); async { let _ = rx.await; } } }
use std::{ future::Future, pin::Pin, task::{Context, Poll}, }; use futures_core::future::BoxFuture; // a poor man's join future. joined future is only used when starting/stopping the server. // pin_project and pinned futures are overkill for this task. pub(crate) struct JoinAll<T> { fut: Vec<JoinFuture<T>>, } pub(crate) fn join_all<T>(fut: Vec<impl Future<Output = T> + Send + 'static>) -> JoinAll<T> { let fut = fut .into_iter() .map(|f| JoinFuture::Future(Box::pin(f))) .collect(); JoinAll { fut } } enum JoinFuture<T> { Future(BoxFuture<'static, T>), Result(Option<T>), } impl<T> Unpin for JoinAll<T> {} impl<T> Future for JoinAll<T> { type Output = Vec<T>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let mut ready = true; let this = self.get_mut(); for fut in this.fut.iter_mut() { if let JoinFuture::Future(f) = fut { match f.as_mut().poll(cx) { Poll::Ready(t) => { *fut = JoinFuture::Result(Some(t)); } Poll::Pending => ready = false, } } } if ready { let mut res = Vec::new(); for fut in this.fut.iter_mut() { if let JoinFuture::Result(f) = fut { res.push(f.take().unwrap()); } } Poll::Ready(res) } else { Poll::Pending } } } #[cfg(test)] mod test { use actix_utils::future::ready; use super::*; #[actix_rt::test] async fn test_join_all() { let futs = vec![ready(Ok(1)), ready(Err(3)), ready(Ok(9))]; let mut res = join_all(futs).await.into_iter(); assert_eq!(Ok(1), res.next().unwrap()); assert_eq!(Err(3), res.next().unwrap()); assert_eq!(Ok(9), res.next().unwrap()); } }
//! General purpose TCP server. #![doc(html_logo_url = "https://actix.rs/img/logo.png")] #![doc(html_favicon_url = "https://actix.rs/favicon.ico")] mod accept; mod availability; mod builder; mod handle; mod join_all; mod server; mod service; mod signals; mod socket; mod test_server; mod waker_queue; mod worker; #[doc(hidden)] pub use self::socket::FromStream; pub use self::{ builder::{MpTcp, ServerBuilder}, handle::ServerHandle, server::Server, service::ServerServiceFactory, test_server::TestServer, }; /// Start server building process #[doc(hidden)] #[deprecated(since = "2.0.0", note = "Use `Server::build()`.")] pub fn new() -> ServerBuilder { ServerBuilder::default() }
use std::{ future::Future, io, mem, pin::Pin, task::{Context, Poll}, thread, time::Duration, }; use actix_rt::{time::sleep, System}; use futures_core::{future::BoxFuture, Stream}; use futures_util::stream::StreamExt as _; use tokio::sync::{mpsc::UnboundedReceiver, oneshot}; use tracing::{error, info}; use crate::{ accept::Accept, builder::ServerBuilder, join_all::join_all, service::InternalServiceFactory, signals::{SignalKind, Signals}, waker_queue::{WakerInterest, WakerQueue}, worker::{ServerWorker, ServerWorkerConfig, WorkerHandleServer}, ServerHandle, }; #[derive(Debug)] pub(crate) enum ServerCommand { /// Worker failed to accept connection, indicating a probable panic. /// /// Contains index of faulted worker. WorkerFaulted(usize), /// Pause accepting connections. /// /// Contains return channel to notify caller of successful state change. Pause(oneshot::Sender<()>), /// Resume accepting connections. /// /// Contains return channel to notify caller of successful state change. Resume(oneshot::Sender<()>), /// Stop accepting connections and begin shutdown procedure. Stop { /// True if shut down should be graceful. graceful: bool, /// Return channel to notify caller that shutdown is complete. completion: Option<oneshot::Sender<()>>, /// Force System exit when true, overriding `ServerBuilder::system_exit()` if it is false. force_system_stop: bool, }, } /// General purpose TCP server that runs services receiving Tokio `TcpStream`s. /// /// Handles creating worker threads, restarting faulted workers, connection accepting, and /// back-pressure logic. /// /// Creates a worker per CPU core (or the number specified in [`ServerBuilder::workers`]) and /// distributes connections with a round-robin strategy. /// /// The [Server] must be awaited or polled in order to start running. It will resolve when the /// server has fully shut down. /// /// # Shutdown Signals /// On UNIX systems, `SIGTERM` will start a graceful shutdown and `SIGQUIT` or `SIGINT` will start a /// forced shutdown. On Windows, a Ctrl-C signal will start a forced shutdown. /// /// A graceful shutdown will wait for all workers to stop first. /// /// # Examples /// The following is a TCP echo server. Test using `telnet 127.0.0.1 8080`. /// /// ```no_run /// use std::io; /// /// use actix_rt::net::TcpStream; /// use actix_server::Server; /// use actix_service::{fn_service, ServiceFactoryExt as _}; /// use bytes::BytesMut; /// use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _}; /// /// #[actix_rt::main] /// async fn main() -> io::Result<()> { /// let bind_addr = ("127.0.0.1", 8080); /// /// Server::build() /// .bind("echo", bind_addr, move || { /// fn_service(move |mut stream: TcpStream| { /// async move { /// let mut size = 0; /// let mut buf = BytesMut::new(); /// /// loop { /// match stream.read_buf(&mut buf).await { /// // end of stream; bail from loop /// Ok(0) => break, /// /// // write bytes back to stream /// Ok(bytes_read) => { /// stream.write_all(&buf[size..]).await.unwrap(); /// size += bytes_read; /// } /// /// Err(err) => { /// eprintln!("Stream Error: {:?}", err); /// return Err(()); /// } /// } /// } /// /// Ok(()) /// } /// }) /// .map_err(|err| eprintln!("Service Error: {:?}", err)) /// })? /// .run() /// .await /// } /// ``` #[must_use = "Server does nothing unless you `.await` or poll it"] pub struct Server { handle: ServerHandle, fut: BoxFuture<'static, io::Result<()>>, } impl Server { /// Create server build. pub fn build() -> ServerBuilder { ServerBuilder::default() } pub(crate) fn new(builder: ServerBuilder) -> Self { Server { handle: ServerHandle::new(builder.cmd_tx.clone()), fut: Box::pin(ServerInner::run(builder)), } } /// Get a `Server` handle that can be used issue commands and change it's state. /// /// See [ServerHandle](ServerHandle) for usage. pub fn handle(&self) -> ServerHandle { self.handle.clone() } } impl Future for Server { type Output = io::Result<()>; #[inline] fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { Pin::new(&mut Pin::into_inner(self).fut).poll(cx) } } pub struct ServerInner { worker_handles: Vec<WorkerHandleServer>, accept_handle: Option<thread::JoinHandle<()>>, worker_config: ServerWorkerConfig, services: Vec<Box<dyn InternalServiceFactory>>, waker_queue: WakerQueue, system_stop: bool, stopping: bool, } impl ServerInner { async fn run(builder: ServerBuilder) -> io::Result<()> { let (mut this, mut mux) = Self::run_sync(builder)?; while let Some(cmd) = mux.next().await { this.handle_cmd(cmd).await; if this.stopping { break; } } Ok(()) } fn run_sync(mut builder: ServerBuilder) -> io::Result<(Self, ServerEventMultiplexer)> { // Give log information on what runtime will be used. let is_actix = actix_rt::System::try_current().is_some(); let is_tokio = tokio::runtime::Handle::try_current().is_ok(); match (is_actix, is_tokio) { (true, _) => info!("Actix runtime found; starting in Actix runtime"), (_, true) => info!("Tokio runtime found; starting in existing Tokio runtime"), (_, false) => panic!("Actix or Tokio runtime not found; halting"), } for (_, name, lst) in &builder.sockets { info!( r#"starting service: "{}", workers: {}, listening on: {}"#, name, builder.threads, lst.local_addr() ); } let sockets = mem::take(&mut builder.sockets) .into_iter() .map(|t| (t.0, t.2)) .collect(); let (waker_queue, worker_handles, accept_handle) = Accept::start(sockets, &builder)?; let mux = ServerEventMultiplexer { signal_fut: (builder.listen_os_signals).then(Signals::new), cmd_rx: builder.cmd_rx, }; let server = ServerInner { waker_queue, accept_handle: Some(accept_handle), worker_handles, worker_config: builder.worker_config, services: builder.factories, system_stop: builder.exit, stopping: false, }; Ok((server, mux)) } async fn handle_cmd(&mut self, item: ServerCommand) { match item { ServerCommand::Pause(tx) => { self.waker_queue.wake(WakerInterest::Pause); let _ = tx.send(()); } ServerCommand::Resume(tx) => { self.waker_queue.wake(WakerInterest::Resume); let _ = tx.send(()); } ServerCommand::Stop { graceful, completion, force_system_stop, } => { self.stopping = true; // Signal accept thread to stop. // Signal is non-blocking; we wait for thread to stop later. self.waker_queue.wake(WakerInterest::Stop); // send stop signal to workers let workers_stop = self .worker_handles .iter() .map(|worker| worker.stop(graceful)) .collect::<Vec<_>>(); if graceful { // wait for all workers to shut down let _ = join_all(workers_stop).await; } // wait for accept thread stop self.accept_handle .take() .unwrap() .join() .expect("Accept thread must not panic in any case"); if let Some(tx) = completion { let _ = tx.send(()); } if self.system_stop || force_system_stop { sleep(Duration::from_millis(300)).await; System::try_current().as_ref().map(System::stop); } } ServerCommand::WorkerFaulted(idx) => { // TODO: maybe just return with warning log if not found ? assert!(self.worker_handles.iter().any(|wrk| wrk.idx == idx)); error!("worker {} has died; restarting", idx); let factories = self .services .iter() .map(|service| service.clone_factory()) .collect(); match ServerWorker::start( idx, factories, self.waker_queue.clone(), self.worker_config, ) { Ok((handle_accept, handle_server)) => { *self .worker_handles .iter_mut() .find(|wrk| wrk.idx == idx) .unwrap() = handle_server; self.waker_queue.wake(WakerInterest::Worker(handle_accept)); } Err(err) => error!("can not restart worker {}: {}", idx, err), }; } } } fn map_signal(signal: SignalKind) -> ServerCommand { match signal { SignalKind::Int => { info!("SIGINT received; starting forced shutdown"); ServerCommand::Stop { graceful: false, completion: None, force_system_stop: true, } } SignalKind::Term => { info!("SIGTERM received; starting graceful shutdown"); ServerCommand::Stop { graceful: true, completion: None, force_system_stop: true, } } SignalKind::Quit => { info!("SIGQUIT received; starting forced shutdown"); ServerCommand::Stop { graceful: false, completion: None, force_system_stop: true, } } } } } struct ServerEventMultiplexer { cmd_rx: UnboundedReceiver<ServerCommand>, signal_fut: Option<Signals>, } impl Stream for ServerEventMultiplexer { type Item = ServerCommand; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { let this = Pin::into_inner(self); if let Some(signal_fut) = &mut this.signal_fut { if let Poll::Ready(signal) = Pin::new(signal_fut).poll(cx) { this.signal_fut = None; return Poll::Ready(Some(ServerInner::map_signal(signal))); } } this.cmd_rx.poll_recv(cx) } }
use std::{ marker::PhantomData, net::SocketAddr, task::{Context, Poll}, }; use actix_service::{Service, ServiceFactory as BaseServiceFactory}; use actix_utils::future::{ready, Ready}; use futures_core::future::LocalBoxFuture; use tracing::error; use crate::{ socket::{FromStream, MioStream}, worker::WorkerCounterGuard, }; #[doc(hidden)] pub trait ServerServiceFactory<Stream: FromStream>: Send + Clone + 'static { type Factory: BaseServiceFactory<Stream, Config = ()>; fn create(&self) -> Self::Factory; } pub(crate) trait InternalServiceFactory: Send { fn name(&self, token: usize) -> &str; fn clone_factory(&self) -> Box<dyn InternalServiceFactory>; fn create(&self) -> LocalBoxFuture<'static, Result<(usize, BoxedServerService), ()>>; } pub(crate) type BoxedServerService = Box< dyn Service< (WorkerCounterGuard, MioStream), Response = (), Error = (), Future = Ready<Result<(), ()>>, >, >; pub(crate) struct StreamService<S, I> { service: S, _phantom: PhantomData<I>, } impl<S, I> StreamService<S, I> { pub(crate) fn new(service: S) -> Self { StreamService { service, _phantom: PhantomData, } } } impl<S, I> Service<(WorkerCounterGuard, MioStream)> for StreamService<S, I> where S: Service<I>, S::Future: 'static, S::Error: 'static, I: FromStream, { type Response = (); type Error = (); type Future = Ready<Result<(), ()>>; fn poll_ready(&self, ctx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { self.service.poll_ready(ctx).map_err(|_| ()) } fn call(&self, (guard, req): (WorkerCounterGuard, MioStream)) -> Self::Future { ready(match FromStream::from_mio(req) { Ok(stream) => { let f = self.service.call(stream); actix_rt::spawn(async move { let _ = f.await; drop(guard); }); Ok(()) } Err(err) => { error!("can not convert to an async TCP stream: {err}"); Err(()) } }) } } pub(crate) struct StreamNewService<F: ServerServiceFactory<Io>, Io: FromStream> { name: String, inner: F, token: usize, addr: SocketAddr, _t: PhantomData<Io>, } impl<F, Io> StreamNewService<F, Io> where F: ServerServiceFactory<Io>, Io: FromStream + Send + 'static, { pub(crate) fn create( name: String, token: usize, inner: F, addr: SocketAddr, ) -> Box<dyn InternalServiceFactory> { Box::new(Self { name, token, inner, addr, _t: PhantomData, }) } } impl<F, Io> InternalServiceFactory for StreamNewService<F, Io> where F: ServerServiceFactory<Io>, Io: FromStream + Send + 'static, { fn name(&self, _: usize) -> &str { &self.name } fn clone_factory(&self) -> Box<dyn InternalServiceFactory> { Box::new(Self { name: self.name.clone(), inner: self.inner.clone(), token: self.token, addr: self.addr, _t: PhantomData, }) } fn create(&self) -> LocalBoxFuture<'static, Result<(usize, BoxedServerService), ()>> { let token = self.token; let fut = self.inner.create().new_service(()); Box::pin(async move { match fut.await { Ok(inner) => { let service = Box::new(StreamService::new(inner)) as _; Ok((token, service)) } Err(_) => Err(()), } }) } } impl<F, T, I> ServerServiceFactory<I> for F where F: Fn() -> T + Send + Clone + 'static, T: BaseServiceFactory<I, Config = ()>, I: FromStream, { type Factory = T; fn create(&self) -> T { (self)() } }
use std::{ fmt, future::Future, pin::Pin, task::{Context, Poll}, }; use tracing::trace; /// Types of process signals. // #[allow(dead_code)] #[derive(Debug, Clone, Copy, PartialEq)] #[allow(dead_code)] // variants are never constructed on non-unix pub(crate) enum SignalKind { /// `SIGINT` Int, /// `SIGTERM` Term, /// `SIGQUIT` Quit, } impl fmt::Display for SignalKind { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(match self { SignalKind::Int => "SIGINT", SignalKind::Term => "SIGTERM", SignalKind::Quit => "SIGQUIT", }) } } /// Process signal listener. pub(crate) struct Signals { #[cfg(not(unix))] signals: futures_core::future::BoxFuture<'static, std::io::Result<()>>, #[cfg(unix)] signals: Vec<(SignalKind, actix_rt::signal::unix::Signal)>, } impl Signals { /// Constructs an OS signal listening future. pub(crate) fn new() -> Self { trace!("setting up OS signal listener"); #[cfg(not(unix))] { Signals { signals: Box::pin(actix_rt::signal::ctrl_c()), } } #[cfg(unix)] { use actix_rt::signal::unix; let sig_map = [ (unix::SignalKind::interrupt(), SignalKind::Int), (unix::SignalKind::terminate(), SignalKind::Term), (unix::SignalKind::quit(), SignalKind::Quit), ]; let signals = sig_map .iter() .filter_map(|(kind, sig)| { unix::signal(*kind) .map(|tokio_sig| (*sig, tokio_sig)) .map_err(|e| { tracing::error!( "can not initialize stream handler for {:?} err: {}", sig, e ) }) .ok() }) .collect::<Vec<_>>(); Signals { signals } } } } impl Future for Signals { type Output = SignalKind; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { #[cfg(not(unix))] { self.signals.as_mut().poll(cx).map(|_| SignalKind::Int) } #[cfg(unix)] { for (sig, fut) in self.signals.iter_mut() { if fut.poll_recv(cx).is_ready() { trace!("{} received", sig); return Poll::Ready(*sig); } } Poll::Pending } } }
pub(crate) use std::net::{ SocketAddr as StdSocketAddr, TcpListener as StdTcpListener, ToSocketAddrs, }; use std::{fmt, io}; use actix_rt::net::TcpStream; pub(crate) use mio::net::TcpListener as MioTcpListener; use mio::{event::Source, Interest, Registry, Token}; #[cfg(unix)] pub(crate) use { mio::net::UnixListener as MioUnixListener, std::os::unix::net::UnixListener as StdUnixListener, }; use crate::builder::MpTcp; pub(crate) enum MioListener { Tcp(MioTcpListener), #[cfg(unix)] Uds(MioUnixListener), } impl MioListener { pub(crate) fn local_addr(&self) -> SocketAddr { match *self { MioListener::Tcp(ref lst) => lst .local_addr() .map(SocketAddr::Tcp) .unwrap_or(SocketAddr::Unknown), #[cfg(unix)] MioListener::Uds(ref lst) => lst .local_addr() .map(SocketAddr::Uds) .unwrap_or(SocketAddr::Unknown), } } pub(crate) fn accept(&self) -> io::Result<MioStream> { match *self { MioListener::Tcp(ref lst) => lst.accept().map(|(stream, _)| MioStream::Tcp(stream)), #[cfg(unix)] MioListener::Uds(ref lst) => lst.accept().map(|(stream, _)| MioStream::Uds(stream)), } } } impl Source for MioListener { fn register( &mut self, registry: &Registry, token: Token, interests: Interest, ) -> io::Result<()> { match *self { MioListener::Tcp(ref mut lst) => lst.register(registry, token, interests), #[cfg(unix)] MioListener::Uds(ref mut lst) => lst.register(registry, token, interests), } } fn reregister( &mut self, registry: &Registry, token: Token, interests: Interest, ) -> io::Result<()> { match *self { MioListener::Tcp(ref mut lst) => lst.reregister(registry, token, interests), #[cfg(unix)] MioListener::Uds(ref mut lst) => lst.reregister(registry, token, interests), } } fn deregister(&mut self, registry: &Registry) -> io::Result<()> { match *self { MioListener::Tcp(ref mut lst) => lst.deregister(registry), #[cfg(unix)] MioListener::Uds(ref mut lst) => { let res = lst.deregister(registry); // cleanup file path if let Ok(addr) = lst.local_addr() { if let Some(path) = addr.as_pathname() { let _ = std::fs::remove_file(path); } } res } } } } impl From<StdTcpListener> for MioListener { fn from(lst: StdTcpListener) -> Self { MioListener::Tcp(MioTcpListener::from_std(lst)) } } #[cfg(unix)] impl From<StdUnixListener> for MioListener { fn from(lst: StdUnixListener) -> Self { MioListener::Uds(MioUnixListener::from_std(lst)) } } impl fmt::Debug for MioListener { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { MioListener::Tcp(ref lst) => write!(f, "{:?}", lst), #[cfg(unix)] MioListener::Uds(ref lst) => write!(f, "{:?}", lst), } } } impl fmt::Display for MioListener { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { MioListener::Tcp(ref lst) => write!(f, "{:?}", lst), #[cfg(unix)] MioListener::Uds(ref lst) => write!(f, "{:?}", lst), } } } pub(crate) enum SocketAddr { Unknown, Tcp(StdSocketAddr), #[cfg(unix)] Uds(std::os::unix::net::SocketAddr), } impl fmt::Display for SocketAddr { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { Self::Unknown => write!(f, "Unknown SocketAddr"), Self::Tcp(ref addr) => write!(f, "{}", addr), #[cfg(unix)] Self::Uds(ref addr) => write!(f, "{:?}", addr), } } } impl fmt::Debug for SocketAddr { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { Self::Unknown => write!(f, "Unknown SocketAddr"), Self::Tcp(ref addr) => write!(f, "{:?}", addr), #[cfg(unix)] Self::Uds(ref addr) => write!(f, "{:?}", addr), } } } #[derive(Debug)] pub enum MioStream { Tcp(mio::net::TcpStream), #[cfg(unix)] Uds(mio::net::UnixStream), } /// Helper trait for converting a Mio stream into a Tokio stream. pub trait FromStream: Sized { /// Creates stream from a `mio` stream. fn from_mio(sock: MioStream) -> io::Result<Self>; } #[cfg(windows)] mod win_impl { use std::os::windows::io::{FromRawSocket, IntoRawSocket}; use super::*; // TODO: This is a workaround and we need an efficient way to convert between Mio and Tokio stream impl FromStream for TcpStream { fn from_mio(sock: MioStream) -> io::Result<Self> { match sock { MioStream::Tcp(mio) => { let raw = IntoRawSocket::into_raw_socket(mio); // SAFETY: This is an in-place conversion from Mio stream to Tokio stream. TcpStream::from_std(unsafe { FromRawSocket::from_raw_socket(raw) }) } } } } } #[cfg(unix)] mod unix_impl { use std::os::unix::io::{FromRawFd, IntoRawFd}; use actix_rt::net::UnixStream; use super::*; // HACK: This is a workaround and we need an efficient way to convert between Mio and Tokio stream impl FromStream for TcpStream { fn from_mio(sock: MioStream) -> io::Result<Self> { match sock { MioStream::Tcp(mio) => { let raw = IntoRawFd::into_raw_fd(mio); // SAFETY: This is an in-place conversion from Mio stream to Tokio stream. TcpStream::from_std(unsafe { FromRawFd::from_raw_fd(raw) }) } MioStream::Uds(_) => { panic!("Should not happen, bug in server impl"); } } } } // HACK: This is a workaround and we need an efficient way to convert between Mio and Tokio stream impl FromStream for UnixStream { fn from_mio(sock: MioStream) -> io::Result<Self> { match sock { MioStream::Tcp(_) => panic!("Should not happen, bug in server impl"), MioStream::Uds(mio) => { let raw = IntoRawFd::into_raw_fd(mio); // SAFETY: This is an in-place conversion from Mio stream to Tokio stream. UnixStream::from_std(unsafe { FromRawFd::from_raw_fd(raw) }) } } } } } pub(crate) fn create_mio_tcp_listener( addr: StdSocketAddr, backlog: u32, mptcp: &MpTcp, ) -> io::Result<MioTcpListener> { use socket2::{Domain, Protocol, Socket, Type}; #[cfg(not(target_os = "linux"))] let protocol = Protocol::TCP; #[cfg(target_os = "linux")] let protocol = if matches!(mptcp, MpTcp::Disabled) { Protocol::TCP } else { Protocol::MPTCP }; let socket = match Socket::new(Domain::for_address(addr), Type::STREAM, Some(protocol)) { Ok(sock) => sock, Err(err) if matches!(mptcp, MpTcp::TcpFallback) => { tracing::warn!("binding socket as MPTCP failed: {err}"); tracing::warn!("falling back to TCP"); Socket::new(Domain::for_address(addr), Type::STREAM, Some(Protocol::TCP))? } Err(err) => return Err(err), }; socket.set_reuse_address(true)?; socket.set_nonblocking(true)?; socket.bind(&addr.into())?; socket.listen(backlog as i32)?; Ok(MioTcpListener::from_std(StdTcpListener::from(socket))) } #[cfg(test)] mod tests { use super::*; #[test] fn socket_addr() { let addr = SocketAddr::Tcp("127.0.0.1:8080".parse().unwrap()); assert!(format!("{:?}", addr).contains("127.0.0.1:8080")); assert_eq!(format!("{}", addr), "127.0.0.1:8080"); let addr: StdSocketAddr = "127.0.0.1:0".parse().unwrap(); let lst = create_mio_tcp_listener(addr, 128, &MpTcp::Disabled).unwrap(); let lst = MioListener::Tcp(lst); assert!(format!("{:?}", lst).contains("TcpListener")); assert!(format!("{}", lst).contains("127.0.0.1")); } #[test] #[cfg(unix)] fn uds() { let _ = std::fs::remove_file("/tmp/sock.xxxxx"); if let Ok(socket) = MioUnixListener::bind("/tmp/sock.xxxxx") { let addr = socket.local_addr().expect("Couldn't get local address"); let a = SocketAddr::Uds(addr); assert!(format!("{:?}", a).contains("/tmp/sock.xxxxx")); assert!(format!("{}", a).contains("/tmp/sock.xxxxx")); let lst = MioListener::Uds(socket); assert!(format!("{:?}", lst).contains("/tmp/sock.xxxxx")); assert!(format!("{}", lst).contains("/tmp/sock.xxxxx")); } } }
use std::{io, net, sync::mpsc, thread}; use actix_rt::{net::TcpStream, System}; use crate::{Server, ServerBuilder, ServerHandle, ServerServiceFactory}; /// A testing server. /// /// `TestServer` is very simple test server that simplify process of writing integration tests for /// network applications. /// /// # Examples /// ``` /// use actix_service::fn_service; /// use actix_server::TestServer; /// /// #[actix_rt::main] /// async fn main() { /// let srv = TestServer::start(|| fn_service( /// |sock| async move { /// println!("New connection: {:?}", sock); /// Ok::<_, ()>(()) /// } /// )); /// /// println!("SOCKET: {:?}", srv.connect()); /// } /// ``` pub struct TestServer; /// Test server handle. pub struct TestServerHandle { addr: net::SocketAddr, host: String, port: u16, server_handle: ServerHandle, thread_handle: Option<thread::JoinHandle<io::Result<()>>>, } impl TestServer { /// Start new `TestServer` using application factory and default server config. pub fn start(factory: impl ServerServiceFactory<TcpStream>) -> TestServerHandle { Self::start_with_builder(Server::build(), factory) } /// Start new `TestServer` using application factory and server builder. pub fn start_with_builder( server_builder: ServerBuilder, factory: impl ServerServiceFactory<TcpStream>, ) -> TestServerHandle { let (tx, rx) = mpsc::channel(); // run server in separate thread let thread_handle = thread::spawn(move || { let lst = net::TcpListener::bind("127.0.0.1:0").unwrap(); let local_addr = lst.local_addr().unwrap(); System::new().block_on(async { let server = server_builder .listen("test", lst, factory) .unwrap() .workers(1) .disable_signals() .run(); tx.send((server.handle(), local_addr)).unwrap(); server.await }) }); let (server_handle, addr) = rx.recv().unwrap(); let host = format!("{}", addr.ip()); let port = addr.port(); TestServerHandle { addr, host, port, server_handle, thread_handle: Some(thread_handle), } } /// Get first available unused local address. pub fn unused_addr() -> net::SocketAddr { use socket2::{Domain, Protocol, Socket, Type}; let addr: net::SocketAddr = "127.0.0.1:0".parse().unwrap(); let domain = Domain::for_address(addr); let socket = Socket::new(domain, Type::STREAM, Some(Protocol::TCP)).unwrap(); socket.set_reuse_address(true).unwrap(); socket.set_nonblocking(true).unwrap(); socket.bind(&addr.into()).unwrap(); socket.listen(1024).unwrap(); net::TcpListener::from(socket).local_addr().unwrap() } } impl TestServerHandle { /// Test server host. pub fn host(&self) -> &str { &self.host } /// Test server port. pub fn port(&self) -> u16 { self.port } /// Get test server address. pub fn addr(&self) -> net::SocketAddr { self.addr } /// Stop server. fn stop(&mut self) { drop(self.server_handle.stop(false)); self.thread_handle.take().unwrap().join().unwrap().unwrap(); } /// Connect to server, returning a Tokio `TcpStream`. pub fn connect(&self) -> io::Result<TcpStream> { let stream = net::TcpStream::connect(self.addr)?; stream.set_nonblocking(true)?; TcpStream::from_std(stream) } } impl Drop for TestServerHandle { fn drop(&mut self) { self.stop() } } #[cfg(test)] mod tests { use actix_service::fn_service; use super::*; #[tokio::test] async fn connect_in_tokio_runtime() { let srv = TestServer::start(|| fn_service(|_sock| async move { Ok::<_, ()>(()) })); assert!(srv.connect().is_ok()); } #[actix_rt::test] async fn connect_in_actix_runtime() { let srv = TestServer::start(|| fn_service(|_sock| async move { Ok::<_, ()>(()) })); assert!(srv.connect().is_ok()); } }
use std::{ collections::VecDeque, ops::Deref, sync::{Arc, Mutex, MutexGuard}, }; use mio::{Registry, Token as MioToken, Waker}; use crate::worker::WorkerHandleAccept; /// Waker token for `mio::Poll` instance. pub(crate) const WAKER_TOKEN: MioToken = MioToken(usize::MAX); /// `mio::Waker` with a queue for waking up the `Accept`'s `Poll` and contains the `WakerInterest` /// the `Poll` would want to look into. pub(crate) struct WakerQueue(Arc<(Waker, Mutex<VecDeque<WakerInterest>>)>); impl Clone for WakerQueue { fn clone(&self) -> Self { Self(self.0.clone()) } } impl Deref for WakerQueue { type Target = (Waker, Mutex<VecDeque<WakerInterest>>); fn deref(&self) -> &Self::Target { self.0.deref() } } impl WakerQueue { /// Construct a waker queue with given `Poll`'s `Registry` and capacity. /// /// A fixed `WAKER_TOKEN` is used to identify the wake interest and the `Poll` needs to match /// event's token for it to properly handle `WakerInterest`. pub(crate) fn new(registry: &Registry) -> std::io::Result<Self> { let waker = Waker::new(registry, WAKER_TOKEN)?; let queue = Mutex::new(VecDeque::with_capacity(16)); Ok(Self(Arc::new((waker, queue)))) } /// Push a new interest to the queue and wake up the accept poll afterwards. pub(crate) fn wake(&self, interest: WakerInterest) { let (waker, queue) = self.deref(); queue .lock() .expect("Failed to lock WakerQueue") .push_back(interest); waker .wake() .unwrap_or_else(|e| panic!("can not wake up Accept Poll: {}", e)); } /// Get a MutexGuard of the waker queue. pub(crate) fn guard(&self) -> MutexGuard<'_, VecDeque<WakerInterest>> { self.deref().1.lock().expect("Failed to lock WakerQueue") } /// Reset the waker queue so it does not grow infinitely. pub(crate) fn reset(queue: &mut VecDeque<WakerInterest>) { std::mem::swap(&mut VecDeque::<WakerInterest>::with_capacity(16), queue); } } /// Types of interests we would look into when `Accept`'s `Poll` is waked up by waker. /// /// These interests should not be confused with `mio::Interest` and mostly not I/O related pub(crate) enum WakerInterest { /// `WorkerAvailable` is an interest from `Worker` notifying `Accept` there is a worker /// available and can accept new tasks. WorkerAvailable(usize), /// `Pause`, `Resume`, `Stop` Interest are from `ServerBuilder` future. It listens to /// `ServerCommand` and notify `Accept` to do exactly these tasks. Pause, Resume, Stop, /// `Worker` is an interest that is triggered after a worker faults. This is determined by /// trying to send work to it. `Accept` would be waked up and add the new `WorkerHandleAccept`. Worker(WorkerHandleAccept), }
use std::{ future::Future, io, mem, num::NonZeroUsize, pin::Pin, rc::Rc, sync::{ atomic::{AtomicUsize, Ordering}, Arc, }, task::{Context, Poll}, time::Duration, }; use actix_rt::{ spawn, time::{sleep, Instant, Sleep}, Arbiter, ArbiterHandle, System, }; use futures_core::{future::LocalBoxFuture, ready}; use tokio::sync::{ mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender}, oneshot, }; use tracing::{error, info, trace}; use crate::{ service::{BoxedServerService, InternalServiceFactory}, socket::MioStream, waker_queue::{WakerInterest, WakerQueue}, }; /// Stop worker message. Returns `true` on successful graceful shutdown /// and `false` if some connections still alive when shutdown execute. pub(crate) struct Stop { graceful: bool, tx: oneshot::Sender<bool>, } #[derive(Debug)] pub(crate) struct Conn { pub io: MioStream, pub token: usize, } /// Create accept and server worker handles. fn handle_pair( idx: usize, conn_tx: UnboundedSender<Conn>, stop_tx: UnboundedSender<Stop>, counter: Counter, ) -> (WorkerHandleAccept, WorkerHandleServer) { let accept = WorkerHandleAccept { idx, conn_tx, counter, }; let server = WorkerHandleServer { idx, stop_tx }; (accept, server) } /// counter: Arc<AtomicUsize> field is owned by `Accept` thread and `ServerWorker` thread. /// /// `Accept` would increment the counter and `ServerWorker` would decrement it. /// /// # Atomic Ordering: /// /// `Accept` always look into it's cached `Availability` field for `ServerWorker` state. /// It lazily increment counter after successful dispatching new work to `ServerWorker`. /// On reaching counter limit `Accept` update it's cached `Availability` and mark worker as /// unable to accept any work. /// /// `ServerWorker` always decrement the counter when every work received from `Accept` is done. /// On reaching counter limit worker would use `mio::Waker` and `WakerQueue` to wake up `Accept` /// and notify it to update cached `Availability` again to mark worker as able to accept work again. /// /// Hence, a wake up would only happen after `Accept` increment it to limit. /// And a decrement to limit always wake up `Accept`. #[derive(Clone)] pub(crate) struct Counter { counter: Arc<AtomicUsize>, limit: usize, } impl Counter { pub(crate) fn new(limit: usize) -> Self { Self { counter: Arc::new(AtomicUsize::new(1)), limit, } } /// Increment counter by 1 and return true when hitting limit #[inline(always)] pub(crate) fn inc(&self) -> bool { self.counter.fetch_add(1, Ordering::Relaxed) != self.limit } /// Decrement counter by 1 and return true if crossing limit. #[inline(always)] pub(crate) fn dec(&self) -> bool { self.counter.fetch_sub(1, Ordering::Relaxed) == self.limit } pub(crate) fn total(&self) -> usize { self.counter.load(Ordering::SeqCst) - 1 } } pub(crate) struct WorkerCounter { idx: usize, inner: Rc<(WakerQueue, Counter)>, } impl Clone for WorkerCounter { fn clone(&self) -> Self { Self { idx: self.idx, inner: self.inner.clone(), } } } impl WorkerCounter { pub(crate) fn new(idx: usize, waker_queue: WakerQueue, counter: Counter) -> Self { Self { idx, inner: Rc::new((waker_queue, counter)), } } #[inline(always)] pub(crate) fn guard(&self) -> WorkerCounterGuard { WorkerCounterGuard(self.clone()) } fn total(&self) -> usize { self.inner.1.total() } } pub(crate) struct WorkerCounterGuard(WorkerCounter); impl Drop for WorkerCounterGuard { fn drop(&mut self) { let (waker_queue, counter) = &*self.0.inner; if counter.dec() { waker_queue.wake(WakerInterest::WorkerAvailable(self.0.idx)); } } } /// Handle to worker that can send connection message to worker and share the availability of worker /// to other threads. /// /// Held by [Accept](crate::accept::Accept). pub(crate) struct WorkerHandleAccept { idx: usize, conn_tx: UnboundedSender<Conn>, counter: Counter, } impl WorkerHandleAccept { #[inline(always)] pub(crate) fn idx(&self) -> usize { self.idx } #[inline(always)] pub(crate) fn send(&self, conn: Conn) -> Result<(), Conn> { self.conn_tx.send(conn).map_err(|msg| msg.0) } #[inline(always)] pub(crate) fn inc_counter(&self) -> bool { self.counter.inc() } } /// Handle to worker than can send stop message to worker. /// /// Held by [ServerBuilder](crate::builder::ServerBuilder). #[derive(Debug)] pub(crate) struct WorkerHandleServer { pub(crate) idx: usize, stop_tx: UnboundedSender<Stop>, } impl WorkerHandleServer { pub(crate) fn stop(&self, graceful: bool) -> oneshot::Receiver<bool> { let (tx, rx) = oneshot::channel(); let _ = self.stop_tx.send(Stop { graceful, tx }); rx } } /// Service worker. /// /// Worker accepts Socket objects via unbounded channel and starts stream processing. pub(crate) struct ServerWorker { // UnboundedReceiver<Conn> should always be the first field. // It must be dropped as soon as ServerWorker dropping. conn_rx: UnboundedReceiver<Conn>, stop_rx: UnboundedReceiver<Stop>, counter: WorkerCounter, services: Box<[WorkerService]>, factories: Box<[Box<dyn InternalServiceFactory>]>, state: WorkerState, shutdown_timeout: Duration, } struct WorkerService { factory_idx: usize, status: WorkerServiceStatus, service: BoxedServerService, } impl WorkerService { fn created(&mut self, service: BoxedServerService) { self.service = service; self.status = WorkerServiceStatus::Unavailable; } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum WorkerServiceStatus { Available, Unavailable, Failed, Restarting, Stopping, Stopped, } impl Default for WorkerServiceStatus { fn default() -> Self { Self::Unavailable } } /// Config for worker behavior passed down from server builder. #[derive(Debug, Clone, Copy)] pub(crate) struct ServerWorkerConfig { shutdown_timeout: Duration, max_blocking_threads: usize, max_concurrent_connections: usize, } impl Default for ServerWorkerConfig { fn default() -> Self { let parallelism = std::thread::available_parallelism().map_or(2, NonZeroUsize::get); // 512 is the default max blocking thread count of a Tokio runtime. let max_blocking_threads = std::cmp::max(512 / parallelism, 1); Self { shutdown_timeout: Duration::from_secs(30), max_blocking_threads, max_concurrent_connections: 25600, } } } impl ServerWorkerConfig { pub(crate) fn max_blocking_threads(&mut self, num: usize) { self.max_blocking_threads = num; } pub(crate) fn max_concurrent_connections(&mut self, num: usize) { self.max_concurrent_connections = num; } pub(crate) fn shutdown_timeout(&mut self, dur: Duration) { self.shutdown_timeout = dur; } } impl ServerWorker { pub(crate) fn start( idx: usize, factories: Vec<Box<dyn InternalServiceFactory>>, waker_queue: WakerQueue, config: ServerWorkerConfig, ) -> io::Result<(WorkerHandleAccept, WorkerHandleServer)> { trace!("starting server worker {}", idx); let (tx1, conn_rx) = unbounded_channel(); let (tx2, stop_rx) = unbounded_channel(); let counter = Counter::new(config.max_concurrent_connections); let pair = handle_pair(idx, tx1, tx2, counter.clone()); // get actix system context if it is set let actix_system = System::try_current(); // get tokio runtime handle if it is set let tokio_handle = tokio::runtime::Handle::try_current().ok(); // service factories initialization channel let (factory_tx, factory_rx) = std::sync::mpsc::sync_channel::<io::Result<()>>(1); // outline of following code: // // if system exists // if uring enabled // start arbiter using uring method // else // start arbiter with regular tokio // else // if uring enabled // start uring in spawned thread // else // start regular tokio in spawned thread // every worker runs in it's own thread and tokio runtime. // use a custom tokio runtime builder to change the settings of runtime. match (actix_system, tokio_handle) { (None, None) => { panic!("No runtime detected. Start a Tokio (or Actix) runtime."); } // no actix system (None, Some(rt_handle)) => { std::thread::Builder::new() .name(format!("actix-server worker {}", idx)) .spawn(move || { let (worker_stopped_tx, worker_stopped_rx) = oneshot::channel(); // local set for running service init futures and worker services let ls = tokio::task::LocalSet::new(); // init services using existing Tokio runtime (so probably on main thread) let services = rt_handle.block_on(ls.run_until(async { let mut services = Vec::new(); for (idx, factory) in factories.iter().enumerate() { match factory.create().await { Ok((token, svc)) => services.push((idx, token, svc)), Err(err) => { error!("can not start worker: {:?}", err); return Err(io::Error::new( io::ErrorKind::Other, format!("can not start server service {}", idx), )); } } } Ok(services) })); let services = match services { Ok(services) => { factory_tx.send(Ok(())).unwrap(); services } Err(err) => { factory_tx.send(Err(err)).unwrap(); return; } }; let worker_services = wrap_worker_services(services); let worker_fut = async move { // spawn to make sure ServerWorker runs as non boxed future. spawn(async move { ServerWorker { conn_rx, stop_rx, services: worker_services.into_boxed_slice(), counter: WorkerCounter::new(idx, waker_queue, counter), factories: factories.into_boxed_slice(), state: WorkerState::default(), shutdown_timeout: config.shutdown_timeout, } .await; // wake up outermost task waiting for shutdown worker_stopped_tx.send(()).unwrap(); }); worker_stopped_rx.await.unwrap(); }; #[cfg(all(target_os = "linux", feature = "io-uring"))] { // TODO: pass max blocking thread config when tokio-uring enable configuration // on building runtime. let _ = config.max_blocking_threads; tokio_uring::start(worker_fut); } #[cfg(not(all(target_os = "linux", feature = "io-uring")))] { let rt = tokio::runtime::Builder::new_current_thread() .enable_all() .max_blocking_threads(config.max_blocking_threads) .build() .unwrap(); rt.block_on(ls.run_until(worker_fut)); } }) .expect("cannot spawn server worker thread"); } // with actix system (Some(_sys), _) => { #[cfg(all(target_os = "linux", feature = "io-uring"))] let arbiter = { // TODO: pass max blocking thread config when tokio-uring enable configuration // on building runtime. let _ = config.max_blocking_threads; Arbiter::new() }; #[cfg(not(all(target_os = "linux", feature = "io-uring")))] let arbiter = { Arbiter::with_tokio_rt(move || { tokio::runtime::Builder::new_current_thread() .enable_all() .max_blocking_threads(config.max_blocking_threads) .build() .unwrap() }) }; arbiter.spawn(async move { // spawn_local to run !Send future tasks. spawn(async move { let mut services = Vec::new(); for (idx, factory) in factories.iter().enumerate() { match factory.create().await { Ok((token, svc)) => services.push((idx, token, svc)), Err(err) => { error!("can not start worker: {:?}", err); Arbiter::current().stop(); factory_tx .send(Err(io::Error::new( io::ErrorKind::Other, format!("can not start server service {}", idx), ))) .unwrap(); return; } } } factory_tx.send(Ok(())).unwrap(); let worker_services = wrap_worker_services(services); // spawn to make sure ServerWorker runs as non boxed future. spawn(ServerWorker { conn_rx, stop_rx, services: worker_services.into_boxed_slice(), counter: WorkerCounter::new(idx, waker_queue, counter), factories: factories.into_boxed_slice(), state: Default::default(), shutdown_timeout: config.shutdown_timeout, }); }); }); } }; // wait for service factories initialization factory_rx.recv().unwrap()?; Ok(pair) } fn restart_service(&mut self, idx: usize, factory_id: usize) { let factory = &self.factories[factory_id]; trace!("service {:?} failed, restarting", factory.name(idx)); self.services[idx].status = WorkerServiceStatus::Restarting; self.state = WorkerState::Restarting(Restart { factory_id, token: idx, fut: factory.create(), }); } fn shutdown(&mut self, force: bool) { self.services .iter_mut() .filter(|srv| srv.status == WorkerServiceStatus::Available) .for_each(|srv| { srv.status = if force { WorkerServiceStatus::Stopped } else { WorkerServiceStatus::Stopping }; }); } fn check_readiness(&mut self, cx: &mut Context<'_>) -> Result<bool, (usize, usize)> { let mut ready = true; for (idx, srv) in self.services.iter_mut().enumerate() { if srv.status == WorkerServiceStatus::Available || srv.status == WorkerServiceStatus::Unavailable { match srv.service.poll_ready(cx) { Poll::Ready(Ok(_)) => { if srv.status == WorkerServiceStatus::Unavailable { trace!( "service {:?} is available", self.factories[srv.factory_idx].name(idx) ); srv.status = WorkerServiceStatus::Available; } } Poll::Pending => { ready = false; if srv.status == WorkerServiceStatus::Available { trace!( "service {:?} is unavailable", self.factories[srv.factory_idx].name(idx) ); srv.status = WorkerServiceStatus::Unavailable; } } Poll::Ready(Err(_)) => { error!( "service {:?} readiness check returned error, restarting", self.factories[srv.factory_idx].name(idx) ); srv.status = WorkerServiceStatus::Failed; return Err((idx, srv.factory_idx)); } } } } Ok(ready) } } enum WorkerState { Available, Unavailable, Restarting(Restart), Shutdown(Shutdown), } struct Restart { factory_id: usize, token: usize, fut: LocalBoxFuture<'static, Result<(usize, BoxedServerService), ()>>, } /// State necessary for server shutdown. struct Shutdown { // Interval for checking the shutdown progress. timer: Pin<Box<Sleep>>, /// Start time of shutdown. start_from: Instant, /// Notify caller of the shutdown outcome (graceful/force). tx: oneshot::Sender<bool>, } impl Default for WorkerState { fn default() -> Self { Self::Unavailable } } impl Drop for ServerWorker { fn drop(&mut self) { Arbiter::try_current().as_ref().map(ArbiterHandle::stop); } } impl Future for ServerWorker { type Output = (); fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let this = self.as_mut().get_mut(); // `StopWorker` message handler if let Poll::Ready(Some(Stop { graceful, tx })) = this.stop_rx.poll_recv(cx) { let num = this.counter.total(); if num == 0 { info!("shutting down idle worker"); let _ = tx.send(true); return Poll::Ready(()); } else if graceful { info!("graceful worker shutdown; finishing {} connections", num); this.shutdown(false); this.state = WorkerState::Shutdown(Shutdown { timer: Box::pin(sleep(Duration::from_secs(1))), start_from: Instant::now(), tx, }); } else { info!("force shutdown worker, closing {} connections", num); this.shutdown(true); let _ = tx.send(false); return Poll::Ready(()); } } match this.state { WorkerState::Unavailable => match this.check_readiness(cx) { Ok(true) => { this.state = WorkerState::Available; self.poll(cx) } Ok(false) => Poll::Pending, Err((token, idx)) => { this.restart_service(token, idx); self.poll(cx) } }, WorkerState::Restarting(ref mut restart) => { let factory_id = restart.factory_id; let token = restart.token; let (token_new, service) = ready!(restart.fut.as_mut().poll(cx)).unwrap_or_else(|_| { panic!( "Can not restart {:?} service", this.factories[factory_id].name(token) ) }); assert_eq!(token, token_new); trace!( "service {:?} has been restarted", this.factories[factory_id].name(token) ); this.services[token].created(service); this.state = WorkerState::Unavailable; self.poll(cx) } WorkerState::Shutdown(ref mut shutdown) => { // drop all pending connections in rx channel. while let Poll::Ready(Some(conn)) = this.conn_rx.poll_recv(cx) { // WorkerCounterGuard is needed as Accept thread has incremented counter. // It's guard's job to decrement the counter together with drop of Conn. let guard = this.counter.guard(); drop((conn, guard)); } // wait for 1 second ready!(shutdown.timer.as_mut().poll(cx)); if this.counter.total() == 0 { // graceful shutdown if let WorkerState::Shutdown(shutdown) = mem::take(&mut this.state) { let _ = shutdown.tx.send(true); } Poll::Ready(()) } else if shutdown.start_from.elapsed() >= this.shutdown_timeout { // timeout forceful shutdown if let WorkerState::Shutdown(shutdown) = mem::take(&mut this.state) { let _ = shutdown.tx.send(false); } Poll::Ready(()) } else { // reset timer and wait for 1 second let time = Instant::now() + Duration::from_secs(1); shutdown.timer.as_mut().reset(time); shutdown.timer.as_mut().poll(cx) } } // actively poll stream and handle worker command WorkerState::Available => loop { match this.check_readiness(cx) { Ok(true) => {} Ok(false) => { trace!("worker is unavailable"); this.state = WorkerState::Unavailable; return self.poll(cx); } Err((token, idx)) => { this.restart_service(token, idx); return self.poll(cx); } } // handle incoming io stream match ready!(this.conn_rx.poll_recv(cx)) { Some(msg) => { let guard = this.counter.guard(); let _ = this.services[msg.token] .service .call((guard, msg.io)) .into_inner(); } None => return Poll::Ready(()), }; }, } } } fn wrap_worker_services(services: Vec<(usize, usize, BoxedServerService)>) -> Vec<WorkerService> { services .into_iter() .fold(Vec::new(), |mut services, (idx, token, service)| { assert_eq!(token, services.len()); services.push(WorkerService { factory_idx: idx, service, status: WorkerServiceStatus::Unavailable, }); services }) }
#![allow(clippy::let_underscore_future, missing_docs)] use std::{ net, sync::{ atomic::{AtomicUsize, Ordering}, mpsc, Arc, }, thread, time::Duration, }; use actix_rt::{net::TcpStream, time::sleep}; use actix_server::{Server, TestServer}; use actix_service::fn_service; fn unused_addr() -> net::SocketAddr { TestServer::unused_addr() } #[test] fn test_bind() { let addr = unused_addr(); let (tx, rx) = mpsc::channel(); let h = thread::spawn(move || { actix_rt::System::new().block_on(async { let srv = Server::build() .workers(1) .disable_signals() .shutdown_timeout(3600) .bind("test", addr, move || { fn_service(|_| async { Ok::<_, ()>(()) }) })? .run(); tx.send(srv.handle()).unwrap(); srv.await }) }); let srv = rx.recv().unwrap(); thread::sleep(Duration::from_millis(500)); net::TcpStream::connect(addr).unwrap(); let _ = srv.stop(true); h.join().unwrap().unwrap(); } #[test] fn test_listen() { let addr = unused_addr(); let (tx, rx) = mpsc::channel(); let lst = net::TcpListener::bind(addr).unwrap(); let h = thread::spawn(move || { actix_rt::System::new().block_on(async { let srv = Server::build() .workers(1) .disable_signals() .shutdown_timeout(3600) .listen("test", lst, move || { fn_service(|_| async { Ok::<_, ()>(()) }) })? .run(); tx.send(srv.handle()).unwrap(); srv.await }) }); let srv = rx.recv().unwrap(); thread::sleep(Duration::from_millis(500)); net::TcpStream::connect(addr).unwrap(); let _ = srv.stop(true); h.join().unwrap().unwrap(); } #[test] fn plain_tokio_runtime() { let addr = unused_addr(); let (tx, rx) = mpsc::channel(); let h = thread::spawn(move || { let rt = tokio::runtime::Builder::new_current_thread() .enable_all() .build() .unwrap(); rt.block_on(async { let srv = Server::build() .workers(1) .disable_signals() .bind("test", addr, move || { fn_service(|_| async { Ok::<_, ()>(()) }) })? .run(); tx.send(srv.handle()).unwrap(); srv.await }) }); let srv = rx.recv().unwrap(); thread::sleep(Duration::from_millis(500)); assert!(net::TcpStream::connect(addr).is_ok()); let _ = srv.stop(true); h.join().unwrap().unwrap(); } #[test] #[cfg(unix)] fn test_start() { use std::io::Read; use actix_codec::{BytesCodec, Framed}; use bytes::Bytes; use futures_util::sink::SinkExt; let addr = unused_addr(); let (tx, rx) = mpsc::channel(); let h = thread::spawn(move || { actix_rt::System::new().block_on(async { let srv = Server::build() .backlog(100) .disable_signals() .bind("test", addr, move || { fn_service(|io: TcpStream| async move { let mut f = Framed::new(io, BytesCodec); f.send(Bytes::from_static(b"test")).await.unwrap(); Ok::<_, ()>(()) }) })? .run(); let _ = tx.send((srv.handle(), actix_rt::System::current())); srv.await }) }); let (srv, sys) = rx.recv().unwrap(); let mut buf = [1u8; 4]; let mut conn = net::TcpStream::connect(addr).unwrap(); let _ = conn.read_exact(&mut buf); assert_eq!(buf, b"test"[..]); // pause let _ = srv.pause(); thread::sleep(Duration::from_millis(200)); let mut conn = net::TcpStream::connect(addr).unwrap(); conn.set_read_timeout(Some(Duration::from_millis(100))) .unwrap(); let res = conn.read_exact(&mut buf); assert!(res.is_err()); // resume let _ = srv.resume(); thread::sleep(Duration::from_millis(100)); assert!(net::TcpStream::connect(addr).is_ok()); assert!(net::TcpStream::connect(addr).is_ok()); assert!(net::TcpStream::connect(addr).is_ok()); let mut buf = [0u8; 4]; let mut conn = net::TcpStream::connect(addr).unwrap(); let _ = conn.read_exact(&mut buf); assert_eq!(buf, b"test"[..]); // stop let _ = srv.stop(false); sys.stop(); h.join().unwrap().unwrap(); thread::sleep(Duration::from_secs(1)); assert!(net::TcpStream::connect(addr).is_err()); } #[actix_rt::test] async fn test_max_concurrent_connections() { // Note: // A TCP listener would accept connects based on it's backlog setting. // // The limit test on the other hand is only for concurrent TCP stream limiting a work // thread accept. use tokio::io::AsyncWriteExt; let addr = unused_addr(); let (tx, rx) = mpsc::channel(); let counter = Arc::new(AtomicUsize::new(0)); let counter_clone = counter.clone(); let max_conn = 3; let h = thread::spawn(move || { actix_rt::System::new().block_on(async { let srv = Server::build() // Set a relative higher backlog. .backlog(12) // max connection for a worker is 3. .max_concurrent_connections(max_conn) .workers(1) .disable_signals() .bind("test", addr, move || { let counter = counter.clone(); fn_service(move |_io: TcpStream| { let counter = counter.clone(); async move { counter.fetch_add(1, Ordering::SeqCst); sleep(Duration::from_secs(20)).await; counter.fetch_sub(1, Ordering::SeqCst); Ok::<(), ()>(()) } }) })? .run(); let _ = tx.send((srv.handle(), actix_rt::System::current())); srv.await }) }); let (srv, sys) = rx.recv().unwrap(); let mut conns = vec![]; for _ in 0..12 { let conn = tokio::net::TcpStream::connect(addr).await.unwrap(); conns.push(conn); } sleep(Duration::from_secs(5)).await; // counter would remain at 3 even with 12 successful connection. // and 9 of them remain in backlog. assert_eq!(max_conn, counter_clone.load(Ordering::SeqCst)); for mut conn in conns { conn.shutdown().await.unwrap(); } srv.stop(false).await; sys.stop(); h.join().unwrap().unwrap(); } // TODO: race-y failures detected due to integer underflow when calling Counter::total #[actix_rt::test] async fn test_service_restart() { use std::task::{Context, Poll}; use actix_service::{fn_factory, Service}; use futures_core::future::LocalBoxFuture; use tokio::io::AsyncWriteExt; struct TestService(Arc<AtomicUsize>); impl Service<TcpStream> for TestService { type Response = (); type Error = (); type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>; fn poll_ready(&self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { let TestService(ref counter) = self; let c = counter.fetch_add(1, Ordering::SeqCst); // Force the service to restart on first readiness check. if c > 0 { Poll::Ready(Ok(())) } else { Poll::Ready(Err(())) } } fn call(&self, _: TcpStream) -> Self::Future { Box::pin(async { Ok(()) }) } } let addr1 = unused_addr(); let addr2 = unused_addr(); let (tx, rx) = mpsc::channel(); let num = Arc::new(AtomicUsize::new(0)); let num2 = Arc::new(AtomicUsize::new(0)); let num_clone = num.clone(); let num2_clone = num2.clone(); let h = thread::spawn(move || { let num = num.clone(); actix_rt::System::new().block_on(async { let srv = Server::build() .backlog(1) .disable_signals() .bind("addr1", addr1, move || { let num = num.clone(); fn_factory(move || { let num = num.clone(); async move { Ok::<_, ()>(TestService(num)) } }) })? .bind("addr2", addr2, move || { let num2 = num2.clone(); fn_factory(move || { let num2 = num2.clone(); async move { Ok::<_, ()>(TestService(num2)) } }) })? .workers(1) .run(); let _ = tx.send(srv.handle()); srv.await }) }); let srv = rx.recv().unwrap(); for _ in 0..5 { TcpStream::connect(addr1) .await .unwrap() .shutdown() .await .unwrap(); TcpStream::connect(addr2) .await .unwrap() .shutdown() .await .unwrap(); } sleep(Duration::from_secs(3)).await; assert!(num_clone.load(Ordering::SeqCst) > 5); assert!(num2_clone.load(Ordering::SeqCst) > 5); let _ = srv.stop(false); h.join().unwrap().unwrap(); } #[ignore] // non-deterministic on CI #[actix_rt::test] async fn worker_restart() { use actix_service::{Service, ServiceFactory}; use futures_core::future::LocalBoxFuture; use tokio::io::{AsyncReadExt, AsyncWriteExt}; struct TestServiceFactory(Arc<AtomicUsize>); impl ServiceFactory<TcpStream> for TestServiceFactory { type Response = (); type Error = (); type Config = (); type Service = TestService; type InitError = (); type Future = LocalBoxFuture<'static, Result<Self::Service, Self::InitError>>; fn new_service(&self, _: Self::Config) -> Self::Future { let counter = self.0.fetch_add(1, Ordering::Relaxed); Box::pin(async move { Ok(TestService(counter)) }) } } struct TestService(usize); impl Service<TcpStream> for TestService { type Response = (); type Error = (); type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>; actix_service::always_ready!(); fn call(&self, stream: TcpStream) -> Self::Future { let counter = self.0; let mut stream = stream.into_std().unwrap(); use std::io::Write; let str = counter.to_string(); let buf = str.as_bytes(); let mut written = 0; while written < buf.len() { if let Ok(n) = stream.write(&buf[written..]) { written += n; } } stream.flush().unwrap(); stream.shutdown(net::Shutdown::Write).unwrap(); // force worker 2 to restart service once. if counter == 2 { panic!("panic on purpose") } else { Box::pin(async { Ok(()) }) } } } let addr = unused_addr(); let (tx, rx) = mpsc::channel(); let counter = Arc::new(AtomicUsize::new(1)); let h = thread::spawn(move || { let counter = counter.clone(); actix_rt::System::new().block_on(async { let srv = Server::build() .disable_signals() .bind("addr", addr, move || TestServiceFactory(counter.clone()))? .workers(2) .run(); let _ = tx.send(srv.handle()); srv.await }) }); let srv = rx.recv().unwrap(); sleep(Duration::from_secs(3)).await; let mut buf = [0; 8]; // worker 1 would not restart and return it's id consistently. let mut stream = TcpStream::connect(addr).await.unwrap(); let n = stream.read(&mut buf).await.unwrap(); let id = String::from_utf8_lossy(&buf[0..n]); assert_eq!("1", id); stream.shutdown().await.unwrap(); // worker 2 dead after return response. let mut stream = TcpStream::connect(addr).await.unwrap(); let n = stream.read(&mut buf).await.unwrap(); let id = String::from_utf8_lossy(&buf[0..n]); assert_eq!("2", id); stream.shutdown().await.unwrap(); // request to worker 1 let mut stream = TcpStream::connect(addr).await.unwrap(); let n = stream.read(&mut buf).await.unwrap(); let id = String::from_utf8_lossy(&buf[0..n]); assert_eq!("1", id); stream.shutdown().await.unwrap(); // TODO: Remove sleep if it can pass CI. sleep(Duration::from_secs(3)).await; // worker 2 restarting and work goes to worker 1. let mut stream = TcpStream::connect(addr).await.unwrap(); let n = stream.read(&mut buf).await.unwrap(); let id = String::from_utf8_lossy(&buf[0..n]); assert_eq!("1", id); stream.shutdown().await.unwrap(); // TODO: Remove sleep if it can pass CI. sleep(Duration::from_secs(3)).await; // worker 2 restarted but worker 1 was still the next to accept connection. let mut stream = TcpStream::connect(addr).await.unwrap(); let n = stream.read(&mut buf).await.unwrap(); let id = String::from_utf8_lossy(&buf[0..n]); assert_eq!("1", id); stream.shutdown().await.unwrap(); // TODO: Remove sleep if it can pass CI. sleep(Duration::from_secs(3)).await; // worker 2 accept connection again but it's id is 3. let mut stream = TcpStream::connect(addr).await.unwrap(); let n = stream.read(&mut buf).await.unwrap(); let id = String::from_utf8_lossy(&buf[0..n]); assert_eq!("3", id); stream.shutdown().await.unwrap(); let _ = srv.stop(false); h.join().unwrap().unwrap(); } #[test] fn no_runtime_on_init() { use std::{thread::sleep, time::Duration}; let addr = unused_addr(); let counter = Arc::new(AtomicUsize::new(0)); let mut srv = Server::build() .workers(2) .disable_signals() .bind("test", addr, { let counter = counter.clone(); move || { counter.fetch_add(1, Ordering::SeqCst); fn_service(|_| async { Ok::<_, ()>(()) }) } }) .unwrap() .run(); fn is_send<T: Send>(_: &T) {} is_send(&srv); is_send(&srv.handle()); sleep(Duration::from_millis(1_000)); assert_eq!(counter.load(Ordering::SeqCst), 0); let rt = tokio::runtime::Builder::new_current_thread() .enable_all() .build() .unwrap(); rt.block_on(async move { let _ = futures_util::poll!(&mut srv); // available after the first poll sleep(Duration::from_millis(500)); assert_eq!(counter.load(Ordering::SeqCst), 2); let _ = srv.handle().stop(true); srv.await }) .unwrap(); }
#![allow(missing_docs)] use std::net; use actix_rt::net::TcpStream; use actix_server::{Server, TestServer}; use actix_service::fn_service; use bytes::BytesMut; use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _}; macro_rules! await_timeout_ms { ($fut:expr, $limit:expr) => { ::actix_rt::time::timeout(::std::time::Duration::from_millis($limit), $fut) .await .unwrap() .unwrap(); }; } #[tokio::test] async fn testing_server_echo() { let srv = TestServer::start(|| { fn_service(move |mut stream: TcpStream| async move { let mut size = 0; let mut buf = BytesMut::new(); match stream.read_buf(&mut buf).await { Ok(0) => return Err(()), Ok(bytes_read) => { stream.write_all(&buf[size..]).await.unwrap(); size += bytes_read; } Err(_) => return Err(()), } Ok((buf.freeze(), size)) }) }); let mut conn = srv.connect().unwrap(); await_timeout_ms!(conn.write_all(b"test"), 200); let mut buf = Vec::new(); await_timeout_ms!(conn.read_to_end(&mut buf), 200); assert_eq!(&buf, b"test".as_ref()); } #[tokio::test] async fn new_with_builder() { let alt_addr = TestServer::unused_addr(); let srv = TestServer::start_with_builder( Server::build() .bind("alt", alt_addr, || { fn_service(|_| async { Ok::<_, ()>(()) }) }) .unwrap(), || { fn_service(|mut sock: TcpStream| async move { let mut buf = [0u8; 16]; sock.read_exact(&mut buf).await }) }, ); // connect to test server srv.connect().unwrap(); // connect to alt service defined in custom ServerBuilder TcpStream::from_std(net::TcpStream::connect(alt_addr).unwrap()).unwrap(); }
#![allow(missing_docs)] use std::{future::Future, sync::mpsc, time::Duration}; async fn oracle<F, Fut>(f: F) -> (u32, u32) where F: FnOnce() -> Fut + Clone + Send + 'static, Fut: Future<Output = u32> + 'static, { let f1 = actix_rt::spawn(f.clone()()); let f2 = actix_rt::spawn(f()); (f1.await.unwrap(), f2.await.unwrap()) } #[actix_rt::main] async fn main() { let (tx, rx) = mpsc::channel(); let (r1, r2) = oracle({ let tx = tx.clone(); || async move { tx.send(()).unwrap(); 4 * 4 } }) .await; assert_eq!(r1, r2); tx.send(()).unwrap(); rx.recv_timeout(Duration::from_millis(100)).unwrap(); rx.recv_timeout(Duration::from_millis(100)).unwrap(); }
use alloc::rc::Rc; use core::{ future::Future, marker::PhantomData, pin::Pin, task::{Context, Poll}, }; use futures_core::ready; use pin_project_lite::pin_project; use super::{Service, ServiceFactory}; /// Service for the `and_then` combinator, chaining a computation onto the end of another service /// which completes successfully. /// /// This is created by the `Pipeline::and_then` method. pub struct AndThenService<A, B, Req>(Rc<(A, B)>, PhantomData<Req>); impl<A, B, Req> AndThenService<A, B, Req> { /// Create new `AndThen` combinator pub(crate) fn new(a: A, b: B) -> Self where A: Service<Req>, B: Service<A::Response, Error = A::Error>, { Self(Rc::new((a, b)), PhantomData) } } impl<A, B, Req> Clone for AndThenService<A, B, Req> { fn clone(&self) -> Self { AndThenService(self.0.clone(), PhantomData) } } impl<A, B, Req> Service<Req> for AndThenService<A, B, Req> where A: Service<Req>, B: Service<A::Response, Error = A::Error>, { type Response = B::Response; type Error = A::Error; type Future = AndThenServiceResponse<A, B, Req>; fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { let (a, b) = &*self.0; let not_ready = !a.poll_ready(cx)?.is_ready(); if !b.poll_ready(cx)?.is_ready() || not_ready { Poll::Pending } else { Poll::Ready(Ok(())) } } fn call(&self, req: Req) -> Self::Future { AndThenServiceResponse { state: State::A { fut: self.0 .0.call(req), b: Some(self.0.clone()), }, } } } pin_project! { pub struct AndThenServiceResponse<A, B, Req> where A: Service<Req>, B: Service<A::Response, Error = A::Error>, { #[pin] state: State<A, B, Req>, } } pin_project! { #[project = StateProj] enum State<A, B, Req> where A: Service<Req>, B: Service<A::Response, Error = A::Error>, { A { #[pin] fut: A::Future, b: Option<Rc<(A, B)>>, }, B { #[pin] fut: B::Future, }, } } impl<A, B, Req> Future for AndThenServiceResponse<A, B, Req> where A: Service<Req>, B: Service<A::Response, Error = A::Error>, { type Output = Result<B::Response, A::Error>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let mut this = self.as_mut().project(); match this.state.as_mut().project() { StateProj::A { fut, b } => { let res = ready!(fut.poll(cx))?; let b = b.take().unwrap(); let fut = b.1.call(res); this.state.set(State::B { fut }); self.poll(cx) } StateProj::B { fut } => fut.poll(cx), } } } /// `.and_then()` service factory combinator pub struct AndThenServiceFactory<A, B, Req> where A: ServiceFactory<Req>, A::Config: Clone, B: ServiceFactory<A::Response, Config = A::Config, Error = A::Error, InitError = A::InitError>, { inner: Rc<(A, B)>, _phantom: PhantomData<Req>, } impl<A, B, Req> AndThenServiceFactory<A, B, Req> where A: ServiceFactory<Req>, A::Config: Clone, B: ServiceFactory<A::Response, Config = A::Config, Error = A::Error, InitError = A::InitError>, { /// Create new `AndThenFactory` combinator pub(crate) fn new(a: A, b: B) -> Self { Self { inner: Rc::new((a, b)), _phantom: PhantomData, } } } impl<A, B, Req> ServiceFactory<Req> for AndThenServiceFactory<A, B, Req> where A: ServiceFactory<Req>, A::Config: Clone, B: ServiceFactory<A::Response, Config = A::Config, Error = A::Error, InitError = A::InitError>, { type Response = B::Response; type Error = A::Error; type Config = A::Config; type Service = AndThenService<A::Service, B::Service, Req>; type InitError = A::InitError; type Future = AndThenServiceFactoryResponse<A, B, Req>; fn new_service(&self, cfg: A::Config) -> Self::Future { let inner = &*self.inner; AndThenServiceFactoryResponse::new( inner.0.new_service(cfg.clone()), inner.1.new_service(cfg), ) } } impl<A, B, Req> Clone for AndThenServiceFactory<A, B, Req> where A: ServiceFactory<Req>, A::Config: Clone, B: ServiceFactory<A::Response, Config = A::Config, Error = A::Error, InitError = A::InitError>, { fn clone(&self) -> Self { Self { inner: self.inner.clone(), _phantom: PhantomData, } } } pin_project! { pub struct AndThenServiceFactoryResponse<A, B, Req> where A: ServiceFactory<Req>, B: ServiceFactory<A::Response>, { #[pin] fut_a: A::Future, #[pin] fut_b: B::Future, a: Option<A::Service>, b: Option<B::Service>, } } impl<A, B, Req> AndThenServiceFactoryResponse<A, B, Req> where A: ServiceFactory<Req>, B: ServiceFactory<A::Response>, { fn new(fut_a: A::Future, fut_b: B::Future) -> Self { AndThenServiceFactoryResponse { fut_a, fut_b, a: None, b: None, } } } impl<A, B, Req> Future for AndThenServiceFactoryResponse<A, B, Req> where A: ServiceFactory<Req>, B: ServiceFactory<A::Response, Error = A::Error, InitError = A::InitError>, { type Output = Result<AndThenService<A::Service, B::Service, Req>, A::InitError>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let this = self.project(); if this.a.is_none() { if let Poll::Ready(service) = this.fut_a.poll(cx)? { *this.a = Some(service); } } if this.b.is_none() { if let Poll::Ready(service) = this.fut_b.poll(cx)? { *this.b = Some(service); } } if this.a.is_some() && this.b.is_some() { Poll::Ready(Ok(AndThenService::new( this.a.take().unwrap(), this.b.take().unwrap(), ))) } else { Poll::Pending } } } #[cfg(test)] mod tests { use alloc::rc::Rc; use core::{ cell::Cell, task::{Context, Poll}, }; use futures_util::future::lazy; use crate::{ fn_factory, ok, pipeline::{pipeline, pipeline_factory}, ready, Ready, Service, ServiceFactory, }; struct Srv1(Rc<Cell<usize>>); impl Service<&'static str> for Srv1 { type Response = &'static str; type Error = (); type Future = Ready<Result<Self::Response, ()>>; fn poll_ready(&self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { self.0.set(self.0.get() + 1); Poll::Ready(Ok(())) } fn call(&self, req: &'static str) -> Self::Future { ok(req) } } #[derive(Clone)] struct Srv2(Rc<Cell<usize>>); impl Service<&'static str> for Srv2 { type Response = (&'static str, &'static str); type Error = (); type Future = Ready<Result<Self::Response, ()>>; fn poll_ready(&self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { self.0.set(self.0.get() + 1); Poll::Ready(Ok(())) } fn call(&self, req: &'static str) -> Self::Future { ok((req, "srv2")) } } #[actix_rt::test] async fn test_poll_ready() { let cnt = Rc::new(Cell::new(0)); let srv = pipeline(Srv1(cnt.clone())).and_then(Srv2(cnt.clone())); let res = lazy(|cx| srv.poll_ready(cx)).await; assert_eq!(res, Poll::Ready(Ok(()))); assert_eq!(cnt.get(), 2); } #[actix_rt::test] async fn test_call() { let cnt = Rc::new(Cell::new(0)); let srv = pipeline(Srv1(cnt.clone())).and_then(Srv2(cnt)); let res = srv.call("srv1").await; assert!(res.is_ok()); assert_eq!(res.unwrap(), ("srv1", "srv2")); } #[actix_rt::test] async fn test_new_service() { let cnt = Rc::new(Cell::new(0)); let cnt2 = cnt.clone(); let new_srv = pipeline_factory(fn_factory(move || ready(Ok::<_, ()>(Srv1(cnt2.clone()))))) .and_then(move || ready(Ok(Srv2(cnt.clone())))); let srv = new_srv.new_service(()).await.unwrap(); let res = srv.call("srv1").await; assert!(res.is_ok()); assert_eq!(res.unwrap(), ("srv1", "srv2")); } }
use core::{ future::Future, marker::PhantomData, pin::Pin, task::{Context, Poll}, }; use futures_core::ready; use pin_project_lite::pin_project; use super::{IntoService, IntoServiceFactory, Service, ServiceFactory}; /// Apply transform function to a service. /// /// The In and Out type params refer to the request and response types for the wrapped service. pub fn apply_fn<I, S, F, Fut, Req, In, Res, Err>( service: I, wrap_fn: F, ) -> Apply<S, F, Req, In, Res, Err> where I: IntoService<S, In>, S: Service<In, Error = Err>, F: Fn(Req, &S) -> Fut, Fut: Future<Output = Result<Res, Err>>, { Apply::new(service.into_service(), wrap_fn) } /// Service factory that produces `apply_fn` service. /// /// The In and Out type params refer to the request and response types for the wrapped service. pub fn apply_fn_factory<I, SF, F, Fut, Req, In, Res, Err>( service: I, f: F, ) -> ApplyFactory<SF, F, Req, In, Res, Err> where I: IntoServiceFactory<SF, In>, SF: ServiceFactory<In, Error = Err>, F: Fn(Req, &SF::Service) -> Fut + Clone, Fut: Future<Output = Result<Res, Err>>, { ApplyFactory::new(service.into_factory(), f) } /// `Apply` service combinator. /// /// The In and Out type params refer to the request and response types for the wrapped service. pub struct Apply<S, F, Req, In, Res, Err> where S: Service<In, Error = Err>, { service: S, wrap_fn: F, _phantom: PhantomData<fn(Req) -> (In, Res, Err)>, } impl<S, F, Fut, Req, In, Res, Err> Apply<S, F, Req, In, Res, Err> where S: Service<In, Error = Err>, F: Fn(Req, &S) -> Fut, Fut: Future<Output = Result<Res, Err>>, { /// Create new `Apply` combinator fn new(service: S, wrap_fn: F) -> Self { Self { service, wrap_fn, _phantom: PhantomData, } } } impl<S, F, Fut, Req, In, Res, Err> Clone for Apply<S, F, Req, In, Res, Err> where S: Service<In, Error = Err> + Clone, F: Fn(Req, &S) -> Fut + Clone, Fut: Future<Output = Result<Res, Err>>, { fn clone(&self) -> Self { Apply { service: self.service.clone(), wrap_fn: self.wrap_fn.clone(), _phantom: PhantomData, } } } impl<S, F, Fut, Req, In, Res, Err> Service<Req> for Apply<S, F, Req, In, Res, Err> where S: Service<In, Error = Err>, F: Fn(Req, &S) -> Fut, Fut: Future<Output = Result<Res, Err>>, { type Response = Res; type Error = Err; type Future = Fut; crate::forward_ready!(service); fn call(&self, req: Req) -> Self::Future { (self.wrap_fn)(req, &self.service) } } /// `ApplyFactory` service factory combinator. pub struct ApplyFactory<SF, F, Req, In, Res, Err> { factory: SF, wrap_fn: F, _phantom: PhantomData<fn(Req) -> (In, Res, Err)>, } impl<SF, F, Fut, Req, In, Res, Err> ApplyFactory<SF, F, Req, In, Res, Err> where SF: ServiceFactory<In, Error = Err>, F: Fn(Req, &SF::Service) -> Fut + Clone, Fut: Future<Output = Result<Res, Err>>, { /// Create new `ApplyFactory` new service instance fn new(factory: SF, wrap_fn: F) -> Self { Self { factory, wrap_fn, _phantom: PhantomData, } } } impl<SF, F, Fut, Req, In, Res, Err> Clone for ApplyFactory<SF, F, Req, In, Res, Err> where SF: ServiceFactory<In, Error = Err> + Clone, F: Fn(Req, &SF::Service) -> Fut + Clone, Fut: Future<Output = Result<Res, Err>>, { fn clone(&self) -> Self { Self { factory: self.factory.clone(), wrap_fn: self.wrap_fn.clone(), _phantom: PhantomData, } } } impl<SF, F, Fut, Req, In, Res, Err> ServiceFactory<Req> for ApplyFactory<SF, F, Req, In, Res, Err> where SF: ServiceFactory<In, Error = Err>, F: Fn(Req, &SF::Service) -> Fut + Clone, Fut: Future<Output = Result<Res, Err>>, { type Response = Res; type Error = Err; type Config = SF::Config; type Service = Apply<SF::Service, F, Req, In, Res, Err>; type InitError = SF::InitError; type Future = ApplyServiceFactoryResponse<SF, F, Fut, Req, In, Res, Err>; fn new_service(&self, cfg: SF::Config) -> Self::Future { let svc = self.factory.new_service(cfg); ApplyServiceFactoryResponse::new(svc, self.wrap_fn.clone()) } } pin_project! { pub struct ApplyServiceFactoryResponse<SF, F, Fut, Req, In, Res, Err> where SF: ServiceFactory<In, Error = Err>, F: Fn(Req, &SF::Service) -> Fut, Fut: Future<Output = Result<Res, Err>>, { #[pin] fut: SF::Future, wrap_fn: Option<F>, _phantom: PhantomData<fn(Req) -> Res>, } } impl<SF, F, Fut, Req, In, Res, Err> ApplyServiceFactoryResponse<SF, F, Fut, Req, In, Res, Err> where SF: ServiceFactory<In, Error = Err>, F: Fn(Req, &SF::Service) -> Fut, Fut: Future<Output = Result<Res, Err>>, { fn new(fut: SF::Future, wrap_fn: F) -> Self { Self { fut, wrap_fn: Some(wrap_fn), _phantom: PhantomData, } } } impl<SF, F, Fut, Req, In, Res, Err> Future for ApplyServiceFactoryResponse<SF, F, Fut, Req, In, Res, Err> where SF: ServiceFactory<In, Error = Err>, F: Fn(Req, &SF::Service) -> Fut, Fut: Future<Output = Result<Res, Err>>, { type Output = Result<Apply<SF::Service, F, Req, In, Res, Err>, SF::InitError>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let this = self.project(); let svc = ready!(this.fut.poll(cx))?; Poll::Ready(Ok(Apply::new(svc, this.wrap_fn.take().unwrap()))) } } #[cfg(test)] mod tests { use futures_util::future::lazy; use super::*; use crate::{ ok, pipeline::{pipeline, pipeline_factory}, Ready, }; #[derive(Clone)] struct Srv; impl Service<()> for Srv { type Response = (); type Error = (); type Future = Ready<Result<(), ()>>; crate::always_ready!(); fn call(&self, _: ()) -> Self::Future { ok(()) } } #[actix_rt::test] async fn test_call() { let srv = pipeline(apply_fn(Srv, |req: &'static str, srv| { let fut = srv.call(()); async move { fut.await.unwrap(); Ok((req, ())) } })); assert_eq!(lazy(|cx| srv.poll_ready(cx)).await, Poll::Ready(Ok(()))); let res = srv.call("srv").await; assert!(res.is_ok()); assert_eq!(res.unwrap(), ("srv", ())); } #[actix_rt::test] async fn test_new_service() { let new_srv = pipeline_factory(apply_fn_factory( || ok::<_, ()>(Srv), |req: &'static str, srv| { let fut = srv.call(()); async move { fut.await.unwrap(); Ok((req, ())) } }, )); let srv = new_srv.new_service(()).await.unwrap(); assert_eq!(lazy(|cx| srv.poll_ready(cx)).await, Poll::Ready(Ok(()))); let res = srv.call("srv").await; assert!(res.is_ok()); assert_eq!(res.unwrap(), ("srv", ())); } }
use alloc::rc::Rc; use core::{ future::Future, marker::PhantomData, pin::Pin, task::{Context, Poll}, }; use futures_core::ready; use pin_project_lite::pin_project; use crate::{Service, ServiceFactory}; /// Convert `Fn(Config, &Service1) -> Future<Service2>` fn to a service factory. pub fn apply_cfg<S1, Req, F, Cfg, Fut, S2, Err>( srv: S1, f: F, ) -> impl ServiceFactory< Req, Config = Cfg, Response = S2::Response, Error = S2::Error, Service = S2, InitError = Err, Future = Fut, > + Clone where S1: Service<Req>, F: Fn(Cfg, &S1) -> Fut, Fut: Future<Output = Result<S2, Err>>, S2: Service<Req>, { ApplyConfigService { srv: Rc::new((srv, f)), _phantom: PhantomData, } } /// Convert `Fn(Config, &ServiceFactory1) -> Future<ServiceFactory2>` fn to a service factory. /// /// Service1 get constructed from `T` factory. pub fn apply_cfg_factory<SF, Req, F, Cfg, Fut, S>( factory: SF, f: F, ) -> impl ServiceFactory< Req, Config = Cfg, Response = S::Response, Error = S::Error, Service = S, InitError = SF::InitError, > + Clone where SF: ServiceFactory<Req, Config = ()>, F: Fn(Cfg, &SF::Service) -> Fut, SF::InitError: From<SF::Error>, Fut: Future<Output = Result<S, SF::InitError>>, S: Service<Req>, { ApplyConfigServiceFactory { srv: Rc::new((factory, f)), _phantom: PhantomData, } } /// Convert `Fn(Config, &Server) -> Future<Service>` fn to NewService\ struct ApplyConfigService<S1, Req, F, Cfg, Fut, S2, Err> where S1: Service<Req>, F: Fn(Cfg, &S1) -> Fut, Fut: Future<Output = Result<S2, Err>>, S2: Service<Req>, { srv: Rc<(S1, F)>, _phantom: PhantomData<(Cfg, Req, Fut, S2)>, } impl<S1, Req, F, Cfg, Fut, S2, Err> Clone for ApplyConfigService<S1, Req, F, Cfg, Fut, S2, Err> where S1: Service<Req>, F: Fn(Cfg, &S1) -> Fut, Fut: Future<Output = Result<S2, Err>>, S2: Service<Req>, { fn clone(&self) -> Self { ApplyConfigService { srv: self.srv.clone(), _phantom: PhantomData, } } } impl<S1, Req, F, Cfg, Fut, S2, Err> ServiceFactory<Req> for ApplyConfigService<S1, Req, F, Cfg, Fut, S2, Err> where S1: Service<Req>, F: Fn(Cfg, &S1) -> Fut, Fut: Future<Output = Result<S2, Err>>, S2: Service<Req>, { type Response = S2::Response; type Error = S2::Error; type Config = Cfg; type Service = S2; type InitError = Err; type Future = Fut; fn new_service(&self, cfg: Cfg) -> Self::Future { let (t, f) = &*self.srv; f(cfg, t) } } /// Convert `Fn(&Config) -> Future<Service>` fn to NewService struct ApplyConfigServiceFactory<SF, Req, F, Cfg, Fut, S> where SF: ServiceFactory<Req, Config = ()>, F: Fn(Cfg, &SF::Service) -> Fut, Fut: Future<Output = Result<S, SF::InitError>>, S: Service<Req>, { srv: Rc<(SF, F)>, _phantom: PhantomData<(Cfg, Req, Fut, S)>, } impl<SF, Req, F, Cfg, Fut, S> Clone for ApplyConfigServiceFactory<SF, Req, F, Cfg, Fut, S> where SF: ServiceFactory<Req, Config = ()>, F: Fn(Cfg, &SF::Service) -> Fut, Fut: Future<Output = Result<S, SF::InitError>>, S: Service<Req>, { fn clone(&self) -> Self { Self { srv: self.srv.clone(), _phantom: PhantomData, } } } impl<SF, Req, F, Cfg, Fut, S> ServiceFactory<Req> for ApplyConfigServiceFactory<SF, Req, F, Cfg, Fut, S> where SF: ServiceFactory<Req, Config = ()>, SF::InitError: From<SF::Error>, F: Fn(Cfg, &SF::Service) -> Fut, Fut: Future<Output = Result<S, SF::InitError>>, S: Service<Req>, { type Response = S::Response; type Error = S::Error; type Config = Cfg; type Service = S; type InitError = SF::InitError; type Future = ApplyConfigServiceFactoryResponse<SF, Req, F, Cfg, Fut, S>; fn new_service(&self, cfg: Cfg) -> Self::Future { ApplyConfigServiceFactoryResponse { cfg: Some(cfg), store: self.srv.clone(), state: State::A { fut: self.srv.0.new_service(()), }, } } } pin_project! { struct ApplyConfigServiceFactoryResponse<SF, Req, F, Cfg, Fut, S> where SF: ServiceFactory<Req, Config = ()>, SF::InitError: From<SF::Error>, F: Fn(Cfg, &SF::Service) -> Fut, Fut: Future<Output = Result<S, SF::InitError>>, S: Service<Req>, { cfg: Option<Cfg>, store: Rc<(SF, F)>, #[pin] state: State<SF, Fut, S, Req>, } } pin_project! { #[project = StateProj] enum State<SF, Fut, S, Req> where SF: ServiceFactory<Req, Config = ()>, SF::InitError: From<SF::Error>, Fut: Future<Output = Result<S, SF::InitError>>, S: Service<Req>, { A { #[pin] fut: SF::Future }, B { svc: SF::Service }, C { #[pin] fut: Fut }, } } impl<SF, Req, F, Cfg, Fut, S> Future for ApplyConfigServiceFactoryResponse<SF, Req, F, Cfg, Fut, S> where SF: ServiceFactory<Req, Config = ()>, SF::InitError: From<SF::Error>, F: Fn(Cfg, &SF::Service) -> Fut, Fut: Future<Output = Result<S, SF::InitError>>, S: Service<Req>, { type Output = Result<S, SF::InitError>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let mut this = self.as_mut().project(); match this.state.as_mut().project() { StateProj::A { fut } => { let svc = ready!(fut.poll(cx))?; this.state.set(State::B { svc }); self.poll(cx) } StateProj::B { svc } => { ready!(svc.poll_ready(cx))?; { let (_, f) = &**this.store; let fut = f(this.cfg.take().unwrap(), svc); this.state.set(State::C { fut }); } self.poll(cx) } StateProj::C { fut } => fut.poll(cx), } } }
//! Trait object forms of services and service factories. use alloc::{boxed::Box, rc::Rc}; use core::{future::Future, pin::Pin}; use crate::{Service, ServiceFactory}; /// A boxed future with no send bound or lifetime parameters. pub type BoxFuture<T> = Pin<Box<dyn Future<Output = T>>>; /// Type alias for service trait object using [`Box`]. pub type BoxService<Req, Res, Err> = Box<dyn Service<Req, Response = Res, Error = Err, Future = BoxFuture<Result<Res, Err>>>>; /// Wraps service as a trait object using [`BoxService`]. pub fn service<S, Req>(service: S) -> BoxService<Req, S::Response, S::Error> where S: Service<Req> + 'static, Req: 'static, S::Future: 'static, { Box::new(ServiceWrapper::new(service)) } /// Type alias for service trait object using [`Rc`]. pub type RcService<Req, Res, Err> = Rc<dyn Service<Req, Response = Res, Error = Err, Future = BoxFuture<Result<Res, Err>>>>; /// Wraps service as a trait object using [`RcService`]. pub fn rc_service<S, Req>(service: S) -> RcService<Req, S::Response, S::Error> where S: Service<Req> + 'static, Req: 'static, S::Future: 'static, { Rc::new(ServiceWrapper::new(service)) } struct ServiceWrapper<S> { inner: S, } impl<S> ServiceWrapper<S> { fn new(inner: S) -> Self { Self { inner } } } impl<S, Req, Res, Err> Service<Req> for ServiceWrapper<S> where S: Service<Req, Response = Res, Error = Err>, S::Future: 'static, { type Response = Res; type Error = Err; type Future = BoxFuture<Result<Res, Err>>; crate::forward_ready!(inner); fn call(&self, req: Req) -> Self::Future { Box::pin(self.inner.call(req)) } } /// Wrapper for a service factory that will map it's services to boxed trait object services. pub struct BoxServiceFactory<Cfg, Req, Res, Err, InitErr>(Inner<Cfg, Req, Res, Err, InitErr>); /// Wraps a service factory that returns service trait objects. pub fn factory<SF, Req>( factory: SF, ) -> BoxServiceFactory<SF::Config, Req, SF::Response, SF::Error, SF::InitError> where SF: ServiceFactory<Req> + 'static, Req: 'static, SF::Response: 'static, SF::Service: 'static, SF::Future: 'static, SF::Error: 'static, SF::InitError: 'static, { BoxServiceFactory(Box::new(FactoryWrapper(factory))) } type Inner<C, Req, Res, Err, InitErr> = Box< dyn ServiceFactory< Req, Config = C, Response = Res, Error = Err, InitError = InitErr, Service = BoxService<Req, Res, Err>, Future = BoxFuture<Result<BoxService<Req, Res, Err>, InitErr>>, >, >; impl<C, Req, Res, Err, InitErr> ServiceFactory<Req> for BoxServiceFactory<C, Req, Res, Err, InitErr> where Req: 'static, Res: 'static, Err: 'static, InitErr: 'static, { type Response = Res; type Error = Err; type Config = C; type Service = BoxService<Req, Res, Err>; type InitError = InitErr; type Future = BoxFuture<Result<Self::Service, InitErr>>; fn new_service(&self, cfg: C) -> Self::Future { self.0.new_service(cfg) } } struct FactoryWrapper<SF>(SF); impl<SF, Req, Cfg, Res, Err, InitErr> ServiceFactory<Req> for FactoryWrapper<SF> where Req: 'static, Res: 'static, Err: 'static, InitErr: 'static, SF: ServiceFactory<Req, Config = Cfg, Response = Res, Error = Err, InitError = InitErr>, SF::Future: 'static, SF::Service: 'static, <SF::Service as Service<Req>>::Future: 'static, { type Response = Res; type Error = Err; type Config = Cfg; type Service = BoxService<Req, Res, Err>; type InitError = InitErr; type Future = BoxFuture<Result<Self::Service, Self::InitError>>; fn new_service(&self, cfg: Cfg) -> Self::Future { let f = self.0.new_service(cfg); Box::pin(async { f.await.map(|s| Box::new(ServiceWrapper::new(s)) as _) }) } }
use crate::{ and_then::{AndThenService, AndThenServiceFactory}, map::Map, map_err::MapErr, transform_err::TransformMapInitErr, IntoService, IntoServiceFactory, Service, ServiceFactory, Transform, }; /// An extension trait for [`Service`]s that provides a variety of convenient adapters. pub trait ServiceExt<Req>: Service<Req> { /// Map this service's output to a different type, returning a new service /// of the resulting type. /// /// This function is similar to the `Option::map` or `Iterator::map` where /// it will change the type of the underlying service. /// /// Note that this function consumes the receiving service and returns a /// wrapped version of it, similar to the existing `map` methods in the /// standard library. fn map<F, R>(self, f: F) -> Map<Self, F, Req, R> where Self: Sized, F: FnMut(Self::Response) -> R, { Map::new(self, f) } /// Map this service's error to a different error, returning a new service. /// /// This function is similar to the `Result::map_err` where it will change /// the error type of the underlying service. For example, this can be useful to /// ensure that services have the same error type. /// /// Note that this function consumes the receiving service and returns a /// wrapped version of it. fn map_err<F, E>(self, f: F) -> MapErr<Self, Req, F, E> where Self: Sized, F: Fn(Self::Error) -> E, { MapErr::new(self, f) } /// Call another service after call to this one has resolved successfully. /// /// This function can be used to chain two services together and ensure that the second service /// isn't called until call to the first service have finished. Result of the call to the first /// service is used as an input parameter for the second service's call. /// /// Note that this function consumes the receiving service and returns a wrapped version of it. fn and_then<I, S1>(self, service: I) -> AndThenService<Self, S1, Req> where Self: Sized, I: IntoService<S1, Self::Response>, S1: Service<Self::Response, Error = Self::Error>, { AndThenService::new(self, service.into_service()) } } impl<S, Req> ServiceExt<Req> for S where S: Service<Req> {} /// An extension trait for [`ServiceFactory`]s that provides a variety of convenient adapters. pub trait ServiceFactoryExt<Req>: ServiceFactory<Req> { /// Map this service's output to a different type, returning a new service /// of the resulting type. fn map<F, R>(self, f: F) -> crate::map::MapServiceFactory<Self, F, Req, R> where Self: Sized, F: FnMut(Self::Response) -> R + Clone, { crate::map::MapServiceFactory::new(self, f) } /// Map this service's error to a different error, returning a new service. fn map_err<F, E>(self, f: F) -> crate::map_err::MapErrServiceFactory<Self, Req, F, E> where Self: Sized, F: Fn(Self::Error) -> E + Clone, { crate::map_err::MapErrServiceFactory::new(self, f) } /// Map this factory's init error to a different error, returning a new service. fn map_init_err<F, E>(self, f: F) -> crate::map_init_err::MapInitErr<Self, F, Req, E> where Self: Sized, F: Fn(Self::InitError) -> E + Clone, { crate::map_init_err::MapInitErr::new(self, f) } /// Call another service after call to this one has resolved successfully. fn and_then<I, SF1>(self, factory: I) -> AndThenServiceFactory<Self, SF1, Req> where Self: Sized, Self::Config: Clone, I: IntoServiceFactory<SF1, Self::Response>, SF1: ServiceFactory< Self::Response, Config = Self::Config, Error = Self::Error, InitError = Self::InitError, >, { AndThenServiceFactory::new(self, factory.into_factory()) } } impl<SF, Req> ServiceFactoryExt<Req> for SF where SF: ServiceFactory<Req> {} /// An extension trait for [`Transform`]s that provides a variety of convenient adapters. pub trait TransformExt<S, Req>: Transform<S, Req> { /// Return a new `Transform` whose init error is mapped to to a different type. fn map_init_err<F, E>(self, f: F) -> TransformMapInitErr<Self, S, Req, F, E> where Self: Sized, F: Fn(Self::InitError) -> E + Clone, { TransformMapInitErr::new(self, f) } } impl<T, Req> TransformExt<T, Req> for T where T: Transform<T, Req> {}
use core::{future::Future, marker::PhantomData}; use crate::{ok, IntoService, IntoServiceFactory, Ready, Service, ServiceFactory}; /// Create `ServiceFactory` for function that can act as a `Service` pub fn fn_service<F, Fut, Req, Res, Err, Cfg>(f: F) -> FnServiceFactory<F, Fut, Req, Res, Err, Cfg> where F: Fn(Req) -> Fut + Clone, Fut: Future<Output = Result<Res, Err>>, { FnServiceFactory::new(f) } /// Create `ServiceFactory` for function that can produce services /// /// # Examples /// ``` /// use std::io; /// use actix_service::{fn_factory, fn_service, Service, ServiceFactory}; /// use futures_util::future::ok; /// /// /// Service that divides two usize values. /// async fn div((x, y): (usize, usize)) -> Result<usize, io::Error> { /// if y == 0 { /// Err(io::Error::new(io::ErrorKind::Other, "divide by zero")) /// } else { /// Ok(x / y) /// } /// } /// /// #[actix_rt::main] /// async fn main() -> io::Result<()> { /// // Create service factory that produces `div` services /// let factory = fn_factory(|| { /// ok::<_, io::Error>(fn_service(div)) /// }); /// /// // construct new service /// let srv = factory.new_service(()).await?; /// /// // now we can use `div` service /// let result = srv.call((10, 20)).await?; /// /// println!("10 / 20 = {}", result); /// /// Ok(()) /// } /// ``` pub fn fn_factory<F, Cfg, Srv, Req, Fut, Err>(f: F) -> FnServiceNoConfig<F, Cfg, Srv, Req, Fut, Err> where F: Fn() -> Fut, Fut: Future<Output = Result<Srv, Err>>, Srv: Service<Req>, { FnServiceNoConfig::new(f) } /// Create `ServiceFactory` for function that accepts config argument and can produce services /// /// Any function that has following form `Fn(Config) -> Future<Output = Service>` could act as /// a `ServiceFactory`. /// /// # Examples /// ``` /// use std::io; /// use actix_service::{fn_factory_with_config, fn_service, Service, ServiceFactory}; /// use futures_util::future::ok; /// /// #[actix_rt::main] /// async fn main() -> io::Result<()> { /// // Create service factory. factory uses config argument for /// // services it generates. /// let factory = fn_factory_with_config(|y: usize| { /// ok::<_, io::Error>(fn_service(move |x: usize| ok::<_, io::Error>(x * y))) /// }); /// /// // construct new service with config argument /// let srv = factory.new_service(10).await?; /// /// let result = srv.call(10).await?; /// assert_eq!(result, 100); /// /// println!("10 * 10 = {}", result); /// Ok(()) /// } /// ``` pub fn fn_factory_with_config<F, Fut, Cfg, Srv, Req, Err>( f: F, ) -> FnServiceConfig<F, Fut, Cfg, Srv, Req, Err> where F: Fn(Cfg) -> Fut, Fut: Future<Output = Result<Srv, Err>>, Srv: Service<Req>, { FnServiceConfig::new(f) } pub struct FnService<F, Fut, Req, Res, Err> where F: FnMut(Req) -> Fut, Fut: Future<Output = Result<Res, Err>>, { f: F, _t: PhantomData<fn(Req)>, } impl<F, Fut, Req, Res, Err> FnService<F, Fut, Req, Res, Err> where F: FnMut(Req) -> Fut, Fut: Future<Output = Result<Res, Err>>, { pub(crate) fn new(f: F) -> Self { Self { f, _t: PhantomData } } } impl<F, Fut, Req, Res, Err> Clone for FnService<F, Fut, Req, Res, Err> where F: FnMut(Req) -> Fut + Clone, Fut: Future<Output = Result<Res, Err>>, { fn clone(&self) -> Self { Self::new(self.f.clone()) } } impl<F, Fut, Req, Res, Err> Service<Req> for FnService<F, Fut, Req, Res, Err> where F: Fn(Req) -> Fut, Fut: Future<Output = Result<Res, Err>>, { type Response = Res; type Error = Err; type Future = Fut; crate::always_ready!(); fn call(&self, req: Req) -> Self::Future { (self.f)(req) } } impl<F, Fut, Req, Res, Err> IntoService<FnService<F, Fut, Req, Res, Err>, Req> for F where F: Fn(Req) -> Fut, Fut: Future<Output = Result<Res, Err>>, { fn into_service(self) -> FnService<F, Fut, Req, Res, Err> { FnService::new(self) } } pub struct FnServiceFactory<F, Fut, Req, Res, Err, Cfg> where F: Fn(Req) -> Fut, Fut: Future<Output = Result<Res, Err>>, { f: F, _t: PhantomData<fn(Req, Cfg)>, } impl<F, Fut, Req, Res, Err, Cfg> FnServiceFactory<F, Fut, Req, Res, Err, Cfg> where F: Fn(Req) -> Fut + Clone, Fut: Future<Output = Result<Res, Err>>, { fn new(f: F) -> Self { FnServiceFactory { f, _t: PhantomData } } } impl<F, Fut, Req, Res, Err, Cfg> Clone for FnServiceFactory<F, Fut, Req, Res, Err, Cfg> where F: Fn(Req) -> Fut + Clone, Fut: Future<Output = Result<Res, Err>>, { fn clone(&self) -> Self { Self::new(self.f.clone()) } } impl<F, Fut, Req, Res, Err> Service<Req> for FnServiceFactory<F, Fut, Req, Res, Err, ()> where F: Fn(Req) -> Fut + Clone, Fut: Future<Output = Result<Res, Err>>, { type Response = Res; type Error = Err; type Future = Fut; crate::always_ready!(); fn call(&self, req: Req) -> Self::Future { (self.f)(req) } } impl<F, Fut, Req, Res, Err, Cfg> ServiceFactory<Req> for FnServiceFactory<F, Fut, Req, Res, Err, Cfg> where F: Fn(Req) -> Fut + Clone, Fut: Future<Output = Result<Res, Err>>, { type Response = Res; type Error = Err; type Config = Cfg; type Service = FnService<F, Fut, Req, Res, Err>; type InitError = (); type Future = Ready<Result<Self::Service, Self::InitError>>; fn new_service(&self, _: Cfg) -> Self::Future { ok(FnService::new(self.f.clone())) } } impl<F, Fut, Req, Res, Err, Cfg> IntoServiceFactory<FnServiceFactory<F, Fut, Req, Res, Err, Cfg>, Req> for F where F: Fn(Req) -> Fut + Clone, Fut: Future<Output = Result<Res, Err>>, { fn into_factory(self) -> FnServiceFactory<F, Fut, Req, Res, Err, Cfg> { FnServiceFactory::new(self) } } /// Convert `Fn(&Config) -> Future<Service>` fn to NewService pub struct FnServiceConfig<F, Fut, Cfg, Srv, Req, Err> where F: Fn(Cfg) -> Fut, Fut: Future<Output = Result<Srv, Err>>, Srv: Service<Req>, { f: F, _t: PhantomData<fn(Cfg, Req) -> (Fut, Srv, Err)>, } impl<F, Fut, Cfg, Srv, Req, Err> FnServiceConfig<F, Fut, Cfg, Srv, Req, Err> where F: Fn(Cfg) -> Fut, Fut: Future<Output = Result<Srv, Err>>, Srv: Service<Req>, { fn new(f: F) -> Self { FnServiceConfig { f, _t: PhantomData } } } impl<F, Fut, Cfg, Srv, Req, Err> Clone for FnServiceConfig<F, Fut, Cfg, Srv, Req, Err> where F: Fn(Cfg) -> Fut + Clone, Fut: Future<Output = Result<Srv, Err>>, Srv: Service<Req>, { fn clone(&self) -> Self { FnServiceConfig { f: self.f.clone(), _t: PhantomData, } } } impl<F, Fut, Cfg, Srv, Req, Err> ServiceFactory<Req> for FnServiceConfig<F, Fut, Cfg, Srv, Req, Err> where F: Fn(Cfg) -> Fut, Fut: Future<Output = Result<Srv, Err>>, Srv: Service<Req>, { type Response = Srv::Response; type Error = Srv::Error; type Config = Cfg; type Service = Srv; type InitError = Err; type Future = Fut; fn new_service(&self, cfg: Cfg) -> Self::Future { (self.f)(cfg) } } /// Converter for `Fn() -> Future<Service>` fn pub struct FnServiceNoConfig<F, Cfg, Srv, Req, Fut, Err> where F: Fn() -> Fut, Srv: Service<Req>, Fut: Future<Output = Result<Srv, Err>>, { f: F, _t: PhantomData<fn(Cfg, Req)>, } impl<F, Cfg, Srv, Req, Fut, Err> FnServiceNoConfig<F, Cfg, Srv, Req, Fut, Err> where F: Fn() -> Fut, Fut: Future<Output = Result<Srv, Err>>, Srv: Service<Req>, { fn new(f: F) -> Self { Self { f, _t: PhantomData } } } impl<F, Cfg, Srv, Req, Fut, Err> ServiceFactory<Req> for FnServiceNoConfig<F, Cfg, Srv, Req, Fut, Err> where F: Fn() -> Fut, Fut: Future<Output = Result<Srv, Err>>, Srv: Service<Req>, { type Response = Srv::Response; type Error = Srv::Error; type Config = Cfg; type Service = Srv; type InitError = Err; type Future = Fut; fn new_service(&self, _: Cfg) -> Self::Future { (self.f)() } } impl<F, Cfg, Srv, Req, Fut, Err> Clone for FnServiceNoConfig<F, Cfg, Srv, Req, Fut, Err> where F: Fn() -> Fut + Clone, Fut: Future<Output = Result<Srv, Err>>, Srv: Service<Req>, { fn clone(&self) -> Self { Self::new(self.f.clone()) } } impl<F, Cfg, Srv, Req, Fut, Err> IntoServiceFactory<FnServiceNoConfig<F, Cfg, Srv, Req, Fut, Err>, Req> for F where F: Fn() -> Fut, Fut: Future<Output = Result<Srv, Err>>, Srv: Service<Req>, { fn into_factory(self) -> FnServiceNoConfig<F, Cfg, Srv, Req, Fut, Err> { FnServiceNoConfig::new(self) } } #[cfg(test)] mod tests { use core::task::Poll; use futures_util::future::lazy; use super::*; #[actix_rt::test] async fn test_fn_service() { let new_srv = fn_service(|()| ok::<_, ()>("srv")); let srv = new_srv.new_service(()).await.unwrap(); let res = srv.call(()).await; assert_eq!(lazy(|cx| srv.poll_ready(cx)).await, Poll::Ready(Ok(()))); assert!(res.is_ok()); assert_eq!(res.unwrap(), "srv"); } #[actix_rt::test] async fn test_fn_service_service() { let srv = fn_service(|()| ok::<_, ()>("srv")); let res = srv.call(()).await; assert_eq!(lazy(|cx| srv.poll_ready(cx)).await, Poll::Ready(Ok(()))); assert!(res.is_ok()); assert_eq!(res.unwrap(), "srv"); } #[actix_rt::test] async fn test_fn_service_with_config() { let new_srv = fn_factory_with_config(|cfg: usize| { ok::<_, ()>(fn_service(move |()| ok::<_, ()>(("srv", cfg)))) }); let srv = new_srv.new_service(1).await.unwrap(); let res = srv.call(()).await; assert_eq!(lazy(|cx| srv.poll_ready(cx)).await, Poll::Ready(Ok(()))); assert!(res.is_ok()); assert_eq!(res.unwrap(), ("srv", 1)); } #[actix_rt::test] async fn test_auto_impl_send() { use alloc::rc::Rc; use crate::{map_config, ServiceExt, ServiceFactoryExt}; let srv_1 = fn_service(|_: Rc<u8>| ok::<_, Rc<u8>>(Rc::new(0u8))); let fac_1 = fn_factory_with_config(|_: Rc<u8>| { ok::<_, Rc<u8>>(fn_service(|_: Rc<u8>| ok::<_, Rc<u8>>(Rc::new(0u8)))) }); let fac_2 = fn_factory(|| ok::<_, Rc<u8>>(fn_service(|_: Rc<u8>| ok::<_, Rc<u8>>(Rc::new(0u8))))); fn is_send<T: Send + Sync + Clone>(_: &T) {} is_send(&fac_1); is_send(&map_config(fac_1.clone(), |_: Rc<u8>| Rc::new(0u8))); is_send(&fac_1.clone().map_err(|_| Rc::new(0u8))); is_send(&fac_1.clone().map(|_| Rc::new(0u8))); is_send(&fac_1.clone().map_init_err(|_| Rc::new(0u8))); // `and_then` is always !Send // is_send(&fac_1.clone().and_then(fac_1.clone())); is_send(&fac_1.new_service(Rc::new(0u8)).await.unwrap()); is_send(&fac_2); is_send(&fac_2.new_service(Rc::new(0u8)).await.unwrap()); is_send(&srv_1); is_send(&ServiceExt::map(srv_1.clone(), |_| Rc::new(0u8))); is_send(&ServiceExt::map_err(srv_1.clone(), |_| Rc::new(0u8))); // `and_then` is always !Send // is_send(&ServiceExt::and_then(srv_1.clone(), srv_1.clone())); } }
//! See [`Service`] docs for information on this crate's foundational trait. #![no_std] #![allow(clippy::type_complexity)] #![doc(html_logo_url = "https://actix.rs/img/logo.png")] #![doc(html_favicon_url = "https://actix.rs/favicon.ico")] extern crate alloc; use alloc::{boxed::Box, rc::Rc, sync::Arc}; use core::{ cell::RefCell, future::Future, task::{self, Context, Poll}, }; mod and_then; mod apply; mod apply_cfg; pub mod boxed; mod ext; mod fn_service; mod macros; mod map; mod map_config; mod map_err; mod map_init_err; mod pipeline; mod ready; mod then; mod transform; mod transform_err; #[allow(unused_imports)] use self::ready::{err, ok, ready, Ready}; pub use self::{ apply::{apply_fn, apply_fn_factory}, apply_cfg::{apply_cfg, apply_cfg_factory}, ext::{ServiceExt, ServiceFactoryExt, TransformExt}, fn_service::{fn_factory, fn_factory_with_config, fn_service}, map_config::{map_config, unit_config}, transform::{apply, ApplyTransform, Transform}, }; /// An asynchronous operation from `Request` to a `Response`. /// /// The `Service` trait models a request/response interaction, receiving requests and returning /// replies. You can think about a service as a function with one argument that returns some result /// asynchronously. Conceptually, the operation looks like this: /// /// ```ignore /// async fn(Request) -> Result<Response, Err> /// ``` /// /// The `Service` trait just generalizes this form. Requests are defined as a generic type parameter /// and responses and other details are defined as associated types on the trait impl. Notice that /// this design means that services can receive many request types and converge them to a single /// response type. /// /// Services can also have mutable state that influence computation by using a `Cell`, `RefCell` /// or `Mutex`. Services intentionally do not take `&mut self` to reduce overhead in the /// common cases. /// /// `Service` provides a symmetric and uniform API; the same abstractions can be used to represent /// both clients and servers. Services describe only _transformation_ operations which encourage /// simple API surfaces. This leads to simpler design of each service, improves test-ability and /// makes composition easier. /// /// ```ignore /// struct MyService; /// /// impl Service<u8> for MyService { /// type Response = u64; /// type Error = MyError; /// type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>; /// /// fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { ... } /// /// fn call(&self, req: u8) -> Self::Future { ... } /// } /// ``` /// /// Sometimes it is not necessary to implement the Service trait. For example, the above service /// could be rewritten as a simple function and passed to [`fn_service`](fn_service()). /// /// ```ignore /// async fn my_service(req: u8) -> Result<u64, MyError>; /// /// let svc = fn_service(my_service) /// svc.call(123) /// ``` pub trait Service<Req> { /// Responses given by the service. type Response; /// Errors produced by the service when polling readiness or executing call. type Error; /// The future response value. type Future: Future<Output = Result<Self::Response, Self::Error>>; /// Returns `Ready` when the service is able to process requests. /// /// If the service is at capacity, then `Pending` is returned and the task is notified when the /// service becomes ready again. This function is expected to be called while on a task. /// /// This is a best effort implementation. False positives are permitted. It is permitted for /// the service to return `Ready` from a `poll_ready` call and the next invocation of `call` /// results in an error. /// /// # Notes /// 1. `poll_ready` might be called on a different task to `call`. /// 1. In cases of chained services, `.poll_ready()` is called for all services at once. fn poll_ready(&self, ctx: &mut task::Context<'_>) -> Poll<Result<(), Self::Error>>; /// Process the request and return the response asynchronously. /// /// This function is expected to be callable off-task. As such, implementations of `call` should /// take care to not call `poll_ready`. If the service is at capacity and the request is unable /// to be handled, the returned `Future` should resolve to an error. /// /// Invoking `call` without first invoking `poll_ready` is permitted. Implementations must be /// resilient to this fact. fn call(&self, req: Req) -> Self::Future; } /// Factory for creating `Service`s. /// /// This is useful for cases where new `Service`s must be produced. One case is a TCP /// server listener: a listener accepts new connections, constructs a new `Service` for each using /// the `ServiceFactory` trait, and uses the new `Service` to process inbound requests on that new /// connection. /// /// `Config` is a service factory configuration type. /// /// Simple factories may be able to use [`fn_factory`] or [`fn_factory_with_config`] to /// reduce boilerplate. pub trait ServiceFactory<Req> { /// Responses given by the created services. type Response; /// Errors produced by the created services. type Error; /// Service factory configuration. type Config; /// The kind of `Service` created by this factory. type Service: Service<Req, Response = Self::Response, Error = Self::Error>; /// Errors potentially raised while building a service. type InitError; /// The future of the `Service` instance.g type Future: Future<Output = Result<Self::Service, Self::InitError>>; /// Create and return a new service asynchronously. fn new_service(&self, cfg: Self::Config) -> Self::Future; } // TODO: remove implement on mut reference. impl<'a, S, Req> Service<Req> for &'a mut S where S: Service<Req> + 'a, { type Response = S::Response; type Error = S::Error; type Future = S::Future; fn poll_ready(&self, ctx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { (**self).poll_ready(ctx) } fn call(&self, request: Req) -> S::Future { (**self).call(request) } } impl<'a, S, Req> Service<Req> for &'a S where S: Service<Req> + 'a, { type Response = S::Response; type Error = S::Error; type Future = S::Future; fn poll_ready(&self, ctx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { (**self).poll_ready(ctx) } fn call(&self, request: Req) -> S::Future { (**self).call(request) } } impl<S, Req> Service<Req> for Box<S> where S: Service<Req> + ?Sized, { type Response = S::Response; type Error = S::Error; type Future = S::Future; fn poll_ready(&self, ctx: &mut Context<'_>) -> Poll<Result<(), S::Error>> { (**self).poll_ready(ctx) } fn call(&self, request: Req) -> S::Future { (**self).call(request) } } impl<S, Req> Service<Req> for Rc<S> where S: Service<Req> + ?Sized, { type Response = S::Response; type Error = S::Error; type Future = S::Future; fn poll_ready(&self, ctx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { (**self).poll_ready(ctx) } fn call(&self, request: Req) -> S::Future { (**self).call(request) } } /// This impl is deprecated since v2 because the `Service` trait now receives shared reference. impl<S, Req> Service<Req> for RefCell<S> where S: Service<Req>, { type Response = S::Response; type Error = S::Error; type Future = S::Future; fn poll_ready(&self, ctx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { self.borrow().poll_ready(ctx) } fn call(&self, request: Req) -> S::Future { self.borrow().call(request) } } impl<S, Req> ServiceFactory<Req> for Rc<S> where S: ServiceFactory<Req>, { type Response = S::Response; type Error = S::Error; type Config = S::Config; type Service = S::Service; type InitError = S::InitError; type Future = S::Future; fn new_service(&self, cfg: S::Config) -> S::Future { self.as_ref().new_service(cfg) } } impl<S, Req> ServiceFactory<Req> for Arc<S> where S: ServiceFactory<Req>, { type Response = S::Response; type Error = S::Error; type Config = S::Config; type Service = S::Service; type InitError = S::InitError; type Future = S::Future; fn new_service(&self, cfg: S::Config) -> S::Future { self.as_ref().new_service(cfg) } } /// Trait for types that can be converted to a `Service` pub trait IntoService<S, Req> where S: Service<Req>, { /// Convert to a `Service` fn into_service(self) -> S; } /// Trait for types that can be converted to a `ServiceFactory` pub trait IntoServiceFactory<SF, Req> where SF: ServiceFactory<Req>, { /// Convert `Self` to a `ServiceFactory` fn into_factory(self) -> SF; } impl<S, Req> IntoService<S, Req> for S where S: Service<Req>, { fn into_service(self) -> S { self } } impl<SF, Req> IntoServiceFactory<SF, Req> for SF where SF: ServiceFactory<Req>, { fn into_factory(self) -> SF { self } } /// Convert object of type `U` to a service `S` pub fn into_service<I, S, Req>(tp: I) -> S where I: IntoService<S, Req>, S: Service<Req>, { tp.into_service() }
/// An implementation of [`poll_ready`]() that always signals readiness. /// /// This should only be used for basic leaf services that have no concept of un-readiness. /// For wrapper or other service types, use [`forward_ready!`] for simple cases or write a bespoke /// `poll_ready` implementation. /// /// [`poll_ready`]: crate::Service::poll_ready /// /// # Examples /// ```no_run /// use actix_service::Service; /// use futures_util::future::{ready, Ready}; /// /// struct IdentityService; /// /// impl Service<u32> for IdentityService { /// type Response = u32; /// type Error = (); /// type Future = Ready<Result<Self::Response, Self::Error>>; /// /// actix_service::always_ready!(); /// /// fn call(&self, req: u32) -> Self::Future { /// ready(Ok(req)) /// } /// } /// ``` /// /// [`forward_ready!`]: crate::forward_ready #[macro_export] macro_rules! always_ready { () => { #[inline] fn poll_ready( &self, _: &mut ::core::task::Context<'_>, ) -> ::core::task::Poll<Result<(), Self::Error>> { ::core::task::Poll::Ready(Ok(())) } }; } /// An implementation of [`poll_ready`] that forwards readiness checks to a /// named struct field. /// /// Tuple structs are not supported. /// /// [`poll_ready`]: crate::Service::poll_ready /// /// # Examples /// ```no_run /// use actix_service::Service; /// use futures_util::future::{ready, Ready}; /// /// struct WrapperService<S> { /// inner: S, /// } /// /// impl<S> Service<()> for WrapperService<S> /// where /// S: Service<()>, /// { /// type Response = S::Response; /// type Error = S::Error; /// type Future = S::Future; /// /// actix_service::forward_ready!(inner); /// /// fn call(&self, req: ()) -> Self::Future { /// self.inner.call(req) /// } /// } /// ``` #[macro_export] macro_rules! forward_ready { ($field:ident) => { #[inline] fn poll_ready( &self, cx: &mut ::core::task::Context<'_>, ) -> ::core::task::Poll<Result<(), Self::Error>> { self.$field .poll_ready(cx) .map_err(::core::convert::Into::into) } }; } #[cfg(test)] mod tests { use core::{ cell::Cell, convert::Infallible, task::{self, Context, Poll}, }; use futures_util::{ future::{ready, Ready}, task::noop_waker, }; use crate::Service; struct IdentityService; impl Service<u32> for IdentityService { type Response = u32; type Error = Infallible; type Future = Ready<Result<Self::Response, Self::Error>>; always_ready!(); fn call(&self, req: u32) -> Self::Future { ready(Ok(req)) } } struct CountdownService(Cell<u32>); impl Service<()> for CountdownService { type Response = (); type Error = Infallible; type Future = Ready<Result<Self::Response, Self::Error>>; fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { let count = self.0.get(); if count == 0 { Poll::Ready(Ok(())) } else { self.0.set(count - 1); cx.waker().wake_by_ref(); Poll::Pending } } fn call(&self, _: ()) -> Self::Future { ready(Ok(())) } } struct WrapperService<S> { inner: S, } impl<S> Service<()> for WrapperService<S> where S: Service<()>, { type Response = S::Response; type Error = S::Error; type Future = S::Future; forward_ready!(inner); fn call(&self, _: ()) -> Self::Future { self.inner.call(()) } } #[test] fn test_always_ready_macro() { let waker = noop_waker(); let mut cx = task::Context::from_waker(&waker); let svc = IdentityService; assert!(svc.poll_ready(&mut cx).is_ready()); assert!(svc.poll_ready(&mut cx).is_ready()); assert!(svc.poll_ready(&mut cx).is_ready()); } #[test] fn test_forward_ready_macro() { let waker = noop_waker(); let mut cx = task::Context::from_waker(&waker); let svc = WrapperService { inner: CountdownService(Cell::new(3)), }; assert!(svc.poll_ready(&mut cx).is_pending()); assert!(svc.poll_ready(&mut cx).is_pending()); assert!(svc.poll_ready(&mut cx).is_pending()); assert!(svc.poll_ready(&mut cx).is_ready()); } }
use core::{ future::Future, marker::PhantomData, pin::Pin, task::{Context, Poll}, }; use pin_project_lite::pin_project; use super::{Service, ServiceFactory}; /// Service for the `map` combinator, changing the type of a service's response. /// /// This is created by the `ServiceExt::map` method. pub struct Map<A, F, Req, Res> { service: A, f: F, _t: PhantomData<fn(Req) -> Res>, } impl<A, F, Req, Res> Map<A, F, Req, Res> { /// Create new `Map` combinator pub(crate) fn new(service: A, f: F) -> Self where A: Service<Req>, F: FnMut(A::Response) -> Res, { Self { service, f, _t: PhantomData, } } } impl<A, F, Req, Res> Clone for Map<A, F, Req, Res> where A: Clone, F: Clone, { fn clone(&self) -> Self { Map { service: self.service.clone(), f: self.f.clone(), _t: PhantomData, } } } impl<A, F, Req, Res> Service<Req> for Map<A, F, Req, Res> where A: Service<Req>, F: FnMut(A::Response) -> Res + Clone, { type Response = Res; type Error = A::Error; type Future = MapFuture<A, F, Req, Res>; crate::forward_ready!(service); fn call(&self, req: Req) -> Self::Future { MapFuture::new(self.service.call(req), self.f.clone()) } } pin_project! { pub struct MapFuture<A, F, Req, Res> where A: Service<Req>, F: FnMut(A::Response) -> Res, { f: F, #[pin] fut: A::Future, } } impl<A, F, Req, Res> MapFuture<A, F, Req, Res> where A: Service<Req>, F: FnMut(A::Response) -> Res, { fn new(fut: A::Future, f: F) -> Self { MapFuture { f, fut } } } impl<A, F, Req, Res> Future for MapFuture<A, F, Req, Res> where A: Service<Req>, F: FnMut(A::Response) -> Res, { type Output = Result<Res, A::Error>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let this = self.project(); match this.fut.poll(cx) { Poll::Ready(Ok(resp)) => Poll::Ready(Ok((this.f)(resp))), Poll::Ready(Err(err)) => Poll::Ready(Err(err)), Poll::Pending => Poll::Pending, } } } /// `MapNewService` new service combinator pub struct MapServiceFactory<A, F, Req, Res> { a: A, f: F, r: PhantomData<fn(Req) -> Res>, } impl<A, F, Req, Res> MapServiceFactory<A, F, Req, Res> { /// Create new `Map` new service instance pub(crate) fn new(a: A, f: F) -> Self where A: ServiceFactory<Req>, F: FnMut(A::Response) -> Res, { Self { a, f, r: PhantomData, } } } impl<A, F, Req, Res> Clone for MapServiceFactory<A, F, Req, Res> where A: Clone, F: Clone, { fn clone(&self) -> Self { Self { a: self.a.clone(), f: self.f.clone(), r: PhantomData, } } } impl<A, F, Req, Res> ServiceFactory<Req> for MapServiceFactory<A, F, Req, Res> where A: ServiceFactory<Req>, F: FnMut(A::Response) -> Res + Clone, { type Response = Res; type Error = A::Error; type Config = A::Config; type Service = Map<A::Service, F, Req, Res>; type InitError = A::InitError; type Future = MapServiceFuture<A, F, Req, Res>; fn new_service(&self, cfg: A::Config) -> Self::Future { MapServiceFuture::new(self.a.new_service(cfg), self.f.clone()) } } pin_project! { pub struct MapServiceFuture<A, F, Req, Res> where A: ServiceFactory<Req>, F: FnMut(A::Response) -> Res, { #[pin] fut: A::Future, f: Option<F>, } } impl<A, F, Req, Res> MapServiceFuture<A, F, Req, Res> where A: ServiceFactory<Req>, F: FnMut(A::Response) -> Res, { fn new(fut: A::Future, f: F) -> Self { MapServiceFuture { f: Some(f), fut } } } impl<A, F, Req, Res> Future for MapServiceFuture<A, F, Req, Res> where A: ServiceFactory<Req>, F: FnMut(A::Response) -> Res, { type Output = Result<Map<A::Service, F, Req, Res>, A::InitError>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let this = self.project(); if let Poll::Ready(svc) = this.fut.poll(cx)? { Poll::Ready(Ok(Map::new(svc, this.f.take().unwrap()))) } else { Poll::Pending } } } #[cfg(test)] mod tests { use futures_util::future::lazy; use super::*; use crate::{ok, IntoServiceFactory, Ready, ServiceExt, ServiceFactoryExt}; struct Srv; impl Service<()> for Srv { type Response = (); type Error = (); type Future = Ready<Result<(), ()>>; crate::always_ready!(); fn call(&self, _: ()) -> Self::Future { ok(()) } } #[actix_rt::test] async fn test_poll_ready() { let srv = Srv.map(|_| "ok"); let res = lazy(|cx| srv.poll_ready(cx)).await; assert_eq!(res, Poll::Ready(Ok(()))); } #[actix_rt::test] async fn test_call() { let srv = Srv.map(|_| "ok"); let res = srv.call(()).await; assert!(res.is_ok()); assert_eq!(res.unwrap(), "ok"); } #[actix_rt::test] async fn test_new_service() { let new_srv = (|| ok::<_, ()>(Srv)).into_factory().map(|_| "ok"); let srv = new_srv.new_service(&()).await.unwrap(); let res = srv.call(()).await; assert!(res.is_ok()); assert_eq!(res.unwrap(), ("ok")); } }
use core::marker::PhantomData; use super::{IntoServiceFactory, ServiceFactory}; /// Adapt external config argument to a config for provided service factory /// /// Note that this function consumes the receiving service factory and returns /// a wrapped version of it. pub fn map_config<I, SF, Req, F, Cfg>(factory: I, f: F) -> MapConfig<SF, Req, F, Cfg> where I: IntoServiceFactory<SF, Req>, SF: ServiceFactory<Req>, F: Fn(Cfg) -> SF::Config, { MapConfig::new(factory.into_factory(), f) } /// Replace config with unit. pub fn unit_config<I, SF, Cfg, Req>(factory: I) -> UnitConfig<SF, Cfg, Req> where I: IntoServiceFactory<SF, Req>, SF: ServiceFactory<Req, Config = ()>, { UnitConfig::new(factory.into_factory()) } /// `map_config()` adapter service factory pub struct MapConfig<SF, Req, F, Cfg> { factory: SF, cfg_mapper: F, e: PhantomData<fn(Cfg, Req)>, } impl<SF, Req, F, Cfg> MapConfig<SF, Req, F, Cfg> { /// Create new `MapConfig` combinator pub(crate) fn new(factory: SF, cfg_mapper: F) -> Self where SF: ServiceFactory<Req>, F: Fn(Cfg) -> SF::Config, { Self { factory, cfg_mapper, e: PhantomData, } } } impl<SF, Req, F, Cfg> Clone for MapConfig<SF, Req, F, Cfg> where SF: Clone, F: Clone, { fn clone(&self) -> Self { Self { factory: self.factory.clone(), cfg_mapper: self.cfg_mapper.clone(), e: PhantomData, } } } impl<SF, Req, F, Cfg> ServiceFactory<Req> for MapConfig<SF, Req, F, Cfg> where SF: ServiceFactory<Req>, F: Fn(Cfg) -> SF::Config, { type Response = SF::Response; type Error = SF::Error; type Config = Cfg; type Service = SF::Service; type InitError = SF::InitError; type Future = SF::Future; fn new_service(&self, cfg: Self::Config) -> Self::Future { let mapped_cfg = (self.cfg_mapper)(cfg); self.factory.new_service(mapped_cfg) } } /// `unit_config()` config combinator pub struct UnitConfig<SF, Cfg, Req> { factory: SF, _phantom: PhantomData<fn(Cfg, Req)>, } impl<SF, Cfg, Req> UnitConfig<SF, Cfg, Req> where SF: ServiceFactory<Req, Config = ()>, { /// Create new `UnitConfig` combinator pub(crate) fn new(factory: SF) -> Self { Self { factory, _phantom: PhantomData, } } } impl<SF, Cfg, Req> Clone for UnitConfig<SF, Cfg, Req> where SF: Clone, { fn clone(&self) -> Self { Self { factory: self.factory.clone(), _phantom: PhantomData, } } } impl<SF, Cfg, Req> ServiceFactory<Req> for UnitConfig<SF, Cfg, Req> where SF: ServiceFactory<Req, Config = ()>, { type Response = SF::Response; type Error = SF::Error; type Config = Cfg; type Service = SF::Service; type InitError = SF::InitError; type Future = SF::Future; fn new_service(&self, _: Cfg) -> Self::Future { self.factory.new_service(()) } }
use core::{ future::Future, marker::PhantomData, pin::Pin, task::{Context, Poll}, }; use pin_project_lite::pin_project; use super::{Service, ServiceFactory}; /// Service for the `map_err` combinator, changing the type of a service's error. /// /// This is created by the `ServiceExt::map_err` method. pub struct MapErr<S, Req, F, E> { service: S, mapper: F, _t: PhantomData<fn(Req) -> E>, } impl<S, Req, F, E> MapErr<S, Req, F, E> { /// Create new `MapErr` combinator pub(crate) fn new(service: S, mapper: F) -> Self where S: Service<Req>, F: Fn(S::Error) -> E, { Self { service, mapper, _t: PhantomData, } } } impl<S, Req, F, E> Clone for MapErr<S, Req, F, E> where S: Clone, F: Clone, { fn clone(&self) -> Self { MapErr { service: self.service.clone(), mapper: self.mapper.clone(), _t: PhantomData, } } } impl<A, Req, F, E> Service<Req> for MapErr<A, Req, F, E> where A: Service<Req>, F: Fn(A::Error) -> E + Clone, { type Response = A::Response; type Error = E; type Future = MapErrFuture<A, Req, F, E>; fn poll_ready(&self, ctx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { self.service.poll_ready(ctx).map_err(&self.mapper) } fn call(&self, req: Req) -> Self::Future { MapErrFuture::new(self.service.call(req), self.mapper.clone()) } } pin_project! { pub struct MapErrFuture<A, Req, F, E> where A: Service<Req>, F: Fn(A::Error) -> E, { f: F, #[pin] fut: A::Future, } } impl<A, Req, F, E> MapErrFuture<A, Req, F, E> where A: Service<Req>, F: Fn(A::Error) -> E, { fn new(fut: A::Future, f: F) -> Self { MapErrFuture { f, fut } } } impl<A, Req, F, E> Future for MapErrFuture<A, Req, F, E> where A: Service<Req>, F: Fn(A::Error) -> E, { type Output = Result<A::Response, E>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let this = self.project(); this.fut.poll(cx).map_err(this.f) } } /// Factory for the `map_err` combinator, changing the type of a new /// service's error. /// /// This is created by the `NewServiceExt::map_err` method. pub struct MapErrServiceFactory<SF, Req, F, E> where SF: ServiceFactory<Req>, F: Fn(SF::Error) -> E + Clone, { a: SF, f: F, e: PhantomData<fn(Req) -> E>, } impl<SF, Req, F, E> MapErrServiceFactory<SF, Req, F, E> where SF: ServiceFactory<Req>, F: Fn(SF::Error) -> E + Clone, { /// Create new `MapErr` new service instance pub(crate) fn new(a: SF, f: F) -> Self { Self { a, f, e: PhantomData, } } } impl<SF, Req, F, E> Clone for MapErrServiceFactory<SF, Req, F, E> where SF: ServiceFactory<Req> + Clone, F: Fn(SF::Error) -> E + Clone, { fn clone(&self) -> Self { Self { a: self.a.clone(), f: self.f.clone(), e: PhantomData, } } } impl<SF, Req, F, E> ServiceFactory<Req> for MapErrServiceFactory<SF, Req, F, E> where SF: ServiceFactory<Req>, F: Fn(SF::Error) -> E + Clone, { type Response = SF::Response; type Error = E; type Config = SF::Config; type Service = MapErr<SF::Service, Req, F, E>; type InitError = SF::InitError; type Future = MapErrServiceFuture<SF, Req, F, E>; fn new_service(&self, cfg: SF::Config) -> Self::Future { MapErrServiceFuture::new(self.a.new_service(cfg), self.f.clone()) } } pin_project! { pub struct MapErrServiceFuture<SF, Req, F, E> where SF: ServiceFactory<Req>, F: Fn(SF::Error) -> E, { #[pin] fut: SF::Future, mapper: F, } } impl<SF, Req, F, E> MapErrServiceFuture<SF, Req, F, E> where SF: ServiceFactory<Req>, F: Fn(SF::Error) -> E, { fn new(fut: SF::Future, mapper: F) -> Self { MapErrServiceFuture { fut, mapper } } } impl<SF, Req, F, E> Future for MapErrServiceFuture<SF, Req, F, E> where SF: ServiceFactory<Req>, F: Fn(SF::Error) -> E + Clone, { type Output = Result<MapErr<SF::Service, Req, F, E>, SF::InitError>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let this = self.project(); if let Poll::Ready(svc) = this.fut.poll(cx)? { Poll::Ready(Ok(MapErr::new(svc, this.mapper.clone()))) } else { Poll::Pending } } } #[cfg(test)] mod tests { use futures_util::future::lazy; use super::*; use crate::{err, ok, IntoServiceFactory, Ready, ServiceExt, ServiceFactoryExt}; struct Srv; impl Service<()> for Srv { type Response = (); type Error = (); type Future = Ready<Result<(), ()>>; fn poll_ready(&self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { Poll::Ready(Err(())) } fn call(&self, _: ()) -> Self::Future { err(()) } } #[actix_rt::test] async fn test_poll_ready() { let srv = Srv.map_err(|_| "error"); let res = lazy(|cx| srv.poll_ready(cx)).await; assert_eq!(res, Poll::Ready(Err("error"))); } #[actix_rt::test] async fn test_call() { let srv = Srv.map_err(|_| "error"); let res = srv.call(()).await; assert!(res.is_err()); assert_eq!(res.err().unwrap(), "error"); } #[actix_rt::test] async fn test_new_service() { let new_srv = (|| ok::<_, ()>(Srv)).into_factory().map_err(|_| "error"); let srv = new_srv.new_service(&()).await.unwrap(); let res = srv.call(()).await; assert!(res.is_err()); assert_eq!(res.err().unwrap(), "error"); } }
use core::{ future::Future, marker::PhantomData, pin::Pin, task::{Context, Poll}, }; use pin_project_lite::pin_project; use super::ServiceFactory; /// `MapInitErr` service combinator pub struct MapInitErr<A, F, Req, Err> { a: A, f: F, e: PhantomData<fn(Req) -> Err>, } impl<A, F, Req, Err> MapInitErr<A, F, Req, Err> where A: ServiceFactory<Req>, F: Fn(A::InitError) -> Err, { /// Create new `MapInitErr` combinator pub(crate) fn new(a: A, f: F) -> Self { Self { a, f, e: PhantomData, } } } impl<A, F, Req, E> Clone for MapInitErr<A, F, Req, E> where A: Clone, F: Clone, { fn clone(&self) -> Self { Self { a: self.a.clone(), f: self.f.clone(), e: PhantomData, } } } impl<A, F, Req, E> ServiceFactory<Req> for MapInitErr<A, F, Req, E> where A: ServiceFactory<Req>, F: Fn(A::InitError) -> E + Clone, { type Response = A::Response; type Error = A::Error; type Config = A::Config; type Service = A::Service; type InitError = E; type Future = MapInitErrFuture<A, F, Req, E>; fn new_service(&self, cfg: A::Config) -> Self::Future { MapInitErrFuture::new(self.a.new_service(cfg), self.f.clone()) } } pin_project! { pub struct MapInitErrFuture<A, F, Req, E> where A: ServiceFactory<Req>, F: Fn(A::InitError) -> E, { f: F, #[pin] fut: A::Future, } } impl<A, F, Req, E> MapInitErrFuture<A, F, Req, E> where A: ServiceFactory<Req>, F: Fn(A::InitError) -> E, { fn new(fut: A::Future, f: F) -> Self { MapInitErrFuture { f, fut } } } impl<A, F, Req, E> Future for MapInitErrFuture<A, F, Req, E> where A: ServiceFactory<Req>, F: Fn(A::InitError) -> E, { type Output = Result<A::Service, E>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let this = self.project(); this.fut.poll(cx).map_err(this.f) } }
// TODO: see if pipeline is necessary #![allow(dead_code)] use core::{ marker::PhantomData, task::{Context, Poll}, }; use crate::{ and_then::{AndThenService, AndThenServiceFactory}, map::{Map, MapServiceFactory}, map_err::{MapErr, MapErrServiceFactory}, map_init_err::MapInitErr, then::{ThenService, ThenServiceFactory}, IntoService, IntoServiceFactory, Service, ServiceFactory, }; /// Construct new pipeline with one service in pipeline chain. pub(crate) fn pipeline<I, S, Req>(service: I) -> Pipeline<S, Req> where I: IntoService<S, Req>, S: Service<Req>, { Pipeline { service: service.into_service(), _phantom: PhantomData, } } /// Construct new pipeline factory with one service factory. pub(crate) fn pipeline_factory<I, SF, Req>(factory: I) -> PipelineFactory<SF, Req> where I: IntoServiceFactory<SF, Req>, SF: ServiceFactory<Req>, { PipelineFactory { factory: factory.into_factory(), _phantom: PhantomData, } } /// Pipeline service - pipeline allows to compose multiple service into one service. pub(crate) struct Pipeline<S, Req> { service: S, _phantom: PhantomData<fn(Req)>, } impl<S, Req> Pipeline<S, Req> where S: Service<Req>, { /// Call another service after call to this one has resolved successfully. /// /// This function can be used to chain two services together and ensure that /// the second service isn't called until call to the first service have /// finished. Result of the call to the first service is used as an /// input parameter for the second service's call. /// /// Note that this function consumes the receiving service and returns a /// wrapped version of it. pub fn and_then<I, S1>( self, service: I, ) -> Pipeline<impl Service<Req, Response = S1::Response, Error = S::Error> + Clone, Req> where Self: Sized, I: IntoService<S1, S::Response>, S1: Service<S::Response, Error = S::Error>, { Pipeline { service: AndThenService::new(self.service, service.into_service()), _phantom: PhantomData, } } /// Chain on a computation for when a call to the service finished, /// passing the result of the call to the next service `U`. /// /// Note that this function consumes the receiving pipeline and returns a /// wrapped version of it. pub fn then<F, S1>( self, service: F, ) -> Pipeline<impl Service<Req, Response = S1::Response, Error = S::Error> + Clone, Req> where Self: Sized, F: IntoService<S1, Result<S::Response, S::Error>>, S1: Service<Result<S::Response, S::Error>, Error = S::Error>, { Pipeline { service: ThenService::new(self.service, service.into_service()), _phantom: PhantomData, } } /// Map this service's output to a different type, returning a new service /// of the resulting type. /// /// This function is similar to the `Option::map` or `Iterator::map` where /// it will change the type of the underlying service. /// /// Note that this function consumes the receiving service and returns a /// wrapped version of it, similar to the existing `map` methods in the /// standard library. pub fn map<F, R>(self, f: F) -> Pipeline<Map<S, F, Req, R>, Req> where Self: Sized, F: FnMut(S::Response) -> R, { Pipeline { service: Map::new(self.service, f), _phantom: PhantomData, } } /// Map this service's error to a different error, returning a new service. /// /// This function is similar to the `Result::map_err` where it will change /// the error type of the underlying service. This is useful for example to /// ensure that services have the same error type. /// /// Note that this function consumes the receiving service and returns a /// wrapped version of it. pub fn map_err<F, E>(self, f: F) -> Pipeline<MapErr<S, Req, F, E>, Req> where Self: Sized, F: Fn(S::Error) -> E, { Pipeline { service: MapErr::new(self.service, f), _phantom: PhantomData, } } } impl<T, Req> Clone for Pipeline<T, Req> where T: Clone, { fn clone(&self) -> Self { Pipeline { service: self.service.clone(), _phantom: PhantomData, } } } impl<S: Service<Req>, Req> Service<Req> for Pipeline<S, Req> { type Response = S::Response; type Error = S::Error; type Future = S::Future; #[inline] fn poll_ready(&self, ctx: &mut Context<'_>) -> Poll<Result<(), S::Error>> { self.service.poll_ready(ctx) } #[inline] fn call(&self, req: Req) -> Self::Future { self.service.call(req) } } /// Pipeline factory pub(crate) struct PipelineFactory<SF, Req> { factory: SF, _phantom: PhantomData<fn(Req)>, } impl<SF, Req> PipelineFactory<SF, Req> where SF: ServiceFactory<Req>, { /// Call another service after call to this one has resolved successfully. pub fn and_then<I, SF1>( self, factory: I, ) -> PipelineFactory< impl ServiceFactory< Req, Response = SF1::Response, Error = SF::Error, Config = SF::Config, InitError = SF::InitError, Service = impl Service<Req, Response = SF1::Response, Error = SF::Error> + Clone, > + Clone, Req, > where Self: Sized, SF::Config: Clone, I: IntoServiceFactory<SF1, SF::Response>, SF1: ServiceFactory< SF::Response, Config = SF::Config, Error = SF::Error, InitError = SF::InitError, >, { PipelineFactory { factory: AndThenServiceFactory::new(self.factory, factory.into_factory()), _phantom: PhantomData, } } /// Create `NewService` to chain on a computation for when a call to the /// service finished, passing the result of the call to the next /// service `U`. /// /// Note that this function consumes the receiving pipeline and returns a /// wrapped version of it. pub fn then<I, SF1>( self, factory: I, ) -> PipelineFactory< impl ServiceFactory< Req, Response = SF1::Response, Error = SF::Error, Config = SF::Config, InitError = SF::InitError, Service = impl Service<Req, Response = SF1::Response, Error = SF::Error> + Clone, > + Clone, Req, > where Self: Sized, SF::Config: Clone, I: IntoServiceFactory<SF1, Result<SF::Response, SF::Error>>, SF1: ServiceFactory< Result<SF::Response, SF::Error>, Config = SF::Config, Error = SF::Error, InitError = SF::InitError, >, { PipelineFactory { factory: ThenServiceFactory::new(self.factory, factory.into_factory()), _phantom: PhantomData, } } /// Map this service's output to a different type, returning a new service /// of the resulting type. pub fn map<F, R>(self, f: F) -> PipelineFactory<MapServiceFactory<SF, F, Req, R>, Req> where Self: Sized, F: FnMut(SF::Response) -> R + Clone, { PipelineFactory { factory: MapServiceFactory::new(self.factory, f), _phantom: PhantomData, } } /// Map this service's error to a different error, returning a new service. pub fn map_err<F, E>(self, f: F) -> PipelineFactory<MapErrServiceFactory<SF, Req, F, E>, Req> where Self: Sized, F: Fn(SF::Error) -> E + Clone, { PipelineFactory { factory: MapErrServiceFactory::new(self.factory, f), _phantom: PhantomData, } } /// Map this factory's init error to a different error, returning a new service. pub fn map_init_err<F, E>(self, f: F) -> PipelineFactory<MapInitErr<SF, F, Req, E>, Req> where Self: Sized, F: Fn(SF::InitError) -> E + Clone, { PipelineFactory { factory: MapInitErr::new(self.factory, f), _phantom: PhantomData, } } } impl<T, Req> Clone for PipelineFactory<T, Req> where T: Clone, { fn clone(&self) -> Self { PipelineFactory { factory: self.factory.clone(), _phantom: PhantomData, } } } impl<SF, Req> ServiceFactory<Req> for PipelineFactory<SF, Req> where SF: ServiceFactory<Req>, { type Config = SF::Config; type Response = SF::Response; type Error = SF::Error; type Service = SF::Service; type InitError = SF::InitError; type Future = SF::Future; #[inline] fn new_service(&self, cfg: SF::Config) -> Self::Future { self.factory.new_service(cfg) } }
//! When MSRV is 1.48, replace with `core::future::Ready` and `core::future::ready()`. use core::{ future::Future, pin::Pin, task::{Context, Poll}, }; /// Future for the [`ready`](ready()) function. #[derive(Debug, Clone)] #[must_use = "futures do nothing unless you `.await` or poll them"] pub struct Ready<T> { val: Option<T>, } impl<T> Ready<T> { /// Unwraps the value from this immediately ready future. #[inline] pub fn into_inner(mut self) -> T { self.val.take().unwrap() } } impl<T> Unpin for Ready<T> {} impl<T> Future for Ready<T> { type Output = T; #[inline] fn poll(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<T> { let val = self.val.take().expect("Ready can not be polled twice."); Poll::Ready(val) } } /// Creates a future that is immediately ready with a value. #[allow(dead_code)] pub(crate) fn ready<T>(val: T) -> Ready<T> { Ready { val: Some(val) } } /// Create a future that is immediately ready with a success value. #[allow(dead_code)] pub(crate) fn ok<T, E>(val: T) -> Ready<Result<T, E>> { Ready { val: Some(Ok(val)) } } /// Create a future that is immediately ready with an error value. #[allow(dead_code)] pub(crate) fn err<T, E>(err: E) -> Ready<Result<T, E>> { Ready { val: Some(Err(err)), } }
use alloc::rc::Rc; use core::{ future::Future, marker::PhantomData, pin::Pin, task::{Context, Poll}, }; use futures_core::ready; use pin_project_lite::pin_project; use super::{Service, ServiceFactory}; /// Service for the `then` combinator, chaining a computation onto the end of /// another service. /// /// This is created by the `Pipeline::then` method. pub(crate) struct ThenService<A, B, Req>(Rc<(A, B)>, PhantomData<Req>); impl<A, B, Req> ThenService<A, B, Req> { /// Create new `.then()` combinator pub(crate) fn new(a: A, b: B) -> ThenService<A, B, Req> where A: Service<Req>, B: Service<Result<A::Response, A::Error>, Error = A::Error>, { Self(Rc::new((a, b)), PhantomData) } } impl<A, B, Req> Clone for ThenService<A, B, Req> { fn clone(&self) -> Self { ThenService(self.0.clone(), PhantomData) } } impl<A, B, Req> Service<Req> for ThenService<A, B, Req> where A: Service<Req>, B: Service<Result<A::Response, A::Error>, Error = A::Error>, { type Response = B::Response; type Error = B::Error; type Future = ThenServiceResponse<A, B, Req>; fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { let (a, b) = &*self.0; let not_ready = !a.poll_ready(cx)?.is_ready(); if !b.poll_ready(cx)?.is_ready() || not_ready { Poll::Pending } else { Poll::Ready(Ok(())) } } fn call(&self, req: Req) -> Self::Future { ThenServiceResponse { state: State::A { fut: self.0 .0.call(req), b: Some(self.0.clone()), }, } } } pin_project! { pub(crate) struct ThenServiceResponse<A, B, Req> where A: Service<Req>, B: Service<Result<A::Response, A::Error>>, { #[pin] state: State<A, B, Req>, } } pin_project! { #[project = StateProj] enum State<A, B, Req> where A: Service<Req>, B: Service<Result<A::Response, A::Error>>, { A { #[pin] fut: A::Future, b: Option<Rc<(A, B)>> }, B { #[pin] fut: B::Future }, } } impl<A, B, Req> Future for ThenServiceResponse<A, B, Req> where A: Service<Req>, B: Service<Result<A::Response, A::Error>>, { type Output = Result<B::Response, B::Error>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let mut this = self.as_mut().project(); match this.state.as_mut().project() { StateProj::A { fut, b } => { let res = ready!(fut.poll(cx)); let b = b.take().unwrap(); let fut = b.1.call(res); this.state.set(State::B { fut }); self.poll(cx) } StateProj::B { fut } => fut.poll(cx), } } } /// `.then()` service factory combinator pub(crate) struct ThenServiceFactory<A, B, Req>(Rc<(A, B)>, PhantomData<Req>); impl<A, B, Req> ThenServiceFactory<A, B, Req> where A: ServiceFactory<Req>, A::Config: Clone, B: ServiceFactory< Result<A::Response, A::Error>, Config = A::Config, Error = A::Error, InitError = A::InitError, >, { /// Create new `AndThen` combinator pub(crate) fn new(a: A, b: B) -> Self { Self(Rc::new((a, b)), PhantomData) } } impl<A, B, Req> ServiceFactory<Req> for ThenServiceFactory<A, B, Req> where A: ServiceFactory<Req>, A::Config: Clone, B: ServiceFactory< Result<A::Response, A::Error>, Config = A::Config, Error = A::Error, InitError = A::InitError, >, { type Response = B::Response; type Error = A::Error; type Config = A::Config; type Service = ThenService<A::Service, B::Service, Req>; type InitError = A::InitError; type Future = ThenServiceFactoryResponse<A, B, Req>; fn new_service(&self, cfg: A::Config) -> Self::Future { let srv = &*self.0; ThenServiceFactoryResponse::new(srv.0.new_service(cfg.clone()), srv.1.new_service(cfg)) } } impl<A, B, Req> Clone for ThenServiceFactory<A, B, Req> { fn clone(&self) -> Self { Self(self.0.clone(), PhantomData) } } pin_project! { pub(crate) struct ThenServiceFactoryResponse<A, B, Req> where A: ServiceFactory<Req>, B: ServiceFactory< Result<A::Response, A::Error>, Config = A::Config, Error = A::Error, InitError = A::InitError, >, { #[pin] fut_b: B::Future, #[pin] fut_a: A::Future, a: Option<A::Service>, b: Option<B::Service>, } } impl<A, B, Req> ThenServiceFactoryResponse<A, B, Req> where A: ServiceFactory<Req>, B: ServiceFactory< Result<A::Response, A::Error>, Config = A::Config, Error = A::Error, InitError = A::InitError, >, { fn new(fut_a: A::Future, fut_b: B::Future) -> Self { Self { fut_a, fut_b, a: None, b: None, } } } impl<A, B, Req> Future for ThenServiceFactoryResponse<A, B, Req> where A: ServiceFactory<Req>, B: ServiceFactory< Result<A::Response, A::Error>, Config = A::Config, Error = A::Error, InitError = A::InitError, >, { type Output = Result<ThenService<A::Service, B::Service, Req>, A::InitError>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let this = self.project(); if this.a.is_none() { if let Poll::Ready(service) = this.fut_a.poll(cx)? { *this.a = Some(service); } } if this.b.is_none() { if let Poll::Ready(service) = this.fut_b.poll(cx)? { *this.b = Some(service); } } if this.a.is_some() && this.b.is_some() { Poll::Ready(Ok(ThenService::new( this.a.take().unwrap(), this.b.take().unwrap(), ))) } else { Poll::Pending } } } #[cfg(test)] mod tests { use alloc::rc::Rc; use core::{ cell::Cell, task::{Context, Poll}, }; use futures_util::future::lazy; use crate::{ err, ok, pipeline::{pipeline, pipeline_factory}, ready, Ready, Service, ServiceFactory, }; #[derive(Clone)] struct Srv1(Rc<Cell<usize>>); impl Service<Result<&'static str, &'static str>> for Srv1 { type Response = &'static str; type Error = (); type Future = Ready<Result<Self::Response, Self::Error>>; fn poll_ready(&self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { self.0.set(self.0.get() + 1); Poll::Ready(Ok(())) } fn call(&self, req: Result<&'static str, &'static str>) -> Self::Future { match req { Ok(msg) => ok(msg), Err(_) => err(()), } } } struct Srv2(Rc<Cell<usize>>); impl Service<Result<&'static str, ()>> for Srv2 { type Response = (&'static str, &'static str); type Error = (); type Future = Ready<Result<Self::Response, ()>>; fn poll_ready(&self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { self.0.set(self.0.get() + 1); Poll::Ready(Err(())) } fn call(&self, req: Result<&'static str, ()>) -> Self::Future { match req { Ok(msg) => ok((msg, "ok")), Err(()) => ok(("srv2", "err")), } } } #[actix_rt::test] async fn test_poll_ready() { let cnt = Rc::new(Cell::new(0)); let srv = pipeline(Srv1(cnt.clone())).then(Srv2(cnt.clone())); let res = lazy(|cx| srv.poll_ready(cx)).await; assert_eq!(res, Poll::Ready(Err(()))); assert_eq!(cnt.get(), 2); } #[actix_rt::test] async fn test_call() { let cnt = Rc::new(Cell::new(0)); let srv = pipeline(Srv1(cnt.clone())).then(Srv2(cnt)); let res = srv.call(Ok("srv1")).await; assert!(res.is_ok()); assert_eq!(res.unwrap(), ("srv1", "ok")); let res = srv.call(Err("srv")).await; assert!(res.is_ok()); assert_eq!(res.unwrap(), ("srv2", "err")); } #[actix_rt::test] async fn test_factory() { let cnt = Rc::new(Cell::new(0)); let cnt2 = cnt.clone(); let blank = move || ready(Ok::<_, ()>(Srv1(cnt2.clone()))); let factory = pipeline_factory(blank).then(move || ready(Ok(Srv2(cnt.clone())))); let srv = factory.new_service(&()).await.unwrap(); let res = srv.call(Ok("srv1")).await; assert!(res.is_ok()); assert_eq!(res.unwrap(), ("srv1", "ok")); let res = srv.call(Err("srv")).await; assert!(res.is_ok()); assert_eq!(res.unwrap(), ("srv2", "err")); } }
use alloc::{rc::Rc, sync::Arc}; use core::{ future::Future, marker::PhantomData, pin::Pin, task::{Context, Poll}, }; use futures_core::ready; use pin_project_lite::pin_project; use crate::{IntoServiceFactory, Service, ServiceFactory}; /// Apply a [`Transform`] to a [`Service`]. pub fn apply<T, S, I, Req>(t: T, factory: I) -> ApplyTransform<T, S, Req> where I: IntoServiceFactory<S, Req>, S: ServiceFactory<Req>, T: Transform<S::Service, Req, InitError = S::InitError>, { ApplyTransform::new(t, factory.into_factory()) } /// Defines the interface of a service factory that wraps inner service during construction. /// /// Transformers wrap an inner service and runs during inbound and/or outbound processing in the /// service lifecycle. It may modify request and/or response. /// /// For example, a timeout service wrapper: /// /// ```ignore /// pub struct Timeout<S> { /// service: S, /// timeout: Duration, /// } /// /// impl<S: Service<Req>, Req> Service<Req> for Timeout<S> { /// type Response = S::Response; /// type Error = TimeoutError<S::Error>; /// type Future = TimeoutServiceResponse<S>; /// /// actix_service::forward_ready!(service); /// /// fn call(&self, req: Req) -> Self::Future { /// TimeoutServiceResponse { /// fut: self.service.call(req), /// sleep: Sleep::new(clock::now() + self.timeout), /// } /// } /// } /// ``` /// /// This wrapper service is decoupled from the underlying service implementation and could be /// applied to any service. /// /// The `Transform` trait defines the interface of a service wrapper. `Transform` is often /// implemented for middleware, defining how to construct a middleware Service. A Service that is /// constructed by the factory takes the Service that follows it during execution as a parameter, /// assuming ownership of the next Service. /// /// A transform for the `Timeout` middleware could look like this: /// /// ```ignore /// pub struct TimeoutTransform { /// timeout: Duration, /// } /// /// impl<S: Service<Req>, Req> Transform<S, Req> for TimeoutTransform { /// type Response = S::Response; /// type Error = TimeoutError<S::Error>; /// type InitError = S::Error; /// type Transform = Timeout<S>; /// type Future = Ready<Result<Self::Transform, Self::InitError>>; /// /// fn new_transform(&self, service: S) -> Self::Future { /// ready(Ok(Timeout { /// service, /// timeout: self.timeout, /// })) /// } /// } /// ``` pub trait Transform<S, Req> { /// Responses produced by the service. type Response; /// Errors produced by the service. type Error; /// The `TransformService` value created by this factory type Transform: Service<Req, Response = Self::Response, Error = Self::Error>; /// Errors produced while building a transform service. type InitError; /// The future response value. type Future: Future<Output = Result<Self::Transform, Self::InitError>>; /// Creates and returns a new Transform component, asynchronously fn new_transform(&self, service: S) -> Self::Future; } impl<T, S, Req> Transform<S, Req> for Rc<T> where T: Transform<S, Req>, { type Response = T::Response; type Error = T::Error; type Transform = T::Transform; type InitError = T::InitError; type Future = T::Future; fn new_transform(&self, service: S) -> T::Future { self.as_ref().new_transform(service) } } impl<T, S, Req> Transform<S, Req> for Arc<T> where T: Transform<S, Req>, { type Response = T::Response; type Error = T::Error; type Transform = T::Transform; type InitError = T::InitError; type Future = T::Future; fn new_transform(&self, service: S) -> T::Future { self.as_ref().new_transform(service) } } /// Apply a [`Transform`] to a [`Service`]. pub struct ApplyTransform<T, S, Req>(Rc<(T, S)>, PhantomData<Req>); impl<T, S, Req> ApplyTransform<T, S, Req> where S: ServiceFactory<Req>, T: Transform<S::Service, Req, InitError = S::InitError>, { /// Create new `ApplyTransform` new service instance fn new(t: T, service: S) -> Self { Self(Rc::new((t, service)), PhantomData) } } impl<T, S, Req> Clone for ApplyTransform<T, S, Req> { fn clone(&self) -> Self { ApplyTransform(self.0.clone(), PhantomData) } } impl<T, S, Req> ServiceFactory<Req> for ApplyTransform<T, S, Req> where S: ServiceFactory<Req>, T: Transform<S::Service, Req, InitError = S::InitError>, { type Response = T::Response; type Error = T::Error; type Config = S::Config; type Service = T::Transform; type InitError = T::InitError; type Future = ApplyTransformFuture<T, S, Req>; fn new_service(&self, cfg: S::Config) -> Self::Future { ApplyTransformFuture { store: self.0.clone(), state: ApplyTransformFutureState::A { fut: self.0.as_ref().1.new_service(cfg), }, } } } pin_project! { pub struct ApplyTransformFuture<T, S, Req> where S: ServiceFactory<Req>, T: Transform<S::Service, Req, InitError = S::InitError>, { store: Rc<(T, S)>, #[pin] state: ApplyTransformFutureState<T, S, Req>, } } pin_project! { #[project = ApplyTransformFutureStateProj] pub enum ApplyTransformFutureState<T, S, Req> where S: ServiceFactory<Req>, T: Transform<S::Service, Req, InitError = S::InitError>, { A { #[pin] fut: S::Future }, B { #[pin] fut: T::Future }, } } impl<T, S, Req> Future for ApplyTransformFuture<T, S, Req> where S: ServiceFactory<Req>, T: Transform<S::Service, Req, InitError = S::InitError>, { type Output = Result<T::Transform, T::InitError>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let mut this = self.as_mut().project(); match this.state.as_mut().project() { ApplyTransformFutureStateProj::A { fut } => { let srv = ready!(fut.poll(cx))?; let fut = this.store.0.new_transform(srv); this.state.set(ApplyTransformFutureState::B { fut }); self.poll(cx) } ApplyTransformFutureStateProj::B { fut } => fut.poll(cx), } } } #[cfg(test)] mod tests { use core::time::Duration; use actix_utils::future::{ready, Ready}; use super::*; // pseudo-doctest for Transform trait #[allow(unused)] pub struct TimeoutTransform { timeout: Duration, } // pseudo-doctest for Transform trait impl<S: Service<Req>, Req> Transform<S, Req> for TimeoutTransform { type Response = S::Response; type Error = S::Error; type InitError = S::Error; type Transform = Timeout<S>; type Future = Ready<Result<Self::Transform, Self::InitError>>; fn new_transform(&self, service: S) -> Self::Future { ready(Ok(Timeout { service, _timeout: self.timeout, })) } } // pseudo-doctest for Transform trait #[allow(unused)] pub struct Timeout<S> { service: S, _timeout: Duration, } // pseudo-doctest for Transform trait impl<S: Service<Req>, Req> Service<Req> for Timeout<S> { type Response = S::Response; type Error = S::Error; type Future = S::Future; crate::forward_ready!(service); fn call(&self, req: Req) -> Self::Future { self.service.call(req) } } }
use core::{ future::Future, marker::PhantomData, pin::Pin, task::{Context, Poll}, }; use pin_project_lite::pin_project; use super::Transform; /// Transform for the [`TransformExt::map_init_err`] combinator, changing the type of a new /// [`Transform`]'s initialization error. pub struct TransformMapInitErr<T, S, Req, F, E> { transform: T, mapper: F, _phantom: PhantomData<fn(Req) -> (S, E)>, } impl<T, S, F, E, Req> TransformMapInitErr<T, S, Req, F, E> { pub(crate) fn new(t: T, f: F) -> Self where T: Transform<S, Req>, F: Fn(T::InitError) -> E, { Self { transform: t, mapper: f, _phantom: PhantomData, } } } impl<T, S, Req, F, E> Clone for TransformMapInitErr<T, S, Req, F, E> where T: Clone, F: Clone, { fn clone(&self) -> Self { Self { transform: self.transform.clone(), mapper: self.mapper.clone(), _phantom: PhantomData, } } } impl<T, S, F, E, Req> Transform<S, Req> for TransformMapInitErr<T, S, Req, F, E> where T: Transform<S, Req>, F: Fn(T::InitError) -> E + Clone, { type Response = T::Response; type Error = T::Error; type Transform = T::Transform; type InitError = E; type Future = TransformMapInitErrFuture<T, S, F, E, Req>; fn new_transform(&self, service: S) -> Self::Future { TransformMapInitErrFuture { fut: self.transform.new_transform(service), f: self.mapper.clone(), } } } pin_project! { pub struct TransformMapInitErrFuture<T, S, F, E, Req> where T: Transform<S, Req>, F: Fn(T::InitError) -> E, { #[pin] fut: T::Future, f: F, } } impl<T, S, F, E, Req> Future for TransformMapInitErrFuture<T, S, F, E, Req> where T: Transform<S, Req>, F: Fn(T::InitError) -> E + Clone, { type Output = Result<T::Transform, E>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let this = self.project(); if let Poll::Ready(res) = this.fut.poll(cx) { Poll::Ready(res.map_err(this.f)) } else { Poll::Pending } } }
//! Task-notifying counter. use core::{cell::Cell, fmt, task}; use std::rc::Rc; use local_waker::LocalWaker; /// Simple counter with ability to notify task on reaching specific number /// /// Counter could be cloned, total n-count is shared across all clones. #[derive(Debug, Clone)] pub struct Counter(Rc<CounterInner>); impl Counter { /// Create `Counter` instance with max value. pub fn new(capacity: usize) -> Self { Counter(Rc::new(CounterInner { capacity, count: Cell::new(0), task: LocalWaker::new(), })) } /// Create new counter guard, incrementing the counter. #[inline] pub fn get(&self) -> CounterGuard { CounterGuard::new(self.0.clone()) } /// Returns true if counter is below capacity. Otherwise, register to wake task when it is. #[inline] pub fn available(&self, cx: &mut task::Context<'_>) -> bool { self.0.available(cx) } /// Get total number of acquired guards. #[inline] pub fn total(&self) -> usize { self.0.count.get() } } struct CounterInner { count: Cell<usize>, capacity: usize, task: LocalWaker, } impl CounterInner { fn inc(&self) { self.count.set(self.count.get() + 1); } fn dec(&self) { let num = self.count.get(); self.count.set(num - 1); if num == self.capacity { self.task.wake(); } } fn available(&self, cx: &mut task::Context<'_>) -> bool { if self.count.get() < self.capacity { true } else { self.task.register(cx.waker()); false } } } impl fmt::Debug for CounterInner { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Counter") .field("count", &self.count.get()) .field("capacity", &self.capacity) .field("task", &self.task) .finish() } } /// An RAII structure that keeps the underlying counter incremented until this guard is dropped. #[derive(Debug)] pub struct CounterGuard(Rc<CounterInner>); impl CounterGuard { fn new(inner: Rc<CounterInner>) -> Self { inner.inc(); CounterGuard(inner) } } impl Unpin for CounterGuard {} impl Drop for CounterGuard { fn drop(&mut self) { self.0.dec(); } }
//! A symmetric either future. use core::{ future::Future, pin::Pin, task::{Context, Poll}, }; use pin_project_lite::pin_project; pin_project! { /// Combines two different futures that have the same output type. /// /// Construct variants with [`Either::left`] and [`Either::right`]. /// /// # Examples /// ``` /// use actix_utils::future::{ready, Ready, Either}; /// /// # async fn run() { /// let res = Either::<_, Ready<usize>>::left(ready(42)); /// assert_eq!(res.await, 42); /// /// let res = Either::<Ready<usize>, _>::right(ready(43)); /// assert_eq!(res.await, 43); /// # } /// ``` #[project = EitherProj] #[derive(Debug, Clone)] pub enum Either<L, R> { /// A value of type `L`. #[allow(missing_docs)] Left { #[pin] value: L }, /// A value of type `R`. #[allow(missing_docs)] Right { #[pin] value: R }, } } impl<L, R> Either<L, R> { /// Creates new `Either` using left variant. #[inline] pub fn left(value: L) -> Either<L, R> { Either::Left { value } } /// Creates new `Either` using right variant. #[inline] pub fn right(value: R) -> Either<L, R> { Either::Right { value } } } impl<T> Either<T, T> { /// Unwraps into inner value when left and right have a common type. #[inline] pub fn into_inner(self) -> T { match self { Either::Left { value } => value, Either::Right { value } => value, } } } impl<L, R> Future for Either<L, R> where L: Future, R: Future<Output = L::Output>, { type Output = L::Output; #[inline] fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { match self.project() { EitherProj::Left { value } => value.poll(cx), EitherProj::Right { value } => value.poll(cx), } } } #[cfg(test)] mod tests { use super::*; use crate::future::{ready, Ready}; #[actix_rt::test] async fn test_either() { let res = Either::<_, Ready<usize>>::left(ready(42)); assert_eq!(res.await, 42); let res = Either::<Ready<usize>, _>::right(ready(43)); assert_eq!(res.await, 43); } }
//! Helpers for constructing futures. mod either; mod poll_fn; mod ready; pub use self::either::Either; pub use self::poll_fn::{poll_fn, PollFn}; pub use self::ready::{err, ok, ready, Ready};
//! Simple "poll function" future and factory. use core::{ fmt, future::Future, pin::Pin, task::{Context, Poll}, }; /// Creates a future driven by the provided function that receives a task context. /// /// # Examples /// ``` /// # use std::task::Poll; /// # use actix_utils::future::poll_fn; /// # async fn test_poll_fn() { /// let res = poll_fn(|_| Poll::Ready(42)).await; /// assert_eq!(res, 42); /// /// let mut i = 5; /// let res = poll_fn(|cx| { /// i -= 1; /// /// if i > 0 { /// cx.waker().wake_by_ref(); /// Poll::Pending /// } else { /// Poll::Ready(42) /// } /// }) /// .await; /// assert_eq!(res, 42); /// # } /// # actix_rt::Runtime::new().unwrap().block_on(test_poll_fn()); /// ``` #[inline] pub fn poll_fn<F, T>(f: F) -> PollFn<F> where F: FnMut(&mut Context<'_>) -> Poll<T>, { PollFn { f } } /// Future for the [`poll_fn`] function. pub struct PollFn<F> { f: F, } impl<F> fmt::Debug for PollFn<F> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("PollFn").finish() } } impl<F, T> Future for PollFn<F> where F: FnMut(&mut Context<'_>) -> Poll<T>, { type Output = T; #[inline] fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { // SAFETY: we are not moving out of the pinned field // see https://github.com/rust-lang/rust/pull/102737 (unsafe { &mut self.get_unchecked_mut().f })(cx) } } #[cfg(test)] mod tests { use std::marker::PhantomPinned; use super::*; static_assertions::assert_impl_all!(PollFn<()>: Unpin); static_assertions::assert_not_impl_all!(PollFn<PhantomPinned>: Unpin); #[actix_rt::test] async fn test_poll_fn() { let res = poll_fn(|_| Poll::Ready(42)).await; assert_eq!(res, 42); let mut i = 5; let res = poll_fn(|cx| { i -= 1; if i > 0 { cx.waker().wake_by_ref(); Poll::Pending } else { Poll::Ready(42) } }) .await; assert_eq!(res, 42); } // following soundness tests taken from https://github.com/tokio-rs/tokio/pull/5087 #[allow(dead_code)] fn require_send<T: Send>(_t: &T) {} #[allow(dead_code)] fn require_sync<T: Sync>(_t: &T) {} trait AmbiguousIfUnpin<A> { fn some_item(&self) {} } impl<T: ?Sized> AmbiguousIfUnpin<()> for T {} impl<T: ?Sized + Unpin> AmbiguousIfUnpin<[u8; 0]> for T {} const _: fn() = || { let pinned = std::marker::PhantomPinned; let f = poll_fn(move |_| { // Use `pinned` to take ownership of it. let _ = &pinned; std::task::Poll::Pending::<()> }); require_send(&f); require_sync(&f); AmbiguousIfUnpin::some_item(&f); }; }
//! When `core::future::Ready` has a `into_inner()` method, this can be deprecated. use core::{ future::Future, pin::Pin, task::{Context, Poll}, }; /// Future for the [`ready`] function. /// /// Panic will occur if polled more than once. /// /// # Examples /// ``` /// use actix_utils::future::ready; /// /// // async /// # async fn run() { /// let a = ready(1); /// assert_eq!(a.await, 1); /// # } /// /// // sync /// let a = ready(1); /// assert_eq!(a.into_inner(), 1); /// ``` #[derive(Debug, Clone)] #[must_use = "futures do nothing unless you `.await` or poll them"] pub struct Ready<T> { val: Option<T>, } impl<T> Ready<T> { /// Unwraps the value from this immediately ready future. #[inline] pub fn into_inner(mut self) -> T { self.val.take().unwrap() } } impl<T> Unpin for Ready<T> {} impl<T> Future for Ready<T> { type Output = T; #[inline] fn poll(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<T> { let val = self.val.take().expect("Ready polled after completion"); Poll::Ready(val) } } /// Creates a future that is immediately ready with a value. /// /// # Examples /// ```no_run /// use actix_utils::future::ready; /// /// # async fn run() { /// let a = ready(1); /// assert_eq!(a.await, 1); /// # } /// /// // sync /// let a = ready(1); /// assert_eq!(a.into_inner(), 1); /// ``` #[inline] pub fn ready<T>(val: T) -> Ready<T> { Ready { val: Some(val) } } /// Creates a future that is immediately ready with a success value. /// /// # Examples /// ```no_run /// use actix_utils::future::ok; /// /// # async fn run() { /// let a = ok::<_, ()>(1); /// assert_eq!(a.await, Ok(1)); /// # } /// ``` #[inline] pub fn ok<T, E>(val: T) -> Ready<Result<T, E>> { Ready { val: Some(Ok(val)) } } /// Creates a future that is immediately ready with an error value. /// /// # Examples /// ```no_run /// use actix_utils::future::err; /// /// # async fn run() { /// let a = err::<(), _>(1); /// assert_eq!(a.await, Err(1)); /// # } /// ``` #[inline] pub fn err<T, E>(err: E) -> Ready<Result<T, E>> { Ready { val: Some(Err(err)), } } #[cfg(test)] mod tests { use std::rc::Rc; use futures_util::task::noop_waker; use static_assertions::{assert_impl_all, assert_not_impl_any}; use super::*; assert_impl_all!(Ready<()>: Send, Sync, Unpin, Clone); assert_impl_all!(Ready<Rc<()>>: Unpin, Clone); assert_not_impl_any!(Ready<Rc<()>>: Send, Sync); #[test] #[should_panic] fn multiple_poll_panics() { let waker = noop_waker(); let mut cx = Context::from_waker(&waker); let mut ready = ready(1); assert_eq!(Pin::new(&mut ready).poll(&mut cx), Poll::Ready(1)); // panic! let _ = Pin::new(&mut ready).poll(&mut cx); } }
//! Various utilities used in the Actix ecosystem. #![deny(rust_2018_idioms, nonstandard_style)] #![warn(future_incompatible, missing_docs)] #![doc(html_logo_url = "https://actix.rs/img/logo.png")] #![doc(html_favicon_url = "https://actix.rs/favicon.ico")] pub mod counter; pub mod future;
//! Routing and runtime macros for Actix Web. //! //! # Actix Web Re-exports //! Actix Web re-exports a version of this crate in it's entirety so you usually don't have to //! specify a dependency on this crate explicitly. Sometimes, however, updates are made to this //! crate before the actix-web dependency is updated. Therefore, code examples here will show //! explicit imports. Check the latest [actix-web attributes docs] to see which macros //! are re-exported. //! //! # Runtime Setup //! Used for setting up the actix async runtime. See [macro@main] macro docs. //! //! ``` //! #[actix_web_codegen::main] // or `#[actix_web::main]` in Actix Web apps //! async fn main() { //! async { println!("Hello world"); }.await //! } //! ``` //! //! # Single Method Handler //! There is a macro to set up a handler for each of the most common HTTP methods that also define //! additional guards and route-specific middleware. //! //! See docs for: [GET], [POST], [PATCH], [PUT], [DELETE], [HEAD], [CONNECT], [OPTIONS], [TRACE] //! //! ``` //! # use actix_web::HttpResponse; //! # use actix_web_codegen::get; //! #[get("/test")] //! async fn get_handler() -> HttpResponse { //! HttpResponse::Ok().finish() //! } //! ``` //! //! # Multiple Method Handlers //! Similar to the single method handler macro but takes one or more arguments for the HTTP methods //! it should respond to. See [macro@route] macro docs. //! //! ``` //! # use actix_web::HttpResponse; //! # use actix_web_codegen::route; //! #[route("/test", method = "GET", method = "HEAD")] //! async fn get_and_head_handler() -> HttpResponse { //! HttpResponse::Ok().finish() //! } //! ``` //! //! # Multiple Path Handlers //! Acts as a wrapper for multiple single method handler macros. It takes no arguments and //! delegates those to the macros for the individual methods. See [macro@routes] macro docs. //! //! ``` //! # use actix_web::HttpResponse; //! # use actix_web_codegen::routes; //! #[routes] //! #[get("/test")] //! #[get("/test2")] //! #[delete("/test")] //! async fn example() -> HttpResponse { //! HttpResponse::Ok().finish() //! } //! ``` //! //! [actix-web attributes docs]: https://docs.rs/actix-web/latest/actix_web/#attributes //! [GET]: macro@get //! [POST]: macro@post //! [PUT]: macro@put //! [HEAD]: macro@head //! [CONNECT]: macro@macro@connect //! [OPTIONS]: macro@options //! [TRACE]: macro@trace //! [PATCH]: macro@patch //! [DELETE]: macro@delete #![recursion_limit = "512"] #![deny(rust_2018_idioms, nonstandard_style)] #![warn(future_incompatible)] #![doc(html_logo_url = "https://actix.rs/img/logo.png")] #![doc(html_favicon_url = "https://actix.rs/favicon.ico")] #![cfg_attr(docsrs, feature(doc_auto_cfg))] use proc_macro::TokenStream; use quote::quote; mod route; mod scope; /// Creates resource handler, allowing multiple HTTP method guards. /// /// # Syntax /// ```plain /// #[route("path", method="HTTP_METHOD"[, attributes])] /// ``` /// /// # Attributes /// - `"path"`: Raw literal string with path for which to register handler. /// - `name = "resource_name"`: Specifies resource name for the handler. If not set, the function /// name of handler is used. /// - `method = "HTTP_METHOD"`: Registers HTTP method to provide guard for. Upper-case string, /// "GET", "POST" for example. /// - `guard = "function_name"`: Registers function as guard using `actix_web::guard::fn_guard`. /// - `wrap = "Middleware"`: Registers a resource middleware. /// /// # Notes /// Function name can be specified as any expression that is going to be accessible to the generate /// code, e.g `my_guard` or `my_module::my_guard`. /// /// # Examples /// ``` /// # use actix_web::HttpResponse; /// # use actix_web_codegen::route; /// #[route("/test", method = "GET", method = "HEAD", method = "CUSTOM")] /// async fn example() -> HttpResponse { /// HttpResponse::Ok().finish() /// } /// ``` #[proc_macro_attribute] pub fn route(args: TokenStream, input: TokenStream) -> TokenStream { route::with_method(None, args, input) } /// Creates resource handler, allowing multiple HTTP methods and paths. /// /// # Syntax /// ```plain /// #[routes] /// #[<method>("path", ...)] /// #[<method>("path", ...)] /// ... /// ``` /// /// # Attributes /// The `routes` macro itself has no parameters, but allows specifying the attribute macros for /// the multiple paths and/or methods, e.g. [`GET`](macro@get) and [`POST`](macro@post). /// /// These helper attributes take the same parameters as the [single method handlers](crate#single-method-handler). /// /// # Examples /// ``` /// # use actix_web::HttpResponse; /// # use actix_web_codegen::routes; /// #[routes] /// #[get("/test")] /// #[get("/test2")] /// #[delete("/test")] /// async fn example() -> HttpResponse { /// HttpResponse::Ok().finish() /// } /// ``` #[proc_macro_attribute] pub fn routes(_: TokenStream, input: TokenStream) -> TokenStream { route::with_methods(input) } macro_rules! method_macro { ($variant:ident, $method:ident) => { #[doc = concat!("Creates route handler with `actix_web::guard::", stringify!($variant), "`.")] /// /// # Syntax /// ```plain #[doc = concat!("#[", stringify!($method), r#"("path"[, attributes])]"#)] /// ``` /// /// # Attributes /// - `"path"`: Raw literal string with path for which to register handler. /// - `name = "resource_name"`: Specifies resource name for the handler. If not set, the /// function name of handler is used. /// - `guard = "function_name"`: Registers function as guard using `actix_web::guard::fn_guard`. /// - `wrap = "Middleware"`: Registers a resource middleware. /// /// # Notes /// Function name can be specified as any expression that is going to be accessible to the /// generate code, e.g `my_guard` or `my_module::my_guard`. /// /// # Examples /// ``` /// # use actix_web::HttpResponse; #[doc = concat!("# use actix_web_codegen::", stringify!($method), ";")] #[doc = concat!("#[", stringify!($method), r#"("/")]"#)] /// async fn example() -> HttpResponse { /// HttpResponse::Ok().finish() /// } /// ``` #[proc_macro_attribute] pub fn $method(args: TokenStream, input: TokenStream) -> TokenStream { route::with_method(Some(route::MethodType::$variant), args, input) } }; } method_macro!(Get, get); method_macro!(Post, post); method_macro!(Put, put); method_macro!(Delete, delete); method_macro!(Head, head); method_macro!(Connect, connect); method_macro!(Options, options); method_macro!(Trace, trace); method_macro!(Patch, patch); /// Prepends a path prefix to all handlers using routing macros inside the attached module. /// /// # Syntax /// /// ``` /// # use actix_web_codegen::scope; /// #[scope("/prefix")] /// mod api { /// // ... /// } /// ``` /// /// # Arguments /// /// - `"/prefix"` - Raw literal string to be prefixed onto contained handlers' paths. /// /// # Example /// /// ``` /// # use actix_web_codegen::{scope, get}; /// # use actix_web::Responder; /// #[scope("/api")] /// mod api { /// # use super::*; /// #[get("/hello")] /// pub async fn hello() -> impl Responder { /// // this has path /api/hello /// "Hello, world!" /// } /// } /// # fn main() {} /// ``` #[proc_macro_attribute] pub fn scope(args: TokenStream, input: TokenStream) -> TokenStream { scope::with_scope(args, input) } /// Marks async main function as the Actix Web system entry-point. /// /// Note that Actix Web also works under `#[tokio::main]` since version 4.0. However, this macro is /// still necessary for actor support (since actors use a `System`). Read more in the /// [`actix_web::rt`](https://docs.rs/actix-web/4/actix_web/rt) module docs. /// /// # Examples /// ``` /// #[actix_web::main] /// async fn main() { /// async { println!("Hello world"); }.await /// } /// ``` #[proc_macro_attribute] pub fn main(_: TokenStream, item: TokenStream) -> TokenStream { let mut output: TokenStream = (quote! { #[::actix_web::rt::main(system = "::actix_web::rt::System")] }) .into(); output.extend(item); output } /// Marks async test functions to use the Actix Web system entry-point. /// /// # Examples /// ``` /// #[actix_web::test] /// async fn test() { /// assert_eq!(async { "Hello world" }.await, "Hello world"); /// } /// ``` #[proc_macro_attribute] pub fn test(_: TokenStream, item: TokenStream) -> TokenStream { let mut output: TokenStream = (quote! { #[::actix_web::rt::test(system = "::actix_web::rt::System")] }) .into(); output.extend(item); output } /// Converts the error to a token stream and appends it to the original input. /// /// Returning the original input in addition to the error is good for IDEs which can gracefully /// recover and show more precise errors within the macro body. /// /// See <https://github.com/rust-analyzer/rust-analyzer/issues/10468> for more info. fn input_and_compile_error(mut item: TokenStream, err: syn::Error) -> TokenStream { let compile_err = TokenStream::from(err.to_compile_error()); item.extend(compile_err); item }
use std::collections::HashSet; use actix_router::ResourceDef; use proc_macro::TokenStream; use proc_macro2::{Span, TokenStream as TokenStream2}; use quote::{quote, ToTokens, TokenStreamExt}; use syn::{punctuated::Punctuated, Ident, LitStr, Path, Token}; use crate::input_and_compile_error; #[derive(Debug)] pub struct RouteArgs { pub(crate) path: syn::LitStr, pub(crate) options: Punctuated<syn::MetaNameValue, Token![,]>, } impl syn::parse::Parse for RouteArgs { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { // path to match: "/foo" let path = input.parse::<syn::LitStr>().map_err(|mut err| { err.combine(syn::Error::new( err.span(), r#"invalid service definition, expected #[<method>("<path>")]"#, )); err })?; // verify that path pattern is valid let _ = ResourceDef::new(path.value()); // if there's no comma, assume that no options are provided if !input.peek(Token![,]) { return Ok(Self { path, options: Punctuated::new(), }); } // advance past comma separator input.parse::<Token![,]>()?; // if next char is a literal, assume that it is a string and show multi-path error if input.cursor().literal().is_some() { return Err(syn::Error::new( Span::call_site(), r#"Multiple paths specified! There should be only one."#, )); } // zero or more options: name = "foo" let options = input.parse_terminated(syn::MetaNameValue::parse, Token![,])?; Ok(Self { path, options }) } } macro_rules! standard_method_type { ( $($variant:ident, $upper:ident, $lower:ident,)+ ) => { #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum MethodType { $( $variant, )+ } impl MethodType { fn as_str(&self) -> &'static str { match self { $(Self::$variant => stringify!($variant),)+ } } fn parse(method: &str) -> Result<Self, String> { match method { $(stringify!($upper) => Ok(Self::$variant),)+ _ => Err(format!("HTTP method must be uppercase: `{}`", method)), } } pub(crate) fn from_path(method: &Path) -> Result<Self, ()> { match () { $(_ if method.is_ident(stringify!($lower)) => Ok(Self::$variant),)+ _ => Err(()), } } } }; } standard_method_type! { Get, GET, get, Post, POST, post, Put, PUT, put, Delete, DELETE, delete, Head, HEAD, head, Connect, CONNECT, connect, Options, OPTIONS, options, Trace, TRACE, trace, Patch, PATCH, patch, } impl TryFrom<&syn::LitStr> for MethodType { type Error = syn::Error; fn try_from(value: &syn::LitStr) -> Result<Self, Self::Error> { Self::parse(value.value().as_str()) .map_err(|message| syn::Error::new_spanned(value, message)) } } impl ToTokens for MethodType { fn to_tokens(&self, stream: &mut TokenStream2) { let ident = Ident::new(self.as_str(), Span::call_site()); stream.append(ident); } } #[derive(Debug, Clone, PartialEq, Eq, Hash)] enum MethodTypeExt { Standard(MethodType), Custom(LitStr), } impl MethodTypeExt { /// Returns a single method guard token stream. fn to_tokens_single_guard(&self) -> TokenStream2 { match self { MethodTypeExt::Standard(method) => { quote! { .guard(::actix_web::guard::#method()) } } MethodTypeExt::Custom(lit) => { quote! { .guard(::actix_web::guard::Method( ::actix_web::http::Method::from_bytes(#lit.as_bytes()).unwrap() )) } } } } /// Returns a multi-method guard chain token stream. fn to_tokens_multi_guard(&self, or_chain: Vec<impl ToTokens>) -> TokenStream2 { debug_assert!( !or_chain.is_empty(), "empty or_chain passed to multi-guard constructor" ); match self { MethodTypeExt::Standard(method) => { quote! { .guard( ::actix_web::guard::Any(::actix_web::guard::#method()) #(#or_chain)* ) } } MethodTypeExt::Custom(lit) => { quote! { .guard( ::actix_web::guard::Any( ::actix_web::guard::Method( ::actix_web::http::Method::from_bytes(#lit.as_bytes()).unwrap() ) ) #(#or_chain)* ) } } } } /// Returns a token stream containing the `.or` chain to be passed in to /// [`MethodTypeExt::to_tokens_multi_guard()`]. fn to_tokens_multi_guard_or_chain(&self) -> TokenStream2 { match self { MethodTypeExt::Standard(method_type) => { quote! { .or(::actix_web::guard::#method_type()) } } MethodTypeExt::Custom(lit) => { quote! { .or( ::actix_web::guard::Method( ::actix_web::http::Method::from_bytes(#lit.as_bytes()).unwrap() ) ) } } } } } impl ToTokens for MethodTypeExt { fn to_tokens(&self, stream: &mut TokenStream2) { match self { MethodTypeExt::Custom(lit_str) => { let ident = Ident::new(lit_str.value().as_str(), Span::call_site()); stream.append(ident); } MethodTypeExt::Standard(method) => method.to_tokens(stream), } } } impl TryFrom<&syn::LitStr> for MethodTypeExt { type Error = syn::Error; fn try_from(value: &syn::LitStr) -> Result<Self, Self::Error> { match MethodType::try_from(value) { Ok(method) => Ok(MethodTypeExt::Standard(method)), Err(_) if value.value().chars().all(|c| c.is_ascii_uppercase()) => { Ok(MethodTypeExt::Custom(value.clone())) } Err(err) => Err(err), } } } struct Args { path: syn::LitStr, resource_name: Option<syn::LitStr>, guards: Vec<Path>, wrappers: Vec<syn::Expr>, methods: HashSet<MethodTypeExt>, } impl Args { fn new(args: RouteArgs, method: Option<MethodType>) -> syn::Result<Self> { let mut resource_name = None; let mut guards = Vec::new(); let mut wrappers = Vec::new(); let mut methods = HashSet::new(); let is_route_macro = method.is_none(); if let Some(method) = method { methods.insert(MethodTypeExt::Standard(method)); } for nv in args.options { if nv.path.is_ident("name") { if let syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Str(lit), .. }) = nv.value { resource_name = Some(lit); } else { return Err(syn::Error::new_spanned( nv.value, "Attribute name expects literal string", )); } } else if nv.path.is_ident("guard") { if let syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Str(lit), .. }) = nv.value { guards.push(lit.parse::<Path>()?); } else { return Err(syn::Error::new_spanned( nv.value, "Attribute guard expects literal string", )); } } else if nv.path.is_ident("wrap") { if let syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Str(lit), .. }) = nv.value { wrappers.push(lit.parse()?); } else { return Err(syn::Error::new_spanned( nv.value, "Attribute wrap expects type", )); } } else if nv.path.is_ident("method") { if !is_route_macro { return Err(syn::Error::new_spanned( &nv, "HTTP method forbidden here; to handle multiple methods, use `route` instead", )); } else if let syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Str(lit), .. }) = nv.value.clone() { if !methods.insert(MethodTypeExt::try_from(&lit)?) { return Err(syn::Error::new_spanned( nv.value, format!("HTTP method defined more than once: `{}`", lit.value()), )); } } else { return Err(syn::Error::new_spanned( nv.value, "Attribute method expects literal string", )); } } else { return Err(syn::Error::new_spanned( nv.path, "Unknown attribute key is specified; allowed: guard, method and wrap", )); } } Ok(Args { path: args.path, resource_name, guards, wrappers, methods, }) } } pub struct Route { /// Name of the handler function being annotated. name: syn::Ident, /// Args passed to routing macro. /// /// When using `#[routes]`, this will contain args for each specific routing macro. args: Vec<Args>, /// AST of the handler function being annotated. ast: syn::ItemFn, /// The doc comment attributes to copy to generated struct, if any. doc_attributes: Vec<syn::Attribute>, } impl Route { pub fn new(args: RouteArgs, ast: syn::ItemFn, method: Option<MethodType>) -> syn::Result<Self> { let name = ast.sig.ident.clone(); // Try and pull out the doc comments so that we can reapply them to the generated struct. // Note that multi line doc comments are converted to multiple doc attributes. let doc_attributes = ast .attrs .iter() .filter(|attr| attr.path().is_ident("doc")) .cloned() .collect(); let args = Args::new(args, method)?; if args.methods.is_empty() { return Err(syn::Error::new( Span::call_site(), "The #[route(..)] macro requires at least one `method` attribute", )); } if matches!(ast.sig.output, syn::ReturnType::Default) { return Err(syn::Error::new_spanned( ast, "Function has no return type. Cannot be used as handler", )); } Ok(Self { name, args: vec![args], ast, doc_attributes, }) } fn multiple(args: Vec<Args>, ast: syn::ItemFn) -> syn::Result<Self> { let name = ast.sig.ident.clone(); // Try and pull out the doc comments so that we can reapply them to the generated struct. // Note that multi line doc comments are converted to multiple doc attributes. let doc_attributes = ast .attrs .iter() .filter(|attr| attr.path().is_ident("doc")) .cloned() .collect(); if matches!(ast.sig.output, syn::ReturnType::Default) { return Err(syn::Error::new_spanned( ast, "Function has no return type. Cannot be used as handler", )); } Ok(Self { name, args, ast, doc_attributes, }) } } impl ToTokens for Route { fn to_tokens(&self, output: &mut TokenStream2) { let Self { name, ast, args, doc_attributes, } = self; #[allow(unused_variables)] // used when force-pub feature is disabled let vis = &ast.vis; // TODO(breaking): remove this force-pub forwards-compatibility feature #[cfg(feature = "compat-routing-macros-force-pub")] let vis = syn::Visibility::Public(<Token![pub]>::default()); let registrations: TokenStream2 = args .iter() .map(|args| { let Args { path, resource_name, guards, wrappers, methods, } = args; let resource_name = resource_name .as_ref() .map_or_else(|| name.to_string(), LitStr::value); let method_guards = { debug_assert!(!methods.is_empty(), "Args::methods should not be empty"); let mut others = methods.iter(); let first = others.next().unwrap(); if methods.len() > 1 { let other_method_guards = others .map(|method_ext| method_ext.to_tokens_multi_guard_or_chain()) .collect(); first.to_tokens_multi_guard(other_method_guards) } else { first.to_tokens_single_guard() } }; quote! { let __resource = ::actix_web::Resource::new(#path) .name(#resource_name) #method_guards #(.guard(::actix_web::guard::fn_guard(#guards)))* #(.wrap(#wrappers))* .to(#name); ::actix_web::dev::HttpServiceFactory::register(__resource, __config); } }) .collect(); let stream = quote! { #(#doc_attributes)* #[allow(non_camel_case_types, missing_docs)] #vis struct #name; impl ::actix_web::dev::HttpServiceFactory for #name { fn register(self, __config: &mut actix_web::dev::AppService) { #ast #registrations } } }; output.extend(stream); } } pub(crate) fn with_method( method: Option<MethodType>, args: TokenStream, input: TokenStream, ) -> TokenStream { let args = match syn::parse(args) { Ok(args) => args, // on parse error, make IDEs happy; see fn docs Err(err) => return input_and_compile_error(input, err), }; let ast = match syn::parse::<syn::ItemFn>(input.clone()) { Ok(ast) => ast, // on parse error, make IDEs happy; see fn docs Err(err) => return input_and_compile_error(input, err), }; match Route::new(args, ast, method) { Ok(route) => route.into_token_stream().into(), // on macro related error, make IDEs happy; see fn docs Err(err) => input_and_compile_error(input, err), } } pub(crate) fn with_methods(input: TokenStream) -> TokenStream { let mut ast = match syn::parse::<syn::ItemFn>(input.clone()) { Ok(ast) => ast, // on parse error, make IDEs happy; see fn docs Err(err) => return input_and_compile_error(input, err), }; let (methods, others) = ast .attrs .into_iter() .map(|attr| match MethodType::from_path(attr.path()) { Ok(method) => Ok((method, attr)), Err(_) => Err(attr), }) .partition::<Vec<_>, _>(Result::is_ok); ast.attrs = others.into_iter().map(Result::unwrap_err).collect(); let methods = match methods .into_iter() .map(Result::unwrap) .map(|(method, attr)| { attr.parse_args() .and_then(|args| Args::new(args, Some(method))) }) .collect::<Result<Vec<_>, _>>() { Ok(methods) if methods.is_empty() => { return input_and_compile_error( input, syn::Error::new( Span::call_site(), "The #[routes] macro requires at least one `#[<method>(..)]` attribute.", ), ) } Ok(methods) => methods, Err(err) => return input_and_compile_error(input, err), }; match Route::multiple(methods, ast) { Ok(route) => route.into_token_stream().into(), // on macro related error, make IDEs happy; see fn docs Err(err) => input_and_compile_error(input, err), } }
use proc_macro::TokenStream; use proc_macro2::{Span, TokenStream as TokenStream2}; use quote::{quote, ToTokens as _}; use crate::{ input_and_compile_error, route::{MethodType, RouteArgs}, }; pub fn with_scope(args: TokenStream, input: TokenStream) -> TokenStream { match with_scope_inner(args, input.clone()) { Ok(stream) => stream, Err(err) => input_and_compile_error(input, err), } } fn with_scope_inner(args: TokenStream, input: TokenStream) -> syn::Result<TokenStream> { if args.is_empty() { return Err(syn::Error::new( Span::call_site(), "missing arguments for scope macro, expected: #[scope(\"/prefix\")]", )); } let scope_prefix = syn::parse::<syn::LitStr>(args.clone()).map_err(|err| { syn::Error::new( err.span(), "argument to scope macro is not a string literal, expected: #[scope(\"/prefix\")]", ) })?; let scope_prefix_value = scope_prefix.value(); if scope_prefix_value.ends_with('/') { // trailing slashes cause non-obvious problems // it's better to point them out to developers rather than return Err(syn::Error::new( scope_prefix.span(), "scopes should not have trailing slashes; see https://docs.rs/actix-web/4/actix_web/struct.Scope.html#avoid-trailing-slashes", )); } let mut module = syn::parse::<syn::ItemMod>(input).map_err(|err| { syn::Error::new(err.span(), "#[scope] macro must be attached to a module") })?; // modify any routing macros (method or route[s]) attached to // functions by prefixing them with this scope macro's argument if let Some((_, items)) = &mut module.content { for item in items { if let syn::Item::Fn(fun) = item { fun.attrs = fun .attrs .iter() .map(|attr| modify_attribute_with_scope(attr, &scope_prefix_value)) .collect(); } } } Ok(module.to_token_stream().into()) } /// Checks if the attribute is a method type and has a route path, then modifies it. fn modify_attribute_with_scope(attr: &syn::Attribute, scope_path: &str) -> syn::Attribute { match (attr.parse_args::<RouteArgs>(), attr.clone().meta) { (Ok(route_args), syn::Meta::List(meta_list)) if has_allowed_methods_in_scope(attr) => { let modified_path = format!("{}{}", scope_path, route_args.path.value()); let options_tokens: Vec<TokenStream2> = route_args .options .iter() .map(|option| { quote! { ,#option } }) .collect(); let combined_options_tokens: TokenStream2 = options_tokens .into_iter() .fold(TokenStream2::new(), |mut acc, ts| { acc.extend(std::iter::once(ts)); acc }); syn::Attribute { meta: syn::Meta::List(syn::MetaList { tokens: quote! { #modified_path #combined_options_tokens }, ..meta_list.clone() }), ..attr.clone() } } _ => attr.clone(), } } fn has_allowed_methods_in_scope(attr: &syn::Attribute) -> bool { MethodType::from_path(attr.path()).is_ok() || attr.path().is_ident("route") || attr.path().is_ident("ROUTE") }
use std::future::Future; use actix_utils::future::{ok, Ready}; use actix_web::{ dev::{Service, ServiceRequest, ServiceResponse, Transform}, http::{ self, header::{HeaderName, HeaderValue}, StatusCode, }, web, App, Error, HttpRequest, HttpResponse, Responder, }; use actix_web_codegen::{ connect, delete, get, head, options, patch, post, put, route, routes, trace, }; use futures_core::future::LocalBoxFuture; // Make sure that we can name function as 'config' #[get("/config")] async fn config() -> impl Responder { HttpResponse::Ok() } #[get("/test")] async fn test_handler() -> impl Responder { HttpResponse::Ok() } #[put("/test")] async fn put_test() -> impl Responder { HttpResponse::Created() } #[patch("/test")] async fn patch_test() -> impl Responder { HttpResponse::Ok() } #[post("/test")] async fn post_test() -> impl Responder { HttpResponse::NoContent() } #[head("/test")] async fn head_test() -> impl Responder { HttpResponse::Ok() } #[connect("/test")] async fn connect_test() -> impl Responder { HttpResponse::Ok() } #[options("/test")] async fn options_test() -> impl Responder { HttpResponse::Ok() } #[trace("/test")] async fn trace_test() -> impl Responder { HttpResponse::Ok() } #[get("/test")] fn auto_async() -> impl Future<Output = Result<HttpResponse, actix_web::Error>> { ok(HttpResponse::Ok().finish()) } #[get("/test")] fn auto_sync() -> impl Future<Output = Result<HttpResponse, actix_web::Error>> { ok(HttpResponse::Ok().finish()) } #[put("/test/{param}")] async fn put_param_test(_: web::Path<String>) -> impl Responder { HttpResponse::Created() } #[delete("/test/{param}")] async fn delete_param_test(_: web::Path<String>) -> impl Responder { HttpResponse::NoContent() } #[get("/test/{param}")] async fn get_param_test(_: web::Path<String>) -> impl Responder { HttpResponse::Ok() } #[route("/hello", method = "HELLO")] async fn custom_route_test() -> impl Responder { HttpResponse::Ok() } #[route( "/multi", method = "GET", method = "POST", method = "HEAD", method = "HELLO" )] async fn route_test() -> impl Responder { HttpResponse::Ok() } #[routes] #[get("/routes/test")] #[get("/routes/test2")] #[post("/routes/test")] async fn routes_test() -> impl Responder { HttpResponse::Ok() } // routes overlap with the more specific route first, therefore accessible #[routes] #[get("/routes/overlap/test")] #[get("/routes/overlap/{foo}")] async fn routes_overlapping_test(req: HttpRequest) -> impl Responder { // foo is only populated when route is not /routes/overlap/test match req.match_info().get("foo") { None => assert!(req.uri() == "/routes/overlap/test"), Some(_) => assert!(req.uri() != "/routes/overlap/test"), } HttpResponse::Ok() } // routes overlap with the more specific route last, therefore inaccessible #[routes] #[get("/routes/overlap2/{foo}")] #[get("/routes/overlap2/test")] async fn routes_overlapping_inaccessible_test(req: HttpRequest) -> impl Responder { // foo is always populated even when path is /routes/overlap2/test assert!(req.match_info().get("foo").is_some()); HttpResponse::Ok() } #[get("/custom_resource_name", name = "custom")] async fn custom_resource_name_test<'a>(req: HttpRequest) -> impl Responder { assert!(req.url_for_static("custom").is_ok()); assert!(req.url_for_static("custom_resource_name_test").is_err()); HttpResponse::Ok() } mod guard_module { use actix_web::{guard::GuardContext, http::header}; pub fn guard(ctx: &GuardContext) -> bool { ctx.header::<header::Accept>() .map(|h| h.preference() == "image/*") .unwrap_or(false) } } #[get("/test/guard", guard = "guard_module::guard")] async fn guard_test() -> impl Responder { HttpResponse::Ok() } pub struct ChangeStatusCode; impl<S, B> Transform<S, ServiceRequest> for ChangeStatusCode where S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>, S::Future: 'static, B: 'static, { type Response = ServiceResponse<B>; type Error = Error; type Transform = ChangeStatusCodeMiddleware<S>; type InitError = (); type Future = Ready<Result<Self::Transform, Self::InitError>>; fn new_transform(&self, service: S) -> Self::Future { ok(ChangeStatusCodeMiddleware { service }) } } pub struct ChangeStatusCodeMiddleware<S> { service: S, } impl<S, B> Service<ServiceRequest> for ChangeStatusCodeMiddleware<S> where S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>, S::Future: 'static, B: 'static, { type Response = ServiceResponse<B>; type Error = Error; type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>; actix_web::dev::forward_ready!(service); fn call(&self, req: ServiceRequest) -> Self::Future { let fut = self.service.call(req); Box::pin(async move { let mut res = fut.await?; let headers = res.headers_mut(); let header_name = HeaderName::from_lowercase(b"custom-header").unwrap(); let header_value = HeaderValue::from_str("hello").unwrap(); headers.insert(header_name, header_value); Ok(res) }) } } #[get("/test/wrap", wrap = "ChangeStatusCode")] async fn get_wrap(_: web::Path<String>) -> impl Responder { // panic!("actually never gets called because path failed to extract"); HttpResponse::Ok() } /// Using expression, not just path to type, in wrap attribute. /// /// Regression from <https://github.com/actix/actix-web/issues/3118>. #[route( "/catalog", method = "GET", method = "HEAD", wrap = "actix_web::middleware::Compress::default()" )] async fn get_catalog() -> impl Responder { HttpResponse::Ok().body("123123123") } #[actix_rt::test] async fn test_params() { let srv = actix_test::start(|| { App::new() .service(get_param_test) .service(put_param_test) .service(delete_param_test) }); let request = srv.request(http::Method::GET, srv.url("/test/it")); let response = request.send().await.unwrap(); assert_eq!(response.status(), http::StatusCode::OK); let request = srv.request(http::Method::PUT, srv.url("/test/it")); let response = request.send().await.unwrap(); assert_eq!(response.status(), http::StatusCode::CREATED); let request = srv.request(http::Method::DELETE, srv.url("/test/it")); let response = request.send().await.unwrap(); assert_eq!(response.status(), http::StatusCode::NO_CONTENT); } #[actix_rt::test] async fn test_body() { let srv = actix_test::start(|| { App::new() .service(post_test) .service(put_test) .service(head_test) .service(connect_test) .service(options_test) .service(trace_test) .service(patch_test) .service(test_handler) .service(route_test) .service(routes_overlapping_test) .service(routes_overlapping_inaccessible_test) .service(routes_test) .service(custom_resource_name_test) .service(guard_test) }); let request = srv.request(http::Method::GET, srv.url("/test")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::HEAD, srv.url("/test")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::CONNECT, srv.url("/test")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::OPTIONS, srv.url("/test")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::TRACE, srv.url("/test")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::PATCH, srv.url("/test")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::PUT, srv.url("/test")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); assert_eq!(response.status(), http::StatusCode::CREATED); let request = srv.request(http::Method::POST, srv.url("/test")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); assert_eq!(response.status(), http::StatusCode::NO_CONTENT); let request = srv.request(http::Method::GET, srv.url("/test")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::GET, srv.url("/multi")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::POST, srv.url("/multi")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::HEAD, srv.url("/multi")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::PATCH, srv.url("/multi")); let response = request.send().await.unwrap(); assert!(!response.status().is_success()); let request = srv.request(http::Method::GET, srv.url("/routes/test")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::GET, srv.url("/routes/test2")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::POST, srv.url("/routes/test")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::GET, srv.url("/routes/not-set")); let response = request.send().await.unwrap(); assert!(response.status().is_client_error()); let request = srv.request(http::Method::GET, srv.url("/routes/overlap/test")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::GET, srv.url("/routes/overlap/bar")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::GET, srv.url("/routes/overlap2/test")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::GET, srv.url("/routes/overlap2/bar")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::GET, srv.url("/custom_resource_name")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv .request(http::Method::GET, srv.url("/test/guard")) .insert_header(("Accept", "image/*")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); } #[actix_rt::test] async fn test_auto_async() { let srv = actix_test::start(|| App::new().service(auto_async)); let request = srv.request(http::Method::GET, srv.url("/test")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); } #[actix_web::test] async fn test_wrap() { let srv = actix_test::start(|| App::new().service(get_wrap)); let request = srv.request(http::Method::GET, srv.url("/test/wrap")); let mut response = request.send().await.unwrap(); assert_eq!(response.status(), StatusCode::NOT_FOUND); assert!(response.headers().contains_key("custom-header")); let body = response.body().await.unwrap(); let body = String::from_utf8(body.to_vec()).unwrap(); assert!(body.contains("wrong number of parameters")); }
use actix_web::{guard::GuardContext, http, http::header, web, App, HttpResponse, Responder}; use actix_web_codegen::{delete, get, post, route, routes, scope}; pub fn image_guard(ctx: &GuardContext) -> bool { ctx.header::<header::Accept>() .map(|h| h.preference() == "image/*") .unwrap_or(false) } #[scope("/test")] mod scope_module { // ensure that imports can be brought into the scope use super::*; #[get("/test/guard", guard = "image_guard")] pub async fn guard() -> impl Responder { HttpResponse::Ok() } #[get("/test")] pub async fn test() -> impl Responder { HttpResponse::Ok().finish() } #[get("/twice-test/{value}")] pub async fn twice(value: web::Path<String>) -> impl actix_web::Responder { let int_value: i32 = value.parse().unwrap_or(0); let doubled = int_value * 2; HttpResponse::Ok().body(format!("Twice value: {}", doubled)) } #[post("/test")] pub async fn post() -> impl Responder { HttpResponse::Ok().body("post works") } #[delete("/test")] pub async fn delete() -> impl Responder { "delete works" } #[route("/test", method = "PUT", method = "PATCH", method = "CUSTOM")] pub async fn multiple_shared_path() -> impl Responder { HttpResponse::Ok().finish() } #[routes] #[head("/test1")] #[connect("/test2")] #[options("/test3")] #[trace("/test4")] pub async fn multiple_separate_paths() -> impl Responder { HttpResponse::Ok().finish() } // test calling this from other mod scope with scope attribute... pub fn mod_common(message: String) -> impl actix_web::Responder { HttpResponse::Ok().body(message) } } /// Scope doc string to check in cargo expand. #[scope("/v1")] mod mod_scope_v1 { use super::*; /// Route doc string to check in cargo expand. #[get("/test")] pub async fn test() -> impl Responder { scope_module::mod_common("version1 works".to_string()) } } #[scope("/v2")] mod mod_scope_v2 { use super::*; // check to make sure non-function tokens in the scope block are preserved... enum TestEnum { Works, } #[get("/test")] pub async fn test() -> impl Responder { // make sure this type still exists... let test_enum = TestEnum::Works; match test_enum { TestEnum::Works => scope_module::mod_common("version2 works".to_string()), } } } #[actix_rt::test] async fn scope_get_async() { let srv = actix_test::start(|| App::new().service(scope_module::test)); let request = srv.request(http::Method::GET, srv.url("/test/test")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); } #[actix_rt::test] async fn scope_get_param_async() { let srv = actix_test::start(|| App::new().service(scope_module::twice)); let request = srv.request(http::Method::GET, srv.url("/test/twice-test/4")); let mut response = request.send().await.unwrap(); let body = response.body().await.unwrap(); let body_str = String::from_utf8(body.to_vec()).unwrap(); assert_eq!(body_str, "Twice value: 8"); } #[actix_rt::test] async fn scope_post_async() { let srv = actix_test::start(|| App::new().service(scope_module::post)); let request = srv.request(http::Method::POST, srv.url("/test/test")); let mut response = request.send().await.unwrap(); let body = response.body().await.unwrap(); let body_str = String::from_utf8(body.to_vec()).unwrap(); assert_eq!(body_str, "post works"); } #[actix_rt::test] async fn multiple_shared_path_async() { let srv = actix_test::start(|| App::new().service(scope_module::multiple_shared_path)); let request = srv.request(http::Method::PUT, srv.url("/test/test")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::PATCH, srv.url("/test/test")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); } #[actix_rt::test] async fn multiple_multi_path_async() { let srv = actix_test::start(|| App::new().service(scope_module::multiple_separate_paths)); let request = srv.request(http::Method::HEAD, srv.url("/test/test1")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::CONNECT, srv.url("/test/test2")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::OPTIONS, srv.url("/test/test3")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::TRACE, srv.url("/test/test4")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); } #[actix_rt::test] async fn scope_delete_async() { let srv = actix_test::start(|| App::new().service(scope_module::delete)); let request = srv.request(http::Method::DELETE, srv.url("/test/test")); let mut response = request.send().await.unwrap(); let body = response.body().await.unwrap(); let body_str = String::from_utf8(body.to_vec()).unwrap(); assert_eq!(body_str, "delete works"); } #[actix_rt::test] async fn scope_get_with_guard_async() { let srv = actix_test::start(|| App::new().service(scope_module::guard)); let request = srv .request(http::Method::GET, srv.url("/test/test/guard")) .insert_header(("Accept", "image/*")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); } #[actix_rt::test] async fn scope_v1_v2_async() { let srv = actix_test::start(|| { App::new() .service(mod_scope_v1::test) .service(mod_scope_v2::test) }); let request = srv.request(http::Method::GET, srv.url("/v1/test")); let mut response = request.send().await.unwrap(); let body = response.body().await.unwrap(); let body_str = String::from_utf8(body.to_vec()).unwrap(); assert_eq!(body_str, "version1 works"); let request = srv.request(http::Method::GET, srv.url("/v2/test")); let mut response = request.send().await.unwrap(); let body = response.body().await.unwrap(); let body_str = String::from_utf8(body.to_vec()).unwrap(); assert_eq!(body_str, "version2 works"); }
use actix_web::{Responder, HttpResponse, App}; use actix_web_codegen::*; /// doc comments shouldn't break anything #[get("/")] async fn index() -> impl Responder { HttpResponse::Ok() } #[actix_web::main] async fn main() { let srv = actix_test::start(|| App::new().service(index)); let request = srv.get("/"); let response = request.send().await.unwrap(); assert!(response.status().is_success()); }
use actix_web_codegen::*; use actix_web::http::Method; use std::str::FromStr; #[route("/", method = "hello")] async fn index() -> String { "Hello World!".to_owned() } #[actix_web::main] async fn main() { use actix_web::App; let srv = actix_test::start(|| App::new().service(index)); let request = srv.request(Method::from_str("hello").unwrap(), srv.url("/")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); }