base-api-utils 1.1.125__tar.gz → 1.1.126__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (138) hide show
  1. {base_api_utils-1.1.125/src/base_api_utils.egg-info → base_api_utils-1.1.126}/PKG-INFO +2 -1
  2. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/pyproject.toml +2 -1
  3. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/otel_instrumentation.py +125 -35
  4. {base_api_utils-1.1.125 → base_api_utils-1.1.126/src/base_api_utils.egg-info}/PKG-INFO +2 -1
  5. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils.egg-info/requires.txt +1 -0
  6. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/tests/test_otel_instrumentation.py +158 -2
  7. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/LICENSE +0 -0
  8. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/README.md +0 -0
  9. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/setup.cfg +0 -0
  10. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/__init__.py +0 -0
  11. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/commands/__init__.py +0 -0
  12. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/commands/failed_task_management_mixin.py +0 -0
  13. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/domain/__init__.py +0 -0
  14. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/domain/event_message.py +0 -0
  15. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/domain/event_message_factory.py +0 -0
  16. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/domain/events.py +0 -0
  17. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/domain/exceptions.py +0 -0
  18. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/dtos/__init__.py +0 -0
  19. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/dtos/authz_user.py +0 -0
  20. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/fields/__init__.py +0 -0
  21. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/fields/email_list_field.py +0 -0
  22. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/filters/__init__.py +0 -0
  23. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/filters/base_filter.py +0 -0
  24. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/filters/custom_ordering_filter.py +0 -0
  25. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/filters/filter_utils_mixin.py +0 -0
  26. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/handlers/__init__.py +0 -0
  27. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/handlers/base_event_handler.py +0 -0
  28. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/handlers/sponsor_event_handler.py +0 -0
  29. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/handlers/sponsorship_addon_event_handler.py +0 -0
  30. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/handlers/sponsorship_event_handler.py +0 -0
  31. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/handlers/summit_event_handler.py +0 -0
  32. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/ioc/__init__.py +0 -0
  33. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/ioc/container.py +0 -0
  34. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/log_handlers.py +0 -0
  35. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/log_redaction.py +0 -0
  36. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/logging_config.py +0 -0
  37. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/models/__init__.py +0 -0
  38. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/models/item_image.py +0 -0
  39. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/otel_celery.py +0 -0
  40. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/otel_logging.py +0 -0
  41. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/security/__init__.py +0 -0
  42. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/security/abstract_access_token_service.py +0 -0
  43. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/security/abstract_oauth2_api_client.py +0 -0
  44. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/security/access_token_service.py +0 -0
  45. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/security/check_sponsor_user_permissions.py +0 -0
  46. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/security/group_required.py +0 -0
  47. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/security/oauth2_authentication.py +0 -0
  48. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/security/oauth2_client_factory.py +0 -0
  49. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/security/oauth2_scope_required.py +0 -0
  50. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/security/permission_event_handler.py +0 -0
  51. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/security/shared.py +0 -0
  52. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/security/user_permissions_service.py +0 -0
  53. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/serializers/__init__.py +0 -0
  54. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/serializers/base_model_serializer.py +0 -0
  55. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/serializers/email_list_char_field.py +0 -0
  56. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/serializers/nullable_slug_related_field.py +0 -0
  57. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/serializers/serializers_registry.py +0 -0
  58. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/serializers/task_result_serializer.py +0 -0
  59. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/serializers/timestamp_field.py +0 -0
  60. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/serializers/v2/__init__.py +0 -0
  61. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/serializers/v2/abstract_serializer.py +0 -0
  62. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/serializers/v2/base_model_serializer.py +0 -0
  63. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/serializers/v2/expands.py +0 -0
  64. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/serializers/v2/query_params.py +0 -0
  65. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/serializers/v2/spectacular.py +0 -0
  66. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/services/__init__.py +0 -0
  67. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/services/abstract_domain_events_service.py +0 -0
  68. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/services/abstract_event_dispatcher.py +0 -0
  69. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/services/abstract_images_service.py +0 -0
  70. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/services/abstract_sponsor_metadata_service.py +0 -0
  71. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/services/abstract_storage_service.py +0 -0
  72. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/services/abstract_summit_metadata_service.py +0 -0
  73. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/services/amqp_service.py +0 -0
  74. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/services/celery_failed.py +0 -0
  75. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/services/event_dispatcher.py +0 -0
  76. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/services/images_service.py +0 -0
  77. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/services/s3_service.py +0 -0
  78. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/services/strategies/__init__.py +0 -0
  79. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/services/strategies/abstract_task_runner_strategy.py +0 -0
  80. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/services/strategies/publish_domain_event_strategy.py +0 -0
  81. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/tests/__init__.py +0 -0
  82. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/tests/test_failed_celery_task_management.py +0 -0
  83. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/tests/test_task_status_endpoints.py +0 -0
  84. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/tracing.py +0 -0
  85. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/urls.py +0 -0
  86. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/utils/__init__.py +0 -0
  87. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/utils/admin_groups.py +0 -0
  88. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/utils/async_helpers.py +0 -0
  89. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/utils/circuit_breaker.py +0 -0
  90. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/utils/config.py +0 -0
  91. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/utils/custom_auto_schema.py +0 -0
  92. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/utils/db_connection_helpers.py +0 -0
  93. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/utils/debounce_helpers.py +0 -0
  94. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/utils/enums.py +0 -0
  95. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/utils/env_var_eval.py +0 -0
  96. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/utils/exceptions.py +0 -0
  97. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/utils/expand_queryset_optimization_mixin.py +0 -0
  98. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/utils/external_errors.py +0 -0
  99. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/utils/file_lock.py +0 -0
  100. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/utils/fingerprint_helpers.py +0 -0
  101. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/utils/http_helpers.py +0 -0
  102. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/utils/inject_job.py +0 -0
  103. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/utils/log_redaction.py +0 -0
  104. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/utils/look_up_value_mixin.py +0 -0
  105. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/utils/model_helpers.py +0 -0
  106. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/utils/oauth2_custom_schema_base.py +0 -0
  107. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/utils/pagination.py +0 -0
  108. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/utils/rate_utils.py +0 -0
  109. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/utils/read_write_serializer_mixin.py +0 -0
  110. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/utils/serializers.py +0 -0
  111. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/utils/service_utils.py +0 -0
  112. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/utils/string.py +0 -0
  113. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/utils/tests.py +0 -0
  114. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/views/__init__.py +0 -0
  115. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/views/base_view.py +0 -0
  116. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/views/parent_children_crud.py +0 -0
  117. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/views/root_entity_crud.py +0 -0
  118. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils/views/tasks_result_view.py +0 -0
  119. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils.egg-info/SOURCES.txt +0 -0
  120. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils.egg-info/dependency_links.txt +0 -0
  121. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/src/base_api_utils.egg-info/top_level.txt +0 -0
  122. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/tests/test_amqp_service.py +0 -0
  123. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/tests/test_check_sponsor_user_permissions.py +0 -0
  124. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/tests/test_circuit_breaker.py +0 -0
  125. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/tests/test_db_connection_helpers.py +0 -0
  126. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/tests/test_file_lock.py +0 -0
  127. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/tests/test_is_admin.py +0 -0
  128. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/tests/test_lazy_imports.py +0 -0
  129. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/tests/test_log_redaction.py +0 -0
  130. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/tests/test_logging_config.py +0 -0
  131. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/tests/test_oauth2_scope_required.py +0 -0
  132. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/tests/test_otel_celery.py +0 -0
  133. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/tests/test_otel_logging.py +0 -0
  134. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/tests/test_retryable_event_propagation.py +0 -0
  135. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/tests/test_timestamp_field.py +0 -0
  136. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/tests/test_token_logging.py +0 -0
  137. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/tests/test_tracing.py +0 -0
  138. {base_api_utils-1.1.125 → base_api_utils-1.1.126}/tests/test_v2_abstract_serializer.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: base-api-utils
