textmap.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. # Copyright The OpenTelemetry Authors
  2. # SPDX-License-Identifier: Apache-2.0
  3. import abc
  4. import typing
  5. from collections.abc import Iterable, Mapping, MutableMapping
  6. from opentelemetry.context.context import Context
  7. CarrierT = typing.TypeVar("CarrierT")
  8. # pylint: disable=invalid-name
  9. CarrierValT = list[str] | str
  10. class Getter(abc.ABC, typing.Generic[CarrierT]):
  11. """This class implements a Getter that enables extracting propagated
  12. fields from a carrier.
  13. """
  14. @abc.abstractmethod
  15. def get(self, carrier: CarrierT, key: str) -> list[str] | None:
  16. """Function that can retrieve zero
  17. or more values from the carrier. In the case that
  18. the value does not exist, returns None.
  19. Args:
  20. carrier: An object which contains values that are used to
  21. construct a Context.
  22. key: key of a field in carrier.
  23. Returns: first value of the propagation key or None if the key doesn't
  24. exist.
  25. """
  26. @abc.abstractmethod
  27. def keys(self, carrier: CarrierT) -> list[str]:
  28. """Function that can retrieve all the keys in a carrier object.
  29. Args:
  30. carrier: An object which contains values that are
  31. used to construct a Context.
  32. Returns:
  33. list of keys from the carrier.
  34. """
  35. class Setter(abc.ABC, typing.Generic[CarrierT]):
  36. """This class implements a Setter that enables injecting propagated
  37. fields into a carrier.
  38. """
  39. @abc.abstractmethod
  40. def set(self, carrier: CarrierT, key: str, value: str) -> None:
  41. """Function that can set a value into a carrier""
  42. Args:
  43. carrier: An object which contains values that are used to
  44. construct a Context.
  45. key: key of a field in carrier.
  46. value: value for a field in carrier.
  47. """
  48. class DefaultGetter(Getter[Mapping[str, CarrierValT]]):
  49. def get(
  50. self, carrier: Mapping[str, CarrierValT], key: str
  51. ) -> list[str] | None:
  52. """Getter implementation to retrieve a value from a dictionary.
  53. Args:
  54. carrier: dictionary in which to get value
  55. key: the key used to get the value
  56. Returns:
  57. A list with a single string with the value if it exists, else None.
  58. """
  59. val = carrier.get(key, None)
  60. if val is None:
  61. return None
  62. if isinstance(val, Iterable) and not isinstance(val, str):
  63. return list(val)
  64. return [val]
  65. def keys(self, carrier: Mapping[str, CarrierValT]) -> list[str]:
  66. """Keys implementation that returns all keys from a dictionary."""
  67. return list(carrier.keys())
  68. default_getter: Getter[CarrierT] = DefaultGetter() # type: ignore
  69. class DefaultSetter(Setter[MutableMapping[str, CarrierValT]]):
  70. def set(
  71. self,
  72. carrier: MutableMapping[str, CarrierValT],
  73. key: str,
  74. value: CarrierValT,
  75. ) -> None:
  76. """Setter implementation to set a value into a dictionary.
  77. Args:
  78. carrier: dictionary in which to set value
  79. key: the key used to set the value
  80. value: the value to set
  81. """
  82. carrier[key] = value
  83. default_setter: Setter[CarrierT] = DefaultSetter() # type: ignore
  84. class TextMapPropagator(abc.ABC):
  85. """This class provides an interface that enables extracting and injecting
  86. context into headers of HTTP requests. HTTP frameworks and clients
  87. can integrate with TextMapPropagator by providing the object containing the
  88. headers, and a getter and setter function for the extraction and
  89. injection of values, respectively.
  90. """
  91. @abc.abstractmethod
  92. def extract(
  93. self,
  94. carrier: CarrierT,
  95. context: Context | None = None,
  96. getter: Getter[CarrierT] = default_getter,
  97. ) -> Context:
  98. """Create a Context from values in the carrier.
  99. The extract function should retrieve values from the carrier
  100. object using getter, and use values to populate a
  101. Context value and return it.
  102. Args:
  103. getter: a function that can retrieve zero
  104. or more values from the carrier. In the case that
  105. the value does not exist, return an empty list.
  106. carrier: and object which contains values that are
  107. used to construct a Context. This object
  108. must be paired with an appropriate getter
  109. which understands how to extract a value from it.
  110. context: an optional Context to use. Defaults to root
  111. context if not set.
  112. Returns:
  113. A Context with configuration found in the carrier.
  114. """
  115. @abc.abstractmethod
  116. def inject(
  117. self,
  118. carrier: CarrierT,
  119. context: Context | None = None,
  120. setter: Setter[CarrierT] = default_setter,
  121. ) -> None:
  122. """Inject values from a Context into a carrier.
  123. inject enables the propagation of values into HTTP clients or
  124. other objects which perform an HTTP request. Implementations
  125. should use the `Setter` 's set method to set values on the
  126. carrier.
  127. Args:
  128. carrier: An object that a place to define HTTP headers.
  129. Should be paired with setter, which should
  130. know how to set header values on the carrier.
  131. context: an optional Context to use. Defaults to current
  132. context if not set.
  133. setter: An optional `Setter` object that can set values
  134. on the carrier.
  135. """
  136. @property
  137. @abc.abstractmethod
  138. def fields(self) -> set[str]:
  139. """
  140. Gets the fields set in the carrier by the `inject` method.
  141. If the carrier is reused, its fields that correspond with the ones
  142. present in this attribute should be deleted before calling `inject`.
  143. Returns:
  144. A set with the fields set in `inject`.
  145. """