latch-asgi 0.2.0__tar.gz → 1.0.0__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 (26) hide show
  1. latch_asgi-1.0.0/COPYING +121 -0
  2. latch_asgi-1.0.0/PKG-INFO +18 -0
  3. latch_asgi-1.0.0/latch_asgi/asgi_iface.py +72 -0
  4. {latch_asgi-0.2.0 → latch_asgi-1.0.0}/latch_asgi/auth.py +7 -15
  5. {latch_asgi-0.2.0 → latch_asgi-1.0.0}/latch_asgi/config.py +2 -0
  6. {latch_asgi-0.2.0 → latch_asgi-1.0.0}/latch_asgi/context/common.py +30 -19
  7. latch_asgi-1.0.0/latch_asgi/context/http.py +28 -0
  8. latch_asgi-1.0.0/latch_asgi/context/websocket.py +50 -0
  9. {latch_asgi-0.2.0 → latch_asgi-1.0.0}/latch_asgi/datadog_propagator.py +14 -12
  10. latch_asgi-1.0.0/latch_asgi/framework/common.py +40 -0
  11. {latch_asgi-0.2.0 → latch_asgi-1.0.0}/latch_asgi/framework/http.py +60 -66
  12. {latch_asgi-0.2.0 → latch_asgi-1.0.0}/latch_asgi/framework/websocket.py +100 -128
  13. latch_asgi-1.0.0/latch_asgi/server.py +495 -0
  14. latch_asgi-1.0.0/pyproject.toml +152 -0
  15. latch_asgi-0.2.0/PKG-INFO +0 -25
  16. latch_asgi-0.2.0/latch_asgi/asgi_iface.py +0 -328
  17. latch_asgi-0.2.0/latch_asgi/context/http.py +0 -42
  18. latch_asgi-0.2.0/latch_asgi/context/websocket.py +0 -34
  19. latch_asgi-0.2.0/latch_asgi/framework/common.py +0 -7
  20. latch_asgi-0.2.0/latch_asgi/server.py +0 -339
  21. latch_asgi-0.2.0/pyproject.toml +0 -74
  22. {latch_asgi-0.2.0 → latch_asgi-1.0.0}/README.md +0 -0
  23. {latch_asgi-0.2.0 → latch_asgi-1.0.0}/latch_asgi/__init__.py +0 -0
  24. {latch_asgi-0.2.0 → latch_asgi-1.0.0}/latch_asgi/context/__init__.py +0 -0
  25. {latch_asgi-0.2.0 → latch_asgi-1.0.0}/latch_asgi/framework/__init__.py +0 -0
  26. {latch_asgi-0.2.0 → latch_asgi-1.0.0}/latch_asgi/py.typed +0 -0
