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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
//! Span.
use crate::carrier;
use crate::convert::MaybeAsRef;
use crate::log::{Log, LogBuilder, StdErrorLogFieldsBuilder};
use crate::sampler::{AllSampler, Sampler};
use crate::tag::{StdTag, Tag, TagValue};
use crate::Result;
use std::borrow::Cow;
use std::io::{Read, Write};
use std::time::SystemTime;

/// Finished span receiver.
pub type SpanReceiver<T> = crossbeam_channel::Receiver<FinishedSpan<T>>;
/// Sender of finished spans to the destination channel.
pub type SpanSender<T> = crossbeam_channel::Sender<FinishedSpan<T>>;

/// Span.
///
/// When this span is dropped, it will be converted to `FinishedSpan` and
/// it will be sent to the associated `SpanReceiver`.
#[derive(Debug)]
pub struct Span<T>(Option<SpanInner<T>>);
impl<T> Span<T> {
    /// Makes an inactive span.
    ///
    /// This span is never traced.
    ///
    /// # Examples
    ///
    /// ```
    /// use rustracing::span::Span;
    ///
    /// let span = Span::<()>::inactive();
    /// assert!(! span.is_sampled());
    /// ```
    pub fn inactive() -> Self {
        Span(None)
    }

    /// Returns a handle of this span.
    pub fn handle(&self) -> SpanHandle<T>
    where
        T: Clone,
    {
        SpanHandle(
            self.0
                .as_ref()
                .map(|inner| (inner.context.clone(), inner.span_tx.clone())),
        )
    }

    /// Returns `true` if this span is sampled (i.e., being traced).
    pub fn is_sampled(&self) -> bool {
        self.0.is_some()
    }

    /// Returns the context of this span.
    pub fn context(&self) -> Option<&SpanContext<T>> {
        self.0.as_ref().map(|x| &x.context)
    }

    /// Sets the operation name of this span.
    pub fn set_operation_name<F, N>(&mut self, f: F)
    where
        F: FnOnce() -> N,
        N: Into<Cow<'static, str>>,
    {
        if let Some(inner) = self.0.as_mut() {
            inner.operation_name = f().into();
        }
    }

    /// Sets the finish time of this span.
    pub fn set_finish_time<F>(&mut self, f: F)
    where
        F: FnOnce() -> SystemTime,
    {
        if let Some(inner) = self.0.as_mut() {
            inner.finish_time = Some(f());
        }
    }

    /// Sets the tag to this span.
    pub fn set_tag<F>(&mut self, f: F)
    where
        F: FnOnce() -> Tag,
    {
        use std::iter::once;
        self.set_tags(|| once(f()));
    }

    /// Sets the tags to this span.
    pub fn set_tags<F, I>(&mut self, f: F)
    where
        F: FnOnce() -> I,
        I: IntoIterator<Item = Tag>,
    {
        if let Some(inner) = self.0.as_mut() {
            for tag in f() {
                inner.tags.retain(|x| x.name() != tag.name());
                inner.tags.push(tag);
            }
        }
    }

    /// Sets the baggage item to this span.
    pub fn set_baggage_item<F>(&mut self, f: F)
    where
        F: FnOnce() -> BaggageItem,
    {
        if let Some(inner) = self.0.as_mut() {
            let item = f();
            inner.context.baggage_items.retain(|x| x.name != item.name);
            inner.context.baggage_items.push(item);
        }
    }

    /// Gets the baggage item that has the name `name`.
    pub fn get_baggage_item(&self, name: &str) -> Option<&BaggageItem> {
        if let Some(inner) = self.0.as_ref() {
            inner.context.baggage_items.iter().find(|x| x.name == name)
        } else {
            None
        }
    }

    /// Logs structured data.
    pub fn log<F>(&mut self, f: F)
    where
        F: FnOnce(&mut LogBuilder),
    {
        if let Some(inner) = self.0.as_mut() {
            let mut builder = LogBuilder::new();
            f(&mut builder);
            if let Some(log) = builder.finish() {
                inner.logs.push(log);
            }
        }
    }

