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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
use super::ExtractFormat;
use super::InjectFormat;

use super::Result;
use super::Span;
use super::SpanContext;
use super::StartOptions;


/// Smallest set of operations that a concrete tracer must implement.
///
/// While OpenTracingRust users develop against the `Tracer` structure,
/// the logic of a tracer is implemented through this trait.
///
/// `Tracer` is therefore a wrapper around `TracerInterface` trait objects
/// and provides some helper methods that are useful for all tracers.
///
/// # Implementing tracers
///
/// OpenTracingRust aims to minimise the amount of work to implement tracers.
/// This is achieved by `Box`ing traits into structures that are passed around my clients.
///
/// The following elements must be provided by tracer implementations:
///
///   * An inner context that implements `ImplContext` to store a tracer specific span id.
///   * An inner tracer that implements `TracerInterface` to inject/extract/create spans.
///   * A function that sends `FinishedSpan`s to the distributed tracer.
///
/// How these elements are implemented and what they do is up to the tracer implementation
/// with one exception: `FinishedSpan`s are sent over an `crossbeam_channel::unbounded`
/// so `ImplContext` has to be `Send`.
///
/// # Examples
///
/// If you are looking to implement your tracer checkout the following first:
///
///   * The `FileTracer` implementation that is part of OpenTracingRust.
///   * Example `1-custom-tracer.rs`, which implements an in-memory tracer.
pub trait TracerInterface : Send + Sync {
    /// Attempt to extract a SpanContext from a carrier.
    fn extract(&self, fmt: ExtractFormat) -> Result<Option<SpanContext>>;

    /// Inject tracing information into a carrier.
    fn inject(&self, context: &SpanContext, fmt: InjectFormat) -> Result<()>;

    /// Create a new `Span` with the given operation name and starting options.
    fn span(&self, name: &str, options: StartOptions) -> Span;
}


/// The library users interface to tracing.
///
/// This structure is the focus point for clients to use in combination with `SpanContext`.
/// The configured tracer is stored in this structure and backs the available methods.
///
/// The `Tracer` structure also provides some utility methods to make common operations easier.
pub struct Tracer {
    tracer: Box<dyn TracerInterface>
}

impl Tracer {
    /// Creates a new `Tracer` for a concrete tracer.
    pub fn new<T: TracerInterface + 'static>(tracer: T) -> Tracer {
        Tracer {
            tracer: Box::new(tracer)
        }
    }
}

impl Tracer {
    /// Attempt to extract a SpanContext from a carrier.
    ///
    /// If the carrier (i.e, HTTP Request, RPC Message, ...) includes tracing information
    /// this method returns `Ok(Some(context))`, otherwise `Ok(None)` is returned.
    ///
    /// If the method fails to extract a context because the carrier fails or because
    /// the tracing information is incorrectly formatted an `Error` is returned.
    pub fn extract(&self, fmt: ExtractFormat) -> Result<Option<SpanContext>> {
        self.tracer.extract(fmt)
    }

    /// Inject tracing information into a carrier.
    ///
    /// If the method fails to inject the context because the carrier fails.
    pub fn inject(
        &self, context: &SpanContext, fmt: InjectFormat
    ) -> Result<()> {
        self.tracer.inject(context, fmt)
    }

    /// Create a new `Span` with the given operation name and default starting options.
    pub fn span(&self, name: &str) -> Span {
        self.span_with_options(name, StartOptions::default())
    }

    /// Create a new `Span` with the given operation name and starting options.
    pub fn span_with_options(&self, name: &str, options: StartOptions) -> Span {
        self.tracer.span(name, options)
    }
}


#[cfg(test)]
mod tests {
    use std::collections::HashMap;
    use std::io;
    use std::io::BufRead;

    use crossbeam_channel::unbounded;

    use super::super::ExtractFormat;
    use super::super::InjectFormat;

    use super::super::ImplContextBox;
    use super::super::Result;
    use super::super::Span;
    use super::super::SpanContext;
    use super::super::SpanReference;
    use super::super::SpanReferenceAware;
    use super::super::SpanSender;
    use super::super::StartOptions;

