#![forbid(unsafe_code)]
#![warn(missing_docs, missing_debug_implementations, rust_2018_idioms)]
#![cfg_attr(docsrs, feature(doc_cfg))]
use std::sync::Arc;
use std::task::{Context, Poll};
use http::Request;
use tower::{Layer, Service};
pub use dynamic_config_web_core::{sections, NotInScope, Sections, Snapshot};
#[derive(Clone)]
pub struct SnapshotLayer {
sections: Arc<Sections>,
}
impl SnapshotLayer {
#[must_use]
pub fn new(sections: Sections) -> Self {
Self {
sections: Arc::new(sections),
}
}
#[must_use]
pub fn names(&self) -> Vec<&'static str> {
self.sections.names()
}
}
impl std::fmt::Debug for SnapshotLayer {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("SnapshotLayer")
.field("sections", &self.sections.names())
.finish()
}
}
impl<S> Layer<S> for SnapshotLayer {
type Service = SnapshotService<S>;
fn layer(&self, inner: S) -> Self::Service {
SnapshotService {
inner,
sections: Arc::clone(&self.sections),
}
}
}
#[derive(Clone)]
pub struct SnapshotService<S> {
inner: S,
sections: Arc<Sections>,
}
impl<S> std::fmt::Debug for SnapshotService<S> {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("SnapshotService")
.field("sections", &self.sections.names())
.finish_non_exhaustive()
}
}
impl<S, B> Service<Request<B>> for SnapshotService<S>
where
S: Service<Request<B>>,
{
type Response = S::Response;
type Error = S::Error;
type Future = S::Future;
fn poll_ready(&mut self, context: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner.poll_ready(context)
}
fn call(&mut self, mut request: Request<B>) -> Self::Future {
let taken = self.sections.take();
let merged = match request.extensions_mut().remove::<Snapshot>() {
Some(outer) => outer.merged_with(taken),
None => taken,
};
request.extensions_mut().insert(merged);
self.inner.call(request)
}
}