We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Consider renaming BaggagePropagator
BaggagePropagator is probably a too-generic name. In contrast, there's `TraceContextTextMapPropagator`, so maybe renaming it to something along those lines could convey more clarity.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `opentelemetry-api/src/opentelemetry/baggage/propagation/__init__.py`
Content:
```
1 # Copyright The OpenTelemetry Authors
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #     http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 #
15 import typing
16 import urllib.parse
17 
18 from opentelemetry import baggage
19 from opentelemetry.context import get_current
20 from opentelemetry.context.context import Context
21 from opentelemetry.propagators import textmap
22 
23 
24 class BaggagePropagator(textmap.TextMapPropagator):
25     """Extracts and injects Baggage which is used to annotate telemetry."""
26 
27     MAX_HEADER_LENGTH = 8192
28     MAX_PAIR_LENGTH = 4096
29     MAX_PAIRS = 180
30     _BAGGAGE_HEADER_NAME = "baggage"
31 
32     def extract(
33         self,
34         getter: textmap.Getter[textmap.TextMapPropagatorT],
35         carrier: textmap.TextMapPropagatorT,
36         context: typing.Optional[Context] = None,
37     ) -> Context:
38         """Extract Baggage from the carrier.
39 
40         See
41         `opentelemetry.propagators.textmap.TextMapPropagator.extract`
42         """
43 
44         if context is None:
45             context = get_current()
46 
47         header = _extract_first_element(
48             getter.get(carrier, self._BAGGAGE_HEADER_NAME)
49         )
50 
51         if not header or len(header) > self.MAX_HEADER_LENGTH:
52             return context
53 
54         baggage_entries = header.split(",")
55         total_baggage_entries = self.MAX_PAIRS
56         for entry in baggage_entries:
57             if total_baggage_entries <= 0:
58                 return context
59             total_baggage_entries -= 1
60             if len(entry) > self.MAX_PAIR_LENGTH:
61                 continue
62             try:
63                 name, value = entry.split("=", 1)
64             except Exception:  # pylint: disable=broad-except
65                 continue
66             context = baggage.set_baggage(
67                 urllib.parse.unquote(name).strip(),
68                 urllib.parse.unquote(value).strip(),
69                 context=context,
70             )
71 
72         return context
73 
74     def inject(
75         self,
76         set_in_carrier: textmap.Setter[textmap.TextMapPropagatorT],
77         carrier: textmap.TextMapPropagatorT,
78         context: typing.Optional[Context] = None,
79     ) -> None:
80         """Injects Baggage into the carrier.
81 
82         See
83         `opentelemetry.propagators.textmap.TextMapPropagator.inject`
84         """
85         baggage_entries = baggage.get_all(context=context)
86         if not baggage_entries:
87             return
88 
89         baggage_string = _format_baggage(baggage_entries)
90         set_in_carrier(carrier, self._BAGGAGE_HEADER_NAME, baggage_string)
91 
92     @property
93     def fields(self) -> typing.Set[str]:
94         """Returns a set with the fields set in `inject`."""
95         return {self._BAGGAGE_HEADER_NAME}
96 
97 
98 def _format_baggage(baggage_entries: typing.Mapping[str, object]) -> str:
99     return ",".join(
100         key + "=" + urllib.parse.quote_plus(str(value))
101         for key, value in baggage_entries.items()
102     )
103 
104 
105 def _extract_first_element(
106     items: typing.Optional[typing.Iterable[textmap.TextMapPropagatorT]],
107 ) -> typing.Optional[textmap.TextMapPropagatorT]:
108     if items is None:
109         return None
110     return next(iter(items), None)
111
```

