mas_tower/tracing/
make_span.rs

1// Copyright 2023 The Matrix.org Foundation C.I.C.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use tracing::Span;
16
17use super::enrich_span::EnrichSpan;
18use crate::utils::FnWrapper;
19
20/// A trait for creating a span for a request.
21pub trait MakeSpan<R> {
22    fn make_span(&self, request: &R) -> Span;
23}
24
25impl<R, F> MakeSpan<R> for FnWrapper<F>
26where
27    F: Fn(&R) -> Span,
28{
29    fn make_span(&self, request: &R) -> Span {
30        (self.0)(request)
31    }
32}
33
34/// Make span from a function.
35pub fn make_span_fn<R, F>(f: F) -> FnWrapper<F>
36where
37    F: Fn(&R) -> Span,
38{
39    FnWrapper(f)
40}
41
42/// A macro to implement [`MakeSpan`] for a tuple of types, where the first type
43/// implements [`MakeSpan`] and the rest implement [`EnrichSpan`].
44macro_rules! impl_for_tuple {
45    (M, $($T:ident),+) => {
46        impl<R, M, $($T),+> MakeSpan<R> for (M, $($T),+)
47        where
48            M: MakeSpan<R>,
49            $($T: EnrichSpan<R>),+
50        {
51            fn make_span(&self, request: &R) -> Span {
52                #[allow(non_snake_case)]
53                let (ref m, $(ref $T),+) = *self;
54
55                let span = m.make_span(request);
56                $(
57                    $T.enrich_span(&span, request);
58                )+
59                span
60            }
61        }
62    };
63}
64
65impl_for_tuple!(M, T1);
66impl_for_tuple!(M, T1, T2);
67impl_for_tuple!(M, T1, T2, T3);
68impl_for_tuple!(M, T1, T2, T3, T4);
69impl_for_tuple!(M, T1, T2, T3, T4, T5);
70impl_for_tuple!(M, T1, T2, T3, T4, T5, T6);
71impl_for_tuple!(M, T1, T2, T3, T4, T5, T6, T7);
72impl_for_tuple!(M, T1, T2, T3, T4, T5, T6, T7, T8);