    use super::Tracer;
    use super::TracerInterface;


    #[derive(Debug, Clone)]
    struct TestContext {
        pub name: String
    }
    impl SpanReferenceAware for TestContext {
        fn reference_span(&mut self, _: &SpanReference) {}
    }

    struct TestTracer {
        sender: SpanSender
    }
    impl TracerInterface for TestTracer {
        fn extract(&self, fmt: ExtractFormat) -> Result<Option<SpanContext>> {
            match fmt {
                ExtractFormat::Binary(carrier) => {
                    let mut reader = self::io::BufReader::new(carrier);
                    let mut name = String::new();
                    reader.read_line(&mut name)?;

                    let mut context = SpanContext::new(ImplContextBox::new(
                        TestContext { name: name.trim().to_owned() }
                    ));
                    for line in reader.lines() {
                        let line = line?;
                        let cells: Vec<&str> = line.split(':').collect();
                        context.set_baggage_item(String::from(cells[0]), String::from(cells[1]));
                    }
                    Ok(Some(context))
                }

                ExtractFormat::HttpHeaders(carrier) => {
                    let mut context = SpanContext::new(ImplContextBox::new(
                        TestContext { name: carrier.get("Span-Name").unwrap() }
                    ));
                    for (key, value) in carrier.items() {
                        if key.starts_with("Baggage-") {
                            context.set_baggage_item(String::from(&key[8..]), value.clone());
                        }
                    }
                    Ok(Some(context))
                }

                ExtractFormat::TextMap(carrier) => {
                    let mut context = SpanContext::new(ImplContextBox::new(
                        TestContext { name: carrier.get("span-name").unwrap() }
                    ));
                    for (key, value) in carrier.items() {
                        if key.starts_with("baggage-") {
                            context.set_baggage_item(String::from(&key[8..]), value.clone());
                        }
                    }
                    Ok(Some(context))
                }
            }
        }

        fn inject(
            &self, context: &SpanContext, fmt: InjectFormat
        ) -> Result<()> {
            match fmt {
                InjectFormat::Binary(carrier) => {
                    let inner = context.impl_context::<TestContext>().unwrap();
                    carrier.write_fmt(format_args!("TraceId: {}\n", "123"))?;
                    carrier.write_fmt(
                        format_args!("Span Name: {}\n", &inner.name)
                    )?;
                    for (key, value) in context.baggage_items() {
                        carrier.write_fmt(format_args!("Baggage-{}: {}\n", key, value))?;
                    }
                    Ok(())
                }

                InjectFormat::HttpHeaders(carrier) => {
                    let inner = context.impl_context::<TestContext>().unwrap();
                    carrier.set("Trace-Id", "123");
                    carrier.set("Span-Name", &inner.name);
                    for (key, value) in context.baggage_items() {
                        let key = format!("Baggage-{}", key);
                        carrier.set(&key, value);
                    }
                    Ok(())
                }

                InjectFormat::TextMap(carrier) => {
                    let inner = context.impl_context::<TestContext>().unwrap();
                    carrier.set("trace-id", "123");
                    carrier.set("span-name", &inner.name);
                    for (key, value) in context.baggage_items() {
                        let key = format!("baggage-{}", key);
                        carrier.set(&key, value);
                    }
                    Ok(())
                }
            }
        }

        fn span(&self, name: &str, options: StartOptions) -> Span {
            let context = SpanContext::new(ImplContextBox::new(TestContext {
                name: String::from("test-span")
            }));
            Span::new(name, context, options, self.sender.clone())
        }
    }


    #[test]
    fn create_span() {
        let (sender, _) = unbounded();
        let tracer = Tracer::new(TestTracer {sender});
        let _span: Span = tracer.span("test-span");
    }

