use std::task::{Context, Poll};
use http::{Request, Response};
use tower::Service;
use super::{CallbackLayer, MakeCallbackHandler, ResponseFuture};
#[derive(Debug, Clone, Copy)]
pub struct Callback<S, M> {
pub(crate) inner: S,
pub(crate) make_callback_handler: M,
}
impl<S, M> Callback<S, M> {
pub fn new(inner: S, make_callback_handler: M) -> Self {
Self {
inner,
make_callback_handler,
}
}
pub fn layer(make_handler: M) -> CallbackLayer<M>
where
M: MakeCallbackHandler,
{
CallbackLayer::new(make_handler)
}
pub fn inner(&self) -> &S {
&self.inner
}
pub fn inner_mut(&mut self) -> &mut S {
&mut self.inner
}
pub fn into_inner(self) -> S {
self.inner
}
}
impl<S, M, RequestBody, ResponseBody> Service<Request<RequestBody>> for Callback<S, M>
where
S: Service<Request<RequestBody>, Response = Response<ResponseBody>>,
M: MakeCallbackHandler,
{
type Response = Response<ResponseBody>;
type Error = S::Error;
type Future = ResponseFuture<S::Future, M::Handler>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, request: Request<RequestBody>) -> Self::Future {
let (head, body) = request.into_parts();
let handler = self.make_callback_handler.make_handler(&head);
let request = Request::from_parts(head, body);
ResponseFuture {
inner: self.inner.call(request),
handler: Some(handler),
}
}
}