@@ -0,0 +1,121 @@
1
+ Creative Commons Legal Code
2
+
3
+ CC0 1.0 Universal
4
+
5
+ CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
6
+ LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
7
+ ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
8
+ INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
9
+ REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
10
+ PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
11
+ THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
12
+ HEREUNDER.
13
+
14
+ Statement of Purpose
15
+
16
+ The laws of most jurisdictions throughout the world automatically confer
17
+ exclusive Copyright and Related Rights (defined below) upon the creator
18
+ and subsequent owner(s) (each and all, an "owner") of an original work of
19
+ authorship and/or a database (each, a "Work").
20
+
21
+ Certain owners wish to permanently relinquish those rights to a Work for
22
+ the purpose of contributing to a commons of creative, cultural and
23
+ scientific works ("Commons") that the public can reliably and without fear
24
+ of later claims of infringement build upon, modify, incorporate in other
25
+ works, reuse and redistribute as freely as possible in any form whatsoever
26
+ and for any purposes, including without limitation commercial purposes.
27
+ These owners may contribute to the Commons to promote the ideal of a free
28
+ culture and the further production of creative, cultural and scientific
29
+ works, or to gain reputation or greater distribution for their Work in
30
+ part through the use and efforts of others.
31
+
32
+ For these and/or other purposes and motivations, and without any
33
+ expectation of additional consideration or compensation, the person
34
+ associating CC0 with a Work (the "Affirmer"), to the extent that he or she
35
+ is an owner of Copyright and Related Rights in the Work, voluntarily
36
+ elects to apply CC0 to the Work and publicly distribute the Work under its
37
+ terms, with knowledge of his or her Copyright and Related Rights in the
38
+ Work and the meaning and intended legal effect of CC0 on those rights.
39
+
40
+ 1. Copyright and Related Rights. A Work made available under CC0 may be
41
+ protected by copyright and related or neighboring rights ("Copyright and
42
+ Related Rights"). Copyright and Related Rights include, but are not
43
+ limited to, the following:
44
+
45
+ i. the right to reproduce, adapt, distribute, perform, display,
46
+ communicate, and translate a Work;
47
+ ii. moral rights retained by the original author(s) and/or performer(s);
48
+ iii. publicity and privacy rights pertaining to a person's image or
49
+ likeness depicted in a Work;
50
+ iv. rights protecting against unfair competition in regards to a Work,
51
+ subject to the limitations in paragraph 4(a), below;
52
+ v. rights protecting the extraction, dissemination, use and reuse of data
53
+ in a Work;
54
+ vi. database rights (such as those arising under Directive 96/9/EC of the
55
+ European Parliament and of the Council of 11 March 1996 on the legal
56
+ protection of databases, and under any national implementation
57
+ thereof, including any amended or successor version of such
58
+ directive); and
59
+ vii. other similar, equivalent or corresponding rights throughout the
60
+ world based on applicable law or treaty, and any national
61
+ implementations thereof.
62
+
63
+ 2. Waiver. To the greatest extent permitted by, but not in contravention
64
+ of, applicable law, Affirmer hereby overtly, fully, permanently,
65
+ irrevocably and unconditionally waives, abandons, and surrenders all of
66
+ Affirmer's Copyright and Related Rights and associated claims and causes
67
+ of action, whether now known or unknown (including existing as well as
68
+ future claims and causes of action), in the Work (i) in all territories
69
+ worldwide, (ii) for the maximum duration provided by applicable law or
70
+ treaty (including future time extensions), (iii) in any current or future
71
+ medium and for any number of copies, and (iv) for any purpose whatsoever,
72
+ including without limitation commercial, advertising or promotional
73
+ purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
74
+ member of the public at large and to the detriment of Affirmer's heirs and
75
+ successors, fully intending that such Waiver shall not be subject to
76
+ revocation, rescission, cancellation, termination, or any other legal or
77
+ equitable action to disrupt the quiet enjoyment of the Work by the public
78
+ as contemplated by Affirmer's express Statement of Purpose.
79
+
80
+ 3. Public License Fallback. Should any part of the Waiver for any reason
81
+ be judged legally invalid or ineffective under applicable law, then the
82
+ Waiver shall be preserved to the maximum extent permitted taking into
83
+ account Affirmer's express Statement of Purpose. In addition, to the
84
+ extent the Waiver is so judged Affirmer hereby grants to each affected
85
+ person a royalty-free, non transferable, non sublicensable, non exclusive,
86
+ irrevocable and unconditional license to exercise Affirmer's Copyright and
87
+ Related Rights in the Work (i) in all territories worldwide, (ii) for the
88
+ maximum duration provided by applicable law or treaty (including future
89
+ time extensions), (iii) in any current or future medium and for any number
90
+ of copies, and (iv) for any purpose whatsoever, including without
91
+ limitation commercial, advertising or promotional purposes (the
92
+ "License"). The License shall be deemed effective as of the date CC0 was
93
+ applied by Affirmer to the Work. Should any part of the License for any
94
+ reason be judged legally invalid or ineffective under applicable law, such
95
+ partial invalidity or ineffectiveness shall not invalidate the remainder
96
+ of the License, and in such case Affirmer hereby affirms that he or she
97
+ will not (i) exercise any of his or her remaining Copyright and Related
98
+ Rights in the Work or (ii) assert any associated claims and causes of
99
+ action with respect to the Work, in either case contrary to Affirmer's
100
+ express Statement of Purpose.
101
+
102
+ 4. Limitations and Disclaimers.
103
+
104
+ a. No trademark or patent rights held by Affirmer are waived, abandoned,
105
+ surrendered, licensed or otherwise affected by this document.
106
+ b. Affirmer offers the Work as-is and makes no representations or
107
+ warranties of any kind concerning the Work, express, implied,
108
+ statutory or otherwise, including without limitation warranties of
109
+ title, merchantability, fitness for a particular purpose, non
110
+ infringement, or the absence of latent or other defects, accuracy, or
111
+ the present or absence of errors, whether or not discoverable, all to
112
+ the greatest extent permissible under applicable law.
113
+ c. Affirmer disclaims responsibility for clearing rights of other persons
114
+ that may apply to the Work or any use thereof, including without
115
+ limitation any person's Copyright and Related Rights in the Work.
116
+ Further, Affirmer disclaims responsibility for obtaining any necessary
117
+ consents, permissions or other rights required for any use of the
118
+ Work.
119
+ d. Affirmer understands and acknowledges that Creative Commons is not a
120
+ party to this document and has no duty or obligation with respect to
121
+ this CC0 or use of the Work.
@@ -0,0 +1,18 @@
1
+ Metadata-Version: 2.1
2
+ Name: latch-asgi
3
+ Version: 1.0.0
4
+ Summary: ASGI python server
5
+ Author-Email: Max Smolin <max@latch.bio>
6
+ License: CC0-1.0
7
+ Requires-Python: <4.0,>=3.11
8
+ Requires-Dist: hypercorn[uvloop]<1.0.0,>=0.14.3
9
+ Requires-Dist: latch-data-validation<1.0.0,>=0.1.3
10
+ Requires-Dist: latch-o11y<1.0.0,>=0.1.4
11
+ Requires-Dist: latch-config<1.0.0,>=0.1.6
12
+ Requires-Dist: PyJWT[crypto]<3.0.0,>=2.6.0
13
+ Requires-Dist: orjson<4.0.0,>=3.8.5
14
+ Requires-Dist: opentelemetry-sdk<2.0.0,>=1.15.0
15
+ Requires-Dist: opentelemetry-api<2.0.0,>=1.15.0
16
+ Description-Content-Type: text/markdown
17
+
18
+ # python-asgi
@@ -0,0 +1,72 @@
1
+ from collections.abc import Awaitable, Callable
2
+ from typing import TypeAlias
3
+
4
+ from hypercorn.typing import (
5
+ HTTPDisconnectEvent,
6
+ HTTPRequestEvent,
7
+ HTTPResponseBodyEvent,
8
+ HTTPResponseStartEvent,
9
+ HTTPServerPushEvent,
10
+ LifespanShutdownCompleteEvent,
11
+ LifespanShutdownEvent,
12
+ LifespanShutdownFailedEvent,
13
+ LifespanStartupCompleteEvent,
14
+ LifespanStartupEvent,
15
+ LifespanStartupFailedEvent,
16
+ WebsocketAcceptEvent,
17
+ WebsocketCloseEvent,
18
+ WebsocketConnectEvent,
19
+ WebsocketDisconnectEvent,
20
+ WebsocketReceiveEvent,
21
+ WebsocketResponseBodyEvent,
22
+ WebsocketResponseStartEvent,
23
+ WebsocketSendEvent,
24
+ )
25
+
26
+ # >>> Lifespan
27
+ LifespanReceiveEvent: TypeAlias = LifespanStartupEvent | LifespanShutdownEvent
28
+ LifespanReceiveCallable: TypeAlias = Callable[[], Awaitable[LifespanReceiveEvent]]
29
+
30
+ LifespanShutdownSendEvent: TypeAlias = (
31
+ LifespanShutdownCompleteEvent | LifespanShutdownFailedEvent
32
+ )
33
+ LifespanStartupSendEvent: TypeAlias = (
34
+ LifespanStartupCompleteEvent | LifespanStartupFailedEvent
35
+ )
36
+
37
+ LifespanSendEvent: TypeAlias = LifespanStartupSendEvent | LifespanShutdownSendEvent
38
+ LifespanSendCallable: TypeAlias = Callable[[LifespanSendEvent], Awaitable[None]]
39
+
40
+ # >>> HTTP
41
+
42
+ HTTPReceiveEvent: TypeAlias = HTTPRequestEvent | HTTPDisconnectEvent
43
+ HTTPReceiveCallable: TypeAlias = Callable[[], Awaitable[HTTPReceiveEvent]]
44
+
45
+ HTTPSendEvent: TypeAlias = (
46
+ HTTPResponseStartEvent
47
+ | HTTPResponseBodyEvent
48
+ | HTTPServerPushEvent
49
+ | HTTPDisconnectEvent
50
+ )
51
+ HTTPSendCallable: TypeAlias = Callable[[HTTPSendEvent], Awaitable[None]]
52
+
53
+ # >>> Websocket
54
+
55
+ WebsocketReceiveEventT: TypeAlias = (
56
+ WebsocketConnectEvent | WebsocketReceiveEvent | WebsocketDisconnectEvent
57
+ )
58
+ WebsocketReceiveCallable: TypeAlias = Callable[[], Awaitable[WebsocketReceiveEventT]]
59
+
60
+ WebsocketSendEventT: TypeAlias = (
61
+ WebsocketAcceptEvent
62
+ | WebsocketSendEvent
63
+ | WebsocketResponseBodyEvent
64
+ | WebsocketResponseStartEvent
65
+ | WebsocketCloseEvent
66
+ )
67
+ WebsocketSendCallable: TypeAlias = Callable[[WebsocketSendEventT], Awaitable[None]]
68
+
69
+ # >>> WWW
70
+
71
+ WWWReceiveCallable = HTTPReceiveCallable | WebsocketReceiveCallable
72
+ WWWSendCallable = HTTPSendCallable | WebsocketSendCallable
@@ -3,7 +3,7 @@
3
3
  import re
4
4
  from dataclasses import dataclass
5
5
  from http import HTTPStatus
6
- from typing import Literal
6
+ from typing import Literal, Self
7
7
 
8
8
  import jwt
9
9
  from jwt import PyJWKClient
@@ -37,14 +37,10 @@ class _HTTPUnauthorized(HTTPErrorResponse):
37
37
  """WARNING: HTTPForbidden is the correct error to use in virtually all cases"""
38
38
 
39
39
  def __init__(
40
- self,
40
+ self: Self,
41
41
  error_description: str,
42
- error: (
43
- Literal["invalid_request"]
44
- | Literal["invalid_token"]
45
- | Literal["insufficient_scope"]
46
- ),
47
- ):
42
+ error: (Literal["invalid_request", "invalid_token", "insufficient_scope"]),
43
+ ) -> None:
48
44
  escaped_description = error_description.replace('"', '\\"')