    /// Logs an error.
    ///
    /// This is a simple wrapper of `log` method
    /// except that the `StdTag::error()` tag will be set in this method.
    pub fn error_log<F>(&mut self, f: F)
    where
        F: FnOnce(&mut StdErrorLogFieldsBuilder),
    {
        if let Some(inner) = self.0.as_mut() {
            let mut builder = LogBuilder::new();
            f(&mut builder.error());
            if let Some(log) = builder.finish() {
                inner.logs.push(log);
            }
            if inner.tags.iter().find(|x| x.name() == "error").is_none() {
                inner.tags.push(StdTag::error());
            }
        }
    }

    /// Starts a `ChildOf` span if this span is sampled.
    pub fn child<N, F>(&self, operation_name: N, f: F) -> Span<T>
    where
        N: Into<Cow<'static, str>>,
        T: Clone,
        F: FnOnce(StartSpanOptions<AllSampler, T>) -> Span<T>,
    {
        self.handle().child(operation_name, f)
    }

    /// Starts a `FollowsFrom` span if this span is sampled.
    pub fn follower<N, F>(&self, operation_name: N, f: F) -> Span<T>
    where
        N: Into<Cow<'static, str>>,
        T: Clone,
        F: FnOnce(StartSpanOptions<AllSampler, T>) -> Span<T>,
    {
        self.handle().follower(operation_name, f)
    }

    pub(crate) fn new(
        operation_name: Cow<'static, str>,
        start_time: SystemTime,
        references: Vec<SpanReference<T>>,
        tags: Vec<Tag>,
        state: T,
        baggage_items: Vec<BaggageItem>,
        span_tx: SpanSender<T>,
    ) -> Self {
        let context = SpanContext::new(state, baggage_items);
        let inner = SpanInner {
            operation_name,
            start_time,
            finish_time: None,
            references,
            tags,
            logs: Vec::new(),
            context,
            span_tx,
        };
        Span(Some(inner))
    }
}
impl<T> Drop for Span<T> {
    fn drop(&mut self) {
        if let Some(inner) = self.0.take() {
            let finished = FinishedSpan {
                operation_name: inner.operation_name,
                start_time: inner.start_time,
                finish_time: inner.finish_time.unwrap_or_else(SystemTime::now),
                references: inner.references,
                tags: inner.tags,
                logs: inner.logs,
                context: inner.context,
            };
            let _ = inner.span_tx.try_send(finished);
        }
    }
}
impl<T> MaybeAsRef<SpanContext<T>> for Span<T> {
    fn maybe_as_ref(&self) -> Option<&SpanContext<T>> {
        self.context()
    }
}

#[derive(Debug)]
struct SpanInner<T> {
    operation_name: Cow<'static, str>,
    start_time: SystemTime,
    finish_time: Option<SystemTime>,
    references: Vec<SpanReference<T>>,
    tags: Vec<Tag>,
    logs: Vec<Log>,
    context: SpanContext<T>,
    span_tx: SpanSender<T>,
}

/// Finished span.
#[derive(Debug)]
pub struct FinishedSpan<T> {
    operation_name: Cow<'static, str>,
    start_time: SystemTime,
    finish_time: SystemTime,
    references: Vec<SpanReference<T>>,
    tags: Vec<Tag>,
    logs: Vec<Log>,
    context: SpanContext<T>,
}
impl<T> FinishedSpan<T> {
    /// Returns the operation name of this span.
    pub fn operation_name(&self) -> &str {
        self.operation_name.as_ref()
    }

    /// Returns the start time of this span.
    pub fn start_time(&self) -> SystemTime {
        self.start_time
    }

    /// Returns the finish time of this span.
    pub fn finish_time(&self) -> SystemTime {
        self.finish_time
    }

    /// Returns the logs recorded during this span.
    pub fn logs(&self) -> &[Log] {
        &self.logs
    }

    /// Returns the tags of this span.
    pub fn tags(&self) -> &[Tag] {
        &self.tags
    }

