use crate::rustracing::carrier::{ExtractFromBinary, InjectToBinary};
use crate::span::HSpan;
use crate::span_wrap::SpanWrap;
use rustracing::sampler::*;
use rustracing::span::StartSpanOptions;
use rustracing_jaeger::{
span::{SpanContext, SpanContextState},
Tracer,
};
use rustracing_jaeger::{Result, Span as RjSpan};
use std::{borrow::Cow, io::Cursor};
pub type EncodedSpanContext = Vec<u8>;
#[derive(Clone, Debug)]
pub struct HSpanContext(pub SpanContext);
impl HSpanContext {
pub fn follower<S: Into<Cow<'static, str>>>(
&self,
tracer: &Tracer,
operation_name: S,
) -> HSpan {
tracer
.span(operation_name)
.follows_from(&self.0)
.start()
.into()
}
pub fn follower_<'a, N: Into<Cow<'static, str>>, F>(
&'a self,
tracer: &Tracer,
operation_name: N,
f: F,
) -> HSpan
where
F: FnOnce(StartSpanOptions<'_, BoxSampler<SpanContextState>, SpanContextState>) -> RjSpan,
{
f(tracer.span(operation_name).follows_from(&self.0)).into()
}
pub fn encode(&self) -> Result<EncodedSpanContext> {
let mut enc: Vec<u8> = [0; 37].to_vec(); let mut slice = &mut enc[..];
SpanContextState::inject_to_binary(&self.0, &mut slice)?;
Ok(enc)
}
pub fn decode(enc: &EncodedSpanContext) -> Result<Self> {
let mut cursor = Cursor::new(enc);
SpanContextState::extract_from_binary(&mut cursor).map(|x| HSpanContext(x.unwrap()))
}
pub fn wrap<T>(self, data: T) -> SpanWrap<T> {
SpanWrap::new(data, Some(self))
}
}