@@ -8,18 +8,37 @@ import OpenTelemetryApi
88
99/// Provides a framework for detection of resource information from the environment variable
1010public struct EnvVarHeaders {
11- private static let otelAttributesEnv = " OTEL_EXPORTER_OTLP_HEADERS "
1211 private static let labelListSplitter = Character ( " , " )
1312 private static let labelKeyValueSplitter = Character ( " = " )
1413
1514 /// This resource information is loaded from the
1615 /// environment variable.
17- public static let attributes : [ ( String , String ) ] ? = parseAttributes ( rawEnvAttributes: ProcessInfo . processInfo. environment [ otelAttributesEnv] )
16+ public static let attributes : [ ( String , String ) ] ? = EnvVarHeaders . attributes ( )
17+
18+ public static func attributes( for rawEnvAttributes: String ? = ProcessInfo . processInfo. environment [ " OTEL_EXPORTER_OTLP_HEADERS " ] ) -> [ ( String , String ) ] ? {
19+ parseAttributes ( rawEnvAttributes: rawEnvAttributes)
20+ }
1821
1922 private init ( ) { }
2023
24+ private static func isKey( token: String ) -> Bool {
25+ let alpha = CharacterSet ( charactersIn: " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ " )
26+ let digit = CharacterSet ( charactersIn: " 0123456789 " )
27+ let special = CharacterSet ( charactersIn: " !#$%&'*+-.^_`|~ " )
28+ let tchar = special. union ( alpha) . union ( digit)
29+ return tchar. isSuperset ( of: CharacterSet ( charactersIn: token) )
30+ }
31+
32+ private static func isValue( baggage: String ) -> Bool {
33+ let asciiSet = CharacterSet ( charactersIn: UnicodeScalar ( 0 ) ..< UnicodeScalar ( 0x80 ) )
34+ let special = CharacterSet ( charactersIn: " ^ \" | \" $ " )
35+ let baggageOctet = asciiSet. subtracting ( . controlCharacters) . subtracting ( . whitespaces) . union ( special)
36+ return baggageOctet. isSuperset ( of: CharacterSet ( charactersIn: baggage) )
37+ }
38+
2139 /// Creates a label map from the environment variable string.
2240 /// - Parameter rawEnvLabels: the comma-separated list of labels
41+ /// NOTE: Parsing does not fully match W3C Correlation-Context
2342 private static func parseAttributes( rawEnvAttributes: String ? ) -> [ ( String , String ) ] ? {
2443 guard let rawEnvLabels = rawEnvAttributes else { return nil }
2544
@@ -30,10 +49,17 @@ public struct EnvVarHeaders {
3049 if split. count != 2 {
3150 return
3251 }
52+
3353 let key = split [ 0 ] . trimmingCharacters ( in: . whitespaces)
34- let value = split [ 1 ] . trimmingCharacters ( in: CharacterSet ( charactersIn: " ^ \" | \" $ " ) )
54+ guard isKey ( token: key) else { return }
55+
56+ let value = split [ 1 ] . trimmingCharacters ( in: . whitespaces)
57+ guard isValue ( baggage: value) else { return }
58+
3559 labels. append ( ( key, value) )
3660 }
37- return labels
61+ return labels. count > 0 ? labels : nil
3862 }
3963}
64+
65+
0 commit comments