use crate::{Executor, ExecutorService};
use tower_layer::Layer;
#[derive(Clone)]
pub struct ExecutorLayer<E> {
executor: E,
}
impl<E> ExecutorLayer<E>
where
E: Executor,
{
pub fn new(executor: E) -> Self {
Self { executor }
}
pub fn builder() -> ExecutorLayerBuilder<E> {
ExecutorLayerBuilder::new()
}
}
impl ExecutorLayer<tokio::runtime::Handle> {
pub fn current() -> Self {
Self::new(tokio::runtime::Handle::current())
}
}
impl<S, E> Layer<S> for ExecutorLayer<E>
where
E: Clone,
{
type Service = ExecutorService<S, E>;
fn layer(&self, service: S) -> Self::Service {
ExecutorService::new(service, self.executor.clone())
}
}
pub struct ExecutorLayerBuilder<E> {
executor: Option<E>,
}
impl<E> ExecutorLayerBuilder<E> {
fn new() -> Self {
Self { executor: None }
}
}
impl<E> ExecutorLayerBuilder<E>
where
E: Executor,
{
pub fn executor(mut self, executor: E) -> Self {
self.executor = Some(executor);
self
}
pub fn build(self) -> ExecutorLayer<E> {
ExecutorLayer {
executor: self.executor.expect("executor must be configured"),
}
}
}
impl ExecutorLayerBuilder<tokio::runtime::Handle> {
pub fn handle(mut self, handle: tokio::runtime::Handle) -> Self {
self.executor = Some(handle);
self
}
pub fn current(mut self) -> Self {
self.executor = Some(tokio::runtime::Handle::current());
self
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn test_layer_creation() {
let layer = ExecutorLayer::current();
let _layer2 = layer.clone();
}
#[tokio::test]
async fn test_builder() {
let layer = ExecutorLayer::<tokio::runtime::Handle>::builder()
.current()
.build();
let _layer2 = layer.clone();
}
#[tokio::test]
async fn test_builder_with_handle() {
let handle = tokio::runtime::Handle::current();
let layer = ExecutorLayer::builder().handle(handle).build();
let _layer2 = layer.clone();
}
}