49
45
  super().__init__(
50
46
  HTTPStatus.UNAUTHORIZED,
@@ -63,7 +59,7 @@ class Authorization:
63
59
  execution_token: str | None = None
64
60
  sdk_token: str | None = None
65
61
 
66
- def unauthorized_if_none(self):
62
+ def unauthorized_if_none(self: Self) -> None:
67
63
  if self.oauth_sub is not None:
68
64
  return
69
65
  if self.execution_token is not None:
@@ -71,10 +67,7 @@ class Authorization:
71
67
  if self.sdk_token is not None:
72
68
  return
73
69
 
74
- raise _HTTPUnauthorized(
75
- "Authenticaton required",
76
- error="invalid_request",
77
- )
70
+ raise _HTTPUnauthorized("Authenticaton required", error="invalid_request")
78
71
 
79
72
 
80
73
  @trace_app_function
@@ -121,8 +114,7 @@ def get_signer_sub(auth_header: str) -> Authorization:
121
114
  jwt_key = jwk_client.get_signing_key_from_jwt(oauth_token).key
122
115
  except jwt.exceptions.InvalidTokenError as e:
123
116
  raise _HTTPUnauthorized(
124
- error_description="JWT decoding failed",
125
- error="invalid_token",
117
+ error_description="JWT decoding failed", error="invalid_token"
126
118
  ) from e
127
119
  except jwt.exceptions.PyJWKClientError:
128
120
  # fixme(maximsmol): gut this abomination
@@ -1,4 +1,5 @@
1
1
  from dataclasses import dataclass
2
+
2
3
  from latch_config.config import read_config
3
4
 
4
5
 
@@ -8,4 +9,5 @@ class AuthConfig:
8
9
  self_signed_jwk: str
9
10
  allow_spoofing: bool = False
10
11
 
12
+
11
13
  config = read_config(AuthConfig, "auth_")
@@ -1,61 +1,72 @@
1
1
  from dataclasses import dataclass, field
2
- from typing import Generic, TypeVar
3
-
4
- from latch_o11y.o11y import AttributesDict, app_tracer, trace_app_function
5
-
6
- from ..asgi_iface import WWWReceiveCallable, WWWScope, WWWSendCallable
2
+ from typing import Generic, Self, TypeVar
3
+
4
+ from hypercorn.typing import WWWScope
5
+ from latch_o11y.o11y import (
6
+ AttributesDict,
7
+ app_tracer,
8
+ dict_to_attrs,
9
+ trace_app_function,
10
+ )
11
+ from opentelemetry.util.types import AttributeValue
12
+
13
+ from ..asgi_iface import WWWReceiveCallable, WWWSendCallable
7
14
  from ..auth import Authorization, get_signer_sub
15
+ from ..framework.common import otel_header_whitelist
16
+ from ..framework.http import current_http_request_span
8
17
 
9
- # todo(ayush): this sucks
10
18
  Scope = TypeVar("Scope", bound=WWWScope)
11
- Send = TypeVar("Send", bound=WWWSendCallable)
12
- Receive = TypeVar("Receive", bound=WWWReceiveCallable)
19
+ SendCallable = TypeVar("SendCallable", bound=WWWSendCallable)
20
+ ReceiveCallable = TypeVar("ReceiveCallable", bound=WWWReceiveCallable)
13
21
 
14
22
 
15
23
  @dataclass
16
- class Context(Generic[Scope, Receive, Send]):
24
+ class Context(Generic[Scope, ReceiveCallable, SendCallable]):
17
25
  scope: Scope
18
- receive: Receive
19
- send: Send
26
+ receive: ReceiveCallable
27
+ send: SendCallable
20
28
 
21
29
  auth: Authorization = field(default_factory=Authorization, init=False)
22
30
 
23
31
  _header_cache: dict[bytes, bytes] = field(default_factory=dict, init=False)
24
32
  _db_response_idx: int = field(default=0, init=False)
25
33
 
26
- def __post_init__(self):
34
+ def __post_init__(self: Self) -> None:
27
35
  with app_tracer.start_as_current_span("find Authentication header"):
28
36
  auth_header = self.header_str("authorization")
29
37
 
30
38
  if auth_header is not None:
31
39
  self.auth = get_signer_sub(auth_header)
32
40
 
33
- def header(self, x: str | bytes):
41
+ if self.auth.oauth_sub is not None:
42
+ current_http_request_span().set_attribute("enduser.id", self.auth.oauth_sub)
43
+
44
+ def header(self: Self, x: str | bytes) -> bytes | None:
34
45
  if isinstance(x, str):
35
- x = x.encode("utf-8")
46
+ x = x.encode("latin-1")
36
47
 
37
48
  if x in self._header_cache:
38
49
  return self._header_cache[x]
39
50
 
40
- for k, v in self.scope.headers:
51
+ for k, v in self.scope["headers"]:
41
52
  self._header_cache[k] = v
42
53
  if k == x:
43
54
  return v
44
55
 
45
56
  return None
46
57
 
47
- def header_str(self, x: str | bytes):
58
+ def header_str(self: Self, x: str | bytes) -> str | None:
48
59
  res = self.header(x)
49
60
  if res is None:
50
61
  return None
51
62
 
52
63
  return res.decode("latin-1")
53
64
 
54
- def add_request_span_attrs(self, data: AttributesDict, prefix: str):
55
- raise NotImplementedError()
65
+ def add_request_span_attrs(self: Self, data: AttributesDict, prefix: str) -> None:
66
+ current_http_request_span().set_attributes(dict_to_attrs(data, prefix))
56
67
 
57
68
  @trace_app_function
58
- def add_db_response(self, data: AttributesDict):
69
+ def add_db_response(self: Self, data: AttributesDict) -> None:
59
70
  # todo(maximsmol): datadog has shit support for events
60
71
  # current_http_request_span().add_event(
61
72
  # f"database response {self._db_response_idx}", dict_to_attrs(data, "data")
@@ -0,0 +1,28 @@
1
+ from collections.abc import Awaitable, Callable
2
+ from dataclasses import dataclass
3
+ from typing import Any, Self, TypeAlias, TypeVar
4
+
5
+ from hypercorn.typing import HTTPScope
6
+ from latch_o11y.o11y import trace_app_function
7
+
8
+ from ..asgi_iface import HTTPReceiveCallable, HTTPSendCallable
9
+ from ..framework.http import HTTPMethod, receive_class_ext
10
+ from . import common
11
+
12
+ T = TypeVar("T")
13
+
14
+
15
+ @dataclass
16
+ class Context(common.Context[HTTPScope, HTTPReceiveCallable, HTTPSendCallable]):
17
+ @trace_app_function
18
+ async def receive_request_payload(self: Self, cls: type[T]) -> T:
19
+ json, res = await receive_class_ext(self.receive, cls)
20
+
21
+ self.add_request_span_attrs(json, "http.request.body.data")
22
+
23
+ return res
24
+
25
+
26
+ HandlerResult: TypeAlias = Any | None
27
+ Handler: TypeAlias = Callable[[Context], Awaitable[HandlerResult]]
28
+ Route: TypeAlias = Handler | tuple[list[HTTPMethod], Handler]
@@ -0,0 +1,50 @@
1
+ from collections.abc import Awaitable, Callable
2
+ from dataclasses import dataclass
3
+ from typing import Any, Self, TypeAlias, TypeVar
4
+
5
+ from hypercorn.typing import WebsocketScope
6
+ from latch_o11y.o11y import AttributesDict, dict_to_attrs, trace_app_function
7
+ from opentelemetry.trace import get_current_span
8
+
9
+ from ..asgi_iface import WebsocketReceiveCallable, WebsocketSendCallable
10
+ from ..framework.common import Headers
11
+ from ..framework.websocket import (
12
+ accept_connection,
13
+ current_websocket_session_span,
14
+ receive_class_ext,
15
+ send_websocket_auto,
16
+ )
17
+ from . import common
18
+
19
+ T = TypeVar("T")
20
+
21
+
22
+ @dataclass
23
+ class Context(
24
+ common.Context[WebsocketScope, WebsocketReceiveCallable, WebsocketSendCallable]
25
+ ):
26
+ def add_session_span_attrs(self: Self, data: AttributesDict, prefix: str) -> None:
27
+ current_websocket_session_span().set_attributes(dict_to_attrs(data, prefix))
28
+
29
+ @trace_app_function
30
+ async def accept_connection(
31
+ self: Self, *, subprotocol: str | None = None, headers: Headers | None = None
32
+ ) -> None:
33
+ await accept_connection(self.send, subprotocol=subprotocol, headers=headers)
34
+
35
+ @trace_app_function
36
+ async def receive_message(self: Self, cls: type[T]) -> T:
37
+ json, res = await receive_class_ext(self.receive, cls)
38
+
39
+ get_current_span().set_attributes(dict_to_attrs(json, "payload"))
40
+
41
+ return res
42
+
43
+ @trace_app_function
44
+ async def send_message(self: Self, data: Any) -> None:
45
+ await send_websocket_auto(self.send, data)
46
+
47
+
48
+ HandlerResult = str
49
+ Handler: TypeAlias = Callable[[Context], Awaitable[HandlerResult]]
50
+ Route: TypeAlias = Handler
@@ -1,3 +1,5 @@
1
+ from typing import Self
2
+
1
3
  from opentelemetry import trace
2
4
  from opentelemetry.context.context import Context
3
5
  from opentelemetry.propagators import textmap
@@ -6,7 +8,7 @@ from opentelemetry.propagators import textmap
6
8
  class DDTraceContextTextMapPropagator(textmap.TextMapPropagator):
7
9
  # https://github.com/open-telemetry/opentelemetry-python-contrib/blob/934af7ea4f9b1e0294ced6a014d6eefdda156b2b/exporter/opentelemetry-exporter-datadog/src/opentelemetry/exporter/datadog/propagator.py
8
10
  def extract(
9
- self,
11
+ self: Self,
10
12
  carrier: textmap.CarrierT,
11
13
  context: Context | None = None,
12
14
  getter: textmap.Getter[textmap.CarrierT] = textmap.default_getter,
@@ -28,12 +30,16 @@ class DDTraceContextTextMapPropagator(textmap.TextMapPropagator):
28
30
  sampling_priority = getter.get(carrier, "x-datadog-sampling-priority")
29
31
 
30
32
  trace_flags = trace.TraceFlags()
31
- if sampling_priority is not None and len(sampling_priority) > 0:
32
- if int(sampling_priority[0]) in (
33
+ if (
34
+ sampling_priority is not None
35
+ and len(sampling_priority) > 0
36
+ and int(sampling_priority[0])
37
+ in (
33
38
  1, # auto keep
34
39
  2, # user keep
35
- ):
36
- trace_flags = trace.TraceFlags(trace.TraceFlags.SAMPLED)
40
+ )
41
+ ):
42
+ trace_flags = trace.TraceFlags(trace.TraceFlags.SAMPLED)
37
43
 
38
44
  dd_origin = getter.get(carrier, "x-datadog-origin")
39
45
 
@@ -51,7 +57,7 @@ class DDTraceContextTextMapPropagator(textmap.TextMapPropagator):
51
57
  return trace.set_span_in_context(trace.NonRecordingSpan(span_context), context)
52
58
 
53
59
  def inject(
54
- self,
60
+ self: Self,
55
61
  carrier: textmap.CarrierT,
56
62
  context: Context | None = None,
57
63
  setter: textmap.Setter[textmap.CarrierT] = textmap.default_setter,
@@ -69,11 +75,7 @@ class DDTraceContextTextMapPropagator(textmap.TextMapPropagator):
69
75
  "x-datadog-trace-id",
70
76
  str(span_context.trace_id & 0xFFFF_FFFF_FFFF_FFFF),
71
77
  )
72
- setter.set(
73
- carrier,
74
- "x-datadog-parent-id",
75
- str(span_context.span_id),
76
- )
78
+ setter.set(carrier, "x-datadog-parent-id", str(span_context.span_id))
77
79
  setter.set(
78
80
  carrier,
79
81
  "x-datadog-sampling-priority",
@@ -87,7 +89,7 @@ class DDTraceContextTextMapPropagator(textmap.TextMapPropagator):
87
89
  )
88
90
 
89
91
  @property
90
- def fields(self) -> set[str]:
92
+ def fields(self: Self) -> set[str]:
91
93
  return {
92
94
  "x-datadog-trace-id",
93
95
  "x-datadog-parent-id",
@@ -0,0 +1,40 @@
1
+ from typing import TypeAlias
2
+
3
+ from opentelemetry.trace import get_tracer
4
+
5
+ Headers: TypeAlias = dict[str | bytes, str | bytes]
6
+
7
+ tracer = get_tracer(__name__)
8
+
9
+ otel_header_whitelist = {
10
+ "host",
11
+ "content-type",
12
+ "content-length",
13
+ "accept",
14
+ "accept-encoding",
15
+ "accept-language",
16
+ "user-agent",
17
+ "dnt",
18
+ "sec-fetch-dest",
19
+ "sec-fetch-mode",
20
+ "sec-fetch-site",
21
+ "sec-fetch-user",
22
+ "sec-gpc",
23
+ "te",
24
+ "upgrade-insecure-requests",
25
+ "device-memory",
26
+ "downlink",
27
+ "dpr",
28
+ "ect",
29
+ "rtt",
30
+ "sec-ch-prefers-color-scheme",
31
+ "sec-ch-prefers-reduced-motion",
32
+ "sec-ch-ua",
33
+ "sec-ch-ua-arch",
34
+ "sec-ch-ua-full-version",
35
+ "sec-ch-ua-mobile",
36
+ "sec-ch-ua-model",
37
+ "sec-ch-ua-platform",
38
+ "sec-ch-ua-platfrom-version",
39
+ "viewport-width",
40
+ }