tower_worker/worker/layer.rs
1use std::future::Future;
2use tower_layer::Layer;
3
4/// Spawns a worker task with a clone of the inner service.
5///
6/// The default Tokio executor is used to run the given service, which means
7/// that this layer can only be used on the Tokio runtime.
8///
9/// See the module documentation for more details.
10pub struct WorkerLayer<T> {
11 make_worker: T,
12}
13
14impl<T> WorkerLayer<T> {
15 /// Creates a new [`WorkerLayer`] with the provided `make_worker` closure.
16 ///
17 /// `make_worker` accepts a clone of the inner service and returns a
18 /// `Future` that will be spawned as a tokio task.
19 ///
20 /// [`Future`]: std::future::Future
21 pub fn new(make_worker: T) -> Self {
22 Self { make_worker }
23 }
24}
25
26impl<S, T, F> Layer<S> for WorkerLayer<T>
27where
28 S: Clone,
29 T: Fn(S) -> F,
30 F: Future<Output = ()> + Send + 'static,
31{
32 type Service = S;
33
34 fn layer(&self, inner: S) -> Self::Service {
35 tokio::spawn((self.make_worker)(inner.clone()));
36
37 inner
38 }
39}