    /// Returns the references of this span.
    pub fn references(&self) -> &[SpanReference<T>] {
        &self.references
    }

    /// Returns the context of this span.
    pub fn context(&self) -> &SpanContext<T> {
        &self.context
    }
}

/// Span context.
///
/// Each `SpanContext` encapsulates the following state:
///
/// - `T`: OpenTracing-implementation-dependent state (for example, trace and span ids) needed to refer to a distinct `Span` across a process boundary
/// - `BaggageItems`: These are just key:value pairs that cross process boundaries
#[derive(Debug, Clone)]
pub struct SpanContext<T> {
    state: T,
    baggage_items: Vec<BaggageItem>,
}
impl<T> SpanContext<T> {
    /// Makes a new `SpanContext` instance.
    pub fn new(state: T, mut baggage_items: Vec<BaggageItem>) -> Self {
        baggage_items.reverse();
        baggage_items.sort_by(|a, b| a.name().cmp(b.name()));
        baggage_items.dedup_by(|a, b| a.name() == b.name());
        SpanContext {
            state,
            baggage_items,
        }
    }

    /// Returns the implementation-dependent state of this context.
    pub fn state(&self) -> &T {
        &self.state
    }

    /// Returns the baggage items associated with this context.
    pub fn baggage_items(&self) -> &[BaggageItem] {
        &self.baggage_items
    }

    /// Injects this context to the **Text Map** `carrier`.
    pub fn inject_to_text_map<C>(&self, carrier: &mut C) -> Result<()>
    where
        C: carrier::TextMap,
        T: carrier::InjectToTextMap<C>,
    {
        track!(T::inject_to_text_map(self, carrier))
    }

    /// Injects this context to the **HTTP Header** `carrier`.
    pub fn inject_to_http_header<C>(&self, carrier: &mut C) -> Result<()>
    where
        C: carrier::SetHttpHeaderField,
        T: carrier::InjectToHttpHeader<C>,
    {
        track!(T::inject_to_http_header(self, carrier))
    }

    /// Injects this context to the **Binary** `carrier`.
    pub fn inject_to_binary<C>(&self, carrier: &mut C) -> Result<()>
    where
        C: Write,
        T: carrier::InjectToBinary<C>,
    {
        track!(T::inject_to_binary(self, carrier))
    }

    /// Extracts a context from the **Text Map** `carrier`.
    pub fn extract_from_text_map<C>(carrier: &C) -> Result<Option<Self>>
    where
        C: carrier::TextMap,
        T: carrier::ExtractFromTextMap<C>,
    {
        track!(T::extract_from_text_map(carrier))
    }

    /// Extracts a context from the **HTTP Header** `carrier`.
    pub fn extract_from_http_header<'a, C>(carrier: &'a C) -> Result<Option<Self>>
    where
        C: carrier::IterHttpHeaderFields<'a>,
        T: carrier::ExtractFromHttpHeader<'a, C>,
    {
        track!(T::extract_from_http_header(carrier))
    }

    /// Extracts a context from the **Binary** `carrier`.
    pub fn extract_from_binary<C>(carrier: &mut C) -> Result<Option<Self>>
    where
        C: Read,
        T: carrier::ExtractFromBinary<C>,
    {
        track!(T::extract_from_binary(carrier))
    }
}
impl<T> MaybeAsRef<SpanContext<T>> for SpanContext<T> {
    fn maybe_as_ref(&self) -> Option<&Self> {
        Some(self)
    }
}

/// Baggage item.
///
/// `BaggageItem`s are key:value string pairs that apply to a `Span`, its `SpanContext`,
/// and all `Span`s which directly or transitively reference the local `Span`.
/// That is, `BaggageItem`s propagate in-band along with the trace itself.
///
/// `BaggageItem`s enable powerful functionality given a full-stack OpenTracing integration
/// (for example, arbitrary application data from a mobile app can make it, transparently,
/// all the way into the depths of a storage system),
/// and with it some powerful costs: use this feature with care.
///
/// Use this feature thoughtfully and with care.
/// Every key and value is copied into every local and remote child of the associated `Span`,
/// and that can add up to a lot of network and cpu overhead.
#[derive(Debug, Clone)]
pub struct BaggageItem {
    name: String,
    value: String,
}
impl BaggageItem {
    /// Makes a new `BaggageItem` instance.
    pub fn new(name: &str, value: &str) -> Self {
        BaggageItem {
            name: name.to_owned(),
            value: value.to_owned(),
        }
    }

