-
Notifications
You must be signed in to change notification settings - Fork 384
/
collector.rs
247 lines (216 loc) · 8.72 KB
/
collector.rs
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
//! # HTTP Jaeger Collector Client
use http::Uri;
use std::sync::atomic::AtomicUsize;
/// `CollectorAsyncClientHttp` implements an async version of the
/// `TCollectorSyncClient` interface over HTTP
#[derive(Debug)]
pub(crate) struct CollectorAsyncClientHttp {
endpoint: Uri,
#[cfg(feature = "collector_client")]
client: isahc::HttpClient,
#[cfg(all(feature = "wasm_collector_client", not(feature = "collector_client")))]
client: WasmHttpClient,
payload_size_estimate: AtomicUsize,
}
#[cfg(feature = "wasm_collector_client")]
#[derive(Debug)]
struct WasmHttpClient {
auth: Option<String>,
}
#[cfg(feature = "collector_client")]
mod collector_client {
use super::*;
use crate::exporter::thrift::jaeger;
use http::{Request, Uri};
use isahc::{
auth::{Authentication, Credentials},
config::Configurable,
HttpClient,
};
use std::io::{self, Cursor};
use std::sync::atomic::{AtomicUsize, Ordering};
use thrift::protocol::TBinaryOutputProtocol;
impl CollectorAsyncClientHttp {
/// Create a new HTTP collector client
pub(crate) fn new(
endpoint: Uri,
username: Option<String>,
password: Option<String>,
) -> thrift::Result<Self> {
let mut builder = HttpClient::builder();
if let (Some(username), Some(password)) = (username, password) {
builder = builder
.authentication(Authentication::basic())
.credentials(Credentials::new(username, password));
}
let client = builder
.build()
.map_err(|err| io::Error::new(io::ErrorKind::Other, err.to_string()))?;
let payload_size_estimate = AtomicUsize::new(512);
Ok(CollectorAsyncClientHttp {
endpoint,
client,
payload_size_estimate,
})
}
/// Submit list of Jaeger batches
pub(crate) async fn submit_batch(
&self,
batch: jaeger::Batch,
) -> thrift::Result<jaeger::BatchSubmitResponse> {
// estimate transport capacity based on last request
let estimate = self.payload_size_estimate.load(Ordering::Relaxed);
// Write payload to transport buffer
let transport = Cursor::new(Vec::with_capacity(estimate));
let mut protocol = TBinaryOutputProtocol::new(transport, true);
batch.write_to_out_protocol(&mut protocol)?;
// Use current batch capacity as new estimate
self.payload_size_estimate
.store(protocol.transport.get_ref().len(), Ordering::Relaxed);
// Build collector request
let req = Request::builder()
.method("POST")
.uri(&self.endpoint)
.header("Content-Type", "application/vnd.apache.thrift.binary")
.body(protocol.transport.into_inner())
.expect("request should always be valid");
// Send request to collector
let res = self
.client
.send_async(req)
.await
.map_err(|err| io::Error::new(io::ErrorKind::Other, err.to_string()))?;
if !res.status().is_success() {
return Err(thrift::Error::from(io::Error::new(
io::ErrorKind::Other,
format!("Expected success response, got {:?}", res.status()),
)));
}
Ok(jaeger::BatchSubmitResponse { ok: true })
}
}
}
#[cfg(all(feature = "wasm_collector_client", not(feature = "collector_client")))]
mod wasm_collector_client {
use super::*;
use crate::exporter::thrift::jaeger;
use futures_util::future;
use http::Uri;
use js_sys::Uint8Array;
use std::future::Future;
use std::io::{self, Cursor};
use std::pin::Pin;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::task::{Context, Poll};
use thrift::protocol::TBinaryOutputProtocol;
use wasm_bindgen::JsCast;
use wasm_bindgen_futures::JsFuture;
use web_sys::{Request, RequestCredentials, RequestInit, RequestMode, Response};
impl CollectorAsyncClientHttp {
/// Create a new HTTP collector client
pub(crate) fn new(
endpoint: Uri,
username: Option<String>,
password: Option<String>,
) -> thrift::Result<Self> {
let auth = if let (Some(username), Some(password)) = (username, password) {
let mut auth = String::from("Basic ");
base64::encode_config_buf(username, base64::STANDARD, &mut auth);
auth.push(':');
base64::encode_config_buf(password, base64::STANDARD, &mut auth);
Some(auth)
} else {
None
};
let payload_size_estimate = AtomicUsize::new(512);
Ok(Self {
endpoint,
client: WasmHttpClient { auth },
payload_size_estimate,
})
}
/// Submit list of Jaeger batches
pub(crate) fn submit_batch(
&self,
batch: jaeger::Batch,
) -> impl Future<Output = thrift::Result<jaeger::BatchSubmitResponse>> + Send + 'static
{
self.build_request(batch)
.map(post_request)
.map(|fut| future::Either::Left(SubmitBatchFuture(fut)))
.unwrap_or_else(|e| future::Either::Right(future::err(e)))
}
fn build_request(&self, batch: jaeger::Batch) -> thrift::Result<Request> {
// estimate transport capacity based on last request
let estimate = self.payload_size_estimate.load(Ordering::Relaxed);
// Write payload to transport buffer
let transport = Cursor::new(Vec::with_capacity(estimate));
let mut protocol = TBinaryOutputProtocol::new(transport, true);
batch.write_to_out_protocol(&mut protocol)?;
// Use current batch capacity as new estimate
self.payload_size_estimate
.store(protocol.transport.get_ref().len(), Ordering::Relaxed);
// Build collector request
let mut options = RequestInit::new();
options.method("POST");
options.mode(RequestMode::Cors);
let body: Uint8Array = protocol.transport.get_ref().as_slice().into();
options.body(Some(body.as_ref()));
if self.client.auth.is_some() {
options.credentials(RequestCredentials::Include);
}
let request = Request::new_with_str_and_init(&self.endpoint.to_string(), &options)
.map_err(jsvalue_into_ioerror)?;
let headers = request.headers();
headers
.set("Content-Type", "application/vnd.apache.thrift.binary")
.map_err(jsvalue_into_ioerror)?;
if let Some(auth) = self.client.auth.as_ref() {
headers
.set("Authorization", auth)
.map_err(jsvalue_into_ioerror)?;
}
Ok(request)
}
}
async fn post_request(request: Request) -> thrift::Result<jaeger::BatchSubmitResponse> {
// Send request to collector
let window = web_sys::window().unwrap();
let res_value = JsFuture::from(window.fetch_with_request(&request))
.await
.map_err(jsvalue_into_ioerror)?;
let res: Response = res_value.dyn_into().unwrap();
if !res.ok() {
return Err(thrift::Error::from(io::Error::new(
io::ErrorKind::Other,
format!(
"Expected success response, got {} ({})",
res.status(),
res.status_text()
),
)));
}
Ok(jaeger::BatchSubmitResponse { ok: true })
}
/// Wrapper of web fetch API future marked as Send.
///
/// At the moment, the web APIs are single threaded. Since all opentelemetry futures are
/// required to be Send, we mark this future as Send.
#[pin_project::pin_project]
struct SubmitBatchFuture<F>(#[pin] F);
unsafe impl<F> Send for SubmitBatchFuture<F> {}
impl<F: Future> Future for SubmitBatchFuture<F> {
type Output = F::Output;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
self.project().0.poll(cx)
}
}
fn jsvalue_into_ioerror(value: wasm_bindgen::JsValue) -> io::Error {
io::Error::new(
io::ErrorKind::Other,
js_sys::JSON::stringify(&value)
.map(String::from)
.unwrap_or_else(|_| "unknown error".to_string()),
)
}
}