-
Notifications
You must be signed in to change notification settings - Fork 496
/
Copy pathcommon.rs
761 lines (674 loc) · 20.9 KB
/
common.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
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
use std::borrow::{Borrow, Cow};
use std::sync::Arc;
use std::{fmt, hash};
use std::hash::{Hash, Hasher};
/// The key part of attribute [KeyValue] pairs.
///
/// See the [attribute naming] spec for guidelines.
///
/// [attribute naming]: /~https://github.com/open-telemetry/semantic-conventions/blob/main/docs/general/attribute-naming.md
#[non_exhaustive]
#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Key(OtelString);
impl Key {
/// Create a new `Key`.
///
/// # Examples
///
/// ```
/// use opentelemetry::Key;
/// use std::sync::Arc;
///
/// let key1 = Key::new("my_static_str");
/// let key2 = Key::new(String::from("my_owned_string"));
/// let key3 = Key::new(Arc::from("my_ref_counted_str"));
/// ```
pub fn new(value: impl Into<Key>) -> Self {
value.into()
}
/// Create a new const `Key`.
pub const fn from_static_str(value: &'static str) -> Self {
Key(OtelString::Static(value))
}
/// Returns a reference to the underlying key name
pub fn as_str(&self) -> &str {
self.0.as_str()
}
}
impl From<&'static str> for Key {
/// Convert a `&str` to a `Key`.
fn from(key_str: &'static str) -> Self {
Key(OtelString::Static(key_str))
}
}
impl From<String> for Key {
/// Convert a `String` to a `Key`.
fn from(string: String) -> Self {
Key(OtelString::Owned(string.into_boxed_str()))
}
}
impl From<Arc<str>> for Key {
/// Convert a `String` to a `Key`.
fn from(string: Arc<str>) -> Self {
Key(OtelString::RefCounted(string))
}
}
impl From<Cow<'static, str>> for Key {
/// Convert a `Cow<'static, str>` to a `Key`
fn from(string: Cow<'static, str>) -> Self {
match string {
Cow::Borrowed(s) => Key(OtelString::Static(s)),
Cow::Owned(s) => Key(OtelString::Owned(s.into_boxed_str())),
}
}
}
impl fmt::Debug for Key {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(fmt)
}
}
impl From<Key> for String {
fn from(key: Key) -> Self {
match key.0 {
OtelString::Owned(s) => s.to_string(),
OtelString::Static(s) => s.to_string(),
OtelString::RefCounted(s) => s.to_string(),
}
}
}
impl fmt::Display for Key {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.0 {
OtelString::Owned(s) => s.fmt(fmt),
OtelString::Static(s) => s.fmt(fmt),
OtelString::RefCounted(s) => s.fmt(fmt),
}
}
}
impl Borrow<str> for Key {
fn borrow(&self) -> &str {
self.0.as_str()
}
}
impl AsRef<str> for Key {
fn as_ref(&self) -> &str {
self.0.as_str()
}
}
#[derive(Clone, Debug, Eq)]
enum OtelString {
Owned(Box<str>),
Static(&'static str),
RefCounted(Arc<str>),
}
impl OtelString {
fn as_str(&self) -> &str {
match self {
OtelString::Owned(s) => s.as_ref(),
OtelString::Static(s) => s,
OtelString::RefCounted(s) => s.as_ref(),
}
}
}
impl PartialOrd for OtelString {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for OtelString {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.as_str().cmp(other.as_str())
}
}
impl PartialEq for OtelString {
fn eq(&self, other: &Self) -> bool {
self.as_str().eq(other.as_str())
}
}
impl hash::Hash for OtelString {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
self.as_str().hash(state)
}
}
/// A [Value::Array] containing homogeneous values.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq)]
pub enum Array {
/// Array of bools
Bool(Vec<bool>),
/// Array of integers
I64(Vec<i64>),
/// Array of floats
F64(Vec<f64>),
/// Array of strings
String(Vec<StringValue>),
}
impl fmt::Display for Array {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Array::Bool(values) => display_array_str(values, fmt),
Array::I64(values) => display_array_str(values, fmt),
Array::F64(values) => display_array_str(values, fmt),
Array::String(values) => {
write!(fmt, "[")?;
for (i, t) in values.iter().enumerate() {
if i > 0 {
write!(fmt, ",")?;
}
write!(fmt, "\"{}\"", t)?;
}
write!(fmt, "]")
}
}
}
}
fn display_array_str<T: fmt::Display>(slice: &[T], fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(fmt, "[")?;
for (i, t) in slice.iter().enumerate() {
if i > 0 {
write!(fmt, ",")?;
}
write!(fmt, "{}", t)?;
}
write!(fmt, "]")
}
macro_rules! into_array {
($(($t:ty, $val:expr),)+) => {
$(
impl From<$t> for Array {
fn from(t: $t) -> Self {
$val(t)
}
}
)+
}
}
into_array!(
(Vec<bool>, Array::Bool),
(Vec<i64>, Array::I64),
(Vec<f64>, Array::F64),
(Vec<StringValue>, Array::String),
);
/// The value part of attribute [KeyValue] pairs.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq)]
pub enum Value {
/// bool values
Bool(bool),
/// i64 values
I64(i64),
/// f64 values
F64(f64),
/// String values
String(StringValue),
/// Array of homogeneous values
Array(Array),
}
/// Wrapper for string-like values
#[non_exhaustive]
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct StringValue(OtelString);
impl fmt::Debug for StringValue {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
impl fmt::Display for StringValue {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.0 {
OtelString::Owned(s) => s.fmt(f),
OtelString::Static(s) => s.fmt(f),
OtelString::RefCounted(s) => s.fmt(f),
}
}
}
impl AsRef<str> for StringValue {
fn as_ref(&self) -> &str {
self.0.as_str()
}
}
impl StringValue {
/// Returns a string slice to this value
pub fn as_str(&self) -> &str {
self.0.as_str()
}
}
impl From<StringValue> for String {
fn from(s: StringValue) -> Self {
match s.0 {
OtelString::Owned(s) => s.to_string(),
OtelString::Static(s) => s.to_string(),
OtelString::RefCounted(s) => s.to_string(),
}
}
}
impl From<&'static str> for StringValue {
fn from(s: &'static str) -> Self {
StringValue(OtelString::Static(s))
}
}
impl From<String> for StringValue {
fn from(s: String) -> Self {
StringValue(OtelString::Owned(s.into_boxed_str()))
}
}
impl From<Arc<str>> for StringValue {
fn from(s: Arc<str>) -> Self {
StringValue(OtelString::RefCounted(s))
}
}
impl From<Cow<'static, str>> for StringValue {
fn from(s: Cow<'static, str>) -> Self {
match s {
Cow::Owned(s) => StringValue(OtelString::Owned(s.into_boxed_str())),
Cow::Borrowed(s) => StringValue(OtelString::Static(s)),
}
}
}
impl From<Value> for StringValue {
fn from(s: Value) -> Self {
match s {
Value::Bool(v) => format!("{}", v).into(),
Value::I64(v) => format!("{}", v).into(),
Value::F64(v) => format!("{}", v).into(),
Value::String(v) => v,
Value::Array(v) => format!("{}", v).into(),
}
}
}
impl Value {
/// String representation of the `Value`
///
/// This will allocate if the underlying value is not a `String`.
pub fn as_str(&self) -> Cow<'_, str> {
match self {
Value::Bool(v) => format!("{}", v).into(),
Value::I64(v) => format!("{}", v).into(),
Value::F64(v) => format!("{}", v).into(),
Value::String(v) => Cow::Borrowed(v.as_str()),
Value::Array(v) => format!("{}", v).into(),
}
}
}
macro_rules! from_values {
(
$(
($t:ty, $val:expr);
)+
) => {
$(
impl From<$t> for Value {
fn from(t: $t) -> Self {
$val(t)
}
}
)+
}
}
from_values!(
(bool, Value::Bool);
(i64, Value::I64);
(f64, Value::F64);
(StringValue, Value::String);
);
impl From<&'static str> for Value {
fn from(s: &'static str) -> Self {
Value::String(s.into())
}
}
impl From<String> for Value {
fn from(s: String) -> Self {
Value::String(s.into())
}
}
impl From<Arc<str>> for Value {
fn from(s: Arc<str>) -> Self {
Value::String(s.into())
}
}
impl From<Cow<'static, str>> for Value {
fn from(s: Cow<'static, str>) -> Self {
Value::String(s.into())
}
}
impl fmt::Display for Value {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Value::Bool(v) => v.fmt(fmt),
Value::I64(v) => v.fmt(fmt),
Value::F64(v) => v.fmt(fmt),
Value::String(v) => fmt.write_str(v.as_str()),
Value::Array(v) => v.fmt(fmt),
}
}
}
/// A key-value pair describing an attribute.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct KeyValue {
/// The attribute name
pub key: Key,
/// The attribute value
pub value: Value,
}
impl KeyValue {
/// Create a new `KeyValue` pair.
pub fn new<K, V>(key: K, value: V) -> Self
where
K: Into<Key>,
V: Into<Value>,
{
KeyValue {
key: key.into(),
value: value.into(),
}
}
}
struct F64Hashable(f64);
impl PartialEq for F64Hashable {
fn eq(&self, other: &Self) -> bool {
self.0.to_bits() == other.0.to_bits()
}
}
impl Eq for F64Hashable {}
impl Hash for F64Hashable {
fn hash<H: Hasher>(&self, state: &mut H) {
self.0.to_bits().hash(state);
}
}
impl Hash for KeyValue {
fn hash<H: Hasher>(&self, state: &mut H) {
self.key.hash(state);
match &self.value {
Value::F64(f) => F64Hashable(*f).hash(state),
Value::Array(a) => match a {
Array::Bool(b) => b.hash(state),
Array::I64(i) => i.hash(state),
Array::F64(f) => f.iter().for_each(|f| F64Hashable(*f).hash(state)),
Array::String(s) => s.hash(state),
},
Value::Bool(b) => b.hash(state),
Value::I64(i) => i.hash(state),
Value::String(s) => s.hash(state),
};
}
}
impl Eq for KeyValue {}
/// Information about a library or crate providing instrumentation.
///
/// An instrumentation scope should be named to follow any naming conventions
/// of the instrumented library (e.g. 'middleware' for a web framework).
///
/// See the [instrumentation libraries] spec for more information.
///
/// [instrumentation libraries]: /~https://github.com/open-telemetry/opentelemetry-specification/blob/v1.9.0/specification/overview.md#instrumentation-libraries
#[derive(Debug, Default, Clone)]
#[non_exhaustive]
pub struct InstrumentationScope {
/// The library name.
///
/// This should be the name of the crate providing the instrumentation.
name: Cow<'static, str>,
/// The library version.
version: Option<Cow<'static, str>>,
/// [Schema URL] used by this library.
///
/// [Schema URL]: /~https://github.com/open-telemetry/opentelemetry-specification/blob/v1.9.0/specification/schemas/overview.md#schema-url
schema_url: Option<Cow<'static, str>>,
/// Specifies the instrumentation scope attributes to associate with emitted telemetry.
attributes: Vec<KeyValue>,
}
impl PartialEq for InstrumentationScope {
fn eq(&self, other: &Self) -> bool {
self.name == other.name
&& self.version == other.version
&& self.schema_url == other.schema_url
&& {
let mut self_attrs = self.attributes.clone();
let mut other_attrs = other.attributes.clone();
self_attrs.sort_unstable_by(|a, b| a.key.cmp(&b.key));
other_attrs.sort_unstable_by(|a, b| a.key.cmp(&b.key));
self_attrs == other_attrs
}
}
}
impl Eq for InstrumentationScope {}
impl hash::Hash for InstrumentationScope {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
self.name.hash(state);
self.version.hash(state);
self.schema_url.hash(state);
let mut sorted_attrs = self.attributes.clone();
sorted_attrs.sort_unstable_by(|a, b| a.key.cmp(&b.key));
for attribute in sorted_attrs {
attribute.hash(state);
}
}
}
impl InstrumentationScope {
/// Create a new builder to create an [InstrumentationScope]
pub fn builder<T: Into<Cow<'static, str>>>(name: T) -> InstrumentationScopeBuilder {
InstrumentationScopeBuilder {
name: name.into(),
version: None,
schema_url: None,
attributes: None,
}
}
/// Returns the instrumentation library name.
#[inline]
pub fn name(&self) -> &str {
&self.name
}
/// Returns the instrumentation library version.
#[inline]
pub fn version(&self) -> Option<&str> {
self.version.as_deref()
}
/// Returns the [Schema URL] used by this library.
///
/// [Schema URL]: /~https://github.com/open-telemetry/opentelemetry-specification/blob/v1.9.0/specification/schemas/overview.md#schema-url
#[inline]
pub fn schema_url(&self) -> Option<&str> {
self.schema_url.as_deref()
}
/// Returns the instrumentation scope attributes to associate with emitted telemetry.
#[inline]
pub fn attributes(&self) -> impl Iterator<Item = &KeyValue> {
self.attributes.iter()
}
}
/// Configuration options for [InstrumentationScope].
///
/// An instrumentation scope is a library or crate providing instrumentation.
/// It should be named to follow any naming conventions of the instrumented
/// library (e.g. 'middleware' for a web framework).
///
/// Apart from the name, all other fields are optional.
///
/// See the [instrumentation libraries] spec for more information.
///
/// [instrumentation libraries]: /~https://github.com/open-telemetry/opentelemetry-specification/blob/v1.9.0/specification/overview.md#instrumentation-libraries
#[derive(Debug)]
pub struct InstrumentationScopeBuilder {
name: Cow<'static, str>,
version: Option<Cow<'static, str>>,
schema_url: Option<Cow<'static, str>>,
attributes: Option<Vec<KeyValue>>,
}
impl InstrumentationScopeBuilder {
/// Configure the version for the instrumentation scope
///
/// # Examples
///
/// ```
/// let scope = opentelemetry::InstrumentationScope::builder("my-crate")
/// .with_version("v0.1.0")
/// .build();
/// ```
pub fn with_version(mut self, version: impl Into<Cow<'static, str>>) -> Self {
self.version = Some(version.into());
self
}
/// Configure the Schema URL for the instrumentation scope
///
/// # Examples
///
/// ```
/// let scope = opentelemetry::InstrumentationScope::builder("my-crate")
/// .with_schema_url("https://opentelemetry.io/schemas/1.17.0")
/// .build();
/// ```
pub fn with_schema_url(mut self, schema_url: impl Into<Cow<'static, str>>) -> Self {
self.schema_url = Some(schema_url.into());
self
}
/// Configure the attributes for the instrumentation scope
///
/// # Examples
///
/// ```
/// use opentelemetry::KeyValue;
///
/// let scope = opentelemetry::InstrumentationScope::builder("my-crate")
/// .with_attributes([KeyValue::new("k", "v")])
/// .build();
/// ```
pub fn with_attributes<I>(mut self, attributes: I) -> Self
where
I: IntoIterator<Item = KeyValue>,
{
self.attributes = Some(attributes.into_iter().collect());
self
}
/// Create a new [InstrumentationScope] from this configuration
pub fn build(self) -> InstrumentationScope {
InstrumentationScope {
name: self.name,
version: self.version,
schema_url: self.schema_url,
attributes: self.attributes.unwrap_or_default(),
}
}
}
#[cfg(test)]
mod tests {
use std::hash::{Hash, Hasher};
use crate::{InstrumentationScope, KeyValue};
use rand::random;
use std::collections::hash_map::DefaultHasher;
use std::f64;
#[test]
fn kv_float_equality() {
let kv1 = KeyValue::new("key", 1.0);
let kv2 = KeyValue::new("key", 1.0);
assert_eq!(kv1, kv2);
let kv1 = KeyValue::new("key", 1.0);
let kv2 = KeyValue::new("key", 1.01);
assert_ne!(kv1, kv2);
let kv1 = KeyValue::new("key", f64::NAN);
let kv2 = KeyValue::new("key", f64::NAN);
assert_ne!(kv1, kv2, "NAN is not equal to itself");
for float_val in [
f64::INFINITY,
f64::NEG_INFINITY,
f64::MAX,
f64::MIN,
f64::MIN_POSITIVE,
]
.iter()
{
let kv1 = KeyValue::new("key", *float_val);
let kv2 = KeyValue::new("key", *float_val);
assert_eq!(kv1, kv2);
}
for _ in 0..100 {
let random_value = random::<f64>();
let kv1 = KeyValue::new("key", random_value);
let kv2 = KeyValue::new("key", random_value);
assert_eq!(kv1, kv2);
}
}
#[test]
fn kv_float_hash() {
for float_val in [
f64::NAN,
f64::INFINITY,
f64::NEG_INFINITY,
f64::MAX,
f64::MIN,
f64::MIN_POSITIVE,
]
.iter()
{
let kv1 = KeyValue::new("key", *float_val);
let kv2 = KeyValue::new("key", *float_val);
assert_eq!(hash_helper(&kv1), hash_helper(&kv2));
}
for _ in 0..100 {
let random_value = random::<f64>();
let kv1 = KeyValue::new("key", random_value);
let kv2 = KeyValue::new("key", random_value);
assert_eq!(hash_helper(&kv1), hash_helper(&kv2));
}
}
fn hash_helper<T: Hash>(item: &T) -> u64 {
let mut hasher = DefaultHasher::new();
item.hash(&mut hasher);
hasher.finish()
}
#[test]
fn instrumentation_scope_equality() {
let scope1 = InstrumentationScope::builder("my-crate")
.with_version("v0.1.0")
.with_schema_url("https://opentelemetry.io/schemas/1.17.0")
.with_attributes([KeyValue::new("k", "v")])
.build();
let scope2 = InstrumentationScope::builder("my-crate")
.with_version("v0.1.0")
.with_schema_url("https://opentelemetry.io/schemas/1.17.0")
.with_attributes([KeyValue::new("k", "v")])
.build();
assert_eq!(scope1, scope2);
}
#[test]
fn instrumentation_scope_equality_attributes_diff_order() {
let scope1 = InstrumentationScope::builder("my-crate")
.with_version("v0.1.0")
.with_schema_url("https://opentelemetry.io/schemas/1.17.0")
.with_attributes([KeyValue::new("k1", "v1"), KeyValue::new("k2", "v2")])
.build();
let scope2 = InstrumentationScope::builder("my-crate")
.with_version("v0.1.0")
.with_schema_url("https://opentelemetry.io/schemas/1.17.0")
.with_attributes([KeyValue::new("k2", "v2"), KeyValue::new("k1", "v1")])
.build();
assert_eq!(scope1, scope2);
// assert hash are same for both scopes
let mut hasher1 = std::collections::hash_map::DefaultHasher::new();
scope1.hash(&mut hasher1);
let mut hasher2 = std::collections::hash_map::DefaultHasher::new();
scope2.hash(&mut hasher2);
assert_eq!(hasher1.finish(), hasher2.finish());
}
#[test]
fn instrumentation_scope_equality_different_attributes() {
let scope1 = InstrumentationScope::builder("my-crate")
.with_version("v0.1.0")
.with_schema_url("https://opentelemetry.io/schemas/1.17.0")
.with_attributes([KeyValue::new("k1", "v1"), KeyValue::new("k2", "v2")])
.build();
let scope2 = InstrumentationScope::builder("my-crate")
.with_version("v0.1.0")
.with_schema_url("https://opentelemetry.io/schemas/1.17.0")
.with_attributes([KeyValue::new("k2", "v3"), KeyValue::new("k4", "v5")])
.build();
assert_ne!(scope1, scope2);
// assert hash are same for both scopes
let mut hasher1 = std::collections::hash_map::DefaultHasher::new();
scope1.hash(&mut hasher1);
let mut hasher2 = std::collections::hash_map::DefaultHasher::new();
scope2.hash(&mut hasher2);
assert_ne!(hasher1.finish(), hasher2.finish());
}
}