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
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
#![cfg(not(doctest))]
#![allow(
rustdoc::bare_urls,
rustdoc::broken_intra_doc_links,
rustdoc::invalid_rust_codeblocks
)]
use std::{
collections::HashMap,
convert::TryFrom,
fmt,
future::Future,
sync::{
atomic::{AtomicUsize, Ordering},
Arc,
},
time::{Duration, Instant},
};
use async_trait::async_trait;
use futures::{future::BoxFuture, stream::StreamExt};
use opentelemetry::{
global::handle_error,
sdk::{
export::{
trace::{ExportResult, SpanData, SpanExporter},
ExportError,
},
trace::EvictedHashMap,
},
trace::TraceError,
Key, Value,
};
use opentelemetry_semantic_conventions::resource::SERVICE_NAME;
use opentelemetry_semantic_conventions::trace::{
HTTP_HOST, HTTP_METHOD, HTTP_ROUTE, HTTP_STATUS_CODE, HTTP_TARGET, HTTP_URL, HTTP_USER_AGENT,
};
use thiserror::Error;
#[cfg(any(feature = "yup-authorizer", feature = "gcp_auth"))]
use tonic::metadata::MetadataValue;
use tonic::{
transport::{Channel, ClientTlsConfig},
Request,
};
#[cfg(feature = "yup-authorizer")]
use yup_oauth2::authenticator::Authenticator;
#[allow(clippy::derive_partial_eq_without_eq)] pub mod proto;
use proto::devtools::cloudtrace::v2::BatchWriteSpansRequest;
use proto::devtools::cloudtrace::v2::{
span::{time_event::Annotation, Attributes, TimeEvent, TimeEvents},
trace_service_client::TraceServiceClient,
AttributeValue, Span, TruncatableString,
};
use proto::logging::v2::{
log_entry::Payload, logging_service_v2_client::LoggingServiceV2Client, LogEntry,
LogEntrySourceLocation, WriteLogEntriesRequest,
};
#[derive(Clone)]
pub struct StackDriverExporter {
tx: futures::channel::mpsc::Sender<Vec<SpanData>>,
pending_count: Arc<AtomicUsize>,
maximum_shutdown_duration: Duration,
}
impl StackDriverExporter {
pub fn builder() -> Builder {
Builder::default()
}
pub fn pending_count(&self) -> usize {
self.pending_count.load(Ordering::Relaxed)
}
}
impl SpanExporter for StackDriverExporter {
fn export(&mut self, batch: Vec<SpanData>) -> BoxFuture<'static, ExportResult> {
match self.tx.try_send(batch) {
Err(e) => Box::pin(std::future::ready(Err(e.into()))),
Ok(()) => {
self.pending_count.fetch_add(1, Ordering::Relaxed);
Box::pin(std::future::ready(Ok(())))
}
}
}
fn shutdown(&mut self) {
let start = Instant::now();
while (Instant::now() - start) < self.maximum_shutdown_duration && self.pending_count() > 0
{
std::thread::yield_now();
}
}
}
impl fmt::Debug for StackDriverExporter {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
#[allow(clippy::unneeded_field_pattern)]
let Self {
tx: _,
pending_count,
maximum_shutdown_duration,
} = self;
f.debug_struct("StackDriverExporter")
.field("tx", &"(elided)")
.field("pending_count", pending_count)
.field("maximum_shutdown_duration", maximum_shutdown_duration)
.finish()
}
}
#[derive(Clone, Default)]
pub struct Builder {
maximum_shutdown_duration: Option<Duration>,
num_concurrent_requests: Option<usize>,
log_context: Option<LogContext>,
}
impl Builder {
pub fn maximum_shutdown_duration(mut self, duration: Duration) -> Self {
self.maximum_shutdown_duration = Some(duration);
self
}
pub fn num_concurrent_requests(mut self, num_concurrent_requests: usize) -> Self {
self.num_concurrent_requests = Some(num_concurrent_requests);
self
}
pub fn log_context(mut self, log_context: LogContext) -> Self {
self.log_context = Some(log_context);
self
}
pub async fn build<A: Authorizer>(
self,
authenticator: A,
) -> Result<(StackDriverExporter, impl Future<Output = ()>), Error>
where
Error: From<A::Error>,
{
let Self {
maximum_shutdown_duration,
num_concurrent_requests,
log_context,
} = self;
let uri = http::uri::Uri::from_static("https://cloudtrace.googleapis.com:443");
let trace_channel = Channel::builder(uri)
.tls_config(ClientTlsConfig::new())
.map_err(|e| Error::Transport(e.into()))?
.connect()
.await
.map_err(|e| Error::Transport(e.into()))?;
let log_client = match log_context {
Some(log_context) => {
let log_channel = Channel::builder(http::uri::Uri::from_static(
"https://logging.googleapis.com:443",
))
.tls_config(ClientTlsConfig::new())
.map_err(|e| Error::Transport(e.into()))?
.connect()
.await
.map_err(|e| Error::Transport(e.into()))?;
Some(LogClient {
client: LoggingServiceV2Client::new(log_channel),
context: Arc::new(InternalLogContext::from(log_context)),
})
}
None => None,
};
let (tx, rx) = futures::channel::mpsc::channel(64);
let pending_count = Arc::new(AtomicUsize::new(0));
let scopes = Arc::new(match log_client {
Some(_) => vec![TRACE_APPEND, LOGGING_WRITE],
None => vec![TRACE_APPEND],
});
let count_clone = pending_count.clone();
let future = async move {
let trace_client = TraceServiceClient::new(trace_channel);
let authorizer = &authenticator;
let log_client = log_client.clone();
rx.for_each_concurrent(num_concurrent_requests, move |batch| {
let trace_client = trace_client.clone();
let log_client = log_client.clone();
let pending_count = count_clone.clone();
let scopes = scopes.clone();
ExporterContext {
trace_client,
log_client,
authorizer,
pending_count,
scopes,
}
.export(batch)
})
.await
};
let exporter = StackDriverExporter {
tx,
pending_count,
maximum_shutdown_duration: maximum_shutdown_duration
.unwrap_or_else(|| Duration::from_secs(5)),
};
Ok((exporter, future))
}
}
struct ExporterContext<'a, A> {
trace_client: TraceServiceClient<Channel>,
log_client: Option<LogClient>,
authorizer: &'a A,
pending_count: Arc<AtomicUsize>,
scopes: Arc<Vec<&'static str>>,
}
impl<A: Authorizer> ExporterContext<'_, A>
where
Error: From<A::Error>,
{
async fn export(mut self, batch: Vec<SpanData>) {
use proto::devtools::cloudtrace::v2::span::time_event::Value;
let mut entries = Vec::new();
let mut spans = Vec::with_capacity(batch.len());
for span in batch {
let trace_id = hex::encode(span.span_context.trace_id().to_bytes());
let span_id = hex::encode(span.span_context.span_id().to_bytes());
let time_event = match &self.log_client {
None => span
.events
.into_iter()
.map(|event| TimeEvent {
time: Some(event.timestamp.into()),
value: Some(Value::Annotation(Annotation {
description: Some(to_truncate(event.name.into_owned())),
..Default::default()
})),
})
.collect(),
Some(client) => {
entries.extend(span.events.into_iter().map(|event| {
let (mut level, mut target, mut labels) =
(LogSeverity::Default, None, HashMap::default());
for kv in event.attributes {
match kv.key.as_str() {
"level" => {
level = match kv.value.as_str().as_ref() {
"DEBUG" | "TRACE" => LogSeverity::Debug,
"INFO" => LogSeverity::Info,
"WARN" => LogSeverity::Warning,
"ERROR" => LogSeverity::Error,
_ => LogSeverity::Default, }
}
"target" => target = Some(kv.value.as_str().into_owned()),
key => {
labels.insert(key.to_owned(), kv.value.as_str().into_owned());
}
}
}
let project_id = self.authorizer.project_id();
let log_id = &client.context.log_id;
LogEntry {
log_name: format!("projects/{project_id}/logs/{log_id}"),
resource: Some(client.context.resource.clone()),
severity: level as i32,
timestamp: Some(event.timestamp.into()),
labels,
trace: format!("projects/{project_id}/traces/{trace_id}"),
span_id: span_id.clone(),
source_location: target.map(|target| LogEntrySourceLocation {
file: String::new(),
line: 0,
function: target,
}),
payload: Some(Payload::TextPayload(event.name.into_owned())),
..Default::default()
}
}));
vec![]
}
};
spans.push(Span {
name: format!(
"projects/{}/traces/{}/spans/{}",
self.authorizer.project_id(),
hex::encode(span.span_context.trace_id().to_bytes()),
hex::encode(span.span_context.span_id().to_bytes())
),
display_name: Some(to_truncate(span.name.into_owned())),
span_id: hex::encode(span.span_context.span_id().to_bytes()),
parent_span_id: hex::encode(span.parent_span_id.to_bytes()),
start_time: Some(span.start_time.into()),
end_time: Some(span.end_time.into()),
attributes: Some(span.attributes.into()),
time_events: Some(TimeEvents {
time_event,
..Default::default()
}),
..Default::default()
});
}
let mut req = Request::new(BatchWriteSpansRequest {
name: format!("projects/{}", self.authorizer.project_id()),
spans,
});
self.pending_count.fetch_sub(1, Ordering::Relaxed);
if let Err(e) = self.authorizer.authorize(&mut req, &self.scopes).await {
handle_error(TraceError::from(Error::Authorizer(e.into())));
} else if let Err(e) = self.trace_client.batch_write_spans(req).await {
handle_error(TraceError::from(Error::Transport(e.into())));
}
let client = match &mut self.log_client {
Some(client) => client,
None => return,
};
let mut req = Request::new(WriteLogEntriesRequest {
log_name: format!(
"projects/{}/logs/{}",
self.authorizer.project_id(),
client.context.log_id,
),
entries,
dry_run: false,
labels: HashMap::default(),
partial_success: true,
resource: None,
});
if let Err(e) = self.authorizer.authorize(&mut req, &self.scopes).await {
handle_error(TraceError::from(Error::from(e)));
} else if let Err(e) = client.client.write_log_entries(req).await {
handle_error(TraceError::from(Error::Transport(e.into())));
}
}
}
#[cfg(feature = "yup-authorizer")]
pub struct YupAuthorizer {
authenticator: Authenticator<hyper_rustls::HttpsConnector<hyper::client::HttpConnector>>,
project_id: String,
}
#[cfg(feature = "yup-authorizer")]
impl YupAuthorizer {
pub async fn new(
credentials_path: impl AsRef<std::path::Path>,
persistent_token_file: impl Into<Option<std::path::PathBuf>>,
) -> Result<Self, Error> {
let service_account_key = yup_oauth2::read_service_account_key(&credentials_path).await?;
let project_id = service_account_key
.project_id
.as_ref()
.ok_or_else(|| Error::Other("project_id is missing".into()))?
.clone();
let mut authenticator =
yup_oauth2::ServiceAccountAuthenticator::builder(service_account_key);
if let Some(persistent_token_file) = persistent_token_file.into() {
authenticator = authenticator.persist_tokens_to_disk(persistent_token_file);
}
Ok(Self {
authenticator: authenticator.build().await?,
project_id,
})
}
}
#[cfg(feature = "yup-authorizer")]
#[async_trait]
impl Authorizer for YupAuthorizer {
type Error = Error;
fn project_id(&self) -> &str {
&self.project_id
}
async fn authorize<T: Send + Sync>(
&self,
req: &mut Request<T>,
scopes: &[&str],
) -> Result<(), Self::Error> {
let token = self
.authenticator
.token(scopes)
.await
.map_err(|e| Error::Authorizer(e.into()))?;
req.metadata_mut().insert(
"authorization",
MetadataValue::try_from(format!("Bearer {}", token.as_str())).unwrap(),
);
Ok(())
}
}
#[cfg(feature = "gcp_auth")]
pub struct GcpAuthorizer {
manager: gcp_auth::AuthenticationManager,
project_id: String,
}
#[cfg(feature = "gcp_auth")]
impl GcpAuthorizer {
pub async fn new() -> Result<Self, Error> {
let manager = gcp_auth::AuthenticationManager::new()
.await
.map_err(|e| Error::Authorizer(e.into()))?;
let project_id = manager
.project_id()
.await
.map_err(|e| Error::Authorizer(e.into()))?;
Ok(Self {
manager,
project_id,
})
}
}
#[cfg(feature = "gcp_auth")]
#[async_trait]
impl Authorizer for GcpAuthorizer {
type Error = Error;
fn project_id(&self) -> &str {
&self.project_id
}
async fn authorize<T: Send + Sync>(
&self,
req: &mut Request<T>,
scopes: &[&str],
) -> Result<(), Self::Error> {
let token = self
.manager
.get_token(scopes)
.await
.map_err(|e| Error::Authorizer(e.into()))?;
req.metadata_mut().insert(
"authorization",
MetadataValue::try_from(format!("Bearer {}", token.as_str())).unwrap(),
);
Ok(())
}
}
#[async_trait]
pub trait Authorizer: Sync + Send + 'static {
type Error: std::error::Error + fmt::Debug + Send + Sync;
fn project_id(&self) -> &str;
async fn authorize<T: Send + Sync>(
&self,
request: &mut Request<T>,
scopes: &[&str],
) -> Result<(), Self::Error>;
}
impl From<Value> for AttributeValue {
fn from(v: Value) -> AttributeValue {
use proto::devtools::cloudtrace::v2::attribute_value;
let new_value = match v {
Value::Bool(v) => attribute_value::Value::BoolValue(v),
Value::F64(v) => attribute_value::Value::StringValue(to_truncate(v.to_string())),
Value::I64(v) => attribute_value::Value::IntValue(v),
Value::String(v) => attribute_value::Value::StringValue(to_truncate(v.to_string())),
Value::Array(_) => attribute_value::Value::StringValue(to_truncate(v.to_string())),
};
AttributeValue {
value: Some(new_value),
}
}
}
fn to_truncate(s: String) -> TruncatableString {
TruncatableString {
value: s,
..Default::default()
}
}
#[derive(Debug, Error)]
pub enum Error {
#[error("authorizer error: {0}")]
Authorizer(#[source] Box<dyn std::error::Error + Send + Sync>),
#[error("I/O error: {0}")]
Io(#[from] std::io::Error),
#[error("{0}")]
Other(#[from] Box<dyn std::error::Error + Send + Sync>),
#[error("tonic error: {0}")]
Transport(#[source] Box<dyn std::error::Error + Send + Sync>),
}
impl ExportError for Error {
fn exporter_name(&self) -> &'static str {
"stackdriver"
}
}
enum LogSeverity {
Default = 0,
Debug = 100,
Info = 200,
Warning = 400,
Error = 500,
}
#[derive(Clone)]
struct LogClient {
client: LoggingServiceV2Client<Channel>,
context: Arc<InternalLogContext>,
}
struct InternalLogContext {
log_id: String,
resource: proto::api::MonitoredResource,
}
#[derive(Clone)]
pub struct LogContext {
pub log_id: String,
pub resource: MonitoredResource,
}
impl From<LogContext> for InternalLogContext {
fn from(cx: LogContext) -> Self {
let mut labels = HashMap::default();
let resource = match cx.resource {
MonitoredResource::CloudRunRevision {
project_id,
service_name,
revision_name,
location,
configuration_name,
} => {
labels.insert("project_id".to_string(), project_id);
if let Some(service_name) = service_name {
labels.insert("service_name".to_string(), service_name);
}
if let Some(revision_name) = revision_name {
labels.insert("revision_name".to_string(), revision_name);
}
if let Some(location) = location {
labels.insert("location".to_string(), location);
}
if let Some(configuration_name) = configuration_name {
labels.insert("configuration_name".to_string(), configuration_name);
}
proto::api::MonitoredResource {
r#type: "cloud_run_revision".to_owned(),
labels,
}
}
MonitoredResource::GenericNode {
project_id,
location,
namespace,
node_id,
} => {
labels.insert("project_id".to_string(), project_id);
if let Some(location) = location {
labels.insert("location".to_string(), location);
}
if let Some(namespace) = namespace {
labels.insert("namespace".to_string(), namespace);
}
if let Some(node_id) = node_id {
labels.insert("node_id".to_string(), node_id);
}
proto::api::MonitoredResource {
r#type: "generic_node".to_owned(),
labels,
}
}
MonitoredResource::GenericTask {
project_id,
location,
namespace,
job,
task_id,
} => {
labels.insert("project_id".to_owned(), project_id);
if let Some(location) = location {
labels.insert("location".to_owned(), location);
}
if let Some(namespace) = namespace {
labels.insert("namespace".to_owned(), namespace);
}
if let Some(job) = job {
labels.insert("job".to_owned(), job);
}
if let Some(task_id) = task_id {
labels.insert("task_id".to_owned(), task_id);
}
proto::api::MonitoredResource {
r#type: "generic_task".to_owned(),
labels,
}
}
MonitoredResource::Global { project_id } => {
labels.insert("project_id".to_owned(), project_id);
proto::api::MonitoredResource {
r#type: "global".to_owned(),
labels,
}
}
};
Self {
log_id: cx.log_id,
resource,
}
}
}
#[derive(Clone)]
pub enum MonitoredResource {
Global {
project_id: String,
},
GenericNode {
project_id: String,
location: Option<String>,
namespace: Option<String>,
node_id: Option<String>,
},
GenericTask {
project_id: String,
location: Option<String>,
namespace: Option<String>,
job: Option<String>,
task_id: Option<String>,
},
CloudRunRevision {
project_id: String,
service_name: Option<String>,
revision_name: Option<String>,
location: Option<String>,
configuration_name: Option<String>,
},
}
impl From<EvictedHashMap> for Attributes {
fn from(attributes: EvictedHashMap) -> Self {
let mut dropped_attributes_count: i32 = 0;
let attribute_map = attributes
.into_iter()
.flat_map(|(k, v)| {
let key = k.as_str();
if key.len() > 128 {
dropped_attributes_count += 1;
return None;
}
if k == SERVICE_NAME {
return Some((GCP_SERVICE_NAME.to_owned(), v.into()));
} else if key == HTTP_PATH_ATTRIBUTE {
return Some((GCP_HTTP_PATH.to_owned(), v.into()));
}
for (otel_key, gcp_key) in KEY_MAP {
if otel_key == &k {
return Some((gcp_key.to_owned(), v.into()));
}
}
Some((key.to_owned(), v.into()))
})
.collect();
Attributes {
attribute_map,
dropped_attributes_count,
}
}
}
const KEY_MAP: [(&Key, &str); 7] = [
(&HTTP_HOST, "/http/host"),
(&HTTP_METHOD, "/http/method"),
(&HTTP_TARGET, "/http/path"),
(&HTTP_URL, "/http/url"),
(&HTTP_USER_AGENT, "/http/user_agent"),
(&HTTP_STATUS_CODE, "/http/status_code"),
(&HTTP_ROUTE, "/http/route"),
];
const TRACE_APPEND: &str = "https://www.googleapis.com/auth/trace.append";
const LOGGING_WRITE: &str = "https://www.googleapis.com/auth/logging.write";
const HTTP_PATH_ATTRIBUTE: &str = "http.path";
const GCP_HTTP_PATH: &str = "/http/path";
const GCP_SERVICE_NAME: &str = "g.co/gae/app/module";
#[cfg(test)]
mod tests {
use super::*;
use opentelemetry::{sdk::trace::EvictedHashMap, KeyValue, Value};
use opentelemetry_semantic_conventions as semcov;
#[test]
fn test_attributes_mapping() {
let capacity = 10;
let mut attributes = EvictedHashMap::new(capacity, 0);
attributes.insert(semcov::trace::HTTP_HOST.string("example.com:8080"));
attributes.insert(semcov::trace::HTTP_METHOD.string("POST"));
attributes.insert(KeyValue::new(
"http.path",
Value::String("/path/12314/?q=ddds#123".into()),
));
attributes.insert(
semcov::trace::HTTP_URL.string("https://example.com:8080/webshop/articles/4?s=1"),
);
attributes
.insert(semcov::trace::HTTP_USER_AGENT.string("CERN-LineMode/2.15 libwww/2.17b3"));
attributes.insert(semcov::trace::HTTP_STATUS_CODE.i64(200));
attributes.insert(semcov::trace::HTTP_ROUTE.string("/webshop/articles/:article_id"));
attributes.insert(semcov::resource::SERVICE_NAME.string("Test Service Name"));
let actual: Attributes = attributes.into();
assert_eq!(actual.attribute_map.len(), 8);
assert_eq!(actual.dropped_attributes_count, 0);
assert_eq!(
actual.attribute_map.get("/http/host"),
Some(&AttributeValue::from(Value::String(
"example.com:8080".into()
)))
);
assert_eq!(
actual.attribute_map.get("/http/method"),
Some(&AttributeValue::from(Value::String("POST".into()))),
);
assert_eq!(
actual.attribute_map.get("/http/path"),
Some(&AttributeValue::from(Value::String(
"/path/12314/?q=ddds#123".into()
))),
);
assert_eq!(
actual.attribute_map.get("/http/route"),
Some(&AttributeValue::from(Value::String(
"/webshop/articles/:article_id".into()
))),
);
assert_eq!(
actual.attribute_map.get("/http/url"),
Some(&AttributeValue::from(Value::String(
"https://example.com:8080/webshop/articles/4?s=1".into(),
))),
);
assert_eq!(
actual.attribute_map.get("/http/user_agent"),
Some(&AttributeValue::from(Value::String(
"CERN-LineMode/2.15 libwww/2.17b3".into()
))),
);
assert_eq!(
actual.attribute_map.get("/http/status_code"),
Some(&AttributeValue::from(Value::I64(200))),
);
assert_eq!(
actual.attribute_map.get("g.co/gae/app/module"),
Some(&AttributeValue::from(Value::String(
"Test Service Name".into()
))),
);
}
#[test]
fn test_attributes_mapping_http_target() {
let capacity = 10;
let mut attributes = EvictedHashMap::new(capacity, 0);
attributes.insert(semcov::trace::HTTP_TARGET.string("/path/12314/?q=ddds#123"));
let actual: Attributes = attributes.into();
assert_eq!(actual.attribute_map.len(), 1);
assert_eq!(actual.dropped_attributes_count, 0);
assert_eq!(
actual.attribute_map.get("/http/path"),
Some(&AttributeValue::from(Value::String(
"/path/12314/?q=ddds#123".into()
))),
);
}
#[test]
fn test_attributes_mapping_dropped_attributes_count() {
let capacity = 10;
let mut attributes = EvictedHashMap::new(capacity, 0);
attributes.insert(KeyValue::new("answer", Value::I64(42)));
attributes.insert(KeyValue::new("long_attribute_key_dvwmacxpeefbuemoxljmqvldjxmvvihoeqnuqdsyovwgljtnemouidabhkmvsnauwfnaihekcfwhugejboiyfthyhmkpsaxtidlsbwsmirebax", Value::String("Some value".into())));
let actual: Attributes = attributes.into();
assert_eq!(
actual,
Attributes {
attribute_map: HashMap::from([(
"answer".into(),
AttributeValue::from(Value::I64(42))
),]),
dropped_attributes_count: 1,
}
);
assert_eq!(actual.attribute_map.len(), 1);
assert_eq!(actual.dropped_attributes_count, 1);
}
}