Debian Codegraph @

awscrt/aws_iot_metrics.py

raw symbols SCIP
1 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 # SPDX-License-Identifier: Apache-2.0.
3
4 from dataclasses import dataclass
5 from typing import List, Optional
6 from enum import Enum
7 import sys
8
9
10 @dataclass
11 class IoTMetricsMetadata:
12 """A key-value pair for IoT SDK metrics metadata.
13
14 Metadata entries are appended to the MQTT CONNECT packet username field
15 as part of the Metadata query parameter.
16
17 Args:
18 key (str): The metadata key (e.g., "IoTSDKVersion", "IoTSDKFeature", "CRTVersion")
19 value (str): The metadata value
20 """
21 key: str
22 value: str
23
24
25 @dataclass
26 class AWSIoTMetrics:
27 """Configuration for IoT SDK metrics that are embedded in MQTT Connect Packet username field.
28
29 Args:
30 library_name (str): The SDK library name (e.g., "IoTDeviceSDK/Python")
31 metadata_entries (Optional[List[IoTMetricsMetadata]]): Optional list for storing key-value pairs of metadata
32
33 """
34 library_name: str = "IoTDeviceSDK/Python"
35 metadata_entries: Optional[List[IoTMetricsMetadata]] = None
36
37
38 # Metrics Version Constant
39 IOT_SDK_METRICS_FEATURE_VERSION = 1
40
41 # Feature ID Constants
42
43
44 class _MetricsFeatureId(str, Enum):
45 """Feature IDs for IoT SDK metrics tracking.
46
47 Each ID is a single character used to encode feature usage in the metrics
48 string with the format "ID/Value". IDs are assigned sequentially and never
49 reused to ensure historical data consistency across SDK versions.
50 """
51 RETRY_JITTER_MODE = "A"
52 SESSION_BEHAVIOR = "B"
53 OFFLINE_QUEUE_BEHAVIOR = "C"
54 OUTBOUND_TOPIC_ALIAS_BEHAVIOR = "D"
55 INBOUND_TOPIC_ALIAS_BEHAVIOR = "E"
56 PROTOCOL_VERSION = "F"
57 SOCKET_IMPLEMENTATION = "G"
58 HTTP_PROXY_TYPE = "H"
59 CERTIFICATE_SOURCE = "I"
60 TLS_CIPHER_PREFERENCE = "J"
61 MINIMUM_TLS_VERSION = "K"
62
63 # Feature Value Constants
64
65
66 def _certificate_source_metrics_value(source):
67 """Map _CertificateSource to its single-character metrics value.
68
69 Mapping: CERTIFICATE_FILES->A, PKCS11->B, WINDOWS_CERT_STORE->C, PKCS12_FILE->E.
70 "D" is reserved for Java KeyStore.
71 Returns None if source is None or unrecognized.
72 """
73 from awscrt.io import _CertificateSource
74 mapping = {
75 _CertificateSource.CERTIFICATE_FILES: "A",
76 _CertificateSource.PKCS11: "B",
77 _CertificateSource.WINDOWS_CERT_STORE: "C",
78 _CertificateSource.PKCS12_FILE: "E",
79 }
80 return mapping.get(source)
81
82
83 def _protocol_version_metrics_value(protocol):
84 """Map protocol version to its single-character metrics value.
85
86 Mapping: MQTT311->3, MQTT5->5.
87 """
88 mapping = {
89 "MQTT311": "3",
90 "MQTT5": "5",
91 }
92 return mapping.get(protocol)
93
94
95 def _socket_implementation_metrics_value():
96 """Detect the socket implementation and return its single-character metrics value.
97
98 Mapping: Windows (WINSOCK)->B, all other platforms (POSIX)->A.
99 """
100 if sys.platform == "win32":
101 return "B"
102 return "A"
103
104
105 def _http_proxy_type_metrics_value(proxy_options):
106 """Map proxy options to the single-character metrics value for proxy type.
107
108 Mapping: HTTPS (has tls_connection_options)->B, HTTP->A.
109 """
110 if getattr(proxy_options, 'tls_connection_options', None) is not None:
111 return "B"
112 return "A"
113
114
115 def _retry_jitter_metrics_value(mode):
116 """Map ExponentialBackoffJitterMode to its single-character metrics value.
117
118 Mapping: NONE->A, FULL->B, DECORRELATED->C.
119 Returns None for DEFAULT.
120 """
121 from awscrt.mqtt5 import ExponentialBackoffJitterMode
122 mapping = {
123 ExponentialBackoffJitterMode.NONE: "A",
124 ExponentialBackoffJitterMode.FULL: "B",
125 ExponentialBackoffJitterMode.DECORRELATED: "C",
126 }
127 return mapping.get(mode)
128
129
130 def _client_session_behavior_metrics_value(behavior):
131 """Map ClientSessionBehaviorType to its single-character metrics value.
132
133 Mapping: CLEAN->A, REJOIN_POST_SUCCESS->B, REJOIN_ALWAYS->C.
134 Returns None for DEFAULT.
135 """
136 from awscrt.mqtt5 import ClientSessionBehaviorType
137 mapping = {
138 ClientSessionBehaviorType.CLEAN: "A",
139 ClientSessionBehaviorType.REJOIN_POST_SUCCESS: "B",
140 ClientSessionBehaviorType.REJOIN_ALWAYS: "C",
141 }
142 return mapping.get(behavior)
143
144
145 def _client_operation_queue_behavior_metrics_value(behavior):
146 """Map ClientOperationQueueBehaviorType to its single-character metrics value.
147
148 Mapping: FAIL_NON_QOS1_PUBLISH_ON_DISCONNECT->A,
149 FAIL_QOS0_PUBLISH_ON_DISCONNECT->B, FAIL_ALL_ON_DISCONNECT->C.
150 Returns None for DEFAULT.
151 """
152 from awscrt.mqtt5 import ClientOperationQueueBehaviorType
153 mapping = {
154 ClientOperationQueueBehaviorType.FAIL_NON_QOS1_PUBLISH_ON_DISCONNECT: "A",
155 ClientOperationQueueBehaviorType.FAIL_QOS0_PUBLISH_ON_DISCONNECT: "B",
156 ClientOperationQueueBehaviorType.FAIL_ALL_ON_DISCONNECT: "C",
157 }
158 return mapping.get(behavior)
159
160
161 def _outbound_topic_alias_behavior_metrics_value(behavior):
162 """Map OutboundTopicAliasBehaviorType to its single-character metrics value.
163
164 Mapping: MANUAL->A, LRU->B, DISABLED->C.
165 Returns None for DEFAULT.
166 """
167 from awscrt.mqtt5 import OutboundTopicAliasBehaviorType
168 mapping = {
169 OutboundTopicAliasBehaviorType.MANUAL: "A",
170 OutboundTopicAliasBehaviorType.LRU: "B",
171 OutboundTopicAliasBehaviorType.DISABLED: "C",
172 }
173 return mapping.get(behavior)
174
175
176 def _inbound_topic_alias_behavior_metrics_value(behavior):
177 """Map InboundTopicAliasBehaviorType to its single-character metrics value.
178
179 Mapping: ENABLED->A, DISABLED->B.
180 Returns None for DEFAULT.
181 """
182 from awscrt.mqtt5 import InboundTopicAliasBehaviorType
183 mapping = {
184 InboundTopicAliasBehaviorType.ENABLED: "A",
185 InboundTopicAliasBehaviorType.DISABLED: "B",
186 }
187 return mapping.get(behavior)
188
189
190 def _minimum_tls_version_metrics_value(version):
191 """Map TlsVersion to its single-character metrics value.
192
193 Mapping: SSLv3->A, TLSv1->B, TLSv1_1->C, TLSv1_2->D, TLSv1_3->E.
194 Returns None for DEFAULT.
195 """
196 from awscrt.io import TlsVersion
197 mapping = {
198 TlsVersion.SSLv3: "A",
199 TlsVersion.TLSv1: "B",
200 TlsVersion.TLSv1_1: "C",
201 TlsVersion.TLSv1_2: "D",
202 TlsVersion.TLSv1_3: "E",
203 }
204 return mapping.get(version)
205
206
207 def _tls_cipher_preference_metrics_value(pref):
208 """Map TlsCipherPref to its single-character metrics value.
209
210 Mapping: PQ_TLSv1_0_2021_05->F, PQ_DEFAULT->H, TLSv1_2_2025_07->I.
211 Letters A-E, G, J, K are reserved for cipher preferences exposed by
212 other language SDKs but not by Python.
213 Returns None for DEFAULT or any unrecognized value.
214 """
215 from awscrt.io import TlsCipherPref
216 mapping = {
217 TlsCipherPref.PQ_TLSv1_0_2021_05: "F",
218 TlsCipherPref.PQ_DEFAULT: "H",
219 TlsCipherPref.TLSv1_2_2025_07: "I",
220 }
221 return mapping.get(pref)
222
223
224 # MQTT5 encoding list
225 def _get_encoded_feature_list(client_options):
226 """Generates the encoded feature list string for metrics from MQTT5 ClientOptions.
227
228 Format: "ID/Value,ID/Value,..."
229 Example: "A/B,C/A,F/5,G/A" means retry_jitter_mode=FULL, offline_queue_behavior=
230 FAIL_NON_QOS1_PUBLISH_ON_DISCONNECT, protocol=MQTT5, socket=POSIX.
231
232 MQTT5 connections always include:
233 - F (protocol_version): set to MQTT5
234 - G (socket_implementation): detected from platform (POSIX or WINSOCK)
235
236 Conditionally includes (only when the option is explicitly set and not DEFAULT):
237 - A (retry_jitter_mode): from client_options.retry_jitter_mode
238 - B (session_behavior): from client_options.session_behavior
239 - C (offline_queue_behavior): from client_options.offline_queue_behavior
240 - D (outbound_topic_alias_behavior): from topic_aliasing_options.outbound_behavior
241 - E (inbound_topic_alias_behavior): from topic_aliasing_options.inbound_behavior
242 - H (http_proxy_type): HTTP or HTTPS based on proxy TLS settings
243 - I (certificate_source): detected from TlsContextOptions
244 - J (tls_cipher_preference): mapped from TlsCipherPref on the TLS context
245 - K (minimum_tls_version): mapped from TlsVersion on the TLS context
246
247 Args:
248 client_options: MQTT5 ClientOptions dataclass.
249 Returns:
250 str: The encoded feature list string.
251 """
252
253 features = []
254
255 # A: retry_jitter_mode
256 if client_options.retry_jitter_mode is not None:
257 val = _retry_jitter_metrics_value(client_options.retry_jitter_mode)
258 if val:
259 features.append(f"{_MetricsFeatureId.RETRY_JITTER_MODE.value}/{val}")
260
261 # B: session_behavior
262 if client_options.session_behavior is not None:
263 val = _client_session_behavior_metrics_value(client_options.session_behavior)
264 if val:
265 features.append(f"{_MetricsFeatureId.SESSION_BEHAVIOR.value}/{val}")
266
267 # C: offline_queue_behavior
268 if client_options.offline_queue_behavior is not None:
269 val = _client_operation_queue_behavior_metrics_value(client_options.offline_queue_behavior)
270 if val:
271 features.append(f"{_MetricsFeatureId.OFFLINE_QUEUE_BEHAVIOR.value}/{val}")
272
273 # D: outbound_topic_alias_behavior
274 if client_options.topic_aliasing_options is not None:
275 if client_options.topic_aliasing_options.outbound_behavior is not None:
276 val = _outbound_topic_alias_behavior_metrics_value(client_options.topic_aliasing_options.outbound_behavior)
277 if val:
278 features.append(f"{_MetricsFeatureId.OUTBOUND_TOPIC_ALIAS_BEHAVIOR.value}/{val}")
279
280 # E: inbound_topic_alias_behavior
281 if client_options.topic_aliasing_options is not None:
282 if client_options.topic_aliasing_options.inbound_behavior is not None:
283 val = _inbound_topic_alias_behavior_metrics_value(client_options.topic_aliasing_options.inbound_behavior)
284 if val:
285 features.append(f"{_MetricsFeatureId.INBOUND_TOPIC_ALIAS_BEHAVIOR.value}/{val}")
286
287 # F: protocol_version - MQTT5 always uses client options
288 features.append(f"{_MetricsFeatureId.PROTOCOL_VERSION.value}/{_protocol_version_metrics_value('MQTT5')}")
289
290 # G: socket_implementation - Detect based on platform
291 features.append(f"{_MetricsFeatureId.SOCKET_IMPLEMENTATION.value}/{_socket_implementation_metrics_value()}")
292
293 # H: http_proxy_type - Determine based on whether proxy uses TLS
294 if client_options.http_proxy_options is not None:
295 val = _http_proxy_type_metrics_value(client_options.http_proxy_options)
296 features.append(f"{_MetricsFeatureId.HTTP_PROXY_TYPE.value}/{val}")
297
298 # I: certificate_source - detected from TlsContextOptions factory method
299 if client_options.tls_ctx is not None:
300 val = _certificate_source_metrics_value(client_options.tls_ctx._certificate_source)
301 if val:
302 features.append(f"{_MetricsFeatureId.CERTIFICATE_SOURCE.value}/{val}")
303
304 # J: tls_cipher_preference - security policy
305 if client_options.tls_ctx is not None:
306 val = _tls_cipher_preference_metrics_value(client_options.tls_ctx._cipher_pref)
307 if val:
308 features.append(f"{_MetricsFeatureId.TLS_CIPHER_PREFERENCE.value}/{val}")
309
310 # K: minimum_tls_version - The minimum TLS version set on TLSContextOptions
311 if client_options.tls_ctx is not None:
312 val = _minimum_tls_version_metrics_value(client_options.tls_ctx._min_tls_ver)
313 if val:
314 features.append(f"{_MetricsFeatureId.MINIMUM_TLS_VERSION.value}/{val}")
315
316 return ",".join(features)
317
318 # MQTT3 encoding list
319
320
321 def _get_encoded_feature_list_mqtt3(proxy_options, tls_ctx=None):
322 """Generates the encoded feature list string for metrics from MQTT3 connection options.
323 Format: "ID/Value,ID/Value..."
324
325 MQTT3 connections always include:
326 - F (protocol_version): set to MQTT311
327 - G (socket_implementation): detected from platform (POSIX or WINSOCK)
328
329 Conditionally includes:
330 - H (http_proxy_type): HTTP or HTTPS based on proxy TLS settings
331 - I (certificate_source): detected from TlsContextOptions
332 - J (tls_cipher_preference): mapped from TlsCipherPref on the TLS context
333 - K (minimum_tls_version): mapped from TlsVersion on the TLS context
334
335 Args:
336 proxy_options: Optional HttpProxyOptions from the Connection.
337 tls_ctx: Optional ClientTlsContext used by the connection.
338 Returns:
339 str: The encoded feature list string.
340 """
341 features = [
342 f"{_MetricsFeatureId.PROTOCOL_VERSION.value}/{_protocol_version_metrics_value('MQTT311')}",
343 f"{_MetricsFeatureId.SOCKET_IMPLEMENTATION.value}/{_socket_implementation_metrics_value()}"
344 ]
345 # H: http_proxy_type - Determine based on whether proxy uses TLS
346 if proxy_options is not None:
347 val = _http_proxy_type_metrics_value(proxy_options)
348 features.append(f"{_MetricsFeatureId.HTTP_PROXY_TYPE.value}/{val}")
349
350 # I: certificate_source - detected from TlsContextOptions factory method
351 if tls_ctx is not None:
352 val = _certificate_source_metrics_value(tls_ctx._certificate_source)
353 if val:
354 features.append(f"{_MetricsFeatureId.CERTIFICATE_SOURCE.value}/{val}")
355
356 # J: tls_cipher_preference - security policy
357 if tls_ctx is not None:
358 val = _tls_cipher_preference_metrics_value(tls_ctx._cipher_pref)
359 if val:
360 features.append(f"{_MetricsFeatureId.TLS_CIPHER_PREFERENCE.value}/{val}")
361
362 # K: minimum_tls_version - the minimum TLS version set on TLSContextOptions
363 if tls_ctx is not None:
364 val = _minimum_tls_version_metrics_value(tls_ctx._min_tls_ver)
365 if val:
366 features.append(f"{_MetricsFeatureId.MINIMUM_TLS_VERSION.value}/{val}")
367
368 return ",".join(features)
369
370
371 def _merge_feature_lists(crt_features, user_features):
372 """Merge CRT-generated features with user-provided (IoT SDK) features.
373
374 When both lists contain the same feature ID, the user-provided value
375 takes precedence.
376
377 Args:
378 crt_features (str): CRT-generated feature list.
379 user_features (str): User-provided feature list from the IoT SDK.
380 May be empty string if no SDK features are provided.
381 Returns:
382 str: The merged feature list string.
383 """
384 merged = {}
385 # Parse CRT Features
386 for pair in crt_features.split(","):
387 if "/" in pair:
388 fid, val = pair.split("/", 1)
389 merged[fid] = val
390
391 for pair in user_features.split(","):
392 if "/" in pair:
393 fid, val = pair.split("/", 1)
394 merged[fid] = val
395 return ",".join(f"{k}/{v}" for k, v in merged.items())
396
397 # Metrics creation
398
399
400 def _create_metrics(user_metrics, crt_feature_list):
401 """Create the final AWSIoTMetrics object by merging CRT and user-provided data.
402
403 Applies the following rules to produce the final metrics:
404
405 1. library_name: Uses the value from user_metrics if provided,
406 otherwise defaults to "IoTDeviceSDK/Python".
407 2. CRTVersion: Automatically set to the current awscrt
408 package version. Cannot be overridden by user input.
409 3. IoTSDKMetricsVersion: Always set to the current
410 IOT_SDK_METRICS_FEATURE_VERSION constant.
411 4. IoTSDKFeature: If the user-provided metrics version
412 matches IOT_SDK_METRICS_FEATURE_VERSION, the CRT feature list is
413 merged with the user's IoTSDKFeature (user values take precedence
414 for duplicate feature IDs). Otherwise, only CRT features are used.
415 5. Any additional user metadata entries (other than CRTVersion,
416 IoTSDKMetricsVersion, IoTSDKFeature) are passed through unchanged.
417
418 Args:
419 user_metrics: Metrics configuration from the IoT SDK. May be None if no SDK-level metrics are provided.
420 crt_feature_list: Encoded CRT feature list string generated by _get_encoded_feature_list or _get_encoded_feature_list_mqtt3.
421 Returns:
422 AWSIoTMetrics: The final metrics object ready to be embedded in the
423 MQTT CONNECT packet username field.
424 """
425
426 from awscrt import __version__ as crt_version
427
428 final_metrics = AWSIoTMetrics(
429 library_name=user_metrics.library_name if user_metrics else "IoTDeviceSDK/Python"
430 )
431
432 # CRTVERSION: not modifiable by user, automatically set
433 metadata = {"CRTVersion": crt_version}
434
435 # Extract user_metadata from IoT SDK
436 user_metrics_version = None
437 user_feature = ""
438 if user_metrics and user_metrics.metadata_entries:
439 for entry in user_metrics.metadata_entries:
440 if entry.key == "IoTSDKMetricsVersion":
441 user_metrics_version = entry.value
442 elif entry.key == "IoTSDKFeature":
443 user_feature = entry.value
444 elif entry.key != "CRTVersion":
445 metadata[entry.key] = entry.value
446
447 # Merge features: if version matches, merge CRT + SDK; otherwise CRT only
448 if (user_metrics_version is not None and user_metrics_version.isdigit() and int(
449 user_metrics_version) == IOT_SDK_METRICS_FEATURE_VERSION):
450 metadata["IoTSDKFeature"] = _merge_feature_lists(crt_feature_list, user_feature)
451 else:
452 metadata["IoTSDKFeature"] = _merge_feature_lists(crt_feature_list, "")
453
454 # Always set current metrics version
455 metadata["IoTSDKMetricsVersion"] = str(IOT_SDK_METRICS_FEATURE_VERSION)
456
457 final_metrics.metadata_entries = [IoTMetricsMetadata(key=k, value=v) for k, v in metadata.items()]
458 return final_metrics
459
460
461 def _create_metrics_mqtt5(client_options):
462 """Create the final AWSIoTMetrics object for an MQTT5 client.
463
464 Generates the CRT feature list from the full set of MQTT5 ClientOptions,
465 including detected certificate source from the TLS context.
466
467 Args:
468 client_options: MQTT5 ClientOptions dataclass containing all
469 connection configuration and optional user (AWSIoTMetrics) metrics.
470 Returns:
471 AWSIoTMetrics: The final metrics object with merged CRT and SDK features.
472 """
473 crt_feature_list = _get_encoded_feature_list(client_options)
474 return _create_metrics(client_options.metrics, crt_feature_list)
475
476
477 def _create_metrics_mqtt3(user_metrics=None, proxy_options=None, tls_ctx=None):
478 """Create the final AWSIoTMetrics object for an MQTT3 connection.
479
480 Generates the CRT feature list from the MQTT3 connection parameters,
481 including detected certificate source from the TLS context.
482
483 Args:
484 user_metrics: Optional AWSIoTMetrics configuration provided by the IoT SDK.
485 proxy_options: Optional HTTP proxy options from the Connection.
486 tls_ctx: Optional ClientTlsContext from the connection.
487 Returns:
488 AWSIoTMetrics: The final metrics object with merged CRT and SDK features.
489 """
490 crt_feature_list = _get_encoded_feature_list_mqtt3(proxy_options, tls_ctx)
491 return _create_metrics(user_metrics, crt_feature_list)