httpx2 2.9.1__tar.gz → 2.11.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 (40) hide show
  1. {httpx2-2.9.1 → httpx2-2.11.0}/CHANGELOG.md +42 -0
  2. {httpx2-2.9.1 → httpx2-2.11.0}/PKG-INFO +49 -10
  3. {httpx2-2.9.1 → httpx2-2.11.0}/README.md +22 -0
  4. {httpx2-2.9.1 → httpx2-2.11.0}/httpx2/__init__.py +1 -0
  5. {httpx2-2.9.1 → httpx2-2.11.0}/httpx2/_client.py +14 -23
  6. {httpx2-2.9.1 → httpx2-2.11.0}/httpx2/_config.py +2 -0
  7. {httpx2-2.9.1 → httpx2-2.11.0}/httpx2/_content.py +1 -1
  8. {httpx2-2.9.1 → httpx2-2.11.0}/httpx2/_models.py +16 -2
  9. {httpx2-2.9.1 → httpx2-2.11.0}/httpx2/_multipart.py +6 -0
  10. httpx2-2.11.0/httpx2/_sse.py +226 -0
  11. {httpx2-2.9.1 → httpx2-2.11.0}/httpx2/_status_codes.py +38 -11
  12. httpx2-2.11.0/httpx2/_transports/__init__.py +27 -0
  13. {httpx2-2.9.1 → httpx2-2.11.0}/httpx2/_transports/wsgi.py +2 -0
  14. {httpx2-2.9.1 → httpx2-2.11.0}/httpx2/_urls.py +58 -1
  15. httpx2-2.11.0/httpx2/websockets/__init__.py +57 -0
  16. {httpx2-2.9.1 → httpx2-2.11.0}/httpx2/websockets/_api.py +34 -4
  17. {httpx2-2.9.1 → httpx2-2.11.0}/httpx2/websockets/_ping.py +6 -4
  18. {httpx2-2.9.1 → httpx2-2.11.0}/httpx2/websockets/_transport.py +3 -6
  19. {httpx2-2.9.1 → httpx2-2.11.0}/pyproject.toml +10 -8
  20. httpx2-2.9.1/httpx2/_sse.py +0 -158
  21. httpx2-2.9.1/httpx2/_transports/__init__.py +0 -15
  22. httpx2-2.9.1/httpx2/websockets/__init__.py +0 -35
  23. {httpx2-2.9.1 → httpx2-2.11.0}/.gitignore +0 -0
  24. {httpx2-2.9.1 → httpx2-2.11.0}/LICENSE.md +0 -0
  25. {httpx2-2.9.1 → httpx2-2.11.0}/httpx2/__version__.py +0 -0
  26. {httpx2-2.9.1 → httpx2-2.11.0}/httpx2/_alias.py +0 -0
  27. {httpx2-2.9.1 → httpx2-2.11.0}/httpx2/_api.py +0 -0
  28. {httpx2-2.9.1 → httpx2-2.11.0}/httpx2/_auth.py +0 -0
  29. {httpx2-2.9.1 → httpx2-2.11.0}/httpx2/_decoders.py +0 -0
  30. {httpx2-2.9.1 → httpx2-2.11.0}/httpx2/_exceptions.py +0 -0
  31. {httpx2-2.9.1 → httpx2-2.11.0}/httpx2/_main.py +0 -0
  32. {httpx2-2.9.1 → httpx2-2.11.0}/httpx2/_transports/asgi.py +0 -0
  33. {httpx2-2.9.1 → httpx2-2.11.0}/httpx2/_transports/base.py +0 -0
  34. {httpx2-2.9.1 → httpx2-2.11.0}/httpx2/_transports/default.py +0 -0
  35. {httpx2-2.9.1 → httpx2-2.11.0}/httpx2/_transports/mock.py +0 -0
  36. {httpx2-2.9.1 → httpx2-2.11.0}/httpx2/_types.py +0 -0
  37. {httpx2-2.9.1 → httpx2-2.11.0}/httpx2/_urlparse.py +0 -0
  38. {httpx2-2.9.1 → httpx2-2.11.0}/httpx2/_utils.py +0 -0
  39. {httpx2-2.9.1 → httpx2-2.11.0}/httpx2/py.typed +0 -0
  40. {httpx2-2.9.1 → httpx2-2.11.0}/httpx2/websockets/_exceptions.py +0 -0
@@ -4,6 +4,48 @@ All notable changes to this project will be documented in this file.
4
4
 
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
6
6
 