    /// Returns the name of this item.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the value of this item.
    pub fn value(&self) -> &str {
        &self.value
    }
}

/// Span reference.
#[derive(Debug, Clone)]
#[allow(missing_docs)]
pub enum SpanReference<T> {
    ChildOf(T),
    FollowsFrom(T),
}
impl<T> SpanReference<T> {
    /// Returns the span context state of this reference.
    pub fn span(&self) -> &T {
        match *self {
            SpanReference::ChildOf(ref x) | SpanReference::FollowsFrom(ref x) => x,
        }
    }

    /// Returns `true` if this is a `ChildOf` reference.
    pub fn is_child_of(&self) -> bool {
        if let SpanReference::ChildOf(_) = *self {
            true
        } else {
            false
        }
    }

    /// Returns `true` if this is a `FollowsFrom` reference.
    pub fn is_follows_from(&self) -> bool {
        if let SpanReference::FollowsFrom(_) = *self {
            true
        } else {
            false
        }
    }
}

/// Candidate span for tracing.
#[derive(Debug)]
pub struct CandidateSpan<'a, T: 'a> {
    tags: &'a [Tag],
    references: &'a [SpanReference<T>],
    baggage_items: &'a [BaggageItem],
}
impl<'a, T: 'a> CandidateSpan<'a, T> {
    /// Returns the tags of this span.
    pub fn tags(&self) -> &[Tag] {
        self.tags
    }

    /// Returns the references of this span.
    pub fn references(&self) -> &[SpanReference<T>] {
        self.references
    }

    /// Returns the baggage items of this span.
    pub fn baggage_items(&self) -> &[BaggageItem] {
        self.baggage_items
    }
}

