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
use rand::distributions::Alphanumeric;
use rand::{thread_rng, Rng};
use std::fmt::Debug;
use tracing::*;
use tracing_futures::Instrument;

pub async fn request_with_span<Fut: std::future::Future<Output = Result<T, E>>, T, E: Debug>(fut: Fut) -> Result<T, E> {
    let req_id: String = thread_rng().sample_iter(&Alphanumeric).take(10).map(char::from).collect();
    let req_id = req_id.as_str();
    let span = tracing::error_span!("req", req_id);

    with_span(span, async move {
        debug!("Start request [{}]", req_id);
        fut.await
            .map_err(|err| {
                error!("Request error: {:?}", err);
                err
            })
            .map(|res| {
                debug!("Request completed successfully");
                res
            })
    })
    .await
}

#[inline]
pub async fn with_span<Fut: std::future::Future>(span: Span, fut: Fut) -> Fut::Output {
    fut.instrument(span).await
}