    #[test]
    fn extract_binary() {
        let mut buffer = io::Cursor::new("test-span\na:b\n");
        let (sender, _) = unbounded();
        let tracer = Tracer::new(TestTracer {sender});
        let context = tracer.extract(
            ExtractFormat::Binary(Box::new(&mut buffer))
        ).unwrap().unwrap();
        let inner = context.impl_context::<TestContext>().unwrap();
        assert_eq!("test-span", inner.name);
        let items: Vec<(String, String)> = context.baggage_items()
            .map(|(k, v)| (k.clone(), v.clone()))
            .collect();
        assert_eq!(items, vec![(String::from("a"), String::from("b"))]);
    }

    #[test]
    fn extract_http_headers() {
        let mut map = HashMap::new();
        map.insert(String::from("Span-Name"), String::from("2"));
        map.insert(String::from("Baggage-a"), String::from("b"));
        let (sender, _) = unbounded();
        let tracer = Tracer::new(TestTracer {sender});
        let context = tracer.extract(ExtractFormat::HttpHeaders(Box::new(&map))).unwrap().unwrap();
        let inner = context.impl_context::<TestContext>().unwrap();
        assert_eq!("2", inner.name);
        let items: Vec<(String, String)> = context.baggage_items()
            .map(|(k, v)| (k.clone(), v.clone()))
            .collect();
        assert_eq!(items, vec![(String::from("a"), String::from("b"))]);
    }

    #[test]
    fn extract_textmap() {
        let mut map = HashMap::new();
        map.insert(String::from("span-name"), String::from("2"));
        map.insert(String::from("baggage-a"), String::from("b"));
        let (sender, _) = unbounded();
        let tracer = Tracer::new(TestTracer {sender});
        let context = tracer.extract(ExtractFormat::TextMap(Box::new(&map))).unwrap().unwrap();
        let inner = context.impl_context::<TestContext>().unwrap();
        assert_eq!("2", inner.name);
        let items: Vec<(String, String)> = context.baggage_items()
            .map(|(k, v)| (k.clone(), v.clone()))
            .collect();
        assert_eq!(items, vec![(String::from("a"), String::from("b"))]);
    }

    #[test]
    fn inject_binary() {
        let (sender, _) = unbounded();
        let tracer = Tracer::new(TestTracer {sender});
        let mut span = tracer.span("test-span");
        span.set_baggage_item("a", "b");

        let mut buffer: Vec<u8> = Vec::new();
        tracer.inject(span.context(), InjectFormat::Binary(Box::new(&mut buffer))).unwrap();
        assert_eq!(
            String::from_utf8(buffer).unwrap(),
            "TraceId: 123\nSpan Name: test-span\nBaggage-a: b\n"
        );
    }

    #[test]
    fn inject_http_headers() {
        let (sender, _) = unbounded();
        let tracer = Tracer::new(TestTracer {sender});
        let mut span = tracer.span("test-span");
        span.set_baggage_item("a", "b");

        let mut map = HashMap::new();
        tracer.inject(span.context(), InjectFormat::HttpHeaders(Box::new(&mut map))).unwrap();

        let mut items: Vec<(String, String)> = map.iter()
            .map(|(k, v)| (k.clone(), v.clone()))
            .collect();
        items.sort();
        assert_eq!(items, [
            (String::from("Baggage-a"), String::from("b")),
            (String::from("Span-Name"), String::from("test-span")),
            (String::from("Trace-Id"), String::from("123"))
        ]);
    }

    #[test]
    fn inject_textmap() {
        let (sender, _) = unbounded();
        let tracer = Tracer::new(TestTracer {sender});
        let mut span = tracer.span("test-span");
        span.set_baggage_item("a", "b");

        let mut map = HashMap::new();
        tracer.inject(span.context(), InjectFormat::TextMap(Box::new(&mut map))).unwrap();

        let mut items: Vec<(String, String)> = map.iter()
            .map(|(k, v)| (k.clone(), v.clone()))
            .collect();
        items.sort();
        assert_eq!(items, [
            (String::from("baggage-a"), String::from("b")),
            (String::from("span-name"), String::from("test-span")),
            (String::from("trace-id"), String::from("123"))
        ]);
    }
}