scuffle_bootstrap/
service.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
use std::pin::Pin;
use std::sync::Arc;
use std::task::{ready, Context, Poll};

pub trait Service<Global>: Send + Sync + 'static + Sized {
	fn name(&self) -> Option<&'static str> {
		None
	}

	/// Initialize the service
	fn enabled(&self, global: &Arc<Global>) -> impl std::future::Future<Output = anyhow::Result<bool>> + Send {
		let _ = global;
		std::future::ready(Ok(true))
	}

	fn run(
		self,
		global: Arc<Global>,
		ctx: scuffle_context::Context,
	) -> impl std::future::Future<Output = anyhow::Result<()>> + Send + 'static {
		let _ = global;
		async move {
			ctx.done().await;
			Ok(())
		}
	}
}

impl<G, F, Fut> Service<G> for F
where
	F: FnOnce(Arc<G>, scuffle_context::Context) -> Fut + Send + Sync + 'static,
	Fut: std::future::Future<Output = anyhow::Result<()>> + Send + 'static,
{
	fn run(
		self,
		global: Arc<G>,
		ctx: scuffle_context::Context,
	) -> impl std::future::Future<Output = anyhow::Result<()>> + Send + 'static {
		self(global, ctx)
	}
}

pin_project_lite::pin_project! {
	#[must_use = "futures do nothing unless polled"]
	pub struct NamedFuture<T> {
		name: &'static str,
		#[pin]
		fut: T,
	}
}

impl<T> NamedFuture<T> {
	pub fn new(name: &'static str, fut: T) -> Self {
		Self { name, fut }
	}
}

impl<T> std::future::Future for NamedFuture<T>
where
	T: std::future::Future,
{
	type Output = (&'static str, T::Output);

	fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
		let this = self.project();
		let res = ready!(this.fut.poll(cx));
		Poll::Ready((this.name, res))
	}
}