Path: `opentelemetry-api/src/opentelemetry/propagate/__init__.py`
Content:
```
1 # Copyright The OpenTelemetry Authors
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #     http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 
15 """
16 API for propagation of context.
17 
18 The propagators for the
19 ``opentelemetry.propagators.composite.CompositeHTTPPropagator`` can be defined
20 via configuration in the ``OTEL_PROPAGATORS`` environment variable. This
21 variable should be set to a comma-separated string of names of values for the
22 ``opentelemetry_propagator`` entry point. For example, setting
23 ``OTEL_PROPAGATORS`` to ``tracecontext,baggage`` (which is the default value)
24 would instantiate
25 ``opentelemetry.propagators.composite.CompositeHTTPPropagator`` with 2
26 propagators, one of type
27 ``opentelemetry.trace.propagation.tracecontext.TraceContextTextMapPropagator``
28 and other of type ``opentelemetry.baggage.propagation.BaggagePropagator``.
29 Notice that these propagator classes are defined as
30 ``opentelemetry_propagator`` entry points in the ``setup.cfg`` file of
31 ``opentelemetry``.
32 
33 Example::
34 
35     import flask
36     import requests
37     from opentelemetry import propagators
38 
39 
40     PROPAGATOR = propagators.get_global_textmap()
41 
42 
43     def get_header_from_flask_request(request, key):
44         return request.headers.get_all(key)
45 
46     def set_header_into_requests_request(request: requests.Request,
47                                             key: str, value: str):
48         request.headers[key] = value
49 
50     def example_route():
51         context = PROPAGATOR.extract(
52             get_header_from_flask_request,
53             flask.request
54         )
55         request_to_downstream = requests.Request(
56             "GET", "http://httpbin.org/get"
57         )
58         PROPAGATOR.inject(
59             set_header_into_requests_request,
60             request_to_downstream,
61             context=context
62         )
63         session = requests.Session()
64         session.send(request_to_downstream.prepare())
65 
66 
67 .. _Propagation API Specification:
68     https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/context/api-propagators.md
69 """
70 
71 import typing
72 from logging import getLogger
73 from os import environ
74 
75 from pkg_resources import iter_entry_points
76 
77 from opentelemetry.context.context import Context
78 from opentelemetry.environment_variables import OTEL_PROPAGATORS
79 from opentelemetry.propagators import composite, textmap
80 
81 logger = getLogger(__name__)
82 
83 
84 def extract(
85     getter: textmap.Getter[textmap.TextMapPropagatorT],
86     carrier: textmap.TextMapPropagatorT,
87     context: typing.Optional[Context] = None,
88 ) -> Context:
89     """Uses the configured propagator to extract a Context from the carrier.
90 
91     Args:
92         getter: an object which contains a get function that can retrieve zero
93             or more values from the carrier and a keys function that can get all the keys
94             from carrier.
95         carrier: and object which contains values that are
96             used to construct a Context. This object
97             must be paired with an appropriate getter
98             which understands how to extract a value from it.
99         context: an optional Context to use. Defaults to current
100             context if not set.
101     """
102     return get_global_textmap().extract(getter, carrier, context)
103 
104 
105 def inject(
106     set_in_carrier: textmap.Setter[textmap.TextMapPropagatorT],
107     carrier: textmap.TextMapPropagatorT,
108     context: typing.Optional[Context] = None,
109 ) -> None:
110     """Uses the configured propagator to inject a Context into the carrier.
111 
112     Args:
113         set_in_carrier: A setter function that can set values
114             on the carrier.
115         carrier: An object that contains a representation of HTTP
116             headers. Should be paired with set_in_carrier, which
117             should know how to set header values on the carrier.
118         context: an optional Context to use. Defaults to current
119             context if not set.
120     """
121     get_global_textmap().inject(set_in_carrier, carrier, context)
122 
123 
124 try:
125 
126     propagators = []
127 
128     # Single use variable here to hack black and make lint pass
129     environ_propagators = environ.get(
130         OTEL_PROPAGATORS, "tracecontext,baggage",
131     )
132 
133     for propagator in environ_propagators.split(","):
134         propagators.append(  # type: ignore
135             next(  # type: ignore
136                 iter_entry_points("opentelemetry_propagator", propagator)
137             ).load()()
138         )
139 
140 except Exception:  # pylint: disable=broad-except
141     logger.exception("Failed to load configured propagators")
142     raise
143 
144 _HTTP_TEXT_FORMAT = composite.CompositeHTTPPropagator(propagators)  # type: ignore
145 
146 
147 def get_global_textmap() -> textmap.TextMapPropagator:
148     return _HTTP_TEXT_FORMAT
149 
150 
151 def set_global_textmap(http_text_format: textmap.TextMapPropagator,) -> None:
152     global _HTTP_TEXT_FORMAT  # pylint:disable=global-statement
153     _HTTP_TEXT_FORMAT = http_text_format  # type: ignore
154
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/opentelemetry-api/src/opentelemetry/baggage/propagation/__init__.py b/opentelemetry-api/src/opentelemetry/baggage/propagation/__init__.py
--- a/opentelemetry-api/src/opentelemetry/baggage/propagation/__init__.py
+++ b/opentelemetry-api/src/opentelemetry/baggage/propagation/__init__.py
@@ -21,7 +21,7 @@
 from opentelemetry.propagators import textmap
 
 
-class BaggagePropagator(textmap.TextMapPropagator):
+class W3CBaggagePropagator(textmap.TextMapPropagator):
     """Extracts and injects Baggage which is used to annotate telemetry."""
 
     MAX_HEADER_LENGTH = 8192
diff --git a/opentelemetry-api/src/opentelemetry/propagate/__init__.py b/opentelemetry-api/src/opentelemetry/propagate/__init__.py
--- a/opentelemetry-api/src/opentelemetry/propagate/__init__.py
+++ b/opentelemetry-api/src/opentelemetry/propagate/__init__.py
@@ -25,7 +25,7 @@
 ``opentelemetry.propagators.composite.CompositeHTTPPropagator`` with 2
 propagators, one of type
 ``opentelemetry.trace.propagation.tracecontext.TraceContextTextMapPropagator``
-and other of type ``opentelemetry.baggage.propagation.BaggagePropagator``.
+and other of type ``opentelemetry.baggage.propagation.W3CBaggagePropagator``.
 Notice that these propagator classes are defined as
 ``opentelemetry_propagator`` entry points in the ``setup.cfg`` file of
 ``opentelemetry``.

{"golden_diff": "diff --git a/opentelemetry-api/src/opentelemetry/baggage/propagation/__init__.py b/opentelemetry-api/src/opentelemetry/baggage/propagation/__init__.py\n--- a/opentelemetry-api/src/opentelemetry/baggage/propagation/__init__.py\n+++ b/opentelemetry-api/src/opentelemetry/baggage/propagation/__init__.py\n@@ -21,7 +21,7 @@\n from opentelemetry.propagators import textmap\n \n \n-class BaggagePropagator(textmap.TextMapPropagator):\n+class W3CBaggagePropagator(textmap.TextMapPropagator):\n     \"\"\"Extracts and injects Baggage which is used to annotate telemetry.\"\"\"\n \n     MAX_HEADER_LENGTH = 8192\ndiff --git a/opentelemetry-api/src/opentelemetry/propagate/__init__.py b/opentelemetry-api/src/opentelemetry/propagate/__init__.py\n--- a/opentelemetry-api/src/opentelemetry/propagate/__init__.py\n+++ b/opentelemetry-api/src/opentelemetry/propagate/__init__.py\n@@ -25,7 +25,7 @@\n ``opentelemetry.propagators.composite.CompositeHTTPPropagator`` with 2\n propagators, one of type\n ``opentelemetry.trace.propagation.tracecontext.TraceContextTextMapPropagator``\n-and other of type ``opentelemetry.baggage.propagation.BaggagePropagator``.\n+and other of type ``opentelemetry.baggage.propagation.W3CBaggagePropagator``.\n Notice that these propagator classes are defined as\n ``opentelemetry_propagator`` entry points in the ``setup.cfg`` file of\n ``opentelemetry``.\n", "issue": "Consider renaming BaggagePropagator\nBaggagePropagator is probably a too-generic name. In contrast, there's `TraceContextTextMapPropagator`, so maybe renaming it to something along those lines could convey more clarity.\n", "before_files": [{"content": "# Copyright The OpenTelemetry Authors\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nimport typing\nimport urllib.parse\n\nfrom opentelemetry import baggage\nfrom opentelemetry.context import get_current\nfrom opentelemetry.context.context import Context\nfrom opentelemetry.propagators import textmap\n\n\nclass BaggagePropagator(textmap.TextMapPropagator):\n    \"\"\"Extracts and injects Baggage which is used to annotate telemetry.\"\"\"\n\n    MAX_HEADER_LENGTH = 8192\n    MAX_PAIR_LENGTH = 4096\n    MAX_PAIRS = 180\n    _BAGGAGE_HEADER_NAME = \"baggage\"\n\n    def extract(\n        self,\n        getter: textmap.Getter[textmap.TextMapPropagatorT],\n        carrier: textmap.TextMapPropagatorT,\n        context: typing.Optional[Context] = None,\n    ) -> Context:\n        \"\"\"Extract Baggage from the carrier.\n\n        See\n        `opentelemetry.propagators.textmap.TextMapPropagator.extract`\n        \"\"\"\n\n        if context is None:\n            context = get_current()\n\n        header = _extract_first_element(\n            getter.get(carrier, self._BAGGAGE_HEADER_NAME)\n        )\n\n        if not header or len(header) > self.MAX_HEADER_LENGTH:\n            return context\n\n        baggage_entries = header.split(\",\")\n        total_baggage_entries = self.MAX_PAIRS\n        for entry in baggage_entries:\n            if total_baggage_entries <= 0:\n                return context\n            total_baggage_entries -= 1\n            if len(entry) > self.MAX_PAIR_LENGTH:\n                continue\n            try:\n                name, value = entry.split(\"=\", 1)\n            except Exception:  # pylint: disable=broad-except\n                continue\n            context = baggage.set_baggage(\n                urllib.parse.unquote(name).strip(),\n                urllib.parse.unquote(value).strip(),\n                context=context,\n            )\n\n        return context\n\n    def inject(\n        self,\n        set_in_carrier: textmap.Setter[textmap.TextMapPropagatorT],\n        carrier: textmap.TextMapPropagatorT,\n        context: typing.Optional[Context] = None,\n    ) -> None:\n        \"\"\"Injects Baggage into the carrier.\n\n        See\n        `opentelemetry.propagators.textmap.TextMapPropagator.inject`\n        \"\"\"\n        baggage_entries = baggage.get_all(context=context)\n        if not baggage_entries:\n            return\n\n        baggage_string = _format_baggage(baggage_entries)\n        set_in_carrier(carrier, self._BAGGAGE_HEADER_NAME, baggage_string)\n\n    @property\n    def fields(self) -> typing.Set[str]:\n        \"\"\"Returns a set with the fields set in `inject`.\"\"\"\n        return {self._BAGGAGE_HEADER_NAME}\n\n\ndef _format_baggage(baggage_entries: typing.Mapping[str, object]) -> str:\n    return \",\".join(\n        key + \"=\" + urllib.parse.quote_plus(str(value))\n        for key, value in baggage_entries.items()\n    )\n\n\ndef _extract_first_element(\n    items: typing.Optional[typing.Iterable[textmap.TextMapPropagatorT]],\n) -> typing.Optional[textmap.TextMapPropagatorT]:\n    if items is None:\n        return None\n    return next(iter(items), None)\n", "path": "opentelemetry-api/src/opentelemetry/baggage/propagation/__init__.py"}, {"content": "# Copyright The OpenTelemetry Authors\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nAPI for propagation of context.\n\nThe propagators for the\n``opentelemetry.propagators.composite.CompositeHTTPPropagator`` can be defined\nvia configuration in the ``OTEL_PROPAGATORS`` environment variable. This\nvariable should be set to a comma-separated string of names of values for the\n``opentelemetry_propagator`` entry point. For example, setting\n``OTEL_PROPAGATORS`` to ``tracecontext,baggage`` (which is the default value)\nwould instantiate\n``opentelemetry.propagators.composite.CompositeHTTPPropagator`` with 2\npropagators, one of type\n``opentelemetry.trace.propagation.tracecontext.TraceContextTextMapPropagator``\nand other of type ``opentelemetry.baggage.propagation.BaggagePropagator``.\nNotice that these propagator classes are defined as\n``opentelemetry_propagator`` entry points in the ``setup.cfg`` file of\n``opentelemetry``.\n\nExample::\n\n    import flask\n    import requests\n    from opentelemetry import propagators\n\n\n    PROPAGATOR = propagators.get_global_textmap()\n\n\n    def get_header_from_flask_request(request, key):\n        return request.headers.get_all(key)\n\n    def set_header_into_requests_request(request: requests.Request,\n                                            key: str, value: str):\n        request.headers[key] = value\n\n    def example_route():\n        context = PROPAGATOR.extract(\n            get_header_from_flask_request,\n            flask.request\n        )\n        request_to_downstream = requests.Request(\n            \"GET\", \"http://httpbin.org/get\"\n        )\n        PROPAGATOR.inject(\n            set_header_into_requests_request,\n            request_to_downstream,\n            context=context\n        )\n        session = requests.Session()\n        session.send(request_to_downstream.prepare())\n\n\n.. _Propagation API Specification:\n    https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/context/api-propagators.md\n\"\"\"\n\nimport typing\nfrom logging import getLogger\nfrom os import environ\n\nfrom pkg_resources import iter_entry_points\n\nfrom opentelemetry.context.context import Context\nfrom opentelemetry.environment_variables import OTEL_PROPAGATORS\nfrom opentelemetry.propagators import composite, textmap\n\nlogger = getLogger(__name__)\n\n\ndef extract(\n    getter: textmap.Getter[textmap.TextMapPropagatorT],\n    carrier: textmap.TextMapPropagatorT,\n    context: typing.Optional[Context] = None,\n) -> Context:\n    \"\"\"Uses the configured propagator to extract a Context from the carrier.\n\n    Args:\n        getter: an object which contains a get function that can retrieve zero\n            or more values from the carrier and a keys function that can get all the keys\n            from carrier.\n        carrier: and object which contains values that are\n            used to construct a Context. This object\n            must be paired with an appropriate getter\n            which understands how to extract a value from it.\n        context: an optional Context to use. Defaults to current\n            context if not set.\n    \"\"\"\n    return get_global_textmap().extract(getter, carrier, context)\n\n\ndef inject(\n    set_in_carrier: textmap.Setter[textmap.TextMapPropagatorT],\n    carrier: textmap.TextMapPropagatorT,\n    context: typing.Optional[Context] = None,\n) -> None:\n    \"\"\"Uses the configured propagator to inject a Context into the carrier.\n\n    Args:\n        set_in_carrier: A setter function that can set values\n            on the carrier.\n        carrier: An object that contains a representation of HTTP\n            headers. Should be paired with set_in_carrier, which\n            should know how to set header values on the carrier.\n        context: an optional Context to use. Defaults to current\n            context if not set.\n    \"\"\"\n    get_global_textmap().inject(set_in_carrier, carrier, context)\n\n\ntry:\n\n    propagators = []\n\n    # Single use variable here to hack black and make lint pass\n    environ_propagators = environ.get(\n        OTEL_PROPAGATORS, \"tracecontext,baggage\",\n    )\n\n    for propagator in environ_propagators.split(\",\"):\n        propagators.append(  # type: ignore\n            next(  # type: ignore\n                iter_entry_points(\"opentelemetry_propagator\", propagator)\n            ).load()()\n        )\n\nexcept Exception:  # pylint: disable=broad-except\n    logger.exception(\"Failed to load configured propagators\")\n    raise\n\n_HTTP_TEXT_FORMAT = composite.CompositeHTTPPropagator(propagators)  # type: ignore\n\n\ndef get_global_textmap() -> textmap.TextMapPropagator:\n    return _HTTP_TEXT_FORMAT\n\n\ndef set_global_textmap(http_text_format: textmap.TextMapPropagator,) -> None:\n    global _HTTP_TEXT_FORMAT  # pylint:disable=global-statement\n    _HTTP_TEXT_FORMAT = http_text_format  # type: ignore\n", "path": "opentelemetry-api/src/opentelemetry/propagate/__init__.py"}], "after_files": [{"content": "# Copyright The OpenTelemetry Authors\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nimport typing\nimport urllib.parse\n\nfrom opentelemetry import baggage\nfrom opentelemetry.context import get_current\nfrom opentelemetry.context.context import Context\nfrom opentelemetry.propagators import textmap\n\n\nclass W3CBaggagePropagator(textmap.TextMapPropagator):\n    \"\"\"Extracts and injects Baggage which is used to annotate telemetry.\"\"\"\n\n    MAX_HEADER_LENGTH = 8192\n    MAX_PAIR_LENGTH = 4096\n    MAX_PAIRS = 180\n    _BAGGAGE_HEADER_NAME = \"baggage\"\n\n    def extract(\n        self,\n        getter: textmap.Getter[textmap.TextMapPropagatorT],\n        carrier: textmap.TextMapPropagatorT,\n        context: typing.Optional[Context] = None,\n    ) -> Context:\n        \"\"\"Extract Baggage from the carrier.\n\n        See\n        `opentelemetry.propagators.textmap.TextMapPropagator.extract`\n        \"\"\"\n\n        if context is None:\n            context = get_current()\n\n        header = _extract_first_element(\n            getter.get(carrier, self._BAGGAGE_HEADER_NAME)\n        )\n\n        if not header or len(header) > self.MAX_HEADER_LENGTH:\n            return context\n\n        baggage_entries = header.split(\",\")\n        total_baggage_entries = self.MAX_PAIRS\n        for entry in baggage_entries:\n            if total_baggage_entries <= 0:\n                return context\n            total_baggage_entries -= 1\n            if len(entry) > self.MAX_PAIR_LENGTH:\n                continue\n            try:\n                name, value = entry.split(\"=\", 1)\n            except Exception:  # pylint: disable=broad-except\n                continue\n            context = baggage.set_baggage(\n                urllib.parse.unquote(name).strip(),\n                urllib.parse.unquote(value).strip(),\n                context=context,\n            )\n\n        return context\n\n    def inject(\n        self,\n        set_in_carrier: textmap.Setter[textmap.TextMapPropagatorT],\n        carrier: textmap.TextMapPropagatorT,\n        context: typing.Optional[Context] = None,\n    ) -> None:\n        \"\"\"Injects Baggage into the carrier.\n\n        See\n        `opentelemetry.propagators.textmap.TextMapPropagator.inject`\n        \"\"\"\n        baggage_entries = baggage.get_all(context=context)\n        if not baggage_entries:\n            return\n\n        baggage_string = _format_baggage(baggage_entries)\n        set_in_carrier(carrier, self._BAGGAGE_HEADER_NAME, baggage_string)\n\n    @property\n    def fields(self) -> typing.Set[str]:\n        \"\"\"Returns a set with the fields set in `inject`.\"\"\"\n        return {self._BAGGAGE_HEADER_NAME}\n\n\ndef _format_baggage(baggage_entries: typing.Mapping[str, object]) -> str:\n    return \",\".join(\n        key + \"=\" + urllib.parse.quote_plus(str(value))\n        for key, value in baggage_entries.items()\n    )\n\n\ndef _extract_first_element(\n    items: typing.Optional[typing.Iterable[textmap.TextMapPropagatorT]],\n) -> typing.Optional[textmap.TextMapPropagatorT]:\n    if items is None:\n        return None\n    return next(iter(items), None)\n", "path": "opentelemetry-api/src/opentelemetry/baggage/propagation/__init__.py"}, {"content": "# Copyright The OpenTelemetry Authors\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nAPI for propagation of context.\n\nThe propagators for the\n``opentelemetry.propagators.composite.CompositeHTTPPropagator`` can be defined\nvia configuration in the ``OTEL_PROPAGATORS`` environment variable. This\nvariable should be set to a comma-separated string of names of values for the\n``opentelemetry_propagator`` entry point. For example, setting\n``OTEL_PROPAGATORS`` to ``tracecontext,baggage`` (which is the default value)\nwould instantiate\n``opentelemetry.propagators.composite.CompositeHTTPPropagator`` with 2\npropagators, one of type\n``opentelemetry.trace.propagation.tracecontext.TraceContextTextMapPropagator``\nand other of type ``opentelemetry.baggage.propagation.W3CBaggagePropagator``.\nNotice that these propagator classes are defined as\n``opentelemetry_propagator`` entry points in the ``setup.cfg`` file of\n``opentelemetry``.\n\nExample::\n\n    import flask\n    import requests\n    from opentelemetry import propagators\n\n\n    PROPAGATOR = propagators.get_global_textmap()\n\n\n    def get_header_from_flask_request(request, key):\n        return request.headers.get_all(key)\n\n    def set_header_into_requests_request(request: requests.Request,\n                                            key: str, value: str):\n        request.headers[key] = value\n\n    def example_route():\n        context = PROPAGATOR.extract(\n            get_header_from_flask_request,\n            flask.request\n        )\n        request_to_downstream = requests.Request(\n            \"GET\", \"http://httpbin.org/get\"\n        )\n        PROPAGATOR.inject(\n            set_header_into_requests_request,\n            request_to_downstream,\n            context=context\n        )\n        session = requests.Session()\n        session.send(request_to_downstream.prepare())\n\n\n.. _Propagation API Specification:\n    https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/context/api-propagators.md\n\"\"\"\n\nimport typing\nfrom logging import getLogger\nfrom os import environ\n\nfrom pkg_resources import iter_entry_points\n\nfrom opentelemetry.context.context import Context\nfrom opentelemetry.environment_variables import OTEL_PROPAGATORS\nfrom opentelemetry.propagators import composite, textmap\n\nlogger = getLogger(__name__)\n\n\ndef extract(\n    getter: textmap.Getter[textmap.TextMapPropagatorT],\n    carrier: textmap.TextMapPropagatorT,\n    context: typing.Optional[Context] = None,\n) -> Context:\n    \"\"\"Uses the configured propagator to extract a Context from the carrier.\n\n    Args:\n        getter: an object which contains a get function that can retrieve zero\n            or more values from the carrier and a keys function that can get all the keys\n            from carrier.\n        carrier: and object which contains values that are\n            used to construct a Context. This object\n            must be paired with an appropriate getter\n            which understands how to extract a value from it.\n        context: an optional Context to use. Defaults to current\n            context if not set.\n    \"\"\"\n    return get_global_textmap().extract(getter, carrier, context)\n\n\ndef inject(\n    set_in_carrier: textmap.Setter[textmap.TextMapPropagatorT],\n    carrier: textmap.TextMapPropagatorT,\n    context: typing.Optional[Context] = None,\n) -> None:\n    \"\"\"Uses the configured propagator to inject a Context into the carrier.\n\n    Args:\n        set_in_carrier: A setter function that can set values\n            on the carrier.\n        carrier: An object that contains a representation of HTTP\n            headers. Should be paired with set_in_carrier, which\n            should know how to set header values on the carrier.\n        context: an optional Context to use. Defaults to current\n            context if not set.\n    \"\"\"\n    get_global_textmap().inject(set_in_carrier, carrier, context)\n\n\ntry:\n\n    propagators = []\n\n    # Single use variable here to hack black and make lint pass\n    environ_propagators = environ.get(\n        OTEL_PROPAGATORS, \"tracecontext,baggage\",\n    )\n\n    for propagator in environ_propagators.split(\",\"):\n        propagators.append(  # type: ignore\n            next(  # type: ignore\n                iter_entry_points(\"opentelemetry_propagator\", propagator)\n            ).load()()\n        )\n\nexcept Exception:  # pylint: disable=broad-except\n    logger.exception(\"Failed to load configured propagators\")\n    raise\n\n_HTTP_TEXT_FORMAT = composite.CompositeHTTPPropagator(propagators)  # type: ignore\n\n\ndef get_global_textmap() -> textmap.TextMapPropagator:\n    return _HTTP_TEXT_FORMAT\n\n\ndef set_global_textmap(http_text_format: textmap.TextMapPropagator,) -> None:\n    global _HTTP_TEXT_FORMAT  # pylint:disable=global-statement\n    _HTTP_TEXT_FORMAT = http_text_format  # type: ignore\n", "path": "opentelemetry-api/src/opentelemetry/propagate/__init__.py"}]}