Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add MakeService::into_service and MakeService::as_service #492

Merged
merged 8 commits into from
Dec 29, 2020
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions tower/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added

- Added `MakeService::into_service` and `MakeService::as_service` for
converting `MakeService`s into `Service`s.

### Changed

- All middleware `tower-*` crates were merged into `tower` and placed
Expand Down
2 changes: 1 addition & 1 deletion tower/src/make/make_connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use std::task::{Context, Poll};
use tokio::io::{AsyncRead, AsyncWrite};
use tower_service::Service;

/// The MakeConnection trait is used to create transports.
/// The `MakeConnection` trait is used to create transports.
///
/// The goal of this service is to allow composable methods for creating
/// `AsyncRead + AsyncWrite` transports. This could mean creating a TLS
Expand Down
179 changes: 179 additions & 0 deletions tower/src/make/make_service.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
//! Contains `MakeService` which is a trait alias for a `Service` of `Service`s.

use crate::sealed::Sealed;
use std::fmt;
use std::future::Future;
use std::marker::PhantomData;
use std::task::{Context, Poll};
use tower_service::Service;

Expand Down Expand Up @@ -37,6 +41,87 @@ pub trait MakeService<Target, Request>: Sealed<(Target, Request)> {

/// Create and return a new service value asynchronously.
fn make_service(&mut self, target: Target) -> Self::Future;

/// Consume this `MakeService` and convert it into a `Service`.
///
/// # Example
/// ```
/// use std::convert::Infallible;
/// use tower::Service;
/// use tower::make::MakeService;
/// use tower::service_fn;
///
/// # fn main() {
/// # async {
/// // A `MakeService`
/// let make_service = service_fn(|make_req: ()| async {
/// Ok::<_, Infallible>(service_fn(|req: String| async {
/// Ok::<_, Infallible>(req)
/// }))
/// });
///
/// // Convert the `MakeService` into a `Service`
/// let mut svc = make_service.into_service();
///
/// // Make a new service
/// let mut new_svc = svc.call(()).await.unwrap();
///
/// // Call the service
/// let res = new_svc.call("foo".to_string()).await.unwrap();
/// # };
/// # }
/// ```
fn into_service(self) -> IntoService<Self, Request>
where
Self: Sized,
{
IntoService {
make: self,
_marker: PhantomData,
}
}

/// Convert this `MakeService` into a `Service` without consuming the original `MakeService`.
///
/// # Example
/// ```
/// use std::convert::Infallible;
/// use tower::Service;
/// use tower::make::MakeService;
/// use tower::service_fn;
///
/// # fn main() {
/// # async {
/// // A `MakeService`
/// let mut make_service = service_fn(|make_req: ()| async {
/// Ok::<_, Infallible>(service_fn(|req: String| async {
/// Ok::<_, Infallible>(req)
/// }))
/// });
///
/// // Convert the `MakeService` into a `Service`
/// let mut svc = make_service.as_service();
///
/// // Make a new service
/// let mut new_svc = svc.call(()).await.unwrap();
///
/// // Call the service
/// let res = new_svc.call("foo".to_string()).await.unwrap();
///
/// // The original `MakeService` is still accessible
/// let new_svc = make_service.make_service(()).await.unwrap();
/// # };
/// # }
/// ```
fn as_service(&mut self) -> AsService<Self, Request>
where
Self: Sized,
{
AsService {
make: self,
_marker: PhantomData,
}
}
}

impl<M, S, Target, Request> Sealed<(Target, Request)> for M
Expand Down Expand Up @@ -65,3 +150,97 @@ where
Service::call(self, target)
}
}

/// Service returned by [`MakeService::into_service`][into].
///
/// See the documentation on [`into_service`][into] for details.
///
/// [into]: MakeService::into_service
pub struct IntoService<M, Request> {
make: M,
_marker: PhantomData<Request>,
}

impl<M, Request> Clone for IntoService<M, Request>
where
M: Clone,
{
fn clone(&self) -> Self {
Self {
make: self.make.clone(),
_marker: PhantomData,
}
}
}

impl<M, Request> fmt::Debug for IntoService<M, Request>
where
M: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("IntoService")
.field("make", &self.make)
.finish()
}
}

impl<M, S, Target, Request> Service<Target> for IntoService<M, Request>
where
M: Service<Target, Response = S>,
S: Service<Request>,
{
type Response = M::Response;
type Error = M::Error;
type Future = M::Future;

#[inline]
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.make.poll_ready(cx)
}

#[inline]
fn call(&mut self, target: Target) -> Self::Future {
self.make.make_service(target)
}
}

/// Service returned by [`MakeService::as_service`][as].
///
/// See the documentation on [`as_service`][as] for details.
///
/// [as]: MakeService::as_service
pub struct AsService<'a, M, Request> {
make: &'a mut M,
_marker: PhantomData<Request>,
}

impl<M, Request> fmt::Debug for AsService<'_, M, Request>
where
M: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("AsService")
.field("make", &self.make)
.finish()
}
}

impl<M, S, Target, Request> Service<Target> for AsService<'_, M, Request>
where
M: Service<Target, Response = S>,
S: Service<Request>,
{
type Response = M::Response;
type Error = M::Error;
type Future = M::Future;

#[inline]
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.make.poll_ready(cx)
}

#[inline]
fn call(&mut self, target: Target) -> Self::Future {
self.make.make_service(target)
}
}
4 changes: 3 additions & 1 deletion tower/src/make/mod.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
//! Trait aliases for Services that produce specific types of Responses.

mod make_connection;
mod make_service;

pub mod make_service;

pub use self::make_connection::MakeConnection;
#[doc(inline)]
pub use self::make_service::MakeService;
davidpdrsn marked this conversation as resolved.
Show resolved Hide resolved