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
use crate::util::{http_method_str, http_url};
use actix_http::{encoding::Decoder, BoxedPayloadStream, Error, Payload};
use actix_web::{
body::MessageBody,
http::{
self,
header::{HeaderName, HeaderValue},
},
web::Bytes,
};
use awc::{
error::SendRequestError,
http::header::{CONTENT_LENGTH, USER_AGENT},
ClientRequest, ClientResponse,
};
use futures_util::{future::TryFutureExt as _, Future, Stream};
use opentelemetry::{
global,
propagation::Injector,
trace::{SpanKind, Status, TraceContextExt, Tracer, TracerProvider},
Context, KeyValue,
};
use opentelemetry_semantic_conventions::trace::{
HTTP_FLAVOR, HTTP_METHOD, HTTP_REQUEST_CONTENT_LENGTH, HTTP_STATUS_CODE, HTTP_URL,
HTTP_USER_AGENT, NET_PEER_IP, NET_PEER_NAME, NET_PEER_PORT,
};
use serde::Serialize;
use std::fmt::{self, Debug};
use std::mem;
use std::str::FromStr;
pub struct InstrumentedClientRequest {
cx: Context,
attrs: Vec<KeyValue>,
span_namer: fn(&ClientRequest) -> String,
request: ClientRequest,
}
impl Debug for InstrumentedClientRequest {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let span_namer = fmt::Pointer::fmt(&(self.span_namer as usize as *const ()), f);
f.debug_struct("InstrumentedClientRequest")
.field("cx", &self.cx)
.field("attrs", &self.attrs)
.field("span_namer", &span_namer)
.field("request", &self.request)
.finish()
}
}
fn default_span_namer(request: &ClientRequest) -> String {
format!(
"{} {}",
request.get_method(),
request.get_uri().host().unwrap_or_default()
)
}
pub trait ClientExt {
fn trace_request(self) -> InstrumentedClientRequest
where
Self: Sized,
{
self.trace_request_with_context(Context::current())
}
fn trace_request_with_context(self, cx: Context) -> InstrumentedClientRequest;
}
impl ClientExt for ClientRequest {
fn trace_request_with_context(self, cx: Context) -> InstrumentedClientRequest {
InstrumentedClientRequest {
cx,
attrs: Vec::new(),
span_namer: default_span_namer,
request: self,
}
}
}
type AwcResult = Result<ClientResponse<Decoder<Payload<BoxedPayloadStream>>>, SendRequestError>;
impl InstrumentedClientRequest {
pub async fn send(self) -> AwcResult {
self.trace_request(|request| request.send()).await
}
pub async fn send_body<B>(self, body: B) -> AwcResult
where
B: MessageBody + 'static,
{
self.trace_request(|request| request.send_body(body)).await
}
pub async fn send_form<T: Serialize>(self, value: &T) -> AwcResult {
self.trace_request(|request| request.send_form(value)).await
}
pub async fn send_json<T: Serialize>(self, value: &T) -> AwcResult {
self.trace_request(|request| request.send_json(value)).await
}
pub async fn send_stream<S, E>(self, stream: S) -> AwcResult
where
S: Stream<Item = Result<Bytes, E>> + Unpin + 'static,
E: std::error::Error + Into<Error> + 'static,
{
self.trace_request(|request| request.send_stream(stream))
.await
}
async fn trace_request<F, R>(mut self, f: F) -> AwcResult
where
F: FnOnce(ClientRequest) -> R,
R: Future<Output = AwcResult>,
{
let tracer = global::tracer_provider().versioned_tracer(
"actix-web-opentelemetry",
Some(env!("CARGO_PKG_VERSION")),
None,
);
self.attrs.extend(
&mut [
KeyValue::new(HTTP_METHOD, http_method_str(self.request.get_method())),
KeyValue::new(HTTP_URL, http_url(self.request.get_uri())),
KeyValue::new(HTTP_FLAVOR, format!("{:?}", self.request.get_version())),
]
.into_iter(),
);
if let Some(user_agent) = self
.request
.headers()
.get(USER_AGENT)
.and_then(|len| len.to_str().ok())
{
self.attrs
.push(KeyValue::new(HTTP_USER_AGENT, user_agent.to_string()))
}
if let Some(content_length) = self.request.headers().get(CONTENT_LENGTH).and_then(|len| {
len.to_str()
.ok()
.and_then(|str_len| str_len.parse::<i64>().ok())
}) {
self.attrs
.push(KeyValue::new(HTTP_REQUEST_CONTENT_LENGTH, content_length))
}
if let Some(host) = self.request.get_uri().host() {
self.attrs
.push(KeyValue::new(NET_PEER_NAME, host.to_string()));
}
if let Some(peer_addr) = self.request.get_peer_addr() {
self.attrs.push(NET_PEER_IP.string(peer_addr.to_string()));
}
if let Some(peer_port) = self.request.get_uri().port_u16() {
if peer_port != 80 && peer_port != 443 {
self.attrs.push(NET_PEER_PORT.i64(peer_port.into()));
}
}
let span = tracer
.span_builder((self.span_namer)(&self.request))
.with_kind(SpanKind::Client)
.with_attributes(mem::take(&mut self.attrs))
.start_with_context(&tracer, &self.cx);
let cx = self.cx.with_span(span);
global::get_text_map_propagator(|injector| {
injector.inject_context(&cx, &mut ActixClientCarrier::new(&mut self.request));
});
f(self.request)
.inspect_ok(|res| record_response(res, &cx))
.inspect_err(|err| record_err(err, &cx))
.await
}
pub fn with_attributes(
mut self,
attrs: impl IntoIterator<Item = KeyValue>,
) -> InstrumentedClientRequest {
self.attrs.extend(&mut attrs.into_iter());
self
}
pub fn with_span_namer(
mut self,
span_namer: fn(&ClientRequest) -> String,
) -> InstrumentedClientRequest {
self.span_namer = span_namer;
self
}
}
fn convert_status(status: http::StatusCode) -> Status {
match status.as_u16() {
100..=399 => Status::Unset,
400..=599 => Status::error(""),
code => Status::error(format!("Invalid HTTP status code {}", code)),
}
}
fn record_response<T>(response: &ClientResponse<T>, cx: &Context) {
let span = cx.span();
let status = convert_status(response.status());
span.set_status(status);
span.set_attribute(HTTP_STATUS_CODE.i64(response.status().as_u16() as i64));
span.end();
}
fn record_err<T: fmt::Debug>(err: T, cx: &Context) {
let span = cx.span();
span.set_status(Status::error(format!("{:?}", err)));
span.end();
}
struct ActixClientCarrier<'a> {
request: &'a mut ClientRequest,
}
impl<'a> ActixClientCarrier<'a> {
fn new(request: &'a mut ClientRequest) -> Self {
ActixClientCarrier { request }
}
}
impl<'a> Injector for ActixClientCarrier<'a> {
fn set(&mut self, key: &str, value: String) {
let header_name = HeaderName::from_str(key).expect("Must be header name");
let header_value = HeaderValue::from_str(&value).expect("Must be a header value");
self.request.headers_mut().insert(header_name, header_value);
}
}