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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
use crate::{
    span::{test_span, HSpan, NOOP_SPAN},
    span_context::{EncodedSpanContext, HSpanContext},
};
use rustracing::{sampler::*, span::StartSpanOptions};
use rustracing_jaeger::{span::SpanContextState, Span as RjSpan, Tracer};
use serde::de::DeserializeOwned;
// use serde::Deserialize;
use serde::Serialize;
use std::borrow::Cow;

/// SpanWrap is a simple way to couple some data along with a struct. It is
/// common to send some data on a channel which will be used as arguments
/// to a function on the receiving side, where we also want to continue the
/// trace on the receiving side. This struct helps keep that data together
/// with minimal boilerplate.
///
/// The use of shrinkwrap allows the entire struct to be used as if it were
/// a bare T (in most situations), but the RjSpan can also be extracted.
#[derive(Shrinkwrap)]
#[shrinkwrap(mutable)]
pub struct SpanWrap<T> {
    #[shrinkwrap(main_field)]
    pub data: T,
    pub span_context: Option<HSpanContext>,
}

impl<T> SpanWrap<T> {
    pub fn new(data: T, span_context: Option<HSpanContext>) -> Self {
        Self { data, span_context }
    }

    pub fn follower<S: Into<Cow<'static, str>>>(
        &self,
        tracer: &Tracer,
        operation_name: S,
    ) -> Option<HSpan> {
        self.span_context
            .as_ref()
            .map(|context| context.follower(tracer, operation_name))
    }

    pub fn follower_or_null<S: Into<Cow<'static, str>>>(
        &self,
        tracer: &Tracer,
        operation_name: S,
    ) -> HSpan {
        self.follower(tracer, operation_name)
            .unwrap_or_else(|| NOOP_SPAN.follower("noop"))
    }

    pub fn follower_<'a, N: Into<Cow<'static, str>>, F>(
        &'a self,
        tracer: &Tracer,
        operation_name: N,
        f: F,
    ) -> Option<HSpan>
    where
        F: FnOnce(StartSpanOptions<'_, BoxSampler<SpanContextState>, SpanContextState>) -> RjSpan,
    {
        self.span_context
            .as_ref()
            .map(|context| context.follower_(tracer, operation_name, f))
    }

    /// Map the data field to a new value while keeping the same span_context
    pub fn map<F, U>(self, f: F) -> SpanWrap<U>
    where
        F: FnOnce(T) -> U,
    {
        SpanWrap {
            data: f(self.data),
            span_context: self.span_context,
        }
    }
}

impl<T: std::fmt::Debug> std::fmt::Debug for SpanWrap<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "SpanWrap({:?}, {:?})", self.data, self.span_context)
    }
}

impl<T: PartialEq> PartialEq for SpanWrap<T> {
    fn eq(&self, other: &Self) -> bool {
        self.data == other.data
    }
}

#[derive(Serialize, Deserialize, Clone)]
pub struct EncodedSpanWrap<T>
where
    T: Serialize + DeserializeOwned + Clone,
{
    #[serde(bound(deserialize = "T: DeserializeOwned"))]
    pub data: T,
    pub span_context: Option<EncodedSpanContext>,
}

impl<T> EncodedSpanWrap<T>
where
    T: Serialize + DeserializeOwned + Clone,
{
    /// Map the data field to a new value while keeping the same span_context
    pub fn map<F, U>(self, f: F) -> EncodedSpanWrap<U>
    where
        F: FnOnce(T) -> U,
        U: Serialize + DeserializeOwned + Clone,
    {
        EncodedSpanWrap {
            data: f(self.data),
            span_context: self.span_context,
        }
    }

    /// Return new struct with new inner data and cloned context
    pub fn swapped<U>(&self, data: U) -> EncodedSpanWrap<U>
    where
        U: Serialize + DeserializeOwned + Clone,
    {
        EncodedSpanWrap {
            data,
            span_context: self.span_context.clone(),
        }
    }
}

impl<'a, T> From<SpanWrap<T>> for EncodedSpanWrap<T>
where
    T: Serialize + DeserializeOwned + Clone,
{
    fn from(sw: SpanWrap<T>) -> Self {
        Self {
            data: sw.data,
            span_context: match sw.span_context {
                Some(c) => c.encode().ok().or_else(|| {
                    warn!("Failed to decode SpanContext, throwing it away!");
                    None
                }),
                None => None,
            },
        }
    }
}

impl<'a, T> From<EncodedSpanWrap<T>> for SpanWrap<T>
where
    T: Serialize + DeserializeOwned + Clone,
{
    fn from(swe: EncodedSpanWrap<T>) -> Self {
        Self {
            data: swe.data,
            span_context: match swe.span_context {
                Some(c) => HSpanContext::decode(c).ok().or_else(|| {
                    warn!("Failed to decode SpanContext, throwing it away!");
                    None
                }),
                None => None,
            },
        }
    }
}

impl<'a, T> std::fmt::Debug for EncodedSpanWrap<T>
where
    T: Serialize + DeserializeOwned + Clone + std::fmt::Debug,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "SpanWrap({:?}, {:?})", self.data, self.span_context)
    }
}

impl<T> PartialEq for EncodedSpanWrap<T>
where
    T: Serialize + DeserializeOwned + Clone + PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        self.data == other.data
    }
}

pub fn test_wrap<T>(t: T) -> SpanWrap<T> {
    test_span().wrap(t)
}

pub fn test_wrap_enc<T: Serialize + DeserializeOwned + Clone>(t: T) -> EncodedSpanWrap<T> {
    test_span().wrap(t).into()
}

// impl<T> TryFrom<SpanWrap<T>> for EncodedSpanWrap<T>
// where T: Serialize + Deserialize + Clone {
//     type Error = rustracing_jaeger::Error;

//     fn try_from(sw: SpanWrap<T>) -> Result<Self> {
//         Ok(Self {
//             data: sw.data,
//             span_context: match sw.span_context {
//                 Some(c) => Some(c.encode()?),
//                 None => None,
//             },
//         })
//     }
// }

// impl<T> TryFrom<EncodedSpanWrap<T>> for SpanWrap<T>
// where T: Serialize + Deserialize + Clone {
//     type Error = rustracing_jaeger::Error;

//     fn try_from(swe: EncodedSpanWrap<T>) -> Result<Self> {
//         Ok(Self {
//             data: swe.data,
//             span_context: match swe.span_context {
//                 Some(c) => Some(HSpanContext::decode(&c)?),
//                 None => None,
//             },
//         })
//     }
// }