hitbox_fn/upstream.rs
1//! Upstream adapter for async functions.
2
3use std::future::Future;
4
5use hitbox_core::Upstream;
6
7/// Wrapper that adapts an async function to the [`Upstream`] trait.
8///
9/// This allows any async function or closure to be used as the upstream
10/// data source in the hitbox caching FSM.
11///
12/// # Example
13///
14/// ```ignore
15/// use hitbox_fn::FnUpstream;
16///
17/// async fn fetch_data(id: u64) -> Data {
18/// // fetch from database
19/// }
20///
21/// let upstream = FnUpstream::new(fetch_data);
22/// ```
23pub struct FnUpstream<F> {
24 func: F,
25}
26
27impl<F> FnUpstream<F> {
28 /// Create a new function upstream wrapper.
29 pub fn new(func: F) -> Self {
30 Self { func }
31 }
32}
33
34impl<F, Args, Fut, Res> Upstream<Args> for FnUpstream<F>
35where
36 F: FnMut(Args) -> Fut,
37 Fut: Future<Output = Res> + Send,
38{
39 type Response = Res;
40 type Future = Fut;
41
42 fn call(&mut self, req: Args) -> Self::Future {
43 (self.func)(req)
44 }
45}