7
+ ## 2.11.0 (August 18th, 2026)
8
+
9
+ ### Added
10
+
11
+ * Add the public `Origin` value object and `URL.origin` property for normalized,
12
+ hashable origin comparisons. ([#1134](https://github.com/pydantic/httpx2/pull/1134))
13
+
14
+ ### Changed
15
+
16
+ * Require Brotli 1.2.0 or later for the `brotli` extra. ([#1141](https://github.com/pydantic/httpx2/pull/1141))
17
+
18
+ ### Fixed
19
+
20
+ * Restore deprecated status code aliases. ([#1135](https://github.com/pydantic/httpx2/pull/1135))
21
+ * Extract HTTP/2 release notes from changelog headings correctly. ([#1136](https://github.com/pydantic/httpx2/pull/1136))
22
+ * Respect explicit `Transfer-Encoding` headers and expose buffered request body lengths to WSGI applications.
23
+ ([#1137](https://github.com/pydantic/httpx2/pull/1137))
24
+ * Validate multipart part header names and values before serialization.
25
+ ([#1142](https://github.com/pydantic/httpx2/pull/1142))
26
+
27
+ ## 2.10.0 (August 9th, 2026)
28
+
29
+ ### Added
30
+
31
+ * Add support for running on WebAssembly / Emscripten via Pyodide, using a JavaScript
32
+ `fetch`-based transport defined in `httpx2-jsfetch`.
33
+ ([#1119](https://github.com/pydantic/httpx2/pull/1119))
34
+ * Add `max_event_size` to cap SSE event buffering. ([#1071](https://github.com/pydantic/httpx2/pull/1071))
35
+ * Add RFC 9110 status code constants. ([#1069](https://github.com/pydantic/httpx2/pull/1069))
36
+ * Add support for Python 3.15. ([#1090](https://github.com/pydantic/httpx2/pull/1090))
37
+
38
+ ### Changed
39
+
40
+ * Improve SSE chunk buffering performance. ([#1117](https://github.com/pydantic/httpx2/pull/1117))
41
+ * Skip cookie extraction for responses without `Set-Cookie` headers. ([#1107](https://github.com/pydantic/httpx2/pull/1107))
42
+ * Return `str | None` instead of `Any` from `Headers.get`. ([#1121](https://github.com/pydantic/httpx2/pull/1121))
43
+
44
+ ### Fixed
45
+
46
+ * Enforce the WebSocket max message size across fragmented messages. ([#1085](https://github.com/pydantic/httpx2/pull/1085))
47
+ * Ignore unsolicited and duplicate WebSocket Pong frames. ([#1122](https://github.com/pydantic/httpx2/pull/1122))
48
+
7
49
  ## 2.9.1 (July 24th, 2026)
8
50
 
9
51
  ### Fixed
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.4
1
+ Metadata-Version: 2.5
2
2
  Name: httpx2
3
- Version: 2.9.1
3
+ Version: 2.11.0
4
4
  Summary: The next generation HTTP client.
5
5
  Project-URL: Changelog, https://github.com/pydantic/httpx2/blob/main/src/httpx2/CHANGELOG.md
6
6
  Project-URL: Homepage, https://github.com/pydantic/httpx2
@@ -23,18 +23,20 @@ Classifier: Programming Language :: Python :: 3.11
23
23
  Classifier: Programming Language :: Python :: 3.12
24
24
  Classifier: Programming Language :: Python :: 3.13
25
25
  Classifier: Programming Language :: Python :: 3.14
26
+ Classifier: Programming Language :: Python :: 3.15
26
27
  Classifier: Topic :: Internet :: WWW/HTTP
27
28
  Requires-Python: >=3.10
28
- Requires-Dist: anyio>=4.10
29
- Requires-Dist: httpcore2==2.9.1
29
+ Requires-Dist: anyio>=4.10; sys_platform != 'emscripten'
30
+ Requires-Dist: httpcore2==2.11.0; sys_platform != 'emscripten'
31
+ Requires-Dist: httpx2-jsfetch; sys_platform == 'emscripten' and python_version >= '3.12'
30
32
  Requires-Dist: idna>=3.18
31
- Requires-Dist: truststore>=0.10
33
+ Requires-Dist: truststore>=0.10; sys_platform != 'emscripten'
32
34
  Requires-Dist: typing-extensions>=4.5.0; python_version < '3.13'
33
35
  Provides-Extra: brotli
34
- Requires-Dist: brotli; (platform_python_implementation == 'CPython') and extra == 'brotli'
35
- Requires-Dist: brotlicffi; (platform_python_implementation != 'CPython') and extra == 'brotli'
36
+ Requires-Dist: brotli>=1.2.0; (platform_python_implementation == 'CPython') and extra == 'brotli'
37
+ Requires-Dist: brotlicffi>=1.2.0.0; (platform_python_implementation != 'CPython') and extra == 'brotli'
36
38
  Provides-Extra: cli
37
- Requires-Dist: click>=8.4; extra == 'cli'
39
+ Requires-Dist: click>=8.4.2; extra == 'cli'
38
40
  Requires-Dist: pygments==2.*; extra == 'cli'
39
41
  Requires-Dist: rich<16,>=10; extra == 'cli'
40
42
  Provides-Extra: http2
@@ -155,6 +157,28 @@ The [Developer Interface](https://httpx2.pydantic.dev/api/) provides a comprehen
155
157
 
156
158
  To find out about tools that integrate with HTTPX, see [Third Party Packages](https://httpx2.pydantic.dev/third_party_packages/).
157
159
 
160
+ ## Observability with Pydantic Logfire
161
+
162
+ Install Logfire with HTTPX instrumentation support:
163
+
164
+ ```shell
165
+ pip install 'logfire[httpx]'
166
+ ```
167
+
168
+ HTTPX2 works out of the box with [Pydantic Logfire](https://pydantic.dev/logfire), our observability platform built on OpenTelemetry. One line instruments every request, giving you traces, timings, and status codes with no other changes:
169
+
170
+ ```python
171
+ import logfire
172
+ import httpx2
173
+
174
+ logfire.configure()
175
+ logfire.instrument_httpx()
176
+
177
+ httpx2.get("https://pydantic.dev/")
178
+ ```
179
+
180
+ This works the same way for explicit `httpx2.Client()` and `httpx2.AsyncClient()` instances, and you can scope instrumentation to a single client by passing it in: `logfire.instrument_httpx(client)`. Pass `capture_all=True` to also record headers and bodies. See the [Logfire HTTPX docs](https://logfire.pydantic.dev/docs/integrations/http-clients/httpx/) for the full set of options.
181
+
158
182
  ## Contribute
159
183
 
160
184
  If you want to contribute with HTTPX2 check out the [Contributing Guide](https://httpx2.pydantic.dev/contributing/) to learn how to start.
@@ -188,10 +212,25 @@ inspiration around the lower-level networking details.
188
212
 
189
213
  ## Release Information
190
214
 
191
- ### Fixed
215
+ ## 2.11.0 (August 18th, 2026)
216
+
217
+ ### Added
192
218
 
193
- * Alias `httpcore` imports to `httpcore2` in `alias_httpx()`. ([#1082](https://github.com/pydantic/httpx2/pull/1082))
219
+ * Add the public `Origin` value object and `URL.origin` property for normalized,
220
+ hashable origin comparisons. ([#1134](https://github.com/pydantic/httpx2/pull/1134))
221
+
222
+ ### Changed
223
+
224
+ * Require Brotli 1.2.0 or later for the `brotli` extra. ([#1141](https://github.com/pydantic/httpx2/pull/1141))
225
+
226
+ ### Fixed
194
227
 
228
+ * Restore deprecated status code aliases. ([#1135](https://github.com/pydantic/httpx2/pull/1135))
229
+ * Extract HTTP/2 release notes from changelog headings correctly. ([#1136](https://github.com/pydantic/httpx2/pull/1136))
230
+ * Respect explicit `Transfer-Encoding` headers and expose buffered request body lengths to WSGI applications.
231
+ ([#1137](https://github.com/pydantic/httpx2/pull/1137))
232
+ * Validate multipart part header names and values before serialization.
233
+ ([#1142](https://github.com/pydantic/httpx2/pull/1142))
195
234
 
196
235
  ---
197
236
 
@@ -106,6 +106,28 @@ The [Developer Interface](https://httpx2.pydantic.dev/api/) provides a comprehen
106
106
 
107
107
  To find out about tools that integrate with HTTPX, see [Third Party Packages](https://httpx2.pydantic.dev/third_party_packages/).
108
108
 
109
+ ## Observability with Pydantic Logfire
110
+
111
+ Install Logfire with HTTPX instrumentation support:
112
+
113
+ ```shell
114
+ pip install 'logfire[httpx]'
115
+ ```
116
+
117
+ HTTPX2 works out of the box with [Pydantic Logfire](https://pydantic.dev/logfire), our observability platform built on OpenTelemetry. One line instruments every request, giving you traces, timings, and status codes with no other changes:
118
+
119
+ ```python
120
+ import logfire
121
+ import httpx2
122
+
123
+ logfire.configure()
124
+ logfire.instrument_httpx()
125
+
126
+ httpx2.get("https://pydantic.dev/")
127
+ ```
128
+
129
+ This works the same way for explicit `httpx2.Client()` and `httpx2.AsyncClient()` instances, and you can scope instrumentation to a single client by passing it in: `logfire.instrument_httpx(client)`. Pass `capture_all=True` to also record headers and bodies. See the [Logfire HTTPX docs](https://logfire.pydantic.dev/docs/integrations/http-clients/httpx/) for the full set of options.
130
+
109
131
  ## Contribute
110
132
 
111
133
  If you want to contribute with HTTPX2 check out the [Contributing Guide](https://httpx2.pydantic.dev/contributing/) to learn how to start.
@@ -53,6 +53,7 @@ __all__ = [
53
53
  "NetRCAuth",
54
54
  "NetworkError",
55
55
  "options",
56
+ "Origin",
56
57
  "patch",
57
58
  "PoolTimeout",
58
59
  "post",
@@ -16,6 +16,7 @@ from ._config import (
16
16
  DEFAULT_KEEPALIVE_PING_INTERVAL_SECONDS,
17
17
  DEFAULT_KEEPALIVE_PING_TIMEOUT_SECONDS,
18
18
  DEFAULT_LIMITS,
19
+ DEFAULT_MAX_EVENT_SIZE_BYTES,
19
20
  DEFAULT_MAX_MESSAGE_SIZE_BYTES,
20
21
  DEFAULT_MAX_REDIRECTS,
21
22
  DEFAULT_QUEUE_SIZE,
@@ -34,8 +35,8 @@ from ._exceptions import (
34
35
  from ._models import Cookies, Headers, Request, Response
35
36
  from ._sse import EventSource
36
37
  from ._status_codes import codes
38
+ from ._transports import AsyncHTTPTransport, HTTPTransport
37
39
  from ._transports.base import AsyncBaseTransport, BaseTransport
38
- from ._transports.default import AsyncHTTPTransport, HTTPTransport
39
40
  from ._types import (
40
41
  AsyncByteStream,
41
42
  AuthTypes,
@@ -71,30 +72,18 @@ def _is_https_redirect(url: URL, location: URL) -> bool:
71
72
  """
72
73
  Return 'True' if 'location' is a HTTPS upgrade of 'url'
73
74
  """
74
- if url.host != location.host:
75
- return False
75
+ origin = url.origin
76
+ location_origin = location.origin
76
77
 
77
78
  return (
78
- url.scheme == "http"
79
- and _port_or_default(url) == 80
80
- and location.scheme == "https"
81
- and _port_or_default(location) == 443
79
+ origin.host == location_origin.host
80
+ and origin.scheme == "http"
81
+ and origin.port == 80
82
+ and location_origin.scheme == "https"
83
+ and location_origin.port == 443
82
84
  )
83
85
 
84
86
 
85
- def _port_or_default(url: URL) -> int | None:
86
- if url.port is not None:
87
- return url.port
88
- return {"http": 80, "https": 443}.get(url.scheme)
89
-
90
-
91
- def _same_origin(url: URL, other: URL) -> bool:
92
- """
93
- Return 'True' if the given URLs share the same origin.
94
- """
95
- return url.scheme == other.scheme and url.host == other.host and _port_or_default(url) == _port_or_default(other)
96
-
97
-
98
87
  class UseClientDefault:
99
88
  """
100
89
  For some parameters such as `auth=...` and `timeout=...` we need to be able
@@ -533,7 +522,7 @@ class BaseClient:
533
522
  """
534
523
  headers = Headers(request.headers)
535
524
 
536
- if not _same_origin(url, request.url):
525
+ if url.origin != request.url.origin:
537
526
  if not _is_https_redirect(request.url, url):
538
527
  # Strip Authorization headers when responses are redirected
539
528
  # away from the origin. (Except for direct HTTP to HTTPS redirects.)
@@ -871,6 +860,7 @@ class Client(BaseClient):
871
860
  follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
872
861
  timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
873
862
  extensions: RequestExtensions | None = None,
863
+ max_event_size: int | None = DEFAULT_MAX_EVENT_SIZE_BYTES,
874
864
  ) -> Generator[EventSource]:
875
865
  """
876
866
  Connect to a server-sent events endpoint and yield an `EventSource`.
@@ -894,7 +884,7 @@ class Client(BaseClient):
894
884
  timeout=timeout,
895
885
  extensions=extensions,
896
886
  ) as response:
897
- yield EventSource(response)
887
+ yield EventSource(response, max_event_size=max_event_size)
898
888
 
899
889
  @contextmanager
900
890
  def websocket(
@@ -1708,6 +1698,7 @@ class AsyncClient(BaseClient):
1708
1698
  follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
1709
1699
  timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
1710
1700
  extensions: RequestExtensions | None = None,
1701
+ max_event_size: int | None = DEFAULT_MAX_EVENT_SIZE_BYTES,
1711
1702
  ) -> AsyncGenerator[EventSource]:
1712
1703
  """
1713
1704
  Connect to a server-sent events endpoint and yield an `EventSource`.
@@ -1731,7 +1722,7 @@ class AsyncClient(BaseClient):
1731
1722
  timeout=timeout,
1732
1723
  extensions=extensions,
1733
1724
  ) as response:
1734
- yield EventSource(response)
1725
+ yield EventSource(response, max_event_size=max_event_size)
1735
1726
 
1736
1727
  @asynccontextmanager
1737
1728
  async def websocket(
@@ -248,6 +248,8 @@ DEFAULT_TIMEOUT_CONFIG = Timeout(timeout=5.0)
248
248
  DEFAULT_LIMITS = Limits(max_connections=100, max_keepalive_connections=20)
249
249
  DEFAULT_MAX_REDIRECTS = 20
250
250
 
251
+ DEFAULT_MAX_EVENT_SIZE_BYTES = 1024 * 1024
252
+
251
253
  DEFAULT_MAX_MESSAGE_SIZE_BYTES = 65_536
252
254
  DEFAULT_QUEUE_SIZE = 512
253
255
  DEFAULT_KEEPALIVE_PING_INTERVAL_SECONDS = 20.0
@@ -119,7 +119,7 @@ def encode_content(
119
119
  headers = {"Transfer-Encoding": "chunked"}
120
120
  else:
121
121
  headers = {"Content-Length": str(content_length_or_none)}
122
- return headers, IteratorByteStream(content) # type: ignore
122
+ return headers, IteratorByteStream(content)
123
123
 
124
124
  elif isinstance(content, AsyncIterable):
125
125
  headers = {"Transfer-Encoding": "chunked"}
@@ -51,6 +51,8 @@ __all__ = ["Cookies", "Headers", "Request", "Response"]
51
51
 
52
52
  SENSITIVE_HEADERS = {"authorization", "proxy-authorization"}
53
53
 
54
+ _T = typing.TypeVar("_T")
55
+
54
56
 
55
57
  def _is_known_encoding(encoding: str) -> bool:
56
58
  """
@@ -235,7 +237,13 @@ class Headers(typing.MutableMapping[str, str]):
235
237
  """
236
238
  return [(key.decode(self.encoding), value.decode(self.encoding)) for _, key, value in self._list]
237
239
 
238
- def get(self, key: str, default: typing.Any = None) -> typing.Any:
240
+ @typing.overload
241
+ def get(self, key: str, /) -> str | None: ...
242
+
243
+ @typing.overload
244
+ def get(self, key: str, default: _T) -> str | _T: ...
245
+
246
+ def get(self, key: str, default: _T | None = None) -> str | _T | None:
239
247
  """
240
248
  Return a header value. If multiple occurrences of the header occur
241
249
  then concatenate them together with commas.
@@ -444,7 +452,10 @@ class Request:
444
452
 
445
453
  def _prepare(self, default_headers: dict[str, str]) -> None:
446
454
  for key, value in default_headers.items():
447
- # Ignore Transfer-Encoding if the Content-Length has been set explicitly.
455
+ # Ignore Content-Length if Transfer-Encoding has been set explicitly.
456
+ if key.lower() == "content-length" and "Transfer-Encoding" in self.headers:
457
+ continue
458
+ # Ignore Transfer-Encoding if Content-Length has been set explicitly.
448
459
  if key.lower() == "transfer-encoding" and "Content-Length" in self.headers:
449
460
  continue
450
461
  self.headers.setdefault(key, value)
@@ -1079,6 +1090,9 @@ class Cookies(typing.MutableMapping[str, str]):
1079
1090
  """
1080
1091
  Loads any cookies based on the response `Set-Cookie` headers.
1081
1092
  """
1093
+ if "set-cookie" not in response.headers and "set-cookie2" not in response.headers:
1094
+ return
1095
+
1082
1096
  urllib_response = self._CookieCompatResponse(response)
1083
1097
  urllib_request = self._CookieCompatRequest(response.request)
1084
1098
 
@@ -24,6 +24,8 @@ from ._utils import (
24
24
  _HTML5_FORM_ENCODING_REPLACEMENTS = {'"': "%22", "\\": "\\\\"}
25
25
  _HTML5_FORM_ENCODING_REPLACEMENTS.update({chr(c): f"%{c:02X}" for c in range(0x1F + 1) if c != 0x1B})
26
26
  _HTML5_FORM_ENCODING_RE = re.compile(r"|".join([re.escape(c) for c in _HTML5_FORM_ENCODING_REPLACEMENTS.keys()]))
27
+ _HEADER_NAME_RE = re.compile(r"[!#$%&'*+\-.^_`|~0-9A-Za-z]+")
28
+ _FORBIDDEN_HEADER_VALUE_CHARS_RE = re.compile(r"[\x00-\x08\x0a-\x1f\x7f]")
27
29
 
28
30
 
29
31
  def _format_form_param(name: str, value: str) -> bytes:
@@ -176,6 +178,10 @@ class FileField:
176
178
  filename = _format_form_param("filename", self.filename)
177
179
  parts.extend([b"; ", filename])
178
180
  for header_name, header_value in self.headers.items():
181
+ if _HEADER_NAME_RE.fullmatch(header_name) is None:
182
+ raise ValueError("Invalid multipart header name.")
183
+ if _FORBIDDEN_HEADER_VALUE_CHARS_RE.search(header_value) is not None:
184
+ raise ValueError("Invalid control character in multipart header value.")
179
185
  key, val = f"\r\n{header_name}: ".encode(), header_value.encode()
180
186
  parts.extend([key, val])
181
187
  parts.append(b"\r\n\r\n")
@@ -0,0 +1,226 @@
1
+ """
2
+ Server-sent events support, derived from httpx-sse (https://github.com/florimondmanca/httpx-sse).
3
+
4
+ ```
5
+ MIT License
6
+
7
+ Copyright (c) 2022 Florimond Manca
8
+
9
+ Permission is hereby granted, free of charge, to any person obtaining a copy
10
+ of this software and associated documentation files (the "Software"), to deal
11
+ in the Software without restriction, including without limitation the rights
12
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
+ copies of the Software, and to permit persons to whom the Software is
14
+ furnished to do so, subject to the following conditions:
15
+
16
+ The above copyright notice and this permission notice shall be included in all
17
+ copies or substantial portions of the Software.
18
+
19
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25
+ SOFTWARE.
26
+ ```
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import json as jsonlib
32
+ from collections.abc import AsyncIterator, Iterator
33
+ from dataclasses import dataclass
34
+
35
+ from ._config import DEFAULT_MAX_EVENT_SIZE_BYTES
36
+ from ._exceptions import TransportError, request_context
37
+ from ._models import Response
38
+
39
+ __all__ = ["EventSource", "SSEError", "ServerSentEvent"]
40
+
41
+
42
+ class SSEError(TransportError):
43
+ """
44
+ An error that occurred while connecting to a server-sent events endpoint.
45
+ """
46
+
47
+
48
+ @dataclass(frozen=True)
49
+ class ServerSentEvent:
50
+ event: str = "message"
51
+ data: str = ""
52
+ id: str = ""
53
+ retry: int | None = None
54
+
55
+ def json(self) -> object:
56
+ return jsonlib.loads(self.data)
57
+
58
+
59
+ class _SSEEventDecoder:
60
+ def __init__(self, max_event_size: int | None = None) -> None:
61
+ self._max_event_size = max_event_size
62
+ self._event = ""
63
+ self._data: list[str] = []
64
+ self._event_size = 0
65
+ self._last_event_id = ""
66
+ self._retry: int | None = None
67
+ self._pending = False
68
+
69
+ def decode(self, line: str) -> ServerSentEvent | None:
70
+ if not line:
71
+ self._event_size = 0
72
+ if not self._pending:
73
+ return None
74
+
75
+ sse = ServerSentEvent(
76
+ event=self._event or "message",
77
+ data="\n".join(self._data),
78
+ id=self._last_event_id,
79
+ retry=self._retry,
80
+ )
81
+ self._event = ""
82
+ self._data = []
83
+ self._retry = None
84
+ self._pending = False
85
+ return sse
86
+
87
+ if line.startswith(":"):
88
+ return None
89
+
90
+ self._event_size += len(line.encode("utf-8"))
91
+ self._check_size()
92
+
93
+ fieldname, _, value = line.partition(":")
94
+ value = value[1:] if value.startswith(" ") else value
95
+
96
+ if fieldname == "event":
97
+ self._event = value
98
+ self._pending = True
99
+ elif fieldname == "data":
100
+ self._data.append(value)
101
+ self._pending = True
102
+ elif fieldname == "id":
103
+ if "\0" not in value:
104
+ self._last_event_id = value
105
+ self._pending = True
106
+ elif fieldname == "retry":
107
+ try:
108
+ self._retry = int(value)
109
+ self._pending = True
110
+ except ValueError:
111
+ pass
112
+
113
+ return None
114
+
115
+ def check_pending(self, pending_size: int) -> None:
116
+ """
117
+ Bound the total bytes buffered for the in-progress event, including
118
+ a trailing line that has not been terminated by a newline yet.
119
+ """
120
+ self._check_size(pending_size)
121
+
122
+ def _check_size(self, pending_size: int = 0) -> None:
123
+ if self._max_event_size is not None and self._event_size + pending_size > self._max_event_size:
124
+ raise SSEError(f"Server-sent event exceeded the {self._max_event_size} byte limit.")
125
+
126
+
127
+ class _SSELineDecoder:
128
+ def __init__(self) -> None:
129
+ self._parts: list[str] = []
130
+ self._pending_size = 0
131
+ self._trailing_cr = False
132
+
133
+ @property
134
+ def pending_size(self) -> int:
135
+ return self._pending_size
136
+
137
+ def decode(self, text: str) -> list[str]:
138
+ if self._trailing_cr:
139
+ text = "\r" + text
140
+ self._trailing_cr = False
141
+ if text.endswith("\r"):
142
+ self._trailing_cr = True
143
+ text = text[:-1]
144
+
145
+ text = text.replace("\r\n", "\n").replace("\r", "\n")
146
+ if "\n" not in text:
147
+ self._append(text)
148
+ return []
149
+
150
+ lines = text.split("\n")
151
+ self._append(lines[0])
152
+ lines[0] = self._consume_pending()
153
+ self._append(lines.pop())
154
+ return lines
155
+
156
+ def flush(self) -> list[str]:
157
+ if self._trailing_cr:
158
+ self._append("\n")
159
+ self._trailing_cr = False
160
+ buffer = self._consume_pending()
161
+ if not buffer:
162
+ return []
163
+ return buffer.split("\n")
164
+
165
+ def _append(self, text: str) -> None:
166
+ if text:
167
+ self._parts.append(text)
168
+ self._pending_size += len(text.encode("utf-8"))
169
+
170
+ def _consume_pending(self) -> str:
171
+ pending = "".join(self._parts)
172
+ self._parts = []
173
+ self._pending_size = 0
174
+ return pending
175
+
176
+
177
+ class _SSEParser:
178
+ def __init__(self, max_event_size: int | None = None) -> None:
179
+ self._event_decoder = _SSEEventDecoder(max_event_size)
180
+ self._line_decoder = _SSELineDecoder()
181
+
182
+ def decode(self, text: str) -> Iterator[ServerSentEvent]:
183
+ yield from self._decode_lines(self._line_decoder.decode(text))
184
+ self._event_decoder.check_pending(self._line_decoder.pending_size)
185
+
186
+ def flush(self) -> Iterator[ServerSentEvent]:
187
+ yield from self._decode_lines(self._line_decoder.flush())
188
+
189
+ def _decode_lines(self, lines: list[str]) -> Iterator[ServerSentEvent]:
190
+ for line in lines:
191
+ sse = self._event_decoder.decode(line)
192
+ if sse is not None:
193
+ yield sse
194
+
195
+
196
+ class EventSource:
197
+ def __init__(self, response: Response, max_event_size: int | None = DEFAULT_MAX_EVENT_SIZE_BYTES) -> None:
198
+ self._response = response
199
+ self._max_event_size = max_event_size
200
+
201
+ @property
202
+ def response(self) -> Response:
203
+ return self._response
204
+
205
+ def _check_content_type(self) -> None:
206
+ content_type, _, _ = self._response.headers.get("content-type", "").partition(";")
207
+ if content_type.strip().lower() != "text/event-stream":
208
+ raise SSEError(f"Expected response with content type 'text/event-stream', got {content_type.strip()!r}.")
209
+
210
+ def __iter__(self) -> Iterator[ServerSentEvent]:
211
+ with request_context(request=self._response.request):
212
+ self._check_content_type()
213
+ parser = _SSEParser(self._max_event_size)
214
+ for chunk in self._response.iter_text():
215
+ yield from parser.decode(chunk)
216
+ yield from parser.flush()
217
+
218
+ async def __aiter__(self) -> AsyncIterator[ServerSentEvent]:
219
+ with request_context(request=self._response.request):
220
+ self._check_content_type()
221
+ parser = _SSEParser(self._max_event_size)
222
+ async for chunk in self._response.aiter_text():
223
+ for sse in parser.decode(chunk):
224
+ yield sse
225
+ for sse in parser.flush():
226
+ yield sse
@@ -1,21 +1,42 @@
1
1
  from __future__ import annotations
2
2
 
3
- from enum import IntEnum
3
+ import warnings
4
+ from enum import EnumMeta, IntEnum
4
5
 
5
6
  __all__ = ["codes"]
6
7
 
7
-
8
- class codes(IntEnum):
8
+ # Constant names that were renamed by RFC 9110, kept as deprecated aliases
9
+ # mapping each old name to its canonical replacement.
10
+ _DEPRECATED_CODES = {
11
+ "REQUEST_ENTITY_TOO_LARGE": "CONTENT_TOO_LARGE",
12
+ "REQUEST_URI_TOO_LONG": "URI_TOO_LONG",
13
+ "REQUESTED_RANGE_NOT_SATISFIABLE": "RANGE_NOT_SATISFIABLE",
14
+ "UNPROCESSABLE_ENTITY": "UNPROCESSABLE_CONTENT",
15
+ }
16
+
17
+
18
+ class _CodesMeta(EnumMeta):
19
+ def __getattribute__(cls, name: str) -> object:
20
+ if name in _DEPRECATED_CODES:
21
+ new_name = _DEPRECATED_CODES[name]
22
+ warnings.warn(
23
+ f"'{name}' is deprecated. Use '{new_name}' instead.",
24
+ category=DeprecationWarning,
25
+ stacklevel=2,
26
+ )
27
+ return super().__getattribute__(name)
28
+
29
+
30
+ class codes(IntEnum, metaclass=_CodesMeta):
9
31
  """HTTP status codes and reason phrases
10
32
 
11
33
  Status codes from the following RFCs are all observed:
12
34
 
13
- * RFC 7231: Hypertext Transfer Protocol (HTTP/1.1), obsoletes 2616
35
+ * RFC 9110: HTTP Semantics, obsoletes 7231 & 7238
14
36
  * RFC 6585: Additional HTTP Status Codes
15
37
  * RFC 3229: Delta encoding in HTTP
16
38
  * RFC 4918: HTTP Extensions for WebDAV, obsoletes 2518
17
39
  * RFC 5842: Binding Extensions to WebDAV
18
- * RFC 7238: Permanent Redirect
19
40
  * RFC 2295: Transparent Content Negotiation in HTTP
20
41
  * RFC 2774: An HTTP Extension Framework
21
42
  * RFC 7540: Hypertext Transfer Protocol Version 2 (HTTP/2)
@@ -126,14 +147,14 @@ class codes(IntEnum):
126
147
  GONE = 410, "Gone"
127
148
  LENGTH_REQUIRED = 411, "Length Required"
128
149
  PRECONDITION_FAILED = 412, "Precondition Failed"
129
- REQUEST_ENTITY_TOO_LARGE = 413, "Request Entity Too Large"
130
- REQUEST_URI_TOO_LONG = 414, "Request-URI Too Long"
150
+ CONTENT_TOO_LARGE = 413, "Content Too Large"
151
+ URI_TOO_LONG = 414, "URI Too Long"
131
152
  UNSUPPORTED_MEDIA_TYPE = 415, "Unsupported Media Type"
132
- REQUESTED_RANGE_NOT_SATISFIABLE = 416, "Requested Range Not Satisfiable"
153
+ RANGE_NOT_SATISFIABLE = 416, "Range Not Satisfiable"
133
154
  EXPECTATION_FAILED = 417, "Expectation Failed"
134
155
  IM_A_TEAPOT = 418, "I'm a teapot"
135
156
  MISDIRECTED_REQUEST = 421, "Misdirected Request"
136
- UNPROCESSABLE_ENTITY = 422, "Unprocessable Entity"
157
+ UNPROCESSABLE_CONTENT = 422, "Unprocessable Content"
137
158
  LOCKED = 423, "Locked"
138
159
  FAILED_DEPENDENCY = 424, "Failed Dependency"
139
160
  TOO_EARLY = 425, "Too Early"
@@ -156,7 +177,13 @@ class codes(IntEnum):
156
177
  NOT_EXTENDED = 510, "Not Extended"
157
178
  NETWORK_AUTHENTICATION_REQUIRED = 511, "Network Authentication Required"
158
179
 
180
+ # Deprecated aliases for names replaced by RFC 9110.
181
+ REQUEST_ENTITY_TOO_LARGE = CONTENT_TOO_LARGE
182
+ REQUEST_URI_TOO_LONG = URI_TOO_LONG
183
+ REQUESTED_RANGE_NOT_SATISFIABLE = RANGE_NOT_SATISFIABLE
184
+ UNPROCESSABLE_ENTITY = UNPROCESSABLE_CONTENT
185
+
159
186
 
160
187
  # Include lower-case styles for `requests` compatibility.
161
- for code in codes:
162
- setattr(codes, code._name_.lower(), int(code))
188
+ for name, code in codes.__members__.items():
189
+ setattr(codes, name.lower(), int(code))