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
use crate::api::trace::TraceError;
#[cfg(all(feature = "http", any(feature = "surf", feature = "reqwest")))]
use crate::sdk::export::ExportError;
use crate::{
sdk,
trace::{Event, Link, SpanContext, SpanId, SpanKind, StatusCode},
};
use async_trait::async_trait;
#[cfg(feature = "http")]
use http::Request;
#[cfg(feature = "serialize")]
use serde::{Deserialize, Serialize};
#[cfg(all(feature = "http", feature = "reqwest"))]
use std::convert::TryInto;
use std::fmt::Debug;
#[cfg(all(feature = "surf", feature = "http"))]
use std::fmt::{Display, Formatter};
use std::sync::Arc;
use std::time::SystemTime;
pub mod stdout;
pub type ExportResult = Result<(), TraceError>;
#[async_trait]
pub trait SpanExporter: Send + Debug {
async fn export(&mut self, batch: Vec<SpanData>) -> ExportResult;
fn shutdown(&mut self) {}
}
#[cfg(feature = "http")]
#[cfg_attr(docsrs, doc(cfg(feature = "http")))]
#[async_trait]
pub trait HttpClient: Debug + Send + Sync {
async fn send(&self, request: Request<Vec<u8>>) -> ExportResult;
}
#[cfg(all(feature = "reqwest", feature = "http"))]
impl ExportError for reqwest::Error {
fn exporter_name(&self) -> &'static str {
"reqwest"
}
}
#[cfg(all(feature = "surf", feature = "http"))]
impl ExportError for SurfError {
fn exporter_name(&self) -> &'static str {
"surf"
}
}
#[cfg(all(feature = "surf", feature = "http"))]
#[derive(Debug)]
struct SurfError(surf::Error);
#[cfg(all(feature = "surf", feature = "http"))]
impl Display for SurfError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0.to_string())
}
}
#[cfg(all(feature = "surf", feature = "http"))]
impl std::error::Error for SurfError {}
#[cfg(all(feature = "surf", feature = "http"))]
impl From<surf::Error> for SurfError {
fn from(err: surf::Error) -> Self {
SurfError(err)
}
}
#[cfg_attr(feature = "serialize", derive(Deserialize, Serialize))]
#[derive(Clone, Debug, PartialEq)]
pub struct SpanData {
pub span_context: SpanContext,
pub parent_span_id: SpanId,
pub span_kind: SpanKind,
pub name: String,
pub start_time: SystemTime,
pub end_time: SystemTime,
pub attributes: sdk::trace::EvictedHashMap,
pub message_events: sdk::trace::EvictedQueue<Event>,
pub links: sdk::trace::EvictedQueue<Link>,
pub status_code: StatusCode,
pub status_message: String,
pub resource: Arc<sdk::Resource>,
#[cfg_attr(feature = "serialize", serde(skip))]
pub instrumentation_lib: sdk::InstrumentationLibrary,
}
#[cfg(all(feature = "reqwest", feature = "http"))]
#[async_trait]
impl HttpClient for reqwest::Client {
async fn send(&self, request: Request<Vec<u8>>) -> ExportResult {
let _result = self
.execute(request.try_into()?)
.await?
.error_for_status()?;
Ok(())
}
}
#[cfg(all(feature = "reqwest", feature = "http"))]
#[async_trait]
impl HttpClient for reqwest::blocking::Client {
async fn send(&self, request: Request<Vec<u8>>) -> ExportResult {
let _result = self.execute(request.try_into()?)?.error_for_status()?;
Ok(())
}
}
#[cfg(all(feature = "surf", feature = "http"))]
#[async_trait]
impl HttpClient for surf::Client {
async fn send(&self, request: Request<Vec<u8>>) -> ExportResult {
let (parts, body) = request.into_parts();
let uri = parts
.uri
.to_string()
.parse()
.map_err(|_err: surf::http::url::ParseError| TraceError::from("error parse url"))?;
let req = surf::Request::builder(surf::http::Method::Post, uri)
.content_type("application/json")
.body(body);
let result = self.send(req).await.map_err::<SurfError, _>(Into::into)?;
if result.status().is_success() {
Ok(())
} else {
Err(SurfError(surf::Error::from_str(
result.status(),
result.status().canonical_reason(),
))
.into())
}
}
}
#[cfg(feature = "serialize")]
#[cfg(test)]
mod tests {
use super::*;
use crate::trace::{TraceId, TraceState};
#[test]
fn test_serialise() {
let trace_id = 7;
let span_id = 99;
let trace_flags = 0;
let remote = false;
let span_context = SpanContext::new(
TraceId::from_u128(trace_id),
SpanId::from_u64(span_id),
trace_flags,
remote,
TraceState::default(),
);
let parent_span_id = 1;
let span_kind = SpanKind::Client;
let name = "foo/bar baz 人?!".to_string();
let start_time = crate::time::now();
let end_time = crate::time::now();
let capacity = 3;
let attributes = sdk::trace::EvictedHashMap::new(capacity, 0);
let message_events = sdk::trace::EvictedQueue::new(capacity);
let links = sdk::trace::EvictedQueue::new(capacity);
let status_code = StatusCode::Ok;
let status_message = String::new();
let resource = Arc::new(sdk::Resource::default());
let span_data = SpanData {
span_context,
parent_span_id: SpanId::from_u64(parent_span_id),
span_kind,
name,
start_time,
end_time,
attributes,
message_events,
links,
status_code,
status_message,
resource,
instrumentation_lib: sdk::InstrumentationLibrary::new("", None),
};
let encoded: Vec<u8> = bincode::serialize(&span_data).unwrap();
let decoded: SpanData = bincode::deserialize(&encoded[..]).unwrap();
assert_eq!(span_data, decoded);
}
}