/// Options for starting a span.
#[derive(Debug)]
pub struct StartSpanOptions<'a, S: 'a, T: 'a> {
    operation_name: Cow<'static, str>,
    start_time: Option<SystemTime>,
    tags: Vec<Tag>,
    references: Vec<SpanReference<T>>,
    baggage_items: Vec<BaggageItem>,
    span_tx: &'a SpanSender<T>,
    sampler: &'a S,
}
impl<'a, S: 'a, T: 'a> StartSpanOptions<'a, S, T>
where
    S: Sampler<T>,
{
    /// Sets the start time of this span.
    pub fn start_time(mut self, time: SystemTime) -> Self {
        self.start_time = Some(time);
        self
    }

    /// Sets the tag to this span.
    pub fn tag(mut self, tag: Tag) -> Self {
        self.tags.push(tag);
        self
    }

    /// Adds the `ChildOf` reference to this span.
    pub fn child_of<C>(mut self, context: &C) -> Self
    where
        C: MaybeAsRef<SpanContext<T>>,
        T: Clone,
    {
        if let Some(context) = context.maybe_as_ref() {
            let reference = SpanReference::ChildOf(context.state().clone());
            self.references.push(reference);
            self.baggage_items
                .extend(context.baggage_items().iter().cloned());
        }
        self
    }

    /// Adds the `FollowsFrom` reference to this span.
    pub fn follows_from<C>(mut self, context: &C) -> Self
    where
        C: MaybeAsRef<SpanContext<T>>,
        T: Clone,
    {
        if let Some(context) = context.maybe_as_ref() {
            let reference = SpanReference::FollowsFrom(context.state().clone());
            self.references.push(reference);
            self.baggage_items
                .extend(context.baggage_items().iter().cloned());
        }
        self
    }

    /// Starts a new span.
    pub fn start(mut self) -> Span<T>
    where
        T: for<'b> From<CandidateSpan<'b, T>>,
    {
        self.normalize();
        if !self.is_sampled() {
            return Span(None);
        }
        let state = T::from(self.span());
        Span::new(
            self.operation_name,
            self.start_time.unwrap_or_else(SystemTime::now),
            self.references,
            self.tags,
            state,
            self.baggage_items,
            self.span_tx.clone(),
        )
    }

    /// Starts a new span with the explicit `state`.
    pub fn start_with_state(mut self, state: T) -> Span<T> {
        self.normalize();
        if !self.is_sampled() {
            return Span(None);
        }
        Span::new(
            self.operation_name,
            self.start_time.unwrap_or_else(SystemTime::now),
            self.references,
            self.tags,
            state,
            self.baggage_items,
            self.span_tx.clone(),
        )
    }

    pub(crate) fn new<N>(operation_name: N, span_tx: &'a SpanSender<T>, sampler: &'a S) -> Self
    where
        N: Into<Cow<'static, str>>,
    {
        StartSpanOptions {
            operation_name: operation_name.into(),
            start_time: None,
            tags: Vec::new(),
            references: Vec::new(),
            baggage_items: Vec::new(),
            span_tx,
            sampler,
        }
    }

    fn normalize(&mut self) {
        self.tags.reverse();
        self.tags.sort_by(|a, b| a.name().cmp(b.name()));
        self.tags.dedup_by(|a, b| a.name() == b.name());

        self.baggage_items.reverse();
        self.baggage_items.sort_by(|a, b| a.name().cmp(b.name()));
        self.baggage_items.dedup_by(|a, b| a.name() == b.name());
    }

    fn span(&self) -> CandidateSpan<T> {
        CandidateSpan {
            references: &self.references,
            tags: &self.tags,
            baggage_items: &self.baggage_items,
        }
    }

    fn is_sampled(&self) -> bool {
        if let Some(&TagValue::Integer(n)) = self
            .tags
            .iter()
            .find(|t| t.name() == "sampling.priority")
            .map(|t| t.value())
        {
            n > 0
        } else {
            self.sampler.is_sampled(&self.span())
        }
    }
}

/// Immutable handle of `Span`.
#[derive(Debug, Clone)]
pub struct SpanHandle<T>(Option<(SpanContext<T>, SpanSender<T>)>);
impl<T> SpanHandle<T> {
    /// Returns `true` if this span is sampled (i.e., being traced).
    pub fn is_sampled(&self) -> bool {
        self.0.is_some()
    }

    /// Returns the context of this span.
    pub fn context(&self) -> Option<&SpanContext<T>> {
        self.0.as_ref().map(|&(ref context, _)| context)
    }

    /// Gets the baggage item that has the name `name`.
    pub fn get_baggage_item(&self, name: &str) -> Option<&BaggageItem> {
        if let Some(context) = self.context() {
            context.baggage_items.iter().find(|x| x.name == name)
        } else {
            None
        }
    }

    /// Starts a `ChildOf` span if this span is sampled.
    pub fn child<N, F>(&self, operation_name: N, f: F) -> Span<T>
    where
        N: Into<Cow<'static, str>>,
        T: Clone,
        F: FnOnce(StartSpanOptions<AllSampler, T>) -> Span<T>,
    {
        if let Some(&(ref context, ref span_tx)) = self.0.as_ref() {
            let options =
                StartSpanOptions::new(operation_name, span_tx, &AllSampler).child_of(context);
            f(options)
        } else {
            Span::inactive()
        }
    }

    /// Starts a `FollowsFrom` span if this span is sampled.
    pub fn follower<N, F>(&self, operation_name: N, f: F) -> Span<T>
    where
        N: Into<Cow<'static, str>>,
        T: Clone,
        F: FnOnce(StartSpanOptions<AllSampler, T>) -> Span<T>,
    {
        if let Some(&(ref context, ref span_tx)) = self.0.as_ref() {
            let options =
                StartSpanOptions::new(operation_name, span_tx, &AllSampler).follows_from(context);
            f(options)
        } else {
            Span::inactive()
        }
    }
}