-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathotel.rs
1685 lines (1548 loc) · 56.3 KB
/
otel.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
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
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: Apache-2.0
//! Set of filters, tests, and functions that are specific to the OpenTelemetry project.
use crate::config::CaseConvention;
use crate::extensions::case::{
camel_case, kebab_case, pascal_case, screaming_snake_case, snake_case,
};
use itertools::Itertools;
use minijinja::filters::sort;
use minijinja::value::{Kwargs, ValueKind};
use minijinja::{ErrorKind, State, Value};
use serde::de::Error;
const TEMPLATE_PREFIX: &str = "template[";
const TEMPLATE_SUFFIX: &str = "]";
/// Add OpenTelemetry specific filters to the environment.
pub(crate) fn add_filters(env: &mut minijinja::Environment<'_>) {
env.add_filter("attribute_namespace", attribute_namespace);
env.add_filter("attribute_registry_namespace", attribute_registry_namespace);
env.add_filter("attribute_registry_title", attribute_registry_title);
env.add_filter("attribute_registry_file", attribute_registry_file);
env.add_filter("attribute_sort", attribute_sort);
env.add_filter("metric_namespace", metric_namespace);
env.add_filter("required", required);
env.add_filter("not_required", not_required);
env.add_filter("instantiated_type", instantiated_type);
env.add_filter("enum_type", enum_type);
env.add_filter("kebab_case_const", kebab_case_const);
env.add_filter("pascal_case_const", pascal_case_const);
env.add_filter("camel_case_const", camel_case_const);
env.add_filter("snake_case_const", snake_case_const);
env.add_filter("screaming_snake_case_const", screaming_snake_case_const);
env.add_filter("print_member_value", print_member_value);
env.add_filter("body_fields", body_fields);
}
/// Add OpenTelemetry specific tests to the environment.
pub(crate) fn add_tests(env: &mut minijinja::Environment<'_>) {
env.add_test("stable", is_stable);
env.add_test("experimental", is_experimental);
env.add_test("deprecated", is_deprecated);
env.add_test("enum", is_enum);
env.add_test("simple_type", is_simple_type);
env.add_test("template_type", is_template_type);
env.add_test("enum_type", is_enum_type);
}
/// Filters the input value to only include the required "object".
/// A required object is one that has a field named "requirement_level" with the value "required".
/// An object that is "conditionally_required" is not returned by this filter.
pub(crate) fn required(input: Value) -> Result<Vec<Value>, minijinja::Error> {
let mut rv = vec![];
for value in input.try_iter()? {
let required = value.get_attr("requirement_level")?;
if required.as_str() == Some("required") {
rv.push(value);
}
}
Ok(rv)
}
/// Filters the input value to only include the non-required "object".
/// A optional object is one that has a field named "requirement_level" which is not "required".
pub(crate) fn not_required(input: Value) -> Result<Vec<Value>, minijinja::Error> {
let mut rv = vec![];
for value in input.try_iter()? {
let required = value.get_attr("requirement_level")?;
if required.as_str() != Some("required") {
rv.push(value);
}
}
Ok(rv)
}
/// Converts registry.{namespace}.{other}.{components} to {namespace}.
///
/// A [`minijinja::Error`] is returned if the input does not start with "registry" or does not have
/// at least two parts. Otherwise, it returns the namespace (second part of the input).
pub(crate) fn attribute_registry_namespace(input: &str) -> Result<String, minijinja::Error> {
let parts: Vec<&str> = input.split('.').collect();
if parts.len() < 2 || parts[0] != "registry" {
return Err(minijinja::Error::new(
ErrorKind::InvalidOperation,
format!("This attribute registry id `{}` is invalid", input),
));
}
Ok(parts[1].to_owned())
}
/// Converts registry.{namespace}.{other}.{components} to {Namespace} (title case the namespace).
///
/// A [`minijinja::Error`] is returned if the input does not start with "registry" or does not have
/// at least two parts. Otherwise, it returns the namespace (second part of the input, title case).
pub(crate) fn attribute_registry_title(input: &str) -> Result<String, minijinja::Error> {
let parts: Vec<&str> = input.split('.').collect();
if parts.len() < 2 || parts[0] != "registry" {
return Err(minijinja::Error::new(
ErrorKind::InvalidOperation,
format!("This attribute registry id `{}` is invalid", input),
));
}
Ok(CaseConvention::TitleCase.convert(parts[1]))
}
/// attribute_registry_file: Converts registry.{namespace}.{other}.{components} to attributes-registry/{namespace}.md (kebab-case namespace).
///
/// A [`minijinja::Error`] is returned if the input does not start with "registry" or does not have
/// at least two parts. Otherwise, it returns the file path (kebab-case namespace).
pub(crate) fn attribute_registry_file(input: &str) -> Result<String, minijinja::Error> {
let parts: Vec<&str> = input.split('.').collect();
if parts.len() < 2 || parts[0] != "registry" {
return Err(minijinja::Error::new(
ErrorKind::InvalidOperation,
format!("This attribute registry id `{}` is invalid", input),
));
}
Ok(format!(
"attributes-registry/{}.md",
CaseConvention::KebabCase.convert(parts[1])
))
}
/// Converts metric.{namespace}.{other}.{components} to {namespace}.
///
/// A [`minijinja::Error`] is returned if the input does not start with "metric" or does not have
/// at least two parts. Otherwise, it returns the namespace (second part of the input).
pub(crate) fn metric_namespace(input: &str) -> Result<String, minijinja::Error> {
let parts: Vec<&str> = input.split('.').collect();
if parts.len() < 2 || parts[0] != "metric" {
return Err(minijinja::Error::new(
ErrorKind::InvalidOperation,
format!("This metric id `{}` is invalid", input),
));
}
Ok(parts[1].to_owned())
}
/// Converts {namespace}.{attribute_id} to {namespace}.
///
/// A [`minijinja::Error`] is returned if the input does not have
/// at least two parts. Otherwise, it returns the namespace (first part of the input).
pub(crate) fn attribute_namespace(input: &str) -> Result<String, minijinja::Error> {
let parts: Vec<&str> = input.split('.').collect();
if parts.len() < 2 {
return Err(minijinja::Error::new(
ErrorKind::InvalidOperation,
format!("This attribute name `{}` is invalid", input),
));
}
Ok(parts[0].to_owned())
}
/// Converts a semconv id into semconv constant following the namespacing rules and the
/// kebab case convention.
pub(crate) fn kebab_case_const(input: &str) -> String {
// Remove all _ and convert to the kebab case
kebab_case(&input.replace('_', ""))
}
/// Converts a semconv id into semconv constant following the namespacing rules and the
/// pascal case convention.
pub(crate) fn pascal_case_const(input: &str) -> String {
// Remove all _ and convert to the pascal case
pascal_case(&input.replace('_', ""))
}
/// Converts a semconv id into semconv constant following the namespacing rules and the
/// camel case convention.
pub(crate) fn camel_case_const(input: &str) -> String {
// Remove all _ and convert to the camel case
camel_case(&input.replace('_', ""))
}
/// Converts a semconv id into semconv constant following the namespacing rules and the
/// snake case convention.
pub(crate) fn snake_case_const(input: &str) -> String {
// Remove all _ and convert to the snake case
snake_case(&input.replace('_', ""))
}
/// Converts a semconv id into semconv constant following the namespacing rules and the
/// screaming snake case convention.
pub(crate) fn screaming_snake_case_const(input: &str) -> String {
// Remove all _ and convert to the screaming snake case
screaming_snake_case(&input.replace('_', ""))
}
/// Compares two attributes by their requirement_level, then name.
fn compare_requirement_level(
lhs: &Value,
rhs: &Value,
) -> Result<std::cmp::Ordering, minijinja::Error> {
fn sort_ordinal_for_requirement(attribute: &Value) -> Result<i32, minijinja::Error> {
let level = attribute.get_attr("requirement_level")?;
if level
.get_attr("conditionally_required")
.is_ok_and(|v| !v.is_undefined())
{
Ok(2)
} else if level
.get_attr("recommended")
.is_ok_and(|v| !v.is_undefined())
{
Ok(3)
} else {
match level.as_str() {
Some("required") => Ok(1),
Some("recommended") => Ok(3),
Some("opt_in") => Ok(4),
_ => Err(minijinja::Error::custom(format!(
"Expected requirement level, found {}",
level
))),
}
}
}
match sort_ordinal_for_requirement(lhs)?.cmp(&sort_ordinal_for_requirement(rhs)?) {
std::cmp::Ordering::Equal => {
let lhs_name = lhs.get_attr("name")?;
let rhs_name = rhs.get_attr("name")?;
if lhs_name.lt(&rhs_name) {
Ok(std::cmp::Ordering::Less)
} else if lhs_name.eq(&rhs_name) {
Ok(std::cmp::Ordering::Equal)
} else {
Ok(std::cmp::Ordering::Greater)
}
}
other => Ok(other),
}
}
/// Sorts a sequence of attributes by their requirement_level, then name.
pub(crate) fn attribute_sort(input: Value) -> Result<Value, minijinja::Error> {
let mut errors: Vec<minijinja::Error> = vec![];
let opt_result = Value::from(
input
.try_iter()?
.sorted_by(|lhs, rhs| {
// Sorted doesn't allow us to keep errors, so we sneak them into
// a mutable vector.
match compare_requirement_level(lhs, rhs) {
Ok(result) => result,
Err(error) => {
errors.push(error);
std::cmp::Ordering::Less
}
}
})
.to_owned()
.collect::<Vec<_>>(),
);
// If we had an internal error, return the first.
match errors.pop() {
Some(err) => Err(err),
None => Ok(opt_result),
}
}
/// Checks if the input value is an object with a field named "stability" that has the value "stable".
/// Otherwise, it returns false.
#[must_use]
pub(crate) fn is_stable(input: &Value) -> bool {
let result = input.get_attr("stability");
if let Ok(stability) = result {
if let Some(stability) = stability.as_str() {
return stability == "stable";
}
}
false
}
/// Checks if the input value is an object with a field named "stability" that has any value
/// other than "stable". Otherwise, it returns false.
#[must_use]
pub(crate) fn is_experimental(input: &Value) -> bool {
let result = input.get_attr("stability");
if let Ok(stability) = result {
if let Some(stability) = stability.as_str() {
return stability != "stable";
}
}
false
}
/// Checks if the input value is an object with a field named "stability" that has the value "deprecated".
/// Otherwise, it returns false.
#[must_use]
pub(crate) fn is_deprecated(input: &Value) -> bool {
let result = input.get_attr("deprecated");
if let Ok(deprecated) = result {
if let Some(deprecated) = deprecated.as_str() {
return !deprecated.is_empty();
}
}
false
}
/// Returns the instantiated type of the input type.
pub(crate) fn instantiated_type(attr_type: &Value) -> Result<String, minijinja::Error> {
if is_simple_type(attr_type) {
return Ok(attr_type
.as_str()
.expect("should never happen, already tested in is_template_type")
.to_owned());
}
if is_template_type(attr_type) {
let attr_type = attr_type
.as_str()
.expect("should never happen, already tested in is_template_type");
let end = attr_type.len() - TEMPLATE_SUFFIX.len();
return Ok(attr_type[TEMPLATE_PREFIX.len()..end].to_owned());
}
if is_enum_type(attr_type) {
return enum_type(attr_type);
}
Err(minijinja::Error::custom(format!(
"Expected simple type, template type, or enum type, found {}",
attr_type
)))
}
/// Converts an enum member value into:
/// - A quoted and escaped string if the input is a string. JSON escapes are used.
/// - A non-quoted string if the input is a number or a boolean.
/// - An empty string otherwise.
pub(crate) fn print_member_value(input: &Value) -> Result<String, minijinja::Error> {
match input.kind() {
ValueKind::String => {
if let Some(input) = input.as_str() {
// Escape the string and add quotes.
// JSON escapes are used as they are very common for most languages.
if let Ok(input) = serde_json::to_string(input) {
Ok(input)
} else {
Err(minijinja::Error::custom(format!(
"`print_member_value` failed to convert {} to a string",
input
)))
}
} else {
Ok("".to_owned())
}
}
ValueKind::Number => Ok(input.to_string()),
ValueKind::Bool => Ok(input.to_string()),
_ => Ok("".to_owned()),
}
}
/// Returns the inferred enum type of the input type or an error if the input type is not an enum.
pub(crate) fn enum_type(attr_type: &Value) -> Result<String, minijinja::Error> {
if let Ok(members) = attr_type.get_attr("members") {
// Infer the enum type from the members.
let mut inferred_type: Option<String> = None;
for member in members.try_iter()? {
let value = member.get_attr("value")?;
let member_type = match value.kind() {
ValueKind::Number => {
if value.as_i64().is_some() {
"int"
} else {
"double"
}
}
ValueKind::String => "string",
_ => {
return Err(minijinja::Error::custom(format!(
"Enum values are expected to be int, double, or string, found {}",
value
)));
}
};
inferred_type = match inferred_type {
Some(current_inferred_type) => {
if current_inferred_type != member_type {
// If the inferred type is different from the member type, then the enum
// type is "promoted" to a string.
Some("string".to_owned())
} else {
Some(current_inferred_type)
}
}
None => Some(member_type.to_owned()),
};
}
return inferred_type.ok_or_else(|| minijinja::Error::custom("Empty enum type"));
}
Err(minijinja::Error::custom(format!(
"Expected enum type, found {}",
attr_type
)))
}
/// Returns true if the input type is a simple type.
pub(crate) fn is_simple_type(attr_type: &Value) -> bool {
if let Some(attr_type) = attr_type.as_str() {
matches!(
attr_type,
"string"
| "string[]"
| "int"
| "int[]"
| "double"
| "double[]"
| "boolean"
| "boolean[]"
)
} else {
false
}
}
/// Returns true if the input type is a template type.
pub(crate) fn is_template_type(attr_type: &Value) -> bool {
if let Some(attr_type) = attr_type.as_str() {
if attr_type.starts_with(TEMPLATE_PREFIX) && attr_type.ends_with(TEMPLATE_SUFFIX) {
let end = attr_type.len() - TEMPLATE_SUFFIX.len();
return is_simple_type(&Value::from(
attr_type[TEMPLATE_PREFIX.len()..end].to_owned(),
));
}
}
false
}
/// Returns true if the input type is an enum type.
pub(crate) fn is_enum_type(attr_type: &Value) -> bool {
// Check the presence of the "members" field.
if let Ok(v) = attr_type.get_attr("members") {
// Returns true if the "members" field is defined.
return !v.is_undefined();
}
false
}
/// Returns true if the input attribute has an enum type.
pub(crate) fn is_enum(attr: &Value) -> bool {
// Check presence of the "type" field.
let attr_type = attr.get_attr("type");
if let Ok(attr_type) = attr_type {
return is_enum_type(&attr_type);
}
false
}
/// Returns a list of pairs {field, depth} from a body field in depth-first order
/// by default.
///
/// This can be used to iterate over a tree of fields composing an
/// event body.
///
/// ```jinja
/// {% for path, field, depth in body|body_fields %}
/// Do something with {{ field }} at depth {{ depth }} with path {{ path }}
/// {% endfor %}
/// ```
pub(crate) fn body_fields(
state: &State<'_, '_>,
body: Value,
kwargs: Kwargs,
) -> Result<Value, minijinja::Error> {
fn traverse_body_fields(
state: &State<'_, '_>,
v: Value,
rv: &mut Vec<Value>,
path: String,
depth: i64,
sort_by: &str,
) -> Result<(), minijinja::Error> {
if v.is_undefined() || v.is_none() {
return Ok(());
}
let fields = v
.get_attr("fields")
.map_err(|_| minijinja::Error::custom("Invalid body field"))?;
let id = v
.get_attr("id")
.map_err(|_| minijinja::Error::custom("Invalid body field"))?;
let path = if path.is_empty() {
id.to_string()
} else {
format!("{path}.{id}")
};
if fields.is_undefined() {
rv.push(Value::from(vec![Value::from(path), v, Value::from(depth)]));
} else {
rv.push(Value::from(vec![
Value::from(path.clone()),
v,
Value::from(depth),
]));
let kwargs = Kwargs::from_iter([("attribute", Value::from(sort_by))]);
for field in sort(state, fields, kwargs)?.try_iter()? {
traverse_body_fields(state, field, rv, path.clone(), depth + 1, sort_by)?;
}
}
Ok(())
}
let mut rv = Vec::new();
let sort_by = kwargs.get::<Option<&str>>("sort_by")?.unwrap_or("id");
traverse_body_fields(state, body, &mut rv, "".to_owned(), 0, sort_by)?;
Ok(Value::from(rv))
}
#[cfg(test)]
mod tests {
use minijinja::value::Object;
use minijinja::{Environment, Value};
use serde::Serialize;
use std::fmt::Debug;
use std::sync::Arc;
use crate::extensions::otel;
use crate::extensions::otel::{
attribute_registry_file, attribute_registry_namespace, attribute_registry_title,
attribute_sort, is_deprecated, is_experimental, is_stable, metric_namespace,
print_member_value,
};
use weaver_resolved_schema::attribute::Attribute;
use weaver_semconv::any_value::{AnyValueCommonSpec, AnyValueSpec};
use weaver_semconv::attribute::BasicRequirementLevelSpec;
use weaver_semconv::attribute::PrimitiveOrArrayTypeSpec;
use weaver_semconv::attribute::RequirementLevel;
use weaver_semconv::attribute::{AttributeType, EnumEntriesSpec, TemplateTypeSpec, ValueSpec};
#[derive(Debug)]
struct DynAttr {
id: String,
r#type: String,
stability: String,
deprecated: Option<String>,
}
impl Object for DynAttr {
fn get_value(self: &Arc<Self>, key: &Value) -> Option<Value> {
match key.as_str() {
Some("id") => Some(Value::from(self.id.as_str())),
Some("type") => Some(Value::from(self.r#type.as_str())),
Some("stability") => Some(Value::from(self.stability.as_str())),
Some("deprecated") => self.deprecated.as_ref().map(|s| Value::from(s.as_str())),
_ => None,
}
}
}
#[derive(Debug)]
struct DynSomethingElse {
id: String,
r#type: String,
}
impl Object for DynSomethingElse {
fn get_value(self: &Arc<Self>, key: &Value) -> Option<Value> {
match key.as_str() {
Some("id") => Some(Value::from(self.id.as_str())),
Some("type") => Some(Value::from(self.r#type.as_str())),
_ => None,
}
}
}
#[test]
fn test_attribute_registry_namespace() {
// A string that does not start with "registry"
let input = "test";
assert!(attribute_registry_namespace(input).is_err());
// A string that starts with "registry" but does not have at least two parts
let input = "registry";
assert!(attribute_registry_namespace(input).is_err());
// A string that starts with "registry" and has at least two parts
let input = "registry.namespace.other.components";
assert_eq!(attribute_registry_namespace(input).unwrap(), "namespace");
// An empty string
let input = "";
assert!(attribute_registry_namespace(input).is_err());
}
#[test]
fn test_attribute_registry_title() {
// A string that does not start with "registry"
let input = "test";
assert!(attribute_registry_title(input).is_err());
// A string that starts with "registry" but does not have at least two parts
let input = "registry";
assert!(attribute_registry_title(input).is_err());
// A string that starts with "registry" and has at least two parts
let input = "registry.namespace.other.components";
assert_eq!(attribute_registry_title(input).unwrap(), "Namespace");
// An empty string
let input = "";
assert!(attribute_registry_title(input).is_err());
}
#[test]
fn test_attribute_registry_file() {
// A string that does not start with "registry"
let input = "test";
assert!(attribute_registry_file(input).is_err());
// A string that starts with "registry" but does not have at least two parts
let input = "registry";
assert!(attribute_registry_file(input).is_err());
// A string that starts with "registry" and has at least two parts
let input = "registry.namespace.other.components";
assert_eq!(
attribute_registry_file(input).unwrap(),
"attributes-registry/namespace.md"
);
// An empty string
let input = "";
assert!(attribute_registry_file(input).is_err());
}
#[test]
fn test_metric_namespace() {
// A string that does not start with "registry"
let input = "test";
assert!(metric_namespace(input).is_err());
// A string that starts with "registry" but does not have at least two parts
let input = "metric";
assert!(metric_namespace(input).is_err());
// A string that starts with "registry" and has at least two parts
let input = "metric.namespace.other.components";
assert_eq!(metric_namespace(input).unwrap(), "namespace");
// An empty string
let input = "";
assert!(metric_namespace(input).is_err());
}
#[test]
fn test_is_stable() {
// An attribute with stability "stable"
let attr = Value::from_object(DynAttr {
id: "test".to_owned(),
r#type: "test".to_owned(),
stability: "stable".to_owned(),
deprecated: None,
});
assert!(is_stable(&attr));
// An attribute with stability "deprecated"
let attr = Value::from_object(DynAttr {
id: "test".to_owned(),
r#type: "test".to_owned(),
stability: "deprecated".to_owned(),
deprecated: None,
});
assert!(!is_stable(&attr));
// An object without a stability field
let object = Value::from_object(DynSomethingElse {
id: "test".to_owned(),
r#type: "test".to_owned(),
});
assert!(!is_stable(&object));
}
#[test]
fn test_is_experimental() {
// An attribute with stability "experimental"
let attr = Value::from_object(DynAttr {
id: "test".to_owned(),
r#type: "test".to_owned(),
stability: "experimental".to_owned(),
deprecated: None,
});
assert!(is_experimental(&attr));
// An attribute with stability "development"
let attr = Value::from_object(DynAttr {
id: "test".to_owned(),
r#type: "test".to_owned(),
stability: "development".to_owned(),
deprecated: None,
});
assert!(is_experimental(&attr));
// An attribute with stability "alpha"
let attr = Value::from_object(DynAttr {
id: "test".to_owned(),
r#type: "test".to_owned(),
stability: "alpha".to_owned(),
deprecated: None,
});
assert!(is_experimental(&attr));
// An attribute with stability "beta"
let attr = Value::from_object(DynAttr {
id: "test".to_owned(),
r#type: "test".to_owned(),
stability: "beta".to_owned(),
deprecated: None,
});
assert!(is_experimental(&attr));
// An attribute with stability "release_candidate"
let attr = Value::from_object(DynAttr {
id: "test".to_owned(),
r#type: "test".to_owned(),
stability: "release_candidate".to_owned(),
deprecated: None,
});
assert!(is_experimental(&attr));
// An attribute with stability "deprecated"
let attr = Value::from_object(DynAttr {
id: "test".to_owned(),
r#type: "test".to_owned(),
stability: "deprecated".to_owned(),
deprecated: None,
});
assert!(is_experimental(&attr));
// An attribute with stability "stable"
let attr = Value::from_object(DynAttr {
id: "test".to_owned(),
r#type: "test".to_owned(),
stability: "stable".to_owned(),
deprecated: None,
});
assert!(!is_experimental(&attr));
// An object without a stability field
let object = Value::from_object(DynSomethingElse {
id: "test".to_owned(),
r#type: "test".to_owned(),
});
assert!(!is_experimental(&object));
}
#[test]
fn test_is_deprecated() {
// An attribute with stability "experimental" and a deprecated field with a value
let attr = Value::from_object(DynAttr {
id: "test".to_owned(),
r#type: "test".to_owned(),
stability: "experimental".to_owned(),
deprecated: Some("This is deprecated".to_owned()),
});
assert!(is_deprecated(&attr));
// An attribute with stability "stable" and a deprecated field with a value
let attr = Value::from_object(DynAttr {
id: "test".to_owned(),
r#type: "test".to_owned(),
stability: "stable".to_owned(),
deprecated: Some("This is deprecated".to_owned()),
});
assert!(is_deprecated(&attr));
// An object without a deprecated field
let object = Value::from_object(DynSomethingElse {
id: "test".to_owned(),
r#type: "test".to_owned(),
});
assert!(!is_deprecated(&object));
let attr = Value::from_object(DynAttr {
id: "test".to_owned(),
r#type: "test".to_owned(),
stability: "stable".to_owned(),
deprecated: None,
});
assert!(!is_deprecated(&attr));
}
#[test]
fn test_attribute_sort() {
// Attributes in no particular order.
let attributes: Vec<Attribute> = vec![
Attribute {
name: "rec.a".into(),
r#type: AttributeType::PrimitiveOrArray(PrimitiveOrArrayTypeSpec::String),
brief: "".into(),
examples: None,
tag: None,
requirement_level: RequirementLevel::Basic(BasicRequirementLevelSpec::Recommended),
sampling_relevant: None,
note: "".into(),
stability: None,
deprecated: None,
tags: None,
value: None,
prefix: false,
},
Attribute {
name: "rec.b".into(),
r#type: AttributeType::PrimitiveOrArray(PrimitiveOrArrayTypeSpec::String),
brief: "".into(),
examples: None,
tag: None,
requirement_level: RequirementLevel::Basic(BasicRequirementLevelSpec::Recommended),
sampling_relevant: None,
note: "".into(),
stability: None,
deprecated: None,
tags: None,
value: None,
prefix: false,
},
Attribute {
name: "crec.a".into(),
r#type: AttributeType::PrimitiveOrArray(PrimitiveOrArrayTypeSpec::String),
brief: "".into(),
examples: None,
tag: None,
requirement_level: RequirementLevel::ConditionallyRequired { text: "hi".into() },
sampling_relevant: None,
note: "".into(),
stability: None,
deprecated: None,
tags: None,
value: None,
prefix: false,
},
Attribute {
name: "crec.b".into(),
r#type: AttributeType::PrimitiveOrArray(PrimitiveOrArrayTypeSpec::String),
brief: "".into(),
examples: None,
tag: None,
requirement_level: RequirementLevel::ConditionallyRequired { text: "hi".into() },
sampling_relevant: None,
note: "".into(),
stability: None,
deprecated: None,
tags: None,
value: None,
prefix: false,
},
Attribute {
name: "rec.c".into(),
r#type: AttributeType::PrimitiveOrArray(PrimitiveOrArrayTypeSpec::String),
brief: "".into(),
examples: None,
tag: None,
requirement_level: RequirementLevel::Recommended { text: "hi".into() },
sampling_relevant: None,
note: "".into(),
stability: None,
deprecated: None,
tags: None,
value: None,
prefix: false,
},
Attribute {
name: "rec.d".into(),
r#type: AttributeType::PrimitiveOrArray(PrimitiveOrArrayTypeSpec::String),
brief: "".into(),
examples: None,
tag: None,
requirement_level: RequirementLevel::Recommended { text: "hi".into() },
sampling_relevant: None,
note: "".into(),
stability: None,
deprecated: None,
tags: None,
value: None,
prefix: false,
},
Attribute {
name: "opt.a".into(),
r#type: AttributeType::PrimitiveOrArray(PrimitiveOrArrayTypeSpec::String),
brief: "".into(),
examples: None,
tag: None,
requirement_level: RequirementLevel::Basic(BasicRequirementLevelSpec::OptIn),
sampling_relevant: None,
note: "".into(),
stability: None,
deprecated: None,
tags: None,
value: None,
prefix: false,
},
Attribute {
name: "opt.b".into(),
r#type: AttributeType::PrimitiveOrArray(PrimitiveOrArrayTypeSpec::String),
brief: "".into(),
examples: None,
tag: None,
requirement_level: RequirementLevel::Basic(BasicRequirementLevelSpec::OptIn),
sampling_relevant: None,
note: "".into(),
stability: None,
deprecated: None,
tags: None,
value: None,
prefix: false,
},
Attribute {
name: "req.a".into(),
r#type: AttributeType::PrimitiveOrArray(PrimitiveOrArrayTypeSpec::String),
brief: "".into(),
examples: None,
tag: None,
requirement_level: RequirementLevel::Basic(BasicRequirementLevelSpec::Required),
sampling_relevant: None,
note: "".into(),
stability: None,
deprecated: None,
tags: None,
value: None,
prefix: false,
},
Attribute {
name: "req.b".into(),
r#type: AttributeType::PrimitiveOrArray(PrimitiveOrArrayTypeSpec::String),
brief: "".into(),
examples: None,
tag: None,
requirement_level: RequirementLevel::Basic(BasicRequirementLevelSpec::Required),
sampling_relevant: None,
note: "".into(),
stability: None,
deprecated: None,
tags: None,
value: None,
prefix: false,
},
];
let json =
serde_json::to_value(attributes).expect("Failed to serialize attributes to json.");
let value = Value::from_serialize(json);
let result = attribute_sort(value).expect("Failed to sort attributes");
let result_seq = result
.try_iter()
.expect("Result was not a sequence!")
.collect::<Vec<_>>();
// Assert that requirement level takes precedence over anything else.
assert_eq!(result_seq.len(), 10, "Expected 10 items, found {}", result);
let names: Vec<String> = result_seq
.iter()
.map(|item| item.get_attr("name").unwrap().as_str().unwrap().to_owned())
.collect();
let expected_names: Vec<String> = vec![
// Required First
"req.a".to_owned(),
"req.b".to_owned(),
// Conditionally Required Second
"crec.a".to_owned(),
"crec.b".to_owned(),
// Conditionally Recommended + Recommended Third
"rec.a".to_owned(),
"rec.b".to_owned(),
"rec.c".to_owned(),
"rec.d".to_owned(),
// OptIn last
"opt.a".to_owned(),
"opt.b".to_owned(),
];
for (idx, (result, expected)) in names.iter().zip(expected_names.iter()).enumerate() {
assert_eq!(
result, expected,
"Expected item @ {idx} to have name {expected}, found {names:?}"
);
}
}
#[test]
fn test_required_and_not_required_filters() {
let attrs = vec![
Attribute {
name: "attr1".to_owned(),
r#type: AttributeType::PrimitiveOrArray(PrimitiveOrArrayTypeSpec::String),
brief: "".to_owned(),
examples: None,
tag: None,
requirement_level: RequirementLevel::Basic(BasicRequirementLevelSpec::Required),
sampling_relevant: None,
note: "".to_owned(),