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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
use crate::trace::TraceContext;
use opentelemetry::{
    global::BoxedTracer,
    trace::{FutureExt, TraceContextExt, Tracer},
    Context,
};
use trillium::{async_trait, Conn, Handler, Info, Upgrade};

/// Trillium handler that instruments handlers with spans.
///
/// **IMPORTANT** This handler expects [`crate::Trace`] or [`crate::Instrument`] to have been run on
/// the conn prior to running this handler.
#[derive(Debug, Clone)]
pub struct InstrumentHandler<H, T> {
    handler: H,
    tracer: T,
}

#[async_trait]
impl<H, T> Handler for InstrumentHandler<H, T>
where
    H: Handler,
    T: Tracer + Send + Sync + 'static,
    T::Span: Send + Sync + 'static,
{
    async fn init(&mut self, info: &mut Info) {
        let name = self.handler.name();
        self.handler
            .init(info)
            .with_context(Context::current_with_span(
                self.tracer.start(format!("{name}::init")),
            ))
            .await
    }

    async fn run(&self, mut conn: Conn) -> Conn {
        let name = self.handler.name();
        match conn.take_state() {
            Some(TraceContext { context }) => {
                let child = self
                    .tracer
                    .start_with_context(format!("{name}::run"), &context);
                let child_context = Context::current_with_span(child);
                self.handler
                    .run(conn.with_state(TraceContext {
                        context: child_context.clone(),
                    }))
                    .with_context(child_context)
                    .await
                    .with_state(TraceContext { context })
            }

            None => self.handler.run(conn).await,
        }
    }

    async fn before_send(&self, mut conn: Conn) -> Conn {
        let name = self.handler.name();
        match conn.take_state() {
            Some(TraceContext { context }) => {
                let child = self
                    .tracer
                    .start_with_context(format!("{name}::before_send"), &context);

                let child_context = Context::current_with_span(child);
                self.handler
                    .before_send(conn.with_state(TraceContext {
                        context: child_context.clone(),
                    }))
                    .with_context(child_context)
                    .await
                    .with_state(TraceContext { context })
            }

            None => self.handler.before_send(conn).await,
        }
    }

    fn has_upgrade(&self, upgrade: &Upgrade) -> bool {
        self.handler.has_upgrade(upgrade)
    }

    async fn upgrade(&self, upgrade: Upgrade) {
        let name = self.handler.name();
        match upgrade.state().get() {
            Some(TraceContext { context }) => {
                let child = self
                    .tracer
                    .start_with_context(format!("{name}::upgrade"), context);

                self.handler
                    .upgrade(upgrade)
                    .with_context(Context::current_with_span(child))
                    .await
            }

            None => self.handler.upgrade(upgrade).await,
        }
    }
}

/// decorate a handler with a specific tracer
///
/// **IMPORTANT** This handler expects [`crate::Trace`] or [`crate::Instrument`] to have been run on
/// the conn prior to running this handler.
pub fn instrument_handler<H, T>(handler: H, tracer: T) -> InstrumentHandler<H, T>
where
    H: Handler,
    T: Tracer + Send + Sync + 'static,
    T::Span: Send + Sync + 'static,
{
    InstrumentHandler::new(handler, tracer)
}

impl<H, T> InstrumentHandler<H, T>
where
    H: Handler,
    T: Tracer + Send + Sync + 'static,
    T::Span: Send + Sync + 'static,
{
    /// decorate a handler with a specific tracer
    ///
    /// **IMPORTANT** This handler expects [`crate::Trace`] or [`crate::Instrument`] to have been run on
    /// the conn prior to running this handler.
    pub fn new(handler: H, tracer: T) -> Self {
        Self { handler, tracer }
    }
}

/// the primary entrypoint for decorating a handler.
///
/// Uses a global tracer with the name `"trillium-opentelemetry"`
///
/// **IMPORTANT** This handler expects [`crate::Trace`] or [`crate::Instrument`] to have been run on
/// the conn prior to running this handler.
pub fn instrument_handler_global<H>(handler: H) -> InstrumentHandler<H, BoxedTracer>
where
    H: Handler,
{
    InstrumentHandler::new(
        handler,
        opentelemetry::global::tracer("trillium-opentelemetry"),
    )
}