3
- Version: 1.1.125
3
+ Version: 1.1.126
4
4
  Summary: Django Rest Framework micro services common utilities
5
5
  Author-email: Román Gutierrez <roman@tipit.net>, Sebastian Marcet <sebastian@tipit.net>
6
6
  Project-URL: Homepage, https://github.com/fntechgit/base-api-utils
@@ -13,6 +13,7 @@ Requires-Dist: boto3
13
13
  Requires-Dist: celery
14
14
  Requires-Dist: Django>=3.2
15
15
  Requires-Dist: django-celery-results
16
+ Requires-Dist: django-model-utils
16
17
  Requires-Dist: django_filter
17
18
  Requires-Dist: djangorestframework>=3.15.2
18
19
  Requires-Dist: drf-spectacular
@@ -7,12 +7,13 @@ where = ["src"]
7
7
 
8
8
  [project]
9
9
  name = "base-api-utils"
10
- version = "1.1.125"
10
+ version = "1.1.126"
11
11
  dependencies = [
12
12
  "boto3",
13
13
  "celery",
14
14
  "Django>=3.2",
15
15
  "django-celery-results",
16
+ "django-model-utils",
16
17
  "django_filter",
17
18
  "djangorestframework>=3.15.2",
18
19
  "drf-spectacular",
@@ -19,6 +19,10 @@
19
19
  introspection results under the raw token, so: the request hooks rewrite the URL attributes, the
20
20
  Redis hook records the command and never the key, and ``RedactingSpanExporter`` strips the params
21
21
  from everything else before a span is exported.
22
+ - An attribute an instrumentation still records under a pre-stable name that collides with a
23
+ current namespace is exported under its stable name (``StableAttributeSpanExporter``): the
24
+ traces index rejects a Celery span whose ``messaging.destination`` is a string where it holds
25
+ ``messaging.destination.name``.
22
26
 
23
27
  settings.py imports this module, so it imports nothing from the rest of the package:
24
28
  ``base_api_utils.utils`` needs the settings to exist. It needs the OpenTelemetry SDK (the ``otel``
@@ -27,10 +31,12 @@ extra) and is imported only where tracing is on.
27
31
  It reports on the ``audit.otlp`` logger, which ``logging_config.build_logging`` keeps on the console.
28
32
  """
29
33
  import atexit
34
+ import importlib.util
30
35
  import logging
31
36
  import os
32
37
  import re
33
38
  import signal
39
+ import sys
34
40
  import threading
35
41
  from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
36
42
 
@@ -153,31 +159,109 @@ class RedactingSpanExporter(SpanExporter):
153
159
  status = span.status
154
160
  if status.description:
155
161
  status = Status(status.status_code, _redact_text(status.description))
156
- return ReadableSpan(
157
- name=span.name,
158
- context=span.context,
159
- parent=span.parent,
160
- resource=span.resource,
162
+ return _copy_span(
163
+ span,
161
164
  attributes=_redact_attributes(span.attributes or {}),
162
165
  events=[Event(event.name, _redact_attributes(event.attributes or {}), event.timestamp) for event in span.events],
163
- links=span.links,
164
- kind=span.kind,
165
166
  status=status,
166
- start_time=span.start_time,
167
- end_time=span.end_time,
168
- instrumentation_scope=span.instrumentation_scope,
169
167
  )
170
168
 
171
169
 
172
- def _load_instrumentors():
173
- """The instrumentor classes, imported here because each imports the library it instruments:
174
- a module that only wants the sampler or the exporter must not need MySQLdb or redis."""
175
- from opentelemetry.instrumentation.django import DjangoInstrumentor
176
- from opentelemetry.instrumentation.mysqlclient import MySQLClientInstrumentor
177
- from opentelemetry.instrumentation.redis import RedisInstrumentor
178
- from opentelemetry.instrumentation.requests import RequestsInstrumentor
170
+ # Attributes an instrumentation still records under a pre-stable name that the current conventions
171
+ # made a namespace, and the stable name each is exported under. An Elasticsearch index that holds
172
+ # spans of both kinds maps the namespace as an object and rejects, whole, every span that sends the
173
+ # old name as a value. The Celery instrumentation records the routing key as messaging.destination
174
+ # on every publish and every run, and does not read OTEL_SEMCONV_STABILITY_OPT_IN.
175
+ STABLE_ATTRIBUTE_NAMES = {
176
+ 'messaging.destination': 'messaging.destination.name',
177
+ }
178
+
179
+
180
+ class StableAttributeSpanExporter(SpanExporter):
181
+ """Export each attribute of ``STABLE_ATTRIBUTE_NAMES`` under its stable name.
182
+
183
+ A span that already carries the stable name keeps its value and loses the old one. Spans with
184
+ none of these attributes pass through as they are.
185
+ """
186
+
187
+ def __init__(self, exporter):
188
+ self._exporter = exporter
189
+
190
+ def export(self, spans):
191
+ return self._exporter.export([self._rename(span) for span in spans])
192
+
193
+ def shutdown(self):
194
+ return self._exporter.shutdown()
179
195
 
180
- return DjangoInstrumentor, MySQLClientInstrumentor, RedisInstrumentor, RequestsInstrumentor
196
+ def force_flush(self, timeout_millis=30000):
197
+ return self._exporter.force_flush(timeout_millis)
198
+
199
+ @staticmethod
200
+ def _rename(span):
201
+ attributes = span.attributes or {}
202
+ if not any(name in attributes for name in STABLE_ATTRIBUTE_NAMES):
203
+ return span
204
+ renamed = dict(attributes)
205
+ for name, stable_name in STABLE_ATTRIBUTE_NAMES.items():
206
+ if name in renamed:
207
+ renamed.setdefault(stable_name, renamed.pop(name))
208
+ return _copy_span(span, attributes=renamed)
209
+
210
+
211
+ def _copy_span(span, *, attributes, events=None, status=None):
212
+ """``span`` with other attributes, and other events or status when given: ReadableSpan is immutable."""
213
+ return ReadableSpan(
214
+ name=span.name,
215
+ context=span.context,
216
+ parent=span.parent,
217
+ resource=span.resource,
218
+ attributes=attributes,
219
+ events=span.events if events is None else events,
220
+ links=span.links,
221
+ kind=span.kind,
222
+ status=span.status if status is None else status,
223
+ start_time=span.start_time,
224
+ end_time=span.end_time,
225
+ instrumentation_scope=span.instrumentation_scope,
226
+ )
227
+
228
+
229
+ # The library each instrumentor instruments, the module that holds it and its class.
230
+ _INSTRUMENTORS = (
231
+ ('django', 'opentelemetry.instrumentation.django', 'DjangoInstrumentor'),
232
+ ('MySQLdb', 'opentelemetry.instrumentation.mysqlclient', 'MySQLClientInstrumentor'),
233
+ ('redis', 'opentelemetry.instrumentation.redis', 'RedisInstrumentor'),
234
+ ('requests', 'opentelemetry.instrumentation.requests', 'RequestsInstrumentor'),
235
+ )
236
+
237
+
238
+ def _is_installed(library):
239
+ """Whether ``library`` can be imported, without importing it."""
240
+ if library in sys.modules:
241
+ # find_spec() raises for a module that was put there with no __spec__. None blocks the import.
242
+ return sys.modules[library] is not None
243
+ return importlib.util.find_spec(library) is not None
244
+
245
+
246
+ def _load_instrumentors():
247
+ """The Django, mysqlclient, Redis and requests instrumentor classes, in that order.
248
+
249
+ They are imported here because each imports the library it instruments: a module that only
250
+ wants the sampler or the exporter must not need MySQLdb or redis. An instrumentor whose
251
+ library is not installed is None, so a service on SQLite, with no MySQLdb, still gets the
252
+ others.
253
+
254
+ A library that is installed without its instrumentation package raises ImportError: skipped,
255
+ the service would lose those spans with nothing to say so, since settings.py calls setup()
256
+ before Django applies LOGGING and the line below is dropped there."""
257
+ loaded = []
258
+ for library, module_name, class_name in _INSTRUMENTORS:
259
+ if not _is_installed(library):
260
+ logger.info('DjangoTelemetry: %s skipped, %s is not installed', class_name, library)
261
+ loaded.append(None)
262
+ continue
263
+ loaded.append(getattr(importlib.import_module(module_name), class_name))
264
+ return tuple(loaded)
181
265
 
182
266
 
183
267
  class DjangoTelemetry:
@@ -258,13 +342,13 @@ class DjangoTelemetry:
258
342
  """Enrich Redis spans with the command name.
259
343
 
260
344
  Keys are deliberately not recorded: token info is cached under the raw bearer token, so
261
- the key of every token lookup is a credential.
345
+ the key of every token lookup is a credential. The system is left to the instrumentation,
346
+ which records it under the name OTEL_SEMCONV_STABILITY_OPT_IN selects.
262
347
  """
263
348
  if not span.is_recording():
264
349
  return
265
350
  try:
266
351
  cmd = args[0] if args else ''
267
- span.set_attribute('db.system', 'redis')
268
352
  span.set_attribute('redis.command', cmd)
269
353
  except Exception:
270
354
  logger.debug('DjangoTelemetry::redis_hook - could not record the command', exc_info=True)
@@ -332,26 +416,32 @@ class DjangoTelemetry:
332
416
  cls._provider = provider
333
417
  exporter = cls.build_span_exporter(mode)
334
418
  if exporter is not None:
335
- provider.add_span_processor(BatchSpanProcessor(RedactingSpanExporter(exporter)))
419
+ provider.add_span_processor(
420
+ BatchSpanProcessor(RedactingSpanExporter(StableAttributeSpanExporter(exporter))))
336
421
  cls._register_shutdown_hooks()
337
422
 
338
423
  # The instrumentors are installed whatever OTEL_EXPORTER_MODE says: with no provider
339
424
  # configured their spans are no-ops, and tests drive the hooks through setup('test').
425
+ # An instrumentor whose library is not installed is None and is skipped.
340
426
  DjangoInstrumentor, MySQLClientInstrumentor, RedisInstrumentor, RequestsInstrumentor = _load_instrumentors()
341
- DjangoInstrumentor().instrument(
342
- request_hook=cls.request_hook,
343
- response_hook=cls.response_hook,
344
- )
345
- MySQLClientInstrumentor().instrument(
346
- enable_commenter=True,
347
- cursor_instrumentation_enabled=True,
348
- )
349
- RedisInstrumentor().instrument(
350
- tracer_provider=trace.get_tracer_provider(),
351
- request_hook=cls.redis_hook,
352
- )
353
- # Outgoing HTTP: every `requests` client (IDP introspection, sibling services, Stripe).
354
- RequestsInstrumentor().instrument(request_hook=cls.outgoing_request_hook)
427
+ if DjangoInstrumentor is not None:
428
+ DjangoInstrumentor().instrument(
429
+ request_hook=cls.request_hook,
430
+ response_hook=cls.response_hook,
431
+ )
432
+ if MySQLClientInstrumentor is not None:
433
+ MySQLClientInstrumentor().instrument(
434
+ enable_commenter=True,
435
+ cursor_instrumentation_enabled=True,
436
+ )
437
+ if RedisInstrumentor is not None:
438
+ RedisInstrumentor().instrument(
439
+ tracer_provider=trace.get_tracer_provider(),
440
+ request_hook=cls.redis_hook,
441
+ )
442
+ if RequestsInstrumentor is not None:
443
+ # Outgoing HTTP: every `requests` client (IDP introspection, sibling services, Stripe).
444
+ RequestsInstrumentor().instrument(request_hook=cls.outgoing_request_hook)
355
445
  if celery:
356
446
  # Publishing side: a task queued inside a request or job carries that trace to the
357
447
  # worker. The worker side is instrumented again in each forked process (otel_celery).
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: base-api-utils
3
- Version: 1.1.125
3
+ Version: 1.1.126
4
4
  Summary: Django Rest Framework micro services common utilities
5
5
  Author-email: Román Gutierrez <roman@tipit.net>, Sebastian Marcet <sebastian@tipit.net>
6
6
  Project-URL: Homepage, https://github.com/fntechgit/base-api-utils
@@ -13,6 +13,7 @@ Requires-Dist: boto3
13
13
  Requires-Dist: celery
14
14
  Requires-Dist: Django>=3.2
15
15
  Requires-Dist: django-celery-results
16
+ Requires-Dist: django-model-utils
16
17
  Requires-Dist: django_filter
17
18
  Requires-Dist: djangorestframework>=3.15.2
18
19
  Requires-Dist: drf-spectacular
@@ -2,6 +2,7 @@ boto3
2
2
  celery
3
3
  Django>=3.2
4
4
  django-celery-results
5
+ django-model-utils
5
6
  django_filter
6
7
  djangorestframework>=3.15.2
7
8
  drf-spectacular
@@ -205,6 +205,103 @@ class OtelRedactingSpanExporterTest(unittest.TestCase):
205
205
  inner.shutdown.assert_called_once_with()
206
206
 
207
207
 
208
+ class OtelStableAttributeSpanExporterTest(unittest.TestCase):
209
+ """An attribute recorded under a pre-stable name that a current convention made a namespace is
210
+ exported under its stable name.
211
+
212
+ The traces index maps messaging.destination as an object (messaging.destination.name) and
213
+ rejects a span that sends it as a string, which the Celery instrumentation does on every
214
+ publish and every run.
215
+ """
216
+
217
+ def setUp(self):
218
+ self.exported = InMemorySpanExporter()
219
+ self.provider = _provider(telemetry.StableAttributeSpanExporter(self.exported))
220
+
221
+ def _exported_attributes(self, **attributes):
222
+ with self.provider.get_tracer('test').start_as_current_span('apply_async/x', attributes=attributes):
223
+ pass
224
+ (span,) = self.exported.get_finished_spans()
225
+ return dict(span.attributes)
226
+
227
+ def test_the_routing_key_is_exported_under_the_stable_name(self):
228
+ attributes = self._exported_attributes(**{'messaging.destination': 'celery', 'celery.action': 'apply_async'})
229
+
230
+ self.assertEqual(attributes, {'messaging.destination.name': 'celery', 'celery.action': 'apply_async'})
231
+
232
+ def test_a_span_that_carries_both_names_keeps_the_stable_one(self):
233
+ attributes = self._exported_attributes(**{'messaging.destination': 'old', 'messaging.destination.name': 'new'})
234
+
235
+ self.assertEqual(attributes, {'messaging.destination.name': 'new'})
236
+
237
+ def test_the_renamed_span_keeps_the_rest_of_the_span(self):
238
+ tracer = self.provider.get_tracer('test')
239
+ with tracer.start_as_current_span('GET /probe', kind=SpanKind.SERVER) as parent:
240
+ with tracer.start_as_current_span('apply_async/x', kind=SpanKind.PRODUCER,
241
+ attributes={'messaging.destination': 'celery'}) as span:
242
+ span.add_event('published', {'attempt': 1})
243
+ span.set_status(Status(StatusCode.ERROR, 'broker down'))
244
+
245
+ exported = next(s for s in self.exported.get_finished_spans() if s.name == 'apply_async/x')
246
+ self.assertEqual(exported.kind, SpanKind.PRODUCER)
247
+ self.assertEqual(exported.context, span.get_span_context())
248
+ self.assertEqual(exported.parent, parent.get_span_context())
249
+ self.assertEqual((exported.start_time, exported.end_time), (span.start_time, span.end_time))
250
+ self.assertEqual(exported.status.description, 'broker down')
251
+ self.assertEqual([(event.name, dict(event.attributes)) for event in exported.events],
252
+ [('published', {'attempt': 1})])
253
+ self.assertEqual(exported.instrumentation_scope.name, 'test')
254
+
255
+ def test_a_span_without_a_renamed_attribute_is_exported_as_it_is(self):
256
+ finished = InMemorySpanExporter()
257
+ with _provider(finished).get_tracer('test').start_as_current_span(
258
+ 'GET', attributes={'http.url': 'https://api.example/v1/carts'}):
259
+ pass
260
+ (span,) = finished.get_finished_spans()
261
+ inner = MagicMock()
262
+
263
+ telemetry.StableAttributeSpanExporter(inner).export([span])
264
+
265
+ (exported,) = inner.export.call_args.args[0]
266
+ self.assertIs(exported, span)
267
+
268
+ def test_shutdown_and_flush_reach_the_wrapped_exporter(self):
269
+ inner = MagicMock()
270
+ exporter = telemetry.StableAttributeSpanExporter(inner)
271
+
272
+ exporter.force_flush(1234)
273
+ exporter.shutdown()
274
+
275
+ inner.force_flush.assert_called_once_with(1234)
276
+ inner.shutdown.assert_called_once_with()
277
+
278
+ def test_celery_publish_and_run_spans_export_the_routing_key_under_the_stable_name(self):
279
+ pytest.importorskip('opentelemetry.instrumentation.celery')
280
+ from celery import Celery
281
+ from opentelemetry.instrumentation.celery import CeleryInstrumentor
282
+
283
+ instrumentor = CeleryInstrumentor()
284
+ if instrumentor.is_instrumented_by_opentelemetry:
285
+ instrumentor.uninstrument()
286
+ instrumentor.instrument(tracer_provider=self.provider)
287
+ self.addCleanup(instrumentor.uninstrument)
288
+ app = Celery('stable-attributes', broker='memory://', backend='cache+memory://')
289
+
290
+ @app.task(name='probe.ping')
291
+ def ping():
292
+ return 'pong'
293
+
294
+ ping.apply_async()
295
+ ping.apply(routing_key='celery')
296
+
297
+ spans = {span.name: dict(span.attributes) for span in self.exported.get_finished_spans()}
298
+ self.assertEqual(set(spans), {'apply_async/probe.ping', 'run/probe.ping'})
299
+ for name, attributes in spans.items():
300
+ with self.subTest(name):
301
+ self.assertEqual(attributes['messaging.destination.name'], 'celery')
302
+ self.assertNotIn('messaging.destination', attributes)
303
+
304
+
208
305
  class _AcceptAllAdapter(BaseAdapter):
209
306
  def send(self, request, **kwargs):
210
307
  response = Response()
@@ -324,6 +421,14 @@ class OtelHooksTest(unittest.TestCase):
324
421
  self.assertEqual(attributes['redis.command'], 'GET')
325
422
  self.assertNotIn(TOKEN, str(attributes))
326
423
 
424
+ def test_the_redis_hook_leaves_the_system_name_to_the_instrumentation(self):
425
+ # The instrumentation records it under the name OTEL_SEMCONV_STABILITY_OPT_IN selects;
426
+ # a db.system from the hook would put the legacy name back on a db.system.name span.
427
+ with self.tracer.start_as_current_span('GET') as span:
428
+ DjangoTelemetry.redis_hook(span, MagicMock(), ('GET', 'k'), {})
429
+
430
+ self.assertNotIn('db.system', self._attributes())
431
+
327
432
  def test_a_span_that_is_not_recording_is_left_alone(self):
328
433
  span = MagicMock()
329
434
  span.is_recording.return_value = False
@@ -421,6 +526,19 @@ class OtelSetupTest(unittest.TestCase):
421
526
 
422
527
  self.instrument_celery.assert_not_called()
423
528
 
529
+ def test_an_instrumentor_whose_library_is_missing_is_skipped(self):
530
+ # file-upload-api runs on SQLite: there is no MySQLdb, so _load_instrumentors() has no
531
+ # mysqlclient instrumentor for it, and the others must still be installed.
532
+ django, _, redis, outgoing = self.instrumentors
533
+ self.load_instrumentors.return_value = [django, None, redis, outgoing]
534
+
535
+ with self._environ():
536
+ DjangoTelemetry.setup('test', service_name='file-upload-api')
537
+
538
+ for instrumentor in (django, redis, outgoing):
539
+ instrumentor.return_value.instrument.assert_called_once()
540
+ self.instrument_celery.assert_called_once_with()
541
+
424
542
  def test_the_test_environment_never_builds_a_provider(self):
425
543
  with self._environ(OTEL_EXPORTER_MODE='otel_endpoint'):
426
544
  DjangoTelemetry.setup('test', service_name='purchases-api')
@@ -436,7 +554,7 @@ class OtelSetupTest(unittest.TestCase):
436
554
  self.register_shutdown_hooks.assert_not_called()
437
555
 
438
556
  def test_outside_the_test_environment_the_provider_is_built_and_registered(self):
439
- # resource + sampler -> provider -> redacting exporter -> global.
557
+ # resource + sampler -> provider -> redacting exporter -> stable attribute names -> global.
440
558
  with self._environ(OTEL_EXPORTER_MODE='console', ENV='staging'):
441
559
  DjangoTelemetry.setup('staging', service_name='purchases-api')
442
560
 
@@ -447,7 +565,8 @@ class OtelSetupTest(unittest.TestCase):
447
565
  provider = self.TracerProvider.return_value
448
566
  exporter = self.BatchSpanProcessor.call_args.args[0]
449
567
  self.assertIsInstance(exporter, RedactingSpanExporter)
450
- self.assertIsInstance(exporter._exporter, ConsoleSpanExporter)
568
+ self.assertIsInstance(exporter._exporter, telemetry.StableAttributeSpanExporter)
569
+ self.assertIsInstance(exporter._exporter._exporter, ConsoleSpanExporter)
451
570
  provider.add_span_processor.assert_called_once_with(self.BatchSpanProcessor.return_value)
452
571
  self.trace.set_tracer_provider.assert_called_once_with(provider)
453
572
  self.assertIs(DjangoTelemetry._provider, provider)
@@ -474,6 +593,43 @@ class OtelSetupTest(unittest.TestCase):
474
593
  STALL_RELEASE_SECONDS = 5
475
594
 
476
595
 
596
+ class OtelLoadInstrumentorsTest(unittest.TestCase):
597
+ """_load_instrumentors() leaves out an instrumentor only when the library it instruments is not installed."""
598
+
599
+ def setUp(self):
600
+ # Each instrumentation module imports the library it instruments, so the modules are
601
+ # stubs, and so is redis, which the tests do not install. None in sys.modules makes an
602
+ # import raise ImportError: importing the mysqlclient module fails, as it does wherever
603
+ # opentelemetry-instrumentation-mysqlclient or MySQLdb is missing.
604
+ self.stubs = {name: MagicMock(name=name) for name in ('DjangoInstrumentor', 'RedisInstrumentor', 'RequestsInstrumentor')}
605
+ self.modules = {
606
+ 'redis': MagicMock(name='redis'),
607
+ 'opentelemetry.instrumentation.django': MagicMock(DjangoInstrumentor=self.stubs['DjangoInstrumentor']),
608
+ 'opentelemetry.instrumentation.mysqlclient': None,
609
+ 'opentelemetry.instrumentation.redis': MagicMock(RedisInstrumentor=self.stubs['RedisInstrumentor']),
610
+ 'opentelemetry.instrumentation.requests': MagicMock(RequestsInstrumentor=self.stubs['RequestsInstrumentor']),
611
+ }
612
+
613
+ def test_a_missing_library_leaves_its_instrumentor_out(self):
614
+ # A service on SQLite: no MySQLdb.
615
+ with patch.dict(sys.modules, {**self.modules, 'MySQLdb': None}), \
616
+ self.assertLogs('audit.otlp', level='INFO') as logs:
617
+ django, mysqlclient, redis, outgoing = telemetry._load_instrumentors()
618
+
619
+ self.assertIsNone(mysqlclient)
620
+ self.assertEqual((django, redis, outgoing),
621
+ (self.stubs['DjangoInstrumentor'], self.stubs['RedisInstrumentor'], self.stubs['RequestsInstrumentor']))
622
+ self.assertEqual(len(logs.output), 1)
623
+ self.assertIn('MySQLClientInstrumentor', logs.output[0])
624
+
625
+ def test_an_installed_library_without_its_instrumentation_package_raises(self):
626
+ # MySQLdb is installed and opentelemetry-instrumentation-mysqlclient is not: skipped, a
627
+ # service on MySQL would run with no database spans and nothing to say so.
628
+ with patch.dict(sys.modules, {**self.modules, 'MySQLdb': MagicMock(name='MySQLdb')}):
629
+ with self.assertRaises(ImportError):
630
+ telemetry._load_instrumentors()
631
+
632
+
477
633
  class _StalledSpanExporter(SpanExporter):
478
634
  """A collector that accepts the connection and never answers: every export blocks until released."""
479
635