use std::task::{Context, Poll};
use tower::Service;
use crate::context::HasJobContext;
#[derive(Debug, Clone, Copy)]
pub struct Extension<T>(pub T);
impl<S, T> tower::Layer<S> for Extension<T>
where
T: Clone + Send + Sync + 'static,
{
type Service = AddExtension<S, T>;
fn layer(&self, inner: S) -> Self::Service {
AddExtension {
inner,
value: self.0.clone(),
}
}
}
#[derive(Clone, Copy, Debug)]
pub struct AddExtension<S, T> {
pub(crate) inner: S,
pub(crate) value: T,
}
impl<S, T, Req> Service<Req> for AddExtension<S, T>
where
S: Service<Req>,
T: Clone + Send + Sync + 'static,
Req: HasJobContext,
{
type Response = S::Response;
type Error = S::Error;
type Future = S::Future;
#[inline]
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, mut req: Req) -> Self::Future {
req.context_mut().insert(self.value.clone());
self.inner.call(req)
}
}